【发布时间】:2020-06-11 20:08:07
【问题描述】:
我在 python 上的电报机器人有问题。机器人必须每天在规定的时间发送有关天气的信息,在我的情况下是上午 9 点。但是机器人不能正常工作。它在开始后的第一天仅发送一次消息,并且由于某些原因在第二天的 13:07 发送消息(我不明白为什么)。之后它什么也不发送。
这是完整的代码,除了配置文件:
import requests
import pytz
from telegram import Bot, Update
from datetime import time, tzinfo, timezone, datetime
from telegram.ext import Updater, CommandHandler, Filters
from config import TG_TOKEN, PROXY, WEATHER_APP_ID, CITY
class Weather:
@staticmethod
def get_weather():
try:
res = requests.get(
"http://api.openweathermap.org/data/2.5/find",
params={'q': CITY, 'units': 'metric', 'lang': 'ru', 'APPID': WEATHER_APP_ID}
)
data = res.json()
item = data['list'][0]
main = item['main']
weather = item['weather'][0]
weather_desc = weather['description']
temp = main['temp']
feels_like = main['feels_like']
return {
'desc': weather_desc,
'temp': temp,
'feels_like': feels_like
}
except Exception as e:
print("Exception (find):", e)
pass
def message_handler(bot: Bot, job):
weather = Weather().get_weather()
desc = weather['desc']
temp = round(weather['temp'])
feels_like = round(weather['feels_like'])
reply_text = f'{temp}°C {desc} {feels_like}°C'
bot.send_message(
chat_id = job.context['chat_id'],
text = reply_text,
parse_mode= "Markdown"
)
def callback_timer(bot, update, job_queue):
d = datetime.now()
timezone = pytz.timezone("Europe/Moscow")
d_aware = timezone.localize(d)
context = {
'chat_id': update.message.chat_id,
}
notify_time = time(9, 0, 0, 0, tzinfo=d_aware.tzinfo)
bot.send_message(chat_id=update.message.chat_id, text='Starting!')
job_queue.run_daily(message_handler, notify_time, context=context)
def stop_timer(bot, update, job_queue):
bot.send_message(chat_id=update.message.chat_id, text='Stoped!')
job_queue.stop()
def main():
bot = Bot(
token=TG_TOKEN,
base_url=PROXY
)
updater = Updater(
bot=bot,
)
updater.dispatcher.add_handler(CommandHandler('start', callback_timer, pass_job_queue=True))
updater.dispatcher.add_handler(CommandHandler('stop', stop_timer, pass_job_queue=True))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
bot在https://www.pythonanywhere.com/这里有服务,并且一直正常工作。
【问题讨论】:
标签: python telegram telegram-bot python-telegram-bot