Skip to content

Commit

Permalink
update: 支持更多的api和event
Browse files Browse the repository at this point in the history
  • Loading branch information
Redmomn committed Jul 24, 2024
1 parent 9ff944b commit 28b9d2a
Show file tree
Hide file tree
Showing 9 changed files with 250 additions and 521 deletions.
29 changes: 29 additions & 0 deletions cmd/gocq/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package gocq
import (
"bufio"
"bytes"
"image"
"image/color"
"image/png"
"os"
Expand Down Expand Up @@ -102,6 +103,34 @@ func printQRCode(imgData []byte) {
_, _ = colorable.NewColorableStdout().Write(buf)
}

func printQRCodeCommon(imgData []byte) {
const (
black = "\033[48;5;0m \033[0m"
white = "\033[48;5;7m \033[0m"
)
img, err := png.Decode(bytes.NewReader(imgData))
if err != nil {
log.Panic(err)
}
data := img.(*image.Gray).Pix
bound := img.Bounds().Max.X
buf := make([]byte, 0, (bound*4+1)*(bound))
i := 0
for y := 0; y < bound; y++ {
i = y * bound
for x := 0; x < bound; x++ {
if data[i] != 255 {
buf = append(buf, white...)
} else {
buf = append(buf, black...)
}
i++
}
buf = append(buf, '\n')
}
_, _ = colorable.NewColorableStdout().Write(buf)
}

func qrcodeLogin() error {
qrcodeData, _, err := cli.FetchQRCode(1, 2, 1)
if err != nil {
Expand Down
16 changes: 10 additions & 6 deletions cmd/gocq/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"crypto/sha1"
"encoding/hex"
"fmt"
"net/url"
"os"
"path"
"sync"
Expand Down Expand Up @@ -297,13 +298,16 @@ func PasswordHashDecrypt(encryptedPasswordHash string, key []byte) ([]byte, erro
}

func newClient(appInfo *auth.AppInfo) *client.QQClient {
var signUrl string
if len(base.SignServers) != 0 {
signUrl = base.SignServers[0].URL
} else {
signUrl = ""
signUrls := make([]string, len(base.SignServers))
for i, s := range base.SignServers {
u, err := url.Parse(s.URL)
if err != nil || u.Hostname() == "" {
continue
}
signUrls[i] = u.String()
}
c := client.NewClient(0, signUrl, appInfo)
log.Warnf("signUrls: %#v", signUrls)
c := client.NewClient(0, appInfo, signUrls...)
// TODO 服务器更新通知
// c.OnServerUpdated(func(bot *client.QQClient, e *client.ServerUpdatedEvent) bool {
// if !base.UseSSOAddress {
Expand Down
110 changes: 55 additions & 55 deletions coolq/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/hex"
"encoding/json"
"fmt"
"strconv"

"github.com/LagrangeDev/LagrangeGo/client/entity"

Expand Down Expand Up @@ -121,7 +122,7 @@ func (bot *CQBot) CQGetFriendList(spec *onebot.Spec) global.MSG {
// @route(get_group_list)
func (bot *CQBot) CQGetGroupList(noCache bool, spec *onebot.Spec) global.MSG {
if noCache {
_ = bot.Client.RefreshAllGroupsInfo
_ = bot.Client.RefreshAllGroupsInfo()
}
grpInfos := bot.Client.GetCachedAllGroupsInfo()
gs := make([]global.MSG, 0, len(grpInfos))
Expand All @@ -145,7 +146,7 @@ func (bot *CQBot) CQGetGroupList(noCache bool, spec *onebot.Spec) global.MSG {
// @route(get_group_info)
func (bot *CQBot) CQGetGroupInfo(groupID int64, noCache bool, spec *onebot.Spec) global.MSG {
if noCache {
_ = bot.Client.RefreshAllGroupsInfo
_ = bot.Client.RefreshAllGroupsInfo()
}
group := bot.Client.GetCachedGroupInfo(uint32(groupID))
if group != nil {
Expand All @@ -167,7 +168,7 @@ func (bot *CQBot) CQGetGroupInfo(groupID int64, noCache bool, spec *onebot.Spec)
// @route(get_group_member_list)
func (bot *CQBot) CQGetGroupMemberList(groupID int64, noCache bool) global.MSG {
if noCache {
_ = bot.Client.RefreshAllGroupsInfo
_ = bot.Client.RefreshAllGroupsInfo()
}
groupMembers := bot.Client.GetCachedMembersInfo(uint32(groupID))
if groupMembers == nil {
Expand Down Expand Up @@ -874,53 +875,52 @@ func (bot *CQBot) CQSetGroupLeave(groupID int64) global.MSG {
// return OK(nil)
//}

// TODO 计划实现的api 处理加群请求/邀请
// CQProcessGroupRequest 处理加群请求/邀请
//
// https://git.io/Jtz1D
// @route(set_group_add_request)
// @rename(sub_type->"[sub_type\x2Ctype].0")
// @default(approve=true)
//func (bot *CQBot) CQProcessGroupRequest(flag, subType, reason string, approve bool) global.MSG {
// msgs, err := bot.Client.GetGroupSystemMessages()
// if err != nil {
// log.Warnf("获取群系统消息失败: %v", err)
// return Failed(100, "SYSTEM_MSG_API_ERROR", err.Error())
// }
// if subType == "add" {
// for _, req := range msgs.JoinRequests {
// if strconv.FormatInt(req.RequestId, 10) == flag {
// if req.Checked {
// log.Warnf("处理群系统消息失败: 无法操作已处理的消息.")
// return Failed(100, "FLAG_HAS_BEEN_CHECKED", "消息已被处理")
// }
// if approve {
// req.Accept()
// } else {
// req.Reject(false, reason)
// }
// return OK(nil)
// }
// }
// } else {
// for _, req := range msgs.InvitedRequests {
// if strconv.FormatInt(req.RequestId, 10) == flag {
// if req.Checked {
// log.Warnf("处理群系统消息失败: 无法操作已处理的消息.")
// return Failed(100, "FLAG_HAS_BEEN_CHECKED", "消息已被处理")
// }
// if approve {
// req.Accept()
// } else {
// req.Reject(false, reason)
// }
// return OK(nil)
// }
// }
// }
// log.Warnf("处理群系统消息失败: 消息 %v 不存在.", flag)
// return Failed(100, "FLAG_NOT_FOUND", "FLAG不存在")
//}
func (bot *CQBot) CQProcessGroupRequest(flag, subType, reason string, approve bool) global.MSG {
msgs, err := bot.Client.GetGroupSystemMessages()
if err != nil {
log.Warnf("获取群系统消息失败: %v", err)
return Failed(100, "SYSTEM_MSG_API_ERROR", err.Error())
}
if subType == "add" {
for _, req := range msgs {
if strconv.FormatInt(int64(req.Sequence), 10) == flag {
if req.Checked() {
log.Warnf("处理群系统消息失败: 无法操作已处理的消息.")
return Failed(100, "FLAG_HAS_BEEN_CHECKED", "消息已被处理")
}
if approve {
bot.Client.SetGroupRequest(true, req.Sequence, req.EventType, req.GroupUin, "")
} else {
bot.Client.SetGroupRequest(false, req.Sequence, req.EventType, req.GroupUin, reason)
}
return OK(nil)
}
}
} else {
for _, req := range msgs {
if strconv.FormatInt(int64(req.Sequence), 10) == flag {
if req.Checked() {
log.Warnf("处理群系统消息失败: 无法操作已处理的消息.")
return Failed(100, "FLAG_HAS_BEEN_CHECKED", "消息已被处理")
}
if approve {
bot.Client.SetGroupRequest(true, req.Sequence, req.EventType, req.GroupUin, "")
} else {
bot.Client.SetGroupRequest(false, req.Sequence, req.EventType, req.GroupUin, reason)
}
return OK(nil)
}
}
}
log.Warnf("处理群系统消息失败: 消息 %v 不存在.", flag)
return Failed(100, "FLAG_NOT_FOUND", "FLAG不存在")
}

// CQDeleteMessage 撤回消息
//
Expand Down Expand Up @@ -1164,17 +1164,17 @@ func (bot *CQBot) CQHandleQuickOperation(context, operation gjson.Result) global
}
}
}
// TODO 暂未支持
//case "request":
// reqType := context.Get("request_type").Str
// if operation.Get("approve").Exists() {
// if reqType == "friend" {
// bot.CQProcessFriendRequest(context.Get("flag").String(), operation.Get("approve").Bool())
// }
// if reqType == "group" {
// bot.CQProcessGroupRequest(context.Get("flag").String(), context.Get("sub_type").Str, operation.Get("reason").Str, operation.Get("approve").Bool())
// }
// }
case "request":
reqType := context.Get("request_type").Str
if operation.Get("approve").Exists() {
// TODO 暂未支持
//if reqType == "friend" {
// bot.CQProcessFriendRequest(context.Get("flag").String(), operation.Get("approve").Bool())
//}
if reqType == "group" {
bot.CQProcessGroupRequest(context.Get("flag").String(), context.Get("sub_type").Str, operation.Get("reason").Str, operation.Get("approve").Bool())
}
}
}
return OK(nil)
}
Expand Down
60 changes: 12 additions & 48 deletions coolq/bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,20 +86,17 @@ func NewQQBot(cli *client.QQClient) *CQBot {
//bot.Client.TempMessageEvent.Subscribe(bot.tempMessageEvent)
bot.Client.GroupMuteEvent.Subscribe(bot.groupMutedEvent)
bot.Client.GroupRecallEvent.Subscribe(bot.groupRecallEvent)
// TODO 群聊通知消息 运气王
bot.Client.GroupNotifyEvent.Subscribe(bot.groupNotifyEvent)
// TODO 好友戳一戳事件
//bot.Client.FriendNotifyEvent.Subscribe(bot.friendNotifyEvent)
// TODO 成员获得特殊群头衔
//bot.Client.MemberSpecialTitleUpdatedEvent.Subscribe(bot.memberTitleUpdatedEvent)
bot.Client.FriendNotifyEvent.Subscribe(bot.friendNotifyEvent)
bot.Client.MemberSpecialTitleUpdatedEvent.Subscribe(bot.memberTitleUpdatedEvent)
bot.Client.FriendRecallEvent.Subscribe(bot.friendRecallEvent)
// TODO 离线文件
//bot.Client.OfflineFileEvent.Subscribe(bot.offlineFileEvent)
// TODO bot加群
//bot.Client.GroupJoinEvent.Subscribe(bot.joinGroupEvent)
bot.Client.GroupJoinEvent.Subscribe(bot.joinGroupEvent)
// TODO bot退群
//bot.Client.GroupLeaveEvent.Subscribe(bot.leaveGroupEvent)
//bot.Client.GroupMemberJoinEvent.Subscribe(bot.memberJoinEvent)
bot.Client.GroupLeaveEvent.Subscribe(bot.leaveGroupEvent)
bot.Client.GroupMemberJoinEvent.Subscribe(bot.memberJoinEvent)
bot.Client.GroupMemberLeaveEvent.Subscribe(bot.memberLeaveEvent)
// TODO 群成员权限变更
//bot.Client.GroupMemberPermissionChangedEvent.Subscribe(bot.memberPermissionChangedEvent)
Expand All @@ -113,7 +110,7 @@ func NewQQBot(cli *client.QQClient) *CQBot {
// TODO 客户端变更
//bot.Client.OtherClientStatusChangedEvent.Subscribe(bot.otherClientStatusChangedEvent)
// TODO 精华消息
//bot.Client.GroupDigestEvent.Subscribe(bot.groupEssenceMsg)
bot.Client.GroupDigestEvent.Subscribe(bot.groupEssenceMsg)
go func() {
if base.HeartbeatInterval == 0 {
log.Warn("警告: 心跳功能已关闭,若非预期,请检查配置文件。")
Expand Down Expand Up @@ -330,30 +327,11 @@ func (bot *CQBot) SendGroupMessage(groupID int64, m *message.SendingMessage) (in
m.Elements = newElem
bot.checkMedia(newElem, groupID)
ret, err := bot.Client.SendGroupMessage(uint32(groupID), m.Elements)
if err != nil || ret == nil || ret.GroupSequence.IsNone() {
if err != nil || ret == nil {
log.Warnf("群 %v 发送消息失败: 账号可能被风控.", groupID)
return -1, errors.New("send group message failed: blocked by server")
}
// TODO 发送完成之后获取*message.GroupMessage
group := bot.Client.GetCachedGroupInfo(uint32(groupID))
minfo := bot.Client.GetCachedMemberInfo(bot.Client.Uin, uint32(groupID))
return bot.InsertGroupMessage(&message.GroupMessage{
Id: int32(ret.GroupSequence.Unwrap()),
InternalId: int32(ret.Timestamp1),
GroupUin: uint32(groupID),
GroupName: group.GroupName,
Sender: &message.Sender{
Uin: bot.Client.Uin,
Uid: bot.Client.GetUid(bot.Client.Uin),
Nickname: bot.Client.NickName(),
CardName: minfo.MemberCard,
AnonymousInfo: nil,
IsFriend: true,
},
Time: uint64(ret.Timestamp1),
Elements: m.Elements,
OriginalObject: nil,
}, source), nil
return bot.InsertGroupMessage(ret, source), nil
}

// SendPrivateMessage 发送私聊消息
Expand Down Expand Up @@ -401,30 +379,16 @@ func (bot *CQBot) SendPrivateMessage(target int64, groupID int64, m *message.Sen
//session, ok := bot.tempSessionCache.Load(target)
var id int32 = -1
ret, err := bot.Client.SendPrivateMessage(uint32(groupID), m.Elements)
if err != nil {
id = bot.InsertPrivateMessage(&message.PrivateMessage{
Id: int32(ret.PrivateSequence),
InternalId: int32(ret.Timestamp1),
Self: int64(bot.Client.Uin),
Target: target,
Time: int32(ret.Timestamp1),
Sender: &message.Sender{
Uin: bot.Client.Uin,
Uid: bot.Client.GetUid(bot.Client.Uin),
Nickname: bot.Client.NickName(),
AnonymousInfo: nil,
IsFriend: true,
},
Elements: nil,
}, source)
if err != nil || ret == nil {
id = bot.InsertPrivateMessage(ret, source)
}
//switch {
//case bot.Client.FindFriend(target) != nil: // 双向好友
// msg := bot.Client.SendPrivateMessage(target, m)
// if msg != nil {
// id = bot.InsertPrivateMessage(msg, source)
// }
// TODO 临时会话
// TODO 应该是不支持临时会话了
//case ok || groupID != 0: // 临时会话
// if !base.AllowTempSession {
// log.Warnf("发送临时会话消息失败: 已关闭临时会话信息发送功能")
Expand Down Expand Up @@ -618,7 +582,7 @@ func formatMemberName(mem *entity.GroupMember) string {
if mem == nil {
return "未知"
}
return fmt.Sprintf("%s(%d)", mem.MemberName, mem.Uin)
return fmt.Sprintf("%s(%d)", mem.DisplayName(), mem.Uin)
}

// encodeMessageID 临时先这样, 暂时用不上
Expand Down
Loading

0 comments on commit 28b9d2a

Please sign in to comment.