Skip to content

Commit

Permalink
Test3 (#5)
Browse files Browse the repository at this point in the history
* Compiled main.go and pushed changes

* test

* 适配了频道私聊,用bolt数据库取代ini
  • Loading branch information
Hoshinonyaruko authored Oct 23, 2023
1 parent feb03cf commit f8f7100
Show file tree
Hide file tree
Showing 12 changed files with 573 additions and 169 deletions.
292 changes: 246 additions & 46 deletions Processor/Processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
package Processor

import (
"context"
"encoding/json"
"fmt"
"log"
Expand All @@ -21,16 +20,8 @@ import (
"github.com/tencent-connect/botgo/websocket/client"
)

var compatibilityMapping *idmap.IniMapping
var err error

func init() {
compatibilityMapping, err = idmap.NewIniMapping()
if err != nil {
log.Fatalf("Failed to initialize IniMapping: %v", err)
}
}

// Processor 结构体用于处理消息
type Processor struct {
Api openapi.OpenAPI // API 类型
Expand All @@ -45,6 +36,7 @@ type Sender struct {
UserID int64 `json:"user_id"`
}

// 频道信息事件
type OnebotChannelMessage struct {
ChannelID string `json:"channel_id"`
GuildID string `json:"guild_id"`
Expand All @@ -63,7 +55,7 @@ type OnebotChannelMessage struct {
Echo string `json:"echo"`
}

// OnebotGroupMessage represents the message structure for group messages.
// 群信息事件
type OnebotGroupMessage struct {
RawMessage string `json:"raw_message"`
MessageID int `json:"message_id"`
Expand All @@ -82,6 +74,29 @@ type OnebotGroupMessage struct {
UserID int64 `json:"user_id"`
}

// 私聊信息事件
type OnebotPrivateMessage struct {
RawMessage string `json:"raw_message"`
MessageID int `json:"message_id"` // Can be either string or int depending on logic
MessageType string `json:"message_type"`
PostType string `json:"post_type"`
SelfID int64 `json:"self_id"` // Can be either string or int depending on logic
Sender PrivateSender `json:"sender"`
SubType string `json:"sub_type"`
Time int64 `json:"time"`
Avatar string `json:"avatar"`
Echo string `json:"echo"`
Message interface{} `json:"message"` // For array format
MessageSeq int `json:"message_seq,omitempty"` // Optional field
Font int `json:"font,omitempty"` // Optional field
UserID int64 `json:"user_id"` // Can be either string or int depending on logic
}

type PrivateSender struct {
Nickname string `json:"nickname"`
UserID int64 `json:"user_id"` // Can be either string or int depending on logic
}

func FoxTimestamp() int64 {
return time.Now().Unix()
}
Expand Down Expand Up @@ -157,9 +172,11 @@ func (p *Processor) ProcessGuildATMessage(data *dto.WSATMessageData) error {

} else {
// GlobalChannelToGroup为true时的处理逻辑
//将频道转化为一个群
//获取s
s := client.GetGlobalS()
compatibilityMapping.WriteConfig(data.ChannelID, "guild_id", data.GuildID)
//将channelid写入ini,可取出guild_id todo 比ini更好的储存方式
idmap.WriteConfig(data.ChannelID, "guild_id", data.GuildID)
//转换at
messageText := handlers.RevertTransformedText(data.Content)
//转换appid
Expand Down Expand Up @@ -247,7 +264,7 @@ func (p *Processor) ProcessGroupMessage(data *dto.WSGroupATMessageData) error {
// 获取s
s := client.GetGlobalS()

compatibilityMapping.WriteConfig(data.ChannelID, "guild_id", data.GuildID)
idmap.WriteConfig(data.ChannelID, "guild_id", data.GuildID)

// 转换at
messageText := handlers.RevertTransformedText(data.Content)
Expand Down Expand Up @@ -320,48 +337,231 @@ func (p *Processor) ProcessChannelDirectMessage(data *dto.WSDirectMessageData) e
// 打印data结构体
//PrintStructWithFieldNames(data)

// 从私信中提取必要的信息
// 从私信中提取必要的信息 这是测试回复需要用到
//recipientID := data.Author.ID
ChannelID := data.ChannelID
//ChannelID := data.ChannelID
//sourece是源头频道
GuildID := data.GuildID

// 创建私信通道 发主动私信才需要创建
// dm, err := p.Api.CreateDirectMessage(
// context.Background(), &dto.DirectMessageToCreate{
// SourceGuildID: sourceGuildID,
// RecipientID: recipientID,
// },
// )
// if err != nil {
// log.Println("Error creating direct message channel:", err)
// return nil
// }
//GuildID := data.GuildID

timestamp := time.Now().Unix() // 获取当前时间的int64类型的Unix时间戳
timestampStr := fmt.Sprintf("%d", timestamp)
//获取当前的s值 当前ws连接所收到的信息条数
s := client.GetGlobalS()
if !p.Settings.GlobalChannelToGroup {
// 把频道类型的私信转换成普通ob11的私信

dm := &dto.DirectMessage{
GuildID: GuildID,
ChannelID: ChannelID,
CreateTime: timestampStr,
}
//转换appidstring
AppIDString := strconv.FormatUint(p.Settings.AppID, 10)
echostr := AppIDString + "_" + strconv.FormatInt(s, 10)

PrintStructWithFieldNames(dm)
//将真实id转为int userid64
userid64, err := idmap.StoreID(data.Author.ID)
if err != nil {
log.Fatalf("Error storing ID: %v", err)
}
//将真实id写入数据库,可取出ChannelID
idmap.WriteConfig(data.Author.ID, "channel_id", data.ChannelID)
//将channelid写入数据库,可取出guild_id
idmap.WriteConfig(data.ChannelID, "guild_id", data.GuildID)

//收到私聊信息调用的具体还原步骤
//1,idmap还原真实userid,
//2,通过idmap获取channelid,
//3,通过idmap用channelid获取guildid,
//发信息使用的是guildid
//todo 优化数据库读写次数
messageID64, err := idmap.StoreID(data.ID)
if err != nil {
log.Fatalf("Error storing ID: %v", err)
}
messageID := int(messageID64)

privateMsg := OnebotPrivateMessage{
RawMessage: data.Content,
Message: data.Content,
MessageID: messageID,
MessageType: "private",
PostType: "message",
SelfID: int64(p.Settings.AppID),
UserID: userid64,
Sender: PrivateSender{
Nickname: data.Member.Nick,
UserID: userid64,
},
SubType: "friend",
Time: time.Now().Unix(),
Avatar: data.Author.Avatar,
Echo: echostr,
}

// 将当前s和appid和message进行映射
echo.AddMsgID(AppIDString, s, data.ID)
echo.AddMsgType(AppIDString, s, "guild_private")

// 调试
PrintStructWithFieldNames(privateMsg)

// Convert OnebotGroupMessage to map and send
privateMsgMap := structToMap(privateMsg)
err = p.Wsclient.SendMessage(privateMsgMap)
if err != nil {
return fmt.Errorf("error sending group message via wsclient: %v", err)
}
} else {
if !p.Settings.GlobalChannelToGroup {
//将频道私信作为普通频道信息

// 将时间字符串转换为时间戳
t, err := time.Parse(time.RFC3339, string(data.Timestamp))
if err != nil {
return fmt.Errorf("error parsing time: %v", err)
}
//获取s
s := client.GetGlobalS()
//转换at
messageText := handlers.RevertTransformedText(data.Content)
//转换appid
AppIDString := strconv.FormatUint(p.Settings.AppID, 10)
//构造echo
echostr := AppIDString + "_" + strconv.FormatInt(s, 10)
//映射str的userid到int
userid64, err := idmap.StoreID(data.Author.ID)
if err != nil {
log.Printf("Error storing ID: %v", err)
return nil
}
//OnebotChannelMessage
onebotMsg := OnebotChannelMessage{
ChannelID: data.ChannelID,
GuildID: data.GuildID,
Message: messageText,
RawMessage: messageText,
MessageID: data.ID,
MessageType: "guild",
PostType: "message",
SelfID: int64(p.Settings.AppID),
UserID: userid64,
SelfTinyID: "",
Sender: Sender{
Nickname: data.Member.Nick,
TinyID: "",
UserID: userid64,
},
SubType: "channel",
Time: t.Unix(),
Avatar: data.Author.Avatar,
Echo: echostr,
}

//将当前s和appid和message进行映射
echo.AddMsgID(AppIDString, s, data.ID)
//通过echo始终得知真实的事件类型,来对应调用正确的api
echo.AddMsgType(AppIDString, s, "guild_private")

//调试
PrintStructWithFieldNames(onebotMsg)

// 将 onebotMsg 结构体转换为 map[string]interface{}
msgMap := structToMap(onebotMsg)

// 使用 wsclient 发送消息
err = p.Wsclient.SendMessage(msgMap)
if err != nil {
return fmt.Errorf("error sending message via wsclient: %v", err)
}
} else {
//将频道信息转化为群信息(特殊需求情况下)
//将channelid写入ini,可取出guild_id
idmap.WriteConfig(data.ChannelID, "guild_id", data.GuildID)
//转换at
messageText := handlers.RevertTransformedText(data.Content)
//转换appid
AppIDString := strconv.FormatUint(p.Settings.AppID, 10)
//构造echo
echostr := AppIDString + "_" + strconv.FormatInt(s, 10)
//把频道号作为群号
channelIDInt, err := strconv.Atoi(data.ChannelID)
if err != nil {
// handle error, perhaps return it
return fmt.Errorf("failed to convert ChannelID to int: %v", err)
}
//映射str的userid到int
userid64, err := idmap.StoreID(data.Author.ID)
if err != nil {
log.Printf("Error storing ID: %v", err)
return nil
}
//userid := int(userid64)
//映射str的messageID到int
messageID64, err := idmap.StoreID(data.ID)
if err != nil {
log.Printf("Error storing ID: %v", err)
return nil
}
messageID := int(messageID64)
//todo 判断array模式 然后对Message处理成array格式
groupMsg := OnebotGroupMessage{
RawMessage: messageText,
Message: messageText,
MessageID: messageID,
GroupID: int64(channelIDInt),
MessageType: "group",
PostType: "message",
SelfID: int64(p.Settings.AppID),
UserID: userid64,
Sender: Sender{
Nickname: data.Member.Nick,
UserID: userid64,
},
SubType: "normal",
Time: time.Now().Unix(),
Avatar: data.Author.Avatar,
Echo: echostr,
}
//将当前s和appid和message进行映射
echo.AddMsgID(AppIDString, s, data.ID)
echo.AddMsgType(AppIDString, s, "guild_private")

//调试
PrintStructWithFieldNames(groupMsg)

// Convert OnebotGroupMessage to map and send
groupMsgMap := structToMap(groupMsg)
err = p.Wsclient.SendMessage(groupMsgMap)
if err != nil {
return fmt.Errorf("error sending group message via wsclient: %v", err)
}
}

// 发送默认回复
toCreate := &dto.MessageToCreate{
Content: "默认私信回复",
MsgID: data.ID,
}
_, err = p.Api.PostDirectMessage(
context.Background(), dm, toCreate,
)
if err != nil {
log.Println("Error sending default reply:", err)
return nil
}

//return nil

//下面是测试时候固定代码
//发私信给机器人4条机器人不回,就不能继续发了

// timestamp := time.Now().Unix() // 获取当前时间的int64类型的Unix时间戳
// timestampStr := fmt.Sprintf("%d", timestamp)

// dm := &dto.DirectMessage{
// GuildID: GuildID,
// ChannelID: ChannelID,
// CreateTime: timestampStr,
// }

// PrintStructWithFieldNames(dm)

// // 发送默认回复
// toCreate := &dto.MessageToCreate{
// Content: "默认私信回复",
// MsgID: data.ID,
// }
// _, err = p.Api.PostDirectMessage(
// context.Background(), dm, toCreate,
// )
// if err != nil {
// log.Println("Error sending default reply:", err)
// return nil
// }

return nil
}

Expand Down
3 changes: 1 addition & 2 deletions botgo/openapi/v2/openapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,7 @@ func (o *openAPIv2) setupClient() {
func(c *resty.Client, r *resty.Request) error {
// 设置授权方案为 "QQBot"
c.SetAuthScheme("QQBot")
c.SetAuthToken("Sv0g5ZqFKn1E7iSBYxQzzWb7ky0X-W6P6QtGRJy1cgPm8bqGLMl73b9_72kyR9y1mBE-OvXsBMpA")
//c.SetAuthToken(o.token.GetAccessToken())
c.SetAuthToken(o.token.GetAccessToken())
return nil
},
).
Expand Down
4 changes: 2 additions & 2 deletions botgo/token/authtoken.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,11 +96,11 @@ func (atoken *AuthTokenInfo) StartRefreshAccessToken(ctx context.Context, tokenU
return
}

//测试用
// 测试用
// func (atoken *AuthTokenInfo) StartRefreshAccessToken(ctx context.Context, tokenURL, appID, clientSecrent string) (err error) {
// // 创建一个固定的token信息
// fixedTokenInfo := AccessTokenInfo{
// Token: "Sv0g5ZqFKn1E7iSBYxQzzWb7ky0X-W6P6QtGRJy1cgPm8bqGLMl73b9_72kyR9y1mBE-OvXsBMpA",
// Token: "SMvPWUBuXwSyAj1UmvTKVcK7D0iEaBrmbTKVNaJFMk9S5RmpgnGvNOOOTvrqG64NhuER-e-jK2IT",
// ExpiresIn: 3600, // 这里假设token的有效时间是3600秒,你可以根据需要调整
// }
// atoken.setAuthToken(fixedTokenInfo)
Expand Down
2 changes: 1 addition & 1 deletion botgo/token/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ func (t *Token) GetAccessToken() string {
// GetAccessToken 取得测试鉴权Token
// func (t *Token) GetAccessToken() string {
// // 固定的token值
// return "Sv0g5ZqFKn1E7iSBYxQzzWb7ky0X-W6P6QtGRJy1cgPm8bqGLMl73b9_72kyR9y1mBE-OvXsBMpA"
// return "SMvPWUBuXwSyAj1UmvTKVcK7D0iEaBrmbTKVNaJFMk9S5RmpgnGvNOOOTvrqG64NhuER-e-jK2IT"
// }

// UpAccessToken 更新accessToken
Expand Down
Loading

0 comments on commit f8f7100

Please sign in to comment.