Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 37 ยท Bot Concepts and APIs

Telegram Updates and Methods

Understand the Telegram Bot API data model - Update, Message, Chat and User objects, bot_command entities, allowed_updates - and the core methods for sending, editing, deleting and answering.

The Telegram Bot API has two halves. Updates flow in: each one tells your bot that something happened. Methods flow out: each one asks Telegram to do something. If you learn the shapes of the main update objects and the dozen methods that cover 90% of bots, the rest of the API reads like a dictionary.

The Update object

Every update has an integer update_id and exactly one other field that says what kind of update it is. The update ids increase, which is what makes the offset confirmation in getUpdates work.

Field When it appears
message A new message in a private chat, group or supergroup
edited_message A message was edited
channel_post A new post in a channel where the bot is an admin
callback_query A user pressed an inline keyboard button
inline_query A user typed @yourbot something in any chat
my_chat_member The bot was added, removed or its status changed
chat_member Another member's status changed (needs an admin bot and opt-in)
poll, poll_answer Poll state or a vote

You tell Telegram which kinds you want with allowed_updates (an array of those names). Requesting fewer types means less traffic and less code. A bot that ignores edited_message should not receive it.

Message, Chat and User

A message carries the fields below (shortened). Learn these by heart because you will use them in every handler:

  • message_id: unique within the chat, not globally.
  • from: the sender (a User with id, is_bot, first_name, optional username, language_code). Absent for channel posts.
  • chat: where it was sent (id, type which is private, group, supergroup or channel, plus title or names).
  • date: Unix time in seconds.
  • text: the text, if it is a text message. Photos, stickers and files have other fields (photo, document, sticker) and a caption instead of text.
  • entities: markup inside text, such as commands, mentions, links and bold.

Chat ids matter: private chats have positive ids equal to the user's id, groups are negative, and supergroups and channels look like -100 followed by digits. Store ids as numbers (they fit safely in JavaScript numbers for Telegram) and never assume a sign.

Entities and the UTF-16 trap

A command message has an entity { type: 'bot_command', offset: 0, length: 6 }. The offset and length are measured in UTF-16 code units, the same unit JavaScript strings use for .slice(). That is convenient in JavaScript, but different from counting emoji as one character. Let us write a function that classifies updates and extracts commands.

Node.js Classifying updates and reading entities

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.

Two real-world lessons live in that code. First, in groups several bots may be present, so /weather@demo_bot targets one bot and others must ignore it. Second, always handle the "unknown" kind: new update types appear over time.

The methods you will use most

Methods are called with POST (GET also works) and JSON parameters. Grouped by purpose:

Purpose Methods
Identity getMe, logOut, close
Receive getUpdates, setWebhook, deleteWebhook, getWebhookInfo
Send sendMessage, sendPhoto, sendDocument, sendVideo, sendAudio, sendLocation, sendPoll, sendChatAction
Edit and delete editMessageText, editMessageReplyMarkup, deleteMessage, copyMessage, forwardMessage
Interact answerCallbackQuery, answerInlineQuery
Commands setMyCommands, getMyCommands, setMyDescription
Files getFile (then download from /file/bot<token>/<file_path>)
Groups banChatMember, restrictChatMember, getChatMember, pinChatMessage

Three details save time. sendChatAction with typing shows "bot is typing..." for about five seconds, which suits slow replies. answerCallbackQuery must be called for every button press, otherwise the user's button shows a loading spinner. And copyMessage sends a message without the "Forwarded from" header.

Building a checked method layer

A tiny method layer that validates required parameters catches mistakes before they cost a network call. The stand-in below checks the same rules Telegram reports, such as "chat_id is empty" or "message text is empty".

Node.js Required parameters for common methods

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 Proxy trick makes bot.anyMethodName(params) call the API, which is how several real libraries (and small hand-rolled wrappers) expose the whole Bot API without listing every method. The server-side error texts above are typical, but treat the exact strings as examples: your code should branch on error_code and use the description for logging only.

Common errors you will see

  • 400 Bad Request: chat not found: wrong id, or the user never started the bot.
  • 403 Forbidden: bot was blocked by the user: remove that user from your broadcast list.
  • 403 Forbidden: bot can't initiate conversation with a user: the user must message the bot first.
  • 409 Conflict: terminated by other getUpdates request: two instances are polling, or a webhook is set.
  • 429 Too Many Requests: retry after N: wait N seconds.

The next lessons turn to Discord, whose model of ids, REST calls and events is different.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How many 'kind' fields (message, callback_query, ...) does an Update contain besides update_id?

    An Update has update_id and exactly one optional field that describes what happened.
  2. 2. What unit do entity offsets and lengths use?

    Telegram measures entities in UTF-16 code units, which matches JavaScript string indexing.
  3. 3. What must a bot do after receiving a callback_query?

    Each callback query should be answered, even with an empty response, or the client keeps showing a loading indicator.
  4. 4. A command arrives as /weather@other_bot Paris. What should demo_bot do?

    In groups the @botname suffix chooses which bot should answer, so other bots must ignore the command.
  5. 5. Which error means two programs are polling the same bot?

    Only one getUpdates consumer is allowed. A second one, or a configured webhook, produces 409 Conflict.

Summary

  • Updates carry update_id plus one kind field; request only the kinds you need with allowed_updates.
  • message has message_id, from, chat, date, text or media fields, and entities in UTF-16 units.
  • Core methods: sendMessage, editMessageText, deleteMessage, answerCallbackQuery, setMyCommands, getFile, and the group admin methods.
  • Branch on error_code; common failures are blocked users, missing chats and polling conflicts.
  • A thin wrapper (even a Proxy) turns every Bot API method into a function call.

Next: Discord REST API and Snowflakes