Last active
April 2, 2024 18:53
-
-
Save Log1x/aa0ee5575eafde336586722433e1a22e to your computer and use it in GitHub Desktop.
Laracord `/roles` command example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\SlashCommands; | |
use Discord\Parts\Interactions\Interaction; | |
use Discord\Parts\User\Member; | |
use Laracord\Commands\SlashCommand; | |
class Roles extends SlashCommand | |
{ | |
/** | |
* The command name. | |
* | |
* @var string | |
*/ | |
protected $name = 'roles'; | |
/** | |
* The command description. | |
* | |
* @var string | |
*/ | |
protected $description = 'Choose your server roles.'; | |
/** | |
* The role options. | |
*/ | |
protected array $roles = [ | |
[ | |
'name' => 'Apple', | |
'id' => 1222190586266783754, | |
'emoji' => 'π', | |
], | |
[ | |
'name' => 'Banana', | |
'id' => 1222190651332886549, | |
'emoji' => 'π', | |
], | |
[ | |
'name' => 'Pear', | |
'id' => 1222190688079450172, | |
'emoji' => 'π', | |
], | |
]; | |
/** | |
* Handle the slash command. | |
* | |
* @param \Discord\Parts\Interactions\Interaction $interaction | |
* @return void | |
*/ | |
public function handle($interaction) | |
{ | |
$interaction->respondWithMessage( | |
$this->build($interaction), | |
ephemeral: true | |
); | |
} | |
/** | |
* Build the role message. | |
*/ | |
protected function build(Interaction $interaction) | |
{ | |
$message = $this->message() | |
->title('Roles') | |
->content('Click a button below to get a role.'); | |
$roles = collect($this->roles) | |
->reject(fn ($role) => $interaction->member->roles->has($role['id'])); | |
if ($roles->isEmpty()) { | |
return $message | |
->content('You have all the available roles.') | |
->error() | |
->build(); | |
} | |
foreach ($roles as $role) { | |
$message->button( | |
$role['name'], | |
fn (Interaction $interaction) => $this->addRole($interaction, $role), | |
emoji: $role['emoji'], | |
style: 'secondary' | |
); | |
} | |
return $message->build(); | |
} | |
/** | |
* Add a role to the member. | |
*/ | |
protected function addRole(Interaction $interaction, array $role) | |
{ | |
if ($interaction->member->roles->has($role['id'])) { | |
return $interaction->respondWithMessage( | |
$this | |
->message("You already have the {$role['emoji']} **{$role['name']}** role.") | |
->error() | |
->build(), | |
ephemeral: true | |
); | |
} | |
return $interaction->member->addRole($role['id']) | |
->then(fn () => $interaction->updateMessage($this->build($interaction))) | |
->then(fn () => $interaction->sendFollowUpMessage( | |
$this | |
->message("You now have the {$role['emoji']} **{$role['name']}** role.") | |
->build(), | |
ephemeral: true | |
)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome!