Skip to main content

tg-scrape-comments

CLI для выгрузки постов и комментариев из публичных Telegram-каналов в JSONL
Основано на Telethon. Авторизация — через ваш Telegram-аккаунт (номер → код → 2FA при наличии).

  • Требования: Python ≥ 3.10
  • ОС: Linux, macOS, Windows
  • Команда CLI: tg-scrape
  • Пакет на PyPI: tg-scrape-comments

Установка

Из PyPI

pip install tg-scrape-comments

Из GitHub (без клонирования)

pip install "git+https://github.com/Frantsuzova/tg_scrape_comments@main"

Локально из исходников

git clone https://github.com/Frantsuzova/tg_scrape_comments.git
cd tg_scrape_comments
pip install .

Быстрый старт

  1. Получите API ID и API HASH: https://my.telegram.org → API development tools.
  2. Запуск (первые 5 постов для проверки):
tg-scrape @durov --out-dir ./out --post-limit 5   --api-id 123456 --api-hash xxxxxxxxxxxxxxxxxxxxxxxx

При первом запуске будет интерактивный запрос телефона, кода и (при 2FA) пароля. Создастся файл сессии.

Использование переменных окружения

# Linux/macOS
export TELEGRAM_API_ID=123456
export TELEGRAM_API_HASH=xxxxxxxxxxxxxxxxxxxxxxxx
tg-scrape @durov --out-dir ./out

# Windows PowerShell
$env:TELEGRAM_API_ID="123456"
$env:TELEGRAM_API_HASH="xxxxxxxxxxxxxxxxxxxxxxxx"
tg-scrape @durov --out-dir .\out

Несколько каналов

# списком
tg-scrape @durov @telegram https://t.me/some_public_channel --out-dir ./out

# из файла (по одному адресу в строке: @name или https://t.me/name)
tg-scrape --channels-file channels.txt --out-dir ./out

Результат

На каждый канал создаётся файл posts_<username_или_id>.jsonl в --out-dir.
Каждая строка — один пост с агрегированными комментариями (если у канала есть связанный чат/форум).

Пример строки:

{
  "channel_id": 1006503122,
  "channel_username": "durov",
  "post_id": 1234,
  "date_utc": "2025-08-27T10:15:00+00:00",
  "text": "Текст поста",
  "views": 12345,
  "forwards": 10,
  "reactions": [{"reaction":"👍","count":5},{"reaction":"🔥","count":2}],
  "reply_count": 42,
  "comments_count": 40,
  "comments_text": "Комментарий 1\n\nКомментарий 2\n\n…",
  "link": "https://t.me/durov/1234"
}

Быстрая проверка после запуска:

tg-scrape --help
ls -lh ./out
head -n 2 ./out/posts_*.jsonl

Параметры CLI

tg-scrape [channels ...]
  --channels-file PATH      Путь к файлу со списком каналов (по одному в строке).
  --out-dir PATH            Куда писать *.jsonl (по умолчанию текущая папка).
  --session PATH_OR_NAME    Имя/путь файла сессии Telethon (по умолчанию tg_scrape_session).
  --api-id INT              Telegram API ID (или env TELEGRAM_API_ID).
  --api-hash STR            Telegram API HASH (или env TELEGRAM_API_HASH).
  --log-every INT           Прогресс каждые N постов (по умолчанию 200).
  --no-sleep-after-flood    Не ждать при FloodWaitError (по умолчанию ждёт).
  --post-limit INT          Ограничить число постов на канал (для быстрых тестов).

Примечания и ограничения

  • Работает с публичными каналами и их обсуждениями, доступными вашему аккаунту.
  • Если у канала нет связанного чата/форума → comments_count=0, comments_text="".
  • Для каналов с Темами выполняется мэппинг поста на top_id треда.
  • Telegram может возвращать FloodWait — по умолчанию ожидание включено; можно отключить флагом.
  • Не публикуйте API_HASH и не коммитьте файлы *.session.

Google Colab

В Colab используйте %env, а не !export:

%env TELEGRAM_API_ID=123456
%env TELEGRAM_API_HASH=xxxxxxxxxxxxxxxxxxxxxxxx

Запуск:

!tg-scrape @durov --out-dir ./out --post-limit 5

Если интерактивный ввод кода не появляется, можно вызвать модуль напрямую из Python:

import tg_scrape_comments.cli as cli
cli.main(["@durov","--out-dir","./out","--post-limit","5",
          "--api-id","123456","--api-hash","xxxxxxxxxxxxxxxxxxxxxxxx"])

Частые вопросы

Почему файл иногда называется posts_<id>.jsonl, а не posts_<username>.jsonl?
У каналов без username используется числовой id.

Как ускорить проверку?
Флаг --post-limit N и выбор небольшого числа каналов.

Можно выгружать только посты без комментариев?
Пока нет. Планируется флаг --no-comments в следующих версиях.

Лицензия

MIT

Metadata

Release files for tg-scrape-comments 0.1.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for tg-scrape-comments 0.1.3
File Size Uploaded Provenance Actions
tg_scrape_comments-0.1.3.tar.gz 10.5 kB Without provenance Details for tg_scrape_comments-0.1.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for tg-scrape-comments 0.1.3
File Interpreter ABI Platform Actions
tg_scrape_comments-0.1.3-py3-none-any.whl Python 3 none any Details for tg_scrape_comments-0.1.3-py3-none-any.whl

Total release size: 19.6 kB

Release files / tg_scrape_comments-0.1.3.tar.gz

Download URL tg_scrape_comments-0.1.3.tar.gz
Size 10.5 kB
Tags Source
SHA-256 checksum
How to use checksums
7d10af2b970775cbb01154c47ece56aa27c2f56b316ed865142e6d31f20f2d6d
BLAKE2b-256 checksum
How to use checksums
55c44417015b5439419b36f3867287c18baf752a60105b71e9e13ef6f0e221a0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.12.11

Release files / tg_scrape_comments-0.1.3-py3-none-any.whl

Download URL tg_scrape_comments-0.1.3-py3-none-any.whl
Size 9.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f5d2e4aec29275b80c4602f89c99bb3f8698bbffe04384df4c66bc0ca461caeb
BLAKE2b-256 checksum
How to use checksums
7ae92bcea2ea3cb054a8d9c9e99453dfc4709d510daefb77c4b4d1ad5b19387f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.12.11

Security for tg-scrape-comments 0.1.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.3 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page