如何在Discord.NET库中获取Discord用户的自定义状态
Discord.NET 获取用户自定义状态实现方案
前置配置:开启必要网关意图
该功能依赖Discord的特权网关意图,未正确配置的情况下无法获取到状态数据:
- 前往Discord开发者平台的对应机器人应用页,在「Bot」设置栏目下,开启 Presence Intent 和 Server Members Intent 两个特权权限
- 初始化
DiscordSocketClient时,在配置中声明需要使用的网关意图,示例代码:
var clientConfig = new DiscordSocketConfig { // 除了你原有需要的意图外,必须加入GuildPresences和GuildMembers GatewayIntents = GatewayIntents.AllUnprivileged | GatewayIntents.GuildPresences | GatewayIntents.GuildMembers }; var discordClient = new DiscordSocketClient(clientConfig);
注意:如果配置后仍拿不到状态,可重启机器人进程重新拉取网关权限,避免旧的连接缓存了权限配置。
核心实现代码
用户的自定义状态存储在IUser对象的Activities属性中,筛选类型为CustomStatusGame的活动即可拿到对应状态:
// 示例:从指定服务器获取目标用户对象 var targetGuild = discordClient.GetGuild(替换为你的服务器ID); var targetUser = targetGuild.GetUser(替换为目标用户的ID); // 筛选自定义状态 var userCustomStatus = targetUser.Activities.OfType<CustomStatusGame>().FirstOrDefault(); if (userCustomStatus != null) { // 获取自定义状态文本内容 string statusContent = userCustomStatus.State; // 获取自定义状态绑定的表情(如用户未设置则为null) var statusEmoji = userCustomStatus.Emote; Console.WriteLine($"用户自定义状态:{statusContent}"); } else { Console.WriteLine("该用户当前未设置自定义状态"); }
常见注意事项
- 仅能获取用户公开的状态信息,用户设置了对陌生人隐藏的状态无法拉取
- 私聊场景下获取用户状态需要提前缓存过该用户的Presence数据,否则可能返回空
- 低版本的Discord.NET可能不包含
CustomStatusGame类型,建议将库升级到最新稳定版
内容的提问来源于stack exchange,提问作者Sweet1e42
相关产品推荐
相关产品推荐

