QQ机器人插件一:实时天气获取
import nonebot
from nonebot import on_command,on_keyword
from nonebot.rule import to_me
from nonebot.matcher import Matcher
from nonebot.adapters import Message
from nonebot.params import Arg, CommandArg, ArgPlainText
import json,urllib
from urllib.parse import urlencode
from urllib.request import urlopen__plugin_name__ = 'weather'
__plugin_usage__ = '用法: 天气预报,根据输入的城市返回当日天气。'weather = on_keyword({"天气", "天气预报"})
@weather.handle()
async def handle_first_receive(matcher: Matcher, args: Message = CommandArg()):plain_text = args.extract_plain_text() if plain_text:matcher.set_arg(("city",args)) @weather.got("city", prompt="你想查询哪个城市的天气呢?")
async def handle_city(city: Message = Arg(), city_name: str = ArgPlainText("city")):city_weather = await get_weather(city_name)await weather.finish(city_weather)
async def get_weather(city: str) -> str:params = {'app': 'weather.today','cityNm': '北京','appkey': ' ','sign': '自己申请','format': 'json',}url = 'http://api.k780.com'params['cityNm'] = cityparams = urlencode(params)f = urlopen('%s?%s' % (url, params))nowapi_call = f.read()a_result = json.loads(nowapi_call)if a_result:if a_result['success'] != '0':result = a_result['result']return f"日期: {result['days']}\n星期:{result['week']}\n城市:{result['citynm']}\n温度范围:{result['temperature']}\n实时温度:{result['temperature_curr']}\n天气:{result['weather']}"else:return f"你想查询的城市 {city} 暂不支持,请重新输入!"
![在这里插入图片描述](https://img-blog.csdnimg.cn/43429852f46144da94c512d1ab8b46e9.jpeg#pic_center)