Telegram Channel Monitoring API Tutorial

Read one public Telegram channel profile or a three-message sample with Python. Validate flat responses, preserve display counts and avoid hidden polling chains.

Dark cinematic render of a Telegram channel baseline resolving into a stream of new posts and a comment thread feeding an agent core

Before building a Telegram monitor, get one response that answers a smaller question: is this the public channel you intended, or what messages appear in a short recent-post sample? A channel profile and a message page have different shapes. A large-looking subscriber label does not establish exact audience size, and a saved cursor does not by itself prove a reliable, duplicate-free monitoring loop.

This 2026-11-08 repair checks current contracts and saved public references without making a new business call. Original 2026-09-27 UTC excerpts remain below, including a run-ID ambiguity in the old article. The new example performs one selected read and stops. It does not start a schedule, query every comment thread or claim that incremental monitoring was re-tested.

Key takeaway

  • Choose telegram/web/channel-info or telegram/web/channel-posts; the required request key is channel, not username.
  • Posts use a bare handle and an explicit limit of 3 here. The schema default is 20; a limit above 20 makes the server page toward older posts.
  • The business object is directly in outputs[0].data: profile fields for info, messages and pagination for posts. Do not add another data layer or a provider status_code rule.
  • Preserve abbreviated counts and unknown values. Associate a message ID with its channel, and treat continuation as a separate, untested decision.

The retained cover is conceptual artwork. Names, cards, counters and the pictured monitoring/comment chain are illustrative; they are not measurements or actions executed by this revision. The pictured handle, verification badge and REAL-TIME label are not identity or freshness evidence.

Choose one first request

Reader taskEndpointExample bodyInspect first
Check public channel metadataChannel info{"channel":"telegram"}title, username and available profile fields
Inspect a small recent-message sampleChannel posts{"channel":"telegram","limit":3}messages and pagination

Info’s schema documents a bare name, @handle or t.me link and automatic normalization. Posts describes a channel username. To keep the shared example within both contracts, it accepts only a bare handle such as telegram. This is a local input restriction, not a claim that the info API rejects links. A field called username in the returned profile does not rename the request field channel.

The selected posts schema allows integer limit 1–100, default 20. More than 20 explicitly enables server-side paging toward older posts. A single HTTP call can therefore represent a larger retrieval than a reader expects. This example fixes limit at 3 and omits before and after. Three is the requested sample bound, not a guarantee that three messages exist or that all recent activity has been covered.

Historical Telegram catalog Historical Telegram catalog screenshot. It shows the available navigation at capture time, not a newly validated comment workflow or a guarantee that every endpoint shares the same business parser.

Reuse setup and state the stopping point

If you already have a SandBase key, keep SANDBASE_API_KEY in the local environment or secret manager. A connected agent should reuse it and receive one chosen task, not silently call both endpoints to establish a baseline. The selected public reads do not ask for a Telegram login, bot token or MTProto session; that does not grant access to private chats or account-authorized actions.

For a new project, hand the agent SKILL.md, quickstart.md and the human quickstart. A useful request is: “Read up to three recent public messages from telegram, preserve missing fields and pagination metadata, then show the returned field names.” Keep the key outside the chat. Decide on storage, analysis and additional requests after seeing the first result.

Use Python with requests installed. The helper below validates inputs before network access, sets connect/read timeouts and rejects redirects. It sends one request, does not retry, and keeps error text free of upstream response bodies and credentials. A timeout or an HTTP error is a stopping condition rather than an invitation to spend again automatically.

One request, two explicit parsers

Python
import os
import re
import requests


def first_request(task, channel):
    if task not in ("info", "posts"):
        raise ValueError("Choose info or posts")
    # This example accepts bare handles only; it does not normalize links.
    if not isinstance(channel, str) or not re.fullmatch(r"[A-Za-z0-9_]+", channel):
        raise ValueError("Use a nonempty bare channel handle")
    key = os.environ.get("SANDBASE_API_KEY", "").strip()
    if not key:
        raise ValueError("Set SANDBASE_API_KEY in the local environment")
    route = "channel-info" if task == "info" else "channel-posts"
    params = {"channel": channel}
    if task == "posts":
        params["limit"] = 3
    try:
        response = requests.post(
            f"https://api.sandbase.ai/v1/api/telegram/web/{route}",
            headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"},
            json=params, timeout=(10, 90), allow_redirects=False,
        )
        if not 200 <= response.status_code < 300:
            raise RuntimeError(f"HTTP {response.status_code}; request stopped")
        body = response.json()
    except ValueError:
        raise RuntimeError("Response was not valid JSON") from None
    except requests.RequestException:
        raise RuntimeError("Network request failed or timed out") from None
    if not isinstance(body, dict) or body.get("status") != "completed":
        raise RuntimeError("SandBase request did not complete")
    outputs = body.get("outputs")
    if not isinstance(outputs, list) or not outputs or not isinstance(outputs[0], dict):
        raise RuntimeError("Missing documented output")
    payload = outputs[0].get("data")
    if not isinstance(payload, dict):
        raise RuntimeError("Missing business object")
    if task == "info":
        if any(not isinstance(payload.get(field), str) or not payload[field]
               for field in ("title", "username")):
            raise RuntimeError("Missing reference channel identity fields")
    else:
        if not isinstance(payload.get("channel"), str) or not payload["channel"]:
            raise RuntimeError("Missing response channel")
        messages = payload.get("messages")
        if not isinstance(messages, list) or any(not isinstance(m, dict) for m in messages):
            raise RuntimeError("Missing or malformed messages array")
        if not isinstance(payload.get("pagination"), dict):
            raise RuntimeError("Missing reference pagination object")
    return payload


if __name__ == "__main__":
    result = first_request("posts", "telegram")
    print("Business fields:", sorted(result))

For the independent profile task, replace the final assignment with result = first_request("info", "telegram") and keep the print statement. Do not append that line after the posts request unless you intend a second call. No model field belongs in either body; the operation is selected by its vendor-qualified POST URL.

The reference-based info check requires title and username strings. The posts check requires a response channel, a messages array of objects and a pagination object. These are local guards for the selected references, not a schema for every Telegram route. A present empty messages array is accepted. Missing collections or malformed envelopes fail loudly, rather than appearing as a successful quiet channel. Optional counters, media, text and flags are returned unchanged.

Read the original evidence with its limits

The original article dated the following channel-info excerpt 2026-09-27 UTC. Its abbreviated subscriber count is a historical observation, not the channel’s current value:

JSON
{
  "id": "8c815356-e1f6-4668-959c-375f9471822f",
  "status": "completed",
  "model": "telegram/web/channel-info",
  "outputs": [
    {
      "data": {
        "title": "Telegram News",
        "username": "telegram",
        "subscribers": "9.46M",
        "verified": true,
        "counters": { "photos": "16", "videos": "228", "links": "378" }
      }
    }
  ]
}

The old channel-posts excerpt is also retained without alteration:

JSON
{
  "id": "8c815356-e1f6-4668-959c-375f9471822f",
  "status": "completed",
  "model": "telegram/web/channel-posts",
  "outputs": [
    {
      "data": {
        "messages": [
          {
            "id": 460,
            "date": "2026-08-26T19:12:34+00:00",
            "text": "…",
            "views": "1.48M",
            "is_forwarded": false,
            "reactions": []
          }
        ],
        "pagination": { "after_cursor": 460, "before_cursor": 441, "has_more_before": true, "limit": 20 }
      }
    }
  ]
}

Both old excerpts use run ID 8c815356-e1f6-4668-959c-375f9471822f even though their model fields differ. That is an attribution ambiguity in the original record. This repair cannot use that shared ID alone as proof of two separate executions, and it does not silently replace either ID with a guessed value.

The independently saved public examples have timestamps 2026-10-07T17:37:02.535Z for info and 2026-10-07T17:37:14.205Z for posts. Their saved inputs are channel telegram, with limit 3 for posts. They support the direct profile and messages/pagination shapes used here. They are reference material read on November 8, not fresh runs made for this revision. The shorter README and full saved example can show different subscriber display values; do not merge them into a measured growth series.

Historical channel-posts parameter reference Historical channel-posts parameter and envelope reference. Before/after are current documented inputs, but this revision sends neither and has not tested continuation or an incremental polling loop.

Subscriber and view labels are not exact reach

Values such as 9.46M subscribers and 1.48M views in the original excerpts are display strings. A stored reference may show another abbreviated value. Keep the raw string with its retrieval context. Converting an abbreviation into an approximate number does not recover the hidden precision or prove that two snapshots used the same rounding rule.

Subscribers describe a channel-level display count, while views belong to a message observation. A view label is not a count of unique readers or a conversion metric. Do not divide rounded views by rounded subscribers and label the result an exact engagement rate. Nor does a changed display label, by itself, establish a precisely measured growth amount.

Missing views remain unknown; an empty reactions array is an observed empty array, not proof of zero engagement everywhere. False is a returned boolean, while null can mean a field does not apply. Preserve these distinctions. A short reference that omits views or type does not prove the endpoint never returns them, and the example does not insert zero values to make a report look complete.

Keep channel identity with every message

A numeric message ID belongs to a channel. If you later store records from several channels, use channel plus message ID rather than a global ID-only map. Keep the requested handle, response channel and any returned channel identity separate until you verify that they refer to the intended source. The helper preserves the response; it does not silently rewrite its identity to match the input.

A forwarded flag and forwarded_from value describe the observed message’s attribution. They are not an instruction to fetch the source channel. Likewise, text_html contains markup rather than plain text: a display layer must handle it deliberately instead of assuming it is safe to insert unchanged into a page. The example prints field names and does not render HTML, open link previews or download photos and videos.

The content of a media object is bounded by what the reference supplied. An empty photos or videos list does not establish that all media is available, especially when has_unsupported is present. An attached URL is a reference, not evidence that a file was retrieved or that republication rights have been granted.

Cursor direction is documented; continuation was not tested

The selected schema describes after as an integer cursor for newer posts and before as an integer cursor for older posts, using pagination.after_cursor and pagination.before_cursor from the previous result. Defaults are zero. The saved post sample also includes has_more_before, count, limit and pages_fetched. Preserve those values if returned; do not manufacture them from message IDs or expected page length.

This example does not send a cursor, increment IDs or fetch another page. It also makes no claim that polling after a remembered cursor guarantees no duplicates or no missed messages. Building that workflow requires testing actual continuation behavior, deciding when to persist cursor state and handling failed captures. Repeated calls, retries and comments are additional workload, not invisible setup.

Historical post-comments parameter reference Historical post-comments parameter reference. Comments are outside this revision’s two selected tasks; the image does not establish that every message has an accessible thread or that its replies were fetched again.

Budget a read before a monitor

Free inspect on 2026-11-08 lists both selected endpoints at $0.001, eligible for the organization’s 100 daily calls shared across eligible APIs, resetting at 00:00 UTC. Eligibility is not the remaining allowance or balance. No actual charge was measured here, and successful free execution is not promised.

One selected request lists at $0.001; choosing info and posts independently lists at $0.002 before quota effects. The old comment loop could add a call for each qualifying message. A polling schedule multiplies requests again. Limit above 20 also changes retrieval behavior inside the posts request, so a count of HTTP calls is not a measure of the number of underlying pages or messages.

What remains historical

All original Python is preserved verbatim with hashes in the historical archive. The archived blocks include automatic comment traversal, permissive empty defaults, cursor progression and a monitoring skeleton. They document the old article and are not current runnable instructions. This repair replaces that main path with one bounded request and keeps the historical evidence visible.

FAQ

Is the request key username? No. Use channel. The profile’s username is an output field; it does not change the selected request contract.

Why use limit 3 instead of the default? It keeps the first sample small and avoids the documented above-20 server-side backfill behavior. It is not a claim of complete channel coverage.

Can I calculate exact audience growth? Not from abbreviated display strings alone. Preserve the source values and their dates; do not turn approximate subscriber or view labels into exact growth or unique-reader claims.

Where do I go after the first result? The Telegram API hub links the selected endpoints and distinguishes historical navigation for other tasks. Define the next question and its budget before adding pagination, comments, analysis or a schedule.

Found this useful? Share it