nb2 插件编写指南(二)
这一学期过完放假了,也有时间来填之前挖的坑了
突然发现两篇三篇写不完这些东西,就变成长期更新的学习笔记吧
这篇文章要点:
- 使用 api 来发送到指定好友或群
- 定时发送信息
- 有参数传入的插件(例如查询 b 站视频封面)
用到的官方文档:nb2api
本篇还同时发布于我的博客:kamuXiY的小窝
1.NoneBot.adapters 使用
nb2 的协议官方提供了cqhttp
、ding
、mirai
三个
以 cqhttp 为例
cqhttp 的 api 文档:文档
上篇,我们知道,使用这样的格式来发送一条信息到触发这个命令的群或好友:
await bot.send(发送内容)
这个使用的是NoneBot.adapters.cqhttp
的send(event, message, at_sender=False, **kwargs)
模块
这句话同样可以写为以下形式:
await bot.call_api("send_msg", message=发送内容)
await bot.send_msg(message=发送内容)
而发送到指定群的 api 为send_group_msg
便可以写为:
await bot.call_api("send_group_msg",group_id=群号, message=发送内容)
await bot.send_group_msg(group_id=群号, message=发送内容)
这是发送到群的,发送给好友的 api 为send_private_msg
如何定时发送信息?
这个是比较有用的一点
例如发送每日推送,或发送定时公告,或者定时开启爬虫来爬取信息并发出来
可以结合上面发送到指定对象来写出一个好用的定时推送插件
官方定时任务文档:定时任务
先要引入一个插件:nonebot_plugin_apscheduler
使用 nb-cli 脚手架来安装这个插件:
nb plugin install nonebot_plugin_apscheduler
这个插件与其他不同,稍后会直接导入到需要的位置,无需在 bot.py 中导入
除此之外,还需要添加其他配置:
在.env
中添加:
APSCHEDULER_AUTOSTART=true
APSCHEDULER_CONFIG={"apscheduler.timezone": "Asia/Shanghai"}
在 bot.py 中添加:
nonebot.init(apscheduler_autostart=True)
nonebot.init(apscheduler_config={
"apscheduler.timezone": "Asia/Shanghai"
})
插件使用格式:
#导入nonebot.require模块
from nonebot import require
#使用nonebot.require模块导入nonebot_plugin_apscheduler的scheduler
scheduler = require('nonebot_plugin_apscheduler').scheduler
#设置在几点启动脚本
@scheduler.scheduled_job('cron', hour='小时',minute='分钟')
#启动的脚本
async def run_every_2_hour():
'''
需要执行的代码
'''
而发送消息需要用到最开始提到的发送给指定对象方法
但是 bot 本身需要知道自己是谁:
driver = get_driver()
BOT_ID = str(driver.config.bot_id)
bot = driver.bots[BOT_ID]
拿到 BOT_ID 后,bot 就知道自己是谁了
万事具备,我们来写个简单的例子来练练手
例如,我想在每天中午 12 点发一条测试信息到群(924026546),便可以这样写:
from nonebot import on_command, require, get_driver
from nonebot.typing import T_State
from nonebot.adapters import Bot, Event
from nonebot.adapters.cqhttp.message import Message
import nonebot.adapters.cqhttp
import _thread
scheduler = require('nonebot_plugin_apscheduler').scheduler
@scheduler.scheduled_job('cron', hour=12,minute=0)
async def demo():
driver = get_driver()
BOT_ID = str(driver.config.bot_id)
bot = driver.bots[BOT_ID]
group_id=924026546
await bot.send_group_msg(group_id=group_id, message="测试消息")
好了,你已经完全掌握了,来试一试吧!.jpg
结合第一篇的日报发送,来写一篇定时发送最新日报的插件吧!
命运 2 每天凌晨 1 点更新内容,日报是 1:03 更新,我们就 1:05 更新吧
这样写(过长警告 ⚠):
from nonebot import on_command, on_startswith, require, get_driver
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.adapters import Bot, Event
from nonebot.adapters.cqhttp.message import Message
import nonebot.adapters.cqhttp
import _thread
import urllib3
import json
scheduler = require('nonebot_plugin_apscheduler').scheduler
m=5
h=1
@scheduler.scheduled_job('cron', hour=h,minute=m)
async def tm():
driver = get_driver()
BOT_ID = str(driver.config.bot_id)
bot = driver.bots[BOT_ID]
group_id=#这里写群号
try:
try:
url = 'http://www.tianque.top/d2api/today/'
r = urllib3.PoolManager().request('GET', url)
hjson = json.loads(r.data.decode())
img_url = hjson["img_url"]
#print(img_url)
cq = "[CQ:image,file=" + img_url + ",id=40000]"
msg=Message(cq)
await bot.send_group_msg(group_id=group_id, message=msg)
h=1
except:
h=h+1
url = 'http://www.tianque.top/d2api/today/'
r = urllib3.PoolManager().request('GET', url)
hjson = json.loads(r.data.decode())
error_url = hjson["error"]
msg="获取日报失败\nerror:\n"+error_url
await bot.send_group_msg(group_id=group_id, message=msg)
except :
h=h+1
msg="获取日报失败:\n服务器错误"
await bot.send_group_msg(group_id=group_id, message=msg)
直接改一下就能用了,是不是很简单(bushi
有参数传入的插件
官方文档:教程
我们在之前一直使用的是@响应器名.handle()
而要接受参数,或者在之后传入参数,或者判断参数格式错误后要求重新输入,就需要其他方法:
receive()
和got()
一般使用 got()就够用了
这个插件用了网上查的 BV 转 av 方法:
if AV[0:2] in ["BV"]:
table = 'fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF'
tr = {}
for i in range(58):
tr[table[i]] = i
s = [11, 10, 3, 8, 4, 6]
xor = 177451812
add = 8728348608
async def dec(x):
r = 0
for i in range(6):
r += tr[x[s[i]]] * 58 ** i
return "av" + str((r - add) ^ xor)
用了自己搭的 av 查封面的 api 接口:https://www.kamuxiy.top/demo/bilibiliapi/?AV_number=
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.adapters import Bot, Event
from nonebot.adapters.cqhttp.message import Message
import urllib3
import json
bphoto = on_command("/封面图", priority=5)
@bphoto.handle()
async def handle_first_receive(bot: Bot, event: Event, state: T_State):
args = str(event.get_message()).strip() # 首次发送命令时跟随的参数
if args:
state["AV"] = args # 如果用户发送了参数则直接赋值
@bphoto.got("AV", prompt="你想查询哪个视频的封面图呢?")
async def handle_city(bot: Bot, event: Event, state: T_State):
AV = state["AV"]
if AV[0:2] not in ["av", "BV"]:
await bphoto.reject("你想查询的AV或BV号无法查询,请重新输入!")
city_weather = await get_weather(AV)
await bphoto.finish(city_weather)
async def get_weather(AV: str):
try:
if AV[0:2] in ["BV"]:
table = 'fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF'
tr = {}
for i in range(58):
tr[table[i]] = i
s = [11, 10, 3, 8, 4, 6]
xor = 177451812
add = 8728348608
async def dec(x):
r = 0
for i in range(6):
r += tr[x[s[i]]] * 58 ** i
return "av" + str((r - add) ^ xor)
BV = await dec(AV)
url = 'https://www.kamuxiy.top/demo/bilibiliapi/?AV_number=' + BV
r = urllib3.PoolManager().request('GET', url)
hjson = json.loads(r.data.decode())
img_url = hjson['img_url']
cq = "[CQ:image,file=" + img_url + ",id=40000]"
return f"{AV}的封面图是...\n" + Message(cq)
else:
url = 'https://www.kamuxiy.top/demo/bilibiliapi/?AV_number=' + AV
r = urllib3.PoolManager().request('GET', url)
hjson = json.loads(r.data.decode())
img_url = hjson['img_url']
cq = "[CQ:image,file=" + img_url + ",id=40000]"
return f"{AV}的封面图是...\n" + Message(cq)
except:
return f"{AV}的封面图未找到\n可能是视频不存在" + AV
大概这样
got()可以判断"AV"是否在命令后,没有的话会发送 prompt 内的内容来重新单独获取"AV"
若"AV"已经赋值,便会执行 got()下的代码
其他就是之前讲到的内容了
后记
这篇补了几个最近用学到的内容写的插件,算是边学边用吧
帮隔壁三个地平线 4 群写了一个 annabot,最近也在逐渐完善中,期待一下吧!