Langage :
Système de commandes
Gérez les commandes de votre bot avec un système flexible et extensible.
ℹ️ Bonne pratique
Enregistrez vos commandes via l'API (
POST /api/bots/:id/commands) pour qu'elles apparaissent dans le profil public de votre bot. Le handler local reste responsable de l'exécution.Handler de commandes
Gestionnaire de commandes avec cooldown
js
class CommandHandler {
constructor(prefix = '!') {
this.prefix = prefix;
this.commands = new Map();
}
register(name, handler, { cooldown = 0 } = {}) {
this.commands.set(name, { handler, cooldown, cooldowns: new Map() });
}
async handle(message) {
if (!message.content.startsWith(this.prefix)) return;
const [name, ...args] = message.content.slice(this.prefix.length).split(' ');
const cmd = this.commands.get(name.toLowerCase());
if (!cmd) return;
const now = Date.now();
const last = cmd.cooldowns.get(message.authorId) || 0;
if (now - last < cmd.cooldown * 1000) return; // encore en cooldown
cmd.cooldowns.set(message.authorId, now);
await cmd.handler(message, args);
}
}
// --- Utilisation ---
const handler = new CommandHandler('!');
handler.register('ping', async (msg) => {
await sendMessage(msg.channelId, '🏓 Pong !');
}, { cooldown: 5 });
handler.register('aide', async (msg) => {
const cmds = [...handler.commands.keys()].join(', ');
await sendMessage(msg.channelId, `📖 Commandes : ${cmds}`);
});
socket.on('NEW_MESSAGE', (msg) => handler.handle(msg));Enregistrer les commandes via l'API
POST /api/bots/:id/commands
js
const commands = [
{ name: 'ping', description: 'Vérifie la latence', usage: '!ping', cooldown: 5 },
{ name: 'aide', description: 'Affiche les commandes', usage: '!aide', cooldown: 10 },
{ name: 'ban', description: 'Bannit un utilisateur', usage: '!ban @user', cooldown: 0 },
];
for (const cmd of commands) {
await fetch(`${BASE}/api/bots/${BOT_ID}/commands`, {
method: 'POST',
headers: { 'Authorization': `Bot ${TOKEN}`, 'Content-Type': 'application/json' },
body: JSON.stringify(cmd),
});
}