leafbot源码解读

leafbot简介

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)
}
  • cqhttp_http_driver

该驱动对应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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值