Telethon, how to get an entity?
Asked Answered
S

1

8

I started using Telethon to integrate a python app with telegram API. I was able to get it started and send a few messages.

The function for sending messages gets an entity as the first argument. So far I was getting this entity from the get_dialogs function which returns list of entities. I know which group I want to send messages to and don't want to go through get_dialogs every time to get the entity.

So which function can I use to give me an entity to pass it to send message? I am expecting there should be a function which gets a group id (or a similar unique feature from the group) as an input and passes me the entity in response. But so far I wasn't able to locate any function.

def send_message(self,
                     entity,# <--------------- how can I get this entity?
                     message,
                     markdown=False,
                     no_web_page=False):
Swagman answered 8/6, 2017 at 22:1 Comment(0)
R
7

You could potentially save the group/chat/user or anything you want in a external file, if you don't want to query it each time. What send_message actually takes is an InputPeer, that can be, in your case, an InputChat.

Assuming you know what the ID of your chat is, you can do the following:

from telethon.tl.types import InputPeerChat

chat = InputPeerChat(desired_chat_id)
client.send_message(chat, 'your message')
Radome answered 9/6, 2017 at 14:6 Comment(5)
Awesome! This is exactly what I was looking for. ThanksSwagman
I was able to send message to groups with InputPeerChat, but not supergroups and channels. Is there another method I should use to convert supergroup id or channel id to entity? For channels I get this error: telethon.errors.RPCError: (RPCError(...), 'Invalid object ID for a chat. Make sure to pass the right types.')Swagman
actually I figured out the channels, using InputPeerChannel and passing access_hash as the 2nd parameter. But for supergroups still not sure which method to use.Swagman
@Swagman supergroups should be considered channels, so try that?Radome
supergroups should be considered channels: yes, worked great!Swagman

© 2022 - 2024 — McMap. All rights reserved.