W
📎 1 file 4,954 chars
📄
pasted-code-1794177622681.txt
txt 150 lines
▶
# Custom Discord Bot – User-Specific Join Roles

Create a fully functional, production-ready Discord bot using **Node.js, Discord.js v14, and JavaScript**.

## Main Purpose
The bot must allow server owners to configure specific Discord users so that whenever those exact users join the server, they automatically receive a predetermined role.

Unlike ordinary autorole bots, this bot must support **ANY role**, including roles with Administrator, Manage Server, Manage Roles, and other powerful permissions.

## 1. Automatic User-Specific Roles

- Allow the owner to register specific Discord User IDs.
- Assign a custom role to each registered user when they join.
- Support multiple users with different assigned roles.
- Allow multiple users to receive the same role.
- Automatically reassign the role every time the registered user rejoins.
- Do not give these roles to anyone who isn't registered.
- Store all configurations persistently so they survive bot restarts.

## 2. Slash Commands

Create the following slash commands:

**/joinrole add**
- Options: user, role.
- Registers a user and their assigned join role.

**/joinrole remove**
- Options: user.
- Removes their automatic role assignment.

**/joinrole edit**
- Options: user, role.
- Changes the role assigned to a registered user.

**/joinrole list**
- Displays all registered users and their assigned roles.

**/joinrole check**
- Options: user.
- Shows whether the user has an automatic role configured.

**/joinrole test**
- Options: user.
- Checks whether the bot can assign the configured role without actually assigning it.

**/joinrole reload**
- Reloads the saved configuration.

## 3. Administrator Role Support

This is the most important requirement.

The bot must support assigning roles with:
- Administrator
- Manage Server
- Manage Roles
- Manage Channels
- Ban Members
- Kick Members
- Other elevated Discord permissions.

Do not artificially block these roles based on their permissions.

The bot must use Discord's official role hierarchy and permission system. It must have the Manage Roles permission, and its highest role must be above the role it is attempting to assign.

Never attempt to bypass Discord's actual permission or role hierarchy restrictions.

## 4. Security and Access Control

- Only the server owner and explicitly authorized bot managers can configure assignments.
- Add `/joinrole manager add` and `/joinrole manager remove` to manage authorized users.
- Regular members must never be able to change assignments.
- Log every configuration change.
- Log every successful and unsuccessful automatic role assignment.
- Never expose bot tokens or sensitive configuration data.

## 5. Storage

Use SQLite for persistent storage.

Store:
- Discord server ID.
- Discord user ID.
- Assigned role ID.
- Configuration creator.
- Creation timestamp.
- Authorized managers.

Support multiple servers independently.

## 6. Join Event System

When a member joins:
1. Check their Discord User ID against the database.
2. Check whether they have a configured role.
3. Verify the role still exists.
4. Verify the bot has permission and hierarchy access.
5. Assign the role.
6. Log the result.

If the role cannot be assigned, log a clear error instead of crashing.

## 7. Configuration

Include:
- `.env` for the bot token and application ID.
- Configurable logging channel.
- SQLite database.
- Automatic database initialization.
- Clean project structure.
- Error handling.
- Command registration script.

## 8. Additional Features

- `/joinrole enable` – Enables automatic assignments.
- `/joinrole disable` – Disables automatic assignments without deleting configurations.
- `/joinrole info` – Displays bot permissions and role hierarchy status.
- `/joinrole backup` – Exports configurations to JSON.
- `/joinrole restore` – Restores configurations from a backup.

## 9. Appearance

All bot responses should use clean, professional Discord embeds.

Use:
- Dark-themed embeds.
- Green success indicators.
- Red error indicators.
- Blue informational embeds.

Keep responses short and readable.

## 10. Deliverables

Provide:
- Complete working source code.
- All JavaScript files.
- `package.json`.
- `.env.example`.
- Database initialization.
- README with installation instructions.
- Instructions for inviting the bot with the correct permissions.
- Instructions for registering slash commands.
- Instructions for starting the bot.

Do not provide pseudocode, incomplete examples, or placeholder functions. Every command and feature must actually work.

**FINAL REQUIREMENT:** The bot must be capable of automatically assigning a specifically configured user's Administrator role whenever that exact user joins the Discord server, provided Discord's permission and role hierarchy requirements are satisfied.
Kodari AI
KodariNov 8 at 10:41 pm 3
JoinRoleManager
A Discord.js v14 bot that automatically assigns user-specific roles upon member join. Server owners and authorized managers can register Discord users with custom roles via slash commands (/joinrole add, remove, edit, list, check, test, reload). Supports any role including Administrator and elevated permissions, respecting Discord's hierarchy rules. Uses SQLite for persistent multi-server storage, includes enable/disable toggles, info, backup/restore features, and comprehensive logging. Features dark-themed embeds with color-coded success/error/info indicators, secure access control, and full error handling.

Built the user-specific join-role bot with SQLite storage, slash commands, audit logging, and backup and restore.

To start, follow README.md, configure .env, and enable Server Members Intent in the Discord Developer Portal. The bot’s highest role must be above every role it assigns, including Administrator roles.

Kodari can make mistakes. Review important code before using.
Files
.gitignore
bot.js
commands.js
database.js
package.json
README.md
register.js
Code
7 331
bot.js
require('dotenv').config();
const { Client, GatewayIntentBits, PermissionFlagsBits, EmbedBuilder, AttachmentBuilder, MessageFlags } = require('discord.js');
const db = require('./database');

const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers] });
const colors = { success: 0x2ecc71, error: 0xe74c3c, info: 0x3498db };
const embed = (kind, text) => new EmbedBuilder().setColor(colors[kind]).setDescription(text);
const idPattern = /^\d{17,20}$/;

async function audit(guild, text) {
  console.log(`[${guild.id}] ${text}`);
  const channelId = db.settings(guild.id).log_channel_id;
  if (!channelId) return;
  try {
    const channel = await guild.channels.fetch(channelId);
    if (!channel || !channel.isTextBased() || !channel.isSendable()) throw new Error('Channel not found or not sendable');
    await channel.send({ embeds: [embed('info', text.slice(0, 4000))], allowedMentions: { parse: [] } });
  } catch (error) { console.error(`[${guild.id}] Could not send audit log:`, error.message); }
}

async function roleCheck(guild, roleId) {
  const role = await guild.roles.fetch(roleId);
  if (!role) return { error: 'The configured role no longer exists.' };
  const me = await guild.members.fetchMe();
  if (!me.permissions.has(PermissionFlagsBits.ManageRoles)) return { error: 'The bot lacks Manage Roles.' };
  if (role.id === guild.id) return { error: 'The @everyone role cannot be assigned.' };
  if (role.managed) return { error: 'This is an integration-managed role and cannot be assigned by the bot.' };
  if (me.roles.highest.comparePositionTo(role) <= 0) return { error: 'The bot’s highest role must be above the configured role.' };
  return { role };
}

function validateBackup(data, guildId) {
  if (!data || data.version !== 1 || data.guild_id !== guildId || !data.settings || !Array.isArray(data.assignments) || !Array.isArray(data.managers)) throw new Error('Invalid backup or backup belongs to another server.');
  const { enabled, log_channel_id } = data.settings;
  if (![0, 1].includes(enabled) || (log_channel_id !== null && !idPattern.test(log_channel_id))) throw new Error('Invalid backup settings.');
  const users = new Set();
  for (const row of data.assignments) {
    if (!row || !idPattern.test(row.user_id) || !idPattern.test(row.role_id) || !idPattern.test(row.created_by) || typeof row.created_at !== 'string' || !Number.isFinite(Date.parse(row.created_at)) || users.has(row.user_id)) throw new Error('Invalid or duplicate assignment in backup.');
    users.add(row.user_id);
  }
  const managers = new Set();
  for (const user of data.managers) {
    if (typeof user !== 'string' || !idPattern.test(user) || managers.has(user)) throw new Error('Invalid or duplicate manager in backup.');
    managers.add(user);
  }
}

async function readBackup(attachment) {
  const max = 1024 * 1024;
  if (attachment.size > max) throw new Error('Backup exceeds the 1 MB limit.');
  const url = new URL(attachment.url);
  if (url.protocol !== 'https:' || !['cdn.discordapp.com', 'media.discordapp.net'].includes(url.hostname)) throw new Error('Invalid attachment URL.');
  const response = await fetch(url, { redirect: 'error', signal: AbortSignal.timeout(10000) });
  if (!response.ok || !response.body) throw new Error('Could not download the backup.');
  const chunks = [];
  let size = 0;
  for await (const chunk of response.body) {
    size += chunk.length;
    if (size > max) throw new Error('Backup exceeds the 1 MB limit.');
    chunks.push(chunk);
  }
  try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); }
  catch { throw new Error('Backup is not valid JSON.'); }
}

client.once('clientReady', () => {
  console.log(`Logged in as ${client.user.tag}`);
  console.log('KODARI_READY');
});
client.on('error', error => console.error('Discord client error:', error));
client.on('guildMemberAdd', async member => {
  try {
    const assignment = db.get(member.guild.id, member.id);
    if (!assignment || !db.settings(member.guild.id).enabled) return;
    const check = await roleCheck(member.guild, assignment.role_id);
    if (check.error) return await audit(member.guild, `Join assignment failed for user ${member.id}, role ${assignment.role_id}: ${check.error}`);
    await member.roles.add(check.role, 'Configured user-specific join role');
    await audit(member.guild, `Join assignment succeeded: user ${member.id}, role ${assignment.role_id}.`);
  } catch (error) {
    console.error(`Join assignment failed for ${member.id}:`, error);
    await audit(member.guild, `Join assignment failed for user ${member.id}: ${error.message}`).catch(console.error);
  }
});

client.on('interactionCreate', async interaction => {
  if (!interaction.isChatInputCommand() || interaction.commandName !== 'joinrole' || !interaction.inGuild()) return;
  try {
    await interaction.deferReply({ flags: MessageFlags.Ephemeral });
    const guild = interaction.guild;
    const guildId = guild.id;
    const actor = interaction.user.id;
    const owner = actor === guild.ownerId;
    const group = interaction.options.getSubcommandGroup(false);
    const sub = interaction.options.getSubcommand();
    const reply = (kind, text, extra = {}) => interaction.editReply({ embeds: [embed(kind, text)], allowedMentions: { parse: [] }, ...extra });
    if (!owner && !db.isManager(guildId, actor)) return await reply('error', 'Only the server owner and authorized managers can use this command.');
    if (!owner && (group === 'manager' || sub === 'restore')) return await reply('error', 'Only the server owner can manage managers or restore backups.');

    if (group === 'manager') {
      const user = interaction.options.getUser('user', true);
      const changed = sub === 'add' ? db.addManager(guildId, user.id) : db.removeManager(guildId, user.id);
      if (!changed) return await reply('info', sub === 'add' ? 'This user is already a manager.' : 'This user is not a manager.');
      await audit(guild, `Manager ${sub}: user ${user.id}, actor ${actor}.`);
      return await reply('success', `Manager ${sub === 'add' ? 'authorized' : 'removed'}: <@${user.id}>.`);
    }
    if (sub === 'add' || sub === 'edit') {
      const user = interaction.options.getUser('user', true);
      const role = interaction.options.getRole('role', true);
      const existing = db.get(guildId, user.id);
      if (sub === 'add' && existing) return await reply('error', 'This user is already registered. Use `/joinrole edit`.');
      if (sub === 'edit' && !existing) return await reply('error', 'This user is not registered. Use `/joinrole add`.');
      if (role.id === guildId || role.managed) return await reply('error', 'The @everyone role and integration-managed roles cannot be assigned.');
      if (sub === 'add') db.add(guildId, user.id, role.id, actor); else db.edit(guildId, user.id, role.id);
      await audit(guild, `Assignment ${sub}: user ${user.id}, role ${role.id}, actor ${actor}.`);
      const check = await roleCheck(guild, role.id);
      return await reply('success', `Saved <@${user.id}> → <@&${role.id}>.${check.error ? `\nWarning: ${check.error}` : ''}`);
    }
    if (sub === 'remove') {
      const user = interaction.options.getUser('user', true);
      if (!db.remove(guildId, user.id)) return await reply('info', 'This user is not registered.');
      await audit(guild, `Assignment removed: user ${user.id}, actor ${actor}.`);
      return await reply('success', `Removed assignment for <@${user.id}>.`);
    }
    if (sub === 'check' || sub === 'test') {
      const user = interaction.options.getUser('user', true);
      const assignment = db.get(guildId, user.id);
      if (!assignment) return await reply('info', `No assignment for <@${user.id}>.`);
      if (sub === 'check') return await reply('info', `<@${user.id}> → <@&${assignment.role_id}>\nCreated by <@${assignment.created_by}> on ${assignment.created_at}.`);
      const check = await roleCheck(guild, assignment.role_id);
      if (check.error) return await reply('error', check.error);
      return await reply('success', `The bot can assign <@&${assignment.role_id}> to <@${user.id}> when they join.${db.settings(guildId).enabled ? '' : '\nAutomatic assignments are currently disabled.'}`);
    }
    if (sub === 'list') {
      const rows = db.list(guildId);
      if (!rows.length) return await reply('info', 'No assignments configured.');
      const lines = rows.map(row => `<@${row.user_id}> → <@&${row.role_id}>`);
      const pages = [];
      let page = '';
      for (const line of lines) { if (page.length + line.length + 1 > 3800) { pages.push(page); page = ''; } page += `${line}\n`; }
      if (page) pages.push(page);
      const file = pages.length > 1 ? [new AttachmentBuilder(Buffer.from(lines.join('\n')), { name: 'assignments.txt' })] : [];
      return await reply('info', pages[0] + (pages.length > 1 ? `\nShowing ${pages[0].trim().split('\n').length} of ${rows.length}; full list attached.` : ''), { files: file });
    }
    if (sub === 'enable' || sub === 'disable') {
      db.setEnabled(guildId, sub === 'enable');
      await audit(guild, `Automatic assignments ${sub}d by ${actor}.`);
      return await reply('success', `Automatic assignments ${sub === 'enable' ? 'enabled' : 'disabled'}.`);
    }
    if (sub === 'log') {
      const channel = interaction.options.getChannel('channel');
      const old = db.settings(guildId).log_channel_id;
      await audit(guild, `Logging channel changed from ${old || 'none'} to ${channel?.id || 'none'} by ${actor}.`);
      db.setLogChannel(guildId, channel?.id || null);
      if (channel && channel.id !== old) await audit(guild, `Logging channel set by ${actor}.`);
      return await reply('success', channel ? `Logging channel set to <#${channel.id}>. Ensure I can view and send messages there.` : 'Logging channel disabled; events remain in console logs.');
    }
    if (sub === 'reload') {
      db.reload();
      await audit(guild, `Configuration reloaded by ${actor}.`);
      return await reply('success', 'Configuration reloaded. Settings are read directly from SQLite.');
    }
    if (sub === 'info') {
      const me = await guild.members.fetchMe();
      const enabled = db.settings(guildId).enabled;
      return await reply('info', `Automatic assignments: **${enabled ? 'enabled' : 'disabled'}**\nManage Roles: **${me.permissions.has(PermissionFlagsBits.ManageRoles) ? 'yes' : 'no'}**\nHighest bot role: <@&${me.roles.highest.id}> (position ${me.roles.highest.position})\nUse \`/joinrole test\` to check a specific role.`);
    }
    if (sub === 'backup') {
      const data = JSON.stringify(db.backup(guildId), null, 2);
      return await reply('info', 'Server configuration backup:', { files: [new AttachmentBuilder(Buffer.from(data), { name: 'joinrole-backup.json' })] });
    }
    if (sub === 'restore') {
      const data = await readBackup(interaction.options.getAttachment('file', true));
      validateBackup(data, guildId);
      await audit(guild, `Configuration restore initiated by ${actor}.`);
      db.restore(guildId, data);
      await audit(guild, `Configuration restored by ${actor}: ${data.assignments.length} assignments, ${data.managers.length} managers.`);
      return await reply('success', `Restored ${data.assignments.length} assignments and ${data.managers.length} managers.`);
    }
  } catch (error) {
    console.error('Joinrole command failed:', error);
    const payload = { embeds: [embed('error', 'The command failed. Check the bot logs or verify the provided backup and permissions.')], allowedMentions: { parse: [] } };
    try { if (interaction.deferred || interaction.replied) await interaction.editReply(payload); else await interaction.reply({ ...payload, flags: MessageFlags.Ephemeral }); }
    catch (replyError) { console.error('Could not send command error:', replyError); }
  }
});

if (!process.env.DISCORD_TOKEN) {
  console.error('Set DISCORD_TOKEN in .env');
  process.exitCode = 1;
} else {
  client.login(process.env.DISCORD_TOKEN).catch(error => { console.error('Login failed:', error); process.exitCode = 1; });
}