How do I send & receives Telegram messages programmatically? - telegram

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!

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())

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.

Related

Simplest way to get a list of new posts from a telegram channel via API

I'm trying to write a simple server side script that will run every once in a while and check for new messages in certain Telegram channels. I've created a bot, but it looks like a bot can't me a member of a channel, so bot API is of no use here. So what I fugured I need to do is to write a very basic set of requests to do authentication with my own credentials and then fetch messages from certain channels I'm subscribed to and then check if any new messages are there.
Is it possible to do this on a very basic level with HTTP requests, without having to learn and use bot frameworks and such?

Is there an option to view conversations\messages sent by my telegram bot

I have just created a bot on telegram. The purpose is to create private conversations with users (each user separately)
With my facebook bot I can go into the Page "Inbox" and watch all conversations. Is there such an option on telegram ? This helps me alot debugging my system.
To "watch all conversations" you can store them to database (e.g. csv file, SQLite, Postgresql, MongoDB, or any other depending on your environment). And later you can query for them when you need.
Another option, you can create separate predefined chat with you and bot, where bot will write some logs. Or if you have time - you can develop advanced mechanism that will show history (from database mentioned above) and will have ability to reply directly to that chat by chat_id.
I used rocket chat for that. I was creating private room for every user and was adding there the user and the bot (I was doing that via my backend). Then I used rocket chat ui to view the conversations. Currently, I see they have built-in integration with telegram bots: https://docs.rocket.chat/guides/administrator-guides/integrations/telegram

How to ensure that chat_id exists?

I wrote a piece of code which sends messages to a Telegram bot. In order to do so, I use the chat_id of the last conversation retrieved via the getUpdates method.
id = requests.get(f"https://api.telegram.org/bot{token}/getUpdates").json()['result'][-1]['message']['chat']['id']
My understanding is that the a conversation exists if someone started one with the bot via /start.
How can I initiate, from my code, a conversation to make sure a chat_id is available? (= that there is a conversion I can query).
I am also sure that the conversations, should they exist, are not kept indefinitely (this is another reason why requesting an update can yield empty results)
My understanding is that the a conversation exists if someone started one with the bot via /start.
Yes, conversation is always initiated by a user:
Bots can't initiate conversations with users. A user must either add them to a group or send them a message first. People can use telegram.me/ links or username search to find your bot.
Note that /start is not the only option here.
If you try to send a message for user, who didn't start conversation with bot, you will receive something like this: {"ok":false,"error_code":400,"description":"Bad Request: chat not found"}.
How can I initiate, from my code, a conversation to make sure a chat_id is available? (= that there is a conversion I can query).
Normally, you shouldn't worry about that. Bot does not query specific user actions/requests with getUpdates, it queries all interactions from all users and then decides what to do according to internal logic you provide.
You may want to store information about users and/or their requests in a database every time you receive an Update from particular user in getUpdates.
Based on that, bot can make a decision to send for example, a message to him.
I am also sure that the conversations, should they exist, are not kept indefinitely (this is another reason why requesting an update can yield empty results)
Yes, docs clearly state that
Incoming updates are stored on the server until the bot receives them either way, but they will not be kept longer than 24 hours.
An Update on a Telegram servers is an entity with a short life period.
If you haven't saved information about existing users, or lost a database, there's no way to retrieve that data from telegram servers.
P.S.: as a side note, I'd suggest using long polling, as Telegram Bot API is designed to be used with long polling if you're using getUpdates. The most important thing is the timeout request parameter of getUpdates method:
(timeout is) Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only.
As written in question, you're using short polling.

Telegram client to listen for channel updates

I need a way to automate processing of messages/files sent in a Telegram channel. I've been told that is can't be done with a telegram bot since they can't join channels, nor am I the owner of the channel, so I would need to set up a client or to use regular Telegram API to be able to do that. I'm looking for guidance, suggestions, anything that could help me. The script/client will have to run on Windows (so I can't use the cli linux version).
You can try UNOFFICIAL PWRTelegram API, it can be login in use a user account, and have HTTP API like bots.
You can click here to see usages.

can Telegram CLI mimick Telegram bots?

I saw on internet that there is some programs that can use Telegram CLI.
I want to choose between them
for Telegram bot API there is much more documents explaining its functionality, but for CLI there isn't much that explains its features
it seems the only way to know about is to experiment with it.
unfortunately i don't have a linux distro installed on my pc so experimenting isn't an option right know.
so I thought to ask from people who already used it
I know about Telegram bot api, its powers and its limitations
here is my questions:
what can I do using Telegram CLI that I can't do with with bot api, and vice versa?
Telegram bot API:
do not require to register new Telegram account, so you don't need to have another phone number;
bot cannot write to user first, only after user sends a first message to bot;
already has the commands interface (/command);
can do stuff by simple HTTP POST (by sending request via cURL, for example). So you can hook to this tons of stuff (notifications about new articles at the website or so);
you can rather easily create lots of them;
you can write you own implementation in almost any programming language;
you have a list of bots you have created (thanks to #BotFather). If you have lost somehow control of your bot - just revoke the token via #BotFather and it's yours again;
pretty simple to use.
Telegram client application (in this case - CLI):
requires new Telegram account registration with phone number;
acts like any other actual Telegram user (can write to other users first, without invitation). Well, that's a good thing;
not really good cross-platform abilities for now (some lack of CLI-realisations);
not really easy to install and use;
you have to implement the commands handling part;
if you have lost your phone number - pretty much you lose this account, because it's not like you would make some precautions for CLI client account. So you will have to register a new one and repeat the setting procedure for client.
In conclusion, bots actually got rid of CLI clients, in my opinion. I had CLI account right to the moment the bots appeared. After that I deleted it and created a bot. And not just one :)
So, bots are for the "robot" stuff, and real accounts are for the real people.
The Telegram CLI library interacts directly with their MTproto protocol, which means it's like their desktop/mobile app...but for the console. You can send messages from one phone number to another. This means that when authenticating with the CLI application, you use your real number as if you were logging into the mobile application.
I wouldn't suggest using it for bot behavior as you have to write an application that wraps the Telegram CLI and parses the log file as it is displayed...since it doesn't implement all the MTproto methods and the outputs for the log file are custom...it can be quite annoying and different than what you would expect.
With Telegram CLI you can send a number to another Telegram user without having them initiate the conversation first (since it functions just like a normal Telegram client) where the Bot API requires the user to add the Bot and start interaction before the Bot knows you are there.
previous answers are almost correct. Two different interfaces for different purposes:
Telegram Bot API allows to develop a Telegram Bot.
Telegram CLI (as this one, as an implementation example: https://github.com/vysheng/tg) are telegram client implementations, running from command line, based on MTproto protocol, as Chris Brand said.
As a bot developer, I'm interested to have a TG CLI interface (2) to automatize dialogs tests, with bash scripts, with a bot made with (1).

Resources