承接 mhhidayat/php-discord-client 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

mhhidayat/php-discord-client

最新稳定版本:v2.0.3

Composer 安装命令:

composer require mhhidayat/php-discord-client

包简介

Lightweight PHP client for Discord Webhook and Bot API

README 文档

README

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

  • 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

  • PHP 8.0 or higher
  • cURL extension enabled
  • Composer

Dependencies

This library includes:

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

Installation

Install via Composer:

composer require mhhidayat/php-discord-client

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

$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

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

  • 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

Common Methods (Both DiscordWebhook and DiscordBot)

make(): self

Create a new instance of the Discord client.

text(string $text): self

Set a simple text message (max 2000 characters).

setContent(array|Closure $content): self

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

addEmbeds(Closure $embedsHandler): self

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

allowTTS(): self

Enable text-to-speech for the message.

send(): self

Send the message to Discord.

sendWhen(bool|Closure $condition): self

Send the message only if the condition is true.

successful(): bool

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

failed(): bool

Check if the last request failed.

getResponseJson(): string

Get the raw JSON response from Discord.

Webhook-Specific Methods (DiscordWebhook)

setWebhookURL(string $url): self

Set the Discord webhook URL (required for webhooks).

setUsername(string $username): self

Override the default webhook username.

setAvatar(string $avatarURL): self

Override the default webhook avatar.

Bot-Specific Methods (DiscordBot)

setBotToken(string $token): self

Set the Discord bot token (required for bots).

setChannelID(string $channelID): self

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

Static Methods (Both Classes)

withHeaders(array $headers): self

Create instance with custom HTTP headers.

timeout(int $seconds): self

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

withConfig(array $config): self

Create instance with configuration array.

Embed Builder Methods

The EmbedsContract provides these methods for building rich embeds:

title(string $title): self

Set the embed title.

description(string $description): self

Set the embed description.

url(string $url): self

Set the embed URL (makes the title clickable).

color(Colors|int $color): self

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

enableTimestamp(): self

Add the current timestamp to the embed.

authorName(string $authorName): self

Set the author name.

authorUrl(string $authorUrl): self

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

authorIconUrl(string $authorIconUrl): self

Set the author icon URL.

footerText(string $footerText): self

Set the footer text.

footerIconUrl(string $footerIconUrl): self

Set the footer icon URL.

imageUrl(string $imageUrl): self

Set the embed image URL (must be HTTPS).

imageWidth(int $width): self

Set the embed image width in pixels.

imageHeight(int $height): self

Set the embed image height in pixels.

thumbnailUrl(string $thumbnailUrl): self

Set the embed thumbnail URL.

thumbnailWidth(int $width): self

Set the embed thumbnail width in pixels.

thumbnailHeight(int $height): self

Set the embed thumbnail height in pixels.

providerName(string $providerName): self

Set the embed provider name.

providerUrl(string $providerUrl): self

Set the embed provider URL.

Embed Fields Builder Methods

The EmbedsFieldsContract provides these methods for building embed fields:

name(string $name): self

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

value(string $value): self

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

inline(bool $inline): self

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

build(): array

Build and return the fields array (used internally).

fields(array|Closure $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

Set the embed video URL.

videoWidth(int $width): self

Set the embed video width in pixels.

videoHeight(int $height): self

Set the embed video height in pixels.

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

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

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

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

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

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

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

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

See LICENSE for details.

Author

mhhidayat - mhhidayat811@gmail.com

统计信息

  • 总下载量: 1
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 2
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 2
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-12-14