Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 37 ยท Getting Started

Your First Telegram Bot

Build a Telegram bot from scratch in Node.js using only fetch - call getMe, read updates with long polling, reply with sendMessage and confirm updates with offsets - against a runnable stand-in server.

Telegram makes the first bot very small. The Bot API is plain HTTPS: every method is a URL of the form https://api.telegram.org/bot<TOKEN>/<method>, you send JSON, and you get JSON back with an ok flag. There is no SDK to learn and no websocket to maintain. In this lesson you build a complete echo bot with nothing but fetch.

Stand-in server. The sandbox cannot reach the real api.telegram.org, so the examples start a tiny fake Telegram server on 127.0.0.1 that supports getMe, getUpdates and sendMessage with the real request and response shapes. In your own project you only change the base URL, from the fake server's address to https://api.telegram.org.

The response envelope

Every Bot API response has the same outer shape:

JSON
{ "ok": true, "result": { "id": 123456789, "is_bot": true, "first_name": "Demo", "username": "demo_bot" } }

On failure you get "ok": false, an error_code and a description instead of result. Your API wrapper should turn an ok: false response into a thrown error so that you cannot forget to check it.

Step 1: a stand-in server and a call to getMe

getMe is the "hello world" of the Bot API. It needs no parameters and confirms that your token is valid.

Node.js Stand-in Telegram server and getMe

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The call helper is the heart of the wrapper: one place that builds the URL, sends JSON and converts failures into exceptions. Real code would also add a timeout (AbortSignal.timeout(...)) and retry logic, covered later in Middleware and Error Handling.

Step 2: receiving updates with getUpdates

An update is an event for your bot. The most common one holds a message:

JSON
{
  "update_id": 1001,
  "message": {
    "message_id": 7,
    "from": { "id": 555, "is_bot": false, "first_name": "Ana" },
    "chat": { "id": 555, "type": "private" },
    "date": 1760000000,
    "text": "hello"
  }
}

With long polling you call getUpdates repeatedly. Parameters that matter:

  • offset: the first update_id you want. Passing last_update_id + 1 confirms all earlier updates, so Telegram will not send them again.
  • timeout: seconds the server may hold the request open waiting for news. Use something like 30 so that you do not hammer the API.
  • allowed_updates: which update types you want.

Forgetting the offset is the classic first-bot bug: the bot answers the same message forever.

Step 3: reply with sendMessage

sendMessage needs a chat_id and text. To reply to a specific message add reply_parameters: { message_id }. Here is the complete echo bot, with the stand-in holding two pending messages.

Node.js A complete echo bot

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The second poll returns zero updates because the first poll's updates were confirmed when we sent offset = last + 1. In production the loop never ends: while (true), with timeout: 30 so that each call waits for news.

Handling errors in the loop

Networks fail. A polling loop that throws on the first timeout is a bot that dies at 3 a.m. Wrap each round in try/catch, log the error and wait a moment before trying again. If a single update causes your handler to throw, catch it per update so one bad message cannot block the queue; because you have already advanced the offset, it will not be replayed.

JavaScript
while (true) {
  try {
    const updates = await call('getUpdates', { offset, timeout: 30 });
    for (const update of updates) {
      offset = update.update_id + 1;
      try {
        await handleUpdate(update);
      } catch (error) {
        console.error('handler failed for', update.update_id, error);
      }
    }
  } catch (error) {
    console.error('polling failed, retrying in 3 s', error.message);
    await new Promise((r) => setTimeout(r, 3000));
  }
}

This snippet is read-only because it never stops. On the real API, only one consumer may poll a bot at a time; a second getUpdates fails with a 409 Conflict, and you cannot poll while a webhook is set.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What do you pass to getUpdates to confirm that you processed update 1001?

    Passing last_update_id + 1 as the offset confirms every earlier update, so Telegram will not deliver them again.
  2. 2. What does a failed Bot API call look like?

    The envelope always has an ok flag. On failure it carries error_code and description instead of result.
  3. 3. What goes wrong if you forget the offset in a polling loop?

    Without confirmation Telegram redelivers unconfirmed updates, so the bot repeats its replies.
  4. 4. Why wrap each update handler in its own try/catch?

    A per-update catch isolates failures. The offset has already advanced, so the bad update is not replayed forever.

Summary

  • The Bot API is HTTPS plus JSON: https://api.telegram.org/bot<TOKEN>/<method>; responses carry ok, and either result or error_code and description.
  • getMe verifies a token; getUpdates pulls events; sendMessage sends text to a chat_id.
  • Confirm updates by sending offset = last_update_id + 1.
  • Use a timeout for long polling, catch errors per update and retry polling failures with a pause.
  • One wrapper function (call) should be the only place that builds URLs and checks ok.

Next: Your First Discord Bot