nonebot自定义天气查询 plugin
问了gpt才知道 原来可以用多个 Commansession 形成一个嵌套形式 每个命令(params)用一个 异步函数实现即可
不得不说 gpt还是6的(一个号每天可以80次 我有3个号… 真香.jpg)
from nonebot import on_command, CommandSession
from nonebot import on_natural_language, NLPSession, IntentCommand
from nonebot import *
from jieba import posseg
# from nonebot.adapters.cqhttp import Bot, Event
import json
# 自然语言处理
# from .data_source import get_weather_of_city
from .data_source import *
@on_command('weather', aliases=('天气', '天气预报', '查天气'))
async def weather(session: CommandSession):
city = session.current_arg_text.strip()
if not city:
city = (await session.aget(prompt='你想查询哪个城市的天气呢?')).strip()
while not city:
city = (await session.aget(prompt='要查询的城市名称不能为空呢,请重新输入')).strip()
# day = await session.aget(prompt='请输入查询天数(1~15)').strip()
# while not day.isdigit():
# day = await session.get(prompt='请输入要查询的天数(0~15)')
# day = int(day)
check = await is_in(city=city)
if check == 114514 :
await session.send(f'查询{city}的天气信息失败, 请重新输入查询')
return
if check == -114514:
await session.send(f'{city}的城市信息不存在, 请重新输入查询')
return
day = await get_day(session)
day = int(day)
weather_report = await get_weather_of_city(city,day)
await session.send(weather_report)
async def get_day(session: CommandSession):
days = await session.aget(prompt='请输入你想要查询的天数:')
while not str(days).isdigit():
days = await session.aget(prompt='请输入有效的天数:')
return int(days)
# on_natural_language 装饰器将函数声明为一个自然语言处理器
# keywords 表示需要响应的关键词,类型为任意可迭代对象,元素类型为 str
# 如果不传入 keywords,则响应所有没有被当作命令处理的消息
@on_natural_language(keywords = {'天气','weather'}, only_to_me = False)
async def _(session: NLPSession):
# 去掉消息首尾的空白符
stripped_msg = session.msg_text.strip()
# 对消息进行分词和词性标注
words = posseg.lcut(stripped_msg)
city = None
# 遍历 posseg.lcut 返回的列表
for word in words:
# 每个元素是一个 pair 对象,包含 word 和 flag 两个属性,分别表示词和词性
if word.flag == 'ns':
# ns 词性表示地名
city = word.word
break
# 返回意图命令,前两个参数必填,分别表示置信度和意图命令名
return IntentCommand(90.0, 'weather', current_arg=city or '')

浙公网安备 33010602011771号