如何让Discord.Net中的AutocompleteHandler正常工作?
Discord.Net AutocompleteHandler 不显示补全列表的排查与解决
常见排查点与解决方案
1. 确保Slash命令已重新同步到Discord
修改命令参数的自动补全属性后,必须重新将命令同步到Discord服务器或全局,否则Discord端不会识别新的补全配置。
同步命令的示例代码:
// 在Bot启动流程中执行命令同步 var interactionService = services.GetRequiredService<InteractionService>(); // 同步全局命令(适用于所有服务器) foreach (var command in interactionService.SlashCommands) { await _client.Rest.CreateGlobalCommand(command.Build()).ExecuteAsync(); } // 或者同步到指定服务器(测试时更高效) // await _client.Rest.CreateGuildCommand(command.Build(), guildId).ExecuteAsync();
注意:命令同步后可能需要等待1-5分钟,Discord才会更新命令元数据。
2. 验证AutocompleteHandler的依赖注入注册
确保你的ExampleAutocompleteHandler已正确注册到依赖注入容器,且注册方式与InteractionService的解析逻辑匹配:
// 在服务注册时添加单例 var services = new ServiceCollection() .AddSingleton<ExampleAutocompleteHandler>() .AddSingleton<InteractionService>() // 其他服务注册... .BuildServiceProvider();
同时,在添加模块时要传入正确的服务容器:
await interactionService.AddModuleAsync<ItemModule>(services);
3. 检查InteractionService配置是否启用自动补全
创建InteractionService时,确保配置中未禁用自动补全功能(默认是启用的,但自定义配置时需确认):
var interactionService = new InteractionService(_client, new InteractionServiceConfig { EnableAutocomplete = true // 显式启用自动补全 });
4. 确认返回结果的类型与参数类型匹配
AutocompleteResult的Value类型必须与命令参数的类型完全一致。你的代码中参数是string类型,返回的value111、value2也是字符串,这部分没问题,但如果后续修改参数类型,需同步调整返回值类型。
5. 排除客户端缓存或环境问题
- 重启Discord客户端,避免本地缓存导致的旧命令元数据残留
- 确保测试用的服务器中,Bot拥有
应用程序命令相关的权限 - 尝试在不同的服务器或私人频道测试,排除服务器级别的配置限制
完整启动流程示例
以下是包含自动补全配置的完整Bot启动示例,可对比检查自己的代码:
using Discord; using Discord.Interactions; using Discord.WebSocket; using Microsoft.Extensions.DependencyInjection; using System; using System.Threading.Tasks; class Program { static async Task Main(string[] args) { var clientConfig = new DiscordSocketConfig { GatewayIntents = GatewayIntents.Guilds | GatewayIntents.GuildMessages }; var _client = new DiscordSocketClient(clientConfig); var services = new ServiceCollection() .AddSingleton(_client) .AddSingleton<InteractionService>() .AddSingleton<ExampleAutocompleteHandler>() .BuildServiceProvider(); var interactionService = services.GetRequiredService<InteractionService>(); await interactionService.AddModuleAsync<ItemModule>(services); // 同步全局命令 _client.Ready += async () => { foreach (var command in interactionService.SlashCommands) { await _client.Rest.CreateGlobalCommand(command.Build()).ExecuteAsync(); } Console.WriteLine("命令同步完成"); }; // 处理交互事件 _client.InteractionCreated += async (interaction) => { var ctx = new SocketInteractionContext(_client, interaction); await interactionService.ExecuteCommandAsync(ctx, services); }; await _client.LoginAsync(TokenType.Bot, "你的Bot令牌"); await _client.StartAsync(); await Task.Delay(-1); } }
内容的提问来源于stack exchange,提问作者Jofrais
相关产品推荐
相关产品推荐

