commit 984bb893ebef77689105bce07faed40cda3c8109 Author: demo Date: Sun Sep 27 18:35:10 2026 +0800 Initial commit: Telegram 天气预报机器人 diff --git a/README.md b/README.md new file mode 100644 index 0000000..5474180 --- /dev/null +++ b/README.md @@ -0,0 +1,35 @@ +# Weather Bot + +Telegram 天气预报机器人,支持查询全球城市天气。 + +## 功能 + +- 🌤 查询指定城市实时天气 +- 🌡 显示温度、湿度、风速 +- 🌍 支持全球城市 + +## 安装 + +```bash +pip install -r requirements.txt +``` + +## 配置 + +设置环境变量: +```bash +export BOT_TOKEN="your_telegram_bot_token" +export WEATHER_API_KEY="your_openweathermap_api_key" +``` + +## 运行 + +```bash +python3 bot.py +``` + +## 使用 + +- `/start` - 开始使用 +- `/weather 北京` - 查询北京天气 +- `/help` - 查看帮助 diff --git a/bot.py b/bot.py new file mode 100644 index 0000000..4e7a6fb --- /dev/null +++ b/bot.py @@ -0,0 +1,61 @@ +#!/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() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..e145aaf --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +python-telegram-bot>=20.0 +requests>=2.28