Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Discord Php Laravel Package

team-reflex/discord-php

DiscordPHP is a PHP wrapper for Discord’s REST, gateway, and voice APIs. Build Discord bots that run in CLI with ReactPHP-style async handling. Includes limited docs/class reference and community integrations like Laracord for Laravel.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup in Laravel
1. **Install via Composer** (preferably with `laracord/laracord` for Laravel integration):
   ```bash
   composer require team-reflex/discord-php laracord/laracord
  1. Register the Service Provider (if using laracord/laracord): Add to config/app.php under providers:

    Laracord\LaracordServiceProvider::class,
    
  2. Configure the Bot (publish config):

    php artisan vendor:publish --provider="Laracord\LaracordServiceProvider" --tag="config"
    

    Edit .env with your bot token and intents:

    DISCORD_BOT_TOKEN=your_bot_token_here
    DISCORD_INTENTS=GUILDS|GUILD_MESSAGES
    
  3. First Event Listener (in a Laravel command or service):

    use Discord\Discord;
    use Discord\Parts\Channel\Message;
    use Discord\WebSockets\Event;
    
    public function handle(Discord $discord)
    {
        $discord->on(Event::MESSAGE_CREATE, function (Message $message) {
            if ($message->content === '!ping') {
                $message->channel->sendMessage('Pong!');
            }
        });
        $discord->run();
    }
    
  4. Run the Bot (via Artisan command):

    php artisan discord:run
    

Implementation Patterns

1. Laravel Service Container Integration

Leverage laracord/laracord to bind DiscordPHP to Laravel’s container:

// In a service provider or boot method
$this->app->singleton(Discord::class, function ($app) {
    return new Discord([
        'token' => config('discord.bot_token'),
        'intents' => Intents::fromString(config('discord.intents')),
    ]);
});

2. Event-Driven Workflows

Use Laravel’s event system to decouple Discord events from business logic:

// Dispatch a Laravel event when a Discord event fires
$discord->on(Event::MESSAGE_CREATE, function (Message $message) {
    event(new DiscordMessageReceived($message));
});

// Handle in a Laravel listener
public function handle(DiscordMessageReceived $event)
{
    if ($event->message->content === '!help') {
        $event->message->channel->sendMessage('Help content...');
    }
}

3. Command-Line Artisan Commands

Wrap DiscordPHP in an Artisan command for CLI execution:

use Illuminate\Console\Command;
use Discord\Discord;

class RunDiscordBot extends Command
{
    protected $signature = 'discord:run';
    protected $description = 'Run the Discord bot';

    public function handle(Discord $discord)
    {
        $discord->run();
    }
}

4. Message Builder Patterns

Reuse MessageBuilder for consistent message formatting:

protected function buildHelpMessage(): MessageBuilder
{
    return MessageBuilder::new()
        ->setContent('Available commands:')
        ->addEmbed((new Embed())
            ->setTitle('Help')
            ->setDescription('List of commands...')
        );
}

// Usage in event handler
$message->channel->sendMessage($this->buildHelpMessage());

5. Repository Caching

Cache frequent API calls using Laravel’s cache:

use Discord\Parts\User;
use Illuminate\Support\Facades\Cache;

public function getUser(string $userId): ?User
{
    return Cache::remember("discord.user.{$userId}", now()->addHours(1), function () use ($userId) {
        return $this->discord->getUser($userId);
    });
}

6. Voice Integration

For voice support, integrate discord-php/DiscordPHP-Voice:

use Discord\Voice\VoiceClient;

$voice = new VoiceClient($discord, $guild->id);
$voice->connect($channel->id);

Gotchas and Tips

1. CLI-Only Runtime

  • Pitfall: Attempting to run DiscordPHP in a web context (e.g., routes, middleware).
    • Fix: Use ReactPHP integration for webhooks or wrap in a CLI command.
    • Tip: For webhook endpoints, use ReactPHP directly:
      $loop = React\EventLoop\Factory::create();
      $server = new React\Http\Server($loop);
      $server->on('request', [$this, 'handleWebhook']);
      $loop->run();
      

2. Intents and Permissions

  • Pitfall: Missing required intents (e.g., MESSAGE_CONTENT for reading message content).
    • Fix: Enable intents in Discord Developer Portal and in code:
      $discord = new Discord([
          'token' => '...',
          'intents' => Intents::getDefaultIntents() | Intents::MESSAGE_CONTENT,
      ]);
      
    • Tip: Use Intents::fromString() for config-based intents:
      $intents = Intents::fromString(config('discord.intents'));
      

3. Memory Management

  • Pitfall: High memory usage in long-running bots.
    • Fix: Limit cache size or use ini_set('memory_limit', '-1') cautiously.
    • Tip: Offload heavy processing to queues:
      $discord->on(Event::MESSAGE_CREATE, function (Message $message) {
          dispatch(new ProcessMessage($message))->onQueue('discord');
      });
      

4. Rate Limits

  • Pitfall: Hitting Discord’s rate limits (e.g., 50 messages/second).
    • Fix: Implement exponential backoff:
      use Discord\Exceptions\RateLimitException;
      
      try {
          $message->channel->sendMessage('...');
      } catch (RateLimitException $e) {
          sleep($e->retryAfter);
          retry();
      }
      
    • Tip: Use Laravel’s throttle middleware for API routes interacting with Discord.

5. Type Maps and Polymorphism

  • Pitfall: Incorrectly handling polymorphic Discord objects (e.g., Channel types).
    • Fix: Use type maps provided by DiscordPHP:
      $channel = $message->channel;
      if ($channel->type === Channel::TYPE_GUILD_TEXT) {
          // Handle text channel
      }
      
    • Tip: Extend type maps for custom logic:
      class CustomChannel extends Channel
      {
          public function isVerified(): bool
          {
              return $this->type === Channel::TYPE_GUILD_TEXT && $this->nsfw === false;
          }
      }
      

6. Laravel Queue Integration

  • Tip: Process Discord events asynchronously:
    $discord->on(Event::MESSAGE_CREATE, function (Message $message) {
        ProcessMessageJob::dispatch($message);
    });
    
    Define the job:
    class ProcessMessageJob implements ShouldQueue
    {
        use Dispatchable, InteractsWithQueue, Queueable;
    
        public function handle()
        {
            // Process message...
        }
    }
    

7. Debugging WebSocket Issues

  • Pitfall: WebSocket disconnects or silent failures.
    • Fix: Enable logging and reconnection logic:
      $discord->on('disconnect', function () {
          $this->logger->error('WebSocket disconnected. Reconnecting...');
          $this->discord->reconnect();
      });
      
    • Tip: Use stderr logging for CLI:
      $discord->logger = new \Monolog\Logger('discord', [
          new \Monolog\Handler\StreamHandler('php://stderr', \Monolog\Logger::DEBUG),
      ]);
      

8. Windows SSL Certificate Issue

  • Pitfall: Bot exits immediately on Windows due to missing CA certificates.
    • Fix: Download caextract from cURL and set in php.ini:
      openssl.cafile=C:\path\to\caextract.crt
      

9. Extending MessageBuilder

  • Tip: Create reusable builders for complex messages:
    class HelpMessageBuilder extends MessageBuilder
    {
        public function __construct()
        {
            $this->setContent('Help Menu')
                 ->addEmbed($this->buildHelpEmbed());
        }
    
        protected function buildHelpEmbed(): Embed
        {
            return (new Embed())->setDescription('...');
        }
    }
    

10. Testing Strategies

  • Tip: Use Laravel’s testing tools with a mock Discord client:
    $mockDiscord = Mockery::mock(Discord::class);
    $mockDiscord->shouldReceive
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope