DEV Community

Cover image for How to scrape a public Telegram channel without the Telegram API
PIC DEV
PIC DEV

Posted on

How to scrape a public Telegram channel without the Telegram API

The standard advice for reading a Telegram channel from code is Telethon or Pyrogram. That means registering an application to get an api_id, logging in with a phone number, storing a session file and handling flood waits. It is the right tool for private chats and for anything that needs an account.

For public channels it is more than you need. Telegram publishes a web preview of every public channel at https://t.me/s/<channel>, and it is plain HTML.

Open t.me/s/durov in a browser with JavaScript turned off and the posts are still there.

Reading the preview

Each post is a div.tgme_widget_message with a data-post="channel/id" attribute. Inside it:

Data Selector
Text div.tgme_widget_message_text.js-message_text
Date a.tgme_widget_message_date time, attribute datetime
Views .tgme_widget_message_views
Reactions .tgme_widget_message_reactions .tgme_reaction
Photos a.tgme_widget_message_photo_wrap, URL in the background-image style
Forwarded from .tgme_widget_message_forwarded_from_name

Two query parameters do the rest:

  • ?before=<post id> returns the page of posts older than that ID. A page holds 20 posts.
  • ?q=<text> searches the whole history of the channel. It combines with before.

The code

pip install httpx selectolax

import httpx
from selectolax.lexbor import LexborHTMLParser


def parse(html):
    posts = []
    for node in LexborHTMLParser(html).css("div.tgme_widget_message[data-post]"):
        channel, post_id = node.attributes["data-post"].split("/")
        text = node.css_first("div.tgme_widget_message_text.js-message_text")
        time = node.css_first("a.tgme_widget_message_date time")
        views = node.css_first(".tgme_widget_message_views")
        posts.append({
            "id": int(post_id),
            "url": f"https://t.me/{channel}/{post_id}",
            "date": time.attributes.get("datetime") if time else None,
            "text": text.text(separator="\n").strip() if text else None,
            "views": views.text() if views else None,  # "2.1M", "764K"
        })
    return posts


def channel_posts(channel, limit=100, query=None):
    """Newest first. `query` searches the whole history of the channel."""
    posts, before = [], None
    with httpx.Client(headers={"User-Agent": "Mozilla/5.0"}, timeout=30) as client:
        while len(posts) < limit:
            params = {}
            if before:
                params["before"] = before
            if query:
                params["q"] = query
            page = parse(client.get(f"https://t.me/s/{channel}", params=params).text)
            if not page:
                break
            posts += sorted(page, key=lambda p: -p["id"])
            before = min(p["id"] for p in page)
    return posts[:limit]


if __name__ == "__main__":
    for post in channel_posts("durov", limit=45):
        print(post["date"], post["url"], post["views"], (post["text"] or "")[:60].replace("\n", " "))
    print(len(channel_posts("durov", limit=30, query="TON")), "posts mention TON")
Enter fullscreen mode Exit fullscreen mode

Output when I ran it:

2026-11-26T15:26:13+00:00 https://t.me/durov/574 272K Telegram gifts are the only NFTs still alive.
2026-11-25T12:56:51+00:00 https://t.me/durov/573 770K He actually paid $1,000,000 in Grams for @liar.
...
22 posts mention TON
Enter fullscreen mode Exit fullscreen mode

What you run into

View counts are rounded. The preview shows 272K and 1.01M, not exact numbers. Convert them if you want to sort or chart, and do not expect more precision than three digits.

A missing channel is a redirect, not a 404. If the channel does not exist, is private, or has no preview, t.me/s/<name> answers 302 to t.me/<name>. Do not follow redirects blindly or you will parse the wrong page and get zero posts with no error.

Post IDs have gaps. Deleted posts and albums leave holes, so before = oldest_id - 20 skips content. Always take the smallest ID you actually received.

Albums are one post. Several photos arrive under a single ID, each in its own photo_wrap element.

Custom emoji reactions have no character. Standard reactions are an emoji; custom ones are an ID. Paid star reactions are marked with a separate class.

429 on bursts. Many requests in parallel get throttled. Back off for several seconds when it happens and keep the concurrency low.

What is not there at all: comments, member lists, private channels, most groups, and search across all of Telegram. For those you do need the API and an account.

Turning it into a monitor

To follow a channel, store the highest post ID you have seen and on the next run keep only the posts above it. One request per channel covers the last 20 posts, so a check every few minutes is cheap. The state is one integer per channel.

A hosted version

I run this as an Apify Actor, Telegram Channel Scraper, with the parts that the short script leaves out: reactions, media URLs, polls, link previews, forwards, retries and a monitor mode that remembers the last post for you. It costs $1.50 per 1,000 posts. I built it and I earn from it. There are ready-made examples, including one that sends new posts to a Slack or Discord webhook, in this repository.

curl -s -X POST \
  "https://api.apify.com/v2/acts/picdev~telegram-channel-scraper-posts-monitor/run-sync-get-dataset-items" \
  -H "Authorization: Bearer $APIFY_TOKEN" -H "Content-Type: application/json" \
  -d '{"channels": ["durov"], "onlyNewPosts": true, "monitorName": "demo"}'
Enter fullscreen mode Exit fullscreen mode

For one channel and text only, the script above will do.

Top comments (1)

Collapse
 
dosaygo profile image
DOSAYGO •

When archiving a public Telegram channel from the t.me/s web preview before posts are edited or deleted, do you also save a browsable copy of each post's linked discussion comments?