Telegram Bot - how to send a daily messages?

Viewed 1749

I have a problem with my telegram bot on python. Bot has to send information about weather every day in defined time, in my case at 9 am. But bot doesn’t work correctly. It sends a message only 1 time in a first day after starting and for some reasons at 13:07 in a second day (I don’t understand why). After that it sends nothing.

this is the full code, except configuration file:

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 has service here https://www.pythonanywhere.com/, and it works all the time properly.

1 Answers

Stopping the jobqueue will stop all the scheduled jobs (for other users as well). Instead of job_queue.stop(), name the jobs and stop them individually using its name. That's the reason for you not getting the message/alert, since other user might have used /stop

Example,

job_queue.run_daily(message_handler, notify_time, context=context, name = 'daily'+str(update.message.chat_id))

To stop its execution, use

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
Related