skip to Main Content

I am making this telegram script to be able to some telegram usernames into my telegram account. Here is my code below:

from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor

API_TOKEN = '675*********z9Q'
GROUP_CHAT_ID = -100123456789  # Replace with your group chat ID
USERNAMES_TO_ADD = ['Username1', 'Username2', 'Username3']

bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)

async def add_members_to_group(usernames):
    chat_id = GROUP_CHAT_ID
    added_usernames = []

    for username in usernames:
        try:
            user = await bot.get_chat_member(chat_id, username)
            await bot.promote_chat_member(chat_id, user.user.id)
            added_usernames.append(username)
        except Exception as e:
            print(f"Error adding {username}: {e}")

    return added_usernames

@dp.message_handler(commands=['addmembers'])
async def handle_add_members(message: types.Message):
    added_usernames = await add_members_to_group(USERNAMES_TO_ADD)

    if added_usernames:
        response_message = f'Members added successfully: {", ".join(added_usernames)}'
    else:
        response_message = 'No members added.'

    await message.reply(response_message)

if __name__ == '__main__':
    executor.start_polling(dp, skip_updates=True)

How can I change the code to be able to add those members to my group?

Or is there an alternative to go about it?

2

Answers


  1. Use from aiogram import Dispatcher
    instead of from aiogram.dispatcher import Dispatcher.

    Also executor is removed so it won’t work.

    Login or Signup to reply.
  2. Use aiogram Version 2 instead of Version 3.
    To switch to ‘aiogram’ version 2, run the following command:

    pip install --force-reinstall -v "aiogram==2.23.1"
    

    Import it as follows:

    from aiogram import Bot, Dispatcher, executor, types
    

    If you prefer to work with version 3, refer to this page:
    https://docs.aiogram.dev/en/dev-3.x/migration_2_to_3.html

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search