Encrypt Telegram chat history - encryption

I am currently trying to build a telegram bot for connecting emails with a telegram group.
The users should be able to write several messages and (whenever they wish) send the command /sendEmail to send all previously sent messages per email. (Example chat as in the picture below)
As Telegram provides no way to get the chat history, I need to store every single message the moment it is written. But as I don't want any developer to be able to read them, I'd like to encrypt them in a way they can only be decrypted upon sending the email.
Possible data one could use as encryption key:
Encryption code sent by the bot/user (only sent rarely, not every message for the convenience of the user. Like in the picture)
Does anyone know of a way to encrypt all messages until the user sends sendEmail?

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?

How do I send & receives Telegram messages programmatically?

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.

i can't find any thing on my telegram bot API

I'm trying to get all the chat_id's in the telegram bot API
When I call
https://api.telegram.org/botmybot_token/getUpdates
I get this {"ok":true,"result":[]}
You get empty updates because there were no messages (or other actions) from users.
To obtain user's chat_id follow these steps:
User must first find the bot and send it any message, because
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.
Get the following URL: https://api.telegram.org/botmybot_token/getUpdates?timeout=300. Note that you should use timeout= because this is a long polling method (i.e. you will receive response only when there is a new incoming update or timeout is reached):
(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.
You can still receive updates without timeout setting, but that's not the right way to read user interaction. Instead you can you just run long-polling (i.e. with timeout setting) requests in a loop.
You can read more on getting infromation about user's chat_id here:
https://stackoverflow.com/a/56093268/2315573

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.

How to manage too many messages sended to my bot?

I have implemented a php telegram-bot (https://github.com/php-telegram-bot/example-bot). I'm using the getUpdates method to recieve the messages sended to my bot.
The problem is that there are too many spam users sending him fake messages and for that reason I have a long tail of new messages and it produce a big delay for process the important messages.
I have seen that is not possible to block this spam users and it is not possible to recieve more than 100 new message in each call through telegram API. If i'm recieving thousands of messages per second, how can I manage them all with the least possible delay?
Finally I could resolve the issue. The spam come from different groups wich my bot was added. I configure it to not permit to be added to groups and then I use the interface "leaveChat" of the bot api to leave the chats. I have recorded all the chats where my bot recieve message, the group chat ids were easy to identify because they have negative ids.
I also increase the frecuency to download updates up to 20 calls per minute.

Resources