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()
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)]:
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"]}'