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 CLI-focused PHP wrapper for Discord’s REST, Gateway, and Voice APIs. Build bots with event-driven ReactPHP support, with community framework integrations like Laracord for Laravel. Docs and class reference available online.

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. Configure Laravel Service Provider (if using laracord): Add to config/app.php under providers:

    Laracord\LaracordServiceProvider::class,
    

    Publish the config:

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

    Update .env with your bot token:

    DISCORD_BOT_TOKEN=your_bot_token_here
    
  2. First Use Case: Basic Bot Command Create a command handler in app/Console/Commands/DiscordBot.php:

    <?php
    namespace App\Console\Commands;
    
    use Discord\Discord;
    use Discord\Parts\Channel\Message;
    use Discord\WebSockets\Intents;
    use Laracord\Laracord;
    use Illuminate\Console\Command;
    
    class DiscordBot extends Command
    {
        protected $signature = 'discord:bot';
        protected $description = 'Run the Discord bot';
    
        public function handle(Laracord $laracord)
        {
            $discord = $laracord->makeDiscord([
                'token' => config('discord.bot_token'),
                'intents' => Intents::getDefaultIntents()
            ]);
    
            $discord->on('ready', function (Discord $discord) {
                $this->info('Bot is ready!');
            });
    
            $discord->on('messageCreate', function (Message $message) {
                if ($message->content === '!ping') {
                    $message->channel->sendMessage('Pong!');
                }
            });
    
            $discord->run();
        }
    }
    

    Run the bot:

    php artisan discord:bot
    

Implementation Patterns

1. Event-Driven Workflows

  • Pattern: Use Laravel's event system to bridge Discord events with Laravel logic.
  • Example: Dispatch a Laravel event when a Discord message arrives:
    $discord->on('messageCreate', function (Message $message) {
        event(new DiscordMessageReceived($message));
    });
    
  • Listener: Create a listener in app/Listeners/DiscordMessageListener.php:
    public function handle(DiscordMessageReceived $event)
    {
        if ($event->message->content === '!data') {
            $event->message->channel->sendMessage(
                json_encode(['status' => 'ok', 'data' => User::all()->toArray()])
            );
        }
    }
    

2. Command Handling with Laravel Routes

  • Pattern: Use Laravel's route model binding to handle slash commands.
  • Example: Register a slash command route in routes/web.php:
    Route::discordCommand('greet', [GreetCommand::class, 'handle']);
    
  • Command Class: Create app/Http/Controllers/GreetCommand.php:
    public function handle(Discord\Parts\Interactions\CommandInteraction $interaction)
    {
        return $interaction->createResponse('Hello, ' . $interaction->member->username);
    }
    

3. Database Integration

  • Pattern: Sync Discord data with Laravel models.
  • Example: Store guilds in a database:
    $discord->on('guildCreate', function ($guild) {
        Guild::updateOrCreate(
            ['discord_id' => $guild->id],
            ['name' => $guild->name, 'owner_id' => $guild->ownerId]
        );
    });
    

4. Voice Channel Integration

  • Pattern: Use discord-php-voice for voice interactions.
  • Example: Join a voice channel when a command is issued:
    $discord->on('messageCreate', function (Message $message) {
        if ($message->content === '!join') {
            $voice = $discord->voice;
            $voice->join($message->guild->voiceChannel);
        }
    });
    

5. Configuration Management

  • Pattern: Centralize Discord bot settings in Laravel config.
  • Example: Define intents in config/discord.php:
    return [
        'intents' => [
            'default' => Intents::GUILDS | Intents::GUILD_MESSAGES,
            'voice' => Intents::GUILDS | Intents::GUILD_VOICE_STATES,
        ],
    ];
    
  • Usage:
    $discord = $laracord->makeDiscord([
        'token' => config('discord.bot_token'),
        'intents' => config('discord.intents.default'),
    ]);
    

6. Rate Limiting and Cooldowns

  • Pattern: Use Laravel's throttle middleware for commands.
  • Example: Apply a 5-second cooldown to a command:
    $discord->on('messageCreate', function (Message $message) {
        if ($message->content === '!throttled') {
            if ($message->author->can('throttled')) {
                $message->channel->sendMessage('Action performed!');
            } else {
                $message->channel->sendMessage('Too many requests. Try again later.');
            }
        }
    });
    
  • Laravel Throttle: Extend Discord\Parts\User\User to include throttle logic.

Gotchas and Tips

1. CLI-Only Limitation

  • Gotcha: DiscordPHP must run in CLI. Avoid running it in web requests.
  • Tip: Use Laravel's Artisan::queueCommand() to run the bot in the background:
    Artisan::queueCommand('discord:bot');
    

2. Memory Management

  • Gotcha: PHP memory limits may cause crashes with large guilds.
  • Tip: Increase memory limit in your bot script:
    ini_set('memory_limit', '-1');
    
  • Advanced: Use Laravel's queue system to process events asynchronously:
    $discord->on('messageCreate', function (Message $message) {
        dispatch(new ProcessDiscordMessage($message))->onQueue('discord');
    });
    

3. Intents and Privileged Access

  • Gotcha: Some intents (e.g., MESSAGE_CONTENT) require privileged access.
  • Tip: Enable intents in the Discord Developer Portal first.
  • Example: Enable GUILD_MEMBERS intent:
    $discord = $laracord->makeDiscord([
        'token' => config('discord.bot_token'),
        'intents' => Intents::GUILDS | Intents::GUILD_MEMBERS,
    ]);
    

4. Event Loop and Promises

  • Gotcha: DiscordPHP uses an event loop and Promises. Blocking operations (e.g., database queries) can freeze the bot.
  • Tip: Use async/await or Laravel's queue system:
    $discord->on('messageCreate', function (Message $message) {
        \Discord\Promises\promise(function () use ($message) {
            return User::where('discord_id', $message->author->id)->first();
        })->then(function ($user) use ($message) {
            $message->channel->sendMessage("Hello, {$user->name}!");
        });
    });
    

5. Windows SSL Issues

  • Gotcha: PHP on Windows may fail due to missing CA certificates.
  • Tip: Download caextract.crt from cURL's site and set openssl.cafile in php.ini.

6. Rate Limits and Retries

  • Gotcha: Discord API has rate limits. Unhandled errors may crash your bot.
  • Tip: Implement retry logic with Laravel's retry helper:
    try {
        retry(3, function () use ($message) {
            $message->channel->sendMessage('Hello!');
        });
    } catch (\Exception $e) {
        $message->channel->sendMessage('Failed to send message.');
    }
    

7. Laravel Service Container Integration

  • Tip: Bind DiscordPHP components to Laravel's container for easier dependency injection:
    $this->app->bind(Discord::class, function ($app) {
        return $app->make(Laracord::class)->makeDiscord([
            'token' => config('discord.bot_token'),
            'intents' => config('discord.intents.default'),
    
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata