我正在使用 Discord.NET.WebSocket 开发一个 Discord 机器人,它在本地运行完美,可以检索所有必要的公会信息,例如角色和文本通道。但是,当部署到测试服务器时,它无法检索公会角色和特定文本通道信息。
这是出现问题的机器人服务的核心部分:
DiscordSocketClient _client = new DiscordSocketClient(new DiscordSocketConfig
{
GatewayIntents = GatewayIntents.Guilds | GatewayIntents.GuildMembers
});
public async Task<IInviteMetadata> GenerateDiscordInvite()
{
try
{
var guild = _client.GetGuild(Convert.ToUInt64(_discordServerSettings.ClientId));
throw new DiscordBotException(
$"guild id: {guild.Id}," +
$"guild name: {guild.Name}," +
$"guild roles: {string.Join(", ", guild.Roles.Select(role => role.Name))}," +
$"guild channels: {guild.GetTextChannel(Convert.ToUInt64(_discordServerSettings.ChannelId))?.Name}," +
$"client login state: {_client?.LoginState}," +
$"client user name: {_client?.CurrentUser?.Username}," +
$"guild is admin: {guild.CurrentUser?.GuildPermissions.Administrator}," +
$"guild user name: {guild.CurrentUser?.Username}");
}
catch (Exception e)
{
throw a new DiscordBotException("Failed to generate invite: " + e.Message, e);
}
}
此外,这里是初始化
StartAsync
的 DiscordSocketClient
方法:
public async Task StartAsync()
{
await _client.LoginAsync(TokenType.Bot, _discordBotSettings.Token);
await _client.StartAsync();
}
以及调用
StartAsync
的托管服务:
public class BotHostedService : IHostedService
{
private readonly IDiscordBotService _botService;
public BotHostedService(IDiscordBotService botService)
{
_botService = botService;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
await _botService.StartAsync();
}
}
响应示例:
guild id: 123456789123456789,
guild name: TestGuild,
guild roles: Role1, Role2, Role3,
guild channels: General,
client login state: LoggedIn,
client user name: TestBot,
guild is admin: True,
guild user name: TestBot
guild id: 123456789123456789,
guild name: TestGuild,
guild roles: ,
guild channels: ,
client login state: LoggedIn,
client user name: TestBot,
guild is admin: False,
guild user name:
问题:
该机器人部署在测试服务器上时,不会检索对其功能至关重要的
GuildRoles
和 GuildChannels
。本地开发环境不会出现此问题。两种环境都使用具有相同权限的相同 Discord 机器人帐户。
问题:
什么可能导致 Discord 机器人无法在测试服务器上检索
GuildRoles
、GuildChannels
和公会当前用户,尽管在本地按预期工作?是否有我可能忽略的特定环境或配置方面?
我记录了不和谐的机器人和服务器配置:
clientId
、token
、clientSecret
- 它们在本地和测试中是相同的。此外,Discord 中的 Discord 服务器和机器人设置是相同的(因为我在两个环境上使用相同的 Discord 服务器和机器人)。
任何解决此问题的指导或建议将不胜感激。
虽然我无法重新创建您的问题来验证,但它与此问题有一些相似之处client.GetGuild() 返回 null。 Discord.NET - 我相信我的回答对提问者有帮助,并且值得您尝试(我假设它与缓存相关以及 client.GetGuild() 的工作原理)