Search code examples
phpcurl

Discord webhook returns code 50006 (Cannot send an empty message)


I am working on a little piece of code that allows my website to communicate with a discord channel. I set up the webhook and read through several documentations about it, and decided not to go with an API but with a webhook. I dont ask much of it.

I cant seem to figure out what i did wrong here, i submitting a string of text as a json into CURL, but for some odd reason it stays blank.

$url = URL_TO_THE_WEBHOOK
$data = json_encode(
    array(
        "content" => "Hi, i am a dummy text. I talk from the website."
    )
);

$ch= curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, "Content-Type: application/json");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
$response = curl_exec($ch);
$err_status = curl_error($ch);

print_r($data);

if(!empty($response)){
    echo $response;
}else{
    echo $err_status;
}
curl_close($ch);

which sadly returns

{"content":"Hi, i am a dummy text. I talk from the website."}{"message": "Cannot send an empty message", "code": 50006}

Am i missing something?


Solution

  • Okay, its vague in the documentation, but figured it out. Appearantly, the object you are sending needs to have a length attached to it how long the JSON string is.

    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Length" => strlen( $data),"Content-Type: application/json"]);