> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.beatapi.io/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.beatapi.io/_mcp/server.

# Archive a bounded batch of Telegram channel messages

> Re-check one Telegram announcement with telegram.web.fetch_post_detail, or archive a bounded batch of channel messages with telegram.web.fetch_channel_posts and a traceable evidence bundle.

Re-check a single Telegram announcement with `telegram.web.fetch_post_detail` to detect edits against your saved copy, or archive recent announcements for a weekly brief with `telegram.web.fetch_channel_posts`, `archive_telegram.py`, cursor-bounded pagination, and `build_archive_report.py`. Telegram channel admins can edit published messages, so re-checking an existing announcement is a separate task from finding newly published posts. [Telegram Channels](https://telegram.org/tour/channels?setln=en)

For example, you shared an event announcement on Monday. On Wednesday, someone asks whether the meeting point moved. With the original message link and Monday's copy, fetch the message again and compare the two versions.

## How do I check whether an announcement shared in chat has changed?

Split a link such as `t.me/example/123` into the channel username `example` and the integer message ID `123`, and replace both values with the values from your real link. POST the JSON below to `https://api.beatapi.io/v1/social-data/call` with your BeatAPI Bearer credential.

```json
{"action":"telegram.web.fetch_post_detail","params":{"channel":"example","post_id":123}}
```

1. Confirm that the response is the announcement you shared.
2. Record the message link, the time checked, the previous location, the current location and the request ID.
3. If Monday's copy says Gate A and the latest version says Gate C, share Gate C together with the original link. If you only have the current version, report the current location and the time you checked.

To put several recent announcements into a weekly brief, follow steps 1–7 below.

## 1. Set a bounded goal

Start with one public channel and one page of recent announcements (`limit: 20`) for the weekly brief. Every list page and every single-message detail request is billed as a separate request. [BeatAPI pricing](https://beatapi.io/pricing)

## 2. Fetch the initial batch

```bash
curl --fail-with-body -sS https://api.beatapi.io/v1/social-data/call \
  -H "Authorization: Bearer $BEATAPI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"action":"telegram.web.fetch_channel_posts","params":{"channel":"<channel_username>","limit":20}}' \
  -o telegram-page-1.json
```

Replace `<channel_username>` with the channel username. If the HTTP request fails, keep the error output and stop; do not run the archive step. Save each later request under a new raw filename.

## 3. Validate and archive the raw response

Save the script below as `archive_telegram.py`. `archive_telegram.py` checks the business status, the action and the `data` object, validates the cursor types, saves the entire payload and refuses to overwrite an existing archive file.

```python
import json,pathlib,sys
source,target=map(pathlib.Path,sys.argv[1:3])
r=json.loads(source.read_text(encoding="utf-8"))
if r.get("status")!="succeeded" or r.get("action")!="telegram.web.fetch_channel_posts":
    raise ValueError("Expected successful Telegram channel posts")
data=r.get("data")
if not isinstance(data,dict): raise ValueError("Expected channel response object")
if not isinstance(r.get("request_id"),str) or not r["request_id"].strip():raise ValueError("Missing request_id")
paging=data.get("pagination")
if paging is None:paging={}
if not isinstance(paging,dict): raise ValueError("Invalid pagination")
cursors={}
for name in ("before_cursor","after_cursor"):
    value=paging.get(name)
    if value is not None and (isinstance(value,bool) or not isinstance(value,int)):
        raise ValueError("Cursor must be an integer")
    cursors[name]=value
with target.open("x",encoding="utf-8") as f:
    json.dump({"action":r["action"],"request_id":r.get("request_id"),"data":data},f,ensure_ascii=False,indent=2)
print(json.dumps(cursors))
```

## 4. Run and review

```bash
python3 archive_telegram.py telegram-page-1.json telegram-archive-1.json
```

The archive file keeps `action`, `request_id` and `data`. Also keep a request manifest with the channel, the paging direction, the parameters and the collection time. A saved payload does not mean every historical message was retrieved. `archive_telegram.py` only preserves the payload; `build_archive_report.py` in step 6 extracts the documented message array.

## 5. Continue only within the budget

1. For older messages, pass the printed `before_cursor` as `before`. For newer messages, pass the printed `after_cursor` as `after`.
2. Keep `channel` and `limit` unchanged, and save each page under a new filename.
3. Stop when a cursor is missing or repeated, or when you reach the request cap. A missing cursor is not a reason to request page one again.

Budget each next request separately. Channel search and comments use their own actions, not the `before` and `after` pagination parameters.

[Identifiers](/faq/telegram-channel-identifiers) · [Pagination and search](/faq/telegram-pagination)

BeatAPI sanitizes and passes through `data` directly, returning `data.messages`, `data.channel_info`, and `data.pagination` with integer `before_cursor` and `after_cursor` fields.

## 6. Share an archive that links back to each response

Hand over four artifacts: the original response pages, the request manifest, the message file `message-records.jsonl` and the coverage report `report.json`. `build_archive_report.py` writes one object from `data.messages` per JSONL line. To verify an announcement, use the record's request ID and page position to open the original response page, then open the Telegram message.

Keep the original response for every page. When a teammate opens one message in `message-records.jsonl`, the request ID and page position lead back to the exact response that contained the message.

Save `manifest.json` with the actual request-completion time, including the timezone, for each request. Each `response_file` must name the raw response of that request. The example below shows the expected `manifest.json` format for one page:

```json
[{"params":{"channel":"YOUR_CHANNEL","limit":20},"collected_at":"2026-11-16T14:00:00+00:00","response_file":"telegram-page-1.json"}]
```

Save the script below as `build_archive_report.py`, and record the actual parameters for every additional page in `manifest.json`. `build_archive_report.py` rejects mixed channels or limits, repeated requests or request IDs, timestamps that do not increase, failed responses and broken cursor chains. The script copies the original bytes, records each file's SHA-256 and leaves the source files unchanged. `message_count` in `report.json` stays `null`, because a page count is not a message count.

```python
import datetime,hashlib,json,pathlib,sys
manifest=pathlib.Path(sys.argv[1])
target=pathlib.Path(sys.argv[2])
entries=json.loads(manifest.read_text(encoding="utf-8"))
if not isinstance(entries,list) or not entries:raise ValueError("Nonempty manifest required")
pages=[];seen=set();request_ids=set();channel=None;blobs=[];direction=None;last_time=None;batch_limit=None;records=[]
for entry in entries:
    params=entry["params"]
    name=params["channel"]
    if not isinstance(name,str) or not name.strip():raise ValueError("Channel required")
    if channel is None:channel=name
    if name!=channel:raise ValueError("Do not mix channels")
    stamp=entry["collected_at"]
    dt=datetime.datetime.fromisoformat(stamp.replace("Z","+00:00"))
    if dt.tzinfo is None:raise ValueError("Use timestamp with timezone")
    if last_time is not None and dt <= last_time:raise ValueError("Request times must increase")
    last_time=dt
    if set(params)-{"channel","limit","before","after"}:raise ValueError("Unknown request parameter")
    limit=params.get("limit",20)
    if type(limit) is not int or not 1<=limit<=100:raise ValueError("limit must be 1-100")
    if batch_limit is None:batch_limit=limit
    if limit!=batch_limit:raise ValueError("Keep limit unchanged within a scan")
    before=params.get("before",0);after=params.get("after",0)
    if type(before) is not int or type(after) is not int:raise ValueError("Request cursors must be integers")
    if before and after:raise ValueError("Conflicting directions")
    active="before" if before else ("after" if after else None)
    if pages:
        if active is None:raise ValueError("Do not restart at the initial page")
        if direction is not None and active!=direction:raise ValueError("Use separate scans for older and newer pages")
        previous=pages[-1]["returned_cursors"][active+"_cursor"]
        if previous in (None,0) or params[active]!=previous:raise ValueError("Cursor does not continue the previous response")
    if active:direction=active
    canonical={"channel":name,"limit":limit,"before":before,"after":after}
    identity=json.dumps(canonical,sort_keys=True)
    if identity in seen:raise ValueError("Repeated request parameters")
    seen.add(identity)
    path=pathlib.Path(entry["response_file"])
    if not path.is_absolute():path=manifest.parent/path
    raw=path.read_bytes();r=json.loads(raw)
    if r.get("status")!="succeeded" or r.get("action")!="telegram.web.fetch_channel_posts":
        raise ValueError("Failed or wrong action")
    request_id=r.get("request_id")
    if not isinstance(request_id,str) or not request_id.strip() or request_id in request_ids:
        raise ValueError("Distinct nonempty request_id required")
    request_ids.add(request_id)
    if not isinstance(r.get("data"),dict):raise ValueError("Missing data object")
    messages=r["data"].get("messages")
    if not isinstance(messages,list) or any(not isinstance(message,dict) for message in messages):
        raise ValueError("Expected documented data.messages array of objects")
    for index,message in enumerate(messages):
        records.append({"channel":name,"request_id":request_id,"collected_at":stamp,
                        "source_sha256":hashlib.sha256(raw).hexdigest(),"page_index":len(pages),
                        "message_index":index,"message":message})
    paging=r["data"].get("pagination")
    if paging is None:paging={}
    if not isinstance(paging,dict):raise ValueError("Invalid pagination object")
    cursors={key:paging.get(key) for key in ("before_cursor","after_cursor")}
    for value in cursors.values():
        if value is not None and (isinstance(value,bool) or not isinstance(value,int)):
            raise ValueError("Invalid cursor")
    filename="page-"+str(len(pages)+1)+".json"
    blobs.append((filename,raw))
    pages.append({"params":params,"collected_at":stamp,"request_id":r.get("request_id"),
                  "source_file":str(path),"archived_file":filename,
                  "sha256":hashlib.sha256(raw).hexdigest(),"returned_cursors":cursors,"message_records":len(messages)})
report={"state":"partial","channel":channel,"pages":pages,"direction":direction,"limit":batch_limit,
        "message_count":None,"message_records":len(records),"count_basis":"Occurrences, not unique messages",
        "coverage":"Recorded requests only; not full history",
        "generated_at":datetime.datetime.now(datetime.timezone.utc).isoformat()}
target.mkdir()  # Refuse existing directories; all source validation happened above.
for filename,raw in blobs:(target/filename).write_bytes(raw)
with (target/"message-records.jsonl").open("x",encoding="utf-8") as output:
    for record in records:output.write(json.dumps(record,ensure_ascii=False)+"\n")
(target/"report.json").write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding="utf-8")
print(str(target/"report.json"))
```

```bash
python3 build_archive_report.py manifest.json telegram-evidence-batch-1
```

Open `report.json` and check each source file, `request_id`, timestamp and returned cursor against the preserved response. A missing or zero cursor ends that direction; zero is the default of the initial request, not permission to start again from page one. Keep older and newer scans in separate batches. Within one batch, keep `channel`, `limit` and the paging direction unchanged, let the request times increase, and take each next cursor from the previous saved response. A missing cursor ends the batch and does not prove that the history is complete. The destination directory must not exist yet. If a disk write is interrupted, inspect the partial destination, then retry with a new directory name. `build_archive_report.py` makes no network calls.

## 7. Review message records and keep the source of each record

BeatAPI returns `messages`, `channel_info`, and `pagination` under `data`, so the message array path is `data.messages`. Each line of `message-records.jsonl` holds one complete message object plus the channel, `request_id`, collection time, the raw response's SHA-256 and the page position.

Open `message-records.jsonl` in a JSON-lines viewer and work through the records as follows:

1. Filter by `request_id` or `page_index` to find the raw page a record came from. `message_index` is the zero-based position within that page, not a Telegram message ID.
2. Read `message_records` as the number of returned occurrences. Overlapping pages stay intact, so two different messages with the same text are never merged.
3. An empty `messages` array produces an empty JSONL file; a missing `messages` array is rejected instead of being reported as zero.
4. The exact ID and text fields inside each message object are not verified, so the bundle contains no normalized text CSV, and `message_records` is not a count of unique messages.

Keep `channel_info` and all other fields in the raw pages. Signed media links are not durable files; do not download or re-host the media without the relevant rights. Before sharing, remove personal data from a copy and keep the original privately.