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


import asyncio
import aiohttp

INPUT_FILE = "usernames.txt"
FILE_EXISTING = "existing_groups.txt"
FILE_NON_EXISTING = "non_existing.txt"

HEADERS = {
    "User-Agent": (
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
        "AppleWebKit/537.36 (KHTML, like Gecko) "
        "Chrome/124.0.0.0 Safari/537.36"
    )
}

DEAD_PATTERNS = [
    "tgme_page_icon_user",  # Профиль обычного пользователя (не группа/канал)
    "If you have Telegram, you can contact",
    'tgme_page_description">If you have',
]


async def check_channel(session, sem, username):
  clean_name = username.strip().lstrip("@")
  url = f"https://t.me/{clean_name}"

  async with sem:
    try:
      async with session.get(
          url, headers=HEADERS, timeout=aiohttp.ClientTimeout(total=8)
      ) as resp:
        if resp.status != 200:
          return clean_name, False

        html = await resp.text()

        # Проверка на наличие признаков открытого канала/группы
        is_dead = "tgme_page_extra" not in html or any(
            p in html for p in DEAD_PATTERNS
        )
        has_stats = "members" in html.lower() or "subscribers" in html.lower()

        if is_dead and not has_stats:
          return clean_name, False

        return clean_name, True
    except Exception:
      return clean_name, False


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

  # Очищаем входные данные от мусора и дублей
  usernames = []
  for line in raw_lines:
    clean = line.split("|")[0].split()[0].replace("@", "").strip()
    if clean:
      usernames.append(clean)
  usernames = list(dict.fromkeys(usernames))

  total = len(usernames)
  print(f"Загружено {total} юзернеймов. Запуск веб-проверки...")

  # Очищаем файлы перед стартом
  open(FILE_EXISTING, "w", encoding="utf-8").close()
  open(FILE_NON_EXISTING, "w", encoding="utf-8").close()

  # До 10 одновременных запросов, чтобы веб Telegram не накладывал ограничений
  sem = asyncio.Semaphore(10)

  async with aiohttp.ClientSession() as session:
    tasks = [check_channel(session, sem, user) for user in usernames]

    for idx, future in enumerate(asyncio.as_completed(tasks), 1):
      user, exists = await future
      if exists:
        with open(FILE_EXISTING, "a", encoding="utf-8") as f:
          f.write(f"@{user}\n")
        print(f"[{idx}/{total}] [СУЩЕСТВУЕТ]: @{user}")
      else:
        with open(FILE_NON_EXISTING, "a", encoding="utf-8") as f:
          f.write(f"@{user}\n")
        print(f"[{idx}/{total}] [НЕТ/МЕРТВ]: @{user}")

  print("\nПроверка завершена!")
  print(f"Живые сохранены в: {FILE_EXISTING}")
  print(f"Мертвые сохранены в: {FILE_NON_EXISTING}")


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