Creating alerts for Web Apps using Telegram API
As a developer, I prefer not to be in a constant state of worry about whether everything is functioning correctly. Instead, why not automate the monitoring process to ensure that I am notified immediately if any errors occur?
Telegram API to the rescue!
Our goal is to be notified if any request on our website encounters an error. To achieve this, we will use Axios interceptors to monitor every request and alert our bot in case of any issues.
Preparing our Telegram Bot
The first step is to create our bot. Telegram bots are quite easy to set up. Just follow these steps:
After setting up the bot and obtaining the access token, there’s one more essential step before we can start sending messages: acquiring our chatId.
The Telegram API documentation might not be very straightforward, but in essence, this ID can be retrieved by calling the getUpdates
endpoint.
const axios = require('axios');
const getChatId = async () => {
const resp = await axios.get(
`https://api.telegram.org/bot${token}/getUpdates`
);
console.log(resp.data.result[0].message.chat.id);
};
getChatId();
Now we have everything needed to send messages with our Telegram Bot!
const resp = axios.post(`https://api.telegram.org/bot${token}/sendMessage`, {
chat_id: "<chat_id>",
text: "Hello World",
});
Integrating the Bot into the Application
Before integrating the bot into the application, it’s crucial to ensure that our token is not exposed on the client-side.
As I am using Next.js, I will create a route at /api/event
to encapsulate our calls to the Telegram API, thereby safeguarding the token from exposure. Observe the following example closely; it can be easily adapted for use even if you’re not working with Next.js.
On the client side, all we need to do is invoke the /api/event
endpoint whenever necessary. This is valid not only for error notifications but also for staying informed about significant events, such as a user signing up or completing a payment checkout.
Finally, we are now able to use the newly configured Axios instance at any point in our application as needed, just by importing it.
import axios from "@/lib/axios";
And, as expected, we got an alert!