Nonebot QQ机器人插件一:实时天气获取

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({"天气", "天气预报"})
# on_keyword是接收某关键词的意思,api

@weather.handle()
async def handle_first_receive(matcher: Matcher, args: Message = CommandArg()):
    plain_text = args.extract_plain_text()  # 首次发送命令时跟随的参数,例:/天气 上海,则args为上海
    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'] = city
    params = 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} 暂不支持,请重新输入!"


Nonebot QQ机器人插件一:实时天气获取_第1张图片

你可能感兴趣的:(qq机器人,python,开发语言)