スラッシュコマンドでサブコマンドを使ってみる
code:calculator.js
const Discord = require("discord.js");
const calc_commands = {
add: { run: (l, r) => l + r, description: "足し算", mark: "+" },
multiply: { run: (l, r) => l * r, description: "掛け算", mark: "*" },
subtract: { run: (l, r) => l - r, description: "引き算", mark: "-" },
divide: { run: (l, r) => l / r, description: "割り算", mark: "/" },
};
const commands = {
/**
*
* @param {Discord.CommandInteraction} interaction
* @returns
*/
async calc(interaction) {
const subcommand = interaction.options.getSubcommand();
const result = run(...terms);
await interaction.reply(${left} ${mark} ${right} = ${result});
},
};
async function onInteraction(interaction) {
if (!interaction.isCommand()) {
return;
}
}
const client = new Discord.Client({
intents: 0
});
/**
*
* @param {Discord.Client} client
* @param {Discord.ApplicationCommandData[]} commands
* @param {Discord.Snowflake} guildId
* @returns {Promise<import("@discordjs/collection").Collection<string,Discord.ApplicationCommand>>}
*/
async function register(client, commands, guildId) {
if (guildId == null) {
return client.application.commands.set(commands);
}
const guild = await client.guilds.fetch(guildId);
return guild.commands.set(commands);
}
/**
* @type {Discord.ApplicationCommandData}
*/
const calc = {
name: "calc",
description: "簡単な計算をします。",
/**
* @type {Discord.ApplicationCommandOption}
*/
return {
type: "SUB_COMMAND",
name,
description,
return {
type: "NUMBER",
name,
description,
required: true
};
}),
};
})
};
async function onReady() {
await register(client, calc); }
client.on("interactionCreate", interaction => onInteraction(interaction).catch(err => console.error(err)));
client.on("ready", () => onReady().catch(err => console.error(err)));
client.login(process.env.DISCORD_TOKEN).catch(err => {
console.error(err);
process.exit(-1);
});
解説
サブコマンドを使用する際はコマンドの直下のoptionsにはtype: "SUB_COMMAND"としたオブジェクトを入れそこのoptionsで引数の登録などを行う。