Загрузка данных


import asyncio
from telethon import TelegramClient
from telethon.errors import (
    FloodWaitError,
    UsernameInvalidError,
    UsernameNotOccupiedError,
    ChannelPrivateError,
)

API_ID = 2040
API_HASH = "b18441a1ff607e10a989891a5462e627"

INPUT_FILE = "usernames.txt"
EXISTING_FILE = "existing_groups.txt"
NON_EXISTING_FILE = "non_existing.txt"


async def main():
    open(EXISTING_FILE, "w", encoding="utf-8").close()
    open(NON_EXISTING_FILE, "w", encoding="utf-8").close()

    try:
        with open(INPUT_FILE, "r", encoding="utf-8") as f:
            usernames = [line.strip().lstrip("@") for line in f if line.strip()]
    except FileNotFoundError:
        print(f"Ошибка: Не найден файл {INPUT_FILE}!")
        return

    print(f"Загружено {len(usernames)} строк. Запуск проверки...\n")

    async def write_file(filename, text):
        with open(filename, "a", encoding="utf-8") as f:
            f.write(text + "\n")

    async with TelegramClient("session_checker", API_ID, API_HASH) as client:
        existing_count = 0
        non_existing_count = 0

        for idx, username in enumerate(usernames, 1):
            while True:
                try:
                    entity = await client.get_entity(username)
                    is_group = (
                        getattr(entity, "megagroup", False)
                        or type(entity).__name__ == "Chat"
                    )

                    if not is_group:
                        await write_file(NON_EXISTING_FILE, f"@{username}")
                        non_existing_count += 1
                        print(f"[{idx}/{len(usernames)}] Не группа: @{username}")
                        break

                    await write_file(EXISTING_FILE, f"@{username}")
                    existing_count += 1
                    print(f"[{idx}/{len(usernames)}] Найдена группа: @{username}")
                    break

                except (
                    UsernameInvalidError,
                    UsernameNotOccupiedError,
                    ValueError,
                    ChannelPrivateError,
                ):
                    await write_file(NON_EXISTING_FILE, f"@{username}")
                    non_existing_count += 1
                    print(f"[{idx}/{len(usernames)}] Не существует / бан: @{username}")
                    break

                except FloodWaitError as e:
                    print(f"\n[!] Лимит Telegram. Ждем {e.seconds} сек...")
                    await asyncio.sleep(e.seconds + 2)

                except Exception as err:
                    await write_file(NON_EXISTING_FILE, f"@{username}")
                    non_existing_count += 1
                    print(f"[{idx}/{len(usernames)}] Ошибка: @{username}")
                    break

            await asyncio.sleep(2.5)

    print("\n" + "=" * 40)
    print("Готово!")
    print(f"Существуют: {existing_count} -> {EXISTING_FILE}")
    print(f"Не существуют/бан: {non_existing_count} -> {NON_EXISTING_FILE}")
    print("=" * 40)


if __name__ == "__main__":
    asyncio.run(main())