skip to Main Content

Having read the following question:
How to save message from telegram channel as variable

I need to do the same but from a NewMessage event, storing the content of the message in a variable.

However, neither event.text nor event.raw_test seem to be storable in a variable

The following code:

import asyncio
from telethon import TelegramClient, events

import logging
logging.basicConfig(format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s',
                    level=logging.WARNING)

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


channel = 'xxx'


async def main():
        @client.on(events.NewMessage(chats=channel))
        async def handler(event):
            await print (event.text)

        await client.run_until_disconnected()


loop = asyncio.get_event_loop()
loop.run_until_complete(main())

works printing the new channel message, but it gives me two errors along the printed message:

  • await callback(event)
  • TypeError: object NoneType can’t be used in ‘await’ expression

But when I change

        await print (event.text)

for

        msg = await event.text
        print(msg)

I get the same two errors but this time nothing is printed…and I need to save the text from the message as a variable in order to continue the script.

It also doesnt work declaring the variable msg before the function and making it global inside it.

I dont know what else to try. Thanks in advance.

2

Answers


  1. from telethon import TelegramClient, events
    
    import logging
    logging.basicConfig(format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s',
                        level=logging.WARNING)
    
    client = TelegramClient('session', 'api_id', 'api_hash')
    client.start()
    
    channel = 'xxx'
    
    
    @client.on(events.NewMessage(chats=channel))
    async def handler(event):
        print(event.message.message)
    
    
    client.run_until_disconnected()
    

    You don’t need to wrap listener with another async function. And also, you don’t need to await print, just use plain print

    Login or Signup to reply.
  2. The Telethon docs covers this quite well (adapted for your use case):

    from telethon import TelegramClient, events
    
    client = TelegramClient('session', api_id, api_hash)
    
    channel = "xxx"
    
    @client.on(events.NewMessage(chats=channel))
    async def my_event_handler(event):
        print(event.text) # this doesn't need an "await"
    
    client.start()
    client.run_until_disconnected()
    

    Also notice that I haven’t put the event handler in another function, and the run_until_disconnected() call doesn’t call any function, nor is it in one. You don’t even need to import asyncio

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search