2026年2月21日 星期六

ESP32 Telegram 編輯既有訊息(Edit Existing Message) UPdate

ESP32 Telegram 編輯既有訊息(Edit Existing Message) UPdate




/*******************************************************************
An example to show how to edit an existing inline keyboard.
    In this example the keyboard is updated with the state of
    the LED.
 *******************************************************************/
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>

// Wifi network station credentials
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// Telegram BOT Token (Get from Botfather)
#define BOT_TOKEN "77381940254:AAHbrWu9ovb12BKPQyWsbNSjNxfCGCrEWU-o"

// LED parameters
const int ledPin = 2;                // Internal LED on DevKit ESP32-WROOM (GPIO2)
const unsigned long BOT_MTBS = 1000; // mean time between scan messages

WiFiClientSecure secured_client;
UniversalTelegramBot bot(BOT_TOKEN, secured_client);
unsigned long bot_lasttime; // last time messages' scan has been done
int last_message_id = 0;
int ledState = LOW;

void handleNewMessages(int numNewMessages)
{

    for (int i = 0; i < numNewMessages; i++)
    {

        // Get all the important data from the message
        int message_id = bot.messages[i].message_id;
        String chat_id = String(bot.messages[i].chat_id);
        String text = bot.messages[i].text;
        String from_name = bot.messages[i].from_name;
        if (from_name == "")
            from_name = "Guest";
        String msg = ""; // init a message string to use

        // Output the message_id to give you feeling on how this example works
        Serial.print("Message id: ");
        Serial.println(message_id);

        // Inline buttons with callbacks when pressed will raise a callback_query message
        if (bot.messages[i].type == "callback_query")
        {
            Serial.print("Call back button pressed by: ");
            Serial.println(bot.messages[i].from_id);
            Serial.print("Data on the button: ");
            Serial.println(bot.messages[i].text);

            if (text == "/toggleLED")
            {

                // Toggle the ledState and update the LED itself
                ledState = !ledState;
                digitalWrite(ledPin, ledState);

                // Now we can UPDATE the message, lets prepare it for sending:
                msg = "Hi " + from_name + "!\n";
                msg += "Notice how the LED state has changed!\n\n";
                msg += "Try it again, see the button has updated as well:\n\n";

                // Prepare the buttons
                String keyboardJson = "["; // start Json
                keyboardJson += "[{ \"text\" : \"The LED is ";
                if (ledState)
                {
                    keyboardJson += "ON";
                }
                else
                {
                    keyboardJson += "OFF";
                }
                keyboardJson += "\", \"callback_data\" : \"/toggleLED\" }]";
                keyboardJson += ", [{ \"text\" : \"Send text\", \"callback_data\" : \"This text was sent by inline button\" }]"; // add another button
                //keyboardJson += ", [{ \"text\" : \"Go to Google\", \"url\" : \"https://www.google.com\" }]"; // add another button, this one appears after first Update
                keyboardJson += "]"; // end Json

                // Now send this message including the current message_id as the 5th input to UPDATE that message
                bot.sendMessageWithInlineKeyboard(chat_id, msg, "Markdown", keyboardJson, message_id);
            }

            else
            {
                // echo back callback_query which is not handled above
                bot.sendMessage(chat_id, text, "Markdown");
            }
        }

        // 'Normal' messages are handled here
        else
        {
            if (text == "/start")
            {
                // lets create a friendly welcome message
                msg = "Hi " + from_name + "!\n";
                msg += "I am your Telegram Bot running on ESP32.\n\n";
                msg += "Lets test this updating LED button below:\n\n";

                // lets create a button depending on the current ledState
                String keyboardJson = "["; // start of keyboard json
                keyboardJson += "[{ \"text\" : \"The LED is ";
                if (ledState)
                {
                    keyboardJson += "ON";
                }
                else
                {
                    keyboardJson += "OFF";
                }
                keyboardJson += "\", \"callback_data\" : \"/toggleLED\" }]";                                                     //callback is /toggleLED
                keyboardJson += ", [{ \"text\" : \"Send text\", \"callback_data\" : \"This text was sent by inline button\" }]"; // add another button
                keyboardJson += "]";                                                                                             // end of keyboard json

                //first time, send this message as a normal inline keyboard message:
                bot.sendMessageWithInlineKeyboard(chat_id, msg, "Markdown", keyboardJson);
            }
            if (text == "/options")
            {
                String keyboardJson = "[[{ \"text\" : \"Go to Google\", \"url\" : \"https://www.google.com\" }], [{ \"text\" : \"Send\", \"callback_data\" : \"This was sent by inline\" }]]";
                bot.sendMessageWithInlineKeyboard(chat_id, "Choose from one of the following options", "", keyboardJson);
            }
        }
    }
}

void setup()
{
    Serial.begin(115200);
    Serial.println();

    // attempt to connect to Wifi network:
    Serial.print("Connecting to Wifi SSID ");
    Serial.print(WIFI_SSID);
    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
    while (WiFi.status() != WL_CONNECTED)
    {
        Serial.print(".");
        delay(500);
    }
    Serial.print("\nWiFi connected. IP address: ");
    Serial.println(WiFi.localIP());

    Serial.print("Retrieving time: ");
    configTime(0, 0, "pool.ntp.org"); // get UTC time via NTP
    time_t now = time(nullptr);
    while (now < 24 * 3600)
    {
        Serial.print(".");
        delay(100);
        now = time(nullptr);
    }
    Serial.println(now);

    pinMode(ledPin, OUTPUT);        // initialize ledPin as an output.
    digitalWrite(ledPin, ledState); // initialize pin as low (LED Off)
}

void loop()
{
    if (millis() - bot_lasttime > BOT_MTBS)
    {
        int numNewMessages = bot.getUpdates(bot.last_message_received + 1);

        while (numNewMessages)
        {
            Serial.println("got response");
            handleNewMessages(numNewMessages);
            numNewMessages = bot.getUpdates(bot.last_message_received + 1);
        }

        bot_lasttime = millis();
    }
}


這段程式碼展示了 Telegram 機器人一個非常高級且優雅的功能:編輯既有訊息(Edit Existing Message)。

一般的機器人在狀態改變時會不斷傳送「新訊息」,導致聊天視窗被洗版。而這段程式碼則是在「同一則訊息」上直接更新內容與按鈕文字。以下是詳細解說:


1. 核心觀念:編輯訊息

這段程式碼的核心在於 bot.sendMessageWithInlineKeyboard 函式的第五個參數。

C++
// 語法:bot.sendMessageWithInlineKeyboard(chat_id, 訊息, 格式, 鍵盤JSON, 訊息ID);
bot.sendMessageWithInlineKeyboard(chat_id, msg, "Markdown", keyboardJson, message_id);
  • 如果有帶入 message_id,Telegram 就不會傳新訊息,而是去修改該 ID 對應的那則舊訊息。


2. 處理流程詳解 (handleNewMessages)

A. 獲取訊息資訊

C++
int message_id = bot.messages[i].message_id; // 取得目前的訊息 ID
String text = bot.messages[i].text;          // 取得按鈕觸發的 callback_data

B. 處理按鈕回傳 (callback_query)

當使用者點擊按鈕時:

  1. 切換狀態:執行 ledState = !ledState; 並更新實體 LED 燈。

  2. 重新構建 JSON:程式會檢查新的 ledState,動態組合按鈕文字。

    • 如果燈開了,按鈕文字變為 "The LED is ON"。

    • 如果燈關了,按鈕文字變為 "The LED is OFF"。

  3. 原地更新:呼叫 sendMessageWithInlineKeyboard 並傳入 message_id。這會讓使用者感覺按鈕按下去後,原本的文字和按鈕內容直接「變身」了。


3. 指令邏輯:/start 與 /options

  • /start:機器人會第一次送出帶有 LED 狀態按鈕的訊息。這是「父訊息」,之後所有的更新都會發生在這則訊息上。

  • /options:展示傳統的按鈕跳轉功能(如開啟 Google 網頁)。


4. 硬體與環境設定 (setup)

  • GPIO 2:這是大多數 ESP32 開發板(如 WROOM)內建藍色 LED 的引腳。

  • Time Sync:同樣使用了 NTP 時間同步,確保 HTTPS 安全連線不會因為時間誤差而斷線。


5. 為什麼要用「編輯訊息」模式?

傳統模式 (傳送新訊息)編輯模式 (本範例)
聊天紀錄會變得很長、很亂。聊天視窗乾淨整潔。
使用者需要捲動螢幕查看最新狀態。使用者停留在同一個位置即可操作。
適合用於「通知」或「對話紀錄」。適合用於「控制面板」或「設定選單」。



ESP32 Telegram 回覆鍵盤 (Reply Keyboard)」

 ESP32 Telegram 回覆鍵盤 (Reply Keyboard)」


/*******************************************************************
     An example of how to use a custom reply keyboard markup.  
     written by Vadim Sinitski (modified by Brian Lough)
 *******************************************************************/
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>

// Wifi network station credentials
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// Telegram BOT Token (Get from Botfather)
#define BOT_TOKEN "7738940254:AAHbrWu9ovb1BKPQyWsbNSjNxfCGCrEWU-o"
const unsigned long BOT_MTBS = 1000; // mean time between scan messages
const int ledPin = 2 ;

WiFiClientSecure secured_client;
UniversalTelegramBot bot(BOT_TOKEN, secured_client);
unsigned long bot_lasttime;          // last time messages' scan has been done
int ledStatus = 0;

void handleNewMessages(int numNewMessages)
{
  Serial.println("handleNewMessages");
  Serial.println(String(numNewMessages));

  for (int i = 0; i < numNewMessages; i++)
  {
    String chat_id = bot.messages[i].chat_id;
    String text = bot.messages[i].text;

    String from_name = bot.messages[i].from_name;
    if (from_name == "")
      from_name = "Guest";

    if (text == "/ledon")
    {
      digitalWrite(ledPin, HIGH); // turn the LED on (HIGH is the voltage level)
      ledStatus = 1;
      bot.sendMessage(chat_id, "Led is ON", "");
    }

    if (text == "/ledoff")
    {
      ledStatus = 0;
      digitalWrite(ledPin, LOW); // turn the LED off (LOW is the voltage level)
      bot.sendMessage(chat_id, "Led is OFF", "");
    }

    if (text == "/status")
    {
      if (ledStatus)
      {
        bot.sendMessage(chat_id, "Led is ON", "");
      }
      else
      {
        bot.sendMessage(chat_id, "Led is OFF", "");
      }
    }

    if (text == "/options")
    {
      String keyboardJson = "[[\"/ledon\", \"/ledoff\"],[\"/status\"]]";
      bot.sendMessageWithReplyKeyboard(chat_id, "Choose from one of the following options", "", keyboardJson, true);
    }

    if (text == "/start")
    {
      String welcome = "Welcome to Universal Arduino Telegram Bot library, " + from_name + ".\n";
      welcome += "This is Reply Keyboard Markup example.\n\n";
      welcome += "/ledon : to switch the Led ON\n";
      welcome += "/ledoff : to switch the Led OFF\n";
      welcome += "/status : Returns current status of LED\n";
      welcome += "/options : returns the reply keyboard\n";
      bot.sendMessage(chat_id, welcome, "Markdown");
    }
  }
}

void setup()
{
  Serial.begin(115200);
  Serial.println();

  // attempt to connect to Wifi network:
  Serial.print("Connecting to Wifi SSID ");
  Serial.print(WIFI_SSID);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(500);
  }
  Serial.print("\nWiFi connected. IP address: ");
  Serial.println(WiFi.localIP());

  Serial.print("Retrieving time: ");
  configTime(0, 0, "pool.ntp.org"); // get UTC time via NTP
  time_t now = time(nullptr);
  while (now < 24 * 3600)
  {
    Serial.print(".");
    delay(100);
    now = time(nullptr);
  }
  Serial.println(now);

  pinMode(ledPin, OUTPUT); // initialize digital ledPin as an output.
  delay(10);
  digitalWrite(ledPin, LOW); // initialize pin as off
}

void loop()
{
  if (millis() - bot_lasttime > BOT_MTBS)
  {
    int numNewMessages = bot.getUpdates(bot.last_message_received + 1);

    while (numNewMessages)
    {
      Serial.println("got response");
      handleNewMessages(numNewMessages);
      numNewMessages = bot.getUpdates(bot.last_message_received + 1);
    }

    bot_lasttime = millis();
  }
}


這段程式碼將 Telegram 機器人與 ESP32 的硬體控制(LED 燈) 結合,並使用了 「回覆鍵盤 (Reply Keyboard)」。

與前一個範例的「內嵌按鈕」不同,回覆鍵盤會直接取代使用者的手機輸入法鍵盤,讓使用者像點選選單一樣發送指令。以下是詳細說明:


1. 硬體定義與狀態變數

C++
const int ledPin = LED_BUILTIN; // 定義 LED 引腳(通常是開發板上的內建 LED,GPIO 2)
int ledStatus = 0;              // 儲存 LED 的狀態:0 為關,1 為開

2. 指令邏輯:handleNewMessages

這部分決定了收到不同文字指令時,硬體該如何反應:

  • 開燈與關燈 (/ledon, /ledoff)

    C++
    if (text == "/ledon") {
      digitalWrite(ledPin, HIGH); // 輸出高電位,點亮 LED
      ledStatus = 1;              // 記錄狀態
      bot.sendMessage(chat_id, "Led is ON", ""); // 回報訊息
    }
    
  • 查詢狀態 (/status)

    C++
    if (text == "/status") {
      // 根據 ledStatus 變數判斷目前狀態並回報
      if (ledStatus) bot.sendMessage(chat_id, "Led is ON", "");
      else bot.sendMessage(chat_id, "Led is OFF", "");
    }
    

3. 自定義回覆鍵盤 (/options)

這是本程式最實用的部分,它讓控制變得直覺:

C++
if (text == "/options") {
  // 定義鍵盤佈局:第一排兩個按鈕,第二排一個按鈕
  String keyboardJson = "[[\"/ledon\", \"/ledoff\"],[\"/status\"]]";
  
  // 傳送鍵盤,最後一個參數 true 代表點擊後會自動縮回鍵盤
  bot.sendMessageWithReplyKeyboard(chat_id, "Choose from one of the following options", "", keyboardJson, true);
}

4. 初始化與硬體設定 (setup)

除了 WiFi 和時間同步,這裡多了一個關鍵步驟:

C++
pinMode(ledPin, OUTPUT);    // 將 LED 引腳設定為輸出模式
digitalWrite(ledPin, HIGH); // 初始化狀態(注意:有些板子 HIGH 是關燈,視硬體配置而定)

5. 功能比較:Inline vs Reply Keyboard

特性內嵌鍵盤 (Inline - 前一個範例)回覆鍵盤 (Reply - 本範例)
位置附著在特定訊息下方取代手機原本的輸入法區域
操作點擊後發送隱藏資料 (Callback)點擊後等同於「幫使用者打字」發送
外觀較精美,適合單次操作較醒目,適合持續性的選單控制

程式運作流程總結

  1. 啟動:ESP32 連接 WiFi,同步時間,並準備好 GPIO 2 控制權。

  2. 等待:每秒檢查一次 Telegram 訊息。

  3. 互動:

    • 使用者輸入 /start 看到說明。

    • 使用者輸入 /options 彈出「按鈕選單」。

    • 點選按鈕時,手機自動發出 /ledon 等指令。

    • ESP32 接收指令後,切換 LED 正負極電壓,並回傳結果。

ESP32 Telegram 內嵌鍵盤 (Inline Keyboard)

 ESP32 Telegram 內嵌鍵盤 (Inline Keyboard)




/*******************************************************************
    An example of how to use a custom reply keyboard markup.
     written by Vadim Sinitski (modified by Brian Lough)
 *******************************************************************/
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>

// Wifi network station credentials
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// Telegram BOT Token (Get from Botfather)
#define BOT_TOKEN "7738940254:AAHbrWu9ovb1BKPQyWsbNSjNxfCGCrEWU-o"

const unsigned long BOT_MTBS = 1000; // mean time between scan messages

WiFiClientSecure secured_client;
UniversalTelegramBot bot(BOT_TOKEN, secured_client);
unsigned long bot_lasttime;          // last time messages' scan has been done

void handleNewMessages(int numNewMessages)
{
  for (int i = 0; i < numNewMessages; i++)
  {
    // Inline buttons with callbacks when pressed will raise a callback_query message
    if (bot.messages[i].type == "callback_query")
    {
      Serial.print("Call back button pressed by: ");
      Serial.println(bot.messages[i].from_id);
      Serial.print("Data on the button: ");
      Serial.println(bot.messages[i].text);
      bot.sendMessage(bot.messages[i].from_id, bot.messages[i].text, "");
    }
    else
    {
      String chat_id = bot.messages[i].chat_id;
      String text = bot.messages[i].text;

      String from_name = bot.messages[i].from_name;
      if (from_name == "")
        from_name = "Guest";

      if (text == "/options")
      {
        String keyboardJson = "[[{ \"text\" : \"Go to Google\", \"url\" : \"https://www.google.com\" }],[{ \"text\" : \"Send\", \"callback_data\" : \"This was sent by inline\" }]]";
        bot.sendMessageWithInlineKeyboard(chat_id, "Choose from one of the following options", "", keyboardJson);
      }

      if (text == "/start")
      {
        String welcome = "Welcome to Universal Arduino Telegram Bot library, " + from_name + ".\n";
        welcome += "This is Inline Keyboard Markup example.\n\n";
        welcome += "/options : returns the inline keyboard\n";

        bot.sendMessage(chat_id, welcome, "Markdown");
      }
    }
  }
}

void setup()
{
  Serial.begin(115200);
  Serial.println();

  // attempt to connect to Wifi network:
  Serial.print("Connecting to Wifi SSID ");
  Serial.print(WIFI_SSID);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(500);
  }
  Serial.print("\nWiFi connected. IP address: ");
  Serial.println(WiFi.localIP());

  Serial.print("Retrieving time: ");
  configTime(0, 0, "pool.ntp.org"); // get UTC time via NTP
  time_t now = time(nullptr);
  while (now < 24 * 3600)
  {
    Serial.print(".");
    delay(100);
    now = time(nullptr);
  }
  Serial.println(now);
}

void loop()
{
  if (millis() - bot_lasttime > BOT_MTBS)
  {
    int numNewMessages = bot.getUpdates(bot.last_message_received + 1);

    while (numNewMessages)
    {
      Serial.println("got response");
      handleNewMessages(numNewMessages);
      numNewMessages = bot.getUpdates(bot.last_message_received + 1);
    }

    bot_lasttime = millis();
  }
}


這段程式碼展示了 Telegram 機器人最強大的功能之一:內嵌鍵盤 (Inline Keyboard)。與之前的程式不同,這次機器人會送出帶有「按鈕」的訊息,使用者點擊按鈕後會觸發特定的回饋。

以下是逐行詳細說明:


1. 核心邏輯:處理按鈕回傳 (callback_query)

在 handleNewMessages 函式中,新增了對按鈕點擊的判斷:

C++
if (bot.messages[i].type == "callback_query") {
  // 當使用者點擊帶有 callback_data 的按鈕時,會進入這裡
  Serial.print("Call back button pressed by: ");
  Serial.println(bot.messages[i].from_id); // 印出是誰按的
  Serial.print("Data on the button: ");
  Serial.println(bot.messages[i].text);    // 印出按鈕內藏的資料 (callback_data)
  
  // 機器人回應:把按鈕內藏的文字再傳回給使用者
  bot.sendMessage(bot.messages[i].from_id, bot.messages[i].text, "");
}
  • callback_query:這是一種特殊的訊息類型。當按鈕被按下時,Telegram 會發送一個「請求」而不是普通文字,這讓機器人知道該執行哪個特定動作。


2. 建立內嵌鍵盤指令 (/options)

這是本範例的核心,展示如何撰寫 JSON 格式來產生按鈕:

C++
if (text == "/options") {
  // 定義鍵盤結構 (JSON 格式)
  // 第一排:一個按鈕,功能是開啟網址 (URL)
  // 第二排:一個按鈕,點擊後會發送隱藏的 "callback_data"
  String keyboardJson = "[ "
                        "[{ \"text\" : \"Go to Google\", \"url\" : \"https://www.google.com\" }], "
                        "[{ \"text\" : \"Send\", \"callback_data\" : \"This was sent by inline\" }]"
                        " ]";

  // 使用專門的函式傳送帶有鍵盤的訊息
  bot.sendMessageWithInlineKeyboard(chat_id, "Choose from one of the following options", "", keyboardJson);
}
  • 鍵盤 JSON 結構:

    • text: 按鈕上顯示的文字。

    • url: 點擊後會跳轉到該網頁。

    • callback_data: 不會顯示在螢幕上,但點擊後機器人會收到這串文字,用來判斷使用者按了哪個按鈕。


3. 基礎設定與時間同步 (setup & loop)

這部分與前幾個範例類似,但有幾個重點:

  • configTime: 機器人必須同步網路時間(NTP),因為 Telegram 的加密連線會檢查時間戳記。如果開發板時間不準,連線會被拒絕。

  • bot.getUpdates: 在 loop 中持續詢問伺服器有沒有新訊息。如果有訊息(包含按鈕點擊),就會交給 handleNewMessages 處理。


4. 程式邏輯流程圖解

步驟使用者動作機器人反應
1輸入 /start傳送歡迎詞,告知有 /options 指令。
2輸入 /options彈出兩個按鈕:「Go to Google」與「Send」。
3點擊 「Send」手機端不會看到文字發出,但機器人會收到 callback_query,並回傳訊息。

為什麼這很有用?

內嵌鍵盤可以讓你的專案看起來非常專業。例如:

  • 家電控制:不需要打字,直接按「開燈」或「關燈」按鈕。

  • 選單導航:透過按鈕切換不同的感測器數據顯示(如:溫度、濕度、光照)。

MIFARE Classic Command Flow Diagram

MIFARE Classic Command Flow Diagram   這個程式將圖片中的 MIFARE Classic Command Flow Diagram 完整繪製在畫布上(包含中英文對照、虛線錯誤返回路徑、實線流程箭頭以及右側的「典型交易時間」資訊),並提供「上一...