Backend

How to Build a Telegram Alert Bot in Node.js

A practical guide to getting instant Telegram alerts from your Node.js app when a dependency fails, errors spike or the process crashes.

·
8 min read
·
AI-assisted

AI tooling disclosure

Generative AI materially contributed to this article.

Human review confirmed by the author.

How to Build a Telegram Alert Bot in Node.js

The problem: "up" doesn't mean "working"

Here is a situation most backend developers run into sooner or later.

You deploy a Node.js API to a VPS or a container. It depends on a third-party service, such as a payment gateway, an email provider or an SMS API. To keep an eye on it, you add an uptime monitor that pings a /health endpoint every minute.

One day the third-party service starts timing out. Your API is still running, /health still returns 200, and the uptime monitor stays green. But every request that touches the third-party service now fails with a 5xx. The errors are sitting in your logs, and nobody is reading them. You find out when a customer complains, or the next morning when you finally open the logs.

A second, equally common version: a bug throws an unhandled exception, your process manager restarts the app, it crashes again on the same request, and the cycle repeats quietly in the background.

In both cases the gap is the same. An uptime check tells you the process is alive, not that your app is doing its job. What you need is a message pushed to you the moment errors start piling up.

Telegram is a good fit for that. In this guide we’ll build a bot that sends alerts from a Node.js application. By the end you’ll have:

  1. A bot created with BotFather

  2. A reusable sendAlert() function

  3. An error-rate monitor that fires when 5xx errors spike

  4. Crash alerts for uncaughtException and unhandledRejection

  5. Cooldowns so you never get spammed

Requirements: Node.js 18+ (for built-in fetch) and a Telegram account.

Why Telegram for alerts?

  • Free and fast. The Bot API costs nothing and messages arrive in about a second.

  • Already on your phone. No new app, no email filters, no SMS gateway.

  • Simple API. One HTTPS request sends a message. No SDK required.

  • Works for teams. Add the bot to a group and everyone on call sees the alert.

Step 1: Create the bot with BotFather

  1. Open Telegram and search for @BotFather.

  2. Send /newbot.

  3. Choose a display name (for example My App Alerts) and a username ending in bot (for example myapp_alerts_bot).

  4. BotFather replies with a token that looks like 123456789:AAH....

Treat this token like a password. Anyone who has it can send messages as your bot. If it ever leaks, send /revoke to BotFather to generate a new one.

Step 2: Find your chat ID

A bot can only message a chat that has talked to it first.

  1. Open your new bot in Telegram and press Start (or send it any message).

  2. Visit this URL in your browser, using your real token:

https://api.telegram.org/bot<YOUR_TOKEN>/getUpdates
  1. Look for "chat":{"id": ...} in the JSON. That number is your chat ID.

To send alerts to a group instead, add the bot to the group, send a message there, and call getUpdates again. Group IDs are negative numbers (supergroups start with -100).

Store both values as environment variables:

export TELEGRAM_BOT_TOKEN="123456789:AAH..."
export TELEGRAM_CHAT_ID="987654321"

Step 3: Send your first message

Before writing any code, check that everything works with curl:

curl -s -X POST "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/sendMessage" \
  -d chat_id="$TELEGRAM_CHAT_ID" \
  -d text="Hello from my alert bot 🚀"

If your phone buzzes, the setup is correct.

Step 4: A reusable sendAlert() function

Create alert.js. It formats the message, escapes dynamic text, times out quickly, and never throws, because a problem in your alerting code should not take your app down.

// alert.js
const TOKEN = process.env.TELEGRAM_BOT_TOKEN;
const CHAT_ID = process.env.TELEGRAM_CHAT_ID;

const ICONS = { INFO: 'ℹ️', WARN: '⚠️', ERROR: '🚨', RESOLVED: '✅' };

const escapeHtml = (value) =>
  String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');

export async function sendAlert({ level = 'ERROR', title, details = {} }) {
  if (!TOKEN || !CHAT_ID) {
    console.warn('Telegram alerts disabled: missing token or chat id');
    return;
  }

  const lines = [
    `${ICONS[level] ?? '🔔'} <b>${level}: ${escapeHtml(title)}</b>`,
    ...Object.entries(details).map(
      ([key, value]) => `<b>${escapeHtml(key)}:</b> ${escapeHtml(value)}`
    ),
    `<i>${new Date().toISOString()}</i>`,
  ];

  try {
    const res = await fetch(`https://api.telegram.org/bot${TOKEN}/sendMessage`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        chat_id: CHAT_ID,
        text: lines.join('\n').slice(0, 4000), // Telegram's limit is 4096 characters
        parse_mode: 'HTML',
        link_preview_options: { is_disabled: true },
      }),
      signal: AbortSignal.timeout(5000),
    });

    if (!res.ok) {
      console.error('Telegram alert failed:', res.status, await res.text());
    }
  } catch (err) {
    console.error('Telegram alert error:', err.message);
  }
}

Make sure your package.json contains "type": "module" so the import syntax works.

A few details worth noting:

  • parse_mode: 'HTML' lets us use bold and italics. Every dynamic value is escaped, so a stray < in an error message can’t break the formatting.

  • AbortSignal.timeout(5000) stops a slow Telegram request from hanging your process.

  • The try/catch means a failed alert is logged instead of crashing the app.

Step 5: Alert on error spikes

We don’t want an alert for every single 500, because one failed request is noise. We want to know when errors spike, which is exactly what a failing third-party service looks like from the outside.

Create monitor.js:

// monitor.js
import { sendAlert } from './alert.js';

const SERVICE = process.env.SERVICE_NAME ?? 'my-api';

const WINDOW_MS = 60_000;        // look at the last 60 seconds
const THRESHOLD = 10;            // 10 server errors in that window = incident
const RECOVERY_MS = 5 * 60_000;  // quiet for 5 minutes = resolved
const COOLDOWN_MS = 10 * 60_000; // never open a new incident more than once per 10 min

let errors = [];                 // [{ t, route }]
let incidentOpen = false;
let lastAlertAt = 0;
let lastErrorAt = 0;

export function recordError(route) {
  const now = Date.now();
  lastErrorAt = now;
  errors.push({ t: now, route });
  errors = errors.filter((e) => now - e.t < WINDOW_MS);

  const shouldAlert =
    errors.length >= THRESHOLD && !incidentOpen && now - lastAlertAt > COOLDOWN_MS;

  if (!shouldAlert) return;

  incidentOpen = true;
  lastAlertAt = now;

  // Which route is failing the most?
  const counts = {};
  for (const e of errors) counts[e.route] = (counts[e.route] ?? 0) + 1;
  const [topRoute, topCount] = Object.entries(counts).sort((a, b) => b[1] - a[1])[0];

  sendAlert({
    level: 'ERROR',
    title: 'Error rate spike',
    details: {
      Service: SERVICE,
      'Top route': topRoute,
      'Errors (last 60s)': errors.length,
      'Errors on top route': topCount,
      Env: process.env.NODE_ENV ?? 'development',
    },
  });
}

// Tell me when it's over, too.
setInterval(() => {
  if (incidentOpen && Date.now() - lastErrorAt > RECOVERY_MS) {
    incidentOpen = false;
    sendAlert({
      level: 'RESOLVED',
      title: 'Error rate back to normal',
      details: { Service: SERVICE, 'Quiet for': '5 minutes' },
    });
  }
}, 30_000).unref();

Why this design works:

  • Sliding window. Ten errors in a minute is an incident; ten errors spread over a day is not.

  • One incident, one alert. incidentOpen stops the bot from messaging you every second while the problem continues.

  • Cooldown. If the service flaps (fails, recovers, fails again), you won’t get a storm of messages.

  • Recovery message. Knowing a problem is fixed is almost as useful as knowing it started.

  • .unref() ensures the timer never keeps the process alive on its own.

Step 6: Connect it to Express

Here is a server with a route that depends on a third-party payment API, exactly the kind of dependency from the situation above:

// server.js
import express from 'express';
import { sendAlert } from './alert.js';
import { recordError } from './monitor.js';

const app = express();

// Count every 5xx response
app.use((req, res, next) => {
  res.on('finish', () => {
    if (res.statusCode >= 500) {
      // Use the route pattern, not the raw URL, to keep the counts meaningful
      recordError(`${req.method} ${req.route?.path ?? 'unmatched'}`);
    }
  });
  next();
});

// Only checks that the process is alive
app.get('/health', (req, res) => res.json({ status: 'ok' }));

// A route that depends on a third-party service
app.post('/orders', async (req, res) => {
  try {
    const response = await fetch(process.env.PAYMENT_API_URL, {
      method: 'POST',
      signal: AbortSignal.timeout(8000),
    });
    if (!response.ok) {
      throw new Error(`Payment API responded with ${response.status}`);
    }
    res.status(201).json({ ok: true });
  } catch (err) {
    console.error(err);
    res.status(502).json({ error: 'Payment service unavailable' });
  }
});

app.listen(3000, () => {
  console.log('Server running on :3000');
  sendAlert({ level: 'INFO', title: 'Server started' });
});

Notice that /health keeps returning 200 even when /orders is failing. That is the blind spot, and the error counter in the middleware is what closes it.

Using req.route?.path records POST /orders instead of a unique URL for every request, so alerts group errors by route.

Step 7: Catch crashes too

For the second situation, where the process dies, add this near the top of server.js:

async function alertAndExit(title, err) {
  await sendAlert({
    level: 'ERROR',
    title,
    details: {
      Service: process.env.SERVICE_NAME ?? 'my-api',
      Message: err?.message ?? String(err),
    },
  });
  process.exit(1);
}

process.on('uncaughtException', (err) => alertAndExit('Uncaught exception', err));
process.on('unhandledRejection', (err) => alertAndExit('Unhandled rejection', err));

Because sendAlert() has a 5-second timeout and never throws, the process will always exit, even if Telegram is unreachable. Pair this with PM2, systemd or a Docker restart policy so the app comes back on its own and you simply get told what happened. If the app crash-loops, the alert tells you right away instead of leaving it to run unnoticed.

Step 8: Reproduce the situation and test it

You can recreate a failing third-party service without waiting for a real outage. Point PAYMENT_API_URL at any URL that returns a 5xx response. The public httpbin.org service has an endpoint that returns whatever status you ask for:

SERVICE_NAME="my-api" \
PAYMENT_API_URL="https://httpbin.org/status/503" \
TELEGRAM_BOT_TOKEN="123456789:AAH..." \
TELEGRAM_CHAT_ID="987654321" \
node server.js

In another terminal, send enough requests to cross the threshold:

for i in $(seq 1 12); do curl -s -o /dev/null -X POST http://localhost:3000/orders; done

Meanwhile, /health still reports that everything is fine:

curl http://localhost:3000/health
# {"status":"ok"}

But your phone receives a message like this:

🚨 ERROR: Error rate spike
Service: my-api
Top route: POST /orders
Errors (last 60s): 10
Errors on top route: 10
Env: development
2026-11-17T10:30:41.000Z

Stop sending requests, and after five quiet minutes you’ll get a ✅ RESOLVED message.

Tuning your thresholds

The values in monitor.js are starting points. Adjust them to your traffic:

  • Low-traffic apps: lower THRESHOLD (for example 3 to 5) so a handful of errors still triggers an alert.

  • High-traffic apps: a fixed count gets noisy. Track an error percentage (5xx responses divided by total responses) instead.

  • Flaky dependencies: raise WINDOW_MS or THRESHOLD so brief blips don’t wake you up.

  • Alert fatigue: if you start ignoring messages, your thresholds are too sensitive. Tighten them.

Best practices

  • Alert on symptoms, not noise. Notify yourself about error spikes, crashes and failed jobs, not every warning.

  • Always add context. Service, route, environment and counts turn "something is wrong" into "I know where to look".

  • Respect Telegram’s rate limits. Avoid more than about one message per second to a single chat, and about 20 per minute in a group. If you receive an HTTP 429, the response includes a retry_after value, so wait that long before retrying.

  • Keep secrets out of alerts. Never include tokens, passwords, emails or full request bodies in a message.

  • Keep secrets out of Git. Load the bot token from environment variables or a secrets manager.

  • Use separate chats by severity. Send ERROR to an on-call group and INFO to a channel you can mute.

  • Don’t rely on Telegram alone. For critical systems, add a second channel (email, SMS or a paging service) in case Telegram is unavailable.

Where to go from here

Once the basics work, you can extend the bot in several directions:

  • Add inline buttons (for example "Acknowledge" or "Open dashboard") using reply_markup.

  • Send cron and backup results, whether they succeed or fail.

  • Alert on business events such as failed payments, a sudden drop in signups or low stock.

  • Forward alerts from Grafana, Prometheus Alertmanager or GitHub Actions through a webhook that calls your sendAlert() function.

  • Use Telegram topics in a supergroup to keep different services in separate threads.

Conclusion

A good alert is short, specific and rare. With about 100 lines of Node.js and a free Telegram bot, you can close the gap between "the server is up" and "the app is actually working", and hear about problems in seconds instead of from your users.

Comments(0)

Join the discussion by logging into your account.

No comments yet. Be the first to comment!

Shobit Singh

Passionate developer sharing knowledge about modern web technologies and best practices.

Subscribe to Shobit Singh's Newsletter

Direct email dispatches when new stories are published. Zero algorithms.