This snippet allows your members to add specific roles to themselves using a prefix command, `!join ROLENAME`. Kindly read the comments in the code to understand what you need to set up. Credits to the [GitHub Repository](https://github.com/AnIdiotsGuide/discordjs-bot-guide/blob/master/understanding/roles.md#get-role-by-name-or-id) for the find() method used here.
// ensure that the bot's role is above the roles on the position in server settings
const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN});
const event = context.params.event;
const command = `!join`;
/*
**Purpose**
- the variable on line 17 is the source of which roles you want to allow the bot to add from
- only specific roles are allowed so that members cannot add a role that has a certain requirement (example, Nitro Booster)
**Setting up**
- write the name of the roles you want to add, following the respective format (example, `A1` || `A2` || `B1` || `B2`)
- visit this site to learn more about OR operators: https://www.techopedia.com/definition/3486/or-operator
*/
const allowedRoles = `you can have me` || `you can have me too`;
if (event.content.startsWith(command)) {
if (event.content.length == 5) {
await lib.discord.channels['@0.2.2'].messages.create({
channel_id: event.channel_id,
content: `❎ Invalid format, you didn't provide a role name. Try again using \`${command} ROLENAME\`.`,
message_reference: {message_id: event.id},
});
} else if (
!event.content.split(' ').slice(1).join(' ').includes(allowedRoles)
) {
await lib.discord.channels['@0.2.2'].messages.create({
channel_id: event.channel_id,
content: `❎ Invalid role name, you didn't provide a valid role name. Try again.`,
message_reference: {message_id: event.id},
});
}
// checks if the role name the member provided in the message matches one of the names in the `allowedRoles` string above
if (event.content.split(' ').slice(1).join(' ').includes(allowedRoles)) {
// getting role data
const roles = await lib.discord.guilds['@0.1.3'].roles.list({
guild_id: event.guild_id,
});
// getting the role's ID by name using the find() method
const role = roles.find(
(roles) => roles.name === event.content.split(' ').slice(1).join(' ')
);
await lib.discord.guilds['@0.1.3'].members.roles.update({
role_id: role.id,
user_id: event.author.id,
guild_id: event.guild_id,
});
await lib.discord.channels['@0.2.2'].messages.create({
channel_id: event.channel_id,
content: `✅ Role **${role.name}** was successfully added to you!`,
message_reference: {message_id: event.id},
});
}
}