コード例 #1
0
        private T Request <T>(string method, string endpoint, object data = null)
        {
            EnsureAuth();

            var req = new HttpRequestMessage()
            {
                Method     = new HttpMethod(method),
                RequestUri = new Uri(DiscordHttpUtil.BuildBaseUrl(9, DiscordReleaseChannel.Stable) + endpoint),
                Content    = data == null ? null : new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json")
            };

            req.Headers.Add("Authorization", $"{_auth.TokenType} {_auth.AccessToken}");

            var resp    = _httpClient.SendAsync(req).GetAwaiter().GetResult();
            var bodyObj = JToken.Parse(resp.Content.ReadAsStringAsync().Result);

            DiscordHttpUtil.ValidateResponse((int)resp.StatusCode, bodyObj);

            return(bodyObj.ToObject <T>());
        }
コード例 #2
0
        private void authorize(string grantType, Dictionary <string, string> useSpecific)
        {
            Dictionary <string, string> values = new Dictionary <string, string>()
            {
                { "client_id", _clientId.ToString() },
                { "client_secret", _clientSecret },
                { "grant_type", grantType }
            };

            foreach (var key in useSpecific.Keys)
            {
                values[key] = useSpecific[key];
            }

            var resp = _httpClient.PostAsync(DiscordHttpUtil.BuildBaseUrl(9, DiscordReleaseChannel.Stable) + "/oauth2/token", new FormUrlEncodedContent(values)).Result;

            if (resp.StatusCode >= HttpStatusCode.BadRequest)
            {
                throw new OAuth2Exception(JsonConvert.DeserializeObject <OAuth2HttpError>(resp.Content.ReadAsStringAsync().Result));
            }

            _auth = JsonConvert.DeserializeObject <DiscordOAuth2Authorization>(resp.Content.ReadAsStringAsync().Result);
        }
コード例 #3
0
        public static async Task <DiscordMessage> SendFileAsync(this DiscordClient client, ulong channelId, string fileName, byte[] fileData, string message = null, bool tts = false)
        {
            HttpClient httpClient = new HttpClient(new HttpClientHandler()
            {
                Proxy = client.Config.Proxy != null && client.Config.Proxy.Type == AnarchyProxyType.HTTP ? new WebProxy(client.Config.Proxy.Host + client.Config.Proxy.Port, false, new string[] { }, new NetworkCredential()
                {
                    UserName = client.Config.Proxy.Username, Password = client.Config.Proxy.Password
                }) : null
            });

            httpClient.DefaultRequestHeaders.Add("Authorization", client.Token);

            MultipartFormDataContent content = new MultipartFormDataContent
            {
                {
                    new StringContent(JsonConvert.SerializeObject(new MessageProperties()
                    {
                        Content = message,
                        Tts     = tts
                    })),
                    "payload_json"
                },
                { new ByteArrayContent(fileData), "file", fileName }
            };

            return(JsonConvert.DeserializeObject <DiscordMessage>(await httpClient.PostAsync(DiscordHttpUtil.BuildBaseUrl(client.Config.ApiVersion, client.Config.SuperProperties.ReleaseChannel) + $"/channels/{channelId}/messages", content)
                                                                  .GetAwaiter().GetResult().Content.ReadAsStringAsync()).SetClient(client));
        }
コード例 #4
0
        /// <summary>
        /// Sends an HTTP request and checks for errors
        /// </summary>
        /// <param name="method">HTTP method to use</param>
        /// <param name="endpoint">API endpoint (fx. /users/@me)</param>
        /// <param name="payload">JSON content</param>
        private async Task <DiscordHttpResponse> SendAsync(Leaf.xNet.HttpMethod method, string endpoint, object payload = null)
        {
            if (!endpoint.StartsWith("https"))
            {
                endpoint = DiscordHttpUtil.BuildBaseUrl(_discordClient.Config.ApiVersion, _discordClient.Config.SuperProperties.ReleaseChannel) + endpoint;
            }

            string json = "{}";

            if (payload != null)
            {
                if (payload.GetType() == typeof(string))
                {
                    json = (string)payload;
                }
                else
                {
                    json = JsonConvert.SerializeObject(payload);
                }
            }

            uint retriesLeft = _discordClient.Config.RestConnectionRetries;
            bool hasData     = method == Leaf.xNet.HttpMethod.POST || method == Leaf.xNet.HttpMethod.PATCH || method == Leaf.xNet.HttpMethod.PUT || method == Leaf.xNet.HttpMethod.DELETE;

            while (true)
            {
                try
                {
                    DiscordHttpResponse resp;

                    if (_discordClient.Proxy == null || _discordClient.Proxy.Type == ProxyType.HTTP)
                    {
                        HttpClient client = new HttpClient(new HttpClientHandler()
                        {
                            Proxy = _discordClient.Proxy == null ? null : new WebProxy(_discordClient.Proxy.Host, _discordClient.Proxy.Port)
                        });
                        if (_discordClient.Token != null)
                        {
                            client.DefaultRequestHeaders.Add("Authorization", _discordClient.Token);
                        }

                        if (_discordClient.User != null && _discordClient.User.Type == DiscordUserType.Bot)
                        {
                            client.DefaultRequestHeaders.Add("User-Agent", "Anarchy/0.8.1.0");
                        }
                        else
                        {
                            client.DefaultRequestHeaders.Add("User-Agent", _discordClient.Config.SuperProperties.UserAgent);
                            client.DefaultRequestHeaders.Add("X-Super-Properties", _discordClient.Config.SuperProperties.ToBase64());
                        }

                        var response = await client.SendAsync(new HttpRequestMessage()
                        {
                            Content    = hasData ? new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json") : null,
                            Method     = new System.Net.Http.HttpMethod(method.ToString()),
                            RequestUri = new Uri(endpoint)
                        });

                        resp = new DiscordHttpResponse((int)response.StatusCode, response.Content.ReadAsStringAsync().Result);
                    }
                    else
                    {
                        HttpRequest msg = new HttpRequest
                        {
                            IgnoreProtocolErrors = true,
                            UserAgent            = _discordClient.User != null && _discordClient.User.Type == DiscordUserType.Bot ? "Anarchy/0.8.1.0" : _discordClient.Config.SuperProperties.UserAgent,
                            Authorization        = _discordClient.Token
                        };

                        if (hasData)
                        {
                            msg.AddHeader(HttpHeader.ContentType, "application/json");
                        }

                        if (_discordClient.User == null || _discordClient.User.Type == DiscordUserType.User)
                        {
                            msg.AddHeader("X-Super-Properties", _discordClient.Config.SuperProperties.ToBase64());
                        }
                        if (_discordClient.Proxy != null)
                        {
                            msg.Proxy = _discordClient.Proxy;
                        }

                        var response = msg.Raw(method, endpoint, hasData ? new Leaf.xNet.StringContent(json) : null);

                        resp = new DiscordHttpResponse((int)response.StatusCode, response.ToString());
                    }

                    DiscordHttpUtil.ValidateResponse(resp.StatusCode, resp.Body);
                    return(resp);
                }
                catch (Exception ex) when(ex is HttpException || ex is HttpRequestException || ex is TaskCanceledException)
                {
                    if (retriesLeft == 0)
                    {
                        throw new DiscordConnectionException();
                    }

                    retriesLeft--;
                }
                catch (RateLimitException ex)
                {
                    if (_discordClient.Config.RetryOnRateLimit)
                    {
                        Thread.Sleep(ex.RetryAfter);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }