Home > Blockchain >  How I can do a send message task inside a dispatcher.run_async() using python-telegram-bot?
How I can do a send message task inside a dispatcher.run_async() using python-telegram-bot?

Time:03-10

I develop a telegram bot using the python-telegram-bot module. I attempt to run a function without executing it using dispatcher.run_async(myfunction) but how I can do a task for example sending a message from inside the dispatcher.run_async()?

I have all the users id in my database. And this is the snippet of my code.

import telegram
from telegram.ext import Updater

def myfunction():
    # bot.send_message(text='Hello, World',chat_id=<user_id>)

def main():
    """Start the bot."""
    # Create the Updater and pass it your bot's token.
    updater = Updater("TOKEN")

    # Get the dispatcher to register handlers
    dispatcher = updater.dispatcher
    dispatcher.run_async(myfunction)

    # Start the Bot
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

CodePudding user response:

Not sure if this is the intended way, but you can pass the bot the the function by passing it to run_async:

dispatcher.run_async(myFunction, updater.bot)

def myfunction(bot):
    bot.send_message(text='Hello, World',chat_id=123456789)

import telegram
from telegram.ext import Updater

def myfunction(bot):
    bot.send_message(text='Hello, World',chat_id=123456789)

def main():
    """Start the bot."""
    # Create the Updater and pass it your bot's token.
    updater = Updater("<MY-BOT-TOKEN>")

    # Get the dispatcher to register handlers
    dispatcher = updater.dispatcher
    dispatcher.run_async(myfunction, updater.bot)

    # Start the Bot
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()
  • Related