Python LonamiWebs/Telethon get group name of received message

Question:

Code:

from telethon import TelegramClient, events, sync
from telethon.tl.types import PeerChat, PeerChannel

api_id = 123
api_hash = '123'
client = TelegramClient('anon', api_id, api_hash)

@client.on(events.NewMessage())
async def my_event_handler(event):
    if(event.chat.title == 'BotTest'):
        print(event.raw_text)
        

client.start()
client.run_until_disconnected()

Problem:
So this code works if group(BotTest) has me/bot(one user) "event.chat.title"(event.chat) exist but if i join second user (group now has 2 peoples) new messages result in [AttributeError: 'NoneType' object has no attribute 'title'] so there no [chat].

How can i get chat from this object?

UPD: There is [event.chat_id] how question is how to get name from ID.

Asked By: Red007Master

||

Answers:

According to docs:

async def handler(event):
    # Good
    chat = await event.get_chat()

    # BAD. Don't do this
    chat = event.chat

So, you should change how you get your chat object to:

@client.on(events.NewMessage())
async def my_event_handler(event):
    chat = await event.get_chat()
    if(chat.title == 'BotTest'):
        print(event.raw_text)
Answered By: qaziqarta
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.