DEV Community

Sajith Karunatilake
Sajith Karunatilake

Posted on

Send messages to a Discord Server Channel using PHP. Change the variables to customize the code.

Send messages to a Discord Server Channel using PHP. Change the variables to customize the code.

<?php
    $webhook_url        = "https://discord.com/api/webhooks/00000000000000000000/{TOKEN}";
    $user_name          = "SENDING USER";
    $msg_content        = "Message Content!";
    $avatar_url         = "http://dod.gov/avatar.jpg";
    $msg_description    = "This is the message body!";
    $msg_color          = "15844367";
    $msg_footer         = "This is the footer text!";

    $handle = curl_init($webhook_url."?wait=true");

    $data = [
        "tts" => false,
        "username" => $user_name,
        "content" => $msg_content,
        "avatar_url" => $avatar_url,
        "embeds" => [ 
            [ 
                "description" => $msg_description,
                "color" => $msg_color,
                "footer" => [
                    "text" => $msg_footer,
                ]
            ] 
        ]
    ];

    $encodedData = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

    curl_setopt($handle, CURLOPT_POST, 1);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($handle, CURLOPT_POSTFIELDS, $encodedData);
    curl_setopt($handle, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);

    $result = curl_exec($handle);
    $res = json_decode($result);

    echo "Message Sent! Message ID: ".$res->{"id"};
?>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)