jlelse's Blog

Thoughts, stories and ideas

Use Telegram as a notification service with Go

Published on in 👨‍💻 Dev
Share 

Telegram is my favorite messenger for chatting. There are many reasons for this. But Telegram is also very suitable to use it as a notification service for your own projects. For example I get a daily overview of the number of page views of my blogs, but also notifications about new Webmentions, or likes and announcements via ActivityPub are sent to me via Telegram.

That I use Telegram is because the Bot API is so easy to use. Here is the code I use to send messages via Telegram using Go:

import (
	"errors"
	"net/http"
	"net/url"
)

type Telegram struct {
	chat     string
	botToken string
}

var telegramBaseUrl = "https://api.telegram.org/bot"

func (t *Telegram) Post(message string) error {
	params := url.Values{}
	params.Add("chat_id", t.chat)
	params.Add("text", message)
	tgUrl, err := url.Parse(telegramBaseUrl + t.botToken + "/sendMessage")
	if err != nil {
		return errors.New("failed to create Telegram request")
	}
	tgUrl.RawQuery = params.Encode()
	req, _ := http.NewRequest(http.MethodPost, tgUrl.String(), nil)
	resp, err := http.DefaultClient.Do(req)
	if err != nil || resp.StatusCode != 200 {
		return errors.New("failed to send Telegram message")
	}
	return nil
}

That’s just 30 lines of code that allow to send messages via Telegram (it would probably be even shorter). All this code does is to send a simple HTTP request. What is especially great about the Telegram Bot API is that all that is needed is the URL to which the request must be sent, which can simply be composed of the base URL, the bot token and the path.

The necessary bot token can be obtained via the BotFather bot, which is used to create the bot. And to send messages to yourself, it is possible to find out your own chat ID by using the userinfobot. And of course it is necessary to start the bot before it can send you messages.

And that is how this code can be used:

var telegramBot *Telegram

tgChat, tgChatOk := os.LookupEnv("TG_CHAT")
tgBotToken, tgBotTokenOk := os.LookupEnv("TG_BOT_TOKEN")
if tgChatOk && tgBotTokenOk {
    telegramBot = &Telegram{
        chat:     tgChat,
        botToken: tgBotToken,
    }
}

if telegramBot != nil {
    _ = telegramBot.Post("This is a test message!")
}

This code example looks whether the two environment variables TG_CHAT and TG_BOT_TOKEN are set and initializes the telegram variable. If this has worked, a test message is sent.

There are services that are specifically designed to provide an API and app to receive notifications, but I already use Telegram anyway and since Telegram works so well on multiple devices, I don’t need to use another service and can receive notifications on all devices I have Telegram set up on.

Tags:

Jan-Lukas Else
Interactions
You can also create an anonymous comment.