-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup_telegram.py
More file actions
109 lines (91 loc) · 3.54 KB
/
setup_telegram.py
File metadata and controls
109 lines (91 loc) · 3.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
"""
CognivexAI · Telegram Auth — single persistent process
Keeps the TelegramClient alive between OTP send and sign-in.
Usage:
python3 setup_telegram.py +33759239589
(then paste code into .tg_code file when prompted)
"""
import sys, os, asyncio, time
from dotenv import load_dotenv, set_key
load_dotenv()
API_ID = int(os.getenv('TELEGRAM_API_ID', 0))
API_HASH = os.getenv('TELEGRAM_API_HASH', '')
ENV_PATH = os.path.join(os.path.dirname(__file__), '.env')
CODE_FILE = os.path.join(os.path.dirname(__file__), '.tg_code')
async def main():
from telethon import TelegramClient
from telethon.sessions import StringSession
if len(sys.argv) < 2:
print('Usage: python3 setup_telegram.py +33759239589')
return
phone = sys.argv[1]
# Clean up any old code file
if os.path.exists(CODE_FILE):
os.remove(CODE_FILE)
print(f'\n Connecting to Telegram...')
client = TelegramClient(StringSession(), API_ID, API_HASH)
await client.connect()
print(f' Sending OTP to {phone}...')
result = await client.send_code_request(phone)
phone_hash = result.phone_code_hash
print(f'\n ✓ OTP sent!')
print(f' Check your Telegram APP for the code.\n')
print(f' Waiting for code... (write it to .tg_code file)')
# Poll for the code file (keep client alive)
code = None
for _ in range(90): # wait up to 90 seconds
await asyncio.sleep(1)
if os.path.exists(CODE_FILE):
with open(CODE_FILE) as f:
code = f.read().strip()
os.remove(CODE_FILE)
break
if not code:
print(' ✗ Timed out waiting for code.')
await client.disconnect()
return
print(f' Got code: {code} — signing in...')
needs_2fa = False
try:
await client.sign_in(phone, code, phone_code_hash=phone_hash)
except Exception as e:
if 'SessionPasswordNeeded' in type(e).__name__:
needs_2fa = True
else:
print(f' ✗ Sign-in error: {e}')
await client.disconnect()
return
if needs_2fa:
pwd_file = os.path.join(os.path.dirname(__file__), '.tg_pwd')
if os.path.exists(pwd_file):
os.remove(pwd_file)
print(' 2FA required — waiting for password (up to 3 minutes)...')
pwd = None
for _ in range(180):
await asyncio.sleep(1)
if os.path.exists(pwd_file):
with open(pwd_file) as f:
pwd = f.read().strip()
os.remove(pwd_file)
break
if not pwd:
print(' ✗ Timed out waiting for 2FA password.')
await client.disconnect()
return
print(f' Got 2FA password — completing sign-in...')
try:
await client.sign_in(password=pwd)
except Exception as e:
print(f' ✗ 2FA failed: {e}')
await client.disconnect()
return
# Only save session after full successful auth
session_string = client.session.save()
set_key(ENV_PATH, 'TELEGRAM_SESSION', session_string)
await client.disconnect()
print('\n╔══════════════════════════════════════╗')
print('║ ✓ Telegram authenticated! ║')
print('║ Session saved to .env ║')
print('╚══════════════════════════════════════╝\n')
if __name__ == '__main__':
asyncio.run(main())