Coding the Tweet: Building a Custom Branded Twitter Application

UPDATE: The Coding the Tweet demo application and source code have been updated to support PIN-based authorization through oAuth.

With millions of users and an ecosystem saturated with over 700 custom applications, Twitter’s all the rage these days. Love it or hate it, Twitter has become a powerful medium for connecting with people and marketing your skills to a wider audience. As the saying goes:

Twitter marches on.

The popularity of the Twitter platform means that Twitter users have the luxury of choosing from an army of custom websites and desktop applications (my personal favorite is TweetDeck) allowing them to tweet, browse, and search Twitter in new and ever-so-trendy ways. And one of the clever but often-overlooked features of Twitter is that it upgrades these custom applications to first-class citizens within the Twitterverse by tagging each tweet with the hyperlinked name of the tool or medium used to create the tweet:

 

These attributions serve as a gentle encouragement for builders of Twitter tools, as well as a way to get the word out about the latest and greatest Twitter apps, and they even (in my opinion) help foster a sense of exclusivity. It’s a little silly, but what can you do? Twitter psychology is a powerful and subtle thing.

Vanity Plates

So everybody has their favorite Twitter tool, and power-users tend to gravitate towards the more powerful and/or newer tools, and it’s a win-win-win for all concerned: for Twitter, for Twitter users, and for the builders of Twitter tools. And as it turns out, it’s actually pretty easy to build your own custom branded Twitter application in case you want to join in on the fun.

Registering a Custom Twitter Application

Building a bare-bones Twitter client will take you all of about an hour. First, sign into your Twitter account and register a new custom application. Here’s mine:

Enter the details for your custom application, making sure to specify (for the purposes of this demo):

  • Application Type: Client
  • Default Access Type: Read & Write

Save those settings and you’ll be presented with a page containing some authorization/authentication magic for your custom Twitter application. Make a note of your consumer key and consumer secret, as we’ll be plugging those in shortly. (And it’s okay if you have no idea what these are used for.)

At this point, you’ve registered your custom application with Twitter. The only problem is, your custom application doesn’t actually exist yet. Let’s fix that.

A Bare-Bones Twitter Client

You can build a custom Twitter app using just about any language in existence, as a desktop application or a web application. We’ll implement ours as a desktop application using C# and .NET, but if you’d rather go another route, the Twitter API wiki contains tutorials and sample code in different languages.

Our bare-bones Twitter application will have the following functionality:

  • The ability to allow you to post tweets from your custom Twitter application, tagged with the details you specified above.
  • Integration with oAuth, the recommended Twitter authentication mechanism.

It will feature the simplest possible user interface:

The first time you run the client, click the Configure button and cut-and-paste the Consumer Key and Consumer Secret you were given when you registered your custom application and hit the “Get PIN!” button.

Twitter application settings

Your default web browser will open and you’ll see a message similar to the following.

Click the “Allow” button. Once you’ve done this, and you’ll only have to do it once, you’ll be given a PIN:

Enter your pin in the Coding the Tweet settings and click Authorize!

You can then use the appication to post tweets tagged with your custom application name and hyperlink.

The Source Code

You can download the complete source code for the above “generic Twitter” application so you can take a look at what’s going on under the hood. Once all the authentication and authorization stuff is out the way, sending a tweet is as simple as:

// URL-encode the tweet…
string tweet = HttpUtility.UrlEncode(txtTweet.Text);
// And send it off…
string xml = _oAuth.oAuthWebRequest(
    oAuthTwitter.Method.POST,
    “http://twitter.com/statuses/update.xml”,
    “status=”+tweet);

The authentication-related code is slightly more complex (but not much). Essentially, we’re going to execute the following steps. These only have to be performed once:

  1. Accept the Consumer Key and Consumer Secret from the user.
  2. Ask Twitter for the URL of the “authorize this application” page on Twitter.
  3. Open the default web browser and navigate to that page.
  4. Allow the user to specify the PIN he was provided by Twitter.
  5. Bundle this PIN in the call to the http://twitter.com/oauth/access_token API.
  6. Store the returned access_token for future use.

That’s really all there is to it. You now have a custom branded (if somewhat bare-bones) Twitter client which will tag each of your tweets with your URL of choice. The above code can easily be expanded to provide additional functionality or even turned into a full-fledged Twitter client. It can also be very easily converted to a web-based paradigm.

(Thanks to Shannon Witley and Eran Sandler for implementing the oAuth wrapper class to handle the sometimes-pesky details of oAuth authentication.)

Comments

  • Steve J. says:

    Man I am loving this. I’ve ALWAYS wondered how they get those branded links in there. Will be trying this immediately. *Great* article.

  • Anonymous says:

    I’ll be smacking down with the ‘Hammer of Unyielding Awesomeness’ shortly. I put together a simple Twitter demo (using basic auth) a couple weeks ago. I actually came across the oAuth class but couldn’t get it to work in a desktop scenario. I’ll be interested to see how you did it.

    (Assuming I can procrastinate at work this fine morning…uggh)

  • EVH says:

    Nice effort, and well-written, but C# and .NET are terrible languages for this sort of thing. .NET is hardly even capable of doing this properly and in the marketplace you’ll see that practically nobody uses C# for this sort of web interactivity. PHP/Ruby/etc. are the *only* way to do web-related stuff properly. This is becoming clear now that ASP.NET has such a puny market share compared to other languages.

  • ehsanul says:

    Hmmm, isn’t the info on how to do this easy to find? I suppose this post might help some people looking for a clear, step by step guide. The oAuth stuff is a little new for twitter.

    I’ve been meaning to try and implement a twitter bot (non-spammy of course), in Python, half because I want to learn the language, and half because I want a crack at the twuring test - http://www.squidoo.com/twuring

  • Daniel Stutzbach says:

    I registered a twitter application and tried Coding the Tweet. Everything seems to work fine, but twitter shows the tweet as "from the web" even though I sent it using Coding the Tweet. Any ideas?

  • JeremyX says:

    :Daniel I tried the same thing. Did you register the application as a desktop app or a web app? And did you authorize the app.

  • JeremyX says:

    "in the marketplace you’ll see that practically nobody uses C# for this sort of web interactivity"

    @EVH Uh… no.

    http://news.netcraft.com/archives/2009/04/06/april_2009_web_server_survey.html

  • Daniel Stutzbach says:

    JeremyX: As a Desktop app, and, yes, I authorized it.

  • Coding the Wheel says:

    Daniel, if this is just a test version of your twitter app, send me the consumer key/secret (you can regen these after) to james AT codingthewheel.com. Curious to know what the issue is.

  • Coding the Wheel says:

    [i]>Hmmm, isn’t the info on how to do this easy to find?[/i]

    Yes.

    Well, it’s easier to find for other languages. I could only find a few examples for .NET/C# and none of them really went through all the steps. And I couldn’t find a single working example of how to build a *desktop* Twitter app with C#.

  • Coding the Wheel says:

    @EVH: You’re fired. Fired from this blog.

  • Ed K. says:

    I totally see the point of this post. I’m going to take your source code and add a regular-expression Twitter search feature to it.

    Maybe we can bootstrap this thing into an open-source Twitter app.

    And I think EVH was trolling. Anybody with half a brain knows ASP.NET is quickly becoming the dominant web paradigm.

  • Poker Forum says:

    I just started using Twitter and I have to say I love it. It’s a great way to update people on how I’m getting on during my poker… Even if it’s going really badly.

  • Daniel Stutzbach says:

    I’m not sure what changed, but everything works fine now. Twitter correctly shows my application name instead of "web".

  • Morder says:

    Does it have to be a desktop app to get the name to show up instead of "web"?

  • Coding the Wheel says:

    [i]>Does it have to be a desktop app to get the name to show up instead of "web"?[/i]

    No. The attribution should show regardless of whether it’s a desktop or web app. It may take a while for it to percolate through the system. (Just make sure the custom application settings on Twitter correctly identify the type of application.)

    The [url=http://apiwiki.twitter.com/OAuth-Examples]Twitter API Wiki has oAuth examples in PHP, Python, Ruby, and .NET[/url], most or all of which are web-based.

  • DIY FTW! says:

    I can verify that the application works. Quite simple. Ghanks for laying it all out. Not sure how I’m going to use this but I will use it. Can’t believe there’s not more .NET-related information for Twitter. That page you linked to which is also linked from the Twitter API wiki is very sparse.

  • spankster says:

    Thanks for the application.

    I have tried as well and it just says "web" when I submit a tweet. Then, suddenly, it began to work!

    So, encouraged, I registered a new app and deleted the old one (which was for testing), and it hasn’t worked since. I’m not saying it’s your program - because it DID work - it must be something wrong on Twitter’s end but I’m not sure what.

  • Coding the Wheel says:

    [i]>So, encouraged, I registered a new app and deleted the old one (which was for testing), and it hasn’t worked since.[/i]

    @spankster, it looks like there’s some latency between registering a custom application and having its updates appear with the proper attribution. Also, the custom app authorization page on the Twitter side is a little finicky. Did you reset all your settings (in the Coding the Tweet sample app) and cut-and-paste your new consumer key/secret? Were you able to authorize the new application through the Twitter authorization page? If yes, and provided we’re not in one of those windows where the Twitter team is working the kinks out of oAuth or the custom app registration process, everything should work.

  • Morder says:

    @James Devlin, Thanks. It took a long time before it started working. :)

  • Cristovao Morgado says:

    Hi! I’ve been studing your code, but if I use special characters its always fails with a HTTP 401… can you help?

  • Aditya says:

    Hi, when I enter my keys and save, the app crashes with 401 failure. Whats the reason?

  • D. says:

    Aditya, I am getting the same error.

  • Thomas says:

    thanks for this application. As far as I understand, Twitter just introduced a PIN based OAuth sytems, which means that the application doesn’t work anymore. The user must be prompted to enter the 6digit pin. Did you consider implementing a solution for that?

  • Eray Basar says:

    here are infos on the new rules for callbacks: http://groups.google.com/group/twitter-development-talk/browse_thread/thread/472500cfe9e7cdb9/da10ad671877eaca?lnk=raot&pli=1

  • Cristovao Morgado says:

    it still works without the PIN need!
    I’ve fixed a bug with GET requests.. I was trying to get mentions and found it:

    public string WebRequest(Method method, string url, string postData)
    {
    HttpWebRequest webRequest = null;
    StreamWriter requestWriter = null;
    string responseData = "";
    if (method == Method.GET)
    url += "&" + postData;

  • denkmalschutz immobilien says:

    Can anybody confirm if this works without the PIN? I dont think so…
    @cristovao is this a fix for the pin-related "bug"?

  • Bokkie says:

    Any update on the pin code thing leading to the 401 error?

  • Coding the Wheel says:

    The 401 error has been resolved. You need to bundle the PIN (specified by the user after being directed to Twitter for authorization) as the oauth_verifier parameter when you call the /oauth/access_token method. I’ll post the updated code shortly~

  • adam says:

    Hi, does anyone know if you register a app name with twitter, are you able to change it later down the line without having to go through the whole process? would it be straight forward?. I have a twitter app at the moment and would like to use oauth so my current app name appears from tweets sent via it but i would be changing the name if a few weeks so not sure what i should do.

    Any advice would be much appreciated.

    Thanks
    Adam

  • Coding the Wheel says:

    Adam: Yes you can change the app name. Log into Twitter. Click ‘Settings’. Go the the ‘Connections’ tab. In the sidebar click the ‘Developers can edit the registration settings for their applications here.’ Then click the name of your application. Then click the ‘Edit Application Settings’ button.

  • adam says:

    Hi James,

    Thanks for your help, Much appreciated :)

    Adam

  • Cristovão says:

    Nice, all is working 100% !!! Congrats!

  • Bryan says:

    Anyone know how to list all the users who are using the app?

    I have the OAuth working, and it shows the number of users who have registered it but I can’t see anyway to list these uses. It would be nice to get some feedback from them.

    Thanks

  • Andrei says:

    Are those keys "sensitive data"? Can I just store it in app settings and use it for user request for tokens?

  • Ujjwol says:

    Works perfectly…

  • Coding the Wheel says:

    Andrei - yes, those keys ARE sensitive data. Or rather, the token you use in subsequent API requests is sensitive, and should be stored in a local encrypted store.

    See:

    http://apiwiki.twitter.com/Security-Best-Practices#DesktopApplicationSecurity

  • Gus says:

    I’ve been coding a OAUTH class for my Twitter app, and i cant make the API calls , its says

    "Something is technically wrong.
    Thanks for noticing—we’re going to fix it up and have things back to normal soon."

    thats the return for my api calls, what am i doing wrong?

  • Tobi says:

    Hello,
    i cannot send a tweet with a special charater in it. I always get Unauthorized message. For example, try to tweet a "*" (asterisk) oder a ~ (tilde) or something like german "ä". Can you tell me, how to fix this??

    Thank you very much!

  • Tobi says:

    sorry my fault, it works, BUT:
    if i try to send more than one german special character for example "äääää", then not all characters are sent to twitter. or i get unauthorized message if i try to sent "dsdfögüsdgöäsdfg".

  • Helen Neely says:

    Thanks alot for this awesome article and code. I will be hacking out a client app myself to see how well I’ll perform. Your article is a nice head start for anyone serious about developing a Twitter client.

    Thanks again -
    Helen Neely

  • vkamdar says:

    HI,
    Thanks for your code. Your code is awesome. We have just get help from it for our web application.

  • ibito says:

    What about special chars like áéíóú??? I can’t make it to work…

  • Yann ALET says:

    Thanks for this great job, but things goes wrong when you start working with unicode characters éàèù ect ….
    Obviously lots of people experienced this problem
    http://groups.google.com/group/twitter-development-talk/browse_thread/thread/111e7b86133efcaf
    http://code.google.com/p/twitter-api/issues/detail?id=433
    They fixed it for the PHP API, but can you do the same for the .net version ?

    Thanks again for this great job :)

  • Heidi says:

    Hey, what a great article - i love it!
    I´ve just tried it and it works fine, but as said above special chars cause a 401 Error. Is there any fix for that?!

    Thanks and regards
    Heidi

  • Rihards says:

    Great post! Had it all up and running in matter of minutes. Brilliant, and thanks again :)

  • BelugaNeil says:

    Thanks this really helped. Complete code that actually works first time. I also now understand what is going on with OAuth.

  • Vladimir says:

    Hi everybody, sorry that i have to ask something of-the-record but i read this post and find it very usefull and important. The thing i wanted to ask you is that I’m building web app for taking surveys - marketing kinda survey resear ch - and i saw from others, bigger ones that they have their “own” Twitter API for those surveys (i’mean when they distribute results) - now - I don’t understand why like zoomerang.com has to have own Twitter API and how it benifit to them and most important IS THIS CORRECT SUBJECT RELATED TO MY QUESTION? is this tutorial what I acctually need or I should look for some different Twitter API for my Survey just as http://www.zoomerang.com does it?? Please reply to this address anytime you or someone is available and can help me. Thanks a million!

  • Vladimir says:

    Just to ADD TO CONVERSATION ABOVE THAT I JUST WROTE AND FORGOT TO ASK ONE THING. here is the list of very useffull twitter API, etc. http://www.newwebplatform.com/tips-and-tutorials/Twitter/ - is there n the list any of the subjects related to my question/issue - Imean i ask which is the best way to make twitter API for my surveys like collegur zoomerang.com - s from all of this examples at v which should I chose. Sorry for of-the-subject questions but i didn’t had nobody else to ask. Thanks

  • Amit Banerjee says:

    Does not works. I keep getting the error message as:

    “An error occurred during authorization. Did you providede a valid consumer key?”

    I know the consumer key and secret are right and I have tried several times to no success.

  • Anonymous says:

    “Nice effort, and well-written, but C# and .NET are terrible languages for this sort of thing. .NET is hardly even capable of doing this properly and in the marketplace you’ll see that practically nobody uses C# for this sort of web interactivity. PHP/Ruby/etc. are the only way to do web-related stuff properly. This is becoming clear now that ASP.NET has such a puny market share compared to other languages.”

    EVH - sometimes it’s better to say nothing and let people think you don’t know anything, rather than saying something and everyone *knowing* that you don’t know what you’re talking about. That really was a silly and uninformed post.

  • Eric Waideman says:

    Works fine!!

    I’m trying to learn more about OAuth, Can this app be modified to send the username and password and get the PIN without use browser??? My intention to learn better is port this application to run on Windows Mobile 6.5…

    Regards!

  • Steve says:

    For some reason I’d got it into my head that submitting that “register a custom app” form would lead to a manual review, and wondered how I’d go about testing my code without a consumer_key, or how I’d submit a custom app that I hadn’t tested.

    And then I see your post and realise it’s instantaneous.

    D’oh.

    So, thanks!

  • Coding the Wheel says:

    @Eric: I’m not sure, I haven’t looked at this stuff in months.

    @Steve: You’re welcome and good luck!

  • Truestory says:

    Works great. Is there a similar program I can get for my blackberry?

  • tommy says:

    thanks :)
    i was learning about twitter api’s, and your tutorial is awsome.

  • Tommy says:

    Just keep getting the 401 error i am using correct keys so looks like it is on your end

  • santhosh says:

    Thanks Sir, and it is a very good explanation.
    Actually I also got solution like this. But i want to build complete twitter application for desktop users. So configuring become a problem. Suppose if i create consumer key, consumer secret , access token and access token secret. It works only for my twitter account. I am not understand,
    Is it necessary to create every user configure there own key s … Please help me. I am lacking with this problem .

  • tuz says:

    Daniel I tried the same thing. Did you register the application as a desktop app or a web app? And did you authorize the app…

  • JJYates says:

    Okay, so whatever coding language you decide, great. But I’m not clear on what this does for your brand. Is it just used for SEO purposes? Twitter power is subtle, and I don’t want to miss out. JJ|click here

  • AK John says:

    I am working on a project where we want our application to post public notices to several mediums, automatically. Of course, Twitter is one of those mediums. We have an account and such, but can I make it so my users do not have to enter the user name and password for the Twitter account? I just want them to push a button to post the notice and it “magically” posts to Twitter, et al. My user base does not have the user name and password and we don’t want to distribute it out. I appreciate any insight on this.

  • balaji says:

    Hi every one following code is working xxxxxxxx.xml is web site name its like
    http://www.google.com that xml file is google.xml

    String xml = wc.DownloadString(“http://twitter.com/statuses/user_timeline/XXXXXXXX.xml?count=2″);

    DataSet ds = new DataSet();

    ds.ReadXml(new StringReader(xml));

    if (ds.Tables["status"] != null && ds.Tables["user"]!=null)
    {
    Response.Write(ds.Tables["status"].Rows[0]["created_at"].ToString()+” “);
    Response.Write(ds.Tables["user"].Rows[0]["name"].ToString() + “
    “);
    Response.Write(ds.Tables["status"].Rows[0]["text"].ToString() + “
    “);
    Response.Write(ds.Tables["user"].Rows[0]["description"].ToString() + “
    “);
    }

  • Kundan says:

    The ever best custom app i have seen for twitter.

    Its awesome….

    Thanks a lot

  • Lek says:

    Thank you for doing this!
    I can’t wait to put it into my app !!

  • Garry @ TriSys says:

    Thanks for posting this code, which worked really well first time around.

  • Mike says:

    You should create something which will allow ALL of our tweets to be branded. :)

    Maybe one day…

  • shubham says:

    hello ..sir .i m not getting PIN in reverse…..whats may be the reason for that..thnx

  • Quinton says:

    This is fantastic. Thank you for the guidance and great piece of code.

  • Shawn says:

    Using Twitter to promote a business is extremely popular today. I actually found a place to train my martial arts when a friend of mine retweeted a tweet about Indianapolis BJJ that caught my interest. I signed up a week later for classes. See, Twitter marketing does work.

  • Sean says:

    I had been searching for a way to brand tweets with a personal URL. Thank you. I got it to work on my second try. Is the actual tweet the only thing we can brand using your process or can the words “Generic Twitter Client (by Coding The Wheel) be changed also. And if so, How? If not, Thanks again for your time.

  • Andaman & Nicobar says:

    Andaman & Nicobar
    Where else could anyone get that kind of information in such a complete way of writing? I have a presentation incoming week, and I am on the lookout for such information.

  • meet and greet says:

    Thank you for another significant article. Where else could anyone get that type of information in this complete way with words? I’ve got a presentation incoming week, and I am on the lookout for similarly info.

  • keegs says:

    This is the first article I’ve came across which has explained what’s happening *clearly*, and the sample application has compiled and worked without importing multiple references. Thanks for an awesome article.

  • Leave a Reply