Merge pull request #2 from ProjectLored/PerGuild-Commands

Per guild commands
This commit is contained in:
Guz
2021-09-04 12:25:54 -03:00
committed by GitHub
15 changed files with 2553 additions and 219 deletions

View File

View File

2
.gitignore vendored
View File

@@ -1,3 +1,3 @@
node_modules node_modules
config.json *.env
.vscode .vscode

View File

@@ -1,46 +0,0 @@
const {
MessageActionRow,
MessageButton,
} = require('discord.js');
module.exports = {
name: 'ping',
description: 'Replies with Pong!',
options: [{
name: 'input',
type: 'STRING',
description: 'input arg',
required: true,
}],
permissions: [{
id: '870383205306494997',
type: 'ROLE',
permission: false,
},
{
id: '873349611358670878',
type: 'ROLE',
permission: false,
},
],
async execute(interaction) {
const {
value: input,
} = interaction.options.get('input');
const row = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId('button')
.setLabel('Button')
.setStyle('PRIMARY'),
);
interaction.reply({
content: `Ping ${input}`,
components: [row],
});
// console.log(`Ping! ${interaction.options.get('input').value}`);
},
};

View File

@@ -1,68 +1,140 @@
const { SlashCommandBuilder } = require('@discordjs/builders');
const { Routes } = require('discord-api-types/v9');
const fs = require('fs'); const fs = require('fs');
const { const console = require('../../functions/meta/console');
owner,
} = require('../../index');
module.exports = { module.exports = {
name: 'reload', data: new SlashCommandBuilder()
description: 'Reloads a command or all commands, for development purposes.', .setName('reload')
defaultPermissions: false, .setDescription('Reloads a command')
options: [{ .addStringOption(option =>
name: 'command', option.setName('command')
type: 'STRING', .setDescription('The command name to be reloaded')
description: 'Name of the command to reload.', .setRequired(true)),
required: true, permissions: [
}], {
permissions: [{ id: process.env.OWNER,
id: owner.id, type: 'USER',
type: 'USER', permission: true,
permission: true, },
}], ],
async execute(interaction) { properties: {
const { type: [ 'guild', 'per-guild' ],
clientCommands, },
commands, async execute(interaction, client) {
} = require('../../index');
const commandName = interaction.options.getString('command'); await interaction.deferReply({ ephemeral: true });
if (!(await commands.fetch()).find(command => command.name === commandName)) { const { commands, commandsData, rest } = require('../../index');
return interaction.reply({
content: `No such command \`${commandName}\` found.`, const cmdName = interaction.options.getString('command').toLowerCase();
ephemeral: true,
}); const command = commands.find(c => c.data.name === cmdName);
}
else if (commandName === 'reload') { switch (command?.properties?.folder) {
return interaction.reply({ case 'dev':
content: 'You can\'t reload this command.', interaction.editReply({ content: `You can't reload \`${cmdName}\` because it is a development command.`, ephemeral: true });
ephemeral: true, return;
}); case undefined:
interaction.editReply({ content: `Command \`${cmdName}\` wasn't found.`, ephemeral: true });
return;
} }
const commandFolders = fs.readdirSync('./commands'); const cmdIdx = commands.findIndex(c => c.data.name === cmdName);
const folderName = commandFolders.find(folder => fs.readdirSync(`./commands/${folder}`).includes(`${commandName}.js`)); const dataIdx = commandsData.guild.findIndex(c => c.name === cmdName);
delete require.cache[require.resolve(`../${folderName}/${commandName}.js`)]; const oldCommand = command;
const oldCommandData = await commandsData.guild[dataIdx];
const folder = fs.readdirSync('./commands').find(f => fs.readdirSync(`./commands/${f}`).includes(`${cmdName}.js`));
delete require.cache[require.resolve(`../../commands/${folder}/${cmdName}.js`)];
try { try {
const cmd = require(`../${folderName}/${commandName}.js`);
clientCommands.set(commandName, { console.log(
id: (await commands.fetch()).find(command => command.name === commandName).id, 'Old Command --------------------------------\n', oldCommand,
data: cmd, '\nData:\n', oldCommandData,
}); );
await interaction.reply({ if(oldCommand.permissions) {
content: `Command \`${commandName}\` reload completed.`, console.log('Permissions');
ephemeral: true, console.table(oldCommand.permissions);
}); }
const newCommand = require(`../../commands/${folder}/${cmdName}.js`);
const clientCommand = (await client.guilds.cache.get(process.env.DEV_GUILD)?.commands.fetch()).find(c => c.name === cmdName);
if(!newCommand.properties) newCommand.properties = { folder: folder };
else newCommand.properties.folder = folder;
commands[cmdIdx] = {
data: newCommand.data,
properties: newCommand.properties,
permissions: newCommand.permissions,
execute: newCommand.execute,
id: clientCommand.id,
name: clientCommand.name,
};
if(newCommand.properties.type.includes('guild')) {
commandsData.guild[dataIdx] = newCommand.data.toJSON();
await rest.put(
Routes.applicationGuildCommands(process.env.CLIENT, process.env.DEV_GUILD), {
body: commandsData.guild,
},
);
if(newCommand.permissions) {
await clientCommand.permissions.set({ id: clientCommand.id, permissions: newCommand.permissions });
}
}
const guilds = client.guilds.cache.map(g => g.id);
if(newCommand.properties.type.includes('per-guild')) {
commandsData.perGuild[dataIdx] = newCommand.data.toJSON();
for (const guild of guilds) {
if(guild == process.env.DEV_GUILD) continue;
await rest.put(
Routes.applicationGuildCommands(process.env.CLIENT, guild), {
body: commandsData.perGuild,
},
);
}
}
console.log(
'\nNew Command --------------------------------\n', commands[cmdIdx],
'\nData:\n', commandsData.guild[dataIdx],
);
if(newCommand.permissions) {
console.log('Permissions');
console.table(newCommand.permissions);
}
console.table(commands);
interaction.editReply({ content: `Command \`${cmdName}\` reloaded on ${guilds.length} guilds.`, ephemeral: true });
} }
catch (error) { catch (error) {
console.error(error); console.error(error);
await interaction.reply({ await interaction.reply({
content: `A error occur while trying to reload \`${interaction.commandName}\`\n\`\`\`${error}\`\`\``, content: `A error occur while trying to reload the \`${cmdName}\` command.\n\`\`\`diff\n- ${error}\`\`\``,
ephemeral: true, ephemeral: true,
}); });
} }
}, },
}; };

38
commands/utils/invite.js Normal file
View File

@@ -0,0 +1,38 @@
const { SlashCommandBuilder } = require('@discordjs/builders');
module.exports = {
data: new SlashCommandBuilder()
.setName('invite')
.setDescription('Create a invite link for a bot')
.addUserOption(option =>
option.setName('user')
.setDescription('The bot that you want to add to a guild.')
.setRequired(false))
.addStringOption(option =>
option.setName('id')
.setDescription('The id of bot that you want to add to a guild.')
.setRequired(false))
.addIntegerOption(option =>
option.setName('permissions')
.setDescription('Bot permissions numbers generated on the developer portal. Default is 8 (administrator)')
.setRequired(false)),
properties: {
type: [ 'guild', 'per-guild' ],
},
async execute(interaction) {
const botId = () => {
if(interaction.options.getUser('user')) return interaction.options.getUser('user').id;
else if(interaction.options.getString('id')) return Number(interaction.options.getString('id'));
return process.env.CLIENT;
};
const permissions = interaction.options.getInteger('permissions') == null ? 8 : interaction.options.getInteger('permissions');
const link = `https://discord.com/api/oauth2/authorize?client_id=${botId()}&permissions=${permissions}&scope=bot%20applications.commands`;
interaction.reply({ content: link, ephemeral: true });
},
};

23
commands/utils/ping.js Normal file
View File

@@ -0,0 +1,23 @@
const { SlashCommandBuilder } = require('@discordjs/builders');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with pong!'),
permissions: [
{
id: '870383205306494997',
type: 'ROLE',
permission: true,
},
],
properties: {
type: [ 'guild', 'per-guild' ],
},
async execute(interaction) {
console.log('ping');
interaction.reply({ content: 'Ping!', ephemeral: true });
// console.log(`Ping! ${interaction.options.get('input').value}`);
},
};

60
events/client/ready.js Normal file
View File

@@ -0,0 +1,60 @@
const { Routes } = require('discord-api-types/v9');
const { commandsData, commands, rest } = require('../../index');
const console = require('../../functions/meta/console');
module.exports = {
name: 'ready',
async execute(client) {
await client.application?.fetch();
const guilds = await client.guilds.cache.map(guild => guild.id);
console.debug(guilds);
for (const command of commands) {
if(!command.properties.type.includes('guild')) continue;
const clientCommand = (await client.guilds.cache.get(process.env.DEV_GUILD)?.commands.fetch()).find(c => c.name === command.data.name);
if(command.permissions) {
await clientCommand.permissions.set({ id: clientCommand.id, permissions: command.permissions });
}
command.id = clientCommand.id;
command.name = clientCommand.name;
}
for (const guild of guilds) {
if(guild.id == process.env.DEV_GUILD) continue;
try {
await rest.put(
Routes.applicationGuildCommands(process.env.CLIENT, guild), {
body: commandsData.perGuild,
},
);
}
catch (error) {
console.error(error);
}
}
console.info('Guild Commands:');
console.table(commands);
console.info('Bot configurations:');
console.table({
'Owner Id': process.env.OWNER,
'Development Guild Id': process.env.DEV_GUILD,
'Client Id': process.env.CLIENT,
});
console.info('BOT READY');
},
};

View File

@@ -0,0 +1,25 @@
const { Routes } = require('discord-api-types/v9');
const fs = require('fs');
const console = require('../../functions/meta/console');
module.exports = {
name: 'guildCreate',
async execute(guild, client) {
const { commands, commandsData, rest } = require('../../index');
try {
await rest.put(
Routes.applicationGuildCommands(process.env.CLIENT, guild.id), {
body: commandsData.perGuild,
},
);
}
catch (error) {
console.error(error);
}
},
};

View File

@@ -0,0 +1,42 @@
const { commands } = require('../../index');
const console = require('../../functions/meta/console');
module.exports = {
name: 'interactionCreate',
async execute(interaction, client) {
console.system(`New interaction fired: ${interaction.type} ${interaction.id}`);
console.time('Interaction');
if(interaction.isCommand()) {
console.system(`Command ${interaction.commandName} executing\n`);
const command = commands.find(c => c.data.name === interaction.commandName);
console.debug('Command data:');
console.log(command);
console.debug('Command console:');
if(!command) return;
try {
await command.execute(interaction, client);
}
catch (error) {
console.error(error);
await interaction.reply({
content: `A error occur while trying to execute the command.\n\`\`\`diff\n- ${error}\`\`\``,
ephemeral: true,
});
}
console.system(`Command ${interaction.commandName} executed`);
}
console.timeEnd('Interaction');
console.system(`Interaction finished: ${interaction.type} ${interaction.id}`);
},
};

51
functions/meta/console.js Normal file
View File

@@ -0,0 +1,51 @@
const chalk = require('chalk');
module.exports = {
CONSOLE: require('console'),
log: (...args) => console.log(...args),
time: (label) => console.time(chalk.hex('#DF82FF').bold(`\n[ TIME LOG ] ${label}`)),
timeEnd: (label) => console.timeEnd(chalk.hex('#DF82FF').bold(`\n[ TIME LOG ] ${label}`)),
timeLog: (label) => console.timeLog(chalk.hex('#DF82FF').bold(`\n[ TIME LOG ] ${label}`)),
assert: (args) => console.assert(args),
table: (obj) => console.table(obj),
count: (n) => console.count(n),
clear: () => console.clear(),
error: (errorMsg) => {
console.log(
// chalk.bgHex('#D02525').hex('#ffffff').bold('\n ERROR ') +
chalk.hex('#D02525').bold(`\n[ ERROR ] ${errorMsg}`));
console.error(errorMsg);
},
warn: (warnMsg) => {
console.log(
// chalk.bgHex('#E5C10E').hex('#ffffff').bold('\n WARNING ') +
chalk.hex('#E5C10E').bold(`\n[ WARNING ] ${warnMsg}`));
},
system: (systemMsg) => {
console.log(
// chalk.bgHex('#0EB4E5').hex('#ffffff').bold('\n SYSTEM ') +
chalk.hex('#0EB4E5').bold(`\n[ SYSTEM ] ${systemMsg}`));
},
info: (infoMsg) => {
console.log(
// chalk.bgHex('#52C74F').hex('#ffffff').bold('\n INFO ') +
chalk.hex('#52C74F').bold(`\n[ INFO ] ${infoMsg}`));
},
debug: (debugMsg) => {
console.log(
chalk.bgHex('#252525').hex('#ffffff').bold('\n [ DEBUG ] ') + chalk.reset(` ${debugMsg}`));
},
};

155
index.js
View File

@@ -1,110 +1,105 @@
const Discord = require('discord.js'); const { Client, Collection, Intents } = require('discord.js');
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const fs = require('fs'); const fs = require('fs');
const { const console = require('./functions/meta/console');
token,
guildId,
} = require('./config.json');
const client = new Discord.Client({ const client = new Client({
intents: ['GUILDS', 'GUILD_MESSAGES', 'GUILD_MESSAGE_REACTIONS'], intents: [Intents.FLAGS.GUILDS],
}); });
const clientCommands = new Discord.Collection();
async function registryCommands() { client.commands = new Collection();
const owner = (await client.application.fetch()).owner; const commandFolders = fs.readdirSync('./commands');
const commands = [];
const commandsData = {
guild: [],
perGuild: [],
global: [],
};
module.exports = { for (const folder of commandFolders) {
owner,
};
console.time('Duration'); const commandFiles = fs.readdirSync(`./commands/${folder}`).filter(file => file.endsWith('.js'));
const guildCommands = client.guilds.cache.get(guildId).commands; for (const file of commandFiles) {
const commandsData = []; const command = require(`./commands/${folder}/${file}`);
const commandFolders = fs.readdirSync('./commands'); if(command.properties) command.properties.folder = folder;
else command.properties = { folder: folder };
for (const folder of commandFolders) { if(!command.properties.guild) command.properties.guild = process.env.DEV_GUILD;
const commandFiles = fs.readdirSync(`./commands/${folder}`).filter(file => file.endsWith('.js')); commands.push(command);
for (const file of commandFiles) { if(command.properties.type.includes('guild')) {
commandsData.guild.push(command.data.toJSON());
}
const cmd = require(`./commands/${folder}/${file}`); if(command.properties.type.includes('per-guild')) {
commandsData.perGuild.push(command.data.toJSON());
clientCommands.set(cmd.name, cmd); }
commandsData.push(cmd);
if(command.properties.type.includes('per-guild')) {
commandsData.global.push(command.data.toJSON());
} }
} }
await guildCommands.set(commandsData);
for (const folder of commandFolders) {
const commandFiles = fs.readdirSync(`./commands/${folder}`).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const cmd = require(`./commands/${folder}/${file}`);
const cmdId = (await guildCommands.fetch()).find(command => command.name === cmd.name).id;
clientCommands.set(cmd.name, {
id: cmdId,
data: cmd,
});
(await guildCommands.fetch(cmdId)).permissions.set({
id: cmdId,
permissions: cmd.permissions,
});
}
}
module.exports = {
clientCommands,
guildCommands,
};
console.group('\nCOMMANDS REGISTERED');
console.timeEnd('Duration');
console.log('Commands table:');
console.table(clientCommands);
console.groupEnd();
} }
client.on('ready', async () => {
registryCommands(); const rest = new REST({
version: '9',
}).setToken(process.env.TOKEN);
console.log('-- BOT READY --'); module.exports = { commands, commandsData, rest };
}); (async () => {
client.login(token);
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand() || !clientCommands.has(interaction.commandName)) return;
try { try {
await clientCommands.get(interaction.commandName).data.execute(interaction);
await rest.put(
Routes.applicationGuildCommands(process.env.CLIENT, process.env.DEV_GUILD), {
body: commandsData.guild,
},
);
} }
catch (error) { catch (error) {
console.error(error); console.error(error);
await interaction.reply({
content: `A error occur while trying to execute \`${interaction.commandName}\`\n\`\`\`${error}\`\`\``,
ephemeral: true,
});
} }
}); })();
const eventFolders = fs.readdirSync('./events');
for (const folder of eventFolders) {
const eventFiles = fs.readdirSync(`./events/${folder}`).filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const event = require(`./events/${folder}/${file}`);
if (event.once) {
client.once(event.name, (...args) => {
console.system(`New event fired: ${event.name}`);
event.execute(...args, client);
console.system(`Event finished: ${event.name}`);
});
}
else {
client.on(event.name, (...args) => {
console.system(`New event fired: ${event.name}`);
event.execute(...args, client);
console.system(`Event finished: ${event.name}`);
});
}
}
}
client.login(process.env.TOKEN);

14
nodemon.json Normal file
View File

@@ -0,0 +1,14 @@
{
"delay": 3500,
"ignore": [
".git", ".gitignore", ".gitattributes",
"node_modules/**/node_modules"
],
"watch": [
"commands/dev/*",
"./index.js"
],
"env": {
"NODE_ENV": "development"
}
}

2135
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -4,16 +4,23 @@
"description": "", "description": "",
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"start": "node .", "start": "node -r dotenv/config .",
"start-dev": "nodemon -r dotenv/config .",
"test": "echo \"Error: no test specified\" && exit 1" "test": "echo \"Error: no test specified\" && exit 1"
}, },
"keywords": [], "keywords": [],
"author": "Lored", "author": "Lored",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"discord.js": "^13.0.0" "@discordjs/builders": "^0.5.0",
"@discordjs/rest": "^0.1.0-canary.0",
"chalk": "^4.1.2",
"discord-api-types": "^0.22.0",
"discord.js": "^13.1.0",
"dotenv": "^10.0.0"
}, },
"devDependencies": { "devDependencies": {
"eslint": "^7.31.0" "eslint": "^7.31.0",
"nodemon": "^2.0.12"
} }
} }