3

I'm trying to send a message using Python-Telegram-Bot without waiting for a user response but can't get it to work and I get no errors.

Code:
def echo(context):
    context.bot.send_message(chat_id=-516017547, text='test') 
    #chat_id is the group id I found by going to:
    #https://api.telegram.org/bot<MY_API>/getUpdates

def main():
    updater = Updater(API)
    dp = updater.dispatcher

    echo_handler = MessageHandler(Filters.text & (~Filters.command), echo)
    dp.add_handler(echo_handler)

    updater.start_polling()
    updater.idle()

main()

1 Answer 1

8

In python-telegram-bot, the handlers are there to handle incoming updates - and nothing else. However, to call a bot method, you just need an instance of telegram.Bot. In your echo function, that's available as context.bot. However, it's also available in main as updater.bot or updater.dispatcher.bot. Note that you can also use a bot instance without Updater at all:

from telegram import Bot
bot = Bot(TOKEN)
bot.send_message(...)

PS: if you want to use echo as callback for MessageHandler, it must accept exactly to arguments update and context.


Update: This reply was written for PTB <= v13.x. Since v20.0, PTB is based on the asyncio framework, which make the above snippet invalid. Please have a look at PTBs wiki for an introduction on how this works now.


Disclaimer: I'm currently the maintainer of python-telegram-bot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.