使用茉莉云 API 实现 NoneBot2 对话插件

本文将介绍如何使用 NoneBot2 开发一个插件,该插件可以调用茉莉云 API 进行对话,并能够回复艾特它的人,一次艾特可多次回复内容。

插件代码

import requests
from nonebot import on_command, CommandSession

# 茉莉云 API 接口地址
API_URL = "http://i.itpk.cn/api.php"

# 定义一个命令处理器
@on_command('chat', aliases=('对话',))
async def chat(session: CommandSession):
    # 获取对话内容
    text = session.get('text', prompt='你想对我说什么?')
    # 调用茉莉云 API 进行对话
    response = requests.get(API_URL, params={'question': text})
    # 获取回复内容
    reply = response.text.strip()
    # 发送回复消息
    await session.send(reply)

# chat命令的参数解析器
@chat.args_parser
async def _(session: CommandSession):
    stripped_arg = session.current_arg_text.strip()
    if stripped_arg:
        session.state['text'] = stripped_arg

# 启用插件
def enable_chat_plugin(app):
    chat.__plugin_name__ = 'chat'
    chat.__plugin_usage__ = '对话功能'
    app.on_command(chat.__plugin_name__, chat)

在你的 NoneBot2 实例中启用插件

from nonebot import get_bot
from chat_plugin import enable_chat_plugin

bot = get_bot()

enable_chat_plugin(bot)

bot.run()

使用方法

  1. 将以上代码保存为 chat_plugin.py 文件。
  2. 在你的 NoneBot2 项目中导入并启用该插件。
  3. 当有人发送 "对话" 或 "chat" 命令时,机器人会向茉莉云 API 发送问题,并将回复作为消息回复给用户。每次回复只需要发送一次 "对话" 命令即可。

注意

  • 茉莉云 API 接口地址可能需要根据实际情况进行修改。
  • 该插件只提供了一个简单的对话功能,你可以根据自己的需求进行扩展。
NoneBot2 插件:使用茉莉云 API 实现对话功能

原文地址: https://www.cveoy.top/t/topic/pCFv 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录