Random User Agent Selection and User Request Simulation

  • Share this:

Code introduction


This function randomly selects a user agent and simulates a request to get user information. This is usually used to simulate network requests from different devices.


Technology Stack : Telethon

Code Type : Telethon API usage

Code Difficulty : Intermediate


                
                    
def random_user_agent():
    from telethon.tl.functions.users import GetUsersRequest
    from telethon.tl.types import InputPeerUser
    from random import choice

    # List of possible user agents
    user_agents = [
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
        "Mozilla/5.0 (Linux; Android 10; SM-A505FN) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Mobile Safari/537.36",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15"
    ]

    # Randomly select a user agent
    selected_user_agent = choice(user_agents)

    # Simulate a request to get a list of users
    client = telethon.Client()
    client.start()
    user = client(GetUsersRequest([InputPeerUser("user123", "123456")]))
    client.stop()

    # Return the selected user agent
    return selected_user_agent                
              
Tags: