How do I send & receives Telegram messages programmatically?
Asked Answered
Q

2

6

I want to create an app that sends telegram messages to different people by phone number, and/or telegram id.

I've heard about the "Telegram Bot API", but from my understanding it has some limitations (like it can't send messages unless users authorize it and send the first message to it, and it doesn't support sending messages using phone number)

And there is the "Telegram API", which looks like a lot of work and coding..? I'm a 1 man developer and I don't want to spend years to create a Telegram app from scratch that talks to telegram servers and does all the protocols and then I have to update it constantly and so on and so fourth.

I just want something that is easy to code & maintain, and can use my telegram account to programmatically send/receive messages. That's it. Something like :

send.message(phone number, message)

or some sort of REST API that let's me authenticate my telegram account and then provides methods that I can use to send messages to contacts.

Any ideas on how I can implement this? Any pointers would be appreciated!

Quietly answered 3/6, 2020 at 11:6 Comment(0)
T
5

Have a look at MTProto libraries like telethon or pyrogram. They are user-friendly (with lots of helper functions to abstract raw telegram api calls and their interfaces somewhat resemble the telegram bot api)

Here is a sample code (from the telethon docs):

from telethon import TelegramClient

# Remember to use your own values from my.telegram.org!
api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'

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

async def main():
    # You can send messages to yourself...
    await client.send_message('me', 'Hello, myself!')
    # ...to some chat ID
    await client.send_message(-100123456, 'Hello, group!')
    # ...to your contacts
    await client.send_message('+34600123123', 'Hello, friend!')
    # ...or even to any username
    await client.send_message('TelethonChat', 'Hello, Telethon!')

with client:
    client.loop.run_until_complete(main())
Tucci answered 3/6, 2020 at 19:43 Comment(12)
I have few questions if you don't mind? If I use a MTProto library, don't I have to read every doc page and implement every thing that Telegram already has or does ? If not and everything is already implemented by the library owner, don't I have to constantly keep the app updated (like every few hours or every day or everytime an update comes out ) I just want a simple solution that let's me authenticate using a phone number (account) and then let's me use a simple method to send a message. I hope I can deliver my concern and my goal. Sorry if it's misleading.Quietly
To adress your concerns, both the libraries I've mentioned do have a whole bunch of helper methods that are intuitive (abstracting the whole protocol) and are very stable (maintain their interfaces even when telegram updates).And yes, you can just use them to create a script to simply authenticate an account and send messages and exit without the need to keep the script running listening for updates. (the snippet I've just shared exactly does that) and about the docs, you only need to read few pages on how to use the methods since you dont need to know about the underlying protocol to use themTucci
Alright I gave the telethon library a try even though I have no experience with Python and it worked! It's actually only few lines of codes to send a message like the one you posted! I only have few questions left which you don't have to answer but I would be very grateful if you did. 1. Can I have this little python script handle the telegram messaging while I do the main app in php or some other language and just communicate with it? 2. Do you have any recommendations on how I can implement this script in my project in a stable & reliable manner ?Quietly
Even though this would be for a client, it's a small project and I don't want to deliver something that breaks half-through and isn't stable. I hope you understand my concern. I'm just looking for some pointers.Quietly
I'm glad it worked out and I didn't know you were using PHP. There's actually a similar and as equally great library called MadelineProto (docs.madelineproto.xyz). It would make sense if you use that instead.Tucci
Its as easy as invoking yield $MadelineProto->messages->sendMessage(['peer' => '@username', 'message' => " ... "]); to send a message there as well. It should save you the troubles of implementing unnecessary bridge between the python code and the project. And madelineproto is stable and even acknowledged by telegram as far as I know.Tucci
Are you also aware of the Telegram API limits? I'm looking online but can't anything anywhere. I want to know if I can send multiple messages to multiple users. Like If I can send message to 50 contacts and another one to 140 contacts. Is it limited per second, or per minute. Would the system treat this as a spam or flooding?Quietly
yeah, limits are not really known (are not publicized) and depend on a lot of factors but generally it's recommended to have some intervals (like sleep) in between each API call.Tucci
Hey buddy! Sorry to ping you again :(. I'm currently struggling to make my first python app (which uses telethon). I have some really really basic questions. If you have the time and python programming knowledge I would like to talk to you in Discord or by email or any form of contact which doesn't bother you and your privacy. Let me know if you can help a brother out. Thanks.Quietly
You should find a telethon support group over t.me/TelethonChat. Most basic questions are already answered and you can just search there. And if your question is new, people there are friendly so am sure you will get helps should you ask there.Tucci
Yeah I've already tried to join that group. Problem is they have set some anti spam rules that doesn't let me send message in there so it joined me in read-only mode. And my questions are a fairly mix of python basic programming and telethon related.Quietly
Alright, let me see if I could help a bit. lets continue over this roomTucci
R
2

Actually, telegram did a decent job to provide a powerful yet very simple API for its Bots (Attention: You can also use telegram applications like MadelineProto or telegram CLI to send messages and this is different from using Bot APIs. The applications are like your mobile/desktop app and use a real account with a particular authenticated phone numbers and you can do mostly anything that you can do with your phone app. But this is a different story).

For sending messages using bots, you can find all the documentations here. To use these APIs, you need:

  • Create a bot using Bot Father robot: he will help you to create a robot and will eventually give you some secret token that you should use with your robot
  • Some users should "/start" your robot. After starting a robot or any communication from user, you have two different options: (i) you can read the updates by a polling the updates from Telegram server using update method or (ii) setting a webhook: this way, telegram will call that webhook to make you inform about the message. Either way you use, to send message to an account you need the so called "chat_id" of that user (and you should obtain it using one of the mentioned approach)
  • The final step is to send a message: for the simplest case, you want to send a simple text message to a person with some particular chat_id. You only need to call this URL (i.e. the API):
https://api.telegram.org/bot{BOTTOKEN}/sendMessage?chat_id={CHAT_ID}&text={SOME_TEXT}

With this sort of calling REST api, you can call many of the functions and this is only the first step and you can do much more complex and fun stuff! For many languages, there are some packages to work with the API which make everything simple and abstract to developers. A list of most popular packages could be found here.

Rebato answered 3/6, 2020 at 22:19 Comment(1)
Thanks for the explanation Ali. But the problem with the BOT solution is that it requires the user to first interact with it and also it doesn't allow sending message to a contact by phone number.Quietly

© 2022 - 2024 — McMap. All rights reserved.