利用TeleBot()创建一个天气查询机器人
发布时间:2024-01-11 08:05:46
TeleBot()是一个Python库,用于创建一个天气查询机器人。以下是一个使用例子,其中包括创建机器人、设置命令、发送请求和获取天气信息:
import telebot
import requests
# 在Telegram上创建一个机器人
bot = telebot.TeleBot('YOUR_TELEGRAM_BOT_TOKEN')
# 设置命令,当用户发送/start时,回复一条欢迎消息
@bot.message_handler(commands=['start'])
def send_welcome(message):
bot.reply_to(message, '欢迎使用天气查询机器人!请发送您要查询的城市名。')
# 设置命令,当用户发送/stop时,回复一条退出消息并停止机器人
@bot.message_handler(commands=['stop'])
def send_goodbye(message):
bot.reply_to(message, '再见!')
bot.stop_polling()
# 处理用户发送的文本消息
@bot.message_handler(func=lambda message: True)
def send_weather(message):
# 获取用户发送的城市名
city = message.text
# 发送请求到天气API,获取天气信息
weather_api_key = 'YOUR_WEATHER_API_KEY'
weather_api_url = f'http://api.weatherapi.com/v1/current.json?key={weather_api_key}&q={city}'
response = requests.get(weather_api_url)
weather_data = response.json()
# 提取天气信息
location = weather_data['location']['name']
temperature = weather_data['current']['temp_c']
condition = weather_data['current']['condition']['text']
# 构造回复消息
reply = f'当前天气状况:{condition}
{location}的温度:{temperature}摄氏度'
# 发送回复消息给用户
bot.reply_to(message, reply)
# 启动机器人
bot.polling()
上述代码中,首先需要替换YOUR_TELEGRAM_BOT_TOKEN为你在Telegram上创建的机器人的令牌。然后,替换YOUR_WEATHER_API_KEY为你的天气API密钥,可以在[WeatherAPI](https://www.weatherapi.com/)上注册获取。
通过上述代码,我们创建了一个天气查询机器人。用户可以通过发送城市名给机器人来查询该城市的天气情况。当用户发送/start命令时,机器人会回复一条欢迎消息;发送/stop命令时,机器人会回复一条退出消息并停止运行。
