2026年2月21日 星期六

ESP32 Telegram Echo Bot (回音機器人)

 ESP32 Telegram Echo Bot (回音機器人)



/*******************************************************************
 A telegram bot for your ESP32 that responds
    with whatever message you send it.
 *******************************************************************/
#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++)
  {
    bot.sendMessage(bot.messages[i].chat_id, bot.messages[i].text, "");
  }
}

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 Echo Bot (回音機器人),其核心邏輯是「收到什麼就回傳什麼」。這通常是所有物聯網 (IoT) 機器人開發的起點。

以下為您逐行解說:


1. 引用與基本定義

C++
#include <WiFi.h>              // 提供 ESP32 連接 WiFi 的功能
#include <WiFiClientSecure.h>  // 提供 SSL/TLS 加密連線,因為 Telegram 要求 HTTPS 
#include <UniversalTelegramBot.h> // Telegram Bot 的核心 API 函式庫
  • WIFI_SSID / PASSWORD: 設定 WiFi 連線資訊(此處為 Wokwi 模擬器環境)。

  • BOT_TOKEN: 您從 Telegram BotFather 取得的專屬權杖 (Token)。

  • BOT_MTBS: 每隔 1000 毫秒(1秒)詢問一次伺服器是否有新訊息。


2. 核心通訊物件

C++
WiFiClientSecure secured_client;             // 建立加密的客戶端
UniversalTelegramBot bot(BOT_TOKEN, secured_client); // 初始化機器人物件
unsigned long bot_lasttime;                  // 記錄最後一次檢查訊息的時間

3. 處理新訊息 (handleNewMessages)

這是機器人接收到訊息後的「反應」邏輯:

C++
void handleNewMessages(int numNewMessages)
{
  for (int i = 0; i < numNewMessages; i++) // 逐一處理收到的訊息包
  {
    // bot.sendMessage(接收者ID, 文字內容, 解析模式)
    // 這裡直接將收到的 text 內容再發送回該 chat_id
    bot.sendMessage(bot.messages[i].chat_id, bot.messages[i].text, "");
  }
}

4. 初始化設定 (setup)

這段程式碼只在 ESP32 啟動時執行一次。

  • 連接 WiFi: 嘗試連上指定 SSID。

  • 設定憑證: secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT) 是必要的,用來驗證 Telegram 伺服器的安全性。

  • 同步時間: configTime(0, 0, "pool.ntp.org")這非常重要,因為 HTTPS 加密通訊需要正確的時間戳記,否則連線會被 Telegram 拒絕。


5. 主要迴圈 (loop)

程式啟動後會不斷重複執行的部分:

C++
void loop()
{
  // 檢查是否已經超過了設定的間隔時間 (1秒)
  if (millis() - bot_lasttime > BOT_MTBS)
  {
    // 向伺服器要求新訊息,bot.last_message_received + 1 用來確保不重複抓取
    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(); // 更新最後檢查時間
  }
}

程式運作邏輯總結

  1. 連線階段:ESP32 連上 WiFi 並與網路對時。

  2. 輪詢 (Polling):ESP32 每隔一秒問 Telegram:「嘿,有人跟我說話嗎?」

  3. 解析:如果有人傳訊息(例如傳了 "Hello"),bot.getUpdates 就會抓到資料。

  4. 回應handleNewMessages 被觸發,機器人讀取 "Hello" 並立刻執行 sendMessage 把 "Hello" 傳回去。

沒有留言:

張貼留言

ESP32 Telegram 指令選單(Bot Commands)

ESP32 Telegram 指令選單(Bot Commands)  /*******************************************************************  ***********************************...