PHPackages                             mhhidayat/php-discord-client - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. mhhidayat/php-discord-client

ActiveLibrary[API Development](/categories/api)

mhhidayat/php-discord-client
============================

Lightweight PHP client for Discord Webhook and Bot API

v2.0.3(4mo ago)21MITPHPPHP &gt;=8.0

Since Dec 6Pushed 4mo agoCompare

[ Source](https://github.com/mhhidayat/php-discord-client)[ Packagist](https://packagist.org/packages/mhhidayat/php-discord-client)[ RSS](/packages/mhhidayat-php-discord-client/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (2)Versions (10)Used By (0)

PHP Discord Client
==================

[](#php-discord-client)

A comprehensive PHP library for interacting with Discord via both webhooks and bot API. Send messages, rich embeds, and manage Discord communications with an elegant, fluent interface.

Features
--------

[](#features)

- **Webhook Support**: Send messages via Discord webhooks
- **Bot API Support**: Send messages using Discord bot tokens
- **Rich Embeds**: Create beautiful embeds with the fluent builder
- **Flexible Content**: Support for text, embeds, and custom payloads
- **Error Handling**: Comprehensive validation and error reporting
- **Modern PHP**: Built for PHP 8.0+ with type safety and modern features

Requirements
------------

[](#requirements)

- PHP 8.0 or higher
- cURL extension enabled
- Composer

Dependencies
------------

[](#dependencies)

This library includes:

- `vlucas/phpdotenv` for environment variable management (useful for storing tokens and webhook URLs securely)

Installation
------------

[](#installation)

Install via Composer:

```
composer require mhhidayat/php-discord-client
```

Quick Start
-----------

[](#quick-start)

```
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();
```

Basic Usage
-----------

[](#basic-usage)

### Webhook Messages

[](#webhook-messages)

Send messages using Discord webhooks:

```
use Mhhidayat\PhpDiscordClient\DiscordWebhook;

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

### Bot Messages

[](#bot-messages)

Send messages using a Discord bot token:

```
use Mhhidayat\PhpDiscordClient\DiscordBot;

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

### Rich Embeds with Builder

[](#rich-embeds-with-builder)

Use the fluent embed builder for creating rich embeds with both webhooks and bots:

```
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();
```

### Custom Content with Raw Arrays

[](#custom-content-with-raw-arrays)

You can use raw arrays for custom content with both webhooks and bots:

```
// 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();
```

### Customize Username and Avatar

[](#customize-username-and-avatar)

Customize the appearance of your messages (webhooks support username/avatar override, bots use their configured identity):

```
// 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();
```

### Text-to-Speech (TTS)

[](#text-to-speech-tts)

Enable TTS for your messages with both webhooks and bots:

```
// 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();
```

Webhooks vs Bots
----------------

[](#webhooks-vs-bots)

### When to Use Webhooks

[](#when-to-use-webhooks)

Webhooks are perfect for:

- Simple notifications and alerts
- External integrations (CI/CD, monitoring systems)
- One-way communication to Discord
- When you don't need a persistent bot presence
- Quick setup without bot permissions

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

### When to Use Bots

[](#when-to-use-bots)

Bots are ideal for:

- Interactive applications that need to respond to users
- Complex Discord integrations
- When you need advanced Discord features
- Applications requiring persistent presence
- Better rate limiting and API access

```
// 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();
```

### Setup Requirements

[](#setup-requirements)

**Webhooks:**

1. Create a webhook in your Discord server settings
2. Copy the webhook URL
3. Start sending messages immediately

**Bots:**

1. Create a bot application in Discord Developer Portal
2. Generate and copy the bot token
3. Invite the bot to your server with appropriate permissions
4. Get the channel ID where you want to send messages
5. Use the bot token and channel ID in your code

Advanced Usage
--------------

[](#advanced-usage)

### Advanced Embed Fields with Builder

[](#advanced-embed-fields-with-builder)

For more complex field management, you can use the EmbedsFieldsContract:

```
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();
```

### Video Embeds

[](#video-embeds)

Include video content in your embeds:

```
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();
```

### Embed Builder Features

[](#embed-builder-features)

The embed builder provides a fluent interface for creating rich embeds:

```
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();
```

### Available Colors Enum

[](#available-colors-enum)

The library includes a comprehensive Colors enum with Discord's official colors:

```
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
```

### Conditional Sending

[](#conditional-sending)

Send messages only when a condition is met:

```
$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();
    });
```

### Custom Headers

[](#custom-headers)

```
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();
```

### Custom Timeout

[](#custom-timeout)

Default timeout is 15 seconds. You can customize it:

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

### Dynamic Content with Closures

[](#dynamic-content-with-closures)

```
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();
```

### Check Response Status

[](#check-response-status)

```
$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();
}
```

Security Best Practices
-----------------------

[](#security-best-practices)

### Environment Variables

[](#environment-variables)

Store sensitive information like bot tokens and webhook URLs in environment variables:

```
// .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();
```

### Token Security

[](#token-security)

- Never commit tokens or webhook URLs to version control
- Use environment variables or secure configuration management
- Rotate tokens regularly
- Limit bot permissions to only what's needed
- Monitor bot usage and API calls

API Reference
-------------

[](#api-reference)

### Common Methods (Both DiscordWebhook and DiscordBot)

[](#common-methods-both-discordwebhook-and-discordbot)

#### `make(): self`

[](#make-self)

Create a new instance of the Discord client.

#### `text(string $text): self`

[](#textstring-text-self)

Set a simple text message (max 2000 characters).

#### `setContent(array|Closure $content): self`

[](#setcontentarrayclosure-content-self)

Set custom content including embeds. Accepts an array or closure that returns an array.

#### `addEmbeds(Closure $embedsHandler): self`

[](#addembedsclosure-embedshandler-self)

Add rich embeds using the fluent EmbedsContract builder. The closure receives an EmbedsContract instance.

#### `allowTTS(): self`

[](#allowtts-self)

Enable text-to-speech for the message.

#### `send(): self`

[](#send-self)

Send the message to Discord.

#### `sendWhen(bool|Closure $condition): self`

[](#sendwhenboolclosure-condition-self)

Send the message only if the condition is true.

#### `successful(): bool`

[](#successful-bool)

Check if the last request was successful (HTTP 2xx).

#### `failed(): bool`

[](#failed-bool)

Check if the last request failed.

#### `getResponseJson(): string`

[](#getresponsejson-string)

Get the raw JSON response from Discord.

### Webhook-Specific Methods (DiscordWebhook)

[](#webhook-specific-methods-discordwebhook)

#### `setWebhookURL(string $url): self`

[](#setwebhookurlstring-url-self)

Set the Discord webhook URL (required for webhooks).

#### `setUsername(string $username): self`

[](#setusernamestring-username-self)

Override the default webhook username.

#### `setAvatar(string $avatarURL): self`

[](#setavatarstring-avatarurl-self)

Override the default webhook avatar.

### Bot-Specific Methods (DiscordBot)

[](#bot-specific-methods-discordbot)

#### `setBotToken(string $token): self`

[](#setbottokenstring-token-self)

Set the Discord bot token (required for bots).

#### `setChannelID(string $channelID): self`

[](#setchannelidstring-channelid-self)

Set the target channel ID where the bot will send messages (required for bots).

### Static Methods (Both Classes)

[](#static-methods-both-classes)

#### `withHeaders(array $headers): self`

[](#withheadersarray-headers-self)

Create instance with custom HTTP headers.

#### `timeout(int $seconds): self`

[](#timeoutint-seconds-self)

Create instance with custom timeout (default: 15 seconds).

#### `withConfig(array $config): self`

[](#withconfigarray-config-self)

Create instance with configuration array.

### Embed Builder Methods

[](#embed-builder-methods)

The EmbedsContract provides these methods for building rich embeds:

#### `title(string $title): self`

[](#titlestring-title-self)

Set the embed title.

#### `description(string $description): self`

[](#descriptionstring-description-self)

Set the embed description.

#### `url(string $url): self`

[](#urlstring-url-self)

Set the embed URL (makes the title clickable).

#### `color(Colors|int $color): self`

[](#colorcolorsint-color-self)

Set the embed color using the Colors enum or a custom integer.

#### `enableTimestamp(): self`

[](#enabletimestamp-self)

Add the current timestamp to the embed.

#### `authorName(string $authorName): self`

[](#authornamestring-authorname-self)

Set the author name.

#### `authorUrl(string $authorUrl): self`

[](#authorurlstring-authorurl-self)

Set the author URL (makes the author name clickable).

#### `authorIconUrl(string $authorIconUrl): self`

[](#authoriconurlstring-authoriconurl-self)

Set the author icon URL.

#### `footerText(string $footerText): self`

[](#footertextstring-footertext-self)

Set the footer text.

#### `footerIconUrl(string $footerIconUrl): self`

[](#footericonurlstring-footericonurl-self)

Set the footer icon URL.

#### `imageUrl(string $imageUrl): self`

[](#imageurlstring-imageurl-self)

Set the embed image URL (must be HTTPS).

#### `imageWidth(int $width): self`

[](#imagewidthint-width-self)

Set the embed image width in pixels.

#### `imageHeight(int $height): self`

[](#imageheightint-height-self)

Set the embed image height in pixels.

#### `thumbnailUrl(string $thumbnailUrl): self`

[](#thumbnailurlstring-thumbnailurl-self)

Set the embed thumbnail URL.

#### `thumbnailWidth(int $width): self`

[](#thumbnailwidthint-width-self)

Set the embed thumbnail width in pixels.

#### `thumbnailHeight(int $height): self`

[](#thumbnailheightint-height-self)

Set the embed thumbnail height in pixels.

#### `providerName(string $providerName): self`

[](#providernamestring-providername-self)

Set the embed provider name.

#### `providerUrl(string $providerUrl): self`

[](#providerurlstring-providerurl-self)

Set the embed provider URL.

### Embed Fields Builder Methods

[](#embed-fields-builder-methods)

The EmbedsFieldsContract provides these methods for building embed fields:

#### `name(string $name): self`

[](#namestring-name-self)

Set the field name. Must be called before value() and inline().

#### `value(string $value): self`

[](#valuestring-value-self)

Set the field value. Must be called after name().

#### `inline(bool $inline): self`

[](#inlinebool-inline-self)

Set whether the field should be displayed inline. Must be called after name().

#### `build(): array`

[](#build-array)

Build and return the fields array (used internally).

#### `fields(array|Closure $fields): self`

[](#fieldsarrayclosure-fields-self)

Add fields to the embed (max 25 fields). Each field should have 'name', 'value', and optionally 'inline' keys. Accepts either an array or a closure with EmbedsFieldsContract for more control.

#### `videoUrl(string $videoUrl): self`

[](#videourlstring-videourl-self)

Set the embed video URL.

#### `videoWidth(int $width): self`

[](#videowidthint-width-self)

Set the embed video width in pixels.

#### `videoHeight(int $height): self`

[](#videoheightint-height-self)

Set the embed video height in pixels.

Error Handling
--------------

[](#error-handling)

The library throws `DiscordClientException` for validation errors:

```
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();
}
```

Common validation errors:

- Text exceeding 2000 characters
- More than 25 fields in an embed
- Missing webhook URL (for webhooks)
- Missing bot token or channel ID (for bots)
- Missing content (no text or setContent called)
- Image URLs that don't use HTTPS protocol
- Embed title exceeding 256 characters
- Embed description exceeding 4096 characters

Examples
--------

[](#examples)

### Notification System

[](#notification-system)

```
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
```

### Error Logging

[](#error-logging)

```
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();
    }
}
```

### Deployment Notifications

[](#deployment-notifications)

```
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');
```

### Rich Media Embeds

[](#rich-media-embeds)

Showcase images and thumbnails in your embeds:

```
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!'
);
```

### Product Showcase

[](#product-showcase)

Perfect for e-commerce or product announcements:

```
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'
);
```

Troubleshooting
---------------

[](#troubleshooting)

### Common Issues

[](#common-issues)

**"Webhook URL is not set" Error**

```
// ❌ 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();
```

**"No content is set" Error**

```
// ❌ 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();
```

**Bot Messages Not Sending**

- Verify bot token is correct
- Ensure bot has "Send Messages" permission in the target channel
- Check that channel ID is correct
- Confirm bot is added to the server

**Webhook Messages Not Appearing**

- Verify webhook URL is correct and active
- Check webhook hasn't been deleted from Discord
- Ensure webhook has permission to post in the channel

### Debug Response

[](#debug-response)

Check the response from Discord for debugging:

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

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

License
-------

[](#license)

See [LICENSE](./LICENSE.md) for details.

Author
------

[](#author)

mhhidayat -

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance75

Regular maintenance activity

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

9

Last Release

149d ago

Major Versions

v1.1.2 → v2.0.02025-12-14

### Community

Maintainers

![](https://www.gravatar.com/avatar/ab450268cfffa37fc62dfc0e0c3cdfb01e38ff2b9a21e9941494e8ab29b6f14a?d=identicon)[mhhidayat](/maintainers/mhhidayat)

---

Top Contributors

[![mhhidayat](https://avatars.githubusercontent.com/u/111935894?v=4)](https://github.com/mhhidayat "mhhidayat (157 commits)")

---

Tags

composerphp-libraryphp8phpapi clientdiscorddiscord-webhookdiscord-bot

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mhhidayat-php-discord-client/health.svg)

```
[![Health](https://phpackages.com/badges/mhhidayat-php-discord-client/health.svg)](https://phpackages.com/packages/mhhidayat-php-discord-client)
```

###  Alternatives

[phplicengine/bitly

Bitly API v4

22277.3k](/packages/phplicengine-bitly)[fabian-beiner/todoist-php-api-library

A PHP client library that provides a native interface to the official Todoist REST API.

4810.8k](/packages/fabian-beiner-todoist-php-api-library)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
