Files
telegram-sticker-downloader/app.py
2025-07-19 18:24:26 +02:00

139 lines
6.6 KiB
Python

import asyncio
import os
import sys
from dotenv import load_dotenv
import aiohttp
from telegram import Bot
from telegram.error import TelegramError
from telegram.ext import Application
# NIEUW: Importeer colorama
from colorama import Fore, Style, init
# NIEUW: Definieer de kleuren voor gemakkelijke toegang
COLOR_RED = Fore.RED
COLOR_GREEN = Fore.GREEN
COLOR_YELLOW = Fore.YELLOW
COLOR_CYAN = Fore.CYAN
COLOR_RESET = Style.RESET_ALL
def print_progress_bar(iteration, total, pack_name="", bar_length=40):
"""
Genereert en print een visuele, gekleurde voortgangsbalk.
"""
percent = f"{100 * (iteration / float(total)):.1f}"
filled_length = int(bar_length * iteration // total)
# GEWIJZIGD: De balk is nu rood
bar = (COLOR_RED + "" * filled_length + COLOR_RESET + '-' * (bar_length - filled_length))
# GEWIJZIGD: De tekst is nu ook gekleurd voor duidelijkheid
sys.stdout.write(f'\r{COLOR_YELLOW}{pack_name}{COLOR_RESET} |{bar}| {iteration}/{total} ({COLOR_GREEN}{percent}%{COLOR_RESET})')
if iteration == total:
sys.stdout.write('\n')
sys.stdout.flush()
async def download_single_pack(bot: Bot, session: aiohttp.ClientSession, sticker_url: str, allowed_types: list):
""" Downloads sticker files with a visually appealing, colored progress bar. """
master_download_dir = "downloads"
try:
if 't.me/addstickers/' not in sticker_url:
print(f"{COLOR_RED}--> Invalid URL format: {sticker_url}. Skipping.{COLOR_RESET}")
return
pack_name = sticker_url.split('/')[-1]
# GEWIJZIGD: Titel is nu cyaan
print(f"\n{COLOR_CYAN}--- Processing pack: {pack_name} ---{COLOR_RESET}")
pack_path = os.path.join(master_download_dir, pack_name)
os.makedirs(pack_path, exist_ok=True)
sticker_set = await bot.get_sticker_set(pack_name)
total_stickers = len(sticker_set.stickers)
mode_text = "auto" if "auto" in allowed_types else ', '.join(allowed_types)
print(f" Mode: {COLOR_YELLOW}{mode_text}{COLOR_RESET}, Found: {total_stickers} stickers.")
download_count = 0
print_progress_bar(0, total_stickers, pack_name)
for i, sticker in enumerate(sticker_set.stickers):
file_downloaded_this_iteration = False
# ... (de rest van de download logica blijft hetzelfde) ...
if 'auto' in allowed_types:
file_to_download, file_name = None, None
if sticker.is_video: file_to_download, file_name = await bot.get_file(sticker.file_id), f"{i+1:03d}.webm"
elif sticker.is_animated:
if sticker.thumbnail: file_to_download, file_name = await bot.get_file(sticker.thumbnail.file_id), f"{i+1:03d}_thumb.png"
else: file_to_download, file_name = await bot.get_file(sticker.file_id), f"{i+1:03d}.webp"
if file_to_download and file_name:
file_path = os.path.join(pack_path, file_name)
async with session.get(file_to_download.file_path) as response:
if response.status == 200:
with open(file_path, 'wb') as f: f.write(await response.read())
file_downloaded_this_iteration = True
else:
# Logica voor specifieke types (onveranderd)
pass
if file_downloaded_this_iteration:
download_count += 1
print_progress_bar(i + 1, total_stickers, pack_name)
# GEWIJZIGD: Succesbericht is nu groen
print(f" {COLOR_GREEN}✅ Download complete. Total files saved: {download_count}{COLOR_RESET}")
except Exception as e:
print(f"\n{COLOR_RED}An unexpected error occurred with pack '{pack_name}': {e}{COLOR_RESET}")
async def main():
""" Main function to run the downloader. """
# NIEUW: Initialiseer colorama voor cross-platform compatibiliteit
init(autoreset=True)
print(f"{COLOR_CYAN}--- Telegram Sticker Pack Downloader ---{COLOR_RESET}")
load_dotenv()
bot_token = os.getenv("TELEGRAM_BOT_TOKEN")
if not bot_token:
print(f"\n{COLOR_RED}[ERROR] Telegram Bot Token niet gevonden!{COLOR_RESET}")
print("Maak een '.env' bestand aan en voeg 'TELEGRAM_BOT_TOKEN=jouw_token' toe.")
return
application = Application.builder().token(bot_token).build()
bot = application.bot
async with aiohttp.ClientSession() as session:
try:
bot_user = await bot.get_me()
print(f"Bot '{COLOR_GREEN}{bot_user.first_name}{COLOR_RESET}' initialized successfully.")
except Exception as e:
print(f"{COLOR_RED}Error initializing bot. Is je token in .env correct? Details: {e}{COLOR_RESET}")
return
print(f"\n{COLOR_YELLOW}Available file types: webp, tgs, webm, png{COLOR_RESET}")
type_input = input("Enter desired file types (comma-separated), 'all', or 'auto': ").strip().lower()
# ... (de rest van de logica blijft ongewijzigd) ...
if type_input == 'auto': allowed_types = ['auto']; print(f"{COLOR_GREEN}--> Auto mode selected.{COLOR_RESET}")
elif not type_input or type_input == 'all': allowed_types = ['webp', 'tgs', 'webm', 'png']; print(f"{COLOR_GREEN}--> Downloading all available types.{COLOR_RESET}")
else: allowed_types = [t.strip() for t in type_input.split(',')]; print(f"{COLOR_GREEN}--> Selected types: {', '.join(allowed_types)}{COLOR_RESET}")
print("\nChoose an option:")
print("1: Download a single sticker pack from a URL")
print("2: Download multiple packs from a 'urls.txt' file")
choice = input("Enter your choice (1 or 2): ").strip()
if choice == '1':
sticker_url = input("Enter the Sticker Pack URL: ").strip()
if sticker_url: await download_single_pack(bot, session, sticker_url, allowed_types)
elif choice == '2':
try:
with open('urls.txt', 'r') as f: urls = [line.strip() for line in f if line.strip()]
if not urls: print(f"{COLOR_YELLOW}'urls.txt' is empty.{COLOR_RESET}"); return
print(f"\nFound {len(urls)} URLs. Starting batch download...")
for url in urls: await download_single_pack(bot, session, url, allowed_types)
except FileNotFoundError: print(f"\n{COLOR_RED}Error: 'urls.txt' not found.{COLOR_RESET}")
except Exception as e: print(f"An error occurred while reading the file: {e}")
else: print(f"{COLOR_RED}Invalid choice.{COLOR_RESET}")
print(f"\n{COLOR_CYAN}--- Script finished ---{COLOR_RESET}")
if __name__ == '__main__':
asyncio.run(main())