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):
apadana
  • 13,456
  • 15
  • 82
  • 98

1 Answers1

6

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')
Lonami
  • 5,945
  • 2
  • 20
  • 38
  • 1
    Awesome! This is exactly what I was looking for. Thanks – apadana Jun 09 '17 at 14:14
  • 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.') – apadana Jun 10 '17 at 15:41
  • 1
    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. – apadana Jun 10 '17 at 16:02
  • 1
    @apadana supergroups should be considered channels, so try that? – Lonami Jun 10 '17 at 16:41
  • supergroups should be considered channels: yes, worked great! – apadana Jun 10 '17 at 17:58