Files

62 lines
2.2 KiB
Python

#!/usr/bin/env python3
"""Telegram 天气预报机器人"""
import os
import requests
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes
# 从环境变量获取 Token 和 API Key
BOT_TOKEN = os.environ.get("BOT_TOKEN", "your_bot_token_here")
WEATHER_API_KEY = os.environ.get("WEATHER_API_KEY", "your_api_key_here")
WEATHER_URL = "https://api.openweathermap.org/data/2.5/weather"
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(
"🌤 天气预报机器人\n\n"
"使用方法:\n"
"/weather 城市名 - 查询天气\n"
"/help - 查看帮助"
)
async def weather(update: Update, context: ContextTypes.DEFAULT_TYPE):
city = " ".join(context.args) if context.args else "Beijing"
try:
params = {"q": city, "appid": WEATHER_API_KEY, "units": "metric", "lang": "zh_cn"}
r = requests.get(WEATHER_URL, params=params, timeout=10)
data = r.json()
if r.status_code == 200:
temp = data["main"]["temp"]
desc = data["weather"][0]["description"]
humidity = data["main"]["humidity"]
wind = data["wind"]["speed"]
await update.message.reply_text(
f"📍 {city} 天气\n"
f"🌡 温度:{temp}°C\n"
f"🌥 天气:{desc}\n"
f"💧 湿度:{humidity}%\n"
f"💨 风速:{wind} m/s"
)
else:
await update.message.reply_text(f"❌ 未找到城市「{city}」")
except Exception as e:
await update.message.reply_text(f"❌ 查询失败:{e}")
async def help_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(
"📖 帮助\n\n"
"/start - 开始使用\n"
"/weather <城市> - 查询天气\n"
"/help - 查看帮助"
)
def main():
app = Application.builder().token(BOT_TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("weather", weather))
app.add_handler(CommandHandler("help", help_cmd))
print("Bot started...")
app.run_polling()
if __name__ == "__main__":
main()