3
2

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 5 years have passed since last update.

ESP32(Nefry BT)からDiscrodのWebhookに通知するメモ

Posted at

最近Discrodを使ってみてちょっと試してみてます。

Nefry BTで試してますが、ESP32でコンパイルは通ったのでWiFi設定とかだけ書いてあげれば他のESP32デバイスでも使えると思います。

discord.ino
# include <WiFiClientSecure.h>
WiFiClientSecure client;

const int HTTPS_PORT = 443;

void discordPost(String message);

void setup() {
  Serial.begin(115200);
  Serial.println("init..");
  discordPost("こんにちは"); //一回だけPOSTする
}

void loop() {}

//DiscrodにPOSTする関数
void discordPost(String message){
  const char* HOST = "discordapp.com";
  String url = "/api/webhooks/xxxxxx"; //DiscordのWebhookのpath
  String content = "{\"content\": \""+ message +"\"}";
  Serial.print("connecting to ");
  Serial.println(HOST);

  if (!client.connect(HOST, HTTPS_PORT)) {
    Serial.println("connection failed");
    return;
  }

  client.println("POST " + url + " HTTP/1.1");
  client.println("Content-Length: " + String(content.length()));
  client.println("Content-Type: application/json");
  client.println("Host: " + String(HOST));
  client.println("Accept: */*");
  client.println("Connection: close");
  client.println();
  client.println(content);

  unsigned long timeout = millis();
  while (client.available() == 0) {    
    if (millis() - timeout > 5000) {
        Serial.println(">>> Client Timeout !");
        client.stop();
        return;
    }
  }

  // Read all the lines of the reply from server and print them to Serial
  while(client.available()) {
      String line = client.readStringUntil('\r');
      Serial.print(line);
  }

  Serial.println();
  Serial.println("closing connection"); 
}

はまったところ

Content-Lengthをしっかり入れてあげないと動いてくれませんでした。
HipChatに送るときはそのままで問題なかったので、サーバー側でよしなにやってくれてたみたい。

あと、Content-Type: application/jsonのヘッダー指定も忘れずに

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?