A Guide to Discord Bots

Kicking, Banning, Unbanning

// Usage:
// kick @user, kick user_id
// ban @user, ban user_id
// unban @user, unban user_id

const Discord = require('discord.js');

const client = new Discord.Client();
const token = 'your bot token here';
client.login(token);

client.on('message', message => {
  if (message.channel.type != 'text' || message.author.bot)
    return;

  let command = message.content.split(' ')[0].slice(1);
  let args = message.content.replace('.' + command, '').trim();
  let isMod = message.member.roles.has('moderator_role_id');

  switch (command) {
    case 'kick': {
      if (!isMod)
        return;

      let userID = args.includes('<@!') ? args.replace('<@!', '').replace('>', '')
          : args.includes('<@') ? args.replace('<@', '').replace('<', '') : '';

      if (userID == '') {
        message.reply('Invalid user ID or mention.');
        return;
      }

      message.guild.fetchMember(userID).then(member => {
        member.kick("Kicked by " + message.author.tag).then(m => {
          message.channel.send('👢 Kicked <@' + userID + '>.');
        }).catch(() => {
          console.error;
          message.reply('Could not kick the specified member.');
        });
      };
      break;
    }


    case 'ban': {
      if (!isMod)
        return;

      let userID = args.includes('<@!') ? args.replace('<@!', '').replace('>', '')
          : args.includes('<@') ? args.replace('<@', '').replace('<', '') : '';

      if (userID == '') {
        message.reply('Invalid user ID or mention.');
        return;
      }

      message.guild.fetchMember(userID).then(member => {
        member.kick("Banned by " + message.author.tag).then(m => {
          message.channel.send('🔨 Banned <@' + userID + '>.');
        }).catch(() => {
          console.error;
          message.reply('Could not ban the specified member.');
        });
      };
      break;
    }


    case 'unban': {
      if (!isMod)
        return;

      let userID = args.includes('<@!') ? args.replace('<@!', '').replace('>', '')
          : args.includes('<@') ? args.replace('<@', '').replace('<', '') : '';

      if (userID == '') {
        message.reply('Invalid user ID or mention.');
        return;
      }

      message.guild.fetchBans().then(bans => {
        let member = bans.get(userID);

        if (member == null) {
          message.reply('Cannot find a ban for the given user.');
          return;
        }

        message.guild.unban(member, 'Unbanned by ' + message.author.tag).then(user => {
          message.channel.send('Unbanned <@' + userID + '>.');
        }).catch(() => console.error);
      }).catch(() => console.error);
      break;
    }
  }
});

Member.kick(), Member.ban(), Guild.unban().

results matching ""

    No results matching ""