返回 Skill 列表
extension
分类: 开发与工程需要 API Key

生成Telethon的session文件 可重复使用 避免登录过程中的交互 | Generate a session file for Telethon that can be reused to avoid interaction during login

生成可复用的 Telethon .session 文件,实现 Telegram 自动登录与交互,避免重复认证。

person作者: crazypeacehubclawhub

Telethon Session Generator

Generate a .session file to authenticate a Telegram user account via Telethon.

Prerequisites

  • telethon — install with pip install telethon (use venv if needed)
  • API credentials from https://my.telegram.org (api_id + api_hash)

Quick Start

Run the bundled script in interactive (PTY) mode — Telegram will send a login code and optionally ask for 2FA:

python3 scripts/login.py --api-id YOUR_ID --api-hash YOUR_HASH --phone "+86..."

The script prompts for:

  1. Login code — from Telegram app or SMS
  2. 2FA password — only if enabled on the account

On success, <session_name>.session is created in the working directory.

Key Notes

  • Session file is reusable — no need to re-login unless Telegram invalidates it
  • Do NOT commit .session files to version control (treat as secrets)
  • Bot token ≠ session — bots use bot_token= in Telethon, no session file needed
  • If pip install telethon fails on externally-managed Python, use a venv:
    python3 -m venv venv
    source venv/bin/activate
    pip install telethon
    

Using the Session File

from telethon import TelegramClient

client = TelegramClient('telegram_session', api_id, api_hash)
await client.start()  # auto-loads session, no prompt needed