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} 暂不支持,请重新输入!"


在这里插入图片描述

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值