英文:
Discord webhook returns code 50006 (Cannot send an empty message)
问题
抱歉,你的代码中有一些问题,让我来帮你修复一下:
$url = 'URL_TO_THE_WEBHOOK'; // 请将 URL_TO_THE_WEBHOOK 替换为你的 Webhook URL
$data = json_encode(
array(
"content" => "Hi, I am a dummy text. I talk from the website."
)
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
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);
curl_close($ch);
print_r($data);
if (!empty($response)) {
echo $response;
} else {
echo $err_status;
}
上述代码中主要修复了以下几点问题:
- 将
$url
的赋值语句中的URL_TO_THE_WEBHOOK
替换为你的 Webhook URL。 - 修复了
curl_setopt($ch, CURLOPT_HTTPHEADER, ...)
行,确保请求头正确设置。 - 修复了
$ch
的初始化,直接传递 URL 参数给curl_init()
。
请将上述修复后的代码替代原始代码进行尝试,看看是否能够正常发送消息到 Discord 频道。
英文:
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?
答案1
得分: 0
Okay, its vague in the documentation, but figured it out. Apparently, 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"]);
英文:
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"]);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论