我用的是不和谐网3.5.0版。
我有一个OAuth2访问令牌,我试图使用DiscordRestClient
来获取用户的公会,但我得到了401未经授权。
DiscordRestClient discordClient = new();
await discordClient.LoginAsync(TokenType.Bearer, accessToken);
IReadOnlyCollection<IGuild> restGuilds = await discordClient.GetGuildsAsync();
单步执行await discordClient.GetGuildsAsync()
会引发异常。
fail: Microsoft.AspNetCore.Components.Server.Circuits.CircuitHost[111]
Unhandled exception in circuit 'iPxGWxw_tZW73Ya4zYXPehZr3w_Wdcs9uXYuEaUkslY'.
Discord.Net.HttpException: The server responded with error 401: 401: Unauthorized
at Discord.Net.Queue.RequestBucket.SendAsync(RestRequest request)
at Discord.Net.Queue.RequestQueue.SendAsync(RestRequest request)
at Discord.API.DiscordRestApiClient.SendInternalAsync(String method, String endpoint, RestRequest request)
at Discord.API.DiscordRestApiClient.SendAsync[TResponse](String method, String endpoint, BucketId bucketId, ClientBucketType clientBucket, RequestOptions options)
at Discord.API.DiscordRestApiClient.GetGuildAsync(UInt64 guildId, Boolean withCounts, RequestOptions options)
at Discord.Rest.ClientHelper.GetGuildsAsync(BaseDiscordClient client, Boolean withCounts, RequestOptions options)
我可以成功地使用一个常规的HttpClient
虽然,所以我可以确认访问令牌是有效的。
HttpClient httpClient = httpClientFactory.CreateClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
JsonArray? myGuilds = await httpClient.GetFromJsonAsync<JsonArray>("https://discord.com/api/v9/users/@me/guilds");
我哪里做错了?
2条答案
按热度按时间hjzp0vay1#
您可能没有初始化
DiscordRestClient
。使用提供的配置初始化新的DiscordRestClient。
gg58donl2#
确保在发送初始OAuth2请求时定义了正确的"作用域",例如,由于您尝试在那里获取guildren,因此您的作用域也应该包含"guildren"。
示例: