简体   繁体   中英

How can I send a discord webhook using PHP?

I'm trying to make a form send the information to a discord channel, but im having trouble making the webhook connection since it just keeps saying {"message": "Cannot send an empty message", "code": 50006} This is my code:

$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 );

This should be working:

$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));

Snippet extracted from here

You can use this package with more advanced features. https://packagist.org/packages/atakde/discord-webhook-php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM