Sebastian216
Sebastian216

Reputation: 101

Telethon reading message from Channel with id

Hello I'm using Telethon 1.21.1  The most question here are outdated.

This scripts task is to read a message of a specific Channel per id.

I'm not sure where to pass the info for the channel and how if I use the method to read the msg in the proper way. await but I'm not sure how I pull it off

This is what I have:

my_private_channel_id = "-100777000"
my_private_channel = "test"

api_id = # 7 Digit Telegram API ID.
api_hash = ''   # 32 Character API Hash
phone = '+'   #Enter Your Mobilr Number
client = TelegramClient(phone, api_id, api_hash)
async def main():
    await client.send_message('me', 'Hello !!!!') # just to test connection
with client:
    client.loop.run_until_complete(main())
client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone)
    client.sign_in(phone, input('Enter verification code: '))

chats = []
last_date = None
chunk_size = 200
channels=[] #target channel
result = client(GetDialogsRequest(
             offset_date=last_date,
             offset_id=0,
             offset_peer=InputPeerEmpty(),
             limit=chunk_size,
             hash = 0
         ))
chats.extend(result.chats)

for chat in chats:
    try:
        if chat.channels== True:
            readmsg =  client.get_messages(chat, None)
    except:
        continue

Upvotes: 5

Views: 4843

Answers (2)

uingtea
uingtea

Reputation: 6554

I use this

channel = await client.get_entity(PeerChannel(-xxxxxxxxxx))
# ids: int or list(int)
messages = await client.get_messages(channel, ids=[1234, 4564])
for msg in messages:
    print(msg)

Upvotes: 0

Sebastian216
Sebastian216

Reputation: 101

from telethon import TelegramClient, events

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

@client.on(events.NewMessage(chats="@TelethonUpdates"))
async def my_event_handler(event):
   print(event.text)

client.start()
client.run_until_disconnected()

This is the right and simple way.

Upvotes: 4

Related Questions