.NET 6下Discord.Net的MessageReceived事件Content为空求助
Discord.Net 3.8.1 + .NET6 中 MessageReceived 事件 Content 为空的解决方法
1. 确保代码中显式配置正确的网关意图
开发者门户启用意图只是第一步,必须在代码初始化DiscordSocketClient时,将MessageContent和必要的消息意图一起传入:
var socketConfig = new DiscordSocketConfig { // 必须包含 GuildMessages(服务器消息)和 MessageContent,按需添加其他意图 GatewayIntents = GatewayIntents.Guilds | GatewayIntents.GuildMessages | GatewayIntents.MessageContent | GatewayIntents.DirectMessages }; var client = new DiscordSocketClient(socketConfig);
缺少GuildMessages会导致无法接收服务器内的普通消息,缺少MessageContent则会直接导致Content字段为空。
2. 检查命令服务与事件处理逻辑
- 确认
CommandService的配置没有异常过滤规则:var commandServiceConfig = new CommandServiceConfig { CaseSensitiveCommands = false, IgnoreExtraArgs = true }; var commandService = new CommandService(commandServiceConfig); - 检查
MessageReceived事件的处理代码,避免提前修改Content或判断逻辑错误:client.MessageReceived += async (msg) => { if (msg.Author.IsBot) return; int argPos = 0; // 同时支持前缀触发和@机器人触发 if (msg.HasStringPrefix("!", ref argPos) || msg.HasMentionPrefix(client.CurrentUser, ref argPos)) { var context = new SocketCommandContext(client, msg); var result = await commandService.ExecuteAsync(context, argPos, null); if (!result.IsSuccess) await context.Channel.SendMessageAsync(result.ErrorReason); } };
3. 二次验证开发者门户设置
- 进入Discord开发者门户对应应用的Bot页面,确认
Privileged Gateway Intents下的Message Content Intent处于启用状态,务必点击页面底部的Save Changes按钮(容易忽略此步骤)。 - 检查机器人在目标服务器的权限,确保拥有读取消息历史和查看频道权限,权限不足可能导致消息接收异常。
4. 排查版本兼容性问题
尝试将Discord.Net升级到最新稳定版本(如3.12.x),3.8.1可能存在与.NET6适配的小问题,新版本通常会修复意图相关的已知bug。
内容的提问来源于stack exchange,提问作者Zongo
相关产品推荐
相关产品推荐

