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

Compare commits

...

15 Commits

Author SHA1 Message Date
81d2ad3e79 update ascii art. 2020-08-02 13:50:09 +08:00
977337914d update MiraiGo. 2020-08-02 09:14:52 +08:00
6780615d45 update README.md 2020-08-02 05:55:58 +08:00
2670c84c8e env supported. 2020-08-02 05:28:10 +08:00
e2b6c3d607 doc update. 2020-08-01 10:57:48 +08:00
58a3f81142 new event: friend_recall. 2020-08-01 10:55:17 +08:00
64cb539c0d update MiraiGo. 2020-07-31 23:12:02 +08:00
3bb844d1d4 support group quit. 2020-07-31 12:45:52 +08:00
0fdb01e82c cqcode share supported. 2020-07-31 01:30:45 +08:00
7cf199189a doc update. 2020-07-30 22:11:52 +08:00
3aea70e92a fix concurrent write panic #6 2020-07-30 20:04:00 +08:00
d1505ec15d fix typo. 2020-07-30 19:45:47 +08:00
750a01acdd update README.md 2020-07-30 08:54:25 +08:00
a12dcfa2d7 add: group_upload event support.
add: simple debug.
2020-07-30 08:52:01 +08:00
86422c5a00 Update README.md 2020-07-29 22:02:09 +08:00
13 changed files with 152 additions and 127 deletions

View File

@ -13,6 +13,7 @@
- [x] 反向Websocket
#### 拓展支持
> 拓展API可前往 [文档](docs/cqhttp.md) 查看
- [x] HTTP POST多点上报
- [x] 反向WS多点连接
- [x] 修改群名
@ -22,6 +23,19 @@
- [ ] 使用代理请求网络图片
#### 实现
<details>
<summary>已实现CQ码</summary>
- [CQ:image]
- [CQ:face]
- [CQ:at]
- [CQ:share]
- [CQ:reply]
- [CQ:forward]
- [CQ:node]
</details>
<details>
<summary>已实现API</summary>
@ -45,6 +59,7 @@
| /set_group_kick | [群组T人](https://cqhttp.cc/docs/4.15/#/API?id=set_group_kick-群组踢人) |
| /set_group_ban | [群组单人禁言](https://cqhttp.cc/docs/4.15/#/API?id=set_group_ban-群组单人禁言) |
| /set_group_whole_ban | [群组全员禁言](https://cqhttp.cc/docs/4.15/#/API?id=set_group_whole_ban-群组全员禁言) |
| /set_group_leave | [退出群组](https://cqhttp.cc/docs/4.15/#/API?id=set_group_leave-退出群组) |
| /set_group_name | 设置群组名(拓展API) |
| /get_image | 获取图片信息(拓展API) |
| /get_group_msg | 获取群组消息(拓展API) |
@ -63,11 +78,13 @@
| ------------------------------------------------------------ |
| [私聊信息](https://cqhttp.cc/docs/4.15/#/Post?id=私聊消息) |
| [群消息](https://cqhttp.cc/docs/4.15/#/Post?id=群消息) |
| [群消息撤回(拓展Event)](docs/cqhttp.md#群消息撤回) |
| [群消息撤回(拓展Event)](docs/cqhttp.md#群消息撤回) |
| [好友消息撤回(拓展Event)](docs/cqhttp.md#好友消息撤回) |
| [群管理员变动](https://cqhttp.cc/docs/4.15/#/Post?id=群管理员变动) |
| [群成员减少](https://cqhttp.cc/docs/4.15/#/Post?id=群成员减少) |
| [群成员增加](https://cqhttp.cc/docs/4.15/#/Post?id=群成员增加) |
| [群禁言](https://cqhttp.cc/docs/4.15/#/Post?id=群禁言) |
| [群文件上传](https://cqhttp.cc/docs/4.15/#/Post?id=群文件上传)|
| [加好友请求](https://cqhttp.cc/docs/4.15/#/Post?id=加好友请求) |
| [加群请求/邀请](https://cqhttp.cc/docs/4.15/#/Post?id=加群请求/邀请) |

View File

@ -273,6 +273,15 @@ func (bot *CQBot) CQSetGroupWholeBan(groupId int64, enable bool) MSG {
return Failed(100)
}
// https://cqhttp.cc/docs/4.15/#/API?id=set_group_leave-%E9%80%80%E5%87%BA%E7%BE%A4%E7%BB%84
func (bot *CQBot) CQSetGroupLeave(groupId int64) MSG {
if g := bot.Client.FindGroup(groupId); g != nil {
g.Quit()
return OK(nil)
}
return Failed(100)
}
// 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 {
req, ok := bot.friendReqCache.Load(flag)
@ -406,8 +415,8 @@ func (bot *CQBot) CQGetForwardMessage(resId string) MSG {
checkImage(n.Message)
r = append(r, MSG{
"sender": MSG{
"user_id": n.SenderId,
"nick": n.SenderName,
"user_id": n.SenderId,
"nickname": n.SenderName,
},
"time": n.Time,
"content": ToStringMessage(n.Message, 0, false),

View File

@ -51,6 +51,7 @@ func NewQQBot(cli *client.QQClient, conf *global.JsonConfig) *CQBot {
bot.Client.OnTempMessage(bot.tempMessageEvent)
bot.Client.OnGroupMuted(bot.groupMutedEvent)
bot.Client.OnGroupMessageRecalled(bot.groupRecallEvent)
bot.Client.OnFriendMessageRecalled(bot.friendRecallEvent)
bot.Client.OnJoinGroup(bot.joinGroupEvent)
bot.Client.OnLeaveGroup(bot.leaveGroupEvent)
bot.Client.OnGroupMemberJoined(bot.memberJoinEvent)

View File

@ -213,6 +213,8 @@ func (bot *CQBot) ToElement(t string, d map[string]string, group bool) (message.
}
t, _ := strconv.ParseInt(qq, 10, 64)
return message.NewAt(t), nil
case "share":
return message.NewUrlShare(d["url"], d["title"], d["content"], d["image"]), nil
default:
return nil, errors.New("unsupported cq code: " + t)
}

View File

@ -21,7 +21,7 @@ func (bot *CQBot) privateMessageEvent(c *client.QQClient, m *message.PrivateMess
"post_type": "message",
"message_type": "private",
"sub_type": "friend",
"message_id": m.Id,
"message_id": ToGlobalId(m.Sender.Uin, m.Id),
"user_id": m.Sender.Uin,
"message": ToStringMessage(m.Elements, 0, false),
"raw_message": cqm,
@ -40,6 +40,26 @@ func (bot *CQBot) privateMessageEvent(c *client.QQClient, m *message.PrivateMess
func (bot *CQBot) groupMessageEvent(c *client.QQClient, m *message.GroupMessage) {
checkImage(m.Elements)
for _, elem := range m.Elements {
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)
bot.dispatchEventMessage(MSG{
"post_type": "notice",
"notice_type": "group_upload",
"group_id": m.GroupCode,
"user_id": m.Sender.Uin,
"file": MSG{
"id": file.Path,
"name": file.Name,
"size": file.Size,
"busid": file.Busid,
},
"self_id": c.Uin,
"time": time.Now().Unix(),
})
return
}
}
cqm := ToStringMessage(m.Elements, m.GroupCode, true)
id := m.Id
if bot.db != nil {
@ -164,6 +184,20 @@ func (bot *CQBot) groupRecallEvent(c *client.QQClient, e *client.GroupMessageRec
})
}
func (bot *CQBot) friendRecallEvent(c *client.QQClient, e *client.FriendMessageRecalledEvent) {
f := c.FindFriend(e.FriendUin)
gid := ToGlobalId(e.FriendUin, e.MessageId)
log.Infof("好友 %v(%v) 撤回了消息: %v", f.Nickname, f.Uin, gid)
bot.dispatchEventMessage(MSG{
"post_type": "notice",
"notice_type": "friend_recall",
"self_id": c.Uin,
"user_id": f.Uin,
"time": e.Time,
"message_id": gid,
})
}
func (bot *CQBot) joinGroupEvent(c *client.QQClient, group *client.GroupInfo) {
log.Infof("Bot进入了群 %v.", formatGroupName(group))
bot.dispatchEventMessage(bot.groupIncrease(group.Code, 0, c.Uin))

View File

@ -199,7 +199,7 @@ Type: `node`
{
"content": "合并转发1",
"sender": {
"nick": "发送者A",
"nickname": "发送者A",
"user_id": 10086
},
"time": 1595694374
@ -207,7 +207,7 @@ Type: `node`
{
"content": "合并转发2[CQ:image,file=xxxx,url=xxxx]",
"sender": {
"nick": "发送者B",
"nickname": "发送者B",
"user_id": 10087
},
"time": 1595694393
@ -247,3 +247,14 @@ Type: `node`
| `operator_id` | int64 | | 操作者id |
| `message_id` | int64 | | 被撤回的消息id |
#### 好友消息撤回
**上报数据**
| 字段 | 类型 | 可能的值 | 说明 |
| ------------- | ------ | -------------- | -------------- |
| `post_type` | string | `notice` | 上报类型 |
| `notice_type` | string | `friend_recall`| 消息类型 |
| `user_id` | int64 | | 好友id |
| `message_id` | int64 | | 被撤回的消息id |

View File

@ -1,101 +0,0 @@
package global
import (
"bytes"
"fmt"
"golang.org/x/image/font"
"golang.org/x/image/font/basicfont"
"golang.org/x/image/math/fixed"
"image"
"image/color"
_ "image/jpeg"
_ "image/png"
"io"
)
// https://github.com/xrlin/AsciiArt
func Convert(f io.Reader, chars []string, subWidth, subHeight int, imageSwitch bool, bgColor, penColor color.RGBA) (string, *image.NRGBA, error) {
var charsLength = len(chars)
if charsLength == 0 {
return "", nil, fmt.Errorf("no chars provided")
}
if subWidth == 0 || subHeight == 0 {
return "", nil, fmt.Errorf("subWidth and subHeight params is required")
}
m, _, err := image.Decode(f)
if err != nil {
return "", nil, err
}
imageWidth, imageHeight := m.Bounds().Max.X, m.Bounds().Max.Y
var img *image.NRGBA
if imageSwitch {
img = initImage(imageWidth, imageHeight, bgColor)
}
piecesX, piecesY := imageWidth/subWidth, imageHeight/subHeight
var buff bytes.Buffer
for y := 0; y < piecesY; y++ {
offsetY := y * subHeight
for x := 0; x < piecesX; x++ {
offsetX := x * subWidth
averageBrightness := calculateAverageBrightness(m, image.Rect(offsetX, offsetY, offsetX+subWidth, offsetY+subHeight))
char := getCharByBrightness(chars, averageBrightness)
buff.WriteString(char)
if img != nil {
addCharToImage(img, char, x*subWidth, y*subHeight, penColor)
}
}
buff.WriteString("\n")
}
return buff.String(), img, nil
}
func initImage(width, height int, bgColor color.RGBA) *image.NRGBA {
img := image.NewNRGBA(image.Rect(0, 0, width, height))
for x := 0; x < width; x++ {
for y := 0; y < height; y++ {
img.Set(x, y, bgColor)
}
}
return img
}
func calculateAverageBrightness(img image.Image, rect image.Rectangle) float64 {
var averageBrightness float64
width, height := rect.Max.X-rect.Min.X, rect.Max.Y-rect.Min.Y
var brightness float64
for x := rect.Min.X; x < rect.Max.X; x++ {
for y := rect.Min.Y; y < rect.Max.Y; y++ {
r, g, b, _ := img.At(x, y).RGBA()
brightness = float64(r>>8+g>>8+b>>8) / 3
averageBrightness += brightness
}
}
averageBrightness /= float64(width * height)
return averageBrightness
}
func getCharByBrightness(chars []string, brightness float64) string {
index := int(brightness*float64(len(chars))) >> 8
if index == len(chars) {
index--
}
return chars[len(chars)-index-1]
}
func addCharToImage(img *image.NRGBA, char string, x, y int, penColor color.RGBA) {
face := basicfont.Face7x13
point := fixed.Point26_6{X: fixed.Int26_6(x * 64), Y: fixed.Int26_6(y * 64)}
d := &font.Drawer{
Dst: img,
Src: image.NewUniform(penColor),
Face: face,
Dot: point,
}
d.DrawString(char)
}
var Colors = map[string]color.RGBA{"black": {0, 0, 0, 255},
"gray": {140, 140, 140, 255},
"red": {255, 0, 0, 255},
"green": {0, 128, 0, 255},
"blue": {0, 0, 255, 255}}

View File

@ -15,7 +15,7 @@ type JsonConfig struct {
HttpConfig *GoCQHttpConfig `json:"http_config"`
WSConfig *GoCQWebsocketConfig `json:"ws_config"`
ReverseServers []*GoCQReverseWebsocketConfig `json:"ws_reverse_servers"`
Proxy string `json:"proxy"`
Debug bool `json:"debug"`
}
type CQHttpApiConfig struct {

3
go.mod
View File

@ -3,7 +3,7 @@ module github.com/Mrs4s/go-cqhttp
go 1.14
require (
github.com/Mrs4s/MiraiGo v0.0.0-20200729044443-98a77a6cf354
github.com/Mrs4s/MiraiGo v0.0.0-20200802045511-04aad9705bdc
github.com/gin-gonic/gin v1.6.3
github.com/gorilla/websocket v1.4.2
github.com/guonaihong/gout v0.1.1
@ -14,6 +14,7 @@ require (
github.com/t-tomalak/logrus-easy-formatter v0.0.0-20190827215021-c074f06c5816
github.com/tidwall/gjson v1.6.0
github.com/xujiajun/nutsdb v0.5.0
github.com/yinghau76/go-ascii-art v0.0.0-20190517192627-e7f465a30189
golang.org/x/image v0.0.0-20200618115811-c13761719519
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa
golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae // indirect

13
go.sum
View File

@ -1,11 +1,7 @@
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/Mrs4s/MiraiGo v0.0.0-20200727124316-9d432df098d9 h1:sgwJQnKKAJF/FCXyGv5HHpE5BcKGnwGyCSmPKTB7/vE=
github.com/Mrs4s/MiraiGo v0.0.0-20200727124316-9d432df098d9/go.mod h1:M9wh1hjd0rie3+wm27tjPZkYMbD+MBV76CGqp2G7WSU=
github.com/Mrs4s/MiraiGo v0.0.0-20200728112613-91aa75e8270d h1:Pv8lvODPBb+By7CU1crF0/KrmwIrUb4W/3jTs9WDSN4=
github.com/Mrs4s/MiraiGo v0.0.0-20200728112613-91aa75e8270d/go.mod h1:M9wh1hjd0rie3+wm27tjPZkYMbD+MBV76CGqp2G7WSU=
github.com/Mrs4s/MiraiGo v0.0.0-20200729044443-98a77a6cf354 h1:f2Cv15Nir9tcefrvwD0+imVx1RQAw2TQI7LFipPUzrI=
github.com/Mrs4s/MiraiGo v0.0.0-20200729044443-98a77a6cf354/go.mod h1:M9wh1hjd0rie3+wm27tjPZkYMbD+MBV76CGqp2G7WSU=
github.com/Mrs4s/MiraiGo v0.0.0-20200802045511-04aad9705bdc h1:mtPgcLy1VNr+nTA7vQibBYpYpFALJ+ChVkUwA8KNKfI=
github.com/Mrs4s/MiraiGo v0.0.0-20200802045511-04aad9705bdc/go.mod h1:M9wh1hjd0rie3+wm27tjPZkYMbD+MBV76CGqp2G7WSU=
github.com/bwmarrin/snowflake v0.3.0 h1:xm67bEhkKh6ij1790JB83OujPR5CzNe8QuQqAgISZN0=
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=
@ -69,6 +65,8 @@ github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHX
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ=
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
@ -101,9 +99,10 @@ github.com/xujiajun/nutsdb v0.5.0 h1:j/jM3Zw7Chg8WK7bAcKR0Xr7Mal47U1oJAMgySfDn9E
github.com/xujiajun/nutsdb v0.5.0/go.mod h1:owdwN0tW084RxEodABLbO7h4Z2s9WiAjZGZFhRh0/1Q=
github.com/xujiajun/utils v0.0.0-20190123093513-8bf096c4f53b h1:jKG9OiL4T4xQN3IUrhUpc1tG+HfDXppkgVcrAiiaI/0=
github.com/xujiajun/utils v0.0.0-20190123093513-8bf096c4f53b/go.mod h1:AZd87GYJlUzl82Yab2kTjx1EyXSQCAfZDhpTo1SQC4k=
github.com/yinghau76/go-ascii-art v0.0.0-20190517192627-e7f465a30189 h1:4UJw9if55Fu3HOwbfcaQlJ27p3oeJU2JZqoeT3ITJQk=
github.com/yinghau76/go-ascii-art v0.0.0-20190517192627-e7f465a30189/go.mod h1:rIrm5geMiBhPQkdfUm8gDFi/WiHneOp1i9KjmJqc+9I=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/image v0.0.0-20200618115811-c13761719519 h1:1e2ufUJNM3lCHEY5jIgac/7UTjd6cgJNdatjPdFWf34=
golang.org/x/image v0.0.0-20200618115811-c13761719519/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=

52
main.go
View File

@ -12,12 +12,14 @@ import (
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
log "github.com/sirupsen/logrus"
easy "github.com/t-tomalak/logrus-easy-formatter"
"image/color"
asciiart "github.com/yinghau76/go-ascii-art"
"image"
"io"
"io/ioutil"
"os"
"os/signal"
"path"
"strconv"
"strings"
"time"
)
@ -72,7 +74,34 @@ func init() {
func main() {
console := bufio.NewReader(os.Stdin)
conf := global.Load("config.json")
var conf *global.JsonConfig
if global.PathExists("config.json") || os.Getenv("UIN") == "" {
conf = global.Load("config.json")
} else if os.Getenv("UIN") != "" {
log.Infof("将从环境变量加载配置.")
uin, _ := strconv.ParseInt(os.Getenv("UIN"), 10, 64)
pwd := os.Getenv("PASS")
post := os.Getenv("HTTP_POST")
conf = &global.JsonConfig{
Uin: uin,
Password: pwd,
HttpConfig: &global.GoCQHttpConfig{
Enabled: true,
Host: "0.0.0.0",
Port: 5700,
PostUrls: map[string]string{},
},
WSConfig: &global.GoCQWebsocketConfig{
Enabled: true,
Host: "0.0.0.0",
Port: 6700,
},
Debug: os.Getenv("DEBUG") == "true",
}
if post != "" {
conf.HttpConfig.PostUrls[post] = os.Getenv("HTTP_SECRET")
}
}
if conf == nil {
err := global.DefaultConfig().Save("config.json")
if err != nil {
@ -80,14 +109,20 @@ func main() {
return
}
log.Infof("默认配置文件已生成, 请编辑 config.json 后重启程序.")
time.Sleep(time.Second * 5)
return
}
if conf.Uin == 0 || conf.Password == "" {
log.Fatal("请修改 config.json 以添加账号密码.")
log.Warnf("请修改 config.json 以添加账号密码.")
time.Sleep(time.Second * 5)
return
}
if conf.Debug {
log.SetLevel(log.DebugLevel)
log.Warnf("已开启Debug模式.")
}
if !global.PathExists("device.json") {
log.Warn("虚拟设备信息不存在, 将自动生成随机设备,按 Enter 继续.")
_, _ = console.ReadString('\n')
log.Warn("虚拟设备信息不存在, 将自动生成随机设备.")
client.GenRandomDevice()
_ = ioutil.WriteFile("device.json", client.SystemDeviceInfo.ToJson(), 0777)
log.Info("已生成设备信息并保存到 device.json 文件.")
@ -107,10 +142,9 @@ func main() {
if !rsp.Success {
switch rsp.Error {
case client.NeedCaptcha:
art, _, err := global.Convert(bytes.NewReader(rsp.CaptchaImage), []string{" ", "1", "i", ":", "*", "|", "."}, 1, 1, false, global.Colors["gray"], color.RGBA{})
global.Check(err)
fmt.Println(art)
log.Warn("请输入验证码.")
img, _, _ := image.Decode(bytes.NewReader(rsp.CaptchaImage))
fmt.Println(asciiart.New("image", img).Art)
log.Warn("请输入验证码: (回车提交)")
text, _ := console.ReadString('\n')
rsp, err = cli.SubmitCaptcha(strings.ReplaceAll(text, "\n", ""), rsp.CaptchaSign)
continue

View File

@ -127,6 +127,9 @@ func (s *httpServer) Run(addr, authToken string, bot *coolq.CQBot) {
s.engine.Any("/set_group_name", s.SetGroupName)
s.engine.Any("/set_group_name_async", s.SetGroupName)
s.engine.Any("/set_group_leave", s.SetGroupLeave)
s.engine.Any("/set_group_leave_async", s.SetGroupLeave)
s.engine.Any("/get_image", s.GetImage)
s.engine.Any("/get_image_async", s.GetImage)
@ -317,6 +320,11 @@ func (s *httpServer) SetGroupName(c *gin.Context) {
c.JSON(200, s.bot.CQSetGroupName(gid, getParam(c, "name")))
}
func (s *httpServer) SetGroupLeave(c *gin.Context) {
gid, _ := strconv.ParseInt(getParam(c, "group_id"), 10, 64)
c.JSON(200, s.bot.CQSetGroupLeave(gid))
}
func (s *httpServer) GetForwardMessage(c *gin.Context) {
resId := getParam(c, "message_id")
c.JSON(200, s.bot.CQGetForwardMessage(resId))

View File

@ -164,13 +164,15 @@ func (c *websocketClient) listenApi(conn *wsc.Conn, u bool) {
}
j := gjson.ParseBytes(buf[:l])
t := strings.ReplaceAll(j.Get("action").Str, "_async", "")
//log.Infof("调用API: %v p: %v", t, j.Get("params").Raw)
log.Debugf("反向WS接收到API调用: %v 参数: %v", t, j.Get("params").Raw)
if f, ok := wsApi[t]; ok {
ret := f(c.bot, j.Get("params"))
if j.Get("echo").Exists() {
ret["echo"] = j.Get("echo").Value()
}
c.pushLock.Lock()
_, _ = conn.Write([]byte(ret.ToJson()))
c.pushLock.Unlock()
}
}
if c.conf.ReverseReconnectInterval != 0 {
@ -187,6 +189,7 @@ func (c *websocketClient) onBotPushEvent(m coolq.MSG) {
c.pushLock.Lock()
defer c.pushLock.Unlock()
if c.eventConn != nil {
log.Debugf("向WS服务器 %v 推送Event: %v", c.eventConn.RemoteAddr().String(), m.ToJson())
if _, err := c.eventConn.Write([]byte(m.ToJson())); err != nil {
_ = c.eventConn.Close()
if c.conf.ReverseReconnectInterval != 0 {
@ -196,6 +199,7 @@ func (c *websocketClient) onBotPushEvent(m coolq.MSG) {
}
}
if c.universalConn != nil {
log.Debugf("向WS服务器 %v 推送Event: %v", c.universalConn.RemoteAddr().String(), m.ToJson())
_, _ = c.universalConn.Write([]byte(m.ToJson()))
}
}
@ -268,13 +272,15 @@ func (s *websocketServer) listenApi(c *websocket.Conn) {
if t == websocket.TextMessage {
j := gjson.ParseBytes(payload)
t := strings.ReplaceAll(j.Get("action").Str, "_async", "") //TODO: async support
//log.Infof("API调用: %v", j.Get("action").Str)
log.Debugf("WS接收到API调用: %v 参数: %v", t, j.Get("params").Raw)
if f, ok := wsApi[t]; ok {
ret := f(s.bot, j.Get("params"))
if j.Get("echo").Exists() {
ret["echo"] = j.Get("echo").Value()
}
s.pushLock.Lock()
_ = c.WriteJSON(ret)
s.pushLock.Unlock()
}
}
}
@ -285,6 +291,7 @@ func (s *websocketServer) onBotPushEvent(m coolq.MSG) {
defer s.pushLock.Unlock()
pos := 0
for _, conn := range s.eventConn {
log.Debugf("向WS客户端 %v 推送Event: %v", conn.RemoteAddr().String(), m.ToJson())
err := conn.WriteMessage(websocket.TextMessage, []byte(m.ToJson()))
if err != nil {
_ = conn.Close()
@ -386,6 +393,9 @@ var wsApi = map[string]func(*coolq.CQBot, gjson.Result) coolq.MSG{
"set_group_name": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQSetGroupName(p.Get("group_id").Int(), p.Get("name").Str)
},
"set_group_leave": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQSetGroupLeave(p.Get("group_id").Int())
},
"get_image": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQGetImage(p.Get("file").Str)
},