plytas/laravel-discord-interactions
Composer 安装命令:
composer require plytas/laravel-discord-interactions
包简介
Laravel (PHP) client that uses Discord HTTP API to create and respond to interactions
README 文档
README
Create rich Discord interactions and respond to them using Laravel. Utilizes Discord HTTP webhooks without the need of a long-running process.
Installation
You can install the package via composer:
composer require plytas/laravel-discord-interactions
You can publish the config file with:
php artisan vendor:publish --tag="discord-interactions-config"
This is the contents of the published config file:
return [ 'application_id' => env('DISCORD_APPLICATION_ID'), 'public_key' => env('DISCORD_PUBLIC_KEY'), 'bot_token' => env('DISCORD_BOT_TOKEN'), 'route' => [ 'path' => env('DISCORD_ROUTE', '/discord'), 'middleware' => [ 'before' => [ //ThrottleRequests::class, ], 'after' => [ ], ], ], ];
Configuration
Create a new discord application at https://discord.com/developers/applications.
Copy the application id and public key from "General information" tab and bot token from "Bot" tab to your .env file.
Interactions endpoint setup
For local development you can use services such as expose or ngrok to expose your local server to the internet.
In your discord application fill in Interactions Endpoint URL under "General information" with the url of your server followed by the path you set in the config file. By default it is /discord.
https://your-server-url.com/discord
When clicking the "Save Changes" button, Discord will send a couple POST request to the provided URL to verify the endpoint. One of them will intentionally contain an invalid signature. The package will automatically respond to these requests appropriately.
If the changes are saved successfully, you are good to go!
Usage
Creating a command
To create a new chat command, create a new class that implements the Plytas\Discord\Contracts\DiscordCommand interface.
use Plytas\Discord\Contracts\DiscordCommand; use Plytas\Discord\Data\DiscordInteraction; use Plytas\Discord\Data\DiscordMessage; use Plytas\Discord\Data\DiscordResponse; class PingCommand implements DiscordCommand { public function description(): string { return 'Replies with pong'; } public function handle(DiscordInteraction $interaction): DiscordResponse { return $interaction->respondWithMessage( DiscordMessage::new() ->setContent('Pong!') ->ephemeral() ); } }
Registering a command
You can register commands using Plytas\Discord\DiscordCommandRegistry::setCommands method. This can be done in the boot() method of a service provider.
use Plytas\Discord\DiscordCommandRegistry; DiscordCommandRegistry::setCommands([ 'ping' => PingCommand::class, // Nested commands 'user' => [ 'role' => [ 'add' => AddRoleCommand::class, 'remove' => RemoveRoleCommand::class, ], ], ]);
And finally call php artisan discord:register-commands to register the commands with Discord. It's recommended to run this command in a deployment script.
Responding to interactions
Your commands will receive a DiscordInteraction object that contains information about the interaction. You can respond to the interaction directly by returning a DiscordResponse object.
DidcordInteraction object contains helper methods to create responses such as respondWithMessage(), updateMessage() and showModal().
You must respond to interactions within 3 seconds. If you fail to do so, Discord will show a generic error message to the user. If you need more time to process the interaction, it is recommended to respond with a message that indicates that the command is still processing.
After processing is done, you can use \Plytas\Discord\Facades\Discord::updateInteractionMessage() in a \Illuminate\Support\Facades\App::terminating() callback to update the message.
use Illuminate\Support\Facades\App; use Plytas\Discord\Contracts\DiscordCommand; use Plytas\Discord\Data\DiscordInteraction; use Plytas\Discord\Data\DiscordMessage; use Plytas\Discord\Data\DiscordResponse; use Plytas\Discord\Facades\Discord; class PingCommand implements DiscordCommand { public function description(): string { return 'Replies with pong'; } public function handle(DiscordInteraction $interaction): DiscordResponse { // Register a terminating callback to update the message after processing is done App::terminating(function () use ($interaction) { // Simulate a long-running process sleep(5); Discord::updateInteractionMessage( interaction: $interaction, message: DiscordMessage::new() ->setContent('Pong!') ->ephemeral() ); }); // Respond with a message that indicates that the command is still processing return $interaction->respondWithMessage( DiscordMessage::new() ->setContent('Calculating...') ->ephemeral() // Only the user who invoked the command can see the message ); } }
Responding to component interactions
You can add components to your messages to allow users to interact with them.
use Plytas\Discord\Components\ActionRow; use Plytas\Discord\Components\Button; use Plytas\Discord\Contracts\DiscordCommand; use Plytas\Discord\Data\DiscordInteraction; use Plytas\Discord\Data\DiscordMessage; use Plytas\Discord\Data\DiscordResponse; use Plytas\Discord\Enums\ButtonStyle; class RockPaperScissorsCommand implements DiscordCommand { public function description(): string { return 'Play rock-paper-scissors'; } public function handle(DiscordInteraction $interaction): DiscordResponse { return $interaction->respondWithMessage( DiscordMessage::new() ->setContent('Select your move') ->addComponent( component: ActionRow::new() ->addComponent( component: Button::new() ->setCustomId('rock') ->setLabel('Rock') ->setEmoji('🪨') ->setStyle(ButtonStyle::Primary) ) ->addComponent( component: Button::new() ->setCustomId('paper') ->setLabel('Paper') ->setEmoji('📄') ->setStyle(ButtonStyle::Primary) ) ->addComponent( component: Button::new() ->setCustomId('scissors') ->setLabel('Scissors') ->setEmoji('✂️') ->setStyle(ButtonStyle::Primary) ) ) ->ephemeral() // Only the user who invoked the command can see the message ); } }
You can respond to component interactions by creating a new class that implements the \Plytas\Discord\Contracts\DiscordComponentHandler interface.
use Illuminate\Support\Arr; use Plytas\Discord\Contracts\DiscordComponentHandler; use Plytas\Discord\Data\DiscordInteraction; use Plytas\Discord\Data\DiscordMessage; use Plytas\Discord\Data\DiscordResponse; class RockPaperScissorsComponentHandler implements DiscordComponentHandler { public function handle(DiscordInteraction $interaction): DiscordResponse { $playerSelection = $interaction->getMessageComponent()->custom_id; $botSelection = Arr::random(['rock', 'paper', 'scissors']); if ($playerSelection === $botSelection) { $message = 'It\'s a tie!'; } $winningMoves = [ 'rock' => 'scissors', 'paper' => 'rock', 'scissors' => 'paper', ]; if ($winningMoves[$playerSelection] === $botSelection) { $message = 'You win!'; } else { $message = 'You lose!'; } return $interaction->updateMessage( DiscordMessage::new() ->setContent($message) ->ephemeral() ); } }
Registering component handlers
You can register component handlers using Plytas\Discord\DiscordComponentRegistry::setComponentHandlers() method. This method accepts an array of component_id => DiscordComponentHandler class. This can be done in the boot() method of a service provider.
use Plytas\Discord\DiscordComponentRegistry; DiscordComponentRegistry::setComponentHandlers([ 'rock' => RockPaperScissorsComponentHandler::class, 'paper' => RockPaperScissorsComponentHandler::class, 'scissors' => RockPaperScissorsComponentHandler::class, ]);
If you need more control over the component handler registration process, you can use Plytas\Discord\DiscordComponentRegistry::handleComponentsUsing() method.
This method accepts a closure that receives Plytas\Discord\Data\DiscordInteraction object and expects a Plytas\Discord\Data\DiscordResponse object to be returned.
Imagine that your components have a dynamic custom id that contains the name of the game. You can use the following code to handle the components:
use Illuminate\Support\Str; use Plytas\Discord\Data\DiscordInteraction; use Plytas\Discord\Events\ComponentHandlerRegistered; DiscordComponentRegistry::handleComponentsUsing(function(DiscordInteraction $interaction) { $gameName = Str::afterLast($interaction->getMessageComponent()->custom_id, ':'); return match ($gameName) { 'rock-paper-scissors' => (new RockPaperScissorsComponentHandler)->handle($interaction), 'coin-flip' => (new CoinFlipComponentHandler)->handle($interaction), 'default' => $interaction->updateMessage( DiscordMessage::new() ->setContent('Invalid game') ->ephemeral() ); }; });
Warning
Not all components and API features are supported yet. This package started as a personal project and is still in development. If you need a specific feature, feel free to open an issue or a pull request.
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
License
The MIT License (MIT). Please see License File for more information.
plytas/laravel-discord-interactions 适用场景与选型建议
plytas/laravel-discord-interactions 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 378 次下载、GitHub Stars 达 1, 最近一次更新时间为 2024 年 06 月 14 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「laravel」 「discord」 「interactions」 「laravel-discord-interactions」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 plytas/laravel-discord-interactions 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 plytas/laravel-discord-interactions 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 plytas/laravel-discord-interactions 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Laravel package for interactions.
A simple monolog handler for support Discord webhooks
Send Notification to discord channel Webhook using native FilamentPHP Notification Facade class
A simple package to create tables in Discord messages.
An interaction log for Laravel
统计信息
- 总下载量: 378
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 14
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2024-06-14