You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google图片搜索机器人分页按钮交互失败问题求助

图片搜索机器人分页按钮交互失败问题

我正在开发一款调用API实现图片搜索的Google搜索引擎机器人,计划添加分页系统,但目前分页按钮完全无法正常工作,点击时触发交互失败。

相关代码

async function main(currentindex=0,embed=null,response_=null) {
    const keyword = message.content.split(' ')[1]
    const result = await fetch(url + keyword + rest, {
      method: 'GET'
    })
    console.log(currentindex)
    console.log(message)
    const json_Result = await result.json();
    embed = embed ?? new EmbedBuilder()
        .setTitle(json_Result['images_results'][currentindex]['source'])
        .setDescription(json_Result['images_results'][currentindex]['link'])
        .addFields({name: '**Info**', value: json_Result['images_results'][currentindex]['title']})
        .setImage(json_Result['images_results'][currentindex]['thumbnail'])
    const previousButton = new ButtonBuilder()
          .setCustomId('previous')
          .setLabel('PREVIOUS')
          .setDisabled(currentindex > 0)
          .setStyle(ButtonStyle.Primary)
    const nextButton = new ButtonBuilder()
          .setCustomId('next')
          .setLabel('NEXT')
          .setStyle(ButtonStyle.Primary)
    const row = new ActionRowBuilder()
          .addComponents(previousButton, nextButton)
    console.log(message.author)
    response_ = response_ ?? await message.reply({embeds: [embed], components: [row], allowedMentions: {repliedUser: false}})
    console.log(response_)
    const collectorFilter = i => i.user.id === message.author.id;
    const responser = await response_.awaitMessageComponent({ filter: collectorFilter})
    console.log(responser)
    if (responser.customId === 'next') {
        currentindex++;
        main(currentindex, embed, response_)
    } else if (responser.customId === 'previous') {
        currentindex--;
        main(currentindex, embed, response_)
    } else {
        console.log(response_)
    }
}

报错情况

点击按钮时提示"该交互失败了,请再试一次"。

修复方案
  • 修正按钮禁用逻辑:previousButton的禁用条件写反了,应该是当前索引为0时禁用上一页按钮,修改为:

    .setDisabled(currentindex === 0)
    

    同时给下一页按钮添加禁用逻辑,当到达最后一页时禁用:

    .setDisabled(currentindex >= json_Result['images_results'].length - 1)
    
  • 添加交互ACK响应:Discord要求组件交互必须在3秒内确认,否则会触发失败。获取到按钮交互后立即调用deferUpdate():

    const responser = await response_.awaitMessageComponent({ filter: collectorFilter})
    await responser.deferUpdate();
    
  • 替换递归为循环:反复递归调用main会导致潜在内存泄漏,改用循环结构更稳定:

    async function main() {
        let currentindex = 0;
        const keyword = message.content.split(' ')[1];
        const result = await fetch(url + keyword + rest, { method: 'GET' });
        const json_Result = await result.json();
        let response_;
    
        while (true) {
            const embed = new EmbedBuilder()
                .setTitle(json_Result['images_results'][currentindex]['source'])
                .setDescription(json_Result['images_results'][currentindex]['link'])
                .addFields({name: '**Info**', value: json_Result['images_results'][currentindex]['title']})
                .setImage(json_Result['images_results'][currentindex]['thumbnail']);
    
            const previousButton = new ButtonBuilder()
                .setCustomId('previous')
                .setLabel('PREVIOUS')
                .setDisabled(currentindex === 0)
                .setStyle(ButtonStyle.Primary);
    
            const nextButton = new ButtonBuilder()
                .setCustomId('next')
                .setLabel('NEXT')
                .setDisabled(currentindex >= json_Result['images_results'].length - 1)
                .setStyle(ButtonStyle.Primary);
    
            const row = new ActionRowBuilder().addComponents(previousButton, nextButton);
    
            if (!response_) {
                response_ = await message.reply({embeds: [embed], components: [row], allowedMentions: {repliedUser: false}});
            } else {
                await response_.edit({embeds: [embed], components: [row]});
            }
    
            const collectorFilter = i => i.user.id === message.author.id;
            try {
                const responser = await response_.awaitMessageComponent({ filter: collectorFilter, time: 60000 });
                await responser.deferUpdate();
                if (responser.customId === 'next') {
                    currentindex++;
                } else if (responser.customId === 'previous') {
                    currentindex--;
                }
            } catch (error) {
                // 超时后禁用所有按钮
                await response_.edit({components: [
                    new ActionRowBuilder().addComponents(
                        previousButton.setDisabled(true),
                        nextButton.setDisabled(true)
                    )
                ]});
                break;
            }
        }
    }
    

内容的提问来源于stack exchange,提问作者TheDemonSlayerOfTheDemons

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 19:08:24