from aiogram import Bot, Dispatcher, types
from aiogram.filters import CommandStart
TOKEN = 'your_bot_token_here'
bot = Bot(token=TOKEN)
dp = Dispatcher()
group_list = []
async def is_bot_admin(group_id):
bot_status = await bot.get_chat_member(group_id, bot.id)
return bot_status.status
@dp.message(CommandStart())
async def handle_start(message: types.Message):
if message.chat.type in ['group', 'supergroup']:
group_list.append(message.chat.id)
await message.reply('Bot added to the group!')
@dp.message(lambda message: message.photo)
async def forward_photo(message: types.Message):
if message.chat.type == 'private':
for group_id in group_list:
if await is_bot_admin(group_id):
await message.copy_to(chat_id=group_id)
async def main():
await dp.start_polling(bot)
I’m trying to create a Telegram bot that automatically records the IDs of any group it joins. The goal is for the bot to forward private photos to every group where it’s an admin. Although I’ve built the foundation of the code, I’m stuck on detecting when the bot is added to a group and retrieving the group’s ID. Any guidance on how to accomplish this would be really appreciated. Thanks!
yo, i’ve done something similar before. u wanna use the chat_member update. it triggers when the bot’s status changes in a chat. here’s a quick example:
I’ve implemented a similar functionality in my Telegram bots. Instead of using the CommandStart handler, you should leverage the ‘chat_member’ update. This event fires when the bot’s status in a chat changes.
Here’s a snippet to get you started:
@dp.chat_member()
async def handle_chat_member(update: types.ChatMemberUpdated):
if update.new_chat_member.status in [‘member’, ‘administrator’]:
group_list.append(update.chat.id)
await bot.send_message(update.chat.id, ‘Bot added successfully!’)
elif update.new_chat_member.status == 'left':
if update.chat.id in group_list:
group_list.remove(update.chat.id)
This approach will automatically track when your bot is added to or removed from groups. Remember to periodically save the group_list to a database or file for persistence across bot restarts.
I’ve faced a similar challenge when developing Telegram bots. The key is to use the ‘my_chat_member’ update type, which is triggered when the bot’s status in a chat changes. Here’s how you can modify your code:
Add a new handler for ‘my_chat_member’ updates:
@dp.my_chat_member()
async def handle_my_chat_member(update: types.ChatMemberUpdated):
if update.new_chat_member.status == ‘member’:
group_list.append(update.chat.id)
await bot.send_message(update.chat.id, ‘Bot added to the group!’)
This handler will be called whenever the bot is added to a group. It checks if the bot’s new status is ‘member’, then adds the group ID to your list.
Remember to remove the group ID if the bot is kicked:
if update.new_chat_member.status == ‘left’:
if update.chat.id in group_list:
group_list.remove(update.chat.id)
This approach has worked well for me in several projects. Hope it helps!