Streaming Twitter with C#

In this article I will walk through the steps required to create a C# console application that prints a Twitter stream to the console using TweetInvi library

The example was built using Visual Studio 2015 Community Edition and .NET Framework 4.6.

Step 1

Start Visual Studio and create a new console application, I’ve called mine TwitterPublicStream.

 Step 2

Right click on the project in the solution explorer window (In the example below this is TwitterPublicStream) and select Manage Nuget Packages

 

 

 

 

 Step 3

Search for tweetinvi and once found, install it, accepting the various licences, if you are happy to do so.

 Step 4

In order to use the Twitter API’s, you first need to obtain some credentials. To do this you now need to visit the Twitter API home page and follow the instructions.

Step 5

After that 4 step ceremony we are now ready to write some code.

using System;
using Tweetinvi;

namespace TwitterPublicStream
{
 class Program
 {
 static void Main(string[] args)
 {
 // add your Twitter API credentials here 
 Auth.SetUserCredentials("CONSUMER_KEY", "CONSUMER_SECRET", "ACCESS_TOKEN", "ACCESS_TOKEN_SECRET");

 var stream = Stream.CreateFilteredStream();
 // change LEITOT to something that is currently trending on twitter 
 stream.AddTrack("LEITOT");
 stream.MatchingTweetReceived += (sender, theTweet) =>
 {
   
    Console.WriteLine($"A tweet containing LEITOT has been found; the tweet is {theTweet.Tweet}");
 
 };
 stream.StartStreamMatchingAllConditions();

 }
 }
}

At line 2 a using statement is added for the Tweetinvi library.

At line 11 you need to add your Twitter API credentials that you obtained in Step 4.

At line 15 the AddTrack method is called. Track in the Twitter API context is a comma-separated list of phrases which will be used to determine what Tweets will be delivered on the stream. You can find out more here. Whilst testing this I suggest selecting a trending topic without the #. The one shown in the code was a football game between Leicester and Spurs.

At line 16 the MatchingTweetReceived event will output the contents of the tweet to the console.

Line 21 starts the streaming.

Step 6

In the final step, compile and run the program. After a few seconds you should start seeing Tweets populate the console window.

 

Summary

In this article I have explained how to use the superb library TweetInvi to stream Tweets of interest from Twitter into a C# console application.