Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Test4 #57

Merged
merged 112 commits into from
Nov 9, 2023
Merged
Changes from 1 commit
Commits
Show all changes
112 commits
Select commit Hold shift + click to select a range
fad0d50
Compiled main.go and pushed changes
Hoshinonyaruko Oct 23, 2023
fda2572
test
Hoshinonyaruko Oct 23, 2023
34cfac1
适配了频道私聊,用bolt数据库取代ini
Hoshinonyaruko Oct 23, 2023
7fc1f10
适配了nonebot2
Hoshinonyaruko Oct 24, 2023
28f9a73
Merge branch 'main' of https://github.com/Hoshinonyaruko/Gensokyo
Hoshinonyaruko Oct 24, 2023
9fadda4
适配私域
Hoshinonyaruko Oct 24, 2023
1336c6a
add license
Hoshinonyaruko Oct 24, 2023
b094949
add a lot
Hoshinonyaruko Oct 25, 2023
f4787f5
Resolved merge conflicts
Hoshinonyaruko Oct 25, 2023
86698c6
trss support
Hoshinonyaruko Oct 26, 2023
045f3e9
fix
Hoshinonyaruko Oct 26, 2023
618561c
add action
Hoshinonyaruko Oct 26, 2023
7e803aa
add action
Hoshinonyaruko Oct 26, 2023
ece4cef
add action
Hoshinonyaruko Oct 26, 2023
f864a50
fixbug
Hoshinonyaruko Oct 26, 2023
4564731
add wss
Hoshinonyaruko Oct 26, 2023
070e4df
merge
Hoshinonyaruko Oct 26, 2023
84e8fe9
bugfix
Hoshinonyaruko Oct 26, 2023
0e4fd50
fix action
Hoshinonyaruko Oct 26, 2023
fe2234a
fix action again
Hoshinonyaruko Oct 26, 2023
cf67a11
fix action againnn
Hoshinonyaruko Oct 26, 2023
0875837
fa
Hoshinonyaruko Oct 26, 2023
3a3c33f
fix
Hoshinonyaruko Oct 26, 2023
8789fa8
add a lot
Hoshinonyaruko Oct 27, 2023
7943466
add ws server token
Hoshinonyaruko Oct 28, 2023
4660983
merge
Hoshinonyaruko Oct 28, 2023
2a1026a
bugifx
Hoshinonyaruko Oct 28, 2023
4186970
fix
Hoshinonyaruko Oct 28, 2023
2f26828
fixat
Hoshinonyaruko Oct 28, 2023
007e1af
bugfix
Hoshinonyaruko Oct 28, 2023
c41fd77
bugfix
Hoshinonyaruko Oct 28, 2023
d8354b7
test
Hoshinonyaruko Oct 28, 2023
6e3c63c
test
Hoshinonyaruko Oct 28, 2023
f08d9d7
test2
Hoshinonyaruko Oct 28, 2023
4dd6e15
add url service
Hoshinonyaruko Oct 31, 2023
1f8c174
add url service
Hoshinonyaruko Oct 31, 2023
240f569
add url service
Hoshinonyaruko Oct 31, 2023
b191cb7
bugfix
Hoshinonyaruko Oct 31, 2023
42daab3
merge
Hoshinonyaruko Oct 31, 2023
8fec03f
fix
Hoshinonyaruko Oct 31, 2023
cca528b
fix
Hoshinonyaruko Oct 31, 2023
463a182
fix
Hoshinonyaruko Oct 31, 2023
e9187a1
bug fix
Hoshinonyaruko Nov 1, 2023
5ba2815
fix
Hoshinonyaruko Nov 1, 2023
c16e1af
fix
Hoshinonyaruko Nov 1, 2023
ec7863d
test
Hoshinonyaruko Nov 2, 2023
e8a7e73
ok
Hoshinonyaruko Nov 2, 2023
122d17d
add webui
Hoshinonyaruko Nov 2, 2023
4e9c209
merge
Hoshinonyaruko Nov 2, 2023
b502d61
add image_compress
Hoshinonyaruko Nov 3, 2023
3519e3e
merge
Hoshinonyaruko Nov 3, 2023
530ff96
bug fix
Hoshinonyaruko Nov 3, 2023
155a701
fix cq code
Hoshinonyaruko Nov 3, 2023
2f5ee4a
fixbug
Hoshinonyaruko Nov 3, 2023
afa03e3
bugfix
Hoshinonyaruko Nov 3, 2023
fdd1a73
merge
Hoshinonyaruko Nov 3, 2023
fe39cd2
bugfix
Hoshinonyaruko Nov 3, 2023
be08cbe
bugfix
Hoshinonyaruko Nov 3, 2023
931dfef
merge
Hoshinonyaruko Nov 3, 2023
73819c8
bugfix
Hoshinonyaruko Nov 3, 2023
b27f062
bugfix
Hoshinonyaruko Nov 3, 2023
1a94197
bugfix
Hoshinonyaruko Nov 3, 2023
745b28e
bugfix
Hoshinonyaruko Nov 3, 2023
1212c9a
bugfix
Hoshinonyaruko Nov 4, 2023
44d8669
bugfix
Hoshinonyaruko Nov 4, 2023
564aba5
add new feature
Hoshinonyaruko Nov 5, 2023
d7345c1
bugfix
Hoshinonyaruko Nov 5, 2023
472a224
bugfix
Hoshinonyaruko Nov 5, 2023
e22b58b
bugfix
Hoshinonyaruko Nov 5, 2023
22cb473
bugfix
Hoshinonyaruko Nov 5, 2023
e563929
bugfix
Hoshinonyaruko Nov 5, 2023
829b5d7
merge
Hoshinonyaruko Nov 5, 2023
b496ac1
bugfix
Hoshinonyaruko Nov 5, 2023
13e7700
bugfix
Hoshinonyaruko Nov 5, 2023
eb7e630
bugfix
Hoshinonyaruko Nov 5, 2023
32d490f
test
Hoshinonyaruko Nov 5, 2023
9815e3a
test
Hoshinonyaruko Nov 5, 2023
7747de6
test
Hoshinonyaruko Nov 5, 2023
fe2e4be
test
Hoshinonyaruko Nov 5, 2023
ec9e797
test
Hoshinonyaruko Nov 5, 2023
3548108
test
Hoshinonyaruko Nov 5, 2023
1e50a7c
test
Hoshinonyaruko Nov 5, 2023
812e6ea
test
Hoshinonyaruko Nov 5, 2023
76363a6
test
Hoshinonyaruko Nov 5, 2023
d8b05cd
test
Hoshinonyaruko Nov 5, 2023
c2e2b20
test
Hoshinonyaruko Nov 5, 2023
cefac16
test
Hoshinonyaruko Nov 5, 2023
273db15
test
Hoshinonyaruko Nov 5, 2023
5379f7d
test
Hoshinonyaruko Nov 5, 2023
56e2429
test
Hoshinonyaruko Nov 5, 2023
4466f30
test
Hoshinonyaruko Nov 6, 2023
a32a124
test
Hoshinonyaruko Nov 6, 2023
246d9c4
test
Hoshinonyaruko Nov 6, 2023
c91d9e2
test
Hoshinonyaruko Nov 6, 2023
6007979
bugfix
Hoshinonyaruko Nov 6, 2023
af64c33
bugfix
Hoshinonyaruko Nov 6, 2023
f5cfda3
Remove dist directory from tracking
Hoshinonyaruko Nov 6, 2023
53b6e5d
test
Hoshinonyaruko Nov 6, 2023
3991193
test
Hoshinonyaruko Nov 7, 2023
7af6759
bugfix2
Hoshinonyaruko Nov 7, 2023
fdec4ca
bugfix3
Hoshinonyaruko Nov 7, 2023
849c638
bugfix4
Hoshinonyaruko Nov 7, 2023
f268f3d
bugfix5
Hoshinonyaruko Nov 7, 2023
7ada595
bugfix5
Hoshinonyaruko Nov 8, 2023
76376a0
bugfix6
Hoshinonyaruko Nov 8, 2023
8332932
bugfix7
Hoshinonyaruko Nov 8, 2023
ac05d43
bugfix8
Hoshinonyaruko Nov 8, 2023
47b672c
bugfix9
Hoshinonyaruko Nov 8, 2023
9146fd8
bugfix10
Hoshinonyaruko Nov 8, 2023
8b399fb
bugfix11
Hoshinonyaruko Nov 9, 2023
c768a76
bugfix11
Hoshinonyaruko Nov 9, 2023
b07e71a
bugfix12
Hoshinonyaruko Nov 9, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
bugifx
Hoshinonyaruko committed Oct 28, 2023

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
commit 2a1026a83bb38c7e3aca7b5b6a49b8e81bbf42e3
77 changes: 44 additions & 33 deletions callapi/callapi.go
Original file line number Diff line number Diff line change
@@ -4,55 +4,66 @@ import (
"encoding/json"
"fmt"
"log"
"strconv"

"github.com/tencent-connect/botgo/openapi"
)

type EchoData struct {
Seq int `json:"seq"`
// onebot发来的action调用信息
type ActionMessage struct {
Action string `json:"action"`
Params ParamsContent `json:"params"`
Echo interface{} `json:"echo,omitempty"`
}

type EchoContent string
func (a *ActionMessage) UnmarshalJSON(data []byte) error {
type Alias ActionMessage

func (e *EchoContent) UnmarshalJSON(data []byte) error {
// 尝试解析为字符串
var strVal string
if err := json.Unmarshal(data, &strVal); err == nil {
*e = EchoContent(strVal)
return nil
var rawEcho json.RawMessage
temp := &struct {
*Alias
Echo *json.RawMessage `json:"echo,omitempty"`
}{
Alias: (*Alias)(a),
Echo: &rawEcho,
}

// 尝试解析为整数
var intVal int
if err := json.Unmarshal(data, &intVal); err == nil {
*e = EchoContent(strconv.Itoa(intVal))
return nil
if err := json.Unmarshal(data, &temp); err != nil {
return err
}

// 尝试解析为EchoData结构体
var echoData EchoData
if err := json.Unmarshal(data, &echoData); err == nil {
*e = EchoContent(strconv.Itoa(echoData.Seq))
return nil
if rawEcho != nil {
var lastErr error

var intValue int
if lastErr = json.Unmarshal(rawEcho, &intValue); lastErr == nil {
a.Echo = intValue
return nil
}

var strValue string
if lastErr = json.Unmarshal(rawEcho, &strValue); lastErr == nil {
a.Echo = strValue
return nil
}

var arrValue []interface{}
if lastErr = json.Unmarshal(rawEcho, &arrValue); lastErr == nil {
a.Echo = arrValue
return nil
}

var objValue map[string]interface{}
if lastErr = json.Unmarshal(rawEcho, &objValue); lastErr == nil {
a.Echo = objValue
return nil
}

return fmt.Errorf("unable to unmarshal echo: %v", lastErr)
}

// 如果都不符合预期,设置为空字符串
*e = ""
return nil
}

// func (e EchoContent) String() string {
// return string(e)
// }

// onebot发来的action调用信息
type ActionMessage struct {
Action string `json:"action"`
Params ParamsContent `json:"params"`
Echo EchoContent `json:"echo,omitempty"`
}

// params类型
type ParamsContent struct {
BotQQ string `json:"botqq"`
9 changes: 6 additions & 3 deletions handlers/get_group_member_list.go
Original file line number Diff line number Diff line change
@@ -146,9 +146,12 @@ func buildResponse(members []MemberList, echoValue interface{}) map[string]inter
case string:
log.Printf("Setting echo as string: %s", v)
response["echo"] = v
case callapi.EchoContent:
log.Printf("Setting echo from EchoContent: %s", string(v))
response["echo"] = string(v)
case []interface{}:
log.Printf("Setting echo as array: %v", v)
response["echo"] = v
case map[string]interface{}:
log.Printf("Setting echo as object: %v", v)
response["echo"] = v
default:
log.Printf("Unknown type for echo: %T", v)
}
2 changes: 1 addition & 1 deletion handlers/get_guild_list.go
Original file line number Diff line number Diff line change
@@ -44,7 +44,7 @@ func getGuildList(client callapi.Client, api openapi.OpenAPI, apiv2 openapi.Open
response.Message = ""
response.RetCode = 0
response.Status = "ok"
response.Echo = string(message.Echo) // Directly assign the string value
response.Echo = message.Echo

// Convert the members slice to a map
outputMap := structToMap(response)
2 changes: 1 addition & 1 deletion handlers/get_guild_service_profile.go
Original file line number Diff line number Diff line change
@@ -35,7 +35,7 @@ func getGuildServiceProfile(client callapi.Client, api openapi.OpenAPI, apiv2 op
response.Message = ""
response.RetCode = 0
response.Status = "ok"
response.Echo = string(message.Echo) // Directly assign the string value
response.Echo = message.Echo

// Convert the members slice to a map
outputMap := structToMap(response)
2 changes: 1 addition & 1 deletion handlers/get_login_info.go
Original file line number Diff line number Diff line change
@@ -41,7 +41,7 @@ func getLoginInfo(client callapi.Client, api openapi.OpenAPI, apiv2 openapi.Open
response.Message = ""
response.RetCode = 0
response.Status = "ok"
response.Echo = string(message.Echo)
response.Echo = message.Echo

// Convert the members slice to a map
outputMap := structToMap(response)
2 changes: 1 addition & 1 deletion handlers/get_online_clients.go
Original file line number Diff line number Diff line change
@@ -35,7 +35,7 @@ func getOnlineClients(client callapi.Client, api openapi.OpenAPI, apiv2 openapi.
response.Message = ""
response.RetCode = 0
response.Status = "ok"
response.Echo = string(message.Echo)
response.Echo = message.Echo

// Convert the members slice to a map
outputMap := structToMap(response)
2 changes: 1 addition & 1 deletion handlers/get_status.go
Original file line number Diff line number Diff line change
@@ -65,7 +65,7 @@ func getStatus(client callapi.Client, api openapi.OpenAPI, apiv2 openapi.OpenAPI
response.Message = ""
response.RetCode = 0
response.Status = "ok"
response.Echo = string(message.Echo) // Directly assign the string value
response.Echo = message.Echo

outputMap := structToMap(response)

2 changes: 1 addition & 1 deletion handlers/get_version_info.go
Original file line number Diff line number Diff line change
@@ -59,7 +59,7 @@ func getVersionInfo(client callapi.Client, api openapi.OpenAPI, apiv2 openapi.Op
response.Message = ""
response.RetCode = 0
response.Status = "ok"
response.Echo = string(message.Echo) // Directly assign the string value
response.Echo = message.Echo

// Convert the members slice to a map
outputMap := structToMap(response)
10 changes: 5 additions & 5 deletions handlers/message_parser.go
Original file line number Diff line number Diff line change
@@ -19,18 +19,18 @@ type ServerResponse struct {
Data struct {
MessageID int `json:"message_id"`
} `json:"data"`
Message string `json:"message"`
RetCode int `json:"retcode"`
Status string `json:"status"`
Echo string `json:"echo"`
Message string `json:"message"`
RetCode int `json:"retcode"`
Status string `json:"status"`
Echo interface{} `json:"echo"`
}

// 发送成功回执 todo 返回可互转的messageid
func SendResponse(client callapi.Client, err error, message *callapi.ActionMessage) error {
// 设置响应值
response := ServerResponse{}
response.Data.MessageID = 0 // todo 实现messageid转换
response.Echo = string(message.Echo)
response.Echo = message.Echo
if err != nil {
response.Message = err.Error() // 可选:在响应中添加错误消息
//response.RetCode = -1 // 可以是任何非零值,表示出错
16 changes: 10 additions & 6 deletions handlers/send_group_msg.go
Original file line number Diff line number Diff line change
@@ -24,7 +24,11 @@ func init() {

func handleSendGroupMsg(client callapi.Client, api openapi.OpenAPI, apiv2 openapi.OpenAPI, message callapi.ActionMessage) {
// 使用 message.Echo 作为key来获取消息类型
msgType := echo.GetMsgTypeByKey(string(message.Echo))
var msgType string
if echoStr, ok := message.Echo.(string); ok {
// 当 message.Echo 是字符串类型时执行此块
msgType = echo.GetMsgTypeByKey(echoStr)
}

//如果获取不到 就用user_id获取信息类型
if msgType == "" {
@@ -41,12 +45,12 @@ func handleSendGroupMsg(client callapi.Client, api openapi.OpenAPI, apiv2 openap
// 解析消息内容
messageText, foundItems := parseMessageContent(message.Params)

// 获取 echo 的值
echostr := string(message.Echo)

// 使用 echo 获取消息ID
messageID := echo.GetMsgIDByKey(echostr)
log.Println("群组发信息对应的message_id:", messageID)
var messageID string
if echoStr, ok := message.Echo.(string); ok {
messageID = echo.GetMsgIDByKey(echoStr)
log.Println("echo取群组发信息对应的message_id:", messageID)
}
log.Println("群组发信息messageText:", messageText)
log.Println("foundItems:", foundItems)
// 如果messageID为空,通过函数获取
18 changes: 11 additions & 7 deletions handlers/send_guild_channel_msg.go
Original file line number Diff line number Diff line change
@@ -22,7 +22,11 @@ func init() {

func handleSendGuildChannelMsg(client callapi.Client, api openapi.OpenAPI, apiv2 openapi.OpenAPI, message callapi.ActionMessage) {
// 使用 message.Echo 作为key来获取消息类型
msgType := echo.GetMsgTypeByKey(string(message.Echo))
var msgType string
if echoStr, ok := message.Echo.(string); ok {
// 当 message.Echo 是字符串类型时执行此块
msgType = echo.GetMsgTypeByKey(echoStr)
}

//如果获取不到 就用user_id获取信息类型
if msgType == "" {
@@ -46,12 +50,12 @@ func handleSendGuildChannelMsg(client callapi.Client, api openapi.OpenAPI, apiv2
messageText, foundItems := parseMessageContent(params)

channelID := params.ChannelID
// 获取 echo 的值
echostr := string(message.Echo)

//messageType := echo.GetMsgTypeByKey(echostr)
messageID := echo.GetMsgIDByKey(echostr)
log.Println("频道发信息对应的message_id:", messageID)
// 使用 echo 获取消息ID
var messageID string
if echoStr, ok := message.Echo.(string); ok {
messageID = echo.GetMsgIDByKey(echoStr)
log.Println("echo取频道发信息对应的message_id:", messageID)
}
log.Println("频道发信息messageText:", messageText)
log.Println("foundItems:", foundItems)
var err error
26 changes: 15 additions & 11 deletions handlers/send_msg.go
Original file line number Diff line number Diff line change
@@ -24,7 +24,11 @@ func init() {

func handleSendMsg(client callapi.Client, api openapi.OpenAPI, apiv2 openapi.OpenAPI, message callapi.ActionMessage) {
// 使用 message.Echo 作为key来获取消息类型
msgType := echo.GetMsgTypeByKey(string(message.Echo))
var msgType string
if echoStr, ok := message.Echo.(string); ok {
// 当 message.Echo 是字符串类型时执行此块
msgType = echo.GetMsgTypeByKey(echoStr)
}

//如果获取不到 就用group_id获取信息类型
if msgType == "" {
@@ -46,12 +50,12 @@ func handleSendMsg(client callapi.Client, api openapi.OpenAPI, apiv2 openapi.Ope
// 解析消息内容
messageText, foundItems := parseMessageContent(message.Params)

// 获取 echo 的值
echostr := string(message.Echo)

// 使用 echo 获取消息ID
messageID := echo.GetMsgIDByKey(echostr)
log.Println("群组发信息对应的message_id:", messageID)
var messageID string
if echoStr, ok := message.Echo.(string); ok {
messageID = echo.GetMsgIDByKey(echoStr)
log.Println("echo取群组发信息对应的message_id:", messageID)
}
log.Println("群组发信息messageText:", messageText)
log.Println("foundItems:", foundItems)
// 如果messageID为空,通过函数获取
@@ -159,12 +163,12 @@ func handleSendMsg(client callapi.Client, api openapi.OpenAPI, apiv2 openapi.Ope
// 解析消息内容
messageText, foundItems := parseMessageContent(message.Params)

// 获取 echo 的值
echostr := string(message.Echo)

// 使用 echo 获取消息ID
messageID := echo.GetMsgIDByKey(echostr)
log.Println("私聊发信息对应的message_id:", messageID)
var messageID string
if echoStr, ok := message.Echo.(string); ok {
messageID = echo.GetMsgIDByKey(echoStr)
log.Println("echo取私聊发信息对应的message_id:", messageID)
}
log.Println("私聊发信息messageText:", messageText)
log.Println("foundItems:", foundItems)

26 changes: 16 additions & 10 deletions handlers/send_private_msg.go
Original file line number Diff line number Diff line change
@@ -22,7 +22,11 @@ func init() {

func handleSendPrivateMsg(client callapi.Client, api openapi.OpenAPI, apiv2 openapi.OpenAPI, message callapi.ActionMessage) {
// 使用 message.Echo 作为key来获取消息类型
msgType := echo.GetMsgTypeByKey(string(message.Echo))
var msgType string
if echoStr, ok := message.Echo.(string); ok {
// 当 message.Echo 是字符串类型时执行此块
msgType = echo.GetMsgTypeByKey(echoStr)
}

switch msgType {
case "group_private":
@@ -37,12 +41,12 @@ func handleSendPrivateMsg(client callapi.Client, api openapi.OpenAPI, apiv2 open
// 解析消息内容
messageText, foundItems := parseMessageContent(message.Params)

// 获取 echo 的值
echostr := string(message.Echo)

// 使用 echo 获取消息ID
messageID := echo.GetMsgIDByKey(echostr)
log.Println("私聊发信息对应的message_id:", messageID)
var messageID string
if echoStr, ok := message.Echo.(string); ok {
messageID = echo.GetMsgIDByKey(echoStr)
log.Println("echo取私聊发信息对应的message_id:", messageID)
}
log.Println("私聊发信息messageText:", messageText)
log.Println("foundItems:", foundItems)

@@ -142,10 +146,12 @@ func handleSendGuildChannelPrivateMsg(client callapi.Client, api openapi.OpenAPI
}
}

// 获取 echo 的值
echostr := string(message.Echo)
messageID := echo.GetMsgIDByKey(echostr)
log.Println("私聊信息对应的message_id:", messageID)
// 使用 echo 获取消息ID
var messageID string
if echoStr, ok := message.Echo.(string); ok {
messageID = echo.GetMsgIDByKey(echoStr)
log.Println("echo取私聊发信息对应的message_id:", messageID)
}
log.Println("私聊信息messageText:", messageText)
log.Println("foundItems:", foundItems)
// 如果messageID为空,通过函数获取
2 changes: 1 addition & 1 deletion main.go
Original file line number Diff line number Diff line change
@@ -141,7 +141,7 @@ func main() {
}(wsAddr)
}

// Collect results
// 获取连接成功后的wsClient
for i := 0; i < len(conf.Settings.WsAddress); i++ {
select {
case wsClient := <-wsClientChan:
43 changes: 36 additions & 7 deletions server/wsserver.go
Original file line number Diff line number Diff line change
@@ -6,6 +6,7 @@ import (
"log"
"net/http"
"strings"
"time"

"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
@@ -38,17 +39,29 @@ func WsHandlerWithDependencies(api openapi.OpenAPI, apiV2 openapi.OpenAPI, p *Pr
}
}

// 处理正向ws客户端的连接
func wsHandler(api openapi.OpenAPI, apiV2 openapi.OpenAPI, p *Processor.Processors, c *gin.Context) {
// 先获取请求头中的token
// 先从请求头中尝试获取token
tokenFromHeader := c.Request.Header.Get("Authorization")
if tokenFromHeader == "" || !strings.HasPrefix(tokenFromHeader, "Token ") {
log.Printf("Connection failed due to missing or invalid token. Headers: %v, Provided token: %s", c.Request.Header, tokenFromHeader)
c.JSON(http.StatusUnauthorized, gin.H{"error": "Missing or invalid token"})
return
token := ""
if tokenFromHeader != "" {
if strings.HasPrefix(tokenFromHeader, "Token ") {
// 从 "Token " 后面提取真正的token值
token = strings.TrimPrefix(tokenFromHeader, "Token ")
} else if strings.HasPrefix(tokenFromHeader, "Bearer ") {
// 从 "Bearer " 后面提取真正的token值
token = strings.TrimPrefix(tokenFromHeader, "Bearer ")
}
} else {
// 如果请求头中没有token,则从URL参数中获取
token = c.Query("access_token")
}

// 从 "Token " 后面提取真正的token值
token := strings.TrimPrefix(tokenFromHeader, "Token ")
if token == "" {
log.Printf("Connection failed due to missing token. Headers: %v", c.Request.Header)
c.JSON(http.StatusUnauthorized, gin.H{"error": "Missing token"})
return
}

// 使用GetWsServerToken()来获取有效的token
validToken := config.GetWsServerToken()
@@ -76,6 +89,22 @@ func wsHandler(api openapi.OpenAPI, apiV2 openapi.OpenAPI, p *Processor.Processo
// 将此客户端添加到Processor的WsServerClients列表中
p.WsServerClients = append(p.WsServerClients, client)

// 获取botID
botID := config.GetAppID()

// 发送连接成功的消息
message := map[string]interface{}{
"meta_event_type": "lifecycle",
"post_type": "meta_event",
"self_id": botID,
"sub_type": "connect",
"time": int(time.Now().Unix()),
}
err = client.SendMessage(message)
if err != nil {
log.Printf("Error sending connection success message: %v\n", err)
}

defer conn.Close()

for {
75 changes: 65 additions & 10 deletions wsclient/ws.go
Original file line number Diff line number Diff line change
@@ -7,6 +7,7 @@ import (
"log"
"net/http"
"net/url"
"sync"
"time"

"github.com/gorilla/websocket"
@@ -16,9 +17,14 @@ import (
)

type WebSocketClient struct {
conn *websocket.Conn
api openapi.OpenAPI
apiv2 openapi.OpenAPI
conn *websocket.Conn
api openapi.OpenAPI
apiv2 openapi.OpenAPI
botID uint64
urlStr string
cancel context.CancelFunc // Add this
mutex sync.Mutex // Mutex for reconnecting
isReconnecting bool
}

// 发送json信息给onebot应用端
@@ -33,7 +39,6 @@ func (c *WebSocketClient) SendMessage(message map[string]interface{}) error {
log.Println("Error sending message:", err)
return err
}

return nil
}

@@ -44,13 +49,48 @@ func (c *WebSocketClient) handleIncomingMessages(ctx context.Context, cancel con
if err != nil {
log.Println("WebSocket connection closed:", err)
cancel() // cancel heartbeat goroutine
break

if !c.isReconnecting {
go c.Reconnect()
}
return
}

go c.recvMessage(msg)
}
}

// 断线重连
func (client *WebSocketClient) Reconnect() {
client.mutex.Lock()
defer client.mutex.Unlock()

if client.cancel != nil {
client.cancel() // Stop current goroutines
}

client.isReconnecting = true
defer func() {
client.isReconnecting = false
}()

for {
time.Sleep(5 * time.Second)

newClient, err := NewWebSocketClient(client.urlStr, client.botID, client.api, client.apiv2)
if err == nil && newClient != nil {
client.conn = newClient.conn
client.api = newClient.api
client.apiv2 = newClient.apiv2
client.cancel = newClient.cancel // Update cancel function

log.Println("Successfully reconnected to WebSocket.")
return
}
log.Println("Failed to reconnect to WebSocket. Retrying in 5 seconds...")
}
}

// 处理信息,调用腾讯api
func (c *WebSocketClient) recvMessage(msg []byte) {
var message callapi.ActionMessage
@@ -100,6 +140,8 @@ func (c *WebSocketClient) sendHeartbeat(ctx context.Context, botID uint64) {
}
}

const maxRetryAttempts = 5

// NewWebSocketClient 创建 WebSocketClient 实例,接受 WebSocket URL、botID 和 openapi.OpenAPI 实例
func NewWebSocketClient(urlStr string, botID uint64, api openapi.OpenAPI, apiv2 openapi.OpenAPI) (*WebSocketClient, error) {
addresses := config.GetWsAddress()
@@ -137,20 +179,31 @@ func NewWebSocketClient(urlStr string, botID uint64, api openapi.OpenAPI, apiv2
var conn *websocket.Conn
var err error

// Retry mechanism
retryCount := 0
for {
fmt.Println("Dialing URL:", urlStr)
conn, _, err = dialer.Dial(urlStr, headers)
if err != nil {
retryCount++
if retryCount > maxRetryAttempts {
log.Printf("Exceeded maximum retry attempts for WebSocket[%v]: %v\n", urlStr, err)
return nil, err
}
fmt.Printf("Failed to connect to WebSocket[%v]: %v, retrying in 5 seconds...\n", urlStr, err)
time.Sleep(5 * time.Second) // sleep for 5 seconds before retrying
} else {
fmt.Printf("成功连接到 %s.\n", urlStr) // 输出连接成功提示
break // successfully connected, break the loop
fmt.Printf("Successfully connected to %s.\n", urlStr) // 输出连接成功提示
break // successfully connected, break the loop
}
}

client := &WebSocketClient{conn: conn, api: api, apiv2: apiv2}
client := &WebSocketClient{
conn: conn,
api: api,
apiv2: apiv2,
botID: botID,
urlStr: urlStr,
}

// Sending initial message similar to your setupB function
message := map[string]interface{}{
@@ -172,8 +225,10 @@ func NewWebSocketClient(urlStr string, botID uint64, api openapi.OpenAPI, apiv2
// Starting goroutine for heartbeats and another for listening to messages
ctx, cancel := context.WithCancel(context.Background())

client.cancel = cancel

go client.sendHeartbeat(ctx, botID)
go client.handleIncomingMessages(ctx, cancel) //包含收到信息,调用api部分的代码
go client.handleIncomingMessages(ctx, cancel)

return client, nil
}