Integrating GSRoleSync
The bot:
- Listens for new members joining a Discord server.
- Sends a request to the GroupSync API to determine the roles a user should have.
- Updates the user's roles in Discord based on the API response.
- Automatically assigns specific roles like "Verified" and "Adult" if applicable.
Prerequisites
- Node.js installed on your machine.
- Discord bot token.
- GroupSync API credentials.
- Environment variables configured in a
.env
file.
Key Features
- Basic Authorization: The bot authenticates API requests using Basic Auth.
- Dynamic Role Assignment: Roles are added or removed based on API response.
- Special Role Handling: Automatically assigns "Verified" and "Adult" roles if conditions are met.
Code Explanation
Configuration
The bot uses a .env
file for sensitive information. Example:
DISCORD_BOT_TOKEN=your_bot_token_here
GROUPSYNC_USER_EMAIL=your_email@example.com
GROUPSYNC_AUTH_KEY=your_auth_key_here
DISCORD_VERIFIED_ROLE=verified_role_id
DISCORD_ADULT_ROLE=adult_role_id
Discord Client Setup
The bot is initialized using the Client
class from discord.js
:
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
],
});
API Authorization
The bot authenticates API requests using Basic Auth:
function createAuthHeader() {
const credentials = `${enVars.GROUPSYNC_USER_EMAIL}:${enVars.GROUPSYNC_AUTH_KEY}`;
return `Basic ${Buffer.from(credentials).toString('base64')}`;
}
Role Synchronization Logic
The syncUserRoles
function handles role synchronization:
- Sends a POST request to the GroupSync API.
- Parses the API response to determine which roles to add or remove.
- Assigns roles to the user using the Discord.js API.
async function syncUserRoles(discordUserId, guild) {
try {
const response = await axios.post('https://api.groupsync.live/v1/discord/role-sync', {
discordUserId,
discordGuildid: guild.id,
}, {
headers: { 'Authorization': createAuthHeader() },
});
if (response.data.success) {
const member = await guild.members.fetch(discordUserId);
const rolesData = response.data.data.group.roles;
const userData = response.data.data.user;
const addedRoles = [];
const removedRoles = [];
for (const [roleId, hasRole] of Object.entries(rolesData)) {
const role = guild.roles.cache.get(roleId);
if (!role) continue;
if (hasRole) {
await member.roles.add(role);
addedRoles.push(role.name);
} else {
await member.roles.remove(role);
removedRoles.push(role.name);
}
}
const verifiedRole = guild.roles.cache.get(enVars.DISCORD_VERIFIED_ROLE);
if (userData.exists && verifiedRole) {
await member.roles.add(verifiedRole);
addedRoles.push(verifiedRole.name);
}
const adultRole = guild.roles.cache.get(enVars.DISCORD_ADULT_ROLE);
if (userData.vrchatAgeVerified && adultRole) {
await member.roles.add(adultRole);
addedRoles.push(adultRole.name);
}
console.log(`Roles synced for user ${member.user.username}:`);
console.log(`Added roles: ${addedRoles.join(', ') || 'None'}`);
console.log(`Removed roles: ${removedRoles.join(', ') || 'None'}`);
} else {
console.warn(`Role sync failed for user ID ${discordUserId}:`, response.data.message);
}
} catch (error) {
console.error(`Error syncing roles for user ${discordUserId}:`, error.message);
}
}
Event Listener
The bot listens for new members joining and triggers the role sync process:
client.on('guildMemberAdd', async (member) => {
await syncUserRoles(member.user.id, member.guild);
});
Bot Initialization
The bot logs in using the token from the .env
file:
client.once('ready', () => console.log('Bot is online and ready!'));
client.login(enVars.DISCORD_BOT_TOKEN);
Deployment
-
Install dependencies:
npm install discord.js axios dotenv
-
Create a
.env
file with the required variables. -
Run the bot:
node bot.js
Notes
- Ensure the bot has the required permissions to manage roles in Discord.
- Test the bot in a development environment before deploying it to production.
By following this guide, you can set up and understand how the Discord bot synchronizes roles effectively.