Nonebot QQ机器人插件二:知乎热搜获取

QQ机器人插件二:知乎热搜获取

import nonebot
from nonebot import on_keyword
from nonebot.matcher import Matcher
from nonebot.adapters import Message
from nonebot.params import Arg, CommandArg, ArgPlainText

import requests

__plugin_name__ = 'news_hot'
__plugin_usage__ = '用法: 知乎热搜,根据输入的新闻编号返回新闻。'

news_hot = on_keyword({"知乎", "热搜","知乎热搜"})

url = 'https://api.vvhan.com/api/hotlist?type=zhihuHot'
res = requests.get(url).json()


@news_hot.handle()
async def _():
    global  res
    results = res['data']
    news = res["update_time"][:4] +"年" + res["update_time"][5:7] +"月"+ res["update_time"][8:10] + "日" + "知乎热榜\n"
    for i in range(7):
        news += ''.join(str(results[i]["index"]) + '.' + results[i]["title"] + '\n')
    await news_hot.send(f'{news}')

@news_hot.handle()
async def handle_first_receive(matcher: Matcher, args: Message = CommandArg()):
    plain_text = args.extract_plain_text()  # 首次发送命令时跟随的参数,例:知乎 1,则args为1
    print("plain_text",plain_text)
    if plain_text:
        matcher.set_arg(("news",args)) # 如果用户发送了参数则直接赋值

@news_hot.got("news", prompt="你想查看哪个新闻呢?")
async def handle_news(news: Message = Arg(), news_index: str = ArgPlainText("news")):
    if int(news_index)  not in [x for x in range(1,7)]:  # 如果参数不符合要求,则提示用户重新输入
        # 可以使用平台的 Message 类直接构造模板消息
        await news_hot.reject(news.template("你想查询的新闻编号{news_index} 暂不支持,请重新输入!"))

    news_desc = await get_news(news_index)
    await news_hot.finish(news_desc)


# 在这里编写获取具体新闻的函数
async def get_news(news: str) -> str:
    print("news",news)
    global res
    results = res['data']
    return f'{results[int(news) - 1]["index"]}. {results[int(news) - 1]["title"]}\n{results[int(news) - 1]["url"]}'

Nonebot QQ机器人插件二:知乎热搜获取_第1张图片

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