I haven’t been posting regularly because I’m transitioning into the working adult life 😉 . However, I wanted to do this post as a continuation to my previous post about how to build a Telegram Chatbot with API.ai. Without further ado, let’s jump in!
This post assumes you know how to create a Telegram chatbot using the Botfather.
1. Identify notification recipient
You have a bot and lots of users are conversing with your bot. You want to send the notification to the right user. In some cases, you may also want to send the message to all the users and you can do that using this method as well.
This is done by using a HTTP API provided by Telegram called getUpdates. You’ll need to enter https://api.telegram.org/bot<YOUR BOT TOKEN>/getUpdates. It looks like this.
1a. Possible outcomes from getUpdates
In this step, you’ll either get an array of chat/update IDs you can use, or a 409 error telling you that getUpdates have failed because you have active webhooks.
- If you got the active webhook 409 error, you may remove the webhook with the following method setWebhook – https://api.telegram.org/bot<YOUR BOT TOKEN>/setWebhook. Check out the example below. You can add the webhook again in the future, so do not worry.
- If you received an empty array, it simply means there are no active conversations with your bot, or that the last active one was from years ago. Therefore I would urge you to initiate a conversation with your bot (It’s lonely) and test getUpdates again. The method would return you this.
In this scenario, the chat id from the HTTP response is 40980011. Use this in the next step.
2. Send notification
Now that you have obtained the chat_id, use sendMessage to send a notification. You would type https://api.telegram.org/bot<YOUR BOT TOKEN>/sendMessage?chat_id=40980011&text=<YOUR NOTIFICATION TEXT>
Here’s some examples
- Simple Text
- Text and Links
Here’s the output!
Thank you for taking the time to read this post, and I hope it has benefited you in some way. Do feel free to reach out to me if you think I should make an amendment or if you would like to make a clarification. Adiós!
I have removed the bot used in this example so that malicious users will not spam me. I wanted this tutorial to be as realistic as possible hence I divulged the actual tokens and chat_ids 🙂