- Mon 22 August 2022
- General
Telegram is a great platform to send your application alerts to your users. To create a telegram bot for yourself, you can follow the below steps.
Open the Telegram app on your mobile or desktop and search for "BotFather", or you may use this link for that. And enter /start

Then you would be presented with a number of options to try. But to create a new bot enter or click on /newbot

Now it asks for the bot name and 'username' for it, where username should end with 'bot'.
And since it should be unique, your preferred username might have already been taken by others. But eventually, you are going to get a new username and an access token for it

Now, you have a new bot, which Telegram users can find and use it.
When a user sends /start to your bot, you will have new updates for this bot at https://api.telegram.org/bot{your_bot_token}/getUpdates (replace {your_bot_token} with the token you got in the above step). You can use any browser to see the results.
To make the results look good, you can use JSON Formatter extension if you are using a chrome browser. You will get information like the user's name, username, chat_id, and the text the user has sent to you.

You can integrate this within your application by using the chat_id to send alerts or custom messages to the user.
Sending Messages to Users:
Once you have the chat_id, you can send messages back to your users. Here's how to send a message using Python:
import requests
bot_token = "your_bot_token_here"
chat_id = "user_chat_id_here"
message = "Hello! This is a message from your bot."
url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
params = {
"chat_id": chat_id,
"text": message
}
response = requests.post(url, params=params)
if response.status_code == 200:
print("Message sent successfully!")
else:
print(f"Failed to send message: {response.text}")
You can also send messages directly from your browser by visiting:
https://api.telegram.org/bot{your_bot_token}/sendMessage?chat_id={chat_id}&text=Your message here
This completes the bi-directional communication - your bot can now both receive messages from users (via getUpdates) and send messages to them (via sendMessage).