Telegram Bot - 如何发送每日消息?

Telegram Bot - how to send a daily messages?

我在 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()

bot 在这里 https://www.pythonanywhere.com/ 有服务,它一直正常工作。

停止作业队列将停止所有计划的作业(对于其他用户也是如此)。 代替 job_queue.stop(),命名作业并使用其名称单独停止它们。这就是你没有得到 message/alert 的原因,因为其他用户可能使用了 /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