-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSdcSharpClient.cs
More file actions
55 lines (44 loc) · 1.63 KB
/
SdcSharpClient.cs
File metadata and controls
55 lines (44 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#nullable enable
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using ComposableAsync;
using Newtonsoft.Json;
using RateLimiter;
using SDC_Sharp.Types.Exceptions;
using SDC_Sharp.Types.Interfaces;
namespace SDC_Sharp;
public sealed class SdcSharpClient : ISdcSharpClient
{
private static HttpClient s_httpClient = null!;
private static readonly TimeLimiter s_botsRateLimit =
TimeLimiter.GetFromMaxCountByInterval(2, TimeSpan.FromMinutes(1));
private static readonly DelegatingHandler s_handler =
TimeLimiter.GetFromMaxCountByInterval(5, TimeSpan.FromSeconds(10)).AsDelegatingHandler();
public SdcSharpClient(ISdcConfig config)
{
s_httpClient = new HttpClient(s_handler);
s_httpClient.BaseAddress = new Uri("https://api.server-discord.com/v2");
s_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
s_httpClient.DefaultRequestHeaders.Add("Authorization", config.Token);
}
public async Task<T> PostRequest<T>(string path, StringContent data)
{
await s_botsRateLimit;
return await Request<T>(s_httpClient.PostAsync(path, data));
}
public async Task<T> GetRequest<T>(string path)
{
return await Request<T>(s_httpClient.GetAsync(path));
}
private static async Task<T> Request<T>(Task<HttpResponseMessage> task)
{
var response = await task;
response.EnsureSuccessStatusCode();
var str = await response.Content.ReadAsStringAsync();
if (str.StartsWith(@"{""error"":{"))
throw ApiErrorException.GetException(JsonConvert.DeserializeObject<ApiError>(str)!.Error);
return JsonConvert.DeserializeObject<T>(str)!;
}
}