Skip to content

Instantly share code, notes, and snippets.

@Log1x
Last active April 2, 2024 18:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Log1x/aa0ee5575eafde336586722433e1a22e to your computer and use it in GitHub Desktop.
Save Log1x/aa0ee5575eafde336586722433e1a22e to your computer and use it in GitHub Desktop.
Laracord `/roles` command example
<?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
));
}
}
@codeofpunk
Copy link

Awesome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment