Created
November 20, 2021 18:09
-
-
Save clairefro/ba8a10a12254ddd104ca502443604a99 to your computer and use it in GitHub Desktop.
roleassign-bot.js
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
| require("dotenv").config(); | |
| const Discord = require("discord.js"); | |
| const DISCORD_STUDENT_EXPERT_ROLE_ID = | |
| process.env.DISCORD_STUDENT_EXPERT_ROLE_ID; | |
| const DISCORD_STUDENT_LEADER_ROLE_ID = | |
| process.env.DISCORD_STUDENT_LEADER_ROLE_ID; | |
| if ( | |
| !process.env.DISCORD_BOT_TOKEN || | |
| !DISCORD_STUDENT_EXPERT_ROLE_ID || | |
| !DISCORD_STUDENT_LEADER_ROLE_ID | |
| ) { | |
| throw new Error("Mising critical env vars, aborting server start."); | |
| } | |
| const bot = new Discord.Client(); | |
| const handleMessage = async (message) => { | |
| // ignore non-text messages | |
| if (message.channel.type != "text") return; | |
| const isHuman = !message.author.bot; | |
| // Listen for bot messages | |
| if (!isHuman && message.content.match(/^!!assign/)) { | |
| const parts = message.content.split(/\s/); | |
| console.log({ request: message.content }); | |
| const userId = parts[1]; | |
| const eligibleRoles = parts[2].split("|"); | |
| const rolesToAssign = []; | |
| eligibleRoles.forEach((r) => { | |
| if (r === "Postman-Student-Expert") { | |
| rolesToAssign.push(DISCORD_STUDENT_EXPERT_ROLE_ID); | |
| } else if (r === "Postman-Student-Leader") { | |
| rolesToAssign.push(DISCORD_STUDENT_LEADER_ROLE_ID); | |
| } else { | |
| console.warn(`Role with name ${r} not found`); | |
| } | |
| }); | |
| // fetch user by id | |
| let user; | |
| try { | |
| user = await message.guild.members.fetch(userId); | |
| } catch (e) { | |
| // user not found - abort silently | |
| console.error(`User with ID: ${userId} not found.`); | |
| return; | |
| } | |
| // message user | |
| if (rolesToAssign.length) { | |
| user.roles.add(rolesToAssign); | |
| const roleLen = rolesToAssign.length; | |
| const isPlural = roleLen > 1; | |
| const congratsMsg = `🎉 Congratulations! You've been granted ${ | |
| isPlural ? roleLen + " new roles" : "a new role" | |
| } in the XYZ community server. Click your name from the member list in the server to see!`; | |
| user.send(congratsMsg); | |
| } else { | |
| user.send( | |
| `Uh oh, something went wrong with our server when attempting to assign your role.` | |
| ); | |
| } | |
| } | |
| }; | |
| // add message listener | |
| bot.on("message", handleMessage); | |
| try { | |
| bot.login(process.env.DISCORD_BOT_TOKEN); | |
| console.error("Bot started. Listening for requests..."); | |
| } catch (e) { | |
| console.error("Error: Bot login failed. ", e); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment