// server.js
// Import dependency
const { ..., SlashCommandBuilder } = require('@discordjs/builders');
const { REST } = require('@discordjs/rest');
// Create slash command
const commands = [
new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
// NEW: new command
new SlashCommandBuilder()
.setName('animal')
.setDescription('Encyclopedia animal')
.addStringOption(option =>
option.setName('animal')
.setDescription('role category')
.setRequired(true)
.addChoices(
{ name: 'Hippopotamus', value: 'Hippopotamus'},
{ name: 'Tiger', value: 'Tiger'},
{ name: 'Asian Elephant', value: 'Asian Elephant'},
{ name: 'Capybara', value: 'Capybara'},
)
)
].map(command => command.toJSON());
// NEW: Load json static beta
const animals = require('./data/animal.json');
// Register command
const rest = new REST({ version: '10' }).setToken(process.env.token);
rest.put(Routes.applicationGuildCommands(
process.env.clientId,
process.env.guildId
), { body: commands })
.then(() => console.log('Successfully registered application commands.'))
.catch(console.error);
// Reply command
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return;
const { commandName } = interaction;
if (commandName === 'ping') {
const timeTaken = Date.now() - interaction.createdTimestamp;
await interaction.reply(`Pong! This message had a latency of ${timeTaken}ms.`);
} else if (commandName === 'animal') {
// NEW: add new command
const animalInput = interaction.options.getString('animal');
const animalOutput = animals.find(animal => animal.name_en == animalInput);
await interaction.reply(animalOutput.name_th);
}
});
เมื่อ code ทำงานใหม่ กลับไปดูที่ Discord พบว่าบอทของเราเพิ่มคำสั่ง animal มาแล้วพร้อมตัวเลือกทั้ง 4