How to Use TweetSharp to Push Twitter Updates in an Application
Enable a Windows or web app to push Twitter updates on behalf of a user
August 13, 2012
Like it or not, Twitter and social networks are a fundamental part of our lives. Twitter, in particular, has brought a new type of immediacy to everyday events. For many people, it's not unusual to follow, say, a sports event and keep an eye on your Twitter client to read the tweets being pushed by other people at the same time. Another common scenario is when you're engaged in other computer-related activities and want to know what's being tweeted on a given hashtag. Yet another scenario is when you have some real-time information to share and want to tweet about that. It is, however, one thing to push an update whenever you want; it's quite another to tweet regularly about real-time and frequently changing data. In this case, tweeting becomes a repetitive chore. Thanks to the Twitter API, this job can be made easier using some ad hoc software.
In this article, I'll take a look at what it takes to push a Twitter update programmatically on a behalf of a user, to show you how to enable automated tweets in a Windows or web application. The core scenario I'll refer to has some type of service that runs in the background, polls a given feed periodically, and tweets every time it detects a new post.
The Basic Tools for Twitter Programming
All you need to know about programming Twitter can be found on the Twitter Developers web page (for additional information about working with Twitter in applications, see the articles listed at the end of this article). In general, there are three ways to interact programmatically with the Twitter back end using the Twitter API, which consists of several APIs for specific purposes. You can use the Twitter Search API if you need to read the most relevant recent tweets for a given hashtag or text. When using the Search API, you might experience some seconds of delay between the effective time of the tweet and availability of the data. This delay occurs because levels of caching are applied along the way. In addition, because the Search API is a selection of recent tweets, in some cases you might even miss some tweets.
The second method, the Twitter Streaming API, allows you to access the live stream of tweets and get them as they happen. This is the API that most popular Twitter clients use. Finally, by using the REST API you can simulate the behavior of the individual user and perform basic operations programmatically, such as pushing an update, following, retweeting, or reading the timeline. Operations that you perform via the REST API require authentication.
Twitter uses the OAuth protocol for handling user authentication. It's common for developers to resort to using ad hoc libraries to avoid most of the protocol intricacies. For the purposes of this example, I'll be using the TweetSharp Twitter API wrapper installed in the Visual Studio project from NuGet, as shown in Figure 1.
Figure 1: Installing TweetSharp from NuGet
Operating on Behalf of a User
The very first step on the way to using any segment of the Twitter API is the creation of a Twitter application. A Twitter application belongs to a Twitter account and is characterized by a name and, more importantly, by a unique pair of keys: the consumer key and the secret key. These keys are generated as you register the application with the Twitter website. You go to https://dev.twitter.com/, click to create a new app, enter your Twitter credentials, and then follow the next instructions. A Twitter application is not runnable code per se. A Twitter application is simply the driver through which a host Windows application or website will work with the Twitter API.
A Twitter application is also characterized by a permission model that basically determines which operations the app can and cannot perform on behalf of a given user. The read permission will allow the application to read the user's timelines; the read-write permission will also let the application tweet and retweet on behalf of that user. Finally, a third permission level will also let the application access direct messages sent to the user. You indicate the needed permission level when you register your Twitter application. The application's consumer key and secret key should be stored securely, because they're necessary for coding.
As mentioned, a Twitter application is simply a means to automate some basic Twitter operation, and any Twitter operation (read, write, direct messages) is performed by a given user. So the next step is to associate one or more Twitter accounts with the application. The way in which this task is organized depends mostly on the intended use of the host application. Let's examine a couple of scenarios.
A classic example is when your host application is designed to be a Twitter client. In this case, the application will work with a single Twitter account at a time, but the account might change several times during a single session. It's the classic login pattern: The logged-in user takes full control of the application, and the application holds the user's credentials. Once the user logs out, the application forgets the user's credentials and is ready to work for another user. A user logs in with a Twitter application by entering his or her Twitter credentials and explicitly authorizing the application to perform declared operations (read, read-write, direct messaging), as shown in Figure 2.
Figure 2: User Bob authorizing a Twitter app to operate on his account
It should be noted that the neither the Twitter application nor the Windows host application is ever allowed to know your Twitter password, and they're never allowed to change it. However, the Windows host application will know your username and, more importantly, will get a hash of your credentials. You can revoke access to your account for any previously authorized Twitter application at any time. You do so by opening the Settings panel of your Twitter account, as shown in Figure 3. Revoking access will immediately invalidate any hash of your credentials that any Windows app or website hosting the Twitter application might have cached.
Figure 3: Revoking an application's access to a user's Twitter account
Another scenario is when the host application is designed to work with only a few fixed accounts. If your purpose is to tweet changes detected on a given feed (say, an RSS news feed), then you'll likely do so on behalf of some account(s) of yours or accounts that belong to your customer. In this case, there's no need to log in and log out; the hash value of the account credentials is usually stored permanently so that the app can be started and stopped at any time. Revoking access, however, works just as usual.
As the author of the host Windows application (or website), how would you obtain the hash of an authorized Twitter account? The hash takes the form of two strings, known as the access token and the token secret. Note that access token and token secret are application specific. To obtain them, you need to force Twitter users to log in from within the application.
This isn't an issue if you're writing a Twitter client application -- your users will need to log in anyway. But if you're writing a background Twitter application, forcing a login every time an update is tweeted might be too expensive. In this case, you can authenticate users once, get their access token and token secret, and store them permanently to disk. From the standpoint of the background Twitter application, secrets are just constant strings.
Pushing an Update
You're now ready to create a new website or even a console application, reference the TweetSharp library, and build any user interface you need. The interaction between your host application and the Twitter back end begins with the following code:
var twitterApp = new TwitterService(App_ConsumerKey, App_ConsumerSecret);
TwitterService is a TweetSharp class that takes the keys of the Twitter application and returns a root object to work with.
The next step is to instruct the Twitter application to operate on behalf of a given user. As I mentioned, the user is represented by a pair of strings: access token and token secret. These strings are obtained as hash strings from the actual username and password of the Twitter account the application will operate for, by using the following code:
// access-token and token-secret are obtained out of Twitter authenticationtwitterApp.AuthenticateWith(accessToken, tokenSecret);
At this point, the Twitter application is fully configured to operate on behalf of the specified user. To send a tweet, all you need to do is prepare the text and invoke the SendTweet method, as follows:
var twitterStatus = twitterApp.SendTweet(text);
There are many reasons that a tweet might fail. Common reasons are the length of the tweet text or an invalid authorization. However, note that Twitter denies two tweets containing exactly the same text from the same user. This problem is less likely to happen when tweets come from people, but it's fairly common with software both during tests and when background services are in place to monitor feeds. In any case, a look at the response you get from SendTweet is in order.
The return value from SendTweet is an object of type TwitterStatus, which represents a tweet. Its properties are Id, TextAsHtml, Author, Location, and others. If you want to know more about what might possibly have gone bad with the tweet, you can do so using the Response property:
var twitterStatus = twitterApp.SendTweet(text);var responseText = twitterApp.Response.Response;
The Response property is a string property and is set to OK if everything worked fine. Otherwise, it contains a JSON object with two properties: error and request. The error property contains a detailed description of what went wrong and represents a more specific message to show through the user interface or to report in logs. Here's a way to deal with errors:
TwitterError error = twitterApp.Deserialize(service.Response.Response);
In a way, a tweet operation is idempotent in the sense that you can perform the same operation 10 times and the final effect is always the same: Only one tweet is made. However, I recommend you keep under strict control the number of tweets you attempt from an application and apply some application-level logic to prevent multiple tweets of the same text. Note that Twitter applies some rate limits to the programmatic use of the API for all operations. As far as updates are concerned, an account is limited to 1,000 per day and retweets are counted as regular tweets. For more information, read the "About Twitter Limits" page in the Twitter Help Center.
Retweeting a Tweet
Retweeting a tweet programmatically is as easy as doing so manually. You need to get the ID of the tweet and pass it to a new function. You get the ID of a tweet from its TwitterStatus object that TweetSharp provides you. Any tweet you handle via TweetSharp is represented with a TwitterStatus object, which includes the ID property. This is the case whether you retrieve the tweet from the timeline or by using a hashtag query. If you intend to tweet from account A and, at the same time automatically retweet from account B, then the TwitterStatus of the original tweet will give you the ID to retweet. Here's the code you need to accomplish this:
twitterApp.AuthenticateWith(accessToken, tokenSecret);var twitterStatus = twitterApp.SendTweet(id);
As a final note, consider that when using TweetSharp you can easily perform multiple Twitter operations on behalf of different accounts. To switch accounts, you place a call to the AuthenticateWith method. To identify an account, you can't use the username and password directly; instead, you must get a pair of strings (access token and token secret), which are generated on a per-application basis from the original credentials of the Twitter user.
Enrich Your Apps with Twitter
More and more, developers are making standard applications (desktop, mobile, websites) richer and more functional by integrating the ability to tweet their status and retweet other content. The information I've provided here -- the basics of setting up a host application that tweets and retweets on behalf of Twitter users -- should help you add a useful social capability to your applications.
Dino Esposito is a trainer and consultant specializing in web, social, and mobile integrated architecture and effective code design principles and practices. He's the author of Programming Microsoft ASP.NET 4 and Programming Microsoft ASP.NET MVC3 (Microsoft Press).
Twitter: @despos
Learn more about using Twitter in applications:
Read more about:
MicrosoftAbout the Author
You May Also Like