Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: tencent-connect/botgo
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: v0.1.7
Choose a base ref
...
head repository: tencent-connect/botgo
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: master
Choose a head ref
  • 5 commits
  • 19 files changed
  • 3 contributors

Commits on Nov 4, 2024

  1. feat(botgo): 增加消息场景字段 (merge request !99)

    Squash merge branch '20241025_shannonchen_msg_scene_120237142' into 'master'
    feat(botgo): 增加消息场景字段
    shannonchen committed Nov 4, 2024
    Copy the full SHA
    9095581 View commit details

Commits on Nov 12, 2024

  1. feat(botgo): 增加markdown引导消息字段 (merge request !100)

    Squash merge branch 'feature_20241112_shannonchen_ai_search_120234551' into 'master'
    feat(botgo): 增加markdown引导消息字段
    shannonchen committed Nov 12, 2024
    Copy the full SHA
    660d5f6 View commit details

Commits on Nov 25, 2024

  1. 修复examples/receive-and-send配置加载逻辑 (merge request !101)

    Squash merge branch 'fix_20241122_demo_recevie_and_send' into 'master'
    修复examples/receive-and-send配置加载逻辑
    rianli committed Nov 25, 2024
    Copy the full SHA
    07ab80d View commit details

Commits on Dec 18, 2024

  1. 完善 access token 刷新逻辑 (merge request !102)

    Squash merge branch 'fix_20241218_nil_pointer_of_tk' into 'master'
    完善 access token 刷新逻辑
    rianli authored and walli committed Dec 18, 2024
    Copy the full SHA
    c23ec97 View commit details
  2. Merge pull request #55 from HiRyanLee/master

    完善 access token 刷新逻辑 (merge request !102)
    HiRyanLee authored Dec 18, 2024
    Copy the full SHA
    fe31c0d View commit details
8 changes: 8 additions & 0 deletions dto/message.go
Original file line number Diff line number Diff line change
@@ -43,6 +43,8 @@ type Message struct {
FileInfo []byte `json:"file_info,omitempty"`
// 上传富媒体文件后的有效期, 单位:秒, 在有效期内可以重复使用。
TTL uint `json:"ttl,omitempty"`
// 消息场景描述
MessageScene MessageScene `json:"message_scene,omitempty"`
}

// Embed 结构
@@ -81,3 +83,9 @@ type MessageReactionUsers struct {
Cookie string `json:"cookie,omitempty"`
IsEnd bool `json:"is_end,omitempty"`
}

// MessageScene 消息场景
type MessageScene struct {
Source string `json:"source,omitempty"` // 消息来源, realtime_voice: 实时通话场景, ai_search: AI搜索 其它默认为AIO消息
CallbackData string `json:"callback_data,omitempty"` // 回调数据
}
1 change: 1 addition & 0 deletions dto/message_create.go
Original file line number Diff line number Diff line change
@@ -130,6 +130,7 @@ type Markdown struct {
Params []*MarkdownParams `json:"params"` // 模版参数
Content string `json:"content"` // 原生 markdown
Style *MarkdownStyle `json:"style"` // markdown样式
ProcessMsg string `json:"process_msg"` // markdown引导消息
}

// MarkdownStyle markdown 样式
5 changes: 3 additions & 2 deletions dto/webhook.go
Original file line number Diff line number Diff line change
@@ -8,6 +8,7 @@ type WHValidationReq struct {

// WHValidationRsp 机器人回调验证响应结果
type WHValidationRsp struct {
PlainToken string `json:"plain_token"`
Signature string `json:"signature"`
PlainToken string `json:"plain_token"`
Signature string `json:"signature"`
DataVersion string `json:"data_version"` //数据格式版本号

Check failure on line 13 in dto/webhook.go

GitHub Actions / build

commentFormatting: put a space between `//` and comment text (gocritic)
}
2 changes: 1 addition & 1 deletion examples/apitest/main_test.go
Original file line number Diff line number Diff line change
@@ -7,7 +7,7 @@ import (
"testing"
"time"

"gopkg.in/yaml.v2"
"gopkg.in/yaml.v3"

"github.com/tencent-connect/botgo"
"github.com/tencent-connect/botgo/openapi"
File renamed without changes.
3 changes: 0 additions & 3 deletions examples/custom-filter/config.yaml.demo

This file was deleted.

3 changes: 2 additions & 1 deletion examples/custom-filter/main.go
Original file line number Diff line number Diff line change
@@ -29,7 +29,6 @@ const (
)

func main() {
ctx := context.Background()
openapi.RegisterReqFilter("set-trace", ReqFilter)
openapi.RegisterRespFilter("get-trace", RespFilter)
// 加载 appid 和 token
@@ -42,6 +41,8 @@ func main() {
log.Fatalln("parse config failed, err:", err)
}
tokenSource := token.NewQQBotTokenSource(credentials)
ctx, cancel := context.WithCancel(context.Background())
defer cancel() //释放刷新协程
if err = token.StartRefreshAccessToken(ctx, tokenSource); err != nil {
log.Fatalln(err)
}
3 changes: 0 additions & 3 deletions examples/custom-logger/config.yaml.demo

This file was deleted.

5 changes: 2 additions & 3 deletions examples/custom-logger/main.go
Original file line number Diff line number Diff line change
@@ -26,16 +26,13 @@ const (
)

func main() {
ctx := context.Background()

// 初始化新的文件 logger,并使用相对路径来作为日志存放位置,设置最小日志界别为 DebugLevel
logger, err := New("./", DebugLevel)
if err != nil {
log.Fatalln("error log new", err)
}
// 把新的 logger 设置到 sdk 上,替换掉老的控制台 logger
botgo.SetLogger(logger)

content, err := os.ReadFile("config.yaml")
if err != nil {
log.Fatalln("load config file failed, err:", err)
@@ -46,6 +43,8 @@ func main() {
}

tokenSource := token.NewQQBotTokenSource(credentials)
ctx, cancel := context.WithCancel(context.Background())
defer cancel() //释放刷新协程
if err = token.StartRefreshAccessToken(ctx, tokenSource); err != nil {
log.Fatalln(err)
}
5 changes: 1 addition & 4 deletions examples/go.mod
Original file line number Diff line number Diff line change
@@ -4,9 +4,8 @@ go 1.21

require (
github.com/google/uuid v1.3.0
github.com/tencent-connect/botgo v0.0.0-00010101000000-000000000000
github.com/tencent-connect/botgo v0.1.7
go.uber.org/zap v1.19.1
gopkg.in/yaml.v2 v2.4.0
gopkg.in/yaml.v3 v3.0.1
)

@@ -22,5 +21,3 @@ require (
golang.org/x/oauth2 v0.23.0 // indirect
golang.org/x/sync v0.1.0 // indirect
)

replace github.com/tencent-connect/botgo => ../
2 changes: 2 additions & 0 deletions examples/go.sum
Original file line number Diff line number Diff line change
@@ -69,6 +69,8 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/tencent-connect/botgo v0.1.7 h1:+RkHW9T4WOBRGQtOcFAO52VvZEKoTXFq162k2xo0Jac=
github.com/tencent-connect/botgo v0.1.7/go.mod h1:oO1sG9ybhXNickvt+CVym5khwQ+uKhTR+IhTqEfOVsI=
github.com/tidwall/gjson v1.9.3 h1:hqzS9wAHMO+KVBBkLxYdkEeeFHuqr95GfClRLKlgK0E=
github.com/tidwall/gjson v1.9.3/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
Binary file removed examples/img.png
Binary file not shown.
3 changes: 0 additions & 3 deletions examples/receive-and-send/config.yaml.demo

This file was deleted.

8 changes: 3 additions & 5 deletions examples/receive-and-send/main.go
Original file line number Diff line number Diff line change
@@ -28,7 +28,6 @@ const (
var processor Processor

func main() {
ctx := context.Background()
// 加载 appid 和 token
content, err := os.ReadFile("config.yaml")
if err != nil {
@@ -42,10 +41,9 @@ func main() {
log.Fatalln("parse config failed, err:", err)
}
log.Println("credentials:", credentials)
tokenSource := token.NewQQBotTokenSource(&token.QQBotCredentials{
AppID: "",
AppSecret: "",
})
tokenSource := token.NewQQBotTokenSource(credentials)
ctx, cancel := context.WithCancel(context.Background())
defer cancel() //释放刷新协程
if err = token.StartRefreshAccessToken(ctx, tokenSource); err != nil {
log.Fatalln(err)
}
3 changes: 0 additions & 3 deletions examples/simulate-callback-request/config.yaml.demo

This file was deleted.

4 changes: 2 additions & 2 deletions examples/simulate-callback-request/main.go
Original file line number Diff line number Diff line change
@@ -14,7 +14,7 @@ import (
"github.com/tencent-connect/botgo/dto"
"github.com/tencent-connect/botgo/interaction/signature"
"github.com/tencent-connect/botgo/token"
"gopkg.in/yaml.v2"
"gopkg.in/yaml.v3"
)

const host = "http://localhost"
@@ -29,7 +29,7 @@ func main() {
log.Fatalln("load config file failed, err:", err)
}
credentials := &token.QQBotCredentials{}
if err = yaml.Unmarshal(content, &credentials); err != nil {
if err = yaml.Unmarshal(content, credentials); err != nil {
log.Fatalln("parse config failed, err:", err)
}
log.Println("credentials:", credentials)
51 changes: 34 additions & 17 deletions interaction/signature/interaction_test.go
Original file line number Diff line number Diff line change
@@ -5,25 +5,42 @@ import (
"testing"
)

func TestSignature(t *testing.T) {
secret := "abcdefg"
header := http.Header{}
header.Set(HeaderTimestamp, "1234567890")
httpBody := "text body"
sig, err := Generate(secret, header, []byte(httpBody))
if err != nil {
t.Error(err)
func TestVerify(t *testing.T) {
type args struct {
secret string
header http.Header
httpBody []byte
}
t.Log(sig)
tests := []struct {
name string
args args
want bool
wantErr bool
}{
{
name: "test sig",
args: args{

header.Set(HeaderSig, sig)
flag, err := Verify(secret, header, []byte(httpBody))
if err != nil {
t.Error(err)
secret: "123456abcdef",
header: map[string][]string{
"X-Signature-Ed25519": {"e949b5b94ef4103df903fb031d1d16e358db3db83e79e117edd404c8508be3ce8a76d7bad1bed353194c126a1a5915b4ad8b5288c1191cc53a12acffccd82004"},
"X-Signature-Timestamp": {"1728981195"}},
httpBody: []byte(`{"id":"ROBOT1.0_veoihSEXDc8Q.g-6eLpNIa11bH8MisOjn-m-LKxCPntMk6exUXgcWCGpVO7L2QKTNZzjZzFFDSbiOFcqAPWyVA!!","content":"哦一下","timestamp":"2024-10-15T16:33:15+08:00","author":{"id":"675860273","user_openid":"675860273"}}`),
},
want: true,
wantErr: false,
},
}
if !flag {
t.Error("verify failed, but want ok")
} else {
t.Log("verify ok")
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := Verify(tt.args.secret, tt.args.header, tt.args.httpBody)
if (err != nil) != tt.wantErr {
t.Errorf("Verify() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("Verify() got = %v, want %v", got, tt.want)
}
})
}
}
2 changes: 1 addition & 1 deletion interaction/webhook/webhook.go
Original file line number Diff line number Diff line change
@@ -52,7 +52,7 @@ func HTTPHandler(w http.ResponseWriter, r *http.Request, credentials *token.QQBo
log.Errorf("read http callback body error: %s", err)
return
}
log.Debugf("http callback body: %v", string(body))
log.Debugf("http callback body: %s,len:%d", string(body), len(body))
log.Debugf("http callback header: %v", r.Header)
traceID := r.Header.Get(constant.HeaderTraceID)
// 签名验证
22 changes: 18 additions & 4 deletions token/token_source.go
Original file line number Diff line number Diff line change
@@ -179,28 +179,42 @@ func StartRefreshAccessToken(ctx context.Context, tokenSource oauth2.TokenSource
}
log.Debugf("token:%+v ", tk)
go func() {
var consecutiveFailures int
for {
refreshMilliSec := getRefreshMilliSec(tk.ExpiresIn)
var refreshMilliSec int64
//上一轮获取 tk 失败
if tk == nil {
if consecutiveFailures > 10 {
panic("get token failed continuously for more than ten times")
}
consecutiveFailures++
refreshMilliSec = 1000 // 1000ms后重试
} else {
consecutiveFailures = 0
refreshMilliSec = getRefreshMilliSec(tk.ExpiresIn)
}
log.Debugf("refresh after %d milli sec", refreshMilliSec)
ticker := time.NewTicker(time.Duration(refreshMilliSec) * time.Millisecond).C
timer := time.NewTimer(time.Duration(refreshMilliSec) * time.Millisecond)
select {
case <-ticker:
case <-timer.C:
{
log.Debugf("start to refresh access token %s", time.Now().Format(time.StampMilli))
tk, err = tokenSource.Token()
if err != nil {
log.Errorf("refresh access token failed:%s", err)
}
timer.Stop()
}
case <-ctx.Done():
{
log.Warnf("recv ctx:%v exit refresh token", ctx.Err())
timer.Stop()
return
}
}
}
}()
return err
return nil
}

var (