プレフィックスコマンドからスラッシュコマンドへの移転
!ping
という発言に対して pong!
と返すサンプルを例にして、スラッシュコマンドに移転する際の変更点を書いていきます。
jsconst { Client, GatewayIntentBits } = require("discord.js");
const client = new Client({
intents: [
GatewayIntentBits.Guild,
GatewayIntentBits.GuildMessage,
GatewayIntentBits.MessageContent
]
})
const prefix = "!";
client.on("messageCreate", (message) => {
if (message.author.id === client.user.id) return;
if (!message.content.startsWith(prefix) return;
const [command, ...args] = message.slice(prefix.length).split(/\s/);
if (command === "ping") {
return message.reply("pong!");
};
});
これを、 /ping
を使用したら pong!
と返すように変更すると、
jsconst { Client, GatewayIntentBits } = require("discord.js");
const client = new Client({
intents: [
GatewayIntentBits.Guild
]
})
client.on("interactionCreate", (interaction) => {
if (!interaction.isChatInputCommand()) return;
const command = interaction.commandName
if (command === "ping") {
return interaction.reply("pong!");
};
});
変更点
スラッシュコマンドはメッセージ関連がなくても使用できるため、
diff- GatewayIntentBits.GuildMessages
- GatewayIntentBits.MessageContent
イベント名が変更
diff- client.on("messageCreate", (message) => {})
+ client.on("interactionCreate", (interaction) => {})
BOT自身がスラッシュコマンドを使用することはないため、
diff- if (message.author.id === client.user.id) return
コマンドの形式の判別方法が異なる
diff- message.content.startsWith(prefix)
+ interaction.isChatInputCommand()
command
の設定方法が異なる
diff- const [command, ...args] = message.slice(prefix.length).split(/\s/)
+ const command = interaction.commandName
返信方法
diff- message.reply
+ interaction.reply
他は基本的に message
を interaction
に置き換えればいい。