Want to extract pinned messages from the groups/channels on Telegram i am part of using Telethon

Question:

I’m using Telethon API
Want to extract pinned messages of all the channels i am member.
Please guide me with the procedure.

Thank you.

Asked By: vinay kusuma

||

Answers:

You can use GetFullChannelRequest and GetHistoryRequest methods to extract pinned message from one channel

from telethon import TelegramClient
from telethon.tl.functions.channels import GetFullChannelRequest
from telethon.tl.functions.messages import GetHistoryRequest
from telethon.tl.types import PeerChannel

api_id = XXXXX
api_hash = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
phone_number = '+98XXXXXXXX'
################################################

client = TelegramClient('session_name',
                    api_id,
                    api_hash
                    )

assert client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone_number)
    me = client.sign_in(phone_number, input('Enter code: '))

channel_entity = client.get_entity(PeerChannel(channel_id))

channel_info = client(GetFullChannelRequest(channel_entity))

pinned_msg_id = channel_info.full_chat.pinned_msg_id

if pinned_msg_id is not None:
    posts = client(GetHistoryRequest(
        channel_entity,
        limit=1,
        offset_date=None,
        offset_id=pinned_msg_id + 1,
        max_id=0,
        min_id=0,
        add_offset=0,
        hash=0
    ))
    print(posts.messages[0].to_dict())

I used Telethon V0.19, but the previous versions are pretty much the same

Answered By: Alihossein shahabi

As of Telethon 1.2, the code is a lot simpler:

from telethon import TelegramClient, types, sync
with TelegramClient('name', api_id, api_hash) as client:
    message = client.get_messages('TelethonChat', ids=types.InputMessagePinned())

This won’t work for private chats, however (e.g. to fetch the pinned message with yourself). For that, as the currently accepted answer hints, we have to fetch the Full object. For the case of the private chat, this is UserFull by using GetFullUserRequest:

chat = 'me'
full = client(functions.users.GetFullUserRequest(chat))
message = client.get_messages(chat, ids=full.pinned_msg_id)
Answered By: Lonami

To get all pinned messages from channel using Telethon 1.19.5 (sync version) and above you can

from telethon.tl.types import InputMessagesFilterPinned
from telethon import TelegramClient, sync  # noqa: F401

channel_id = -1009999999999

with TelegramClient("name", api_id, api_hash) as client:
    # we need to set limit
    # because otherwise it will return only first pinned message
    pinned_messages = client.get_messages(
        channel_id,
        filter=InputMessagesFilterPinned,
        limit=1000,
    )
    for message in pinned_messages:
        print(message.message)
Answered By: Artem Bernatskyi