Skip to content

Commit

Permalink
Merge pull request #747 from ViBotTeam/husky/decoupling/bot-commands
Browse files Browse the repository at this point in the history
Decouple `commands` object from the bot `Client` object
  • Loading branch information
Ragviswa authored Feb 24, 2024
2 parents bd9dbbb + 8aec176 commit 363b31f
Show file tree
Hide file tree
Showing 9 changed files with 63 additions and 63 deletions.
59 changes: 25 additions & 34 deletions botMeta.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,36 @@
const Discord = require('discord.js');
const fs = require('fs');
const { Client, GatewayIntentBits, Partials } = require('discord.js');
const { rateLimitLogger } = require('./lib/rateLimitLogger');
const bot = new Discord.Client({

const bot = new Client({
intents: [ // Discord moment
Discord.GatewayIntentBits.Guilds,
Discord.GatewayIntentBits.GuildMembers,
Discord.GatewayIntentBits.GuildBans,
Discord.GatewayIntentBits.GuildEmojisAndStickers,
Discord.GatewayIntentBits.GuildIntegrations,
Discord.GatewayIntentBits.GuildWebhooks,
Discord.GatewayIntentBits.GuildInvites,
Discord.GatewayIntentBits.GuildVoiceStates,
Discord.GatewayIntentBits.GuildPresences,
Discord.GatewayIntentBits.GuildMessages,
Discord.GatewayIntentBits.GuildMessageReactions,
Discord.GatewayIntentBits.GuildMessageTyping,
Discord.GatewayIntentBits.DirectMessages,
Discord.GatewayIntentBits.DirectMessageReactions,
Discord.GatewayIntentBits.DirectMessageTyping,
Discord.GatewayIntentBits.MessageContent,
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildBans,
GatewayIntentBits.GuildEmojisAndStickers,
GatewayIntentBits.GuildIntegrations,
GatewayIntentBits.GuildWebhooks,
GatewayIntentBits.GuildInvites,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildMessageTyping,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.DirectMessageReactions,
GatewayIntentBits.DirectMessageTyping,
GatewayIntentBits.MessageContent,
],
partials: [
Discord.Partials.User,
Discord.Partials.Channel,
Discord.Partials.GuildMember,
Discord.Partials.Message,
Discord.Partials.Reaction
Partials.User,
Partials.Channel,
Partials.GuildMember,
Partials.Message,
Partials.Reaction
]
});

rateLimitLogger(bot);

bot.commands = new Discord.Collection();
bot.afkChecks = {};
bot.afkModules = {};
bot.settings = moduleIsAvailable('./guildSettings.json') ? require('./guildSettings.json') : {};
Expand All @@ -49,14 +48,6 @@ bot.emojiServers = moduleIsAvailable('./data/emojiServers.json') ? require('./da
bot.devServers = ['739623118833713214'];
bot.storedEmojis = moduleIsAvailable('./data/emojis.json') ? require('./data/emojis.json') : {};

function loadCommands() {
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
bot.commands.set(command.name, command);
}
}

function moduleIsAvailable(path) {
try {
require.resolve(path);
Expand All @@ -67,4 +58,4 @@ function moduleIsAvailable(path) {
}
}

module.exports = { bot, loadCommands };
module.exports = { bot };
3 changes: 2 additions & 1 deletion botSetup.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const redisConnect = require('./redis.js').setup;
const botSettings = require('./settings.json');
const ErrorLogger = require('./lib/logError');
// Commands
const { commands } = require('./lib/commands');
const emoji = require('./commands/emoji.js');
const afkCheck = require('./commands/afkCheck.js');
const vibotChannels = require('./commands/vibotChannels');
Expand All @@ -27,7 +28,7 @@ const dbSetup = require('./dbSetup.js');

async function deployCommands(bot, guild) {
// Organize commands
const slashCommands = bot.commands.filter(c => c.getSlashCommandData).map(c => c.getSlashCommandData(guild)).filter(c => c).flat();
const slashCommands = commands.filter(c => c.getSlashCommandData).map(c => c.getSlashCommandData(guild)).filter(c => c).flat();

// Deploy commands
const rest = new Discord.REST({ version: '10' }).setToken(require('./settings.json').key);
Expand Down
10 changes: 5 additions & 5 deletions commands/commands.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const Discord = require('discord.js');
const ErrorLogger = require('../lib/logError')
const SlashArgType = require('discord-api-types/v10').ApplicationCommandOptionType;

const { commands } = require('../lib/commands');

module.exports = {
name: 'commands',
Expand All @@ -21,9 +21,9 @@ module.exports = {
const override = userOverride(message.author.id, bot);

if (args.length != 0) {
bot.commands.get(args[0].toLowerCase())
let command = bot.commands.get(args[0].toLowerCase())
if (!command) bot.commands.each(c => {
commands.get(args[0].toLowerCase())
let command = commands.get(args[0].toLowerCase())
if (!command) commands.each(c => {
if (c.alias) {
if (c.alias.includes(args[0].toLowerCase())) {
command = c
Expand Down Expand Up @@ -76,7 +76,7 @@ module.exports = {
if (!role) continue;
if (message.member.roles.highest.position < role.position && !override) continue;
if (!fields[role.name]) fields[role.name] = { position: role.position, commands: [] };
bot.commands.each(command => {
commands.each(command => {
/*if (c.roleOverride && c.roleOverride[message.guildId] && bot.settings[message.guild.id].commands[c.name]) {
if (c.roleOverride[message.guildId] == roleName) fields[role.name].commands.push(';' + c.name);
}
Expand Down
20 changes: 5 additions & 15 deletions commands/reload.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,14 @@
const Discord = require('discord.js');
const ErrorLogger = require('../lib/logError');
const SlashArgType = require('discord-api-types/v10').ApplicationCommandOptionType;
const { slashArg, slashChoices, slashCommandJSON } = require('../utils.js')

const { commands } = require('../lib/commands');
module.exports = {
name: 'reload',
description: 'Reloads a certain command.',
args: '<command>',
guildspecific: true,
role: 'developer',
// args: [slashArg(SlashArgType.String, 'command', {
// required: true,
// description: "Any Command in Vibot"
// }),],
// getSlashCommandData(guild) {
// return slashCommandJSON(this, guild)
// },
async execute(message, args, bot, db) {
if (!bot.adminUsers.includes(message.author.id)) return;
const commandName = args[0].toLowerCase();
const command = bot.commands.get(commandName);
const command = commands.get(commandName);

// Check if command is valid
if (!command) return message.reply(`There is no command with name \`${commandName}\`!`);
Expand All @@ -28,9 +18,9 @@ module.exports = {
delete require.cache[require.resolve(`./${command.name}.js`)];

try {
message.client.commands.delete(command.name);
commands.delete(command.name);
const newCommand = require(`./${command.name}.js`);
message.client.commands.set(newCommand.name, newCommand);
commands.set(newCommand.name, newCommand);
await message.reply(`Command \`${newCommand.name}\` was reloaded!`);
} catch (error) {
console.error(error);
Expand Down
5 changes: 3 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,9 @@ const verification = require('./commands/verification');

// Global Variables/Data
const botSettings = require('./settings.json');
const { bot, loadCommands } = require('./botMeta.js');
loadCommands();
const { bot } = require('./botMeta.js');
require('./lib/commands').load();

const serverWhiteList = require('./data/serverWhiteList.json');
const { MessageManager } = require('./messageManager.js');

Expand Down
15 changes: 15 additions & 0 deletions lib/commands.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const { Collection } = require('discord.js');
const { readdirSync } = require('fs');

const commands = new Collection();

module.exports = {
commands,
load() {
const files = readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of files) {
const command = require(`../commands/${file}`);
commands.set(command.name, command);
}
}
};
8 changes: 5 additions & 3 deletions messageManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ const restarting = require('./commands/restart')
const verification = require('./commands/verification')
const stats = require('./commands/stats')
const modmail = require('./lib/modmail.js')
const { commands } = require('./lib/commands');

const { argString } = require('./commands/commands.js');
const { getDB } = require('./dbSetup.js')
const { LegacyCommandOptions, LegacyParserError } = require('./utils.js')
Expand Down Expand Up @@ -100,7 +102,7 @@ class MessageManager {
}

async handleAutocomplete(interaction) {
const command = this.#bot.commands.get(interaction.commandName) || this.#bot.commands.find(cmd => cmd.alias && cmd.alias.includes(interaction.commandName))
const command = commands.get(interaction.commandName) || commands.find(cmd => cmd.alias && cmd.alias.includes(interaction.commandName))
if (command.autocomplete) command.autocomplete(interaction, this.#bot);
}
/**
Expand Down Expand Up @@ -129,7 +131,7 @@ class MessageManager {
}

// Get the command
const command = this.#bot.commands.get(commandName) || this.#bot.commands.find(cmd => cmd.alias && cmd.alias.includes(commandName))
const command = commands.get(commandName) || commands.find(cmd => cmd.alias && cmd.alias.includes(commandName))

// Handle logging and replying to command errors
async function commandError(userMsg, logMsg) {
Expand Down Expand Up @@ -231,7 +233,7 @@ class MessageManager {
if (message.content.replace(/[^0-9]/g, '') == message.content) return;
const args = message.content.split(/ +/)
const commandName = args.shift().toLowerCase().replace(this.#prefix, '')
const command = this.#bot.commands.get(commandName) || this.#bot.commands.find(c => c.alias && c.alias.includes(commandName))
const command = commands.get(commandName) || commands.find(c => c.alias && c.alias.includes(commandName))
if (!command) this.#sendModMail(message)
else if (command.dms) {
let guild
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "vibot",
"version": "8.16.7",
"version": "8.16.8",
"description": "ViBot",
"main": "index.js",
"dependencies": {
Expand Down
4 changes: 2 additions & 2 deletions redis.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const { createClient } = require('redis');
const { getDB } = require('./dbSetup.js');
const Discord = require('discord.js');
const botSettings = require('./settings.json');

const { commands } = require('./lib/commands');
let client;

/* The MockMessage class is a JavaScript class that represents a message in a webhook interaction and
Expand Down Expand Up @@ -46,7 +46,7 @@ module.exports = {
const data = await client.HGETALL('messagebuttons:' + interaction.message.id);
if (!data.command || !data.callback) return false;
if (data.allowedUser && data.allowedUser != interaction.user.id) return false;
const command = bot.commands.get(data.command) || bot.commands.find(cmd => cmd.alias && cmd.alias.includes(data.command));
const command = commands.get(data.command) || commands.find(cmd => cmd.alias && cmd.alias.includes(data.command));
const callback = command[data.callback];
const db = getDB(interaction.guild.id);
if (data.token) {
Expand Down

0 comments on commit 363b31f

Please sign in to comment.