generated at
スラッシュコマンドでサブコマンドを使ってみる
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 terms = ["left", "right"].map(e => interaction.options.getNumber(e)); const { run, mark } = calc_commands[subcommand]; const result = run(...terms); const [left, right] = terms; await interaction.reply(`${left} ${mark} ${right} = ${result}`); }, }; async function onInteraction(interaction) { if (!interaction.isCommand()) { return; } return commands[interaction.commandName](interaction); } 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: "簡単な計算をします。", options: Object.entries(calc_commands).map(([name, { description }]) => { /** * @type {Discord.ApplicationCommandOption} */ return { type: "SUB_COMMAND", name, description, options: [["left", "左項"], ["right", "右項"]].map(([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 で引数の登録などを行う。