[英]How can I send a discord webhook using PHP?
我正在尝试让表单将信息发送到 discord 通道,但我无法建立 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 );
这应该有效:
$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);
$message = "Hello from php";
$webhook= 'https://your_webhook'; //example https://discord.com/api/webhooks/818892216943509504/iaF6RJ2SA1eH4dyWq4iMWNNigAHCzzLGK6e_DBOzPCkh0C6-R0UQ8TWjW87vi51K30Ei
$data = array('content' => $message);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
file_get_contents($webhook, false, stream_context_create($options));
从这里提取的片段
您可以使用具有更多高级功能的 package。 https://packagist.org/packages/atakde/discord-webhook-php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.