【问题标题】:Telegram Bot - how to send a daily messages?Telegram Bot - 如何发送每日消息?
【发布时间】: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


    【解决方案1】:

    停止作业队列将停止所有计划的作业(对于其他用户也是如此)。 而不是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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-17
      • 2016-05-09
      相关资源
      最近更新 更多