Mark Wang
Mark Wang

Reputation: 352

Search all public posts in telegram, even channels that you're not in

I'm trying to do a public posts search through all channels (including ones you're not in) in telegram programmatically. I know this can be done through the desktop client: see screenshot.

I've tried using telethon, specifically, the SearchGlobalRequest method and client.iter_messages setting entity as None. However, this only searches through channels that you're a member of.

I've searched stackoverflow before, but the last relevant answer said this wasn't possible. I'm wondering if it's been made possible since.

Upvotes: 1

Views: 1190

Answers (1)

MustA
MustA

Reputation: 1148

Telegram introduced hashtag / cashtag searching recently in May. Accessable through raw api SearchPostsRequest:

used usually as await get_public_posts('$TART', limit=None)


from telethon.utils import get_peer_id
from telethon.tl.types import InputPeerEmpty
from telethon.tl.functions.channels import SearchPostsRequest


async def get_public_posts(tag: str, limit: int = 100):
    offset_peer = InputPeerEmpty()
    next_rate = offset_id = 0
    messages = []
    while True:
        r = await client(
            SearchPostsRequest(tag, next_rate, offset_peer, offset_id, 100)
        )
        entities = {get_peer_id(en): en for en in r.chats + r.users}
        for message in r.messages:
            message._finish_init(client, entities, message.peer_id)
            if len(messages) == limit:
                return messages
            messages.append(message)
        offset_id = messages[-1].id
        offset_peer = messages[-1].peer_id
        next_rate = getattr(r, 'next_rate', None)
        if not next_rate:
            return messages

Upvotes: 2

Related Questions