mirror of
https://github.com/Mrs4s/go-cqhttp.git
synced 2025-06-30 20:03:24 +00:00
Compare commits
17 Commits
Author | SHA1 | Date | |
---|---|---|---|
0b02178402 | |||
3819f2c2da | |||
b297aa2e13 | |||
c8160550ec | |||
44b26b70a3 | |||
97f7de85a2 | |||
ae58d26047 | |||
47cb3a5235 | |||
4941f0c3f8 | |||
bc47267c3c | |||
8449770b6d | |||
a38c74a767 | |||
4ab1812640 | |||
c87836355f | |||
8524fbf1ce | |||
92fb69beef | |||
dd03efc9c8 |
20
.github/ISSUE_TEMPLATE/bug--.md
vendored
Normal file
20
.github/ISSUE_TEMPLATE/bug--.md
vendored
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
---
|
||||||
|
name: Bug汇报
|
||||||
|
about: Create a report to help us improve
|
||||||
|
title: ''
|
||||||
|
labels: ''
|
||||||
|
assignees: ''
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**环境信息**
|
||||||
|
请根据实际使用环境修改以下信息
|
||||||
|
go-cqhttp版本: v0.9.10
|
||||||
|
运行环境: windows_amd64
|
||||||
|
连接方式: 反向WS
|
||||||
|
|
||||||
|
**bug内容**
|
||||||
|
请在这里详细描述bug的内容
|
||||||
|
|
||||||
|
**复现方法**
|
||||||
|
请在这里分步骤的描述如何复现这个bug
|
@ -439,7 +439,7 @@ func (bot *CQBot) CQGetForwardMessage(resId string) MSG {
|
|||||||
}
|
}
|
||||||
var r []MSG
|
var r []MSG
|
||||||
for _, n := range m.Nodes {
|
for _, n := range m.Nodes {
|
||||||
checkImage(n.Message)
|
checkMedia(n.Message)
|
||||||
r = append(r, MSG{
|
r = append(r, MSG{
|
||||||
"sender": MSG{
|
"sender": MSG{
|
||||||
"user_id": n.SenderId,
|
"user_id": n.SenderId,
|
||||||
@ -477,7 +477,7 @@ func (bot *CQBot) CQCanSendImage() MSG {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (bot *CQBot) CQCanSendRecord() MSG {
|
func (bot *CQBot) CQCanSendRecord() MSG {
|
||||||
return OK(MSG{"yes": false})
|
return OK(MSG{"yes": true})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (bot *CQBot) CQGetStatus() MSG {
|
func (bot *CQBot) CQGetStatus() MSG {
|
||||||
|
30
coolq/bot.go
30
coolq/bot.go
@ -14,6 +14,7 @@ import (
|
|||||||
"hash/crc32"
|
"hash/crc32"
|
||||||
"path"
|
"path"
|
||||||
"sync"
|
"sync"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type CQBot struct {
|
type CQBot struct {
|
||||||
@ -24,6 +25,7 @@ type CQBot struct {
|
|||||||
friendReqCache sync.Map
|
friendReqCache sync.Map
|
||||||
invitedReqCache sync.Map
|
invitedReqCache sync.Map
|
||||||
joinReqCache sync.Map
|
joinReqCache sync.Map
|
||||||
|
tempMsgCache sync.Map
|
||||||
}
|
}
|
||||||
|
|
||||||
type MSG map[string]interface{}
|
type MSG map[string]interface{}
|
||||||
@ -58,6 +60,7 @@ func NewQQBot(cli *client.QQClient, conf *global.JsonConfig) *CQBot {
|
|||||||
bot.Client.OnGroupMemberLeaved(bot.memberLeaveEvent)
|
bot.Client.OnGroupMemberLeaved(bot.memberLeaveEvent)
|
||||||
bot.Client.OnGroupMemberPermissionChanged(bot.memberPermissionChangedEvent)
|
bot.Client.OnGroupMemberPermissionChanged(bot.memberPermissionChangedEvent)
|
||||||
bot.Client.OnNewFriendRequest(bot.friendRequestEvent)
|
bot.Client.OnNewFriendRequest(bot.friendRequestEvent)
|
||||||
|
bot.Client.OnNewFriendAdded(bot.friendAddedEvent)
|
||||||
bot.Client.OnGroupInvited(bot.groupInvitedEvent)
|
bot.Client.OnGroupInvited(bot.groupInvitedEvent)
|
||||||
bot.Client.OnUserWantJoinGroup(bot.groupJoinReqEvent)
|
bot.Client.OnUserWantJoinGroup(bot.groupJoinReqEvent)
|
||||||
return bot
|
return bot
|
||||||
@ -100,7 +103,7 @@ func (bot *CQBot) SendGroupMessage(groupId int64, m *message.SendingMessage) int
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if i, ok := elem.(*message.VoiceElement); ok {
|
if i, ok := elem.(*message.VoiceElement); ok {
|
||||||
gv, err := bot.Client.UploadGroupPtt(groupId, i.Data, int32(len(i.Data)))
|
gv, err := bot.Client.UploadGroupPtt(groupId, i.Data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Warnf("警告: 群 %v 消息语音上传失败: %v", groupId, err)
|
log.Warnf("警告: 群 %v 消息语音上传失败: %v", groupId, err)
|
||||||
continue
|
continue
|
||||||
@ -121,7 +124,7 @@ func (bot *CQBot) SendPrivateMessage(target int64, m *message.SendingMessage) in
|
|||||||
if i, ok := elem.(*message.ImageElement); ok {
|
if i, ok := elem.(*message.ImageElement); ok {
|
||||||
fm, err := bot.Client.UploadPrivateImage(target, i.Data)
|
fm, err := bot.Client.UploadPrivateImage(target, i.Data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Warnf("警告: 好友 %v 消息图片上传失败.", target)
|
log.Warnf("警告: 私聊 %v 消息图片上传失败.", target)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
newElem = append(newElem, fm)
|
newElem = append(newElem, fm)
|
||||||
@ -130,8 +133,17 @@ func (bot *CQBot) SendPrivateMessage(target int64, m *message.SendingMessage) in
|
|||||||
newElem = append(newElem, elem)
|
newElem = append(newElem, elem)
|
||||||
}
|
}
|
||||||
m.Elements = newElem
|
m.Elements = newElem
|
||||||
ret := bot.Client.SendPrivateMessage(target, m)
|
var id int32
|
||||||
return ToGlobalId(target, ret.Id)
|
if bot.Client.FindFriend(target) != nil {
|
||||||
|
id = bot.Client.SendPrivateMessage(target, m).Id
|
||||||
|
} else {
|
||||||
|
if code, ok := bot.tempMsgCache.Load(target); ok {
|
||||||
|
id = bot.Client.SendTempMessage(code.(int64), target, m).Id
|
||||||
|
} else {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ToGlobalId(target, id)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (bot *CQBot) InsertGroupMessage(m *message.GroupMessage) int32 {
|
func (bot *CQBot) InsertGroupMessage(m *message.GroupMessage) int32 {
|
||||||
@ -173,7 +185,15 @@ func (bot *CQBot) Release() {
|
|||||||
|
|
||||||
func (bot *CQBot) dispatchEventMessage(m MSG) {
|
func (bot *CQBot) dispatchEventMessage(m MSG) {
|
||||||
for _, f := range bot.events {
|
for _, f := range bot.events {
|
||||||
f(m)
|
fn := f
|
||||||
|
go func() {
|
||||||
|
start := time.Now()
|
||||||
|
fn(m)
|
||||||
|
end := time.Now()
|
||||||
|
if end.Sub(start) > time.Second*5 {
|
||||||
|
log.Debugf("警告: 事件处理耗时超过 5 秒 (%v秒), 请检查应用是否有堵塞.", end.Sub(start)/time.Second)
|
||||||
|
}
|
||||||
|
}()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -31,7 +31,7 @@ func ToStringMessage(e []message.IMessageElement, code int64, raw ...bool) (r st
|
|||||||
for _, elem := range e {
|
for _, elem := range e {
|
||||||
switch o := elem.(type) {
|
switch o := elem.(type) {
|
||||||
case *message.TextElement:
|
case *message.TextElement:
|
||||||
r += o.Content
|
r += CQCodeEscapeText(o.Content)
|
||||||
case *message.AtElement:
|
case *message.AtElement:
|
||||||
if o.Target == 0 {
|
if o.Target == 0 {
|
||||||
r += "[CQ:at,qq=all]"
|
r += "[CQ:at,qq=all]"
|
||||||
@ -45,7 +45,11 @@ func ToStringMessage(e []message.IMessageElement, code int64, raw ...bool) (r st
|
|||||||
case *message.FaceElement:
|
case *message.FaceElement:
|
||||||
r += fmt.Sprintf(`[CQ:face,id=%d]`, o.Index)
|
r += fmt.Sprintf(`[CQ:face,id=%d]`, o.Index)
|
||||||
case *message.VoiceElement:
|
case *message.VoiceElement:
|
||||||
r += fmt.Sprintf(`[CQ:record,file=%s]`, o.Name)
|
if ur {
|
||||||
|
r += fmt.Sprintf(`[CQ:record,file=%s]`, o.Name)
|
||||||
|
} else {
|
||||||
|
r += fmt.Sprintf(`[CQ:record,file=%s,url=%s]`, o.Name, o.Url)
|
||||||
|
}
|
||||||
case *message.ImageElement:
|
case *message.ImageElement:
|
||||||
if ur {
|
if ur {
|
||||||
r += fmt.Sprintf(`[CQ:image,file=%s]`, o.Filename)
|
r += fmt.Sprintf(`[CQ:image,file=%s]`, o.Filename)
|
||||||
@ -63,7 +67,7 @@ func (bot *CQBot) ConvertStringMessage(m string, group bool) (r []message.IMessa
|
|||||||
for _, idx := range i {
|
for _, idx := range i {
|
||||||
if idx[0] > si {
|
if idx[0] > si {
|
||||||
text := m[si:idx[0]]
|
text := m[si:idx[0]]
|
||||||
r = append(r, message.NewText(text))
|
r = append(r, message.NewText(CQCodeUnescapeText(text)))
|
||||||
}
|
}
|
||||||
code := m[idx[0]:idx[1]]
|
code := m[idx[0]:idx[1]]
|
||||||
si = idx[1]
|
si = idx[1]
|
||||||
@ -105,7 +109,7 @@ func (bot *CQBot) ConvertStringMessage(m string, group bool) (r []message.IMessa
|
|||||||
r = append(r, elem)
|
r = append(r, elem)
|
||||||
}
|
}
|
||||||
if si != len(m) {
|
if si != len(m) {
|
||||||
r = append(r, message.NewText(m[si:]))
|
r = append(r, message.NewText(CQCodeUnescapeText(m[si:])))
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -200,6 +204,9 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (message.
|
|||||||
if !global.PathExists(rawPath) && global.PathExists(rawPath+".cqimg") {
|
if !global.PathExists(rawPath) && global.PathExists(rawPath+".cqimg") {
|
||||||
rawPath += ".cqimg"
|
rawPath += ".cqimg"
|
||||||
}
|
}
|
||||||
|
if !global.PathExists(rawPath) && d["url"] != "" {
|
||||||
|
return bot.ToElement(t, map[string]string{"file": d["url"]}, group)
|
||||||
|
}
|
||||||
if global.PathExists(rawPath) {
|
if global.PathExists(rawPath) {
|
||||||
b, err := ioutil.ReadFile(rawPath)
|
b, err := ioutil.ReadFile(rawPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -283,6 +290,13 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (message.
|
|||||||
}
|
}
|
||||||
data = b
|
data = b
|
||||||
}
|
}
|
||||||
|
if global.PathExists(path.Join(global.VOICE_PATH, f)) {
|
||||||
|
b, err := ioutil.ReadFile(path.Join(global.VOICE_PATH, f))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
data = b
|
||||||
|
}
|
||||||
if !global.IsAMR(data) {
|
if !global.IsAMR(data) {
|
||||||
return nil, errors.New("unsupported voice file format (please use AMR file for now)")
|
return nil, errors.New("unsupported voice file format (please use AMR file for now)")
|
||||||
}
|
}
|
||||||
@ -306,3 +320,19 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (message.
|
|||||||
return nil, errors.New("unsupported cq code: " + t)
|
return nil, errors.New("unsupported cq code: " + t)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func CQCodeEscapeText(raw string) string {
|
||||||
|
ret := raw
|
||||||
|
ret = strings.ReplaceAll(ret, "[", "[")
|
||||||
|
ret = strings.ReplaceAll(ret, "]", "]")
|
||||||
|
ret = strings.ReplaceAll(ret, "&", "&")
|
||||||
|
return ret
|
||||||
|
}
|
||||||
|
|
||||||
|
func CQCodeUnescapeText(content string) string {
|
||||||
|
ret := content
|
||||||
|
ret = strings.ReplaceAll(ret, "[", "[")
|
||||||
|
ret = strings.ReplaceAll(ret, "]", "]")
|
||||||
|
ret = strings.ReplaceAll(ret, "&", "&")
|
||||||
|
return ret
|
||||||
|
}
|
||||||
|
@ -10,11 +10,12 @@ import (
|
|||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"path"
|
"path"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (bot *CQBot) privateMessageEvent(c *client.QQClient, m *message.PrivateMessage) {
|
func (bot *CQBot) privateMessageEvent(c *client.QQClient, m *message.PrivateMessage) {
|
||||||
checkImage(m.Elements)
|
checkMedia(m.Elements)
|
||||||
cqm := ToStringMessage(m.Elements, 0, true)
|
cqm := ToStringMessage(m.Elements, 0, true)
|
||||||
log.Infof("收到好友 %v(%v) 的消息: %v", m.Sender.DisplayName(), m.Sender.Uin, cqm)
|
log.Infof("收到好友 %v(%v) 的消息: %v", m.Sender.DisplayName(), m.Sender.Uin, cqm)
|
||||||
fm := MSG{
|
fm := MSG{
|
||||||
@ -39,7 +40,7 @@ func (bot *CQBot) privateMessageEvent(c *client.QQClient, m *message.PrivateMess
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (bot *CQBot) groupMessageEvent(c *client.QQClient, m *message.GroupMessage) {
|
func (bot *CQBot) groupMessageEvent(c *client.QQClient, m *message.GroupMessage) {
|
||||||
checkImage(m.Elements)
|
checkMedia(m.Elements)
|
||||||
for _, elem := range m.Elements {
|
for _, elem := range m.Elements {
|
||||||
if file, ok := elem.(*message.GroupFileElement); ok {
|
if file, ok := elem.(*message.GroupFileElement); ok {
|
||||||
log.Infof("群 %v(%v) 内 %v(%v) 上传了文件: %v", m.GroupName, m.GroupCode, m.Sender.DisplayName(), m.Sender.Uin, file.Name)
|
log.Infof("群 %v(%v) 内 %v(%v) 上传了文件: %v", m.GroupName, m.GroupCode, m.Sender.DisplayName(), m.Sender.Uin, file.Name)
|
||||||
@ -117,8 +118,9 @@ func (bot *CQBot) groupMessageEvent(c *client.QQClient, m *message.GroupMessage)
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (bot *CQBot) tempMessageEvent(c *client.QQClient, m *message.TempMessage) {
|
func (bot *CQBot) tempMessageEvent(c *client.QQClient, m *message.TempMessage) {
|
||||||
checkImage(m.Elements)
|
checkMedia(m.Elements)
|
||||||
cqm := ToStringMessage(m.Elements, 0, true)
|
cqm := ToStringMessage(m.Elements, 0, true)
|
||||||
|
bot.tempMsgCache.Store(m.Sender.Uin, m.GroupCode)
|
||||||
log.Infof("收到来自群 %v(%v) 内 %v(%v) 的临时会话消息: %v", m.GroupName, m.GroupCode, m.Sender.DisplayName(), m.Sender.Uin, cqm)
|
log.Infof("收到来自群 %v(%v) 内 %v(%v) 的临时会话消息: %v", m.GroupName, m.GroupCode, m.Sender.DisplayName(), m.Sender.Uin, cqm)
|
||||||
tm := MSG{
|
tm := MSG{
|
||||||
"post_type": "message",
|
"post_type": "message",
|
||||||
@ -260,6 +262,18 @@ func (bot *CQBot) friendRequestEvent(c *client.QQClient, e *client.NewFriendRequ
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (bot *CQBot) friendAddedEvent(c *client.QQClient, e *client.NewFriendEvent) {
|
||||||
|
log.Infof("添加了新好友: %v(%v)", e.Friend.Nickname, e.Friend.Uin)
|
||||||
|
bot.tempMsgCache.Delete(e.Friend.Uin)
|
||||||
|
bot.dispatchEventMessage(MSG{
|
||||||
|
"post_type": "notice",
|
||||||
|
"notice_type": "friend_add",
|
||||||
|
"self_id": c.Uin,
|
||||||
|
"user_id": e.Friend.Uin,
|
||||||
|
"time": time.Now().Unix(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func (bot *CQBot) groupInvitedEvent(c *client.QQClient, e *client.GroupInvitedRequest) {
|
func (bot *CQBot) groupInvitedEvent(c *client.QQClient, e *client.GroupInvitedRequest) {
|
||||||
log.Infof("收到来自群 %v(%v) 内用户 %v(%v) 的加群邀请.", e.GroupName, e.GroupCode, e.InvitorNick, e.InvitorUin)
|
log.Infof("收到来自群 %v(%v) 内用户 %v(%v) 的加群邀请.", e.GroupName, e.GroupCode, e.InvitorNick, e.InvitorUin)
|
||||||
flag := strconv.FormatInt(e.RequestId, 10)
|
flag := strconv.FormatInt(e.RequestId, 10)
|
||||||
@ -278,7 +292,7 @@ func (bot *CQBot) groupInvitedEvent(c *client.QQClient, e *client.GroupInvitedRe
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (bot *CQBot) groupJoinReqEvent(c *client.QQClient, e *client.UserJoinGroupRequest) {
|
func (bot *CQBot) groupJoinReqEvent(c *client.QQClient, e *client.UserJoinGroupRequest) {
|
||||||
log.Infof("群 %v(%v) 收到来自用户 %v(%v) 的加群请求.", e.GroupName, e.GroupName, e.RequesterNick, e.RequesterUin)
|
log.Infof("群 %v(%v) 收到来自用户 %v(%v) 的加群请求.", e.GroupName, e.GroupCode, e.RequesterNick, e.RequesterUin)
|
||||||
flag := strconv.FormatInt(e.RequestId, 10)
|
flag := strconv.FormatInt(e.RequestId, 10)
|
||||||
bot.joinReqCache.Store(flag, e)
|
bot.joinReqCache.Store(flag, e)
|
||||||
bot.dispatchEventMessage(MSG{
|
bot.dispatchEventMessage(MSG{
|
||||||
@ -333,9 +347,10 @@ func (bot *CQBot) groupDecrease(groupCode, userUin int64, operator *client.Group
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func checkImage(e []message.IMessageElement) {
|
func checkMedia(e []message.IMessageElement) {
|
||||||
for _, elem := range e {
|
for _, elem := range e {
|
||||||
if i, ok := elem.(*message.ImageElement); ok {
|
switch i := elem.(type) {
|
||||||
|
case *message.ImageElement:
|
||||||
filename := hex.EncodeToString(i.Md5) + ".image"
|
filename := hex.EncodeToString(i.Md5) + ".image"
|
||||||
if !global.PathExists(path.Join(global.IMAGE_PATH, filename)) {
|
if !global.PathExists(path.Join(global.IMAGE_PATH, filename)) {
|
||||||
_ = ioutil.WriteFile(path.Join(global.IMAGE_PATH, filename), binary.NewWriterF(func(w *binary.Writer) {
|
_ = ioutil.WriteFile(path.Join(global.IMAGE_PATH, filename), binary.NewWriterF(func(w *binary.Writer) {
|
||||||
@ -346,6 +361,17 @@ func checkImage(e []message.IMessageElement) {
|
|||||||
}), 0777)
|
}), 0777)
|
||||||
}
|
}
|
||||||
i.Filename = filename
|
i.Filename = filename
|
||||||
|
case *message.VoiceElement:
|
||||||
|
i.Name = strings.ReplaceAll(i.Name, "{", "")
|
||||||
|
i.Name = strings.ReplaceAll(i.Name, "}", "")
|
||||||
|
if !global.PathExists(path.Join(global.VOICE_PATH, i.Name)) {
|
||||||
|
b, err := global.GetBytes(i.Url)
|
||||||
|
if err != nil {
|
||||||
|
log.Warnf("语音文件 %v 下载失败: %v", i.Name, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
_ = ioutil.WriteFile(path.Join(global.VOICE_PATH, i.Name), b, 0777)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -18,6 +18,8 @@ go-cqhttp 支持导入CQHTTP的配置文件, 具体步骤为:
|
|||||||
{
|
{
|
||||||
"uin": 0,
|
"uin": 0,
|
||||||
"password": "",
|
"password": "",
|
||||||
|
"encrypt_password": false,
|
||||||
|
"password_encrypted": "",
|
||||||
"enable_db": true,
|
"enable_db": true,
|
||||||
"access_token": "",
|
"access_token": "",
|
||||||
"relogin": false,
|
"relogin": false,
|
||||||
@ -26,7 +28,7 @@ go-cqhttp 支持导入CQHTTP的配置文件, 具体步骤为:
|
|||||||
"enabled": true,
|
"enabled": true,
|
||||||
"host": "0.0.0.0",
|
"host": "0.0.0.0",
|
||||||
"port": 5700,
|
"port": 5700,
|
||||||
"post_urls": []
|
"post_urls": {"url:port": "secret"}
|
||||||
},
|
},
|
||||||
"ws_config": {
|
"ws_config": {
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
@ -49,6 +51,8 @@ go-cqhttp 支持导入CQHTTP的配置文件, 具体步骤为:
|
|||||||
| ------------------ | -------- | ------------------------------------------------------------------- |
|
| ------------------ | -------- | ------------------------------------------------------------------- |
|
||||||
| uin | int64 | 登录用QQ号 |
|
| uin | int64 | 登录用QQ号 |
|
||||||
| password | string | 登录用密码 |
|
| password | string | 登录用密码 |
|
||||||
|
| encrypt_password | bool | 是否对密码进行加密. |
|
||||||
|
| password_encrypted | string | 加密后的密码(请勿修改) |
|
||||||
| enable_db | bool | 是否开启内置数据库, 关闭后将无法使用 **回复/撤回** 等上下文相关接口 |
|
| enable_db | bool | 是否开启内置数据库, 关闭后将无法使用 **回复/撤回** 等上下文相关接口 |
|
||||||
| access_token | string | 同CQHTTP的 `access_token` 用于身份验证 |
|
| access_token | string | 同CQHTTP的 `access_token` 用于身份验证 |
|
||||||
| relogin | bool | 是否自动重新登录 |
|
| relogin | bool | 是否自动重新登录 |
|
||||||
@ -57,4 +61,6 @@ go-cqhttp 支持导入CQHTTP的配置文件, 具体步骤为:
|
|||||||
| ws_config | object | Websocket API 配置 |
|
| ws_config | object | Websocket API 配置 |
|
||||||
| ws_reverse_servers | object[] | 反向 Websocket API 配置 |
|
| ws_reverse_servers | object[] | 反向 Websocket API 配置 |
|
||||||
|
|
||||||
|
> 注: 开启密码加密后程序将在每次启动时要求输入解密密钥, 密钥错误会导致登录时提示密码错误.
|
||||||
|
> 解密后密码将储存在内存中,用于自动重连等功能. 所以此加密并不能防止内存读取.
|
||||||
|
> 解密密钥在使用完成后并不会留存在内存中, 所以可用相对简单的字符串作为密钥
|
||||||
|
@ -6,16 +6,18 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type JsonConfig struct {
|
type JsonConfig struct {
|
||||||
Uin int64 `json:"uin"`
|
Uin int64 `json:"uin"`
|
||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
EnableDB bool `json:"enable_db"`
|
EncryptPassword bool `json:"encrypt_password"`
|
||||||
AccessToken string `json:"access_token"`
|
PasswordEncrypted string `json:"password_encrypted"`
|
||||||
ReLogin bool `json:"relogin"`
|
EnableDB bool `json:"enable_db"`
|
||||||
ReLoginDelay int `json:"relogin_delay"`
|
AccessToken string `json:"access_token"`
|
||||||
HttpConfig *GoCQHttpConfig `json:"http_config"`
|
ReLogin bool `json:"relogin"`
|
||||||
WSConfig *GoCQWebsocketConfig `json:"ws_config"`
|
ReLoginDelay int `json:"relogin_delay"`
|
||||||
ReverseServers []*GoCQReverseWebsocketConfig `json:"ws_reverse_servers"`
|
HttpConfig *GoCQHttpConfig `json:"http_config"`
|
||||||
Debug bool `json:"debug"`
|
WSConfig *GoCQWebsocketConfig `json:"ws_config"`
|
||||||
|
ReverseServers []*GoCQReverseWebsocketConfig `json:"ws_reverse_servers"`
|
||||||
|
Debug bool `json:"debug"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type CQHttpApiConfig struct {
|
type CQHttpApiConfig struct {
|
||||||
@ -60,7 +62,9 @@ type GoCQReverseWebsocketConfig struct {
|
|||||||
|
|
||||||
func DefaultConfig() *JsonConfig {
|
func DefaultConfig() *JsonConfig {
|
||||||
return &JsonConfig{
|
return &JsonConfig{
|
||||||
EnableDB: true,
|
EnableDB: true,
|
||||||
|
ReLogin: true,
|
||||||
|
ReLoginDelay: 3,
|
||||||
HttpConfig: &GoCQHttpConfig{
|
HttpConfig: &GoCQHttpConfig{
|
||||||
Enabled: true,
|
Enabled: true,
|
||||||
Host: "0.0.0.0",
|
Host: "0.0.0.0",
|
||||||
|
@ -9,6 +9,8 @@ import (
|
|||||||
|
|
||||||
var IMAGE_PATH = path.Join("data", "images")
|
var IMAGE_PATH = path.Join("data", "images")
|
||||||
|
|
||||||
|
var VOICE_PATH = path.Join("data", "voices")
|
||||||
|
|
||||||
func PathExists(path string) bool {
|
func PathExists(path string) bool {
|
||||||
_, err := os.Stat(path)
|
_, err := os.Stat(path)
|
||||||
return err == nil || os.IsExist(err)
|
return err == nil || os.IsExist(err)
|
||||||
|
2
go.mod
2
go.mod
@ -3,7 +3,7 @@ module github.com/Mrs4s/go-cqhttp
|
|||||||
go 1.14
|
go 1.14
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/Mrs4s/MiraiGo v0.0.0-20200808044635-cd20d7d43dbb
|
github.com/Mrs4s/MiraiGo v0.0.0-20200810032556-a425f9d1b98e
|
||||||
github.com/gin-gonic/gin v1.6.3
|
github.com/gin-gonic/gin v1.6.3
|
||||||
github.com/gorilla/websocket v1.4.2
|
github.com/gorilla/websocket v1.4.2
|
||||||
github.com/guonaihong/gout v0.1.1
|
github.com/guonaihong/gout v0.1.1
|
||||||
|
10
go.sum
10
go.sum
@ -1,11 +1,9 @@
|
|||||||
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-20200807030850-ed30f7ad5934 h1:LoNjIsnyEQFGP9IchIQ65yHRCfNKSru3BAOguRepkCM=
|
github.com/Mrs4s/MiraiGo v0.0.0-20200809221224-7a84cfae6795 h1:Bu4k9ZS/IIy9Shwd9lS/C2P/2I8fYUwg1OpRF91hr1w=
|
||||||
github.com/Mrs4s/MiraiGo v0.0.0-20200807030850-ed30f7ad5934/go.mod h1:0je03wji/tSw4bUH4QCF2Z4/EjyNWjSJTyy5tliX6EM=
|
github.com/Mrs4s/MiraiGo v0.0.0-20200809221224-7a84cfae6795/go.mod h1:0je03wji/tSw4bUH4QCF2Z4/EjyNWjSJTyy5tliX6EM=
|
||||||
github.com/Mrs4s/MiraiGo v0.0.0-20200808003732-2a32e623270d h1:K9jHdcO13mLqQB0xm0/ZlY852FoVQJ/WSDwfdmfhDlU=
|
github.com/Mrs4s/MiraiGo v0.0.0-20200810032556-a425f9d1b98e h1:5LYDouOL9ZgTL5PwZuuSlFYSfboRQjnXqRIlhviRcGE=
|
||||||
github.com/Mrs4s/MiraiGo v0.0.0-20200808003732-2a32e623270d/go.mod h1:0je03wji/tSw4bUH4QCF2Z4/EjyNWjSJTyy5tliX6EM=
|
github.com/Mrs4s/MiraiGo v0.0.0-20200810032556-a425f9d1b98e/go.mod h1:0je03wji/tSw4bUH4QCF2Z4/EjyNWjSJTyy5tliX6EM=
|
||||||
github.com/Mrs4s/MiraiGo v0.0.0-20200808044635-cd20d7d43dbb h1:XLe/UreYJRT65GStA3+irRL1Ao0pHZwBtCmTc+4prwA=
|
|
||||||
github.com/Mrs4s/MiraiGo v0.0.0-20200808044635-cd20d7d43dbb/go.mod h1:0je03wji/tSw4bUH4QCF2Z4/EjyNWjSJTyy5tliX6EM=
|
|
||||||
github.com/bwmarrin/snowflake v0.3.0 h1:xm67bEhkKh6ij1790JB83OujPR5CzNe8QuQqAgISZN0=
|
github.com/bwmarrin/snowflake v0.3.0 h1:xm67bEhkKh6ij1790JB83OujPR5CzNe8QuQqAgISZN0=
|
||||||
github.com/bwmarrin/snowflake v0.3.0/go.mod h1:NdZxfVWX+oR6y2K0o6qAYv6gIOP9rjG0/E9WsDpxqwE=
|
github.com/bwmarrin/snowflake v0.3.0/go.mod h1:NdZxfVWX+oR6y2K0o6qAYv6gIOP9rjG0/E9WsDpxqwE=
|
||||||
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=
|
||||||
|
60
main.go
60
main.go
@ -3,8 +3,11 @@ package main
|
|||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"crypto/md5"
|
||||||
|
"encoding/base64"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/Mrs4s/MiraiGo/binary"
|
||||||
"github.com/Mrs4s/MiraiGo/client"
|
"github.com/Mrs4s/MiraiGo/client"
|
||||||
"github.com/Mrs4s/go-cqhttp/coolq"
|
"github.com/Mrs4s/go-cqhttp/coolq"
|
||||||
"github.com/Mrs4s/go-cqhttp/global"
|
"github.com/Mrs4s/go-cqhttp/global"
|
||||||
@ -33,14 +36,16 @@ func init() {
|
|||||||
if err == nil {
|
if err == nil {
|
||||||
log.SetOutput(io.MultiWriter(os.Stderr, w))
|
log.SetOutput(io.MultiWriter(os.Stderr, w))
|
||||||
}
|
}
|
||||||
if !global.PathExists("data") {
|
if !global.PathExists(global.IMAGE_PATH) {
|
||||||
if err := os.Mkdir("data", 0777); err != nil {
|
if err := os.MkdirAll(global.IMAGE_PATH, 0677); err != nil {
|
||||||
log.Fatalf("创建数据文件夹失败: %v", err)
|
|
||||||
}
|
|
||||||
if err := os.Mkdir(path.Join("data", "images"), 0777); err != nil {
|
|
||||||
log.Fatalf("创建图片缓存文件夹失败: %v", err)
|
log.Fatalf("创建图片缓存文件夹失败: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if !global.PathExists(global.VOICE_PATH) {
|
||||||
|
if err := os.MkdirAll(global.VOICE_PATH, 06777); err != nil {
|
||||||
|
log.Fatalf("创建语音缓存文件夹失败: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
if global.PathExists("cqhttp.json") {
|
if global.PathExists("cqhttp.json") {
|
||||||
log.Info("发现 cqhttp.json 将在五秒后尝试导入配置,按 Ctrl+C 取消.")
|
log.Info("发现 cqhttp.json 将在五秒后尝试导入配置,按 Ctrl+C 取消.")
|
||||||
log.Warn("警告: 该操作会删除 cqhttp.json 并覆盖 config.json 文件.")
|
log.Warn("警告: 该操作会删除 cqhttp.json 并覆盖 config.json 文件.")
|
||||||
@ -112,7 +117,7 @@ func main() {
|
|||||||
time.Sleep(time.Second * 5)
|
time.Sleep(time.Second * 5)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if conf.Uin == 0 || conf.Password == "" {
|
if conf.Uin == 0 || (conf.Password == "" && conf.PasswordEncrypted == "") {
|
||||||
log.Warnf("请修改 config.json 以添加账号密码.")
|
log.Warnf("请修改 config.json 以添加账号密码.")
|
||||||
time.Sleep(time.Second * 5)
|
time.Sleep(time.Second * 5)
|
||||||
return
|
return
|
||||||
@ -132,6 +137,24 @@ func main() {
|
|||||||
log.Fatalf("加载设备信息失败: %v", err)
|
log.Fatalf("加载设备信息失败: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if conf.EncryptPassword && conf.PasswordEncrypted == "" {
|
||||||
|
log.Infof("密码加密已启用, 请输入Key对密码进行加密: (Enter 提交)")
|
||||||
|
strKey, _ := console.ReadString('\n')
|
||||||
|
key := md5.Sum([]byte(strKey))
|
||||||
|
if encrypted := EncryptPwd(conf.Password, key[:]); encrypted != "" {
|
||||||
|
conf.Password = ""
|
||||||
|
conf.PasswordEncrypted = encrypted
|
||||||
|
_ = conf.Save("config.json")
|
||||||
|
} else {
|
||||||
|
log.Warnf("加密时出现问题.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if conf.PasswordEncrypted != "" {
|
||||||
|
log.Infof("密码加密已启用, 请输入Key对密码进行解密以继续: (Enter 提交)")
|
||||||
|
strKey, _ := console.ReadString('\n')
|
||||||
|
key := md5.Sum([]byte(strKey))
|
||||||
|
conf.Password = DecryptPwd(conf.PasswordEncrypted, key[:])
|
||||||
|
}
|
||||||
log.Info("Bot将在5秒后登录并开始信息处理, 按 Ctrl+C 取消.")
|
log.Info("Bot将在5秒后登录并开始信息处理, 按 Ctrl+C 取消.")
|
||||||
time.Sleep(time.Second * 5)
|
time.Sleep(time.Second * 5)
|
||||||
log.Info("开始尝试登录并同步消息...")
|
log.Info("开始尝试登录并同步消息...")
|
||||||
@ -210,3 +233,28 @@ func main() {
|
|||||||
<-c
|
<-c
|
||||||
b.Release()
|
b.Release()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func EncryptPwd(pwd string, key []byte) string {
|
||||||
|
tea := binary.NewTeaCipher(key)
|
||||||
|
if tea == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return base64.StdEncoding.EncodeToString(tea.Encrypt([]byte(pwd)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func DecryptPwd(ePwd string, key []byte) string {
|
||||||
|
defer func() {
|
||||||
|
if pan := recover(); pan != nil {
|
||||||
|
log.Fatalf("密码解密失败: %v", pan)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
encrypted, err := base64.StdEncoding.DecodeString(ePwd)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
tea := binary.NewTeaCipher(key)
|
||||||
|
if tea == nil {
|
||||||
|
panic("密钥错误")
|
||||||
|
}
|
||||||
|
return string(tea.Decrypt(encrypted))
|
||||||
|
}
|
||||||
|
@ -64,14 +64,15 @@ func (c *websocketClient) Run() {
|
|||||||
if !c.conf.Enabled {
|
if !c.conf.Enabled {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if c.conf.ReverseApiUrl != "" {
|
|
||||||
c.connectApi()
|
|
||||||
}
|
|
||||||
if c.conf.ReverseEventUrl != "" {
|
|
||||||
c.connectEvent()
|
|
||||||
}
|
|
||||||
if c.conf.ReverseUrl != "" {
|
if c.conf.ReverseUrl != "" {
|
||||||
c.connectUniversal()
|
c.connectUniversal()
|
||||||
|
} else {
|
||||||
|
if c.conf.ReverseApiUrl != "" {
|
||||||
|
c.connectApi()
|
||||||
|
}
|
||||||
|
if c.conf.ReverseEventUrl != "" {
|
||||||
|
c.connectEvent()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
c.bot.OnEventPush(c.onBotPushEvent)
|
c.bot.OnEventPush(c.onBotPushEvent)
|
||||||
}
|
}
|
||||||
@ -190,16 +191,20 @@ func (c *websocketClient) onBotPushEvent(m coolq.MSG) {
|
|||||||
defer c.pushLock.Unlock()
|
defer c.pushLock.Unlock()
|
||||||
if c.eventConn != nil {
|
if c.eventConn != nil {
|
||||||
log.Debugf("向WS服务器 %v 推送Event: %v", c.eventConn.RemoteAddr().String(), m.ToJson())
|
log.Debugf("向WS服务器 %v 推送Event: %v", c.eventConn.RemoteAddr().String(), m.ToJson())
|
||||||
|
_ = c.eventConn.SetWriteDeadline(time.Now().Add(time.Second * 3))
|
||||||
if _, err := c.eventConn.Write([]byte(m.ToJson())); err != nil {
|
if _, err := c.eventConn.Write([]byte(m.ToJson())); err != nil {
|
||||||
_ = c.eventConn.Close()
|
_ = c.eventConn.Close()
|
||||||
if c.conf.ReverseReconnectInterval != 0 {
|
if c.conf.ReverseReconnectInterval != 0 {
|
||||||
time.Sleep(time.Millisecond * time.Duration(c.conf.ReverseReconnectInterval))
|
go func() {
|
||||||
c.connectEvent()
|
time.Sleep(time.Millisecond * time.Duration(c.conf.ReverseReconnectInterval))
|
||||||
|
c.connectEvent()
|
||||||
|
}()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if c.universalConn != nil {
|
if c.universalConn != nil {
|
||||||
log.Debugf("向WS服务器 %v 推送Event: %v", c.universalConn.RemoteAddr().String(), m.ToJson())
|
log.Debugf("向WS服务器 %v 推送Event: %v", c.universalConn.RemoteAddr().String(), m.ToJson())
|
||||||
|
_ = c.universalConn.SetWriteDeadline(time.Now().Add(time.Second * 3))
|
||||||
_, _ = c.universalConn.Write([]byte(m.ToJson()))
|
_, _ = c.universalConn.Write([]byte(m.ToJson()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user