首页 > 解决方案 > 如何使用 PHP 发送不和谐的 webhook?

问题描述

我正在尝试让表单将信息发送到不和谐的频道,但我无法建立 webhook 连接,因为它只是一直说{"message": "Cannot send an empty message", "code": 50006} 这是我的代码:

$url = "https://discordapp.com/api/webhooks/xxxxxxxxx";

$hookObject = json_encode([
    "content" => "A message will go here",
    "username" => "MyUsername",
], JSON_FORCE_OBJECT);

$ch = curl_init();
var_dump($hookObject);
curl_setopt_array( $ch, [
    CURLOPT_URL => $url,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $hookObject,
    CURLOPT_HTTPHEADER => [
        "Length" => strlen( $hookObject ),
        "Content-Type" => "application/json"
    ]
]);

$response = curl_exec( $ch );
curl_close( $ch );

标签: phpdiscord

解决方案


这应该有效:

$url = "https://discordapp.com/api/webhooks/xxxxxxxxx";
$headers = [ 'Content-Type: application/json; charset=utf-8' ];
$POST = [ 'username' => 'Testing BOT', 'content' => 'Testing message' ];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($POST));
$response   = curl_exec($ch);

推荐阅读