Skip to content

Commit

Permalink
feat: 添加了cqhttp的正向访问驱动
Browse files Browse the repository at this point in the history
  • Loading branch information
huoxue1 committed Oct 22, 2021
1 parent f7bce92 commit fbbbecb
Show file tree
Hide file tree
Showing 8 changed files with 1,827 additions and 9 deletions.
1,586 changes: 1,586 additions & 0 deletions cqhttp_positive_ws_driver/api.go

Large diffs are not rendered by default.

75 changes: 75 additions & 0 deletions cqhttp_positive_ws_driver/bot.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package cqhttp_positive_ws_driver

import (
"errors"
"sync"
"time"

"github.com/gorilla/websocket"
)

type Bot struct {
selfId int64
conn *websocket.Conn
responses sync.Map
lock sync.Mutex
disConnectHandle func(selfId int64)
}

// GetSelfId
/**
* @Description: 获取bot的账号
* @receiver b
* @return int64
* example
*/
func (b *Bot) GetSelfId() int64 {
return b.selfId
}

// Do
/**
* @Description: 执行一个api的调用
* @receiver b
* @param i
* example
*/
func (b *Bot) Do(i interface{}) {
err := b.conn.WriteJSON(i)
if err != nil {
b.wsClose()
return
}
}

// GetResponse
/**
* @Description: 获取一个api调用的响应
* @receiver b
* @param echo api调用的唯一标识
* @return []byte
* @return error
* example
*/
func (b *Bot) GetResponse(echo string) ([]byte, error) {
defer func() {
b.responses.Delete(echo)
}()

for i := 0; i < 120; i++ {
value, ok := b.responses.LoadAndDelete(echo)
if ok {
return value.([]byte), nil
}
time.Sleep(500)
}

return nil, errors.New("get response time out")
}

func (b *Bot) wsClose() {
_ = b.conn.Close()
b.lock.Lock()
b.disConnectHandle(b.selfId)
defer b.lock.Unlock()
}
151 changes: 151 additions & 0 deletions cqhttp_positive_ws_driver/driver.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
package cqhttp_positive_ws_driver

import (
"fmt"
"net/url"
"strconv"
"sync"

"github.com/gorilla/websocket"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
)

type Driver struct {
Name string
address string
port int
bots sync.Map
eventChan chan []byte
connectHandle func(selfId int64, host string, clientRole string)
disConnectHandle func(selfId int64)
}

func (d *Driver) Run() {
u := url.URL{Scheme: "ws", Host: d.address + ":" + strconv.Itoa(d.port)}
conn, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
return
}
_, data, err := conn.ReadMessage()
if err != nil {
return
}
selfId := gjson.GetBytes(data, "self_id").Int()
role := ""
host := d.address

b := new(Bot)
b.conn = conn
b.selfId = selfId
b.responses = sync.Map{}

_, ok := d.bots.Load(selfId)
if ok {
d.bots.LoadOrStore(selfId, b)
} else {
d.bots.Store(selfId, b)
}

d.connectHandle(selfId, host, role)
b.disConnectHandle = d.disConnectHandle
log.Infoln(fmt.Sprintf("the bot %v is connected", selfId))
go func() {
defer func() {
i := recover()
if i != nil {
log.Errorln("ws链接读取出现错误")
log.Errorln(i)
d.disConnectHandle(selfId)
}
}()
for {
_, data, err := conn.ReadMessage()
if err != nil {
b.wsClose()
}

echo := gjson.GetBytes(data, "echo")
if echo.Exists() {
b.responses.Store(echo.String(), data)
} else {
d.eventChan <- data
}
}
}()
}

func (d *Driver) GetEvent() chan []byte {
return d.eventChan
}

func (d *Driver) GetBot(i int64) interface{} {
load, ok := d.bots.Load(i)
if ok {
return load
}

return nil
}

// OnConnect
/**
* @Description:
* @receiver d
* @param f
* example
*/
func (d *Driver) OnConnect(f func(selfId int64, host string, clientRole string)) {
d.connectHandle = f
}

// OnDisConnect
/**
* @Description:
* @receiver d
* @param f
* example
*/
func (d *Driver) OnDisConnect(f func(selfId int64)) {
d.disConnectHandle = f
}

// GetBots
/**
* @Description:
* @receiver d
* @return map[int64]interface{}
* example
*/
func (d *Driver) GetBots() map[int64]interface{} {
m := make(map[int64]interface{})
d.bots.Range(func(key, value interface{}) bool {
m[key.(int64)] = value
return true
})

return m
}

// SetAddress
/**
* @Description:
* @receiver d
* @param string2
* example
*/
func (d *Driver) SetAddress(string2 string) {
d.address = string2
}

func (d *Driver) SetPort(port int) {
d.port = port
}

func NewDriver() *Driver {
d := new(Driver)
d.Name = "cqhttp"
d.bots = sync.Map{}
d.eventChan = make(chan []byte)
return d
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package cqhttp_ws_driver
package cqhttp_reverse_ws_driver

import (
"encoding/json" //nolint:gci
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package cqhttp_ws_driver
package cqhttp_reverse_ws_driver

import (
"errors"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package cqhttp_ws_driver
package cqhttp_reverse_ws_driver

import (
"fmt"
Expand Down Expand Up @@ -137,7 +137,7 @@ func (d *Driver) ServeHTTP(writer http.ResponseWriter, request *http.Request) {

func (d *Driver) Run() {
http.Handle("/"+d.Name+"/ws", d)
if err := http.ListenAndServe(d.address, nil); err != nil {
if err := http.ListenAndServe(fmt.Sprintf("%v:%v", d.address, d.port), nil); err != nil {
log.Panicln(err.Error())
}
}
Expand All @@ -155,6 +155,10 @@ func (d *Driver) GetBot(i int64) interface{} {
return nil
}

func (d *Driver) SetPort(port int) {
d.port = port
}

func NewDriver() *Driver {
d := new(Driver)
d.Name = "cqhttp"
Expand Down
7 changes: 4 additions & 3 deletions driver.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package leafBot

import (
"fmt"

log "github.com/sirupsen/logrus"
)

Expand Down Expand Up @@ -39,6 +37,8 @@ type Driver interface {
// @param string2
//
SetAddress(string2 string)

SetPort(port int)
}

// Conn
Expand Down Expand Up @@ -70,7 +70,8 @@ var driver Driver
* example
*/
func LoadDriver(driver2 Driver) {
driver2.SetAddress(fmt.Sprintf(":%v", DefaultConfig.Port))
driver2.SetAddress(DefaultConfig.Host)
driver2.SetPort(DefaultConfig.Port)
driver2.OnConnect(func(selfId int64, host string, clientRole string) {
defer func() {
err := recover()
Expand Down
5 changes: 3 additions & 2 deletions example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package main

import (
"github.com/huoxue1/leafBot"
"github.com/huoxue1/leafBot/cqhttp_ws_driver"
"github.com/huoxue1/leafBot/cqhttp_positive_ws_driver"
"github.com/huoxue1/leafBot/message"
)

Expand All @@ -14,11 +14,12 @@ func init() {

func main() {
// 创建一个驱动
driver := cqhttp_ws_driver.NewDriver()
driver := cqhttp_positive_ws_driver.NewDriver()
// 注册驱动
leafBot.LoadDriver(driver)
// 初始化Bot
leafBot.InitBots()
// 运行驱动
driver.Run()
select {}
}

0 comments on commit fbbbecb

Please sign in to comment.