Example #1
0
        private void Stream_MatchingTweetReceived(object sender, Tweetinvi.Events.MatchedTweetReceivedEventArgs e)
        {
            _logger.WriteLine($"Got a tweet from {e.Tweet.CreatedBy} [{e.Tweet.CreatedBy.ScreenName}]");
            var user = User.GetUserFromId(e.Tweet.CreatedBy.Id);

            OnTweetReceived?.Invoke(this, new TweetReceivedEventArgs(e.Tweet, e.Json, user));
        }
        protected void SearchStream(Guid?id, HttpResponseMessage response)
        {
            var parameters = new Dictionary <string, object>();

            parameters.Add("Method", "SearchStream");
            if (id.HasValue)
            {
                parameters.Add("Job ID", id);
            }

            // Run the job async, as the stream will never return from this method whilst it's running.
            Task.Run(async() =>
            {
                try
                {
                    _logger.LogWithParameters(LogLevel.Information, "Start importing realtime tweets from Twitter API", parameters);

                    // Listen to the search stream.
                    await _twitterApiTweetService.GetTweetsSearchStreamAsync(response, (realTimeTweet, logger, parameters) =>
                    {
                        // When a tweet is received from the search stream.
                        if (OnTweetReceived != null)
                        {
                            // Invoke the OnTweetReceived delegate, passing in a JSON string of the tweet from the Twitter API.
                            OnTweetReceived.Invoke(realTimeTweet);
                        }
                    });

                    _logger.LogWithParameters(LogLevel.Warning, "Finish importing realtime tweets from Twitter API", parameters);
                }
                catch (TwitterApiException exception)
                {
                    // If the stream disconnects, log the exception and attempt to reconnect to it.
                    _logger.LogWithParameters(LogLevel.Error, exception, "Disconnected from the Twitter API", parameters);
                    ReconnectToStream(id, exception.XRateLimitResetDate);
                }
                catch (Exception exception)
                {
                    // If the stream disconnects, log the exception and attempt to reconnect to it.
                    _logger.LogWithParameters(LogLevel.Error, exception, "Disconnected from the Twitter API", parameters);
                    ReconnectToStream(id, null);
                }
            }, _cancellationToken);
        }