Writing a Tweet Bot in C#

Matthew G.

Ever wonder how difficult it is to write a Tweet Bot in C#?  The answer is, not at all.  It's something that you can probably get done on your lunch break - that is, if your company didn't block access to Twitter.


The first thing you need to do is to install the Nuget Package TweetSharp.  This is a great wrapper for the Twitter API.  Speaking of the API, you'll need to get a Consumer Key, Consumer Secret, Token, and Token Secret from https://dev.twitter.com/.


 Now that you have your keys and Nuget Package installed, create a simple class:

public class Tweeter

{

        // The secret keys that Twitter needs

        private string consumerKey = "YouRConSUmerKey";

private string consumerSecret = "YouRCONsumeRSEcReT";

private string token = "YoUrTOken";

private string tokenSecret = "YoURTOkenSECRet";


        // Create TwitterService and OAuthRequestToken objects

private TwitterService service;

private OAuthRequestToken requestToken;


        // Default constructor, pass in the credentials to Twitter here

public Tweeter()

{

service = new TwitterService();

service.AuthenticateWith(consumerKey, consumerSecret, token, tokenSecret);

}


        public void postTweet()

{

            try

            {

                        // This example shows you how to attach a photo to your tweet

using (var stream = new FileStream(@"c:\pathto\image.jpg", FileMode.Open))

{

var result = service.SendTweetWithMedia(new SendTweetWithMediaOptions

{

Status = "The text of your tweet",

Images = new Dictionary<string, Stream> { { "Image Name", stream } }

});

}

}

catch (Exception ex)

{

                         // Figure out what to do with your errors

}

}

}

And that's it! You can get a lot more complicated with it of course, like running it in its own thread, adding running states to it, time intervals, etc...  Have fun with it, but also remember to be responsible with this power.