FastBot Telegram Bot Library

repository·main·Indexed 42 days ago

https://github.com/gyverlibs/fastbot

A high-performance, lightweight Telegram bot library optimized for ESP8266 (SDK v2.6+) and ESP32 microcontrollers. It features support for Markdown/HTML formatting, inline and keyboard menus, Unicode, and OTA firmware updates via .bin files. The library focuses on a low memory footprint and speed, providing tools to send/edit messages, handle files, and synchronize real-time clocks with Telegram servers.

Tokens
10.9K
Snippets
37
Records
64
Agent score
51%

What's inside FastBot

  1. Overview of FastBot

    main

    FastBot is a high-performance, multifunctional library for creating Telegram bots on ESP8266 (SDK v2.6+) and ESP32 microcontrollers. It is designed to be fast and lightweight, using standard libraries and offering features like an optional chat ID whitelist, manual or timer-based update checking, and support for Markdown/HTML formatting.

    Key Features:

    • Send, delete, edit, and reply to messages.
    • Read and send messages in chats, groups, and channels.
    • Support for Unicode (emojis and non-Latin languages).
    • Inline menus with link buttons.
    • Real-time clock synchronization with Telegram servers.
    • OTA firmware updates via .bin files sent through Telegram.
    • Sending files from memory to chat.
  2. Understand Telegram Bot API limits

    main

    When using FastBot, be aware of the following Telegram-imposed limits to avoid message delivery failures:

    Sending Limits:

    • In a private chat: No more than 1 message per second.
    • In a group: No more than 20 messages per minute.
    • Total limit: No more than 30 messages per second.

    Other Constraints:

    • The bot can only read messages sent within the last 24 hours.
    • Bots cannot see or interact with messages sent by other bots in the same group.
    • If a message exceeds 4,000 characters, Telegram splits it into multiple messages, each with a unique message ID.
  3. Understand the FB_msg structure

    main

    When using attach(callback), the FB_msg object provides the following fields:

    FieldTypeDescription
    userIDString&ID of the user
    usernameString&Username (first_name in API)
    isBotboolTrue if the user is a bot
    chatIDString&ID of the chat
    messageIDint32_tID of the message
    editedbool&True if the message was edited
    textString&Text content of the message
    replyTextString&Text of the replied message (if any)
    queryboolTrue if it is a query
    dataString&Callback data
    isFileboolTrue if the message contains a file
    fileNameString&Name of the file
    fileUrlString&URL of the file
    OTAboolTrue if the file is an OTA update request
    unixuint32_tUnix timestamp of the message
  4. Handle geographic location data

    main

    To process location messages, you must define #define FB_WITH_LOCATION in your configuration. When enabled, the FB_msg structure will include a location field containing latitude and longitude strings.

    // Ensure #define FB_WITH_LOCATION is set before including FastBot
    
    void newMsg(FB_msg& msg) {
      if (msg.location.latitude.length() > 0 && msg.location.longitude.length() > 0) {
        bot.sendMessage("Lat: " + msg.location.latitude + ", Lon: " + msg.location.longitude, msg.chatID);
      }
    }
  5. Synchronize and use Real-Time Clock (RTC)

    main

    FastBot automatically synchronizes its internal clock when it receives a message from the Telegram server (which includes a Unix timestamp). To synchronize, simply send a message to the bot after powering on the device. The library will continue to track time using standard time functions.

    Key Methods:

    • uint32_t getUnix(): Returns the current Unix time, or 0 if the clock is not yet synchronized.
    • bool timeSynced(): Returns true if the clock has been synchronized.
    • FB_Time getTime(gmt): Returns an FB_Time object for the specified timezone (gmt).
    // Method 1
    FB_Time t = bot.getTime(3);
    
    // Method 2
    FB_Time t(bot.getUnix(), 3);
  6. FastBot vs Universal-Arduino-Telegram-Bot

    main

    FastBot is optimized for speed and lower memory footprint compared to Universal-Arduino-Telegram-Bot.

    Key Advantages:

    • Speed: FastBot processes updates and sends messages significantly faster (approx. 2 seconds faster in tests) due to manual response parsing and statically allocated HTTP clients.
    • Memory: It is lighter on Flash (approx. 7kB less) and SRAM (approx. 2kB less) during standard operation.

    Note: Activating the FB_DYNAMIC flag can reduce memory usage by an additional 10kB but will decrease processing speed.

  7. Configure a message whitelist

    main

    You can restrict the bot to only respond to specific chats by using setChatID(). When you provide one or more chat IDs via setChatID(), the library implements a whitelist mechanism: messages from these chats are accepted, while messages from all other chats are ignored.

    bot.setChatID("123456,7891011"); // Only these chats will be processed
  8. Create menus with special formatting

    main

    Menus are created using strings with special formatting characters to define button layout. Note: The library does not perform URL encoding, so avoid using # or & unless they are already encoded.

    Formatting Tokens:

    • \t: Horizontal separation (buttons in the same row).
    • \n: Vertical separation (new row).

    Example 3x1 Menu: "Menu1 \t Menu2 \t Menu3 \n Menu4"

  9. Access message data in the handler

    main

    When the bot's callback is triggered, the following fields are available to inspect the incoming message:

    • userID: The ID of the user.
    • username: The username (first name in API).
    • isBot: Boolean, true if the sender is a bot.
    • chatID: The ID of the chat.
    • messageID: The ID of the message.
    • text: The text content of the message.
    • replyText: The text of the answer, if any.
    • data: The callback data (for inline menus).
    • isFile: Boolean, true if the message contains a file.
    • fileName: The name of the file.
    • fileUrl: The address of the file.
    • query: Boolean, true if it is a query.
    • unix: The Unix timestamp.
  10. Telegram Message Limits and Constraints

    main

    When using FastBot, be aware of Telegram's API limits to avoid message loss or errors:

    Sending Limits:

    • Individual Chats: No more than 1 message per second. Sending more frequently may result in messages not being delivered.
    • Groups: No more than 20 messages per minute.
    • Total Limit: No more than 30 messages per second across all destinations.

    Other Constraints:

    • Message History: The bot can read messages sent within the last 24 hours.
    • Bot-to-Bot: A bot cannot send messages to another bot.
    • Group Visibility: A bot cannot see messages sent by other bots in a group.
    • Text Splitting: Telegram splits text into multiple messages if the length exceeds ~4000 characters. These will have different messageIDs.
    • Reply Parsing: When replying to a message, the library parses the text of the original message, not the text of the reply itself.
  11. Download files from Telegram to local storage

    main

    If an incoming message contains a file, you can download it to the device's internal storage (SPIFFS/LittleFS).

    Requirement: You must include your filesystem library (e.g., LittleFS.h) BEFORE including FastBot.

    Workflow:

    1. Check msg.isFile.
    2. Open a local file for writing ("w").
    3. Use bot.downloadFile(file, msg.fileUrl) to perform the download.
    void newMsg(FB_msg& msg) {
      if (msg.isFile) {
        String path = '/' + msg.fileName;
        File f = LittleFS.open(path, "w");
        bool status = bot.downloadFile(f, msg.fileUrl);
        Serial.println(status ? "OK" : "Error");
      }
    }