2025年11月13日 星期四

使用WOKWI 發送Line Message API 訊息到Line 上

使用WOKWI 發送Line Message API 訊息到Line 上




const char* LINE_CHANNEL_ACCESS_TOKEN = "P7aR4jd31q5usv1YjhlJaC9HGXwcq6G0YknpvDxOb356AnOGHt5MPpzXmJrxj5L9OY5Z70h1DSdKRGr2/6Q8cN0bVoh6PcUMISbfncKvnMmv2HG5GCR+HMgpPj2LQYqOLDKgDqUGchzrkgkrG1KhnhfnugdB04t89/1O/w1cDnyilFU=";

const char* LINE_USER_ID              = "U6a0f091afaaf21d4j1e21ace45205bfd3cf";










#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h> // 用於乾淨地構建 JSON 請求體

// --- Line Message API 參數 (硬編碼) ---
const char* LINE_CHANNEL_ACCESS_TOKEN = "P7aR4jd31q5usv1YjhlJaC9HGXwcq6G0YknpvDxOb356AnOGHt5MPpzXmJrxj5L9OY5Z70h1DSdKRGr2/6Q8cN0bVoh6PcUMISbfncKvnMmv2HG5GCR+HMgpPj2LQYqOLDKgDqUGchzrkgkrG1KhnhfnugdB04t89/1O/w1cDnyilFU=";
const char* LINE_USER_ID              = "U6a0f091afaaf21d4j1e21ace45205bfd3cf";
const char* LINE_MESSAGE_CONTENT      = "Hello World ESP32"; // <-- 要發送的訊息內容
const char* LINE_API_ENDPOINT         = "https://api.line.me/v2/bot/message/push";

// --- Wokwi 模擬 Wi-Fi 憑證 ---
const char* WIFI_SSID     = "Wokwi-GUEST"; // Wokwi 模擬器專用 SSID
const char* WIFI_PASSWORD = "";           // Wokwi 模擬器專用密碼 (空字串)

// --- 輔助函數 ---

/**
 * @brief 連接 Wokwi 模擬 Wi-Fi
 */
void connectWiFi() {
    Serial.print("連線到 Wi-Fi: ");
    Serial.println(WIFI_SSID);
   
    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

    int attempts = 0;
    while (WiFi.status() != WL_CONNECTED && attempts < 20) {
        delay(500);
        Serial.print(".");
        attempts++;
    }

    if (WiFi.status() == WL_CONNECTED) {
        Serial.println("\nWi-Fi 連線成功! (Wokwi 模擬環境)");
        Serial.print("IP 位址: ");
        Serial.println(WiFi.localIP());
    } else {
        Serial.println("\nWi-Fi 連線失敗! (請檢查 Wokwi 網路設定)");
    }
}

/**
 * @brief 向 Line Message API 發送推播訊息
 */
void sendLineMessage() {
    if (WiFi.status() != WL_CONNECTED) {
        Serial.println("Line 訊息發送失敗:Wi-Fi 未連線。");
        return;
    }

    HTTPClient http;
    // 開始 HTTP 連線
    http.begin(LINE_API_ENDPOINT);
   
    // 設定 HTTP 標頭
    http.addHeader("Content-Type", "application/json");
    // Line 要求的授權標頭
    String authHeader = String("Bearer ") + LINE_CHANNEL_ACCESS_TOKEN;
    http.addHeader("Authorization", authHeader);

    // 建立 JSON 請求體
    StaticJsonDocument<256> doc;
    doc["to"] = LINE_USER_ID;

    JsonArray messages = doc.createNestedArray("messages");
    JsonObject msg = messages.createNestedObject();
    msg["type"] = "text";
    msg["text"] = LINE_MESSAGE_CONTENT; // 使用硬編碼的訊息內容

    String requestBody;
    serializeJson(doc, requestBody);

    Serial.println("\n--- 正在發送 Line 訊息 ---");
    Serial.print("發送對象 ID: "); Serial.println(LINE_USER_ID);
    Serial.print("發送內容: "); Serial.println(LINE_MESSAGE_CONTENT);
    Serial.print("請求體: "); Serial.println(requestBody);

    // 發送 POST 請求
    int httpResponseCode = http.POST(requestBody);

    if (httpResponseCode > 0) {
        Serial.printf("[HTTP] POST... code: %d\n", httpResponseCode);
        if (httpResponseCode == HTTP_CODE_OK || httpResponseCode == HTTP_CODE_ACCEPTED) {
            Serial.println("Line 訊息發送成功!");
        } else {
            String payload = http.getString();
            Serial.println("Line 訊息發送失敗,伺服器回應錯誤。");
            Serial.print("錯誤詳情: "); Serial.println(payload);
        }
    } else {
        Serial.printf("[HTTP] POST... 失敗,錯誤碼: %s\n", http.errorToString(httpResponseCode).c_str());
    }

    http.end();
}

void setup() {
    Serial.begin(115200);
    delay(1000);

    Serial.println("--- Line Message Wokwi 測試啟動 ---");
   
    // 1. 連接 Wi-Fi
    connectWiFi();

    // 2. 發送 Line 訊息
    if (WiFi.status() == WL_CONNECTED) {
        sendLineMessage();
    }
   
    Serial.println("\n--- 程式執行結束 ---");
}

void loop() {
    // 程式只在 setup() 中執行一次訊息發送
    delay(1000);
}

沒有留言:

張貼留言

ESP32 (ESP-IDF in VS Code) MFRC522 + MQTT + PYTHON TKinter +SQLite

 ESP32 (ESP-IDF in VS Code) MFRC522 + MQTT + PYTHON TKinter +SQLite  ESP32 VS Code 程式 ; PlatformIO Project Configuration File ; ;   Build op...