From 7a79963c473ae0beb7141790cf5fa86e53c14bb7 Mon Sep 17 00:00:00 2001 From: Miguel N Date: Sun, 27 Dec 2020 22:53:11 +0000 Subject: [PATCH] Assign list of roles to new user on join --- .env.example | 3 +++ src/Bot/init.php | 1 + src/Core/RaspberryBot.php | 28 ++++++++++++++++++++++++++++ 3 files changed, 32 insertions(+) diff --git a/.env.example b/.env.example index 756669a..9d152fd 100644 --- a/.env.example +++ b/.env.example @@ -8,6 +8,9 @@ COMMAND_PREFIX="" # Sign up for an API key at the CatAPI website. Used for commands in the Fun category. CAT_API_KEY="" +# Assign these roles to members on join +JOIN_ROLES="ID1,ID2" + # JSON Web Token Configuration RASPBERRY_STAFF_URL="" RASPBERRY_STAFF_USERNAME="" diff --git a/src/Bot/init.php b/src/Bot/init.php index 6b4c196..b4f6d90 100644 --- a/src/Bot/init.php +++ b/src/Bot/init.php @@ -11,6 +11,7 @@ $dotenv->load(); $dotenv->required('BOT_AUTH_TOKEN')->notEmpty(); $dotenv->required('COMMAND_PREFIX')->notEmpty(); $dotenv->required('CAT_API_KEY')->notEmpty(); +$dotenv->required('JOIN_ROLES')->notEmpty(); define('PROJECT_ROOT', realpath(__DIR__ . '/../../')); diff --git a/src/Core/RaspberryBot.php b/src/Core/RaspberryBot.php index 09508da..412244b 100644 --- a/src/Core/RaspberryBot.php +++ b/src/Core/RaspberryBot.php @@ -2,8 +2,12 @@ namespace nogueiracodes\RaspberryBot\Core; +use Analog\Analog; +use Analog\Handler\Mongo; use Discord\Discord; use Discord\DiscordCommandClient; +use Discord\Parts\User\Member; +use Discord\WebSockets\Event; use Exception; use nogueiracodes\RaspberryBot\Core\Interfaces\Action; use nogueiracodes\RaspberryBot\Core\Interfaces\Command; @@ -127,6 +131,30 @@ class RaspberryBot { $this->commandClient->on('ready', function() { + + $this->commandClient->on(Event::GUILD_MEMBER_ADD, function(Member $member, Discord $discord) { + + Analog::info('Bot: New member ' . $member->username . '#' . $member->discriminator . ' has joined the current guild.'); + + if (isset($_ENV['JOIN_ROLES']) && is_int($_ENV['JOIN_ROLES'])) + { + $roles = explode(',', $_ENV['JOIN_ROLES']); + foreach($roles as $role) + { + // This approach is prone to errors since calling done() passes error responsibility to us, so if an error escapes any of the callbacks, it causes a fatal error + $member->addRole($role)->done(function ($promise) use ($member){ + + Analog::info('Bot: Successfully added role to ' . $member->id); + + }, function($rejectedPromise) use ($member) { + + Analog::error('Bot: Rejected role promise, failed to add role to user ' . $member->id . '. Rejection reason: ' . $rejectedPromise->getMessage()); + + }); + } + } + + }); $this->commandClient->on('message', function($message) {