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

Discord Bot斜杠命令输入时角色白名单过滤失效问题排查

问题:Discord Bot /request命令自动补全显示所有角色,白名单逻辑不生效

我在给Discord Bot的/request斜杠命令做自动补全时,想只显示白名单内的3个角色,但现有代码逻辑未生效,输入命令时仍会展示服务器所有角色。

相关代码:

// Allowed roles for the /request command (whitelist)
const allowedRoleIds = [
"xxxxxxxxxxxxx", // L⛏️ : Mining
"xxxxxxxxxxxxx", // L🦬 : Hunter
"xxxxxxxxxxxxx", // L🪵 : Lumberjack
];

// Handle the /request command
client.on('interactionCreate', async interaction => {
    
    // Check if it's an autocomplete interaction
    if (interaction.isAutocomplete()) {
        if (interaction.commandName === 'request') {
            const focusedOption = interaction.options.getFocused(true);

            // Only handle the "role" option
            if (focusedOption.name === 'role') {
                try {

                    // Fetch and filter roles
                    const roles = interaction.guild.roles.cache.filter((role) =>
                        allowedRoleIds.includes(role.id)
                    );

                    // Create suggestions
                    const suggestions = roles.map((role) => ({
                        name: role.name,
                        value: role.id,
                    }));

                    // Respond with suggestions (limit to 25)
                    await interaction.respond(suggestions.slice(0, 25));
                } catch (error) {
                    console.error('Error in autocomplete logic:', error);

                    // Ensure a fallback response to prevent unknown interaction errors
                    await interaction.respond([]);
                }
            }
        }
        return; // Stop further processing for autocomplete interactions
    }
});

问题原因

你只在自动补全逻辑中做了角色过滤,但命令注册阶段的配置没对应调整:如果注册/request命令时,把role选项的类型设为默认的Role,Discord客户端会优先加载服务器所有角色列表,你的自动补全过滤会被覆盖。

解决方案

1. 修改命令注册的选项配置

将role选项的类型从Role改为String,同时开启自动补全。这样Discord不会默认展示所有角色,完全使用你的自动补全返回结果。

示例注册代码(discord.js v14+):

import { ApplicationCommandOptionType } from 'discord.js';

// 注册/request命令
await client.application.commands.create({
  name: 'request',
  description: '提交角色请求',
  options: [
    {
      name: 'role',
      type: ApplicationCommandOptionType.String,
      description: '选择要请求的角色',
      autocomplete: true,
      required: true
    }
  ]
});

2. 验证现有自动补全逻辑

确认allowedRoleIds中的角色ID是正确的服务器角色ID,无拼写或格式错误。你的过滤逻辑本身是正确的,无需修改。

完成以上两步后,重新部署Bot命令,输入/request时就只会显示白名单内的3个角色了。

内容的提问来源于stack exchange,提问作者Mike - SMT

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 12:50:12