Use telegram for custom notifications

Today, I had to run do some serious number crunching, and I couldn’t use my local machine, because I needed it to work, so I spun up a digital ocean droplet.

In a few minutes, I had my program ready to go.

I found out about screen, a CLI tool that lets you run tasks in the background, after you terminate an SSH session, and my program was soon chugging along nicely.

Pictured: chugging along nicely

I soon realised I’d have to check every now and then, to know when it was done, and in the spirit of automation, I was like “naaa, famm!

naaa, famm!

There are many ways to notify yourself or a third party of some event. You could:

  • send a mail,
  • an SMS,
  • a slack message

and more.

I wanted to try Telegram Messenger, because I’d learned a while back, that it had a bot API, I could use it for such situations.

Creating a Telegram Bot

To create a Telegram bot, visit the botfather, and send him a /newbot message.

Follow the instructions, and you should soon have your API token.

Sending a message is as easy as:

curl -X POST \
-H 'Content-Type: application/json' \
-d '{"chat_id": "123456789", "text": "This is a test from curl"}' \
https://api.telegram.org/bot$TELEGRAM_TOKEN/sendMessage

Be sure to replace $TELEGRAM_TOKEN with API token.

To get yourchat_id,

  • add your bot to a new Group
  • send a message
  • Run:
curl -X GET \
https://api.telegram.org/bot$TELEGRAM_TOKEN/getUpdates

You should get a JSON response, that you can inspect to get your chat_id.

Using the Telegram Bash Client

Next, I forked this bash Telegram client, which lets me send a message via

telegram -t $TELEGRAM_TOKEN -c $TELEGRAM_CHAT "Hello World!"

You can also set those environment variables, so you don’t have to type the TELEGRAM_TOKEN and TELEGRAM_CHAT every time.

The command for sending a “Hello World!” message becomes:

telegram "Hello World!"

Cool, eh?

Yup!

With this, as soon as the task is done, I can use that command to send myself a message, giving a summary of the result.

For more information on using Telegram bots, see their API

I’ve learned I don’t know anything. I've also learned that people will pay for what I know. Maybe that's why they never pay.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store