예제 #1
0
        /// <summary>
        /// Begins the Twitter API search stream, allowing to retrieve tweets in real time.
        /// </summary>
        /// <returns>The response from the HTTP request.</returns>
        public async Task <HttpResponseMessage> GetTweetsSearchStreamResponseAsync()
        {
            var url = string.Format("https://api.twitter.com/2/tweets/search/stream?{0}", EXPANSIONS_AND_FIELD_QUERY);

            var parameters = new Dictionary <string, object>();

            parameters.Add("Method", "GetTweetsSearchStreamResponseAsync");
            parameters.Add("Uri", url);

            try
            {
                using (var httpClient = new HttpClient())
                {
                    using (var request = new HttpRequestMessage(HttpMethod.Get, url))
                    {
                        request.Headers.Add("Authorization", string.Format("Bearer {0}", await _twitterApiAuthenticateService.GetOAuth2TokenAsync())); // Uses oauth authorisation, with the bearer token from the Twitter API.

                        return(await TwitterApiServiceExtensions.GetTwitterApiResponseAsync(httpClient, request));                                     // Returns the response from the HTTP request.
                    }
                }
            }
            catch (TwitterApiException exception)
            {
                // Exception thrown from the Twitter API. Log the error.
                _logger.LogWithParameters(LogLevel.Error, exception, exception.Message, parameters);
                throw;
            }
            catch (Exception exception)
            {
                // General exception thrown. Log the error.
                _logger.LogWithParameters(LogLevel.Error, exception, exception.Message, parameters);
                throw;
            }
        }
예제 #2
0
        public async Task <TweetResult> GetRecentTweetsAsync(string query, int maxResults)
        {
            var url = string.Format("https://api.twitter.com/2/tweets/search/recent?query={0}&max_results={1}&{2}", HttpUtility.UrlPathEncode(query), maxResults, EXPANSIONS_AND_FIELD_QUERY);

            var parameters = new Dictionary <string, object>();

            parameters.Add("Method", "GetRecentTweetsAsync");
            parameters.Add("Uri", url);
            parameters.Add("MaxRules", maxResults);

            try
            {
                TweetResult tweetResult = null;

                using (var httpClient = new HttpClient())
                {
                    // Calls a GET request.

                    using (var request = new HttpRequestMessage(HttpMethod.Get, url))
                    {
                        request.Headers.Add("Authorization", string.Format("Bearer {0}", await _twitterApiAuthenticateService.GetOAuth2TokenAsync()));  // Uses oauth authorisation, with the bearer token from the Twitter API.

                        using (var response = await TwitterApiServiceExtensions.GetTwitterApiResponseAsync(httpClient, request))
                        {
                            // Reads the response from the HTTP request and gets the content.
                            var content = await response.Content.ReadAsStringAsync();

                            try
                            {
                                // Converts the response to a TweetResult instance.
                                tweetResult = JsonConvert.DeserializeObject <TweetResult>(content);
                            }
                            catch (Exception exception)
                            {
                                // Throw an error if unable to convert to a TweetResult.
                                throw new TwitterApiException("Unable to convert the JSON response to a RuleResult type.", exception);
                            }
                        }
                    }
                }

                return(tweetResult);
            }
            catch (TwitterApiException exception)
            {
                // Exception thrown from the Twitter API. Log the error.
                _logger.LogWithParameters(LogLevel.Error, exception, exception.Message, parameters);
                throw;
            }
            catch (Exception exception)
            {
                // General exception thrown. Log the error.
                _logger.LogWithParameters(LogLevel.Error, exception, exception.Message, parameters);
                throw;
            }
        }
예제 #3
0
        /// <summary>
        /// Method to create a Twitter API rule.
        /// </summary>
        /// <param name="ruleEntries">A list of rule entries to be created.</param>
        /// <returns>An instance of <see cref="RuleResult"/>, which lists all the rules created, along with their unique identifier.</returns>
        public async Task <RuleResult> CreateRuleAsync(List <RuleEntry> ruleEntries)
        {
            var url = "https://api.twitter.com/2/tweets/search/stream/rules";

            var parameters = new Dictionary <string, object>();

            parameters.Add("Method", "CreateRuleAsync");
            parameters.Add("Uri", url);

            try
            {
                RuleResult ruleResult = null;

                using (var httpClient = new HttpClient())
                {
                    // Calls a POST request.
                    using (var request = new HttpRequestMessage(HttpMethod.Post, url))
                    {
                        request.Headers.Add("Authorization", string.Format("Bearer {0}", await _twitterApiAuthenticateService.GetOAuth2TokenAsync()));  // Uses oauth authorisation, with the bearer token from the Twitter API.
                        request.Content = new StringContent(JsonConvert.SerializeObject(new { add = ruleEntries }), Encoding.UTF8, "application/json"); // Pass the list of rules to add in JSON format.

                        // Retrieve the response.
                        using (var response = await TwitterApiServiceExtensions.GetTwitterApiResponseAsync(httpClient, request))
                        {
                            // Reads the content from the response.
                            var content = await response.Content.ReadAsStringAsync();

                            try
                            {
                                // Converts the response to a RuleResult instance.
                                ruleResult = JsonConvert.DeserializeObject <RuleResult>(content);
                            }
                            catch (Exception exception)
                            {
                                // Throw an error if unable to convert to a RuleResult.
                                throw new TwitterApiException("Unable to convert the JSON response to a RuleResult type.", exception);
                            }
                        }
                    }
                }

                return(ruleResult);
            }
            catch (TwitterApiException exception)
            {
                // Exception thrown from the Twitter API. Log the error.
                _logger.LogWithParameters(LogLevel.Error, exception, exception.Message, parameters);
                throw;
            }
            catch (Exception exception)
            {
                // General exception thrown. Log the error.
                _logger.LogWithParameters(LogLevel.Error, exception, exception.Message, parameters);
                throw;
            }
        }
예제 #4
0
        /// <summary>
        /// Gets the OAuth2 token which can be used when calling Twitter API methods.
        /// </summary>
        /// <returns>The OAuth2 token.</returns>
        public async Task <string> GetOAuth2TokenAsync()
        {
            var url = "https://api.twitter.com/oauth2/token";

            var parameters = new Dictionary <string, object>();

            parameters.Add("Method", "GetOAuth2TokenAsync");
            parameters.Add("Uri", url);

            var content = string.Empty;

            try
            {
                string token = string.Empty;
                using (var httpClient = new HttpClient())
                {
                    // Calls a POST request.
                    using (var request = new HttpRequestMessage(HttpMethod.Post, url))
                    {
                        request.Headers.Add("Authorization", string.Format("Basic {0}", Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", _twitterApiConfiguration.Value.ClientId, _twitterApiConfiguration.Value.ClientSecret))))); // Uses basic authorisation, with the client ID as the username, and the client secret as the password.
                        request.Content = new FormUrlEncodedContent(new Dictionary <string, string> {
                            { "grant_type", "client_credentials" }
                        });                                                                                                                     // Pass in a form value of "grant_type".

                        // Retrieve the response.
                        using (var response = await TwitterApiServiceExtensions.GetTwitterApiResponseAsync(httpClient, request))
                        {
                            var jsonContent = JObject.Parse(await response.Content.ReadAsStringAsync());
                            token = jsonContent["access_token"].ToString(); // Get the access token from the response.
                        }
                    }
                }
                return(token);
            }
            catch (TwitterApiException exception)
            {
                // Exception thrown from the Twitter API. Log the error.
                _logger.LogWithParameters(LogLevel.Error, exception, exception.Message, parameters);
                throw;
            }
            catch (Exception exception)
            {
                // General exception thrown. Log the error.
                _logger.LogWithParameters(LogLevel.Error, exception, exception.Message, parameters);
                throw;
            }
        }
예제 #5
0
        /// <summary>
        /// Deletes rules from the Twitter API.
        /// </summary>
        /// <param name="ruleIds">A list of all the rule IDs to be deleted.</param>
        /// <returns>An instance of <see cref="Task"/>.</returns>
        public async Task DeleteRuleAsync(List <string> ruleIds)
        {
            var url = "https://api.twitter.com/2/tweets/search/stream/rules";

            var parameters = new Dictionary <string, object>();

            parameters.Add("Method", "DeleteRuleAsync");
            parameters.Add("Uri", url);

            try
            {
                using (var httpClient = new HttpClient())
                {
                    // Calls a POST request.
                    using (var request = new HttpRequestMessage(HttpMethod.Post, url))
                    {
                        request.Headers.Add("Authorization", string.Format("Bearer {0}", await _twitterApiAuthenticateService.GetOAuth2TokenAsync()));               // Uses oauth authorisation, with the bearer token from the Twitter API.
                        request.Content = new StringContent(JsonConvert.SerializeObject(new { delete = new { ids = ruleIds } }), Encoding.UTF8, "application/json"); // Pass the list of rules to delete in JSON format.

                        // Executes the response.
                        using (var response = await TwitterApiServiceExtensions.GetTwitterApiResponseAsync(httpClient, request))
                        {
                        }
                    }
                }
            }
            catch (TwitterApiException exception)
            {
                // Exception thrown from the Twitter API. Log the error.
                _logger.LogWithParameters(LogLevel.Error, exception, exception.Message, parameters);
                throw;
            }
            catch (Exception exception)
            {
                // General exception thrown. Log the error.
                _logger.LogWithParameters(LogLevel.Error, exception, exception.Message, parameters);
                throw;
            }
        }