我一直在按照官方文档学习discord.js,但我无法让机器人回复斜杠(
/
)命令。
//This is the ping.js command file
const { SlashCommandBuilder } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName('pings')
.setDescription('Replies with Pong!'),
async execute(interaction) {
await interaction.reply('Pong!');
},
};
//This is the command handling / interaction handling
const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath);
for (const folder of commandFolders) {
// Grab all the command files from the commands directory you created earlier
const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
if ('data' in command && 'execute' in command) {
commands.push(command.data.toJSON());
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
}
//construct and prepare an instance for the REST module
const rest = new REST().setToken(discordToken);
//deploy the commands
(async () =>{
try{
console.log(`Started refreshing ${commands.length} application (/) commands.`);
const data = await rest.put(
Routes.applicationGuildCommands(discordClientID),
{body:commands},
)
console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (err){
console.error(err);
}
})
client.on(Events.InteractionCreate, async interaction =>{
if(!interaction.isChatInputCommand()) return;
console.log(interaction);
const command = interaction.client.commands.get(interaction.commandName);
if (!command){
console.error(`No command matching ${interaction.commandName} was found`);
return;
}
try{
await command.execute(interaction);
} catch (err){
console.error(err);
if (interaction.replied || interaction.deferred){
await interaction.followUp({content: 'There was an error while executing this command', ephemeral: true});
}else{
await interaction.reply({content: 'There was an error while executing this command', ephemeral: true});
}
}
});
到目前为止,我知道每当我输入
/pings
时,机器人应该用 "Pong!"
进行响应,但我看到的只是服务器中其他机器人的斜线命令。这不是来自应用程序本身。由于我添加了具有这两个范围 bot
和 application.commands
以及“斜杠命令”的机器人,我想这应该可以正常工作。
我尝试在这里找到有用的答案,但它们已经过时或不再工作。
只是想知道你是否成功解决了这个问题?