首页 > web前端 > js教程 > 正文

Discord.js v14 交互式分页组件实现与问题解决

碧海醫心
发布: 2025-11-16 18:06:05
原创
154人浏览过

discord.js v14 交互式分页组件实现与问题解决

本文旨在解决 Discord.js v14 中使用交互式按钮实现分页功能时,遇到的 "Bot is thinking..." 消息持续显示以及交互失败的问题。通过分析问题原因,提供了一种无需发送和删除空消息的解决方案,并分享了优化交互体验的技巧。

在使用 Discord.js v14 开发机器人时,交互式分页是一个常见的需求。然而,在实现过程中,开发者可能会遇到一些问题,例如在使用 deferReply() 后,机器人持续显示 "Bot is thinking..." 消息,或者在不使用 deferReply() 时,按钮交互后显示 "This interaction failed" 的提示。

问题分析

这些问题源于 Discord 交互的机制。当机器人接收到交互请求时,需要在一定时间内做出响应。deferReply() 方法的作用是告诉 Discord 稍后会进行响应,避免因处理时间过长而导致交互失败。然而,如果 deferReply() 后没有及时使用 editReply()、reply() 等方法进行响应,Discord 就会一直显示 "Bot is thinking..." 消息。

如果不使用 deferReply(),但处理交互的时间超过 Discord 规定的时间限制,就会出现 "This interaction failed" 的提示。

解决方案

要解决这个问题,核心在于确保在 deferReply() 后及时做出响应,或者在不使用 deferReply() 的情况下,在 Discord 规定的时间内完成交互处理。

以下是一种无需发送和删除空消息的解决方案:

i.reply("正在处理您的请求...")
.then((msg) => {
  setTimeout(() => {
    msg.delete();
  }, 3000);
});
登录后复制

这段代码首先使用 i.reply() 发送一条消息 "正在处理您的请求...",这会立即响应 Discord 的交互请求,避免 "Bot is thinking..." 消息的持续显示。然后,使用 setTimeout() 函数在 3 秒后删除这条消息,从而减少频道内的消息 clutter。

代码解释:

  • i.reply("正在处理您的请求..."): 使用 reply() 方法回复交互,该方法会立即响应 Discord 的请求。
  • .then((msg) => { ... }): then() 方法会在 reply() 方法成功执行后被调用,msg 参数代表发送的消息对象。
  • setTimeout(() => { msg.delete(); }, 3000);: 使用 setTimeout() 函数设置一个定时器,在 3 秒 (3000 毫秒) 后执行 msg.delete() 方法,删除发送的消息。

完整示例代码

AI建筑知识问答
AI建筑知识问答

用人工智能ChatGPT帮你解答所有建筑问题

AI建筑知识问答 22
查看详情 AI建筑知识问答

以下是一个完整的交互式分页组件示例代码,包含了上述解决方案:

const { ActionRowBuilder, ButtonBuilder, ButtonStyle, ComponentType, EmbedBuilder } = require('discord.js');

module.exports = {
    async execute(interaction, pages, time = 60000) {
        await interaction.deferReply();

        if (pages.length == 1) {
            const page = interaction.editReply({
                embeds: [pages],
                components: [],
                fetchReply: true
            });

            return page;
        }

        const prev = new ButtonBuilder()
            .setCustomId('prev')
            .setEmoji('◀️')
            .setStyle(ButtonStyle.Primary)
            .setDisabled(true)

        const home = new ButtonBuilder()
            .setCustomId('home')
            .setEmoji('?')
            .setStyle(ButtonStyle.Secondary)
            .setDisabled(true)

        const next = new ButtonBuilder()
            .setCustomId('next')
            .setEmoji('▶️')
            .setStyle(ButtonStyle.Primary)

        const buttonRow = new ActionRowBuilder()
            .addComponents(prev, home, next)
        let index = 0;

        let currentPage = await interaction.editReply({
            embeds: [pages[index]],
            components: [buttonRow],
            fetchReply: true
        });

        const collector = await currentPage.createMessageComponentCollector({
            componentType: ComponentType.Button,
            time
        });

        collector.on('collect', async (i) => {
            if (i.user.id != interaction.user.id) {
                const embed = new EmbedBuilder()
                    .setDescription('You can\'t use these buttons!')

                return i.reply({
                    embeds: [embed],
                    ephemeral: true
                });
            }

            // 替换原来的 i.reply
            i.reply("正在处理您的请求...")
                .then((msg) => {
                    setTimeout(() => {
                        msg.delete();
                    }, 3000);
                });


            if (i.customId == 'prev') {
                if (index > 0) index--;
            } else if (i.customId == 'home') {
                index = 0;
            } else if (i.customId == 'next') {
                if (index < pages.length - 1) index++;
            }

            if (index == 0) prev.setDisabled(true);
            else prev.setDisabled(false);

            if (index == 0) home.setDisabled(true);
            else home.setDisabled(false);

            if (index == pages.length - 1) next.setDisabled(true);
            else next.setDisabled(false);

            await currentPage.edit({
                embeds: [pages[index]],
                components: [buttonRow]
            });

            collector.resetTimer();
        });

        collector.on('end', async (i) => {
            await currentPage.edit({
                embeds: [pages[index]],
                components: []
            });
        });
        return currentPage;
    }
}
登录后复制

优化交互体验

除了上述解决方案外,还可以通过以下方式优化交互体验:

  • 使用 ephemeral: true 发送仅用户可见的消息: 如果处理结果只需要用户自己看到,可以使用 ephemeral: true 选项,例如:

    i.reply({ content: "操作已完成!", ephemeral: true });
    登录后复制

    这样发送的消息只有用户自己可见,不会影响其他用户。

  • 优化代码逻辑,缩短处理时间: 尽量优化代码逻辑,减少处理时间,避免因处理时间过长而导致交互失败。

  • 使用 loading 状态: 在处理交互期间,可以显示一个 loading 状态,让用户知道机器人正在处理请求。

总结

通过本文的介绍,相信你已经了解了 Discord.js v14 中交互式分页组件实现过程中可能遇到的问题以及解决方案。记住,核心在于确保在 deferReply() 后及时做出响应,或者在不使用 deferReply() 的情况下,在 Discord 规定的时间内完成交互处理。同时,优化代码逻辑和交互体验,可以为用户提供更好的使用体验。

以上就是Discord.js v14 交互式分页组件实现与问题解决的详细内容,更多请关注php中文网其它相关文章!

相关标签:
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号