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

DiscordJS 将服务器所有频道加入Select Menu时报选项长度超限错误

报错触发原因
  • Discord API对Select Menu下拉选择组件有强制参数限制:单个下拉菜单的选项总数必须处于1~25的区间内,超出长度限制就会触发你看到的校验报错。
  • 原有代码逻辑为先预置1个「取消」选项,再遍历服务器频道缓存全量追加频道选项,只要当前服务器频道总数≥24,算上取消选项的总长度就会突破25的上限,直接触发API拦截。
  • 原有代码未做频道类型过滤,会把语音频道、频道分类、舞台频道、线程、公告频道等非目标类型的频道也加入选项列表,既不符合常规频道选择的使用需求,也会进一步加快选项数超限。
修复方案

首先做两层逻辑优化,保证选项总数不超过API限制,同时过滤无效频道:

  1. 按业务需求过滤频道类型,比如仅保留普通文字频道,剔除不需要的频道类型
  2. 控制追加的频道选项最多为24个,预留1个位置给取消选项,保证总选项数不超过25的上限

修复后的可运行代码如下:

// 需提前从discord.js引入频道类型枚举
const { ChannelType } = require('discord.js');

run: async (interaction) => {
    const embed = new MessageEmbed()
        .setColor('#4ccdea')
        .setTitle('Select a channel below.')
        .setTimestamp()

    // 过滤出需要展示的频道类型,此处示例仅保留服务器普通文字频道,可按需调整过滤规则
    const usableChannels = interaction.guild.channels.cache.filter(channel => {
        return channel.type === ChannelType.GuildText;
    });

    // 最多取24个频道构造选项,预留位置给取消选项
    const selectOptions = usableChannels.first(24).map(channel => {
        return {
            label: channel.name,
            description: `文字频道:${channel.name}`,
            value: channel.id
        }
    });

    // 追加取消选项,此时总选项数最多25个,符合API要求
    selectOptions.push({
        label: 'Cancel',
        description: 'Cancel the channel selection',
        value: 'cancel'
    });

    const selectMenuRow = new MessageActionRow()
        .addComponents(
            new MessageSelectMenu()
                .setCustomId('channel')
                .setPlaceholder('Nothing selected')
                .addOptions(selectOptions)
        )

    await interaction.reply({ embeds: [embed], components: [selectMenuRow] });
}

如果需要覆盖服务器频道数超过24个、必须全量展示可选频道的场景,可以搭配按钮组件做分页逻辑:每次翻页时更新消息内的下拉选项,每一页仅加载对应分页的24个频道+取消选项,既符合API限制,也能实现全量频道选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 01:30:48