Random User Agent Generation with Telethon for Telegram API

  • Share this:

Code introduction


The function uses the Telethon library to generate a random user agent string and creates a Telegram API request to update the user's profile.


Technology Stack : Telethon

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_user_agent():
    import random
    from telethon.tl.functions.account import UpdateProfileRequest
    from telethon.tl.types import InputPeerUser

    # Generate a random user agent for Telegram API requests
    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.152 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',
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36'
    ]
    
    # Randomly select a user agent
    selected_user_agent = random.choice(user_agents)
    
    # Create a random user agent profile
    user_agent_profile = UpdateProfileRequest(
        phone=None, 
        first_name='Random', 
        last_name='User', 
        about='Random User', 
        photo=None, 
        user=InputPeerUser('me', int('0'), 'user_agent')
    )
    
    return selected_user_agent, user_agent_profile                
              
Tags: