public async Task <HttpResponseMessage> GetRedditRequestAsync(string method)
 {
     if (throttler.RequestIsAllowed())
     {
         Console.ForegroundColor = ConsoleColor.Green;
         Console.Write("OK: ");
         Console.ResetColor();
         Console.WriteLine(method);
         return(await client.GetAsync("https://oauth.reddit.com" + method));
     }
     else
     {
         Sleep();
         return(await GetRedditRequestAsync(method));
     }
 }
Esempio n. 2
0
        /// <summary>
        /// Returns a JArray containing article comments in JSON-structure.
        /// </summary>
        /// <param name="subreddit">The name of the subreddit</param>
        /// <param name="articleId">The id of the article</param>
        /// <returns></returns>
        public JArray Fetch(string subreddit, string articleId)
        {
            if (!_tbucket.RequestIsAllowed())
            {
                _tbucket.Delay(_tbucket.TimeToNextRefillInSeconds());
            }
            else
            {
                Console.WriteLine("Request sent: getArticleComments");
            }
            string url = "https://oauth.reddit.com/r/" + subreddit + "/comments/" + articleId;

            var response = _client.GetStringAsync(url).GetAwaiter().GetResult();

            return(JArray.Parse(response));
        }
        /// <summary>
        /// Starts the reddit bot.
        /// </summary>
        ///
        /// <example>
        /// bot.Startbot();
        /// >>Your keyword wasn't found
        /// >>OK
        /// >>Your post to user x has been submitted!
        /// >>Your keyword wasn't found (...)
        /// >>Out of tokens, sleeping for y seconds.
        /// </example>
        public void StartBot()
        {
            Authenticate();
            var     jObjects    = ParseJsonGetListOfValues(FetchJson());
            Anagram anagramizer = new Anagram();

            while (true)
            {
                foreach (var jObject in jObjects)
                {
                    if (_tokenBucket.RequestIsAllowed())
                    {
                        if (ContainsKeyword("!anagramize", jObject))
                        {
                            PostComment($"Anagram: \n{anagramizer.Anagramize(jObject.value.ToString())}", jObject);
                        }
                    }
                    else
                    {
                        int time = _tokenBucket.TimeUntilRefresh();
                        Console.WriteLine($"Out of tokens, sleeping for {time} seconds.");
                        System.Threading.Thread.Sleep(time * 1000);
                    }
                }
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Authenticate the bot to allow for OAuth requests.
        /// </summary>
        /// <param name="clientId">clientId of reddit account</param>
        /// <param name="clientSecret">clientSecret of reddit account</param>
        /// <param name="username">The reddit account's username</param>
        /// <param name="password">The reddit account's password</param>
        /// <exception cref="OAuthException"></exception>
        public void Authenticate(string clientId, string clientSecret, string username, string password)
        {
            if (!_tbucket.RequestIsAllowed())
            {
                _tbucket.Delay(_tbucket.TimeToNextRefillInSeconds());
            }
            _redditUsername = username;
            var authenticationArray         = Encoding.ASCII.GetBytes($"{clientId}:{clientSecret}");
            var encodedAuthenticationString = Convert.ToBase64String(authenticationArray);

            _client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", encodedAuthenticationString);
            _userAgent = $"{_name} /v{_version} by {username}";
            _client.DefaultRequestHeaders.Add("User-Agent", _userAgent);

            var formData = new Dictionary <string, string>
            {
                { "grant_type", "password" },
                { "username", username },
                { "password", password }
            };
            var encodedFormData = new FormUrlEncodedContent(formData);

            var authUrl  = "https://www.reddit.com/api/v1/access_token";
            var response = _client.PostAsync(authUrl, encodedFormData).GetAwaiter().GetResult();

            if (response.StatusCode.ToString() == "OK")
            {
                var responseData = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                Console.WriteLine(responseData);
                var responseToken = JObject.Parse(responseData).SelectToken("access_token");
                if (responseToken == null)
                {
                    throw new OAuthException("Invalid client information");
                }
                // Actual Token
                _accessToken = responseToken.ToString();
                var expirationTimeInSeconds = Int32.Parse(JObject.Parse(responseData).SelectToken("expires_in").ToString());
                _accessTokenExpirationTime = DateTime.Now.AddSeconds(expirationTimeInSeconds);

                // Update AuthorizationHeader
                _client.DefaultRequestHeaders.Authorization = new
                                                              System.Net.Http.Headers.AuthenticationHeaderValue("bearer", _accessToken);
            }
        }