PHP code example of mhhidayat / php-discord-client

1. Go to this page and download the library: Download mhhidayat/php-discord-client library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mhhidayat / php-discord-client example snippets


use Mhhidayat\PhpDiscordClient\DiscordWebhook;
use Mhhidayat\PhpDiscordClient\DiscordBot;

// Send via webhook (simple setup)
DiscordWebhook::make()
    ->setWebhookURL('https://discord.com/api/webhooks/YOUR_WEBHOOK_URL')
    ->text('Hello from webhook!')
    ->send();

// Send via bot (more features)
DiscordBot::make()
    ->setBotToken('YOUR_BOT_TOKEN')
    ->setChannelID('YOUR_CHANNEL_ID')
    ->text('Hello from bot!')
    ->send();

use Mhhidayat\PhpDiscordClient\DiscordWebhook;

DiscordWebhook::make()
    ->setWebhookURL('https://discord.com/api/webhooks/YOUR_WEBHOOK_URL')
    ->text('Hello, Discord!')
    ->send();

use Mhhidayat\PhpDiscordClient\DiscordBot;

DiscordBot::make()
    ->setBotToken('YOUR_BOT_TOKEN')
    ->setChannelID('YOUR_CHANNEL_ID')
    ->text('Hello from bot!')
    ->send();

use Mhhidayat\PhpDiscordClient\DiscordWebhook;
use Mhhidayat\PhpDiscordClient\DiscordBot;
use Mhhidayat\PhpDiscordClient\Contract\EmbedsContract;
use Mhhidayat\PhpDiscordClient\Enums\Colors;

// Using webhook
DiscordWebhook::make()
    ->setWebhookURL('https://discord.com/api/webhooks/YOUR_WEBHOOK_URL')
    ->text('Check out this embed!')
    ->addEmbeds(function (EmbedsContract $embed) {
        $embed->title('Embed Title')
              ->description('This is an embed description')
              ->color(Colors::Blue)
              ->url('https://example.com')
              ->enableTimestamp()
              ->fields([
                  [
                      'name' => 'Field 1',
                      'value' => 'Value 1',
                      'inline' => true
                  ],
                  [
                      'name' => 'Field 2',
                      'value' => 'Value 2',
                      'inline' => true
                  ]
              ]);
    })
    ->send();

// Using bot (same embed builder interface)
DiscordBot::make()
    ->setBotToken('YOUR_BOT_TOKEN')
    ->setChannelID('YOUR_CHANNEL_ID')
    ->addEmbeds(function (EmbedsContract $embed) {
        $embed->title('Bot Embed')
              ->description('Sent via bot API')
              ->color(Colors::Green);
    })
    ->send();

// Using webhook
DiscordWebhook::make()
    ->setWebhookURL('https://discord.com/api/webhooks/YOUR_WEBHOOK_URL')
    ->setContent([
        'content' => 'Check out this embed!',
        'embeds' => [
            [
                'title' => 'Embed Title',
                'description' => 'This is an embed description',
                'color' => 3447003,
                'fields' => [
                    [
                        'name' => 'Field 1',
                        'value' => 'Value 1',
                        'inline' => true
                    ],
                    [
                        'name' => 'Field 2',
                        'value' => 'Value 2',
                        'inline' => true
                    ]
                ]
            ]
        ]
    ])
    ->send();

// Using bot
DiscordBot::make()
    ->setBotToken('YOUR_BOT_TOKEN')
    ->setChannelID('YOUR_CHANNEL_ID')
    ->setContent([
        'content' => 'Bot message with embed!',
        'embeds' => [
            [
                'title' => 'Bot Embed',
                'description' => 'Sent via Discord Bot API',
                'color' => 5814783
            ]
        ]
    ])
    ->send();

// Webhook with custom appearance
DiscordWebhook::make()
    ->setWebhookURL('https://discord.com/api/webhooks/YOUR_WEBHOOK_URL')
    ->setUsername('Custom Bot Name')
    ->setAvatar('https://example.com/avatar.png')
    ->text('Message with custom appearance')
    ->send();

// Bot messages use the bot's configured username and avatar
DiscordBot::make()
    ->setBotToken('YOUR_BOT_TOKEN')
    ->setChannelID('YOUR_CHANNEL_ID')
    ->text('Message from bot')
    ->send();

// Webhook with TTS
DiscordWebhook::make()
    ->setWebhookURL('https://discord.com/api/webhooks/YOUR_WEBHOOK_URL')
    ->text('This message will be read aloud')
    ->allowTTS()
    ->send();

// Bot with TTS
DiscordBot::make()
    ->setBotToken('YOUR_BOT_TOKEN')
    ->setChannelID('YOUR_CHANNEL_ID')
    ->text('Bot TTS message')
    ->allowTTS()
    ->send();

// Webhook example - great for CI/CD notifications
DiscordWebhook::make()
    ->setWebhookURL($_ENV['DISCORD_WEBHOOK_URL'])
    ->setUsername('Deploy Bot')
    ->text('✅ Deployment to production completed successfully!')
    ->send();

// Bot example - better for interactive features
DiscordBot::make()
    ->setBotToken($_ENV['DISCORD_BOT_TOKEN'])
    ->setChannelID($_ENV['DISCORD_CHANNEL_ID'])
    ->text('🤖 Bot is online and ready to help!')
    ->send();

use Mhhidayat\PhpDiscordClient\DiscordWebhook;
use Mhhidayat\PhpDiscordClient\Contract\EmbedsContract;
use Mhhidayat\PhpDiscordClient\Contract\EmbedsFieldsContract;
use Mhhidayat\PhpDiscordClient\Enums\Colors;

DiscordWebhook::make()
    ->setWebhookURL('https://discord.com/api/webhooks/YOUR_WEBHOOK_URL')
    ->addEmbeds(function (EmbedsContract $embed) {
        $embed->title('Server Statistics')
              ->description('Current server performance metrics')
              ->color(Colors::Blue)
              ->fields(function (EmbedsFieldsContract $fields) {
                  $fields->name('CPU Usage')->value('45%')->inline(true);
                  $fields->name('Memory')->value('2.1GB / 8GB')->inline(true);
                  $fields->name('Disk Space')->value('120GB / 500GB')->inline(true);
                  $fields->name('Network')->value('1.2 Mbps')->inline(true);
                  $fields->name('Uptime')->value('15 days, 4 hours')->inline(true);
                  $fields->name('Status')->value('✅ All systems operational')->inline(false);
              });
    })
    ->send();

DiscordWebhook::make()
    ->setWebhookURL('https://discord.com/api/webhooks/YOUR_WEBHOOK_URL')
    ->addEmbeds(function (EmbedsContract $embed) {
        $embed->title('Tutorial Video')
              ->description('Learn how to use our new feature')
              ->color(Colors::Purple)
              ->videoUrl('https://example.com/tutorial.mp4')
              ->videoWidth(1280)
              ->videoHeight(720)
              ->thumbnailUrl('https://example.com/video-thumbnail.jpg');
    })
    ->send();

use Mhhidayat\PhpDiscordClient\DiscordWebhook;
use Mhhidayat\PhpDiscordClient\Contract\EmbedsContract;
use Mhhidayat\PhpDiscordClient\Enums\Colors;

DiscordWebhook::make()
    ->setWebhookURL('https://discord.com/api/webhooks/YOUR_WEBHOOK_URL')
    ->text('Server Status Update')
    ->setUsername('Status Bot')
    ->setAvatar('https://example.com/bot-avatar.png')
    ->addEmbeds(function (EmbedsContract $embed) {
        $embed->title('System Status')
              ->description('All systems are operational')
              ->color(Colors::Green)
              ->url('https://status.example.com')
              ->enableTimestamp()
              ->authorName('System Monitor')
              ->authorUrl('https://example.com')
              ->authorIconUrl('https://example.com/icon.png')
              ->imageUrl('https://example.com/server-chart.png')
              ->imageWidth(400)
              ->imageHeight(200)
              ->thumbnailUrl('https://example.com/status-icon.png')
              ->thumbnailWidth(80)
              ->thumbnailHeight(80)
              ->footerText('Powered by PHP Discord Client')
              ->footerIconUrl('https://example.com/footer-icon.png')
              ->fields([
                  [
                      'name' => 'CPU Usage',
                      'value' => '45%',
                      'inline' => true
                  ],
                  [
                      'name' => 'Memory',
                      'value' => '2.1GB / 8GB',
                      'inline' => true
                  ],
                  [
                      'name' => 'Uptime',
                      'value' => '15 days',
                      'inline' => true
                  ]
              ]);
    })
    ->send();

use Mhhidayat\PhpDiscordClient\Enums\Colors;

// Discord Embed Colors
Colors::Default
Colors::Aqua
Colors::DarkAqua
Colors::Green
Colors::DarkGreen
Colors::Blue
Colors::DarkBlue
Colors::Purple
Colors::DarkPurple
Colors::LuminousVividPink
Colors::DarkVividPink
Colors::Gold
Colors::DarkGold
Colors::Orange
Colors::DarkOrange
Colors::Red
Colors::DarkRed
Colors::Grey
Colors::DarkGrey
Colors::DarkerGrey
Colors::LightGrey
Colors::Navy
Colors::DarkNavy
Colors::Yellow

// Official Discord Palette
Colors::White
Colors::Greyple
Colors::Black
Colors::DarkButNotBlack
Colors::Blurple
Colors::DiscordYellow
Colors::Fuchsia

// Additional Role Colors
Colors::UnnamedRole1
Colors::UnnamedRole2
Colors::BackgroundBlack

// You can also use custom integer colors
->color(16711680) // Custom red color

$webhook = DiscordWebhook::make()
    ->setWebhookURL('https://discord.com/api/webhooks/YOUR_WEBHOOK_URL')
    ->text('Error occurred!')
    ->sendWhen($errorOccurred); // boolean

// Or with a closure
$webhook = DiscordWebhook::make()
    ->setWebhookURL('https://discord.com/api/webhooks/YOUR_WEBHOOK_URL')
    ->text('Error occurred!')
    ->sendWhen(function() {
        return someCondition();
    });

DiscordWebhook::withHeaders([
    'Content-Type: application/json',
    'User-Agent: MyApp/1.0'
])
    ->setWebhookURL('https://discord.com/api/webhooks/YOUR_WEBHOOK_URL')
    ->text('Message with custom headers')
    ->send();

DiscordWebhook::timeout(30)
    ->setWebhookURL('https://discord.com/api/webhooks/YOUR_WEBHOOK_URL')
    ->text('Message with 30 second timeout')
    ->send();

DiscordWebhook::make()
    ->setWebhookURL('https://discord.com/api/webhooks/YOUR_WEBHOOK_URL')
    ->setContent(function() {
        return [
            'content' => 'Dynamic message at ' . date('Y-m-d H:i:s'),
            'embeds' => [
                [
                    'title' => 'Server Status',
                    'description' => 'All systems operational'
                ]
            ]
        ];
    })
    ->send();

$webhook = DiscordWebhook::make()
    ->setWebhookURL('https://discord.com/api/webhooks/YOUR_WEBHOOK_URL')
    ->text('Test message')
    ->send();

if ($webhook->successful()) {
    echo "Message sent successfully!";
}

if ($webhook->failed()) {
    echo "Failed to send message";
    echo $webhook->getResponseJson();
}

// .env file
DISCORD_BOT_TOKEN=your_bot_token_here
DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/your_webhook_url
DISCORD_CHANNEL_ID=your_channel_id_here

// In your PHP code
use Dotenv\Dotenv;

$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

// Using with webhook
DiscordWebhook::make()
    ->setWebhookURL($_ENV['DISCORD_WEBHOOK_URL'])
    ->text('Secure message!')
    ->send();

// Using with bot
DiscordBot::make()
    ->setBotToken($_ENV['DISCORD_BOT_TOKEN'])
    ->setChannelID($_ENV['DISCORD_CHANNEL_ID'])
    ->text('Secure bot message!')
    ->send();

use Mhhidayat\PhpDiscordClient\DiscordWebhook;
use Mhhidayat\PhpDiscordClient\Exception\DiscordClientException;

try {
    DiscordWebhook::make()
        ->setWebhookURL('https://discord.com/api/webhooks/YOUR_WEBHOOK_URL')
        ->text(str_repeat('a', 2001)) // Too long!
        ->send();
} catch (DiscordClientException $e) {
    echo "Error: " . $e->getMessage();
}

use Mhhidayat\PhpDiscordClient\DiscordWebhook;
use Mhhidayat\PhpDiscordClient\DiscordBot;
use Mhhidayat\PhpDiscordClient\Contract\EmbedsContract;
use Mhhidayat\PhpDiscordClient\Enums\Colors;

function sendNotification($message, $level = 'info', $useBot = false) {
    $colors = [
        'info' => Colors::Blue,
        'success' => Colors::Green,
        'warning' => Colors::Gold,
        'error' => Colors::Red
    ];
    
    $icons = [
        'info' => 'â„šī¸',
        'success' => '✅',
        'warning' => 'âš ī¸',
        'error' => '🚨'
    ];
    
    $client = $useBot 
        ? DiscordBot::make()
            ->setBotToken($_ENV['DISCORD_BOT_TOKEN'])
            ->setChannelID($_ENV['DISCORD_CHANNEL_ID'])
        : DiscordWebhook::make()
            ->setWebhookURL($_ENV['DISCORD_WEBHOOK_URL']);
    
    $client->addEmbeds(function (EmbedsContract $embed) use ($message, $level, $colors, $icons) {
        $embed->title($icons[$level] . ' ' . strtoupper($level))
              ->description($message)
              ->color($colors[$level] ?? Colors::Blue)
              ->enableTimestamp();
    })->send();
}

sendNotification('User registration completed', 'success');
sendNotification('Database backup failed', 'error', true); // Use bot

use Mhhidayat\PhpDiscordClient\DiscordWebhook;
use Mhhidayat\PhpDiscordClient\DiscordBot;
use Mhhidayat\PhpDiscordClient\Contract\EmbedsContract;
use Mhhidayat\PhpDiscordClient\Enums\Colors;

function logError($exception, $useBot = false) {
    if ($useBot) {
        DiscordBot::make()
            ->setBotToken($_ENV['DISCORD_BOT_TOKEN'])
            ->setChannelID($_ENV['DISCORD_ERROR_CHANNEL_ID'])
            ->addEmbeds(function (EmbedsContract $embed) use ($exception) {
                $embed->title('🚨 Error Occurred')
                      ->description('An exception was thrown in the application')
                      ->color(Colors::Red)
                      ->enableTimestamp()
                      ->fields([
                          [
                              'name' => 'Message',
                              'value' => $exception->getMessage(),
                              'inline' => false
                          ],
                          [
                              'name' => 'File',
                              'value' => $exception->getFile(),
                              'inline' => true
                          ],
                          [
                              'name' => 'Line',
                              'value' => (string) $exception->getLine(),
                              'inline' => true
                          ]
                      ])
                      ->footerText('Error Logger v2.0 (Bot)');
            })
            ->send();
    } else {
        DiscordWebhook::make()
            ->setWebhookURL($_ENV['DISCORD_WEBHOOK_URL'])
            ->setUsername('Error Logger')
            ->addEmbeds(function (EmbedsContract $embed) use ($exception) {
                $embed->title('🚨 Error Occurred')
                      ->description('An exception was thrown in the application')
                      ->color(Colors::Red)
                      ->enableTimestamp()
                      ->fields([
                          [
                              'name' => 'Message',
                              'value' => $exception->getMessage(),
                              'inline' => false
                          ],
                          [
                              'name' => 'File',
                              'value' => $exception->getFile(),
                              'inline' => true
                          ],
                          [
                              'name' => 'Line',
                              'value' => (string) $exception->getLine(),
                              'inline' => true
                          ]
                      ])
                      ->footerText('Error Logger v2.0 (Webhook)');
            })
            ->send();
    }
}

use Mhhidayat\PhpDiscordClient\DiscordWebhook;
use Mhhidayat\PhpDiscordClient\Contract\EmbedsContract;
use Mhhidayat\PhpDiscordClient\Enums\Colors;

function notifyDeployment($version, $environment, $author) {
    DiscordWebhook::make()
        ->setWebhookURL($_ENV['DISCORD_WEBHOOK_URL'])
        ->setUsername('Deploy Bot')
        ->addEmbeds(function (EmbedsContract $embed) use ($version, $environment, $author) {
            $embed->title('🚀 New Deployment')
                  ->description("Version $version has been deployed to $environment")
                  ->color(Colors::Blurple)
                  ->enableTimestamp()
                  ->authorName($author)
                  ->fields([
                      [
                          'name' => 'Version',
                          'value' => $version,
                          'inline' => true
                      ],
                      [
                          'name' => 'Environment',
                          'value' => $environment,
                          'inline' => true
                      ]
                  ])
                  ->footerText('Automated Deployment System');
        })
        ->send();
}

notifyDeployment('v2.1.0', 'production', 'John Doe');

use Mhhidayat\PhpDiscordClient\DiscordWebhook;
use Mhhidayat\PhpDiscordClient\Contract\EmbedsContract;
use Mhhidayat\PhpDiscordClient\Enums\Colors;

function shareScreenshot($title, $imageUrl, $description = '') {
    DiscordWebhook::make()
        ->setWebhookURL($_ENV['DISCORD_WEBHOOK_URL'])
        ->setUsername('Screenshot Bot')
        ->addEmbeds(function (EmbedsContract $embed) use ($title, $imageUrl, $description) {
            $embed->title($title)
                  ->description($description)
                  ->color(Colors::Purple)
                  ->imageUrl($imageUrl)
                  ->imageWidth(800)
                  ->imageHeight(600)
                  ->thumbnailUrl('https://example.com/app-icon.png')
                  ->thumbnailWidth(64)
                  ->thumbnailHeight(64)
                  ->enableTimestamp()
                  ->footerText('Shared via Screenshot Bot');
        })
        ->send();
}

shareScreenshot(
    'New Feature Preview', 
    'https://example.com/screenshots/new-feature.png',
    'Here\'s a preview of our upcoming feature!'
);

function showcaseProduct($name, $price, $imageUrl, $description) {
    DiscordWebhook::make()
        ->setWebhookURL($_ENV['DISCORD_WEBHOOK_URL'])
        ->addEmbeds(function (EmbedsContract $embed) use ($name, $price, $imageUrl, $description) {
            $embed->title($name)
                  ->description($description)
                  ->color(Colors::Gold)
                  ->imageUrl($imageUrl)
                  ->imageWidth(500)
                  ->imageHeight(500)
                  ->thumbnailUrl('https://example.com/store-logo.png')
                  ->fields([
                      [
                          'name' => '💰 Price',
                          'value' => $price,
                          'inline' => true
                      ],
                      [
                          'name' => 'đŸ“Ļ Stock',
                          'value' => 'In Stock',
                          'inline' => true
                      ]
                  ])
                  ->enableTimestamp()
                  ->footerText('Online Store');
        })
        ->send();
}

showcaseProduct(
    'Premium Headphones',
    '$299.99',
    'https://example.com/products/headphones.jpg',
    'High-quality wireless headphones with noise cancellation'
);

// ❌ Wrong - missing webhook URL
DiscordWebhook::make()->text('Hello')->send();

// ✅ Correct - set webhook URL first
DiscordWebhook::make()
    ->setWebhookURL('https://discord.com/api/webhooks/YOUR_URL')
    ->text('Hello')
    ->send();

// ❌ Wrong - no content
DiscordWebhook::make()
    ->setWebhookURL('https://discord.com/api/webhooks/YOUR_URL')
    ->send();

// ✅ Correct - add content
DiscordWebhook::make()
    ->setWebhookURL('https://discord.com/api/webhooks/YOUR_URL')
    ->text('Hello World')
    ->send();

$webhook = DiscordWebhook::make()
    ->setWebhookURL('https://discord.com/api/webhooks/YOUR_URL')
    ->text('Test message')
    ->send();

if ($webhook->failed()) {
    echo "Error: " . $webhook->getResponseJson();
}
bash
composer