A session generator helper to create a telegram session.

This commit is contained in:
2025-10-03 16:49:19 -07:00
parent 57c8f55be9
commit ba9ca333d4
2 changed files with 41 additions and 1 deletions

View File

@@ -51,3 +51,5 @@ telethon_session.session-journal
session_name.session
session_name.session-journal
session.session
session_generator.py

38
session_generator.py Normal file
View File

@@ -0,0 +1,38 @@
import os
from telethon import TelegramClient
API_ID = int(os.environ.get("TG_API_ID", "0"))
API_HASH = os.environ.get("TG_API_HASH", "")
SESSION_PREFIX = os.environ.get("TG_SESSION", "telethon_session") # writes <prefix>.session in cwd
def _prompt_nonempty(prompt: str, default: str | None = None) -> str:
while True:
val = input(f"{prompt}{f' [{default}]' if default else ''}: ").strip()
if not val and default is not None:
return default
if val:
return val
print("Please enter a value.")
def main():
# If env vars are missing, ask interactively.
global API_ID, API_HASH, SESSION_PREFIX
if not API_ID:
api_id_str = _prompt_nonempty("Enter TG_API_ID (from my.telegram.org)")
try:
API_ID = int(api_id_str)
except ValueError:
raise SystemExit("TG_API_ID must be an integer.")
if not API_HASH:
API_HASH = _prompt_nonempty("Enter TG_API_HASH (from my.telegram.org)")
if not SESSION_PREFIX:
SESSION_PREFIX = _prompt_nonempty("Enter session prefix (file will be <prefix>.session)", "telethon_session")
client = TelegramClient(SESSION_PREFIX, API_ID, API_HASH)
client.start() # this will prompt for phone, code, and 2FA if needed
print(f"Session created: {SESSION_PREFIX}.session")
client.disconnect()
if __name__ == "__main__":
main()