How to use NewMessage event of telethon on google colab

Viewed 244

I have this code and I want to run it on google colab. It works great on my PC but on colab I always get errors like these:

SyntaxError: 'async with' outside async function

or

RuntimeError: You must use "async with" if the event loop is running (i.e. you are inside an "async def")

sometimes it does not wait for getting new messages and finish after one running.

import json
import time
import telethon as tlt
import asyncio
from telethon import events,TelegramClient

chat_name = "sample"


telegram_session="sample_1"
api_id = "0000000"
api_hash = ""

client = TelegramClient(None , api_id, api_hash)

@client.on(events.NewMessage(chats=chat_name))
async def handler(event):
    get_message = event.message.to_dict()
    get_message['date'] = get_message['date'].strftime("%Y-%m-%d %H:%M:%S")
    message_json = json.dumps(get_message)
    print(message_json)
      
      
async with client:
    client.run_until_disconnected()
1 Answers

You need to put async with inside of async def:

...

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

client.loop.run_until_complete(main())
Related