I decided to play around with using the Twitter API and have put together a working example. This example also works with emoji’s which is a whole other beast that I did not have any previous experience with.
First thing that you have to do is go to Twitter’s website and sign up to get API Keys https://developer.twitter.com/en/apply-for-access.
I simplified the process a lot by adding the nuget package from TweetinviAPI. Now we setup the twitter client
var userClient = new TwitterClient(appSettings.ConsumerKey, appSettings.ConsumerSecret, appSettings.AccessToken, appSettings.AccessSecret);
Now we tell the client to read from the sample stream, and tell it what to do for each tweet received. Followed by starting the process.
var sampleStream = userClient.Streams.CreateSampleStream(); sampleStream.TweetReceived += (sender, eventArgs) => { stats.AddTweet(eventArgs.Tweet); }; await sampleStream.StartAsync();
That’s all you need to do read from the Twitter API. However, emoji’s are large part of Tweets. Being able to process them is quite complicated so I decided to use another nuget package to help with this. I ultimately decided to use Unicode.NET.
Even using this package determining if a tweet contains an emoji is no easy feat. Trying to determine if specific code points are actual emojis required me to use a list that I was able to obtain from Github Emojis. Now for each code point that we have we compare that to the list of emojis to determine if it is a proper emoji.
foreach(Codepoint codepoint in tweet.Text.Codepoints()) { string code = codepoint.AsUtf32.ToString("X"); if (emojis.Contains(code)) { containsEmoji = true; if (emojiCount.ContainsKey(code)) { emojiCount[code]++; } else { emojiCount.Add(code, 1); } } }
I also thought it would be fun to track which hashtags are being used in the tweets. This is fairly straight forward using the TweetviniAPI. We can just loop through the hashtags in the tweet via
foreach (Tweetinvi.Models.Entities.IHashtagEntity hashtag in tweet.Hashtags) { //do something fun with the data here }
That’s how it all works. I have a working copy of the project that puts together all of this at https://bitbucket.org/AndySattler/twitterstreamexample/src/master/. Thanks for reading – I hope this helps