获取用户对 Discord 上测验机器人的操作

问题描述 投票:0回答:1

我是编码新手。我想,我正在开发我的第二个机器人。第一个是从json文件中给出随机提示,让玩家想象自己的角色在新的情况下,帮助他们更加了解自己的角色。

无论如何。我需要帮助的机器人是测验机器人。现在,我已经设置了用“!quiz”开始测验的命令,而且效果很好。 不知道这是否会成为以后的问题。对于我的第一个机器人,我只使用了斜杠命令。

我的问题是机器人正在发送第一个问题 按钮上可能有答案,但没有一个有响应。

终端没有给我任何关于此的线索,不和谐告诉我“交互失败”,就是这样。

这是迄今为止我的代码。

const { Client, Intents, MessageActionRow, MessageButton } = require('discord.js');
const { SlashCommandBuilder } = require('@discordjs/builders');
const { token } = require('./config.json');
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const fs = require('fs');

const client = new Client({ intents: [ 'GUILDS',// Required for guild-related events
                                        'GUILD_MESSAGES' // Required for message related events
                                      ] 
                        });
const commands = [];
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

                        // Choose the prefix for starting the quiz
const PREFIX = '!'; // You can change this prefix as needed

client.once('ready', () => {
    console.log('Quiz Bot is ready!');
});

client.on('messageCreate', async (message) => {
    if (message.author.bot) return;
    if (!message.content.startsWith(PREFIX)) return;

    const args = message.content.slice(PREFIX.length).trim().split(/ +/);
    const command = args.shift().toLowerCase();

    if (command === 'quiz') {
        // Example quiz question
        const question = 'What is the capital of France?';
        const answers = ['Paris', 'London', 'Berlin'];
        
        // Create button row for each answer
        const row = new MessageActionRow()
            .addComponents(
                answers.map(answer => new MessageButton()
                    .setCustomId(answer.toLowerCase())
                    .setLabel(answer)
                    .setStyle('PRIMARY')
                )
            );
        
        // Send question with buttons
        await message.channel.send({
            content: question,
            components: [row]
        });
        // Listen for button clicks
        const filter = (interaction) => interaction.customId === answers.find(a => a.toLowerCase() === interaction.customId);
        const collector = message.channel.createMessageComponentCollector({ filter, time: 15000 }); // 15 seconds to answer

        // collector.on('collect', async (interaction) => {
        //     await interaction.reply({ content: `${interaction.user.username} answered ${interaction.customId}`, ephemeral: true });
        // });
        collector.on('collect', async (interaction) => {
            try {
                // Différer la mise à jour de l'interaction jusqu'à ce que le bot ait terminé de traiter l'interaction
                await interaction.deferUpdate();
        
                // Traiter l'interaction ici
                await interaction.reply({ content: `${interaction.user.username} answered ${interaction.customId}`, ephemeral: true });
            } catch (error) {
                console.error('Error handling interaction:', error);
            }
        });
        

        collector.on('end', () => {
            message.channel.send('Quiz ended.');
        });
    } else if (command === 'addquestion') {
        // Call the addQuestion command handler
        await addQuestion(message, args);
    }
});

// Replace 'YOUR_TOKEN' with your actual bot token
client.login(token);

我期望机器人能够理解有人正在点击按钮,并且显然 我检查了开发门户中的授权设置是否正确。我没有尝试管理,因为它似乎没有必要。

我认为我的问题是代码中缺少某些内容来获取用户的交互,但我不知道如何设置它

非常感谢您的帮助!

discord.js bots interaction
1个回答
0
投票

你可以做的是用问题设置一些表情,每个答案一个,然后创建一些像这样的对象

const player = {
      score : 0,
      id: theUserId
 }

每次用户点击代表答案的表情时,他都会获得一分,如果他还没有在玩家列表中,他就会被添加到玩家列表中,并且在测验结束时,您只需将获胜者设置为最高分

© www.soinside.com 2019 - 2024. All rights reserved.