Spaces:
Paused
Paused
Update app.py
Browse files12345678910111276 unmodified lines899091929394955 unmodified lines1011021031041051061074 unmodified lines11211311411511611711813 unmodified lines13213313413513613733 unmodified lines171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221from flask import Flask, request, jsonify, render_template_string, send_from_directoryfrom telethon.sync import TelegramClientfrom telethon import eventsimport osimport sqlite3import hashlibimport asynciofrom pathlib import Pathapp = Flask(__name__)API_ID = '22328650'76 unmodified lines</div><script>let phone = '';let phoneCodeHash = ''; // Added to store phone_code_hashasync function startLogin() {phone = document.getElementById('phone').value;5 unmodified linesconst result = await response.json();alert(result.message);if (result.success) {phoneCodeHash = result.phone_code_hash; // Store the received hashdocument.getElementById('code').style.display = 'inline';document.getElementById('submitCode').style.display = 'inline';}4 unmodified linesconst response = await fetch('/login', {method: 'POST',headers: { 'Content-Type': 'application/json' },// Pass phone_code_hash herebody: JSON.stringify({ phone, code, phone_code_hash: phoneCodeHash, step: 'code' })});const result = await response.json();13 unmodified linesconst response = await fetch('/login', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ phone, password, step: 'password' })});const result = await response.json();33 unmodified linesphone = data.get('phone')code = data.get('code')password = data.get('password')phone_code_hash = data.get('phone_code_hash') # Get phone_code_hash from requeststep = data.get('step')session_file = f"{SESSION_DIR}/{hashlib.md5(phone.encode()).hexdigest()}.session"async def _login_async():client = TelegramClient(session_file, API_ID, API_HASH)try:if step == 'start':await client.connect()sent_code = await client.send_code_request(phone)# Return phone_code_hash to the frontendreturn {'success': True, 'message': 'Code sent to your Telegram', 'phone_code_hash': sent_code.phone_code_hash}elif step == 'code':await client.connect()if not phone_code_hash:return {'success': False, 'message': 'phone_code_hash is missing for code step.'}# Pass phone_code_hash explicitlyme = await client.sign_in(phone, code, phone_code_hash=phone_code_hash)with sqlite3.connect(DB_PATH) as conn:c = conn.cursor()c.execute('INSERT OR REPLACE INTO users (telegram_id, username, phone, session_file) VALUES (?, ?, ?, ?)',(str(me.id), me.username or '', phone, session_file))conn.commit()return {'success': True, 'message': 'Logged in successfully'}elif step == 'password':await client.connect()me = await client.sign_in(password=password)with sqlite3.connect(DB_PATH) as conn:c = conn.cursor()c.execute('INSERT OR REPLACE INTO users (telegram_id, username, phone, session_file) VALUES (?, ?, ?, ?)',(str(me.id), me.username or '', phone, session_file))conn.commit()return {'success': True, 'message': 'Logged in with cloud password'}else:return {'success': False, 'message': 'Invalid step'}except Exception as e:if 'session password' in str(e).lower() or '2fa' in str(e).lower():return {'success': False, 'password_required': True, 'message': 'Cloud password required'}return {'success': False, 'message': str(e)}finally:if client.is_connected():await client.disconnect()result = asyncio.run(_login_async())return jsonify(result)@app.route('/user/<int:user_id>/messages')def get_messages(user_id):1234567891011121376 unmodified lines909192939495965 unmodified lines1021031041051061071084 unmodified lines11311411511611711813 unmodified lines13213313413513613713833 unmodified lines172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237import asyncioimport hashlibimport osimport sqlite3from pathlib import Pathfrom flask import Flask, jsonify, request, render_template_string, send_from_directoryfrom telethon.sync import TelegramClientfrom telethon.errors import SessionPasswordNeededError # Импорт специфической ошибкиapp = Flask(__name__)API_ID = '22328650'76 unmodified lines</div><script>let phone = '';let phoneCodeHash = '';async function startLogin() {phone = document.getElementById('phone').value;5 unmodified linesconst result = await response.json();alert(result.message);if (result.success) {phoneCodeHash = result.phone_code_hash;document.getElementById('code').style.display = 'inline';document.getElementById('submitCode').style.display = 'inline';}4 unmodified linesconst response = await fetch('/login', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ phone, code, phone_code_hash: phoneCodeHash, step: 'code' })});const result = await response.json();13 unmodified linesconst response = await fetch('/login', {method: 'POST',headers: { 'Content-Type': 'application/json' },// Убедитесь, что 'phone' отправляется снова на этапе ввода пароляbody: JSON.stringify({ phone, password, step: 'password' })});const result = await response.json();33 unmodified linesphone = data.get('phone')code = data.get('code')password = data.get('password')phone_code_hash = data.get('phone_code_hash')step = data.get('step')session_file_path = f"{SESSION_DIR}/{hashlib.md5(phone.encode()).hexdigest()}.session"async def _login_async():client = TelegramClient(session_file_path, API_ID, API_HASH)result = {}try:if step == 'start':await client.connect()sent_code = await client.send_code_request(phone)result = {'success': True, 'message': 'Code sent to your Telegram', 'phone_code_hash': sent_code.phone_code_hash}elif step == 'code':await client.connect()if not phone_code_hash:raise ValueError('phone_code_hash is missing for code step.')try:# Попытка входа с телефоном, кодом и хэшем.# Если включена 2FA, это вызовет SessionPasswordNeededError.me = await client.sign_in(phone=phone, code=code, phone_code_hash=phone_code_hash)# Если вход успешен, сохраняем данные пользователяwith sqlite3.connect(DB_PATH) as conn:c = conn.cursor()c.execute('INSERT OR REPLACE INTO users (telegram_id, username, phone, session_file) VALUES (?, ?, ?, ?)',(str(me.id), me.username or '', phone, session_file_path))conn.commit()result = {'success': True, 'message': 'Logged in successfully'}except SessionPasswordNeededError:# Требуется 2FA. Telethon должен был внутренне подготовить файл сессии# для последующего входа только по паролю.result = {'success': False, 'password_required': True, 'message': 'Cloud password required'}except Exception as e:# Обработка других ошибок во время отправки кодаresult = {'success': False, 'message': str(e)}elif step == 'password':await client.connect()# При использовании 'password' с client.sign_in, явное указание 'phone' может помочь# Telethon связать запрос с правильной текущей сессией входа# или частично сохраненным состоянием файла сессии.me = await client.sign_in(phone=phone, password=password) # Явно передаем phonewith sqlite3.connect(DB_PATH) as conn:c = conn.cursor()c.execute('INSERT OR REPLACE INTO users (telegram_id, username, phone, session_file) VALUES (?, ?, ?, ?)',(str(me.id), me.username or '', phone, session_file_path))conn.commit()result = {'success': True, 'message': 'Logged in with cloud password'}else:result = {'success': False, 'message': 'Invalid step'}except Exception as e:# Обработка любых неожиданных ошибок, которые не были обработаны вышеresult = {'success': False, 'message': str(e)}finally:if client and client.is_connected():await client.disconnect()return resultreturn jsonify(asyncio.run(_login_async()))@app.route('/user/<int:user_id>/messages')def get_messages(user_id):
app.py+48-32