NodeJS Discord.js V13按钮“此交互失败”

bjg7j2ky  于 11个月前  发布在  Node.js
关注(0)|答案(1)|浏览(123)

我正在尝试编写一个语言测试Discord机器人。但是,消息按钮不起作用,只会说“此交互失败”。我无法修复它。请注意,我使用的是Discord.js V13。

const { Client, Intents, MessageActionRow, MessageButton } = require('discord.js');
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { SlashCommandBuilder } = require('@discordjs/builders');
const mySecret = process.env['Key']
const clientID = "1174498538084896939"
const guildID = "949420156730376232"

const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });

const commands = [
  {
    name: 'learngerman',
    description: 'Learn German',
  },
  {
    name: 'learnrussian',
    description: 'Learn Russian',
  },
];

const rest = new REST({ version: '9' }).setToken(mySecret);

(async () => {
  try {
    console.log('Started refreshing application (/) commands.');

    await rest.put(
      Routes.applicationGuildCommands(clientID, guildID),
      { body: commands },
    );

    console.log('Successfully reloaded application (/) commands.');
  } catch (error) {
    console.error('Error refreshing application (/) commands:', error);
  }
})();

const questions = {
  german: [
    { question: 'Translate the word "dog" to German:', answer: 'Hund', choices: ['Hund', 'Katze', 'Auto', 'Tisch'] },
    { question: 'Translate the word "tree" to German:', answer: 'Baum', choices: ['Baum', 'Blume', 'Haus', 'Buch'] },
    { question: 'Translate the word "computer" to German:', answer: 'Computer', choices: ['Computer', 'Fenster', 'Stuhl', 'Telefon'] },
    // Add more German questions as needed
  ],
  russian: [
    { question: 'Translate the word "cat" to Russian:', answer: 'кошка', choices: ['кошка', 'собака', 'машина', 'дом'] },
    { question: 'Translate the word "sun" to Russian:', answer: 'солнце', choices: ['солнце', 'луна', 'звезда', 'вода'] },
    { question: 'Translate the word "book" to Russian:', answer: 'книга', choices: ['книга', 'стол', 'цветок', 'окно'] },
    // Add more Russian questions as needed
  ],
};

client.once('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on('interactionCreate', async interaction => {
  if (!interaction.isButton()) return;

  const { customId, user } = interaction;
  const choiceIndex = parseInt(customId);

  if (interaction.customId.startsWith('choice_')) {
    // Interaction is from the initial question, ignore it
    return;
  }

  const commandName = interaction.commandName;

  if (commandName === 'learngerman' || commandName === 'learnrussian') {
    // Implement German and Russian learning logic
    const language = commandName === 'learngerman' ? 'german' : 'russian';
    const randomQuestion = questions[language][Math.floor(Math.random() * questions[language].length)];
    const { answer } = randomQuestion;
    const correct = choiceIndex === 0 && interaction.user.id === user.id;

    await interaction.update({
      content: correct ? `Correct! ${user.username} answered "${answer}".` : `Incorrect! The correct answer is "${answer}".`,
      components: [],
    });
  }
});

client.on('interactionCreate', async interaction => {
  if (!interaction.isCommand()) return;

  const { commandName } = interaction;

  if (commandName === 'learngerman' || commandName === 'learnrussian') {
    // Implement German and Russian learning logic
    const language = commandName === 'learngerman' ? 'german' : 'russian';
    const randomQuestion = questions[language][Math.floor(Math.random() * questions[language].length)];
    const { question, choices } = randomQuestion;

    const row = new MessageActionRow()
      .addComponents(
        choices.map((choice, index) => new MessageButton()
          .setCustomId(index.toString())
          .setLabel(choice)
          .setStyle('PRIMARY')),
      );

    await interaction.reply({
      content: `${question}`,
      components: [row],
    });
  }
});

client.login(mySecret);

字符串
有什么问题吗?我也没有收到任何错误信息。
我重写了ie=t好几次,结果都是一样的。它应该会回应你,告诉你它是对的还是错的。

li9yvcax

li9yvcax1#

看起来当交互被按钮激活时,它不会提供.commandName,所以它不会传递这个if语句:

if (commandName === 'learngerman' || commandName === 'learnrussian') {
  ...
}

字符串
我建议你使用收藏家来制作这个功能。

相关问题