[Python] Telegram bot to send auto message every n hours with python-telegram-bot

Discussão em 'Python' iniciado por Stack, Setembro 29, 2024.

  1. Stack

    Stack Membro Participativo

    I am quite new in building bots so I created a very simple Telegram bot and it works great but can't figure out how to make the bot send messages every n minutes or n hours when /start_auto command is initiated.

    I made a workaround with while loop but it looks stupid and during the loop users won't be able to interact with the bot about other topics.

    I want users to be able to start and stop this scheduled task by commands such as /start_auto and /stop_auto.

    I know there are many other answered questions related to this topic but none of them seem to be working with my code.

    import logging
    import os
    import time

    from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

    logger = logging.getLogger(__name__)

    PORT = int(os.environ.get('PORT', '8443'))


    def start(update, context):
    """Sends a message when the command /start is issued."""
    update.message.reply_text('Hi!')


    def help(update, context):
    """Sends a message when the command /help is issued."""
    update.message.reply_text('Help!')


    def start_auto(update, context):
    """Sends a message when the command /start_auto is issued."""
    n = 0
    while n < 12:
    time.sleep(3600)
    update.message.reply_text('Auto message!')
    n += 1


    def error(update, context):
    """Logs Errors caused by Updates."""
    logger.warning('Update "%s" caused error "%s"', update, context.error)


    def main():
    TOKEN = 'TOKEN_GOES_HERE'
    APP_NAME = 'https://my-tele-test.herokuapp.com/'

    updater = Updater(TOKEN, use_context=True)

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("help", help))
    dp.add_handler(CommandHandler("start_auto", start_auto))

    # log all errors
    dp.add_error_handler(error)
    updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TOKEN, webhook_url=APP_NAME + TOKEN)
    updater.idle()


    if __name__ == '__main__':
    main()

    Continue reading...

Compartilhe esta Página