Ukrainian Flag
Russia is still destroying lives. Click here to help.
Ukrainian Flag
me
Jakub Koleลผyล„ski
Blog Talks Apps
Server alerts using Telegram

Server alerts using Telegram

19.05.2023

I like to know what's happening on my site, but I don't like to check. And I like to know it quick. I want to know right away when something important happens.

I want a popup on my phone. So... what are my options?

Options

Email

First thought was email. You'd think it would be the easiest thing... And it probably is! But between the overchoice of providers and an overarching theme of message limits, I was discontent. Also, email is boring. ๐Ÿ™„

Push

But wait! Did I say a phone popup triggered from a website? That's a push notification! The only prerequisite is a service worker, which I plan to add anyway. Sounds perfect, right? Except all my browsers 'deny all notifications', so I'd have to turn that off. Yeah, no, not doing that.

Telegram

What about writing a bot for one of the chat apps I use? The first one I checked for viability was Telegram, and that was a bullseye. Now THAT is the simplest thing. Here's how:

Registering the bot

  1. Start a chat with The BotFather by saying (or clicking) /start
  2. Write (or click) /newbot
  3. BotFather will ask you for a bot name - display name, changeable
  4. BotFather will ask you for a bot username - permanent.

And that is it. BotFather replies with the link to the bot and the API key.

Wiring up the chat

The bot can only text people who initiated a chat with it. Click the t.me/username link from the BotFather's reply to open the chat and start it.

You also need to find out what your own CHAT_ID is, so that you can send mesages to it. The easiest way is to write something to the bot and check the bot's inbox with a get request to the API. You can open this link in the browser, substituting your actual {API_KEY}:

https://api.telegram.org/bot{API_KEY}/getUpdates

If your CHAT_ID was 123456789, somewhere in the response JSON you'd see this:

{"message_id":2,"from":{"id":123456789}},

Save your CHAT_ID and API_KEY to wherever you keep secrets.

Sending messages

Make a post request to this endpoint:

https://api.telegram.org/bot{API_KEY}/sendMessage

With an object of this shape:

{
	"chat_id": "123456789",
	"text": "important things going on rn"
}

Or better yet, if you're using js you can just copy my work: ๐Ÿ˜€

import { CHAT_ID, API_KEY } from 'server/secrets';

const endpoint = `https://api.telegram.org/bot${API_KEY}/sendMessage`;

export async function sendTelegram(text) {
	await fetch(endpoint, {
		method: 'POST',
		body: JSON.stringify({ chat_id: CHAT_ID, text }),
		headers: { 'Content-Type': 'application/json' },
	});
}

Et voilร !

Just make sure the API_KEY doesn't leak from the sever! ๐Ÿ˜‰




Back to list

Comments:

Sign In to comment

Be the first to comment!