Commit d7abe6f7 authored by wdvxdr1123's avatar wdvxdr1123 Committed by GitHub

Merge pull request #1 from Mrs4s/master

同步
parents 322b70c6 2259e7cc
...@@ -17,6 +17,8 @@ jobs: ...@@ -17,6 +17,8 @@ jobs:
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: Set RELEASE_VERSION env
run: echo ::set-env name=RELEASE_VERSION::${GITHUB_REF:10}
- uses: wangyoucao577/go-release-action@master - uses: wangyoucao577/go-release-action@master
env: env:
CGO_ENABLED: 0 CGO_ENABLED: 0
...@@ -24,4 +26,5 @@ jobs: ...@@ -24,4 +26,5 @@ jobs:
github_token: ${{ secrets.GITHUB_TOKEN }} github_token: ${{ secrets.GITHUB_TOKEN }}
goos: ${{ matrix.goos }} goos: ${{ matrix.goos }}
goarch: ${{ matrix.goarch }} goarch: ${{ matrix.goarch }}
ldflags: "-w -s" ldflags: -w -s -X "github.com/Mrs4s/go-cqhttp/coolq.version=${{ env.RELEASE_VERSION }}"
\ No newline at end of file
package coolq package coolq
import ( import (
"github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/client"
"github.com/Mrs4s/MiraiGo/message"
"github.com/Mrs4s/go-cqhttp/global"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"io/ioutil" "io/ioutil"
"os" "os"
"path" "path"
"runtime" "runtime"
"strconv" "strconv"
"time" "time"
"github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/client"
"github.com/Mrs4s/MiraiGo/message"
"github.com/Mrs4s/go-cqhttp/global"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
) )
var version = "unknown"
// https://cqhttp.cc/docs/4.15/#/API?id=get_login_info-%E8%8E%B7%E5%8F%96%E7%99%BB%E5%BD%95%E5%8F%B7%E4%BF%A1%E6%81%AF // https://cqhttp.cc/docs/4.15/#/API?id=get_login_info-%E8%8E%B7%E5%8F%96%E7%99%BB%E5%BD%95%E5%8F%B7%E4%BF%A1%E6%81%AF
func (bot *CQBot) CQGetLoginInfo() MSG { func (bot *CQBot) CQGetLoginInfo() MSG {
return OK(MSG{"user_id": bot.Client.Uin, "nickname": bot.Client.Nickname}) return OK(MSG{"user_id": bot.Client.Uin, "nickname": bot.Client.Nickname})
...@@ -134,6 +137,7 @@ func (bot *CQBot) CQSendGroupMessage(groupId int64, i interface{}, autoEscape bo ...@@ -134,6 +137,7 @@ func (bot *CQBot) CQSendGroupMessage(groupId int64, i interface{}, autoEscape bo
str = s str = s
} }
if str == "" { if str == "" {
log.Warnf("群消息发送失败: 信息为空. MSG: %v", i)
return Failed(100) return Failed(100)
} }
var elem []message.IMessageElement var elem []message.IMessageElement
...@@ -342,7 +346,7 @@ func (bot *CQBot) CQProcessFriendRequest(flag string, approve bool) MSG { ...@@ -342,7 +346,7 @@ func (bot *CQBot) CQProcessFriendRequest(flag string, approve bool) MSG {
} }
// https://cqhttp.cc/docs/4.15/#/API?id=set_group_add_request-%E5%A4%84%E7%90%86%E5%8A%A0%E7%BE%A4%E8%AF%B7%E6%B1%82%EF%BC%8F%E9%82%80%E8%AF%B7 // https://cqhttp.cc/docs/4.15/#/API?id=set_group_add_request-%E5%A4%84%E7%90%86%E5%8A%A0%E7%BE%A4%E8%AF%B7%E6%B1%82%EF%BC%8F%E9%82%80%E8%AF%B7
func (bot *CQBot) CQProcessGroupRequest(flag, subType string, approve bool) MSG { func (bot *CQBot) CQProcessGroupRequest(flag, subType, reason string, approve bool) MSG {
if subType == "add" { if subType == "add" {
req, ok := bot.joinReqCache.Load(flag) req, ok := bot.joinReqCache.Load(flag)
if !ok { if !ok {
...@@ -352,7 +356,7 @@ func (bot *CQBot) CQProcessGroupRequest(flag, subType string, approve bool) MSG ...@@ -352,7 +356,7 @@ func (bot *CQBot) CQProcessGroupRequest(flag, subType string, approve bool) MSG
if approve { if approve {
req.(*client.UserJoinGroupRequest).Accept() req.(*client.UserJoinGroupRequest).Accept()
} else { } else {
req.(*client.UserJoinGroupRequest).Reject() req.(*client.UserJoinGroupRequest).Reject(false, reason)
} }
return OK(nil) return OK(nil)
} }
...@@ -362,7 +366,7 @@ func (bot *CQBot) CQProcessGroupRequest(flag, subType string, approve bool) MSG ...@@ -362,7 +366,7 @@ func (bot *CQBot) CQProcessGroupRequest(flag, subType string, approve bool) MSG
if approve { if approve {
req.(*client.GroupInvitedRequest).Accept() req.(*client.GroupInvitedRequest).Accept()
} else { } else {
req.(*client.GroupInvitedRequest).Reject() req.(*client.GroupInvitedRequest).Reject(false, reason)
} }
return OK(nil) return OK(nil)
} }
...@@ -485,7 +489,7 @@ func (bot *CQBot) CQHandleQuickOperation(context, operation gjson.Result) MSG { ...@@ -485,7 +489,7 @@ func (bot *CQBot) CQHandleQuickOperation(context, operation gjson.Result) MSG {
bot.CQProcessFriendRequest(context.Get("flag").Str, operation.Get("approve").Bool()) bot.CQProcessFriendRequest(context.Get("flag").Str, operation.Get("approve").Bool())
} }
if reqType == "group" { if reqType == "group" {
bot.CQProcessGroupRequest(context.Get("flag").Str, context.Get("sub_type").Str, operation.Get("approve").Bool()) bot.CQProcessGroupRequest(context.Get("flag").Str, context.Get("sub_type").Str, context.Get("reason").Str, operation.Get("approve").Bool())
} }
} }
} }
...@@ -578,6 +582,7 @@ func (bot *CQBot) CQGetVersionInfo() MSG { ...@@ -578,6 +582,7 @@ func (bot *CQBot) CQGetVersionInfo() MSG {
"plugin_build_configuration": "release", "plugin_build_configuration": "release",
"runtime_version": runtime.Version(), "runtime_version": runtime.Version(),
"runtime_os": runtime.GOOS, "runtime_os": runtime.GOOS,
"version": version,
}) })
} }
......
...@@ -12,7 +12,6 @@ import ( ...@@ -12,7 +12,6 @@ import (
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/xujiajun/nutsdb" "github.com/xujiajun/nutsdb"
"hash/crc32" "hash/crc32"
"math/rand"
"path" "path"
"sync" "sync"
"time" "time"
...@@ -108,7 +107,6 @@ func (bot *CQBot) SendGroupMessage(groupId int64, m *message.SendingMessage) int ...@@ -108,7 +107,6 @@ func (bot *CQBot) SendGroupMessage(groupId int64, m *message.SendingMessage) int
var newElem []message.IMessageElement var newElem []message.IMessageElement
for _, elem := range m.Elements { for _, elem := range m.Elements {
if i, ok := elem.(*message.ImageElement); ok { if i, ok := elem.(*message.ImageElement); ok {
_, _ = bot.Client.UploadGroupImage(int64(rand.Intn(11451419)), i.Data)
gm, err := bot.Client.UploadGroupImage(groupId, i.Data) gm, err := bot.Client.UploadGroupImage(groupId, i.Data)
if err != nil { if err != nil {
log.Warnf("警告: 群 %v 消息图片上传失败: %v", groupId, err) log.Warnf("警告: 群 %v 消息图片上传失败: %v", groupId, err)
...@@ -131,6 +129,7 @@ func (bot *CQBot) SendGroupMessage(groupId int64, m *message.SendingMessage) int ...@@ -131,6 +129,7 @@ func (bot *CQBot) SendGroupMessage(groupId int64, m *message.SendingMessage) int
m.Elements = newElem m.Elements = newElem
ret := bot.Client.SendGroupMessage(groupId, m) ret := bot.Client.SendGroupMessage(groupId, m)
if ret == nil || ret.Id == -1 { if ret == nil || ret.Id == -1 {
log.Warnf("群消息发送失败: 账号可能被风控.")
return -1 return -1
} }
return bot.InsertGroupMessage(ret) return bot.InsertGroupMessage(ret)
...@@ -227,6 +226,9 @@ func formatGroupName(group *client.GroupInfo) string { ...@@ -227,6 +226,9 @@ func formatGroupName(group *client.GroupInfo) string {
} }
func formatMemberName(mem *client.GroupMemberInfo) string { func formatMemberName(mem *client.GroupMemberInfo) string {
if mem == nil {
return "未知"
}
return fmt.Sprintf("%s(%d)", mem.DisplayName(), mem.Uin) return fmt.Sprintf("%s(%d)", mem.DisplayName(), mem.Uin)
} }
......
...@@ -14,7 +14,6 @@ type JsonConfig struct { ...@@ -14,7 +14,6 @@ type JsonConfig struct {
AccessToken string `json:"access_token"` AccessToken string `json:"access_token"`
ReLogin bool `json:"relogin"` ReLogin bool `json:"relogin"`
ReLoginDelay int `json:"relogin_delay"` ReLoginDelay int `json:"relogin_delay"`
AsyncLoad bool `json:"async_load"`
HttpConfig *GoCQHttpConfig `json:"http_config"` HttpConfig *GoCQHttpConfig `json:"http_config"`
WSConfig *GoCQWebsocketConfig `json:"ws_config"` WSConfig *GoCQWebsocketConfig `json:"ws_config"`
ReverseServers []*GoCQReverseWebsocketConfig `json:"ws_reverse_servers"` ReverseServers []*GoCQReverseWebsocketConfig `json:"ws_reverse_servers"`
......
...@@ -3,18 +3,21 @@ module github.com/Mrs4s/go-cqhttp ...@@ -3,18 +3,21 @@ module github.com/Mrs4s/go-cqhttp
go 1.14 go 1.14
require ( require (
github.com/Mrs4s/MiraiGo v0.0.0-20200819185537-8d1e5fb04c17 github.com/Mrs4s/MiraiGo v0.0.0-20200821182324-7654a7a2a106
github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239 // indirect
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
github.com/jehiah/go-strftime v0.0.0-20171201141054-1d33003b3869 // indirect
github.com/jonboulle/clockwork v0.2.0 // indirect
github.com/lestrrat-go/file-rotatelogs v2.3.0+incompatible github.com/lestrrat-go/file-rotatelogs v2.3.0+incompatible
github.com/lestrrat-go/strftime v1.0.1 // indirect github.com/lestrrat-go/strftime v1.0.1 // indirect
github.com/pkg/errors v0.9.1 // indirect github.com/pkg/errors v0.9.1 // indirect
github.com/sirupsen/logrus v1.6.0 github.com/sirupsen/logrus v1.6.0
github.com/t-tomalak/logrus-easy-formatter v0.0.0-20190827215021-c074f06c5816 github.com/t-tomalak/logrus-easy-formatter v0.0.0-20190827215021-c074f06c5816
github.com/tebeka/strftime v0.1.5 // indirect
github.com/tidwall/gjson v1.6.0 github.com/tidwall/gjson v1.6.0
github.com/xujiajun/nutsdb v0.5.0 github.com/xujiajun/nutsdb v0.5.0
github.com/yinghau76/go-ascii-art v0.0.0-20190517192627-e7f465a30189 github.com/yinghau76/go-ascii-art v0.0.0-20190517192627-e7f465a30189
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa
golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae // indirect golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae // indirect
) )
This diff is collapsed.
...@@ -136,6 +136,7 @@ func main() { ...@@ -136,6 +136,7 @@ func main() {
if conf.Debug { if conf.Debug {
log.SetLevel(log.DebugLevel) log.SetLevel(log.DebugLevel)
log.Warnf("已开启Debug模式.") log.Warnf("已开启Debug模式.")
log.Debugf("开发交流群: 192548878")
} }
if !global.PathExists("device.json") { if !global.PathExists("device.json") {
log.Warn("虚拟设备信息不存在, 将自动生成随机设备.") log.Warn("虚拟设备信息不存在, 将自动生成随机设备.")
...@@ -200,7 +201,7 @@ func main() { ...@@ -200,7 +201,7 @@ func main() {
global.Check(cli.ReloadFriendList()) global.Check(cli.ReloadFriendList())
log.Infof("共加载 %v 个好友.", len(cli.FriendList)) log.Infof("共加载 %v 个好友.", len(cli.FriendList))
log.Infof("开始加载群列表...") log.Infof("开始加载群列表...")
global.Check(cli.ReloadGroupList(conf.AsyncLoad)) global.Check(cli.ReloadGroupList())
log.Infof("共加载 %v 个群.", len(cli.GroupList)) log.Infof("共加载 %v 个群.", len(cli.GroupList))
b := coolq.NewQQBot(cli, conf) b := coolq.NewQQBot(cli, conf)
if conf.PostMessageFormat != "string" && conf.PostMessageFormat != "array" { if conf.PostMessageFormat != "string" && conf.PostMessageFormat != "array" {
......
...@@ -4,6 +4,7 @@ import ( ...@@ -4,6 +4,7 @@ import (
"crypto/hmac" "crypto/hmac"
"crypto/sha1" "crypto/sha1"
"encoding/hex" "encoding/hex"
"os"
"strconv" "strconv"
"strings" "strings"
"time" "time"
...@@ -157,7 +158,13 @@ func (s *httpServer) Run(addr, authToken string, bot *coolq.CQBot) { ...@@ -157,7 +158,13 @@ func (s *httpServer) Run(addr, authToken string, bot *coolq.CQBot) {
go func() { go func() {
log.Infof("CQ HTTP 服务器已启动: %v", addr) log.Infof("CQ HTTP 服务器已启动: %v", addr)
log.Fatal(s.engine.Run(addr)) err := s.engine.Run(addr)
if err != nil {
log.Error(err)
log.Infof("请检查端口是否被占用.")
time.Sleep(time.Second * 5)
os.Exit(1)
}
}() }()
} }
...@@ -304,7 +311,7 @@ func (s *httpServer) ProcessGroupRequest(c *gin.Context) { ...@@ -304,7 +311,7 @@ func (s *httpServer) ProcessGroupRequest(c *gin.Context) {
subType = getParam(c, "type") subType = getParam(c, "type")
} }
approve := getParamOrDefault(c, "approve", "true") approve := getParamOrDefault(c, "approve", "true")
c.JSON(200, s.bot.CQProcessGroupRequest(flag, subType, approve == "true")) c.JSON(200, s.bot.CQProcessGroupRequest(flag, subType, getParam(c, "reason"), approve == "true"))
} }
func (s *httpServer) SetGroupCard(c *gin.Context) { func (s *httpServer) SetGroupCard(c *gin.Context) {
...@@ -404,12 +411,12 @@ func getParamWithType(c *gin.Context, k string) (string, gjson.Type) { ...@@ -404,12 +411,12 @@ func getParamWithType(c *gin.Context, k string) (string, gjson.Type) {
} }
if c.Request.Method == "POST" { if c.Request.Method == "POST" {
if h := c.Request.Header.Get("Content-Type"); h != "" { if h := c.Request.Header.Get("Content-Type"); h != "" {
if h == "application/x-www-form-urlencoded" { if strings.Contains(h, "application/x-www-form-urlencoded") {
if p, ok := c.GetPostForm(k); ok { if p, ok := c.GetPostForm(k); ok {
return p, gjson.Null return p, gjson.Null
} }
} }
if h == "application/json" { if strings.Contains(h, "application/json") {
if obj, ok := c.Get("json_body"); ok { if obj, ok := c.Get("json_body"); ok {
res := obj.(gjson.Result).Get(k) res := obj.(gjson.Result).Get(k)
if res.Exists() { if res.Exists() {
......
...@@ -2,24 +2,25 @@ package server ...@@ -2,24 +2,25 @@ package server
import ( import (
"fmt" "fmt"
"github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global"
"github.com/gorilla/websocket"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"net/http" "net/http"
"strconv" "strconv"
"strings" "strings"
"sync" "sync"
"time" "time"
"github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global"
"github.com/gorilla/websocket"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
) )
type websocketServer struct { type websocketServer struct {
bot *coolq.CQBot bot *coolq.CQBot
token string token string
eventConn []*websocket.Conn eventConn []*websocketConn
pushLock *sync.Mutex eventConnMutex sync.Mutex
handshake string handshake string
} }
type websocketClient struct { type websocketClient struct {
...@@ -27,9 +28,13 @@ type websocketClient struct { ...@@ -27,9 +28,13 @@ type websocketClient struct {
token string token string
bot *coolq.CQBot bot *coolq.CQBot
pushLock *sync.Mutex universalConn *websocketConn
universalConn *websocket.Conn eventConn *websocketConn
eventConn *websocket.Conn }
type websocketConn struct {
*websocket.Conn
sync.Mutex
} }
var WebsocketServer = &websocketServer{} var WebsocketServer = &websocketServer{}
...@@ -41,7 +46,6 @@ var upgrader = websocket.Upgrader{ ...@@ -41,7 +46,6 @@ var upgrader = websocket.Upgrader{
func (s *websocketServer) Run(addr, authToken string, b *coolq.CQBot) { func (s *websocketServer) Run(addr, authToken string, b *coolq.CQBot) {
s.token = authToken s.token = authToken
s.pushLock = new(sync.Mutex)
s.bot = b s.bot = b
s.handshake = fmt.Sprintf(`{"_post_method":2,"meta_event_type":"lifecycle","post_type":"meta_event","self_id":%d,"sub_type":"connect","time":%d}`, s.handshake = fmt.Sprintf(`{"_post_method":2,"meta_event_type":"lifecycle","post_type":"meta_event","self_id":%d,"sub_type":"connect","time":%d}`,
s.bot.Client.Uin, time.Now().Unix()) s.bot.Client.Uin, time.Now().Unix())
...@@ -56,7 +60,7 @@ func (s *websocketServer) Run(addr, authToken string, b *coolq.CQBot) { ...@@ -56,7 +60,7 @@ func (s *websocketServer) Run(addr, authToken string, b *coolq.CQBot) {
} }
func NewWebsocketClient(conf *global.GoCQReverseWebsocketConfig, authToken string, b *coolq.CQBot) *websocketClient { func NewWebsocketClient(conf *global.GoCQReverseWebsocketConfig, authToken string, b *coolq.CQBot) *websocketClient {
return &websocketClient{conf: conf, token: authToken, bot: b, pushLock: new(sync.Mutex)} return &websocketClient{conf: conf, token: authToken, bot: b}
} }
func (c *websocketClient) Run() { func (c *websocketClient) Run() {
...@@ -96,7 +100,8 @@ func (c *websocketClient) connectApi() { ...@@ -96,7 +100,8 @@ func (c *websocketClient) connectApi() {
return return
} }
log.Infof("已连接到反向Websocket API服务器 %v", c.conf.ReverseApiUrl) log.Infof("已连接到反向Websocket API服务器 %v", c.conf.ReverseApiUrl)
go c.listenApi(conn, false) wrappedConn := &websocketConn{Conn: conn}
go c.listenApi(wrappedConn, false)
} }
func (c *websocketClient) connectEvent() { func (c *websocketClient) connectEvent() {
...@@ -119,7 +124,7 @@ func (c *websocketClient) connectEvent() { ...@@ -119,7 +124,7 @@ func (c *websocketClient) connectEvent() {
return return
} }
log.Infof("已连接到反向Websocket Event服务器 %v", c.conf.ReverseEventUrl) log.Infof("已连接到反向Websocket Event服务器 %v", c.conf.ReverseEventUrl)
c.eventConn = conn c.eventConn = &websocketConn{Conn: conn}
} }
func (c *websocketClient) connectUniversal() { func (c *websocketClient) connectUniversal() {
...@@ -141,11 +146,12 @@ func (c *websocketClient) connectUniversal() { ...@@ -141,11 +146,12 @@ func (c *websocketClient) connectUniversal() {
} }
return return
} }
go c.listenApi(conn, true) wrappedConn := &websocketConn{Conn: conn}
c.universalConn = conn go c.listenApi(wrappedConn, true)
c.universalConn = wrappedConn
} }
func (c *websocketClient) listenApi(conn *websocket.Conn, u bool) { func (c *websocketClient) listenApi(conn *websocketConn, u bool) {
defer conn.Close() defer conn.Close()
for { for {
_, buf, err := conn.ReadMessage() _, buf, err := conn.ReadMessage()
...@@ -153,33 +159,24 @@ func (c *websocketClient) listenApi(conn *websocket.Conn, u bool) { ...@@ -153,33 +159,24 @@ func (c *websocketClient) listenApi(conn *websocket.Conn, u bool) {
log.Warnf("监听反向WS API时出现错误: %v", err) log.Warnf("监听反向WS API时出现错误: %v", err)
break break
} }
j := gjson.ParseBytes(buf)
t := strings.ReplaceAll(j.Get("action").Str, "_async", "") go conn.handleRequest(c.bot, buf)
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()
log.Debugf("准备发送API %v 处理结果: %v", t, ret.ToJson())
_ = conn.WriteJSON(ret)
c.pushLock.Unlock()
}
} }
if c.conf.ReverseReconnectInterval != 0 { if c.conf.ReverseReconnectInterval != 0 {
time.Sleep(time.Millisecond * time.Duration(c.conf.ReverseReconnectInterval)) time.Sleep(time.Millisecond * time.Duration(c.conf.ReverseReconnectInterval))
if !u { if !u {
c.connectApi() go c.connectApi()
} }
} }
} }
func (c *websocketClient) onBotPushEvent(m coolq.MSG) { func (c *websocketClient) onBotPushEvent(m coolq.MSG) {
c.pushLock.Lock()
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.Lock()
defer c.eventConn.Unlock()
_ = c.eventConn.SetWriteDeadline(time.Now().Add(time.Second * 15))
if err := c.eventConn.WriteJSON(m); err != nil { if err := c.eventConn.WriteJSON(m); err != nil {
log.Warnf("向WS服务器 %v 推送Event时出现错误: %v", c.eventConn.RemoteAddr().String(), err) log.Warnf("向WS服务器 %v 推送Event时出现错误: %v", c.eventConn.RemoteAddr().String(), err)
_ = c.eventConn.Close() _ = c.eventConn.Close()
...@@ -193,6 +190,9 @@ func (c *websocketClient) onBotPushEvent(m coolq.MSG) { ...@@ -193,6 +190,9 @@ func (c *websocketClient) onBotPushEvent(m coolq.MSG) {
} }
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.Lock()
defer c.universalConn.Unlock()
_ = c.universalConn.SetWriteDeadline(time.Now().Add(time.Second * 15))
if err := c.universalConn.WriteJSON(m); err != nil { if err := c.universalConn.WriteJSON(m); err != nil {
log.Warnf("向WS服务器 %v 推送Event时出现错误: %v", c.universalConn.RemoteAddr().String(), err) log.Warnf("向WS服务器 %v 推送Event时出现错误: %v", c.universalConn.RemoteAddr().String(), err)
_ = c.universalConn.Close() _ = c.universalConn.Close()
...@@ -220,10 +220,19 @@ func (s *websocketServer) event(w http.ResponseWriter, r *http.Request) { ...@@ -220,10 +220,19 @@ func (s *websocketServer) event(w http.ResponseWriter, r *http.Request) {
return return
} }
err = c.WriteMessage(websocket.TextMessage, []byte(s.handshake)) err = c.WriteMessage(websocket.TextMessage, []byte(s.handshake))
if err == nil { if err != nil {
log.Infof("接受 Websocket 连接: %v (/event)", r.RemoteAddr) log.Warnf("Websocket 握手时出现错误: %v", err)
s.eventConn = append(s.eventConn, c) c.Close()
return
} }
log.Infof("接受 Websocket 连接: %v (/event)", r.RemoteAddr)
conn := &websocketConn{Conn: c}
s.eventConnMutex.Lock()
s.eventConn = append(s.eventConn, conn)
s.eventConnMutex.Unlock()
} }
func (s *websocketServer) api(w http.ResponseWriter, r *http.Request) { func (s *websocketServer) api(w http.ResponseWriter, r *http.Request) {
...@@ -240,7 +249,8 @@ func (s *websocketServer) api(w http.ResponseWriter, r *http.Request) { ...@@ -240,7 +249,8 @@ func (s *websocketServer) api(w http.ResponseWriter, r *http.Request) {
return return
} }
log.Infof("接受 Websocket 连接: %v (/api)", r.RemoteAddr) log.Infof("接受 Websocket 连接: %v (/api)", r.RemoteAddr)
go s.listenApi(c) conn := &websocketConn{Conn: c}
go s.listenApi(conn)
} }
func (s *websocketServer) any(w http.ResponseWriter, r *http.Request) { func (s *websocketServer) any(w http.ResponseWriter, r *http.Request) {
...@@ -257,40 +267,57 @@ func (s *websocketServer) any(w http.ResponseWriter, r *http.Request) { ...@@ -257,40 +267,57 @@ func (s *websocketServer) any(w http.ResponseWriter, r *http.Request) {
return return
} }
err = c.WriteMessage(websocket.TextMessage, []byte(s.handshake)) err = c.WriteMessage(websocket.TextMessage, []byte(s.handshake))
if err == nil { if err != nil {
log.Infof("接受 Websocket 连接: %v (/)", r.RemoteAddr) log.Warnf("Websocket 握手时出现错误: %v", err)
s.eventConn = append(s.eventConn, c) c.Close()
s.listenApi(c) return
} }
log.Infof("接受 Websocket 连接: %v (/)", r.RemoteAddr)
conn := &websocketConn{Conn: c}
s.eventConn = append(s.eventConn, conn)
s.listenApi(conn)
} }
func (s *websocketServer) listenApi(c *websocket.Conn) { func (s *websocketServer) listenApi(c *websocketConn) {
defer c.Close() defer c.Close()
for { for {
t, payload, err := c.ReadMessage() t, payload, err := c.ReadMessage()
if err != nil { if err != nil {
break break
} }
if t == websocket.TextMessage { if t == websocket.TextMessage {
j := gjson.ParseBytes(payload) go c.handleRequest(s.bot, payload)
t := strings.ReplaceAll(j.Get("action").Str, "_async", "") //TODO: async support }
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() { func (c *websocketConn) handleRequest(bot *coolq.CQBot, payload []byte) {
ret["echo"] = j.Get("echo").Value() defer func() {
} if err := recover(); err != nil {
s.pushLock.Lock() log.Printf("处置WS命令时发生无法恢复的异常:%v", err)
_ = c.WriteJSON(ret) c.Close()
s.pushLock.Unlock() }
} }()
j := gjson.ParseBytes(payload)
t := strings.ReplaceAll(j.Get("action").Str, "_async", "")
log.Debugf("WS接收到API调用: %v 参数: %v", t, j.Get("params").Raw)
if f, ok := wsApi[t]; ok {
ret := f(bot, j.Get("params"))
if j.Get("echo").Exists() {
ret["echo"] = j.Get("echo").Value()
} }
c.Lock()
defer c.Unlock()
_ = c.WriteJSON(ret)
} }
} }
func (s *websocketServer) onBotPushEvent(m coolq.MSG) { func (s *websocketServer) onBotPushEvent(m coolq.MSG) {
s.pushLock.Lock() s.eventConnMutex.Lock()
defer s.pushLock.Unlock() defer s.eventConnMutex.Unlock()
pos := 0 pos := 0
for _, conn := range s.eventConn { for _, conn := range s.eventConn {
log.Debugf("向WS客户端 %v 推送Event: %v", conn.RemoteAddr().String(), m.ToJson()) log.Debugf("向WS客户端 %v 推送Event: %v", conn.RemoteAddr().String(), m.ToJson())
...@@ -372,7 +399,7 @@ var wsApi = map[string]func(*coolq.CQBot, gjson.Result) coolq.MSG{ ...@@ -372,7 +399,7 @@ var wsApi = map[string]func(*coolq.CQBot, gjson.Result) coolq.MSG{
if p.Get("approve").Exists() { if p.Get("approve").Exists() {
apr = p.Get("approve").Bool() apr = p.Get("approve").Bool()
} }
return bot.CQProcessGroupRequest(p.Get("flag").Str, subType, apr) return bot.CQProcessGroupRequest(p.Get("flag").Str, subType, p.Get("reason").Str, apr)
}, },
"set_group_card": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG { "set_group_card": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQSetGroupCard(p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("card").Str) return bot.CQSetGroupCard(p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("card").Str)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment