Search code examples
clibcurl

C libcurl verify if message is sent to webhook


Because of variable my_description changes frequently I get this error:

{"code": 50109, "message": "The request body contains invalid JSON."}

It is possible to modify the code below to verify if libcurl gets an error when sending the message to webhook? I want to print when the message is sent and when exist an error in sending a message.

I tried this:

if(res != CURLE_OK)
    fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));

but it is not helpful. Anybody can help me, please? Thanks!

#include <stdio.h>
#include <curl/curl.h>

#define nullptr ((void*)0)    

int main() {

char message[65500];

int max_len = sizeof message;

CURL *curl;
CURLcode res;

char webhook[] = "DISCORD_WEBHOOK";
char my_description[] = "Description";

snprintf(message, max_len,"{\"username\": \"Test\",\"embeds\":[{\"description\": \"%s\"}]}", my_description);

curl = curl_easy_init();
if(curl) {
    struct curl_slist* headers = nullptr;
    headers = curl_slist_append(headers, "Content-Type: application/json");

    curl_easy_setopt(curl, CURLOPT_URL, webhook);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, message);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

    res = curl_easy_perform(curl);

    curl_easy_cleanup(curl);
  }
return 0;
}

Solution

  • I tried this:

    if(res != CURLE_OK)
      fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
    

    You might want to try this:

    if(res != CURLE_OK) {
      fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
    } else {
      long response_code = 0;
      curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
      if(response_code != 200) {
        // Error
      }
    }
    

    An invalid JSON can be caused by quotes in my_description. Quotes must be replaced with escape sequences \".