OFTQUEST / telegram_client.py
Nicolasmed26's picture
Deploy MedMembers OFT 2026
12f0507 verified
Raw History Blame Contribute Delete
11.6 kB
"""
Telegram MTProto Client Singleton
Manages a Telethon client running in a background thread for use with
synchronous Flask routes. Supports streaming files up to 2GB from
Telegram channels via MTProto API.
Requires TELEGRAM_API_ID and TELEGRAM_API_HASH from https://my.telegram.org
Falls back gracefully when credentials are not configured.
"""
import asyncio
import logging
import os
import queue as thread_queue
import threading
from config import Config
logger = logging.getLogger(__name__)
try:
from telethon import TelegramClient
from telethon.tl.types import DocumentAttributeFilename
HAS_TELETHON = True
except ImportError:
HAS_TELETHON = False
logger.warning("Telethon not installed. MTProto streaming unavailable.")
class TelegramStreamer:
"""
Singleton that manages a Telethon client in a background asyncio loop.
Usage from synchronous Flask code:
streamer = TelegramStreamer.get_instance()
if streamer and streamer.is_ready():
data = streamer.get_file_chunk(message_id, offset, limit)
"""
_instance = None
_lock = threading.Lock()
def __init__(self):
self._client = None
self._loop = None
self._thread = None
self._ready = False
self._channel_entity = None
self._media_cache = {}
@classmethod
def get_instance(cls):
"""Get or create the singleton instance. Returns None if MTProto is not configured."""
if not HAS_TELETHON:
return None
if not Config.TELEGRAM_API_ID or not Config.TELEGRAM_API_HASH:
return None
if not Config.TELEGRAM_BOT_TOKEN:
return None
with cls._lock:
if cls._instance is None:
cls._instance = cls()
cls._instance._start_loop()
return cls._instance
def is_ready(self):
return self._ready and self._client is not None
def _start_loop(self):
self._loop = asyncio.new_event_loop()
self._thread = threading.Thread(target=self._run_loop, daemon=True, name="telethon-loop")
self._thread.start()
try:
future = asyncio.run_coroutine_threadsafe(self._init_client(), self._loop)
future.result(timeout=30)
self._ready = True
logger.info("Telethon MTProto client initialized successfully")
except Exception as e:
logger.error(f"Failed to initialize Telethon client: {e}")
self._ready = False
def _run_loop(self):
asyncio.set_event_loop(self._loop)
self._loop.run_forever()
async def _init_client(self):
session_dir = os.path.join(os.path.dirname(__file__), 'data')
os.makedirs(session_dir, exist_ok=True)
session_path = os.path.join(session_dir, 'bot_session')
self._client = TelegramClient(
session_path,
Config.TELEGRAM_API_ID,
Config.TELEGRAM_API_HASH,
loop=self._loop
)
await self._client.start(bot_token=Config.TELEGRAM_BOT_TOKEN)
logger.info("Telethon client connected")
channel_id = Config.TELEGRAM_CHANNEL_ID
if channel_id:
try:
self._channel_entity = await self._client.get_entity(int(channel_id))
logger.info(f"Channel entity cached: {channel_id}")
except Exception as e:
logger.warning(f"Could not pre-fetch channel entity: {e}")
def _run_async(self, coro, timeout=300):
if not self._ready or not self._loop:
raise RuntimeError("Telethon client not ready")
future = asyncio.run_coroutine_threadsafe(coro, self._loop)
return future.result(timeout=timeout)
# ===== Public sync API =====
def get_file_info(self, message_id):
try:
return self._run_async(self._async_get_file_info(message_id), timeout=30)
except Exception as e:
logger.error(f"get_file_info error for msg {message_id}: {e}")
return None
def get_file_chunk(self, message_id, offset=0, limit=None, timeout=None):
if timeout is None:
timeout = 15 if (limit and limit < 1024 * 1024) else 300
try:
return self._run_async(
self._async_get_file_chunk(message_id, offset, limit),
timeout=timeout
)
except Exception as e:
logger.error(f"get_file_chunk error for msg {message_id}: {e}")
return b''
def stream_file_generator(self, message_id, offset=0, limit=None, chunk_size=1024 * 1024):
q = thread_queue.Queue(maxsize=4)
async def _producer():
try:
media = await self._async_get_media(message_id)
if not media:
q.put(None)
return
downloaded = 0
async for chunk in self._client.iter_download(
media,
offset=offset,
request_size=chunk_size
):
if limit and downloaded + len(chunk) > limit:
remaining = limit - downloaded
if remaining > 0:
q.put(chunk[:remaining])
break
q.put(chunk)
downloaded += len(chunk)
q.put(None)
except Exception as e:
logger.error(f"Stream producer error for msg {message_id}: {e}")
q.put(None)
try:
asyncio.run_coroutine_threadsafe(_producer(), self._loop)
while True:
try:
chunk = q.get(timeout=60)
except thread_queue.Empty:
logger.error(f"Stream timeout waiting for chunk (msg {message_id})")
break
if chunk is None:
break
yield chunk
except Exception as e:
logger.error(f"stream_file_generator error for msg {message_id}: {e}")
return
def upload_file_sync(self, filepath, category, caption=None):
try:
return self._run_async(
self._async_upload_file(filepath, category, caption),
timeout=600
)
except Exception as e:
logger.error(f"upload_file_sync error: {e}")
return None
# ===== Private async methods =====
async def _async_get_file_info(self, message_id):
channel = self._channel_entity
if not channel:
try:
channel = await self._client.get_entity(int(Config.TELEGRAM_CHANNEL_ID))
self._channel_entity = channel
except Exception as e:
logger.error(f"Cannot resolve channel: {e}")
return None
try:
messages = await self._client.get_messages(channel, ids=[message_id])
message = messages[0] if messages else None
except Exception as e:
logger.error(f"get_messages failed for msg_id={message_id}: {e}")
return None
if not message or not message.media:
return None
doc = getattr(message.media, 'document', None)
if doc:
filename = None
for attr in doc.attributes:
if isinstance(attr, DocumentAttributeFilename):
filename = attr.file_name
break
return {
'size': doc.size,
'filename': filename,
'mime_type': doc.mime_type,
'id': doc.id,
'access_hash': doc.access_hash,
}
photo = getattr(message.media, 'photo', None)
if photo:
sizes = getattr(photo, 'sizes', [])
if sizes:
largest = max(sizes, key=lambda s: getattr(s, 'size', 0))
return {
'size': getattr(largest, 'size', 0),
'filename': f'photo_{photo.id}.jpg',
'mime_type': 'image/jpeg',
}
return None
async def _async_get_media(self, message_id):
if message_id in self._media_cache:
return self._media_cache[message_id]
channel = self._channel_entity
if not channel:
channel = await self._client.get_entity(int(Config.TELEGRAM_CHANNEL_ID))
self._channel_entity = channel
messages = await self._client.get_messages(channel, ids=[message_id])
message = messages[0] if messages else None
if not message or not message.media:
return None
self._media_cache[message_id] = message.media
if len(self._media_cache) > 50:
oldest = list(self._media_cache.keys())[0]
del self._media_cache[oldest]
return message.media
async def _async_get_file_chunk(self, message_id, offset, limit):
media = await self._async_get_media(message_id)
if not media:
return b''
CHUNK = 1024 * 1024 # 1MB
aligned_offset = (offset // CHUNK) * CHUNK
skip_bytes = offset - aligned_offset
need_total = skip_bytes + (limit or CHUNK)
data = bytearray()
try:
async for chunk in self._client.iter_download(
media,
offset=aligned_offset,
request_size=CHUNK
):
data.extend(chunk)
if len(data) >= need_total:
break
except Exception as e:
logger.error(f"iter_download error msg={message_id}: {e}")
self._media_cache.pop(message_id, None)
return b''
result = bytes(data[skip_bytes:])
if limit and len(result) > limit:
result = result[:limit]
return result
async def _async_upload_file(self, filepath, category, caption=None):
channel = self._channel_entity
if not channel:
channel = await self._client.get_entity(int(Config.TELEGRAM_CHANNEL_ID))
if not caption:
caption = category
filename = os.path.basename(filepath)
file_size = os.path.getsize(filepath)
logger.info(f"MTProto uploading {filename} ({file_size} bytes)")
ext = os.path.splitext(filename)[1].lower()
is_video = ext in {'.mp4', '.mkv', '.avi', '.mov'}
if is_video:
message = await self._client.send_file(
channel, filepath,
caption=caption,
supports_streaming=True,
force_document=False,
)
else:
message = await self._client.send_file(
channel, filepath,
caption=caption,
force_document=True,
)
if not message:
return None
result = {'message_id': message.id, 'size': file_size}
doc = getattr(message.media, 'document', None) if message.media else None
if doc:
result['file_id'] = str(doc.id)
result['file_unique_id'] = f"mtproto_{doc.id}"
result['access_hash'] = doc.access_hash
elif message.media and hasattr(message.media, 'photo'):
photo = message.media.photo
result['file_id'] = str(photo.id)
result['file_unique_id'] = f"mtproto_{photo.id}"
logger.info(f"MTProto upload complete: msg_id={message.id}")
return result