1
0
mirror of https://github.com/Mrs4s/go-cqhttp.git synced 2025-06-30 03:43:25 +00:00

Compare commits

...

16 Commits

Author SHA1 Message Date
dfeadef1a2 update MiraiGo. 2020-12-02 22:13:52 +08:00
b23f68e746 try to fix #422. 2020-12-02 22:13:02 +08:00
c5a5f71664 update MiraiGo. 2020-12-02 20:34:15 +08:00
6973a10b4b fix #455. 2020-12-02 19:29:31 +08:00
3468c38fbc clear code. 2020-12-02 15:05:20 +08:00
d76bcfb1f0 update MiraiGo. 2020-12-02 00:36:26 +08:00
716c38bab4 Merge branch 'master' into dev 2020-12-02 00:35:24 +08:00
03518b4823 more error message. 2020-12-01 21:14:48 +08:00
09eeff3ce6 feature new cqcode converter 2020-12-01 19:31:17 +08:00
6599bf6aa6 update MiraiGo. 2020-11-29 21:17:16 +08:00
ffb2faeae7 Merge pull request #452 from brownchow/master
remove mkdir, add set -ex
2020-11-29 21:05:54 +08:00
71e3e97aeb update MiraiGo. 2020-11-29 21:01:12 +08:00
dcb708e3e3 remove mkdir, add set -ex 2020-11-29 18:21:01 +08:00
b9fb833af4 Merge pull request #451 from daofeng2015/master
fix:Dockerfile增加代理源
2020-11-29 13:55:19 +08:00
b93df0250d fix:Dockerfile增加代理源 2020-11-28 23:24:24 +08:00
33d64b6e27 update README.md 2020-11-27 01:46:42 +08:00
7 changed files with 172 additions and 88 deletions

View File

@ -2,14 +2,15 @@ FROM golang:1.15.5-alpine AS builder
RUN go env -w GO111MODULE=auto \ RUN go env -w GO111MODULE=auto \
&& go env -w CGO_ENABLED=0 \ && go env -w CGO_ENABLED=0 \
&& mkdir /build && go env -w GOPROXY=https://goproxy.cn,direct
WORKDIR /build WORKDIR /build
COPY ./ . COPY ./ .
RUN cd /build \ RUN set -ex \
&& go build -ldflags "-s -w -extldflags '-static'" -o cqhttp && cd /build \
&& go build -ldflags "-s -w -extldflags '-static'" -o cqhttp
FROM alpine:latest FROM alpine:latest

View File

@ -20,7 +20,7 @@
- [x] 消息撤回事件 - [x] 消息撤回事件
- [x] 解析/发送 回复消息 - [x] 解析/发送 回复消息
- [x] 解析/发送 合并转发 - [x] 解析/发送 合并转发
- [ ] 使用代理请求网络图片 - [x] 使用代理请求网络图片
#### 实现 #### 实现
<details> <details>

View File

@ -58,7 +58,7 @@ func (bot *CQBot) CQGetGroupList(noCache bool) MSG {
func (bot *CQBot) CQGetGroupInfo(groupId int64) MSG { func (bot *CQBot) CQGetGroupInfo(groupId int64) MSG {
group := bot.Client.FindGroup(groupId) group := bot.Client.FindGroup(groupId)
if group == nil { if group == nil {
return Failed(100) return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
} }
return OK(MSG{ return OK(MSG{
"group_id": group.Code, "group_id": group.Code,
@ -72,13 +72,13 @@ func (bot *CQBot) CQGetGroupInfo(groupId int64) MSG {
func (bot *CQBot) CQGetGroupMemberList(groupId int64, noCache bool) MSG { func (bot *CQBot) CQGetGroupMemberList(groupId int64, noCache bool) MSG {
group := bot.Client.FindGroup(groupId) group := bot.Client.FindGroup(groupId)
if group == nil { if group == nil {
return Failed(100) return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
} }
if noCache { if noCache {
t, err := bot.Client.GetGroupMembers(group) t, err := bot.Client.GetGroupMembers(group)
if err != nil { if err != nil {
log.Warnf("刷新群 %v 成员列表失败: %v", groupId, err) log.Warnf("刷新群 %v 成员列表失败: %v", groupId, err)
return Failed(100) return Failed(100, "GET_MEMBERS_API_ERROR", err.Error())
} }
group.Members = t group.Members = t
} }
@ -93,11 +93,11 @@ func (bot *CQBot) CQGetGroupMemberList(groupId int64, noCache bool) MSG {
func (bot *CQBot) CQGetGroupMemberInfo(groupId, userId int64) MSG { func (bot *CQBot) CQGetGroupMemberInfo(groupId, userId int64) MSG {
group := bot.Client.FindGroup(groupId) group := bot.Client.FindGroup(groupId)
if group == nil { if group == nil {
return Failed(100) return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
} }
member := group.FindMember(userId) member := group.FindMember(userId)
if member == nil { if member == nil {
return Failed(102) return Failed(100, "MEMBER_NOT_FOUND", "群员不存在")
} }
return OK(convertGroupMemberInfo(groupId, member)) return OK(convertGroupMemberInfo(groupId, member))
} }
@ -106,7 +106,7 @@ func (bot *CQBot) CQGetGroupFileSystemInfo(groupId int64) MSG {
fs, err := bot.Client.GetGroupFileSystem(groupId) fs, err := bot.Client.GetGroupFileSystem(groupId)
if err != nil { if err != nil {
log.Errorf("获取群 %v 文件系统信息失败: %v", groupId, err) log.Errorf("获取群 %v 文件系统信息失败: %v", groupId, err)
return Failed(100) return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
} }
return OK(fs) return OK(fs)
} }
@ -115,12 +115,12 @@ func (bot *CQBot) CQGetGroupRootFiles(groupId int64) MSG {
fs, err := bot.Client.GetGroupFileSystem(groupId) fs, err := bot.Client.GetGroupFileSystem(groupId)
if err != nil { if err != nil {
log.Errorf("获取群 %v 文件系统信息失败: %v", groupId, err) log.Errorf("获取群 %v 文件系统信息失败: %v", groupId, err)
return Failed(100) return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
} }
files, folders, err := fs.Root() files, folders, err := fs.Root()
if err != nil { if err != nil {
log.Errorf("获取群 %v 根目录文件失败: %v", groupId, err) log.Errorf("获取群 %v 根目录文件失败: %v", groupId, err)
return Failed(100) return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
} }
return OK(MSG{ return OK(MSG{
"files": files, "files": files,
@ -132,12 +132,12 @@ func (bot *CQBot) CQGetGroupFilesByFolderId(groupId int64, folderId string) MSG
fs, err := bot.Client.GetGroupFileSystem(groupId) fs, err := bot.Client.GetGroupFileSystem(groupId)
if err != nil { if err != nil {
log.Errorf("获取群 %v 文件系统信息失败: %v", groupId, err) log.Errorf("获取群 %v 文件系统信息失败: %v", groupId, err)
return Failed(100) return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
} }
files, folders, err := fs.GetFilesByFolder(folderId) files, folders, err := fs.GetFilesByFolder(folderId)
if err != nil { if err != nil {
log.Errorf("获取群 %v 根目录 %v 子文件失败: %v", groupId, folderId, err) log.Errorf("获取群 %v 根目录 %v 子文件失败: %v", groupId, folderId, err)
return Failed(100) return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
} }
return OK(MSG{ return OK(MSG{
"files": files, "files": files,
@ -148,7 +148,7 @@ func (bot *CQBot) CQGetGroupFilesByFolderId(groupId int64, folderId string) MSG
func (bot *CQBot) CQGetGroupFileUrl(groupId int64, fileId string, busId int32) MSG { func (bot *CQBot) CQGetGroupFileUrl(groupId int64, fileId string, busId int32) MSG {
url := bot.Client.GetGroupFileUrl(groupId, fileId, busId) url := bot.Client.GetGroupFileUrl(groupId, fileId, busId)
if url == "" { if url == "" {
return Failed(100) return Failed(100, "FILE_SYSTEM_API_ERROR")
} }
return OK(MSG{ return OK(MSG{
"url": url, "url": url,
@ -158,7 +158,7 @@ func (bot *CQBot) CQGetGroupFileUrl(groupId int64, fileId string, busId int32) M
func (bot *CQBot) CQGetWordSlices(content string) MSG { func (bot *CQBot) CQGetWordSlices(content string) MSG {
slices, err := bot.Client.GetWordSegmentation(content) slices, err := bot.Client.GetWordSegmentation(content)
if err != nil { if err != nil {
return Failed(100) return Failed(100, "WORD_SEGMENTATION_API_ERROR", err.Error())
} }
for i := 0; i < len(slices); i++ { for i := 0; i < len(slices); i++ {
slices[i] = strings.ReplaceAll(slices[i], "\u0000", "") slices[i] = strings.ReplaceAll(slices[i], "\u0000", "")
@ -188,7 +188,7 @@ func (bot *CQBot) CQSendGroupMessage(groupId int64, i interface{}, autoEscape bo
fixAt(elem) fixAt(elem)
mid := bot.SendGroupMessage(groupId, &message.SendingMessage{Elements: elem}) mid := bot.SendGroupMessage(groupId, &message.SendingMessage{Elements: elem})
if mid == -1 { if mid == -1 {
return Failed(100) return Failed(100, "SEND_MSG_API_ERROR", "请参考输出")
} }
log.Infof("发送群 %v(%v) 的消息: %v (%v)", groupId, groupId, limitedString(m.String()), mid) log.Infof("发送群 %v(%v) 的消息: %v (%v)", groupId, groupId, limitedString(m.String()), mid)
return OK(MSG{"message_id": mid}) return OK(MSG{"message_id": mid})
@ -204,7 +204,7 @@ func (bot *CQBot) CQSendGroupMessage(groupId int64, i interface{}, autoEscape bo
} }
if str == "" { if str == "" {
log.Warnf("群消息发送失败: 信息为空. MSG: %v", i) log.Warnf("群消息发送失败: 信息为空. MSG: %v", i)
return Failed(100) return Failed(100, "EMPTY_MSG_ERROR", "消息为空")
} }
var elem []message.IMessageElement var elem []message.IMessageElement
if autoEscape { if autoEscape {
@ -215,7 +215,7 @@ func (bot *CQBot) CQSendGroupMessage(groupId int64, i interface{}, autoEscape bo
fixAt(elem) fixAt(elem)
mid := bot.SendGroupMessage(groupId, &message.SendingMessage{Elements: elem}) mid := bot.SendGroupMessage(groupId, &message.SendingMessage{Elements: elem})
if mid == -1 { if mid == -1 {
return Failed(100) return Failed(100, "SEND_MSG_API_ERROR", "请参考输出")
} }
log.Infof("发送群 %v(%v) 的消息: %v (%v)", groupId, groupId, limitedString(str), mid) log.Infof("发送群 %v(%v) 的消息: %v (%v)", groupId, groupId, limitedString(str), mid)
return OK(MSG{"message_id": mid}) return OK(MSG{"message_id": mid})
@ -312,7 +312,7 @@ func (bot *CQBot) CQSendPrivateMessage(userId int64, i interface{}, autoEscape b
elem := bot.ConvertObjectMessage(m, true) elem := bot.ConvertObjectMessage(m, true)
mid := bot.SendPrivateMessage(userId, &message.SendingMessage{Elements: elem}) mid := bot.SendPrivateMessage(userId, &message.SendingMessage{Elements: elem})
if mid == -1 { if mid == -1 {
return Failed(100) return Failed(100, "SEND_MSG_API_ERROR", "请参考输出")
} }
log.Infof("发送好友 %v(%v) 的消息: %v (%v)", userId, userId, limitedString(m.String()), mid) log.Infof("发送好友 %v(%v) 的消息: %v (%v)", userId, userId, limitedString(m.String()), mid)
return OK(MSG{"message_id": mid}) return OK(MSG{"message_id": mid})
@ -327,7 +327,7 @@ func (bot *CQBot) CQSendPrivateMessage(userId int64, i interface{}, autoEscape b
str = s str = s
} }
if str == "" { if str == "" {
return Failed(100) return Failed(100, "EMPTY_MSG_ERROR", "消息为空")
} }
var elem []message.IMessageElement var elem []message.IMessageElement
if autoEscape { if autoEscape {
@ -337,7 +337,7 @@ func (bot *CQBot) CQSendPrivateMessage(userId int64, i interface{}, autoEscape b
} }
mid := bot.SendPrivateMessage(userId, &message.SendingMessage{Elements: elem}) mid := bot.SendPrivateMessage(userId, &message.SendingMessage{Elements: elem})
if mid == -1 { if mid == -1 {
return Failed(100) return Failed(100, "SEND_MSG_API_ERROR", "请参考输出")
} }
log.Infof("发送好友 %v(%v) 的消息: %v (%v)", userId, userId, limitedString(str), mid) log.Infof("发送好友 %v(%v) 的消息: %v (%v)", userId, userId, limitedString(str), mid)
return OK(MSG{"message_id": mid}) return OK(MSG{"message_id": mid})
@ -351,7 +351,7 @@ func (bot *CQBot) CQSetGroupCard(groupId, userId int64, card string) MSG {
return OK(nil) return OK(nil)
} }
} }
return Failed(100) return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
} }
// https://cqhttp.cc/docs/4.15/#/API?id=set_group_special_title-%E8%AE%BE%E7%BD%AE%E7%BE%A4%E7%BB%84%E4%B8%93%E5%B1%9E%E5%A4%B4%E8%A1%94 // https://cqhttp.cc/docs/4.15/#/API?id=set_group_special_title-%E8%AE%BE%E7%BD%AE%E7%BE%A4%E7%BB%84%E4%B8%93%E5%B1%9E%E5%A4%B4%E8%A1%94
@ -362,7 +362,7 @@ func (bot *CQBot) CQSetGroupSpecialTitle(groupId, userId int64, title string) MS
return OK(nil) return OK(nil)
} }
} }
return Failed(100) return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
} }
func (bot *CQBot) CQSetGroupName(groupId int64, name string) MSG { func (bot *CQBot) CQSetGroupName(groupId int64, name string) MSG {
@ -370,7 +370,7 @@ func (bot *CQBot) CQSetGroupName(groupId int64, name string) MSG {
g.UpdateName(name) g.UpdateName(name)
return OK(nil) return OK(nil)
} }
return Failed(100) return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
} }
func (bot *CQBot) CQSetGroupMemo(groupId int64, msg string) MSG { func (bot *CQBot) CQSetGroupMemo(groupId int64, msg string) MSG {
@ -378,7 +378,7 @@ func (bot *CQBot) CQSetGroupMemo(groupId int64, msg string) MSG {
g.UpdateMemo(msg) g.UpdateMemo(msg)
return OK(nil) return OK(nil)
} }
return Failed(100) return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
} }
// https://cqhttp.cc/docs/4.15/#/API?id=set_group_kick-%E7%BE%A4%E7%BB%84%E8%B8%A2%E4%BA%BA // https://cqhttp.cc/docs/4.15/#/API?id=set_group_kick-%E7%BE%A4%E7%BB%84%E8%B8%A2%E4%BA%BA
@ -389,7 +389,7 @@ func (bot *CQBot) CQSetGroupKick(groupId, userId int64, msg string, block bool)
return OK(nil) return OK(nil)
} }
} }
return Failed(100) return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
} }
// https://cqhttp.cc/docs/4.15/#/API?id=set_group_ban-%E7%BE%A4%E7%BB%84%E5%8D%95%E4%BA%BA%E7%A6%81%E8%A8%80 // https://cqhttp.cc/docs/4.15/#/API?id=set_group_ban-%E7%BE%A4%E7%BB%84%E5%8D%95%E4%BA%BA%E7%A6%81%E8%A8%80
@ -400,7 +400,7 @@ func (bot *CQBot) CQSetGroupBan(groupId, userId int64, duration uint32) MSG {
return OK(nil) return OK(nil)
} }
} }
return Failed(100) return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
} }
// https://cqhttp.cc/docs/4.15/#/API?id=set_group_whole_ban-%E7%BE%A4%E7%BB%84%E5%85%A8%E5%91%98%E7%A6%81%E8%A8%80 // https://cqhttp.cc/docs/4.15/#/API?id=set_group_whole_ban-%E7%BE%A4%E7%BB%84%E5%85%A8%E5%91%98%E7%A6%81%E8%A8%80
@ -409,7 +409,7 @@ func (bot *CQBot) CQSetGroupWholeBan(groupId int64, enable bool) MSG {
g.MuteAll(enable) g.MuteAll(enable)
return OK(nil) return OK(nil)
} }
return Failed(100) return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
} }
// https://cqhttp.cc/docs/4.15/#/API?id=set_group_leave-%E9%80%80%E5%87%BA%E7%BE%A4%E7%BB%84 // https://cqhttp.cc/docs/4.15/#/API?id=set_group_leave-%E9%80%80%E5%87%BA%E7%BE%A4%E7%BB%84
@ -418,14 +418,14 @@ func (bot *CQBot) CQSetGroupLeave(groupId int64) MSG {
g.Quit() g.Quit()
return OK(nil) return OK(nil)
} }
return Failed(100) return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
} }
// https://cqhttp.cc/docs/4.15/#/API?id=set_friend_add_request-%E5%A4%84%E7%90%86%E5%8A%A0%E5%A5%BD%E5%8F%8B%E8%AF%B7%E6%B1%82 // https://cqhttp.cc/docs/4.15/#/API?id=set_friend_add_request-%E5%A4%84%E7%90%86%E5%8A%A0%E5%A5%BD%E5%8F%8B%E8%AF%B7%E6%B1%82
func (bot *CQBot) CQProcessFriendRequest(flag string, approve bool) MSG { func (bot *CQBot) CQProcessFriendRequest(flag string, approve bool) MSG {
req, ok := bot.friendReqCache.Load(flag) req, ok := bot.friendReqCache.Load(flag)
if !ok { if !ok {
return Failed(100) return Failed(100, "FLAG_NOT_FOUND", "FLAG不存在")
} }
if approve { if approve {
req.(*client.NewFriendRequest).Accept() req.(*client.NewFriendRequest).Accept()
@ -440,14 +440,14 @@ func (bot *CQBot) CQProcessGroupRequest(flag, subType, reason string, approve bo
msgs, err := bot.Client.GetGroupSystemMessages() msgs, err := bot.Client.GetGroupSystemMessages()
if err != nil { if err != nil {
log.Errorf("获取群系统消息失败: %v", err) log.Errorf("获取群系统消息失败: %v", err)
return Failed(100) return Failed(100, "SYSTEM_MSG_API_ERROR", err.Error())
} }
if subType == "add" { if subType == "add" {
for _, req := range msgs.JoinRequests { for _, req := range msgs.JoinRequests {
if strconv.FormatInt(req.RequestId, 10) == flag { if strconv.FormatInt(req.RequestId, 10) == flag {
if req.Checked { if req.Checked {
log.Errorf("处理群系统消息失败: 无法操作已处理的消息.") log.Errorf("处理群系统消息失败: 无法操作已处理的消息.")
return Failed(100) return Failed(100, "FLAG_HAS_BEEN_CHECKED", "消息已被处理")
} }
if approve { if approve {
req.Accept() req.Accept()
@ -462,7 +462,7 @@ func (bot *CQBot) CQProcessGroupRequest(flag, subType, reason string, approve bo
if strconv.FormatInt(req.RequestId, 10) == flag { if strconv.FormatInt(req.RequestId, 10) == flag {
if req.Checked { if req.Checked {
log.Errorf("处理群系统消息失败: 无法操作已处理的消息.") log.Errorf("处理群系统消息失败: 无法操作已处理的消息.")
return Failed(100) return Failed(100, "FLAG_HAS_BEEN_CHECKED", "消息已被处理")
} }
if approve { if approve {
req.Accept() req.Accept()
@ -474,28 +474,28 @@ func (bot *CQBot) CQProcessGroupRequest(flag, subType, reason string, approve bo
} }
} }
log.Errorf("处理群系统消息失败: 消息 %v 不存在.", flag) log.Errorf("处理群系统消息失败: 消息 %v 不存在.", flag)
return Failed(100) return Failed(100, "FLAG_NOT_FOUND", "FLAG不存在")
} }
// https://cqhttp.cc/docs/4.15/#/API?id=delete_msg-%E6%92%A4%E5%9B%9E%E6%B6%88%E6%81%AF // https://cqhttp.cc/docs/4.15/#/API?id=delete_msg-%E6%92%A4%E5%9B%9E%E6%B6%88%E6%81%AF
func (bot *CQBot) CQDeleteMessage(messageId int32) MSG { func (bot *CQBot) CQDeleteMessage(messageId int32) MSG {
msg := bot.GetMessage(messageId) msg := bot.GetMessage(messageId)
if msg == nil { if msg == nil {
return Failed(100) return Failed(100, "MESSAGE_NOT_FOUND", "消息不存在")
} }
if _, ok := msg["group"]; ok { if _, ok := msg["group"]; ok {
if err := bot.Client.RecallGroupMessage(msg["group"].(int64), msg["message-id"].(int32), msg["internal-id"].(int32)); err != nil { if err := bot.Client.RecallGroupMessage(msg["group"].(int64), msg["message-id"].(int32), msg["internal-id"].(int32)); err != nil {
log.Warnf("撤回 %v 失败: %v", messageId, err) log.Warnf("撤回 %v 失败: %v", messageId, err)
return Failed(100) return Failed(100, "RECALL_API_ERROR", err.Error())
} }
} else { } else {
if msg["sender"].(message.Sender).Uin != bot.Client.Uin { if msg["sender"].(message.Sender).Uin != bot.Client.Uin {
log.Warnf("撤回 %v 失败: 好友会话无法撤回对方消息.") log.Warnf("撤回 %v 失败: 好友会话无法撤回对方消息.", messageId)
return Failed(100) return Failed(100, "CANNOT_RECALL_FRIEND_MSG", "无法撤回对方消息")
} }
if err := bot.Client.RecallPrivateMessage(msg["target"].(int64), int64(msg["time"].(int32)), msg["message-id"].(int32), msg["internal-id"].(int32)); err != nil { if err := bot.Client.RecallPrivateMessage(msg["target"].(int64), int64(msg["time"].(int32)), msg["message-id"].(int32), msg["internal-id"].(int32)); err != nil {
log.Warnf("撤回 %v 失败: %v", messageId, err) log.Warnf("撤回 %v 失败: %v", messageId, err)
return Failed(100) return Failed(100, "RECALL_API_ERROR", err.Error())
} }
} }
return OK(nil) return OK(nil)
@ -505,17 +505,17 @@ func (bot *CQBot) CQDeleteMessage(messageId int32) MSG {
func (bot *CQBot) CQSetGroupAdmin(groupId, userId int64, enable bool) MSG { func (bot *CQBot) CQSetGroupAdmin(groupId, userId int64, enable bool) MSG {
group := bot.Client.FindGroup(groupId) group := bot.Client.FindGroup(groupId)
if group == nil || group.OwnerUin != bot.Client.Uin { if group == nil || group.OwnerUin != bot.Client.Uin {
return Failed(100) return Failed(100, "PERMISSION_DENIED", "群不存在或权限不足")
} }
mem := group.FindMember(userId) mem := group.FindMember(userId)
if mem == nil { if mem == nil {
return Failed(100) return Failed(100, "GROUP_MEMBER_NOT_FOUND", "群成员不存在")
} }
mem.SetAdmin(enable) mem.SetAdmin(enable)
t, err := bot.Client.GetGroupMembers(group) t, err := bot.Client.GetGroupMembers(group)
if err != nil { if err != nil {
log.Warnf("刷新群 %v 成员列表失败: %v", groupId, err) log.Warnf("刷新群 %v 成员列表失败: %v", groupId, err)
return Failed(100) return Failed(100, "GET_MEMBERS_API_ERROR", err.Error())
} }
group.Members = t group.Members = t
return OK(nil) return OK(nil)
@ -524,7 +524,7 @@ func (bot *CQBot) CQSetGroupAdmin(groupId, userId int64, enable bool) MSG {
func (bot *CQBot) CQGetVipInfo(userId int64) MSG { func (bot *CQBot) CQGetVipInfo(userId int64) MSG {
vip, err := bot.Client.GetVipInfo(userId) vip, err := bot.Client.GetVipInfo(userId)
if err != nil { if err != nil {
return Failed(100) return Failed(100, "VIP_API_ERROR", err.Error())
} }
msg := MSG{ msg := MSG{
"user_id": vip.Uin, "user_id": vip.Uin,
@ -597,7 +597,7 @@ func (bot *CQBot) CQGetGroupHonorInfo(groupId int64, t string) MSG {
func (bot *CQBot) CQGetStrangerInfo(userId int64) MSG { func (bot *CQBot) CQGetStrangerInfo(userId int64) MSG {
info, err := bot.Client.GetSummaryInfo(userId) info, err := bot.Client.GetSummaryInfo(userId)
if err != nil { if err != nil {
return Failed(100) return Failed(100, "SUMMARY_API_ERROR", err.Error())
} }
return OK(MSG{ return OK(MSG{
"user_id": info.Uin, "user_id": info.Uin,
@ -692,14 +692,15 @@ func (bot *CQBot) CQGetImage(file string) MSG {
} }
msg["file"] = local msg["file"] = local
return OK(msg) return OK(msg)
} else {
return Failed(100, "LOAD_FILE_ERROR", err.Error())
} }
return Failed(100)
} }
func (bot *CQBot) CQGetForwardMessage(resId string) MSG { func (bot *CQBot) CQGetForwardMessage(resId string) MSG {
m := bot.Client.GetForwardMessage(resId) m := bot.Client.GetForwardMessage(resId)
if m == nil { if m == nil {
return Failed(100) return Failed(100, "MSG_NOT_FOUND", "消息不存在")
} }
r := make([]MSG, 0) r := make([]MSG, 0)
for _, n := range m.Nodes { for _, n := range m.Nodes {
@ -721,7 +722,7 @@ func (bot *CQBot) CQGetForwardMessage(resId string) MSG {
func (bot *CQBot) CQGetMessage(messageId int32) MSG { func (bot *CQBot) CQGetMessage(messageId int32) MSG {
msg := bot.GetMessage(messageId) msg := bot.GetMessage(messageId)
if msg == nil { if msg == nil {
return Failed(100) return Failed(100, "MSG_NOT_FOUND", "消息不存在")
} }
sender := msg["sender"].(message.Sender) sender := msg["sender"].(message.Sender)
gid, isGroup := msg["group"] gid, isGroup := msg["group"]
@ -749,7 +750,7 @@ func (bot *CQBot) CQGetGroupSystemMessages() MSG {
msg, err := bot.Client.GetGroupSystemMessages() msg, err := bot.Client.GetGroupSystemMessages()
if err != nil { if err != nil {
log.Warnf("获取群系统消息失败: %v", err) log.Warnf("获取群系统消息失败: %v", err)
return Failed(100) return Failed(100, "SYSTEM_MSG_API_ERROR", err.Error())
} }
return OK(msg) return OK(msg)
} }
@ -766,12 +767,12 @@ func (bot *CQBot) CQOcrImage(imageId string) MSG {
img, err := bot.makeImageElem(map[string]string{"file": imageId}, true) img, err := bot.makeImageElem(map[string]string{"file": imageId}, true)
if err != nil { if err != nil {
log.Warnf("load image error: %v", err) log.Warnf("load image error: %v", err)
return Failed(100) return Failed(100, "LOAD_FILE_ERROR", err.Error())
} }
rsp, err := bot.Client.ImageOcr(img) rsp, err := bot.Client.ImageOcr(img)
if err != nil { if err != nil {
log.Warnf("ocr image error: %v", err) log.Warnf("ocr image error: %v", err)
return Failed(100) return Failed(100, "OCR_API_ERROR", err.Error())
} }
return OK(rsp) return OK(rsp)
} }
@ -786,12 +787,12 @@ func (bot *CQBot) CQSetGroupPortrait(groupId int64, file, cache string) MSG {
img, err := global.FindFile(file, cache, global.IMAGE_PATH) img, err := global.FindFile(file, cache, global.IMAGE_PATH)
if err != nil { if err != nil {
log.Warnf("set group portrait error: %v", err) log.Warnf("set group portrait error: %v", err)
return Failed(100) return Failed(100, "LOAD_FILE_ERROR", err.Error())
} }
g.UpdateGroupHeadPortrait(img) g.UpdateGroupHeadPortrait(img)
return OK(nil) return OK(nil)
} }
return Failed(100) return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
} }
// https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#get_status-%E8%8E%B7%E5%8F%96%E8%BF%90%E8%A1%8C%E7%8A%B6%E6%80%81 // https://github.com/howmanybots/onebot/blob/master/v11/specs/api/public.md#get_status-%E8%8E%B7%E5%8F%96%E8%BF%90%E8%A1%8C%E7%8A%B6%E6%80%81
@ -827,6 +828,8 @@ func (bot *CQBot) CQGetVersionInfo() MSG {
return 1 return 1
case client.AndroidWatch: case client.AndroidWatch:
return 2 return 2
case client.MacOS:
return 3
default: default:
return -1 return -1
} }
@ -838,8 +841,16 @@ func OK(data interface{}) MSG {
return MSG{"data": data, "retcode": 0, "status": "ok"} return MSG{"data": data, "retcode": 0, "status": "ok"}
} }
func Failed(code int) MSG { func Failed(code int, msg ...string) MSG {
return MSG{"data": nil, "retcode": code, "status": "failed"} m := ""
w := ""
if len(msg) > 0 {
m = msg[0]
}
if len(msg) > 1 {
w = msg[1]
}
return MSG{"data": nil, "retcode": code, "msg": m, "wording": w, "status": "failed"}
} }
func convertGroupMemberInfo(groupId int64, m *client.GroupMemberInfo) MSG { func convertGroupMemberInfo(groupId int64, m *client.GroupMemberInfo) MSG {

View File

@ -1,6 +1,7 @@
package coolq package coolq
import ( import (
"bufio"
"bytes" "bytes"
"crypto/md5" "crypto/md5"
"encoding/base64" "encoding/base64"
@ -9,9 +10,9 @@ import (
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"math"
"net/url" "net/url"
"path" "path"
"regexp"
"runtime" "runtime"
"strconv" "strconv"
"strings" "strings"
@ -23,9 +24,11 @@ import (
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
) )
/*
var matchReg = regexp.MustCompile(`\[CQ:\w+?.*?]`) var matchReg = regexp.MustCompile(`\[CQ:\w+?.*?]`)
var typeReg = regexp.MustCompile(`\[CQ:(\w+)`) var typeReg = regexp.MustCompile(`\[CQ:(\w+)`)
var paramReg = regexp.MustCompile(`,([\w\-.]+?)=([^,\]]+)`) var paramReg = regexp.MustCompile(`,([\w\-.]+?)=([^,\]]+)`)
*/
var IgnoreInvalidCQCode = false var IgnoreInvalidCQCode = false
@ -315,30 +318,70 @@ func ToStringMessage(e []message.IMessageElement, code int64, raw ...bool) (r st
return return
} }
func (bot *CQBot) ConvertStringMessage(m string, group bool) (r []message.IMessageElement) { func (bot *CQBot) ConvertStringMessage(msg string, group bool) (r []message.IMessageElement) {
i := matchReg.FindAllStringSubmatchIndex(m, -1) index := 0
si := 0 stat := 0
for _, idx := range i { rMsg := []rune(msg)
if idx[0] > si { var tempText, cqCode []rune
text := m[si:idx[0]] hasNext := func() bool {
r = append(r, message.NewText(CQCodeUnescapeText(text))) return index < len(rMsg)
}
next := func() rune {
r := rMsg[index]
index++
return r
}
move := func(steps int) {
index += steps
}
peekN := func(count int) string {
lastIdx := int(math.Min(float64(index+count), float64(len(rMsg))))
return string(rMsg[index:lastIdx])
}
isCQCodeBegin := func(r rune) bool {
return r == '[' && peekN(3) == "CQ:"
}
saveTempText := func() {
if len(tempText) != 0 {
r = append(r, message.NewText(CQCodeUnescapeValue(string(tempText))))
} }
code := m[idx[0]:idx[1]] tempText = []rune{}
si = idx[1] cqCode = []rune{}
t := typeReg.FindAllStringSubmatch(code, -1)[0][1] }
ps := paramReg.FindAllStringSubmatch(code, -1) saveCQCode := func() {
d := make(map[string]string) defer func() {
for _, p := range ps { cqCode = []rune{}
d[p[1]] = CQCodeUnescapeValue(p[2]) tempText = []rune{}
}()
reader := strings.NewReader(string(cqCode))
buf := bufio.NewReader(reader)
t, _ := buf.ReadString(',')
t = t[0 : len(t)-1]
params := make(map[string]string)
for buf.Buffered() > 0 {
p, _ := buf.ReadString(',')
if strings.HasSuffix(p, ",") {
p = p[0 : len(p)-1]
}
p = strings.TrimSpace(p)
if p == "" {
continue
}
data := strings.SplitN(p, "=", 2)
if len(data) == 2 {
params[data[0]] = data[1]
} else {
params[p] = ""
}
} }
if t == "reply" { if t == "reply" { // reply 特殊处理
if len(r) > 0 { if len(r) > 0 {
if _, ok := r[0].(*message.ReplyElement); ok { if _, ok := r[0].(*message.ReplyElement); ok {
log.Warnf("警告: 一条信息只能包含一个 Reply 元素.") log.Warnf("警告: 一条信息只能包含一个 Reply 元素.")
continue return
} }
} }
mid, err := strconv.Atoi(d["id"]) mid, err := strconv.Atoi(params["id"])
if err == nil { if err == nil {
org := bot.GetMessage(int32(mid)) org := bot.GetMessage(int32(mid))
if org != nil { if org != nil {
@ -350,19 +393,20 @@ func (bot *CQBot) ConvertStringMessage(m string, group bool) (r []message.IMessa
Elements: bot.ConvertStringMessage(org["message"].(string), group), Elements: bot.ConvertStringMessage(org["message"].(string), group),
}, },
}, r...) }, r...)
continue return
} }
} }
} }
elem, err := bot.ToElement(t, d, group) elem, err := bot.ToElement(t, params, group)
if err != nil { if err != nil {
org := "[" + string(cqCode) + "]"
if !IgnoreInvalidCQCode { if !IgnoreInvalidCQCode {
log.Warnf("转换CQ码 %v 到MiraiGo Element时出现错误: %v 将原样发送.", code, err) log.Warnf("转换CQ码 %v 时出现错误: %v 将原样发送.", org, err)
r = append(r, message.NewText(code)) r = append(r, message.NewText(org))
} else { } else {
log.Warnf("转换CQ码 %v 到MiraiGo Element时出现错误: %v 将忽略.", code, err) log.Warnf("转换CQ码 %v 时出现错误: %v 将忽略.", org, err)
} }
continue return
} }
switch i := elem.(type) { switch i := elem.(type) {
case message.IMessageElement: case message.IMessageElement:
@ -371,9 +415,32 @@ func (bot *CQBot) ConvertStringMessage(m string, group bool) (r []message.IMessa
r = append(r, i...) r = append(r, i...)
} }
} }
if si != len(m) { for hasNext() {
r = append(r, message.NewText(CQCodeUnescapeText(m[si:]))) ch := next()
switch stat {
case 0:
if isCQCodeBegin(ch) {
saveTempText()
tempText = append(tempText, []rune("[CQ:")...)
move(3)
stat = 1
} else {
tempText = append(tempText, ch)
}
case 1:
if isCQCodeBegin(ch) {
move(-1)
stat = 0
} else if ch == ']' {
saveCQCode()
stat = 0
} else {
cqCode = append(cqCode, ch)
tempText = append(tempText, ch)
}
}
} }
saveTempText()
return return
} }
@ -630,14 +697,12 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (m interf
case "xml": case "xml":
resId := d["resid"] resId := d["resid"]
template := CQCodeEscapeValue(d["data"]) template := CQCodeEscapeValue(d["data"])
//println(template)
i, _ := strconv.ParseInt(resId, 10, 64) i, _ := strconv.ParseInt(resId, 10, 64)
msg := message.NewRichXml(template, i) msg := message.NewRichXml(template, i)
return msg, nil return msg, nil
case "json": case "json":
resId := d["resid"] resId := d["resid"]
i, _ := strconv.ParseInt(resId, 10, 64) i, _ := strconv.ParseInt(resId, 10, 64)
log.Warnf("json msg=%s", d["data"])
if i == 0 { if i == 0 {
//默认情况下走小程序通道 //默认情况下走小程序通道
msg := message.NewLightApp(CQCodeUnescapeValue(d["data"])) msg := message.NewLightApp(CQCodeUnescapeValue(d["data"]))

2
go.mod
View File

@ -3,7 +3,7 @@ module github.com/Mrs4s/go-cqhttp
go 1.15 go 1.15
require ( require (
github.com/Mrs4s/MiraiGo v0.0.0-20201126173608-8b500107c54d github.com/Mrs4s/MiraiGo v0.0.0-20201202140458-0eb4eb738d31
github.com/dustin/go-humanize v1.0.0 github.com/dustin/go-humanize v1.0.0
github.com/getlantern/go-update v0.0.0-20190510022740-79c495ab728c github.com/getlantern/go-update v0.0.0-20190510022740-79c495ab728c
github.com/getlantern/golog v0.0.0-20201105130739-9586b8bde3a9 // indirect github.com/getlantern/golog v0.0.0-20201105130739-9586b8bde3a9 // indirect

4
go.sum
View File

@ -1,7 +1,7 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/Mrs4s/MiraiGo v0.0.0-20201126173608-8b500107c54d h1:+oGHcMd+OTR/zmhlaKUI9TjjWHZJaUBQi4I3+HP7faU= github.com/Mrs4s/MiraiGo v0.0.0-20201202140458-0eb4eb738d31 h1:jClElKWovoOzDYmVd16UQc8638d0FvyKCtVj7qF+ej4=
github.com/Mrs4s/MiraiGo v0.0.0-20201126173608-8b500107c54d/go.mod h1:J1zaJWyeX7hQIPpOobqb8opxTNPbguotudPPrHJMoDM= github.com/Mrs4s/MiraiGo v0.0.0-20201202140458-0eb4eb738d31/go.mod h1:J1zaJWyeX7hQIPpOobqb8opxTNPbguotudPPrHJMoDM=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=

View File

@ -112,6 +112,7 @@ func (s *webServer) Dologin() {
cli := s.Cli cli := s.Cli
cli.AllowSlider = true cli.AllowSlider = true
rsp, err := cli.Login() rsp, err := cli.Login()
count := 0
for { for {
global.Check(err) global.Check(err)
var text string var text string
@ -132,7 +133,7 @@ func (s *webServer) Dologin() {
_ = ioutil.WriteFile("captcha.jpg", rsp.CaptchaImage, 0644) _ = ioutil.WriteFile("captcha.jpg", rsp.CaptchaImage, 0644)
img, _, _ := image.Decode(bytes.NewReader(rsp.CaptchaImage)) img, _, _ := image.Decode(bytes.NewReader(rsp.CaptchaImage))
fmt.Println(asciiart.New("image", img).Art) fmt.Println(asciiart.New("image", img).Art)
if conf.WebUi.WebInput { if conf.WebUi != nil && conf.WebUi.WebInput {
log.Warnf("请输入验证码 (captcha.jpg) (http://%s:%d/admin/do_web_write 输入)", conf.WebUi.Host, conf.WebUi.WebUiPort) log.Warnf("请输入验证码 (captcha.jpg) (http://%s:%d/admin/do_web_write 输入)", conf.WebUi.Host, conf.WebUi.WebUiPort)
text = <-WebInput text = <-WebInput
} else { } else {
@ -178,7 +179,7 @@ func (s *webServer) Dologin() {
return return
case client.UnsafeDeviceError: case client.UnsafeDeviceError:
log.Warnf("账号已开启设备锁,请前往 -> %v <- 验证并重启Bot.", rsp.VerifyUrl) log.Warnf("账号已开启设备锁,请前往 -> %v <- 验证并重启Bot.", rsp.VerifyUrl)
if conf.WebUi.WebInput { if conf.WebUi != nil && conf.WebUi.WebInput {
log.Infof(" (http://%s:%d/admin/do_web_write 确认后继续)....", conf.WebUi.Host, conf.WebUi.WebUiPort) log.Infof(" (http://%s:%d/admin/do_web_write 确认后继续)....", conf.WebUi.Host, conf.WebUi.WebUiPort)
text = <-WebInput text = <-WebInput
} else { } else {
@ -193,6 +194,12 @@ func (s *webServer) Dologin() {
if strings.Contains(msg, "版本") { if strings.Contains(msg, "版本") {
msg = "密码错误或账号被冻结" msg = "密码错误或账号被冻结"
} }
if strings.Contains(msg, "上网环境") && count < 5 {
cli.Disconnect()
rsp, err = cli.Login()
count++
continue
}
log.Warnf("登录失败: %v", msg) log.Warnf("登录失败: %v", msg)
log.Infof("按 Enter 继续....") log.Infof("按 Enter 继续....")
readLine() readLine()