Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Telegram Python Bot | Event when Bot is added to a group

i am developing a python script for my telegram right now. The problem is:

How do I know when my bot is added to a group? Is there an Event or something else for that? I want the Bot to send a message to the group he´s beeing added to which says hi and the functions he can.

I dont know if any kind of handler is able deal with this.

like image 508
community_guido Avatar asked Dec 28 '25 23:12

community_guido


2 Answers

Very roughly, you would need to do something like this: register an handler that filters only service messages about new chat members. Then check if the bot is one of the new chat members.

from telegram.ext import Updater, MessageHandler, Filters


def new_member(bot, update):
    for member in update.message.new_chat_members:
        if member.username == 'YourBot':
            update.message.reply_text('Welcome')

updater = Updater('TOKEN')

updater.dispatcher.add_handler(MessageHandler(Filters.status_update.new_chat_members, new_member))

updater.start_polling()
updater.idle()
like image 54
mcont Avatar answered Dec 30 '25 14:12

mcont


With callbacks (preferred)

As of version 12, the preferred way to handle updates is via callbacks. To use them prior to version 13 state use_context=True in your Updater. Version 13 will have this as default.

from telegram.ext import Updater, MessageHandler, Filters

def new_member(update, context):
    for member in update.message.new_chat_members:
        if member.username == 'YourBot':
            update.message.reply_text('Welcome')

updater = Updater('TOKEN', use_context=True)  # use_context will be True by default in version 13+

updater.dispatcher.add_handler(MessageHandler(Filters.status_update.new_chat_members, new_member))

updater.start_polling()
updater.idle()

Please note that the order changed here. Instead of having the update as second, it is now the first argument. Executing the code below will result in an Exception like this:

AttributeError: 'CallbackContext' object has no attribute 'message'

Without callbacks (deprecated in version 12)

Blatantly copying from mcont's answer:

from telegram.ext import Updater, MessageHandler, Filters


def new_member(bot, update):
    for member in update.message.new_chat_members:
        if member.username == 'YourBot':
            update.message.reply_text('Welcome')

updater = Updater('TOKEN')

updater.dispatcher.add_handler(MessageHandler(Filters.status_update.new_chat_members, new_member))

updater.start_polling()
updater.idle()
like image 32
Don Fruendo Avatar answered Dec 30 '25 16:12

Don Fruendo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!