Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from bundle
Telegram MTProto MCP server with userbot watcher, chat/DM parser and context builders
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
session_string_generator.py
1#!/usr/bin/env python32"""3Telegram Session String Generator45This script generates a session string that can be used for Telegram authentication6with the Telegram MCP server. The session string allows for portable authentication7without storing session files.89Usage:10python session_string_generator.py1112Requirements:13- telethon14- python-dotenv1516Note on ID Formats:17When using the MCP server, please be aware that all `chat_id` and `user_id`18parameters support integer IDs, string representations of IDs (e.g., "123456"),19and usernames (e.g., "@mychannel").20"""2122import asyncio23import io24import os25import sys2627from dotenv import load_dotenv28from telethon import errors29from telethon.sessions import StringSession30from telethon.sync import TelegramClient3132load_dotenv()333435def _qr_login(client: TelegramClient) -> None:36import qrcode3738qr = client.qr_login()3940print("\n----- QR Code Login -----\n")4142qr_obj = qrcode.QRCode(border=1)43qr_obj.add_data(qr.url)44qr_obj.make(fit=True)45f = io.StringIO()46qr_obj.print_ascii(out=f, invert=True)47print(f.getvalue())4849print("Scan the QR code above with your Telegram app:")50print(" Open Telegram > Settings > Devices > Link Desktop Device\n")51print(f"Or open this link on a device where you're logged in:\n {qr.url}\n")52print(f"Expires at: {qr.expires.strftime('%H:%M:%S')}")53print("Waiting for you to scan...")5455try:56client.loop.run_until_complete(qr.wait(timeout=120))57except asyncio.TimeoutError:58print("\nQR code expired. Please try again.")59client.disconnect()60sys.exit(1)61except errors.SessionPasswordNeededError:62pw = input("\nTwo-factor authentication enabled. Please enter your password: ")63client.sign_in(password=pw)646566def _phone_login(client: TelegramClient) -> None:67phone = input("Please enter your phone (or bot token): ")6869try:70client.send_code_request(phone)71except errors.FloodWaitError as e:72print(f"\nFlood wait error; you must wait {e.seconds} seconds before trying again.")73client.disconnect()74sys.exit(1)75except errors.PhoneNumberInvalidError:76print("\nThe phone number is invalid.")77client.disconnect()78sys.exit(1)79except Exception as e:80print(f"\nError sending code: {e}")81client.disconnect()82sys.exit(1)8384code = input("\nPlease enter the code you received: ")85try:86client.sign_in(phone, code)87except errors.SessionPasswordNeededError:88pw = input("Two-factor authentication enabled. Please enter your password: ")89client.sign_in(password=pw)909192def main() -> None:93API_ID = os.getenv("TELEGRAM_API_ID")94API_HASH = os.getenv("TELEGRAM_API_HASH")9596if not API_ID or not API_HASH:97print("Error: TELEGRAM_API_ID and TELEGRAM_API_HASH must be set in .env file")98print("Create an .env file with your credentials from https://my.telegram.org/apps")99sys.exit(1)100101try:102API_ID = int(API_ID)103except ValueError:104print("Error: TELEGRAM_API_ID must be an integer")105sys.exit(1)106107print("\n----- Telegram Session String Generator -----\n")108print("This script will generate a session string for your Telegram account.")109print("The generated session string can be added to your .env file.")110print(111"\nYour credentials will NOT be stored on any server and are only used for local authentication.\n"112)113114print("Choose login method:")115print(" 1) QR code login (recommended -- scan from your Telegram app)")116print(" 2) Phone number + verification code")117method = input("\nEnter 1 or 2 [default: 1]: ").strip() or "1"118119try:120client = TelegramClient(StringSession(), API_ID, API_HASH)121client.connect()122123if not client.is_user_authorized():124if method == "1":125_qr_login(client)126else:127_phone_login(client)128129session_string = StringSession.save(client.session)130131print("\nAuthentication successful!")132print("\n----- Your Session String -----")133print(f"\n{session_string}\n")134print("Add this to your .env file as:")135print(f"TELEGRAM_SESSION_STRING={session_string}")136print("\nIMPORTANT: Keep this string private and never share it with anyone!")137138choice = input(139"\nWould you like to automatically update your .env file with this session string? (y/N): "140)141if choice.lower() == "y":142try:143with open(".env", "r") as file:144env_contents = file.readlines()145146session_string_line_found = False147for i, line in enumerate(env_contents):148if line.startswith("TELEGRAM_SESSION_STRING="):149env_contents[i] = f"TELEGRAM_SESSION_STRING={session_string}\n"150session_string_line_found = True151break152153if not session_string_line_found:154env_contents.append(f"TELEGRAM_SESSION_STRING={session_string}\n")155156with open(".env", "w") as file:157file.writelines(env_contents)158159print("\n.env file updated successfully!")160except Exception as e:161print(f"\nError updating .env file: {e}")162print("Please manually add the session string to your .env file.")163164client.disconnect()165166except Exception as e:167print(f"\nError: {e}")168print("Failed to generate session string. Please try again.")169sys.exit(1)170171172if __name__ == "__main__":173main()174