leafbot简介
-
leafbot是一个go语言实现的onebot11sdk实现之一,是一个免费的开源的go语言库,具有开发简单,持续维护等优点,可对接遵循onebot标准的实现,主要对接go-cqhttp
-
leafbot的github仓库地址为:http://github.con/huoxue1/leafbot
-
leafbot文档地址为:https://vtsqr.xyz/leafbot/dist/
driver介绍
driver为和onebot端的通信抽象层实现,目前内置了四种driver,分别对应了go-cqhttp的三种通信模式,还有一个直接连接go-cqhttp进行内置启动,driver包含在形目的driver文件夹下面,每一个driver需要实现如下接口。
type Driver interface {
// Run
// @Description: 运行该驱动的接口,该接口应该为阻塞式运行
//
Run()
// GetEvent
// @Description: 返回一个chan,该chan为事件传递的chan
// @return chan
//
GetEvent() chan []byte
// 当一个bot连接时的回调
OnConnect(func(selfId int64, host string, clientRole string))
// 当bot断开连接时的回调
OnDisConnect(func(selfId int64))
// GetBot
// @Description: 获取一个实现了APi接口的bot
// @param int64 bot的id
// @return interface{}
//
GetBot(int64) interface{
}
// GetBots
// @Description: 获取所有bot
// @return map[int64]interface{}
//
GetBots() map[int64]interface{
}
// 给驱动设置一些运行信息,例如运行地址以及端口之类的
SetConfig(config map[string]interface{
})
// 给驱动添加一个webhook监听,主要用于cqhttp_http_driver
AddWebHook(selfID int64, postHost string, postPort int)
// 给driver设置token,用于onebot端的鉴权
SetToken(token string)
}
该驱动对应go-cqhttp的http连接方式,需要在配置文件中配置listen_address和listen_port,分别为leafbot的监听地址,还需要配置对应的webhook,对应了go-cqhttp端的监听地址。
driver通过实现了http包中的handler接口,即实现了ServerHttp方法,在ServerHttp方法中监听来自cqhttp的上报消息,并在在run方法中注册bot对象,每一个bot对象记录了自己上报端的接口地址和自己的selfId,bot通过调用Do方法进行api的调用
// 实现了ServerHttp方法
func (d *Driver) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
data, err := io.ReadAll(request.Body)
if err != nil {
return
}
d.eventChan <- data
writer.WriteHeader(200)
}
// 注册Bot对象
func (d *Driver) Run() {
log.Infoln("Load the cqhttp_http_driver successful")
for _, s := range d.webHook {
b := new(Bot)
b.selfID = s.selfID
b.postHost = s.postHost
b.postPort = s.postPort
b.responses = sync.Map{
}
b.disConnectHandle = d.disConnectHandle
b.client = gout.NewWithOpt()
b.token = d.token
d.bots.Store(s.selfID, b)
}
log.Infoln("Load the cqhttp_http_driver successful")
log.Infoln(fmt.Sprintf("the cqhttp_http_driver listening in %v:%v", d.listenHost, d