Skip to main content

三:查询天气

main.py
import re

import httpx

from mirai import Mirai, WebSocketAdapter, FriendMessage, GroupMessage, At, Plain

API_KEY = '心知天气的私钥'

async def query(city: str) -> str:
"""查询天气数据。"""
async with httpx.AsyncClient() as client:
try:
resp = await client.get(f'https://api.seniverse.com/v3/weather/now.json', params={
'key': API_KEY,
'location': city,
'language': 'zh-Hans',
'unit': 'c',
})
resp.raise_for_status()
data = resp.json()
return f'当前{data["results"][0]["location"]["name"]}天气为' \
f'{data["results"][0]["now"]["text"]},' \
f'气温{data["results"][0]["now"]["temperature"]}℃。'
except (httpx.NetworkError, httpx.HTTPStatusError, KeyError):
return f'抱歉,没有找到{city}的天气数据。'

if __name__ == '__main__':
bot = Mirai(
qq=12345678, # 改成你的机器人的 QQ 号
adapter=WebSocketAdapter(
verify_key='yirimirai', host='localhost', port=8080
)
)

@bot.on(FriendMessage)
def on_friend_message(event: FriendMessage):
if str(event.message_chain) == '你好':
return bot.send(event, 'Hello, World!')

@bot.on(GroupMessage)
def on_group_message(event: GroupMessage):
if At(bot.qq) in event.message_chain:
return bot.send(event, [At(event.sender.id), '你在叫我吗?'])

@bot.on(GroupMessage)
async def weather_query(event: GroupMessage):
# 从消息链中取出文本
msg = "".join(map(str, event.message_chain[Plain]))
# 匹配指令
m = re.match(r'^查询天气\s*(\w+)\s*$', msg.strip())
if m:
# 取出指令中的地名
city = m.group(1)
await bot.send(event, '查询中……')
# 发送天气消息
await bot.send(event, await query(city))

bot.run()