How to send a notification using your Telegram Chatbot

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.

https://api.telegram.org/bot447150052:AAF511Yap6Dby8pLnt6ksk9BEy-SIpyXDQ4/getUpdates

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 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.

    chat updates

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

Here’s the output!

This slideshow requires JavaScript.

3. Conclusion

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 🙂

 

 

 

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s