community_guido
community_guido

Reputation: 21

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.

Upvotes: 2

Views: 7996

Answers (2)

Don Fruendo
Don Fruendo

Reputation: 350

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()

Upvotes: 3

mcont
mcont

Reputation: 1922

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()

Upvotes: 6

Related Questions