1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ESP32からChatworkへメッセージを送る

Last updated at Posted at 2023-11-09

ESP32からChatworkへメッセージを送ろうと思ったけど、ぴったりの情報が見つけられず試行錯誤したので記録に残します。

動機

M5stackでネットワーク機器にpingして死活確認を行い、落ちてたらChatworkで通知を送ってくるようにしたい。

成功したコード

以下のコードで送れました。

chatwork_send.ino
// Chatwork api活用
#include <WiFi.h>
#include <HTTPClient.h>
#include <ESPping.h>

const char* SSID     = "mySSID";
const char* PASSWORD = "myPASSWORD";

String BASE_URL  = "https://api.chatwork.com/v2/rooms/";
String ROOM_NAME = "xxxxxxxx";                  //グループID
String MYTOKEN   = "xxxxxxxxxxxxxxxxxxx";       //Token
String URL       = BASE_URL + ROOM_NAME + "/messages";

void chatwork_send(String message) {
  String httpRequestData ="";
  httpRequestData += "body=" + message;
 
  //HTTPClientでPOST
  HTTPClient httpclient;
  httpclient.begin(URL.c_str());

  httpclient.addHeader("Content-Type", "application/x-www-form-urlencoded");
  httpclient.addHeader("x-chatworktoken", MYTOKEN.c_str());

  int httpCode = httpclient.POST(httpRequestData);
  
    if (httpCode == HTTP_CODE_OK) {    //送信OK
    Serial.println(httpRequestData);
    Serial.println("chat send!");
    } else {    //送信失敗
    Serial.printf("[HTTP] POST... failed, error: %s\n", httpclient.errorToString(httpCode).c_str());
    Serial.println("chat error!");
    }
  Serial.println();
  httpclient.end();  //HTTPClient終了
  delay(1000);
}

void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.begin(SSID, PASSWORD);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500); Serial.print(".");
  }
  Serial.print("\nWiFi connect: OK");
  chatwork_send("テストだよ");
}

void loop(){}

以上です。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?