Creating a Python bot to remove users from a Telegram group

I’m working on a Python bot for Telegram. I want it to remove users from a group when certain conditions are met. The exact conditions aren’t important right now.

I found a function called Bot.ban_chat_member() that can remove users. But it needs their user IDs to work. The problem is I only have their usernames.

Does anyone know how to get a user’s ID from their username in Telegram? I’m using the python-telegram-bot library.

I’ve looked through the library docs but couldn’t find a clear answer. Any help would be great!

Here’s a basic example of what I’m trying to do:

from telegram.ext import Updater, CommandHandler

def kick_user(update, context):
    username = 'example_user'
    user_id = get_user_id(username)  # This is the part I need help with
    context.bot.ban_chat_member(chat_id=update.effective_chat.id, user_id=user_id)

def main():
    updater = Updater('YOUR_BOT_TOKEN', use_context=True)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler('kick', kick_user))
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

Thanks in advance for any suggestions!

While the previous suggestion works, it might be inefficient for large groups. An alternative approach is to use the getChatMember method, which is more direct:

def kick_user(update, context):
    username = 'example_user'
    chat_id = update.effective_chat.id
    
    try:
        member = context.bot.get_chat_member(chat_id, '@' + username)
        context.bot.ban_chat_member(chat_id=chat_id, user_id=member.user.id)
    except telegram.error.BadRequest:
        context.bot.send_message(chat_id=chat_id, text=f'Unable to find or remove {username}.')

This method is faster and more efficient, especially for larger groups. It directly queries the specific user, reducing unnecessary data retrieval. Remember to import the necessary telegram exceptions to handle potential errors gracefully.

hey, i had a similar problem before. u can try using the getChat method to get the chat info first, then extract the user ID from there. somethin like this:

def kick_user(update, context):
    username = 'example_user'
    chat = context.bot.getChat('@' + username)
    user_id = chat.id
    context.bot.ban_chat_member(chat_id=update.effective_chat.id, user_id=user_id)

hope that helps! lmk if u need anything else

I’ve tackled a similar issue before, and there’s a workaround you can use. Instead of trying to get the user ID directly from the username, you can fetch all the members of the group and then find the matching user.

Here’s how you could modify your code:

def kick_user(update, context):
    username = 'example_user'
    chat_id = update.effective_chat.id
    
    # Get all members of the chat
    members = context.bot.get_chat_members(chat_id)
    
    # Find the user with the matching username
    target_user = next((member for member in members if member.user.username == username), None)
    
    if target_user:
        context.bot.ban_chat_member(chat_id=chat_id, user_id=target_user.user.id)
    else:
        context.bot.send_message(chat_id=chat_id, text=f'User {username} not found in the group.')

This approach might be a bit slower for large groups, but it’s reliable. Just remember to handle potential exceptions, like when the bot doesn’t have the necessary permissions. Hope this helps!