Added moderation commands

This commit is contained in:
ION606
2022-07-09 20:30:31 +03:00
parent 919a7f62dc
commit 373d57de2e
10 changed files with 262 additions and 17 deletions
+137
View File
@@ -0,0 +1,137 @@
//@ts-check
const { log, SEVCODES } = require('../log.js');
const { checkRole } = require('./verify.js');
function kick(guild, user) {
guild.members.kick(user);
}
async function toggle_ban(guild, message, args, ban, reason) {
var user = args[0];
let i = 0;
while (user.indexOf('#') == -1) {
user += args[i];
i++
}
if (ban) {
guild.members.ban(user);
} else {
return new Promise((resolve, reject) => {
message.guild.bans.fetch().then((users) => {
const userObj = users.filter((u) => {
return (`${u.user.username}#${u.user.discriminator}` == user);
}).first();
if (userObj && userObj.user) {
guild.members.unban(userObj.user.id, reason).then(() => {
resolve(userObj.user);
});
} else {
reject("This user is not in the server!");
}
})
});
// //Check if the user is banned or not
// message.guild.invites.fetch().then((invites) => {
// const u = guild.members.cache.get(id);
// u.send(`You have been unbanned from ${guild.name}, you can rejoin using the following link!\nhttps://discord.gg/${invites.first().code}`);
// });
}
}
function toggle_mute(bot, guild, command, message, user, reason, mute) {
const mutedRole = guild.roles.cache.find((role) => role.name.toLowerCase() === 'muted');
const guser = guild.members.cache.get(user.id);
// if there is no `Muted` role, send an error
if (!mutedRole) { return message.channel.send('There is no "muted" role on this server. Please create one then try again'); }
if (mute) {
if (guser.roles.cache.get(mutedRole.id) == undefined) {
guser.roles.add(mutedRole);
log(bot, message, command, user, reason, SEVCODES.low);
} else { message.reply("This user is already muted!"); }
} else {
if (guser.roles.cache.get(mutedRole.id) != undefined) {
guser.roles.remove(mutedRole);
log(bot, message, command, user, reason, SEVCODES.none);
} else { message.reply("This user is not muted!"); }
}
/*
NOTE: use the following function for a "time out" type thing?
setTimeout(() => {
target.roles.remove(mutedRole); // remove the role
}, <time>)
*/
}
function timeOut(bot, user, message, args, command, reason) {
let num = Number(args[1]);
if (!args[1] && !Number.isSafeInteger(num)) { return message.reply(`Please use the following format ${bot.repfix}timeout <user> <amount of time> [*hours* **or** *minutes (default)*]`)}
let ms = num * 60 * 1000;
let timeAsSt = '';
if (args[2] == 'hours') { ms *= 60; timeAsSt = `${args[1]} hours`; }
else { timeAsSt = `${args[2]} minutes`; }
user.timeout(ms, reason);
log(bot, message, command, user, reason, timeAsSt);
}
function moderation_handler(bot, message, args, command) {
const guild = message.guild;
//Verify
if (!checkRole(bot, guild, message.author.id)) { return message.reply('Insufficient Permission!'); }
let mentioned = message.mentions.users.first();
if (mentioned && mentioned.id == message.author.id) { return message.reply(`You can't ${command} yourself!`); }
const reason = args.slice(1).join(' ');
if (message.mentions.members.first() && (message.mentions.members.first().roles.highest.position > message.guild.members.resolve(bot.user).roles.highest.position)) {
return message.reply("I'm not high enough in the role hierarchy to do that!\n_To raise my place, go to **Server Settings -> Roles** then drag me up!_");
}
if (command != 'unban' && !mentioned || !reason) { return message.channel.send(`Please use the following format: _!<command> <user> <reason>`); }
if (command == 'unban' && !args[0] && !reason) { return message.channel.send("Please use the following format: _!unban <user_tag>#<user_discriminator> <reason>\nExample: _!unban John#1122_"); }
// if (command == 'ban' && guild.members.cache.get(mentioned.id).bannable) { message.reply("This user is not bannable!"); } //Broken
// if (command == 'ban' && !message.guild.members.cache.get(mentioned.id)) { message.reply("This user is not in the server"); }
switch (command) {
case 'kick': kick(guild, mentioned);
log(bot, message, command, mentioned, reason, SEVCODES.medium);
break;
case 'ban': toggle_ban(guild, message, mentioned, true, reason);
log(bot, message, command, mentioned, reason, SEVCODES.high);
break;
//Leave the then() catch() thing, it needs to be async
case 'unban': toggle_ban(guild, message, args, false, reason).then((user) => { log(bot, message, command, user, reason, SEVCODES.none)}).catch((note) => { message.reply(note); });
break;
case 'mute': toggle_mute(bot, guild, command, message, mentioned, reason, true);
break;
case 'unmute': toggle_mute(bot, guild, command, message, mentioned, reason, true);
break;
// case 'timeout': timeOut(bot, mentioned, message, args, command, reason);
// shouldIlog = false;
// break;
default: console.log(`ERROR! Moderation Command "${command}" has somehow been used!`);
}
}
module.exports = { moderation_handler }
+43 -2
View File
@@ -15,7 +15,7 @@ async function execute(bot, message, args, command, Discord, mongouri, items, xp
const owner = message.guild.members.cache.get(message.guild.ownerId);
if (message.author.id != message.guild.ownerId) {
return message.reply('Only the server owner can do this!')
return message.reply('Only the server owner can do this!');
}
// @ts-ignore
@@ -37,11 +37,16 @@ async function execute(bot, message, args, command, Discord, mongouri, items, xp
//Chose the appropriate command
command = args[0];
if (command == 'welcome_channel') {
if (!command) {
message.channel.send('Please use the following format _!setup help <welcome, logs>_');
} else if (command == 'welcome_channel') {
if (args.length != 2) { return message.reply('The command format is _!setup welcome_channel <channel name>_'); }
// setWelcomeChannel(dbo, message, args[1]);
const channel = message.guild.channels.cache.find(ch => ch.name === args[1]);
if (!channel) { return message.reply('The specified channel does not exist!'); }
dbo.updateOne({welcomechannel: {$exists: true}}, {$set: {welcomechannel: `${channel.id}`}});
message.reply(`Set ${channel} as the new welcome channel`)
} else if (command == 'welcome_message') {
if (args.length < 2) { return message.reply('The command format is _!setup welcome\\_message_\nUse _{sn}_ to insert the server name, _{un}_ to insert the user name, and _{ut}_ to insert the user tag\nExample: _!setup welcome\\_message Welcome to {sn} Sir {un}#{ut}_'); }
let msg = "";
@@ -51,6 +56,42 @@ async function execute(bot, message, args, command, Discord, mongouri, items, xp
if (msg.length > 30) { return message.reply('Please specify a welcome message under 30 characters!'); }
dbo.updateOne({welcomemessage: {$exists: true}}, {$set: {welcomemessage: msg}})
} else if (command == 'keep_logs') {
if (args.length != 2) { return message.reply('Please specify a parameter\nExample: _!setup keep\\_logs true'); }
let keeplogs = false;
if (args[1] == 'true') { keeplogs = true; }
dbo.updateOne({ _id: 'LOG'}, {$set: {keepLogs: keeplogs}});
message.reply(`Toggled log keeping to ${keeplogs}. Please use _!setup log_channel_ to choose the log channel`);
} else if (command == 'log_channel') {
if (args.length != 2) { return message.reply('Please specify a parameter\nExample: _!setup log\\_channel true_'); }
const channel = message.guild.channels.cache.find(ch => ch.name === args[1]);
if (!channel) { return message.reply('The specified channel does not exist!'); }
dbo.updateOne({_id: 'LOG'}, {$set: {logchannel: `${channel.id}`}});
message.reply(`Made ${channel} the new Selmer Bot Logs channel!`);
} else if (command == 'log_severity') {
const tier = args[1];
const l = ['none', 'low', 'medium', 'high'];
if (!l.includes(tier)) { return message.reply("Please select an existing tier ('none', 'low', 'medium', 'high')"); }
dbo.updateOne({_id: 'LOG'}, {$set: {severity: tier}})
}
else if (command == 'help') {
let temp;
if (args[1] == 'welcome') {
temp = 'Use _!setup welcome\\_channel [channel name]_ to set the welcome channel and _!setup welcome\\_message [message]_ to set a welcome message!\n';
} else if (args[1] == 'logs') {
temp = 'To enable logging, use the command _!setup keep\\_logs true_ and _!setup log\\_channel_ to set up the logging channel!\n';
temp += 'Use _!setup keep\\_logs false_ to disable logging and _!setup log\\_severity [none, low, medium, high]_ to set the threshold\n';
temp += '__Severities:__\n*none* - unmute, unban\n*low* - mute\n*medium* - kick\n*high* - ban\nEvery tier also includes all notifs for ***higher*** tiers (AKA _!setup log\\_severity none_ will log everything from every severity)\n';
} else { temp = 'Please use the following format: _!setup help [welcome, logs]_\nExample: _!setup help welcome_'; }
message.reply(temp);
}
});
+7 -4
View File
@@ -1,6 +1,9 @@
function checkRole(message, args) {
let role = args[0];
if (message.member.hasPermission('ADMINISTRATOR')) { return true; }
function checkRole(bot, guild, userId) {
const role = guild.roles.cache.find((role) => { return (role.name == 'Selmer Bot Commands'); })
const user = guild.members.cache.get(userId);
return (user.roles.cache.get(role.id) || user.id == guild.ownerId || bot.inDebugMode);
/*Maybe implement this later, useless for now
const client = new MongoClient(mongouri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
@@ -20,4 +23,4 @@ function checkRole(message, args) {
module.exports = {name: 'verify', checkRole}
module.exports = { checkRole }
+2 -2
View File
@@ -33,7 +33,7 @@ function isNum(arg) {
function CreateNewCollection(message, client, server, id, opponent = null, game = null) {
client.connect(err => {
const db = client.db(String(server) + "[ECON]");
const db = client.db(String(server));
const dbo = db.collection(id);
if (err) { return console.log(err); }
db.listCollections({name: id})
@@ -312,7 +312,7 @@ module.exports = {
CreateNewCollection(message, client, server, id);
client.connect(err => {
const db = client.db(String(server) + "[ECON]");
const db = client.db(String(server));
const dbo = db.collection(id);
if (err) { return console.log(err); }
+2 -2
View File
@@ -190,7 +190,7 @@ function in_game_redirector(bot, interaction, threadname, doc, client, mongouri,
let turn = doc.turn;
const user1 = doc[turn];
const user2 = doc[Number(!turn)];
const db = client.db(interaction.guildId + "[ECON]");
const db = client.db(interaction.guildId);
const dbo = db.collection(user1);
const other = db.collection(user2);
const thread = interaction.channel;
@@ -241,7 +241,7 @@ module.exports ={
//#endregion
client.connect(err => {
const db = client.db(String(server) + "[ECON]");
const db = client.db(String(server));
const dbo = db.collection(id);
if (err) { return console.log(err); }
+2 -2
View File
@@ -19,7 +19,7 @@ async function handle_interaction(interaction, mongouri, turnManager, bot, STATE
const id = result[0];
const doc = result[1];
const threadname = doc.thread;
const dbo = client.db(interaction.guildId + '[ECON]').collection(id);
const dbo = client.db(interaction.guildId).collection(id);
dbo.find({ 'state': {$exists: true} }).toArray(async function (err, docs) {
if (interaction.user.id == id) {
@@ -78,7 +78,7 @@ async function handle_interaction(interaction, mongouri, turnManager, bot, STATE
current_user.then(function(result) {
const doc = result[1];
const threadname = doc.thread;
const dbo = client.db(interaction.guildId + '[ECON]').collection(id);
const dbo = client.db(interaction.guildId).collection(id);
dbo.find({ 'state': {$exists: true} }).toArray(async function (err, docs) {
if (interaction.user.id == id) {
+47
View File
@@ -0,0 +1,47 @@
const { MongoClient, ServerApiVersion } = require('mongodb');
const Discord = require('discord.js');
const SEVCODES = {
none: 0,
low: 1,
medium: 2,
high: 3
}
const col_list = {0: '0ed300', 1: 'f6ff00', 2: 'ffa100', 3: 'FF0000'}
/**
*
* @param {*} bot
* @param {*} message the message the mod sent (AKA a DISCORD MESSAGE OBJECT)
*/
function log(bot, message, command, mentioned, reason, severity) {
const client = new MongoClient(bot.mongouri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
client.connect(err => {
if (err) { return console.log(err); }
client.db(message.guild.id).collection('SETUP').findOne({_id: 'LOG'}).then((doc) => {
if (!doc) { return message.channel.send("Server logs not set up yet!"); }
const channel = message.guild.channels.cache.get(doc.logchannel);
//Check severity threshold
if (SEVCODES[doc.severity] < severity) { return; }
let action;
if (command.endsWith('e')) { action = (command + 'd'); }
else if (command.endsWith('n')) { action = (command + 'ned'); }
else { action = (command + 'ed'); }
const newEmbed = new Discord.MessageEmbed()
.setColor(col_list[severity])
.setTitle(`User ${mentioned.username}#${mentioned.discriminator} has been ${action}`)
//.setURL('https://discordjs.guide/popular-topics/embeds.html#embed-preview')
.setDescription(`Reason: ${reason}\n Responsible Mod: ${message.author.username}#${message.author.discriminator}`)
.setThumbnail(mentioned.displayAvatarURL())
.setTimestamp();
channel.send({ embeds: [newEmbed] });
});
});
}
module.exports = { log, SEVCODES }
+4
View File
@@ -38,6 +38,10 @@ module.exports ={
}
});
//Uses a different format, only the server owner can use it
temp += '_setup_ - ***SERVER OWNER ONLY*** - use _!setup help_\n';
temp += `\n_(remember to use '${bot.prefix}' before the command!)_`;
message.channel.send(temp);
}
+1 -1
View File
@@ -56,7 +56,7 @@ function changeTurn(client, bot, interaction) {
}
const other_dbo = client.db(interaction.member.guild.id + '[ECON]').collection(id);
const other_dbo = client.db(interaction.member.guild.id).collection(id);
other_dbo.find({'state': {$exists: true}}).toArray((err, docs) => {
//If the person was prone, skip their turn
+17 -4
View File
@@ -1,3 +1,4 @@
//#region imports
const { Client, Intents, MessageActionRow, MessageButton, MessageSelectMenu } = require('discord.js');
const Discord = require('discord.js');
const { MongoClient, ServerApiVersion } = require('mongodb');
@@ -11,7 +12,10 @@ const { welcome } = require('./commands/admin/welcome.js');
const { handle_interaction } = require('./commands/interactionhandler.js');
const { handle_dm } = require('./commands/dm_handler');
const { devCheck } = require('./commands/dev only/devcheck.js');
const { moderation_handler } = require('./commands/admin/moderation.js');
const { exit } = require('process');
//#endregion
const BASE_LVL_XP = 20;
@@ -180,12 +184,15 @@ bot.on('interactionCreate', async interaction => {
//Add the bot to a server setup
bot.on("guildCreate", guild => {
guild.roles.create({ name: 'Selmer Bot Mod' });
if (guild.roles.cache.find((role) => { return (role.name == 'Selmer Bot Commands'); }) == undefined) {
guild.roles.create({ name: 'Selmer Bot Commands' });
}
//const role = guild.roles.cache.find((role) => role.name === 'Selmer Bot Mod'); // member.roles.cache.has('role-id-here');
const server = bot.guilds.cache.get(guild.id);
const owner = server.members.fetch(guild.ownerId).then(function(owner) {
owner.send('Thank you for adding Selmer Bot to your server!\nPlease give people you want to have access to Selmer Bot\'s restricted commands the "_Selmer Bot Mod_" role.');
owner.send('Thank you for adding Selmer Bot to your server!\nPlease give people you want to have access to Selmer Bot\'s restricted commands the "_Selmer Bot Commands_" role.');
owner.send('To help set up Selmer Bot to work better with your server, use _!setup help_ in a channel Selmer Bot is in!');
});
@@ -195,7 +202,7 @@ bot.on("guildCreate", guild => {
if (err) { return console.log(err); }
const dbo = client.db(guild.id).collection('SETUP');
dbo.insertMany([{_id: 'WELCOME', 'welcomechannel': null, 'welcomemessage': null, 'welcomebanner': null}]);
dbo.insertMany([{_id: 'WELCOME', 'welcomechannel': null, 'welcomemessage': null, 'welcomebanner': null}, {_id: 'LOG', 'keepLogs': false, 'logchannel': null, 'severity': 0}]);
});
client.close();
@@ -205,6 +212,7 @@ bot.on("guildCreate", guild => {
//Welcome new members
bot.on('guildMemberAdd', async (member) => {
//Check for impartial data
if(member.partial) await member.fetch();
@@ -253,10 +261,15 @@ bot.on('messageCreate', (message) => {
const args = message.content.slice(prefix.length).split(' ');
const command = args.shift().toLowerCase();
//Log logable commands then execute them
const logable = ['kick', 'ban', 'unban', 'mute', 'unmute', 'timeout'];
if (logable.includes(command)) {
moderation_handler(bot, message, args, command);
}
//Performes the command
//Admin section
if (command == 'reactionrole') { bot.commands.get(command).execute(message, args, Discord, bot); }
else if (command == 'reactionrole') { bot.commands.get(command).execute(message, args, Discord, bot); }
else if(bot.commands.has(command) && command != 'ECON') {
//Database access is required, change the inputs