admin管理员组

文章数量:1576375

nonebot2 插件编写指南(四)(从旧版迁移至 2.0.0-beta.2)

在 nb2 更新之后,许多未进行更新的插件均无法继续使用,包括之前几篇编写的简单插件。
在本篇中,将会对之前自己编写的插件进行新版本的适配。

更换协议适配器

在新版本的 nonebot 中,cqhttp 协议被弃用,如果你仍然使用的是 go-cqhttp 作为 qq 端,那么需要将协议改为 onebot。
使用脚手架安装时使用空格选择 onebot。
在 bot.py 中有以下片段即安装成功:

from nonebot.adapters.onebot.v11 import Adapter as ONEBOT_V11Adapter

和:

driver = nonebot.get_driver()
driver.register_adapter(ONEBOT_V11Adapter)

插件修改

新版本对于插件的影响不大,主要修改点为 import 导入点包和每个事件处理函数的部分。

修改 import 部分

以之前发的日报部分来举例,这是插件的 import 部分:

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

其中,cqhttp 有关的部分需要换成 onebot,Massage 部分需要更换来源,替换过后的样子:

from nonebot import on_command
from nonebot.rule import to_me
from nonebot.params import CommandArg
from nonebot.adapters.onebot.v11 import GroupMessageEvent,Bot,Message

其中nonebot.adaptersnonebot.typing的部分被弃用,取而代之的是nonebot.params和 onebot 协议适配器对应的nonebot.adapters.onebot.v11
而在老版本中常用的 Bot、Massage 和 Event 则归到了 onebot 之下。
而 event 也细分为群 event(GroupMessageEvent)和私聊 event(PrivateMessageEvent)。

修改事件响应器部分

若您的插件不需要使用 event 或者 bot 等来进行消息内容获取或 bot 设置,则可以直接跳过此部分

其实修改的部分只有 event 等数据的获取。
这是老的:

@today.handle()
async def handle_first_receive(bot: Bot, event: Event, state: T_State):

这是新的:

@today.handle()
async def handle_first_receive(event: GroupMessageEvent,message: Message = CommandArg()):

因为在新版中提供了一个新的方法:CommandArg(),这个方法将 Message 部分整合到了一起,提供了更方便的使用方法。
而 event 则可以根据消息来源来设置分开响应。
其他相关部分可以查看 nonebot 官网的 api 部分。

修改事件处理部分

在本插件中,事件处理部分暂无需要修改部分。若您的插件需要修改,请参考官方 api 文档。

若使用官方商店插件

在使用官方商店的第三方插件时,请注意查看此插件是否已适配新版本。
具体方法为:查看此插件 github 仓库,或者使用 pip 或 nb-cli 下载,进入 python 的 site-packages 文件夹下查看此插件源码。

此指南举例插件完整源码

命运 2 日报:

from nonebot import on_command
from nonebot.rule import to_me
from nonebot.params import CommandArg
from nonebot.adapters.onebot.v11 import GroupMessageEvent,Bot,Message

import urllib3
import json

today = on_command("today", aliases={'日报', }, priority=5)

@today.handle()
async def handle_first_receive(event: GroupMessageEvent,message: Message = CommandArg()):
    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"]

            cq = "[CQ:image,file=" + img_url + ",id=40000]"

            await today.send(Message(cq))
        except:
            url = 'http://www.tianque.top/d2api/today/'

            r = urllib3.PoolManager().request('GET', url)
            hjson = json.loads(r.data.decode())

            error_url = hjson["error"]
            await today.send("获取日报失败\n"+
                            "error:\n"+
                            error_url)
    except :
        await today.send("获取日报失败:\n服务器错误")

本文标签: 旧版插件指南beta