Search code examples
pythontelethon

how to set a folder to save telethon sessions in it


I have a code:

client = TelegramClient(
    "new_session", 
    api_id=CONFIG["client_api_id"], 
    api_hash=CONFIG["client_api_hash"]
)

so how i can save the "new_session.session" in another folder


Solution

  • Just pass the path to the client, relative or absolute.

    client = TelegramClient(
        "relative/path/to/new_session", 
        api_id=CONFIG["client_api_id"], 
        api_hash=CONFIG["client_api_hash"]
    )
    
    client = TelegramClient(
        "/absolute/path/to/new_session", 
        api_id=CONFIG["client_api_id"], 
        api_hash=CONFIG["client_api_hash"]
    )
    

    To avoid errors by paths with / or \ among different systems, I prefer to use the pathlib module.

    from pathlib import Path
    
    client = TelegramClient(
        str(Path("path/to/new_session")), 
        api_id=CONFIG["client_api_id"], 
        api_hash=CONFIG["client_api_hash"]
    )
    

    The path to the session file must exist before trying to instantiate the TelegramClient.