⁨Alex Animate Mp4⁩ avatar
Alex Animate Mp4

Exemple de bot Discord

Bot avec un handler pour événement et commande, help dynamique et stockage secrète des paramètres avec .env (dépendances: discord.js et dotenv)

public ⁨7⁩ ⁨files⁩ 2021-01-20 01:36:39 UTC

.env

Raw
TOKEN="TOKEN"
PREFIX="PREFIX"

commands\info\help.js

Raw
module.exports = {
    name: `help`,
    description: `Affiche toutes les commandes du bot.`,
    usage: `[commande] ou rien`,
    aliases: [`h`],
    args: false,
    exclude: true,
    guildOnly: false,
    category: `Information`,
    async execute(client, message, args, discord, functions) {
        const application = await client.fetchApplication();
        if (!args[0]) {
            const embed = new discord.MessageEmbed()
                .setColor(`#1DD460`)
                .setAuthor(message.author.username, message.author.displayAvatarURL({
                    dynamic: true
                }) || "")
                .setTitle(`Liste de toutes les commandes`)
                .setDescription(`Tu peut aussi envoyer \`${process.env.PREFIX}help [commande]\` pour avoir les informations d'une commande !`)
                .setTimestamp()
                .setFooter(client.user.username, client.user.displayAvatarURL({
                    dynamic: true
                }));
            let validCommands = message.author.id == application.owner.id ? client.commands : client.commands.filter(c => !c.exclude === true);
            const categories = validCommands.map(c => c.category).filter((v, i, a) => a.indexOf(v) === i);
            categories.sort((a, b) => `${a}`.localeCompare(`${b}`)).forEach(category => {
                const commands = validCommands.filter(c => c.category === category).sort((a, b) => a.name.localeCompare(b.name)).map(c => `\`${functions.ENVFORMATVALUE(process.env.PREFIX)}${c.name}\``).join('**, **');
                const length = validCommands.filter(c => c.category === category).size;
                embed.addField(`❯ ${category || `Catégorie non indiqué`}: [**${length}**]`, `${commands}`, false);
            });
            if (!embed.fields.length) {
                embed.setTitle(`Aucune commande n'est enregistré !`);
                embed.setDescription(``);
            };
            message.channel.send(embed);
        } else if (args[0]) {
            const command = client.commands.get(client.aliases.get(args[0].toLocaleLowerCase()) || args[0].toLocaleLowerCase());
            if (command.exclude == true && message.author.id !== application.owner.id) return;
            const embed = new discord.MessageEmbed()
                .setColor(`#1DD460`)
                .setAuthor(message.author.username, message.author.displayAvatarURL({
                    dynamic: true
                }) || "")
                .setTitle(`Informations concernant une commande`)
                .addField(`• __Nom__`, `\`${functions.ENVFORMATVALUE(process.env.PREFIX)}${command.name}\``, true)
                if (command.aliases) embed.addField(`• __Aliases__`, `\`${functions.ENVFORMATVALUE(process.env.PREFIX)}${command.aliases.join(`\`**,** \`${functions.ENVFORMATVALUE(process.env.PREFIX)}`)}\``, true);
                if (command.description) embed.addField(`• __Description__`, `\`${command.description}\``);
                if (command.usage) embed.addField(`• __Utilisation__`, `\`${command.usage}\``);
                embed.addField(`• __Catégorie__`, `\`${command.category || `Catégorie non indiqué`}\``, true)
                embed.addField(`• __Arguments nécessaire__`, `\`${command.args ? `Oui` : `Non`}\``, true)
                embed.addField(`• __Serveur uniquement__`, `\`${command.guildOnly ? `Oui` : `Non`}\``, true)
                embed.setTimestamp()
                embed.setFooter(client.user.username, client.user.displayAvatarURL({
                    dynamic: true
                }));
            message.channel.send(embed);
        };
    }
};

commands\test\test.js

Raw
module.exports = {
    name: `test`,
    description: `Test.`,
    usage: ``,
    aliases: [`t`],
    args: false,
    exclude: false,
    guildOnly: false,
    category: `Test`,
    async execute(client, message, args, discord, functions) {
        return message.reply(`TEST !`);
    }
};

events\client\ready.js

Raw
module.exports = (client) => {
    return console.log(`${client.user.username} est en ligne !`);
};

events\guild\message.js

Raw
module.exports = async (client, message) => {
	const path = require(`path`);
	const discord = require(`discord.js`);
	const functions = require(path.join(`../..`, `functions.js`));
	const args = await message.content.slice(functions.ENVFORMATVALUE(process.env.PREFIX).length).trim().split(/ +/g);
	const commandName = args.shift().toLowerCase();
	const command = client.commands.get(commandName) || client.commands.get(client.aliases.get(commandName));

	if (message.author.bot || message.content.indexOf(functions.ENVFORMATVALUE(process.env.PREFIX)) !== 0 || !command) return;

	if (command.args == true && !args.length) return message.reply(command.usage ? `Vous n'avez fourni aucun argument !\nL'utilisation appropriée serait: \`${functions.ENVFORMATVALUE(process.env.PREFIX)}${command.name} ${command.usage}\`` : `Vous n'avez fourni aucun argument !`);

	if (command.guildOnly == true && message.channel.type != `text`) return message.reply(`Cette commande peut-être utilisé que dans un serveur !`);

	return await command.execute(client, message, args, discord, functions);
};

functions.js

Raw
function ENVFORMATVALUE (value) {
    return typeof value == `boolean` ? value : value == `true` ? true : value == `false` ? false : (/^-?\d+$/.test(value)) ? parseFloat(value) : (value) ? value : undefined;
};

module.exports.ENVFORMATVALUE = ENVFORMATVALUE;

index.js

Raw
const Discord = require(`discord.js`);
const client = new Discord.Client();
const fs = require(`fs`);
const path = require(`path`);
const functions = require(path.join(__dirname, `functions.js`));

require(`dotenv`).config();
[`aliases`, `commands`].forEach(x => client[x] = new Discord.Collection());

function LOADEVENTS(src) {
    if (fs.existsSync(src)) {
        if (fs.statSync(src).isDirectory()) {
            return fs.readdirSync(src).forEach((childItemName) => {
                return LOADEVENTS(path.join(src, childItemName));
            });
        } else {
            const options = require(path.join(src));
            return client.on(src.split(`\\`).pop().split(`.`)[0], options.bind(null, client));
        };
    };
};

LOADEVENTS(path.join(__dirname, `events`));

async function LOADCOMMANDS(src) {
    if (fs.existsSync(src)) {
        if (fs.statSync(src).isDirectory()) {
            return fs.readdirSync(src).forEach((childItemName) => {
                return LOADCOMMANDS(path.join(src, childItemName));
            });
        } else {
            const options = require(path.join(src));
            const name = options.name || src.split(`\\`).pop().split(`.`)[0];
            if (options.aliases) await options.aliases.forEach(a => client.aliases.set(a, name));
            return await client.commands.set(name, options);
        };
    };
};

LOADCOMMANDS(path.join(__dirname, `commands`));

client.login(functions.ENVFORMATVALUE(process.env.TOKEN));