JayJona
JayJona

Reputation: 502

read messages from public telegram channel using telethon

I am using Telethon to automate some stuff from Telegram channels. I have already obtained my API key, hash, and token and I can start a new session using Telethon.

The problem is that when a new message arrives from some selected channels, I want to print the text but the code I wrote does not seem to work and I do not understand why. It correctly enters the loop printing "Listening" but nothing is printed when a new message arrives.

This is my code

import configparser
import asyncio

from telethon import TelegramClient, events

# Reading Configs
config = configparser.ConfigParser()
config.read("config.ini")

# Setting configuration values
api_id = int(config['Telegram']['api_id'])
api_hash = str(config['Telegram']['api_hash'])
phone = config['Telegram']['phone']
username = config['Telegram']['username']


channels_list = ["channel1", "channel2"] #these are public channel names taken from https://web.telegram.org/k/#@channelname for example



async def main():
    client = TelegramClient('session_name', api_id, api_hash)
    await client.start(phone)

    @client.on(events.newmessage.NewMessage())
    async def my_event_handler(event):
        print("hello")
        print(event)
    sender = await event.get_sender()
        if sender.username in channels_list:
            channel = sender.username
            # get last message of the channel
            async for message in client.iter_messages(channel, limit=1):
                print(message.text)


    print("Listening...")

    await client.run_until_disconnected()




if __name__ == '__main__': 
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

Upvotes: 1

Views: 81

Answers (1)

Khaliknazar
Khaliknazar

Reputation: 111

You could maybe try this, and use decorator @client.on(events.newmessage.NewMessage()) out of function

channels_list = []  #these are public channel names taken from https://web.telegram.org/k/#@channelname for example

client = TelegramClient(...)


async def main():
    await client.start()
    await client.run_until_disconnected()


@client.on(events.newmessage.NewMessage())
async def my_event_handler(event):
    # get new message of the channel
    print(event.message.message)


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

Upvotes: 2

Related Questions