archive-backend/utils/downloader.py
2026-11-07 17:27:59 +00:00

71 lines
1.6 KiB
Python

import asyncio
import os
from pathlib import Path
import qrcode
from dotenv import load_dotenv
from telethon import TelegramClient
from ..core.config import PHOTOS_DIR
ENV_PATH = Path(__file__).resolve().parent / ".env"
load_dotenv(ENV_PATH)
API_ID = os.getenv("API_ID")
API_HASH = os.getenv("API_HASH")
if not API_ID or not API_HASH:
raise ValueError("API_ID or API_HASH is not defined in .env")
API_ID = int(API_ID)
BASE_DIR = Path(__file__).resolve().parent
SOURCE = str(input("channel username:")).strip().lstrip("@")
CHANNEL =SOURCE
DOWNLOAD_DIR = SOURCE
MEDIA_ROOT = PHOTOS_DIR
async def download_photos(client):
download_path = BASE_DIR / MEDIA_ROOT / DOWNLOAD_DIR
download_path.mkdir(parents=True, exist_ok=True)
async for msg in client.iter_messages(CHANNEL):
if not msg.photo:
continue
filename = f"{msg.photo.id}.jpg"
full_path = download_path / filename
if full_path.is_file() and full_path.stat().st_size > 0:
continue
try:
await msg.download_media(file=full_path)
except Exception as e:
print(e)
async def main():
client = TelegramClient("qr_session", API_ID, API_HASH)
await client.connect()
try:
if not await client.is_user_authorized():
qr = await client.qr_login()
image = qrcode.QRCode()
image.add_data(qr.url)
image.make(fit=True)
image.print_ascii(invert=True)
await download_photos(client)
finally:
await client.disconnect()
asyncio.run(main())