A Telegram scraper that revisits the same public channels for months on end, so the corpus it builds records what changed between visits instead of how everything looked once.
Snowball discovery. Longitudinal metadata snapshots. Two-path deletion detection. Fleet control from a database row. Tabbed terminal dashboard.
Three Compose services and one scrape runner. Per channel the runner drives a metadata collector, a message processor and a discovery module, with Telethon in front of MTProto and PostgreSQL behind everything.
Public Telegram research corpora are snapshots. They record each channel once and miss everything that happens afterwards: the edits, the deletions, the metadata changes, the moderation decisions. In a snapshot, a channel that was renamed, lost its verification badge, picked up a scam flag and quietly removed a third of its posts is indistinguishable from a channel that never moved.
strascico builds its corpus by revisiting the same channels over and over, so those layers exist and can be measured. Channel metadata is appended once per visit rather than overwritten. The prior text of an edited message is archived before the new version lands. A message that disappears from the server is flagged deleted, never removed from the table.
What a snapshot corpus stores as one row per channel, this one stores as one row per channel per visit, so a rename, a lost verification badge or a new scam flag is a difference between two rows rather than something nobody can see.
The bill arrives on every run. Re-reading thousands of channels against an API that rate-limits you, and that can ban the account outright, is a different problem from reading them once. That is where most of the engineering here went: see How it works.
- Longitudinal metadata snapshots: one
metadata_snapshotsrow per channel per visit, appended rather than overwritten - Two-path deletion detection: a single server-side count decides whether a full history diff is needed at all
- Edit archiving: the previous text, entities and media type of an edited message are kept in
message_edits - Derived discovery freeze:
DISCOVERY_MAX_RUNSis recomputed every run, so raising it re-admits parked channels and lowering it evicts them, with noUPDATE - Fleet control plane: one
fleet_controlrow per corpus pauses, drains or aligns every worker, across hosts and across restarts - Snowball discovery: channels enter from forwards,
@mentionsand t.me links, each row carrying the provenance it arrived by - Alignment snapshots: a cutoff-anchored pass that brings the whole corpus to one comparable timestamp
- Profile-picture deduplication: content-addressable by SHA-256, with perceptual and difference hashes for near-duplicates
- Poll capture: question, options, tallies and quiz solutions, refreshed in place on re-observation
- Optional comment scraping: linked discussion groups are followed inline through their parent channel
- Multi-corpus overlays: separate databases in one cluster behind one image, selected by a single
ACTIVE_DATASETline - Crash-resumable runs: per-channel progress lives in
run_channels, so a restart rejoins the run it left rather than starting a new one - Tabbed terminal dashboard:
tgmon.shis interactive on a TTY and a one-shot dump when piped, sowatchandsshkeep working
You need Docker and Docker Compose, and Telegram API credentials from my.telegram.org. Python 3.13+ is only needed for local development.
cp .env.example .env
# fill in API_ID, API_HASH, PHONE and POSTGRES_PASSWORD
# create the Telethon session (prompts for the SMS code, and 2FA if enabled)
pip install telethon python-dotenv
python -c "
from dotenv import dotenv_values
from telethon.sync import TelegramClient
env = dotenv_values('.env')
client = TelegramClient('session', int(env['API_ID']), env['API_HASH'])
client.start(phone=env['PHONE'])
client.disconnect()
"
docker compose up --build -d
./tgmon.shThat brings up three containers: db, a PostgreSQL 16 instance that applies db/init/ to the bootstrap corpus on first boot; import, which bulk-loads the 120,979 channel ids in datasets/tgdataset2.seeds.txt and exits; and scraper, which waits for the import and then starts crawling. If you already have a session.session file, drop it in the project root and skip the Python step.
./tgmon.sh opens the dashboard. Pipe it or run it over ssh and it prints a one-shot dump instead, so watch -n 30 ./tgmon.sh and existing scripts keep working unchanged.
The default ACTIVE_DATASET=tgdataset2 points at the bootstrap database, so a fresh install needs nothing extra. Any other corpus has to be created before you select it, because its database is never created from ACTIVE_DATASET alone. Pointing at one that does not exist gives you a database "..." does not exist error and a restart loop.
./dataset.sh create mycorpus --seeds mycorpus_ids.txt # CREATE DATABASE + schema + migrations
./dataset.sh use mycorpus # rewrite ACTIVE_DATASET in .env
docker compose up -dIn a multi-worker fleet the database lives on the DB host, so dataset.sh create runs once there. Remote workers only need the overlay file and the matching ACTIVE_DATASET line.
pip install -e ".[dev]"
docker compose up -d db
python -m scraperThe test suite wants its own database on port 5433 and no Telegram credentials at all, because it exercises the database and the run logic and never touches the API:
docker run -d --name tgdataset-test-db -p 5433:5432 \
-e POSTGRES_USER=tgdataset2 -e POSTGRES_PASSWORD=testpass -e POSTGRES_DB=tgdataset2 \
postgres:16-alpine
TEST_DSN=postgresql://tgdataset2:testpass@localhost:5433/tgdataset2 pytest tests/ -vConfig is split in two. .env is machine-scoped and stable across corpora: API credentials, database connection, session path, worker identity, delays, plus one selector line ACTIVE_DATASET=<name>. The overlay datasets/<name>.env is corpus-scoped, carries no secrets and is tracked in git. Compose merges the overlay over .env, so the overlay wins.
These are the knobs that change what a corpus collects:
| Variable | Default | Effect |
|---|---|---|
ALIGNMENT_INTERVAL |
30 |
Days between automatic alignment snapshots (0 disables) |
ENABLE_LINK_DISCOVERY |
false |
Resolve @mentions and t.me links into new channels |
SCRAPE_COMMENTS |
false |
Follow linked discussion groups inline |
DISCOVERY_MAX_RUNS |
-1 |
Freeze the run-list after N completed scrapes (-1 unlimited, 0 seeds only) |
RUN_MODE |
normal |
normal, scrape_once or alignment_once |
All options
Machine-scoped, in .env:
| Variable | .env.example |
Description |
|---|---|---|
API_ID / API_HASH |
required | Telegram API credentials |
PHONE |
+1234567890 |
Phone number, only needed to create a session |
ACTIVE_DATASET |
tgdataset2 |
Selects the datasets/<name>.env and .seeds.txt overlay |
POSTGRES_USER |
tgdataset2 |
Database user |
POSTGRES_PASSWORD |
required | Database password |
POSTGRES_HOST / POSTGRES_PORT |
localhost / 5432 |
Database endpoint (db inside Docker) |
SESSION_PATH |
./session |
Telethon session path, without .session |
REQUEST_DELAY |
0.1 |
Seconds between API requests |
CHANNEL_DELAY |
0.1 |
Seconds between channels |
DELAY_JITTER |
0.3 |
Random jitter on delays, as a fraction of the base |
BATCH_SIZE |
100 |
Messages per API request batch |
MESSAGE_OVERLAP |
100 |
Messages re-checked for edits on each pass |
MAX_CONSECUTIVE_ERRORS |
2 |
Per-channel failures before deactivation |
WORKER_ID / WORKER_COUNT |
0 / 1 |
Modulo partitioning across the fleet |
Corpus-scoped, in datasets/<name>.env:
| Variable | Default | Description |
|---|---|---|
POSTGRES_DB |
per corpus | Database name for this corpus |
SEED_CHANNELS |
"" |
Comma-separated usernames or ids, resolved by worker 0 on every startup |
ALIGNMENT_INTERVAL |
30 |
Auto-alignment interval in days |
ENABLE_LINK_DISCOVERY |
false |
Resolve @mentions and t.me links |
SCRAPE_COMMENTS |
false |
Inline-scrape linked discussion groups |
DISCOVERY_MAX_RUNS |
-1 |
Freeze run-list growth after N completed scrape runs |
RUN_MODE |
normal |
normal, scrape_once or alignment_once |
ONCE_TOKEN |
1 |
Arms a one-shot; "once" means once per (RUN_MODE, ONCE_TOKEN) |
Channels enter a corpus from two additive sources, both recorded in channels.source: seed_file is the bulk file loaded once by the import container, and seed_env is SEED_CHANNELS, re-read on every startup and applied with ON CONFLICT DO NOTHING.
Dashboard keys:
| Key | Action | Key | Action |
|---|---|---|---|
1-6 |
jump to tab | r / R |
refresh tab / all tabs |
Tab → l |
next tab | w |
cycle window (5m to 24h) |
Shift-Tab ← h |
previous tab | a |
cycle auto-refresh (off, 10s, 30s, 60s) |
↑ ↓ j k |
scroll | t |
cycle query timeout |
? |
help | d |
switch viewed dataset (view-only) |
q or Ctrl-C |
quit | c |
toggle colour |
The discovery freeze is derived, not stored. Set DISCOVERY_MAX_RUNS=N and the corpus snowballs for N completed scrape runs, then freezes: newly found channels are still recorded, with their forward provenance and their place in the unresolved_references queue, but they stay out of the run-list. The obvious implementation is a frozen column, and it is the wrong one, because unfreezing then means an UPDATE over an unknown subset of rows and there is no way back. Instead each run computes a boundary at run time, the ended_at of the Nth completed scrape, and admits a channel iff its first_seen is at or before it (get_discovery_boundary and get_active_channels). That makes DISCOVERY_MAX_RUNS a live dial. Raising it moves the boundary later and re-admits every parked channel on the next run. Lowering it moves the boundary earlier and evicts the ones not yet pulled. 0 pins the line to the first run's start, so only the seeds are ever scraped. The boundary keys on scrape runs but discovery does not, so alignment runs keep recording forwards and a channel can be discovered and parked without any new scrape.
The list the boundary cuts across is the corpus itself. Each run walks the pending channels, extracts the references it finds in forwards, links and descriptions, and appends them below the run's stop marker, where the next run picks them up.
Two paths for deletion detection. Every run has to answer what is new, what was edited and what was deleted. Diffing the full history against the database answers all three and is unaffordable: a 100k-message channel at a 100-message batch size costs a thousand API calls for one "did anything change" check, and thousands of channels of that per run walks straight into a rate limit. So the cheap check comes first. get_messages(limit=0) returns the server's own message count for a channel, one call carrying no bodies. Compare it against stored_non_deleted + newly_fetched. Equal means no deletion anywhere below the highest stored id, which is the common case, and all that remains is an overlap window of MESSAGE_OVERLAP messages re-read for an advanced edit_date. Lower means something went missing, and only then does the expensive full pull run, diffing returned ids against stored ones and flagging what is absent. Edit detection rides along on the same pages either way. The count has to be channel-wide, incidentally, because max_id does not scope it: the server returns the same total regardless. docs/deletion_detection_design.md records the alternatives and the limits.
Alignment snapshots. A scrape run walks the corpus for as long as it takes, which means channel 1 and channel 8000 are observed weeks apart and any cross-channel comparison is contaminated by that drift. An alignment run fixes a cutoff timestamp, interrupts the scrape, and re-walks the already-completed channels in the order the scrape used, so the corpus gets a consistent cross-section. ALIGNMENT_INTERVAL schedules it; SIGUSR1 and dataset.sh align trigger it by hand. The cohort is not neutral, and docs/alignment_cohort_bias.md quantifies which channels it systematically excludes.
The fleet control plane. Signals only reach one host, which is fine until the fleet is several machines and the two things an operator actually wants are "finish this run and stop" and "hold everything, I am doing maintenance". Both are a single per-corpus fleet_control row that every worker reads at safe checkpoints. One write reaches the whole fleet and survives a restart, which a signal does not. The distinction between the two levers is the useful part. pause freezes between channels: no run is started or resumed, a mid-run slice stops with its rows left pending, and clearing the flag resumes that same run rather than opening a duplicate. drain lets the in-progress run finish properly, marked completed rather than interrupted, then opens nothing further and parks. A drain is what you want before a schema migration. A pause is what you want when the upstream link is flapping.
./dataset.sh pause "db migration" # freeze between channels
./dataset.sh drain "before 003" # finish the current run, then park
./dataset.sh resume # clear both
./dataset.sh align "cohort 4" # alignment snapshot at the next run boundaryBecause a forgotten hold is invisible by construction, the dashboard's control block goes loud when a flag is set, in yellow, carrying updated_at, updated_by and the note. With nothing held it collapses to a dim Control: normal on the run line.
=== CONTROL ===
drain
updated 2026-08-04 23:59:40 by tintando
note: holding for the 02:00 pg_dump
One-shot run modes. RUN_MODE=scrape_once and alignment_once drive exactly one completed run of that type and then park, which is what a final comparable-cohort capture needs. A crash mid-run resumes the same run instead of repeating it, because the guard keys on (RUN_MODE, ONCE_TOKEN); bumping the token re-arms a fresh one-shot.
Corpora as overlays. A corpus is its own database in the shared cluster, with its own seeds and its own run history, so cutting the fleet over to a different one is a one-line change plus a restart on each machine rather than a redeploy. dataset.sh wraps the lifecycle: create, use, list, current and migrate, the last re-applying db/migrations/*.sql idempotently to one corpus or all of them. Telethon sessions stay per account, never per corpus.
tgmon.sh is six tabs on a TTY that redraws in place: the run in progress, throughput, the storage breakdown, the issue list, the run history and a settings form. Every tab's query runs in the background from launch, so switching tabs never blocks on the slow ones. Overview answers whether the fleet is alive and how far the run has got.
1 Overview 2 Throughput 3 Storage 4 Issues 5 Runs 6 Settings
fleet tgdataset2 · view tgdataset2 · window 1h · auto 30s
=== CONTAINERS ===
db running (healthy) Up 6 days (healthy)
scraper running Up 17 hours
import exited Exited (0) 6 days ago
=== CURRENT RUN ===
Run #12 (scrape) running
Started: 2026-06-14 03:12:07 Duration: 17h 00m
Progress: 7690/7842/12065 channels (ok/attempted/total)
worker0: 2,566/2,617/4,022 ch (65.07% attempted)
worker1: 2,559/2,610/4,021 ch (64.91% attempted)
worker2: 2,565/2,615/4,022 ch (65.02% attempted)
Messages: 17,765,295
Control: normal
=== COLLECTION ===
Channels: 456,554 total | 447,142 active | 9,412 inactive | 11,908 complete
Messages: ~474,873,512 | ~36,016 edits tracked
lines 1-19/19
[1-6]tab [<>]nav [up/dn]scroll [r]efresh [R]all [w]in [a]uto [t]imeout [d]ataset [c]olor [?]help [q]uit
Throughput answers whether it is keeping pace. The per-worker split is the part worth having: a fleet where one machine has quietly fallen behind still looks fine in the total. Rates under the threshold render yellow, and messages are attributed to a worker by their parent channel, so a discussion group counts against whoever owns the broadcast channel it hangs off rather than against whoever happens to be reading it.
1 Overview 2 Throughput 3 Storage 4 Issues 5 Runs 6 Settings
fleet tgdataset2 · view tgdataset2 · window 1h · auto 30s
=== THROUGHPUT ===
Current run: 17,407 msgs/min | 461 ch/hr
ETA: ~9h 09m remaining
Last 1h: 1,044,420 msgs (17,407 msgs/min)
worker0: 343,920 msgs (5,732 msgs/min) | 198 ch
worker1: 352,860 msgs (5,881 msgs/min) | 191 ch
worker2: 347,640 msgs (5,794 msgs/min) | 203 ch
Avg run: 1d 02h 10m | 27,328,990 msgs
lines 1-9/9
[1-6]tab [<>]nav [up/dn]scroll [r]efresh [R]all [w]in [a]uto [t]imeout [d]ataset [c]olor [?]help [q]uit
- A snowball is not a sample. The corpus is whatever the seed list reaches by following forwards and mentions. It is not a random or representative slice of Telegram, and any rate computed on it is a within-corpus rate.
- Public channels only. A private or banned channel yields a snapshot with
is_privateset and every other field null, which records the loss rather than the channel. - Deletions are detected, not attributed. The scraper sees that a message is gone. Nothing distinguishes an author deleting their own post from moderation, and a message posted and removed entirely between two visits is never seen at all.
- Message media is not downloaded. Only
media_typeand the presence flag are stored. The one binary store in the schema isprofile_pictures. is_commentis a post-processing step. The scraper writes it false; the query that flips it for genuine comments on a broadcast post lives incomment_post_processing.mdand runs afterwards.- The expensive path scales with channel size. A large channel that deleted one message costs a full historical re-read.
docs/manually_skipping_full_check.mdcovers overriding that by hand. - The throughput count is a sequential scan. There is no index on
messages.collected_at, so past--timeoutthe dashboard falls back to aTABLESAMPLEestimate, marked with a~. - The dashboard is read-only. Pause, drain and align go through
dataset.sh; the TUI only shows the resulting state. - CI never talks to Telegram. The 256 tests cover the database and the run logic. Everything that depends on live Telethon object shapes sits outside that boundary.
Nine tables in three groups: channel identity and metadata, messages and edit history, and the operational bookkeeping that tracks what each run touched. fleet_control is a tenth, added by migration 002.
scraper/src/ holds the crawler: runner.py drives the run cycle and the control-plane checkpoints, messages.py implements the two-path detection, db.py owns every query, alignment.py the cutoff-anchored pass, extractors.py the Telethon-to-column mapping. db/init/001_schema.sql is the schema and db/migrations/ the increments after it. dataset.sh manages corpora, tgmon.sh is the dashboard, multi-config/ carries the fleet compose overlay.
| Document | Purpose |
|---|---|
docs/scraper_spec.md |
Full scraper specification |
docs/schema_design.md |
Schema rationale, table by table |
docs/schema.dbml |
Schema in DBML form |
docs/telethon_field_mapping.md |
Telethon object to database column mapping |
docs/deletion_detection_design.md |
Two-path deletion and edit detection |
docs/alignment_path_selection.md |
How alignment runs interact with deletion detection |
docs/alignment_cohort_bias.md |
Selection bias in the alignment cohort |
docs/channel_recovery_flags.md |
initial_pull_complete and needs_recheck |
docs/manually_skipping_full_check.md |
Overriding the expensive path for one channel |
docs/profiling_time_budget.md |
Where a run's wall-clock actually goes |
comment_post_processing.md |
Deriving is_comment after comment scraping |
multi-config/FLEET.md |
Deploying, controlling and recovering a multi-worker fleet |
The thesis written on this corpus, together with the analysis notebooks and the defense presentation, lives in strascico-thesis. Both name the corpus TGDataset2, which is what it was called when the thesis was submitted.
Python 3.13 and asyncio, Telethon for the MTProto client, asyncpg against PostgreSQL 16, Pillow and imagehash for profile-picture hashing. The fleet runs on Docker Compose. dataset.sh and tgmon.sh are Bash by choice, so a worker needs nothing installed to be inspected over SSH.
This project builds on the methodology and channel list of the original TGDataset by La Morgia et al.
Released under the MIT License. See LICENSE.
The three diagrams in docs/figures/ come from the thesis in strascico-thesis and are reused here under CC BY 4.0, © 2026 Gabriel Alonso Bustamante. See docs/figures/README.md.