Exemplo n.º 1
0
        private void StartTwitterStream()
        {
            TwitterStream = Tweetinvi.Stream.CreateFilteredStream();
            TwitterStream.MatchingTweetReceived += OnTweetReceived;

            TwitterStream.StallWarnings = true;
            TwitterStream.WarningFallingBehindDetected += (sender, args) =>
            {
                Log.WriteWarn("Twitter", $"Stream falling behind: {args.WarningMessage.PercentFull} {args.WarningMessage.Code} {args.WarningMessage.Message}");
            };

            TwitterStream.StreamStopped += (sender, args) =>
            {
                var ex = args.Exception;
                var twitterDisconnectMessage = args.DisconnectMessage;

                if (ex != null)
                {
                    Log.WriteError("Twitter", ex.ToString());
                }

                if (twitterDisconnectMessage != null)
                {
                    Log.WriteError("Twitter", $"Stream stopped: {twitterDisconnectMessage.Code} {twitterDisconnectMessage.Reason}");
                }

                TwitterStream.StopStream();

                Task.Factory.StartNew(() =>
                {
                    Thread.Sleep(5000);
                    TwitterStream.StartStreamMatchingAnyConditionAsync();
                });
            };

            var twitterUsers = Tweetinvi.User.GetUsersFromScreenNames(Config.Twitter.AccountsToFollow.Keys);

            foreach (var user in twitterUsers)
            {
                var channels = Config.Twitter.AccountsToFollow.First(u => u.Key.Equals(user.ScreenName, StringComparison.InvariantCultureIgnoreCase));

                Log.WriteInfo("Twitter", $"Following @{user.ScreenName}");

                TwitterToChannels.Add(user.Id, channels.Value);

                TwitterStream.AddFollow(user);
            }

            TwitterStream.StartStreamMatchingAnyConditionAsync();
        }
Exemplo n.º 2
0
        public async Task StartAsync()
        {
            _eventHubClient = EventHubClient.CreateFromConnectionString(_targetConfig.ConnectionString, _targetConfig.EventHubName);

            Auth.SetUserCredentials(_sourceConfig.Credentials.ConsumerKey, _sourceConfig.Credentials.ConsumerSecret, _sourceConfig.Credentials.AccessToken, _sourceConfig.Credentials.AccessTokenSecret);

            IFilteredStream stream = Stream.CreateFilteredStream();

            foreach (var language in _sourceConfig.Languages)
            {
                stream.AddTweetLanguageFilter((LanguageFilter)language);
            }

            foreach (string track in _sourceConfig.Tracks)
            {
                stream.AddTrack(track);
            }

            stream.MatchingTweetReceived     += OnMatchingTweetReceived;
            stream.DisconnectMessageReceived += OnDisconnectMessageReceived;
            stream.StreamStopped             += OnStreamStopped;

            stream.StallWarnings = true;

            await stream.StartStreamMatchingAnyConditionAsync();
        }
 public async void StartStreamAsync()
 {
     if (!StreamRunning)
     {
         await _stream.StartStreamMatchingAnyConditionAsync();
     }
 }
 public async Task StartTweetStreamAsync()
 {
     if (_filteredStream.StreamState != StreamState.Running)
     {
         _logger.LogInformation("Starting tweet stream.");
         await _filteredStream.StartStreamMatchingAnyConditionAsync();
     }
 }
Exemplo n.º 5
0
        public void AddTrack(string hashtag)
        {
            if (filteredStream.TracksCount > 0)
            {
                filteredStream.StopStream();

                Dictionary <string, Action <ITweet> > tracks = filteredStream.Tracks;

                ReCreateFilteredStream();

                tracks.Keys.ForEach(s => filteredStream.AddTrack(s));
            }

            filteredStream.AddTrack(hashtag);

            filteredStream.StartStreamMatchingAnyConditionAsync();

            Debug.WriteLine("ADDED HASHTAG - " + hashtag);
        }
Exemplo n.º 6
0
        public static async Task Main(string[] args)
        {
            Parser.Default.ParseArguments <Options>(args)
            .WithParsed <Options>(o =>
            {
                if (!o.Photos && !o.Gifs && !o.Videos)
                {
                    Console.WriteLine("\nYou need to provide at least one type of media to be blocked.");
                    Console.WriteLine("\t-p | photos");
                    Console.WriteLine("\t-g | gifs");
                    Console.WriteLine("\t-v | videos");
                    Environment.Exit(0);
                }

                accessToken       = o.AccessToken;
                accessTokenSecret = o.AccessTokenSecret;
                consumerKey       = o.ConsumerKey;
                consumerSecret    = o.ConsumerSecret;
                blockPhotos       = o.Photos;
                blockGifs         = o.Gifs;
                blockVideos       = o.Videos;
            })
            .WithNotParsed <Options>(error =>
            {
                Environment.Exit(0);
            });

            try
            {
                Authenticate();
                InitializeStream();
                await stream.StartStreamMatchingAnyConditionAsync();
            }
            catch (Exception)
            {
                Console.WriteLine("Failed to authenticate. Are your credentials correct?");
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Initializes and starts this stream listener.
        /// </summary>
        /// <param name="filterValue">A value used to filter out specific messages from the stream.</param>
        /// <returns>An awaitable object for this asynchronous operation.</returns>
        public async Task InitializeAsync(string filterValue)
        {
            if (_stream != null)
            {
                return;
            }

            _stream = Tweetinvi.Stream.CreateFilteredStream(
                new TwitterCredentials(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET));
            _stream.AddTrack(filterValue);

            _tweetObservable = Observable.FromEventPattern <MatchedTweetReceivedEventArgs>(_stream, nameof(_stream.MatchingTweetReceived)).
                               Select(pattern => pattern.EventArgs.Tweet);

            await _stream.StartStreamMatchingAnyConditionAsync();
        }
        public async Task StartTwitterStreamAsync(System.IO.Stream hyConnection)
        {
            _streamWriter = new System.IO.StreamWriter(hyConnection)
            {
                AutoFlush = true
            };
            var limiter = new Throttle(1, TimeSpan.FromMilliseconds(THROTTLE_MILLISECONDS));

            _stream = Stream.CreateFilteredStream();
            AddFiltersStream(_filterOptions);
            _stream.MatchingTweetReceived += (sender, t) =>
            {
                var ct = new CancellationToken();
                limiter.Enqueue(async() =>
                {
                    await _streamWriter.WriteLineAsync(JsonConvert.SerializeObject(t.Tweet.ToTweetInfo()));
                }, ct);
            };
            await _stream.StartStreamMatchingAnyConditionAsync();
        }
Exemplo n.º 9
0
 public MainWindow()
 {
     InitializeComponent();
     TimerClock.Interval = (int)TimeSpan.FromMinutes(15).TotalMilliseconds;
     TimerClock.Tick    += delegate { TweetSendedWithin15MinWindow = 0; };
     TimerClock.Start();
     Auth.SetCredentials(Credentials.RandomCredential);
     Jarvis                      = User.GetAuthenticatedUser();
     KeywordStream               = Stream.CreateFilteredStream();
     UserStream                  = Stream.CreateUserStream();
     UserStream.FollowedByUser  += FlowedByUser;
     UserStream.LimitReached    += LimitReached;
     KeywordStream.LimitReached += LimitReached;
     KeywordStream.AddTrack("reallifejarvis");
     KeywordStream.AddTrack("real life jarvis");
     KeywordStream.AddTrack("talktomejarvis");
     KeywordStream.AddTrack("talk to me jarvis");
     KeywordStream.AddTrack("#retweetjarvis");
     KeywordStream.MatchingTweetReceived += NewTweetFound;
     KeywordStream.StartStreamMatchingAnyConditionAsync();
     UserStream.StartStreamAsync();
 }
Exemplo n.º 10
0
        public void TweetTask(string text, bool displayMsg = true)
        {
            RateLimit.RateLimitTrackerMode = RateLimitTrackerMode.TrackAndAwait;                                                               //to avoid ratelimits, let Tweetinvi handle it
            var embed = new EmbedBuilder();

            if (stream == null)
            {
                stream = Stream.CreateFilteredStream();                                                                                             //create a stream for the live feed
            }
            foreach (var feed in twitterFeeds)
            {
                stream.AddFollow(User.GetUserFromScreenName(feed.twitterUser));                                                                                                         //set the stream to follow said user(s)
            }
            stream.MatchingTweetReceived += async(sender, args) =>
            {
                var tweet = args.Tweet;

                foreach (var feed in twitterFeeds)
                {
                    if (tweet.CreatedBy.ScreenName == feed.twitterUser)                                                                                                         //if the twitter screen name matches a saved screen name...
                    {
                        embed = new EmbedBuilder();
                        embed.WithAuthor($"{tweet.CreatedBy.Name} (@{tweet.CreatedBy.ScreenName})", tweet.CreatedBy.ProfileImageUrl, tweet.Url);
                        embed.WithDescription(tweet.Text);
                        embed.WithColor(0, 172, 237);                             //Twitter blue

                        if (tweet.Media.Count > 0)
                        {
                            embed.WithImageUrl(tweet.Media[0].MediaURL);
                        }

                        foreach (var channel in feed.channels)                                                                                                                          //post the embedded tweet in every channel
                        {
                            await channel.SendMessageAsync("", false, embed.Build());
                        }

                        break;
                    }
                }
            };

            stream.StreamStopped += (sender, args) =>
            {
                if (args.Exception != null)
                {
                    Console.WriteLine(args.Exception);
                }
            };

            var MainThread = new Thread(() => stream.StartStreamMatchingAnyConditionAsync());

            MainThread.Start();
            MainThread = new Thread(async() =>
            {
                if (!String.IsNullOrWhiteSpace(text) && displayMsg)
                {
                    var msg = await ReplyAsync($"`Live feed is now hooked into @{text}.`");
                    await Task.Delay(2000);
                    await msg.DeleteAsync();
                }
                else if (!displayMsg)
                {
                    var msg = await ReplyAsync($"`The live feed of @{text} has been removed.`");
                    await Task.Delay(2000);
                    await msg.DeleteAsync();
                }

                await Context.Client.SetGameAsync($"{twitterFeeds.Count} user's Twitter feed", null, ActivityType.Listening);
                while (true)
                {
                    Thread.Sleep(2000);
                    if (!running)
                    {
                        stream.StopStream();
                        stream.ClearFollows();
                        await Context.Client.SetGameAsync(null);
                        break;
                    }
                }
            });
            MainThread.Start();
            MainThread.IsBackground = true;
        }