Auto-detecting group IDs when bot joins Telegram groups with aiogram

I’m working on a Telegram bot that should automatically track which groups it gets added to. Right now I have to manually add group IDs to my list.

telegram_bot = Bot(token=BOT_TOKEN)
dispatcher = Dispatcher()
group_list = []

async def verify_admin_status(group_id):
    bot_member = await telegram_bot.get_chat_member(group_id, telegram_bot.id)
    status = bot_member.status
    return status

@dispatcher.message(F.photo)
async def process_image(msg: types.Message):
    for current_group in group_list:
        admin_check = await verify_admin_status(current_group)
        if msg.chat.type == 'private' and admin_check:
            await msg.copy_to(chat_id=current_group)

async def start_bot():
    await dispatcher.start_polling(telegram_bot)

The bot works fine for forwarding private images to groups where it has admin rights. But I need to populate the group_list by hand which is not practical. How can I make the bot automatically detect and store group IDs when it gets added to new groups?

You need to handle the my_chat_member update to detect when your bot joins or leaves groups. This fires whenever the bot’s membership status changes.

from aiogram.filters import ChatMemberUpdatedFilter

@dispatcher.my_chat_member(ChatMemberUpdatedFilter(member_status_changed=MEMBER))
async def bot_added_to_group(event: types.ChatMemberUpdated):
    if event.new_chat_member.status in ['administrator', 'member']:
        group_id = event.chat.id
        if group_id not in group_list:
            group_list.append(group_id)
            # Save to database or file here
    elif event.new_chat_member.status in ['left', 'kicked']:
        if event.chat.id in group_list:
            group_list.remove(event.chat.id)

If you’re using webhooks, enable the ChatMember update in your webhook settings. Polling handles this automatically. Don’t forget to save the group list to a database or file so it survives restarts.

The my_chat_member handler above works, but here’s the thing - when your bot restarts, group_list goes empty unless you save it somewhere. I’d use a simple JSON file or SQLite database for the group IDs. Also, wrap your get_chat_member call in verify_admin_status with error handling since it’ll throw exceptions if the bot loses group access. You can catch those exceptions and auto-remove the group from your list. One more thing - if your bot’s already in groups before deploying this handler, add a startup routine to check existing chats.

Actually, there’s another approach - use middleware to catch all incoming messages and automatically add new group IDs to your list. Just check if msg.chat.type is ‘group’ or ‘supergroup’ and add the chat ID if it’s not already there. You won’t need separate handlers and it’ll work even if you miss the initial join event.