Randomly Select User ID from Chat

  • Share this:

Code introduction


This function randomly selects a user from a specified user's chat and returns the user's ID. If the number of users in the chat exceeds 100, multiple requests are needed to get all users.


Technology Stack : Telethon

Code Type : Telethon API usage

Code Difficulty : Intermediate


                
                    
def generate_random_chat_id(user):
    from telethon.tl.functions.channels import GetUsersInChannelRequest
    from telethon.tl.types import InputPeerUser
    import random

    chat_id = user.id
    try:
        # Fetch all users in the chat
        response = user.client(GetUsersInChannelRequest(chat_id, 0, 100))
        # Randomly select a user from the chat
        selected_user = random.choice(response.users)
        # Return the random user's ID
        return selected_user.id
    except Exception as e:
        print(f"An error occurred: {e}")
        return None                
              
Tags: