我在python上的电报机器人有问题。 Bot必须每天在规定的时间(例如我的上午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()
机器人在https://www.pythonanywhere.com/处提供服务,并且一直可以正常工作。
答案 0 :(得分:0)
停止作业队列将停止所有计划的作业(其他用户也是如此)。
为作业命名,并使用其名称分别停止job_queue.stop()
。这就是您未收到消息/警报的原因,因为其他用户可能已使用/stop
示例
job_queue.run_daily(message_handler, notify_time, context=context, name = 'daily'+str(update.message.chat_id))
要停止执行,请使用
to_remove = job_queue.get_jobs_by_name('daily'+str(update.message.chat_id)) # This will return a tuple of jobs
to_remove[0].schedule_removal() #It will be removed without executing its callback function again