Friday, 3 April 2009

Quick C# Twitter API

Quick little class I knocked together to do 2 basic functions in twitter but can easily do more. Add this to a cmdlet in powershell or command line app to integrate with anything else!!

///
/// Twitter.cs
/// A simple C# class with 2 basic methods, add away with other methods-
/// http://apiwiki.twitter.com/REST+API+Documentation#statuses/update
///

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Collections.Specialized;
using System.Web;

namespace Net.Ant.Twitter
{
public class Twitter
{
protected string _username;
protected string _password;

/// <summary>
/// Creates a new instance of the Twitter API class
/// </summary>
/// <param name="username">Your Twitter username</param>
/// <param name="password">Your Twitter password</param>
public Twitter(string username, string password)
{
_username = username;
_password = password;
}

#region Twitter API functions

/// <summary>
/// Sends a private message
/// </summary>
/// <param name="user">User to message</param>
/// <param name="text">Message text</param>
public void SendMessage(string user, string text)
{
NameValueCollection col = new NameValueCollection();
col.Add("user",user);
col.Add("text",text);
HttpPOSTRequest("http://twitter.com/direct_messages/new.xml", col);
}

/// <summary>
/// Tweet/Update!
/// </summary>
/// <param name="message">Message text</param>
public void Tweet(string message)
{
NameValueCollection col = new NameValueCollection();
col.Add("message", message);
HttpPOSTRequest("http://twitter.com/statuses/update.xml", col);
}

#endregion

#region Internal functions for HTTP requests

/// <summary>
/// Make a call to the twitter website, will used the username/pass in the class
/// </summary>
/// <param name="url">The URL to request</param>
protected string HttpPOSTRequest(string url,NameValueCollection post_parameters )
{
HttpWebRequest req = (HttpWebRequest) WebRequest.Create(url);
req.Credentials = new NetworkCredential(_username, _password);
req.PreAuthenticate = true;

string postData = PostEncodeArray(post_parameters);

req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postData.Length;
using(Stream writeStream = req.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(postData);
writeStream.Write(bytes, 0, bytes.Length);
}

// make request
string result=string.Empty;
using (HttpWebResponse response = (HttpWebResponse) req.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader (responseStream, Encoding.UTF8))
{
result = readStream.ReadToEnd();
}
}
}
return result;
}

/// <summary>
/// Posts the supplied data to specified url.
/// </summary>
/// <returns>a string containing the result of the post.</returns>
protected string PostEncodeArray(NameValueCollection m_values)
{
StringBuilder parameters=new StringBuilder();

for (int i=0;i < m_values.Count;i++)
{
if (parameters.Length != 0) parameters.Append("&");
parameters.Append(m_values.AllKeys[i] + "=" + HttpUtility.HtmlEncode(m_values.Get(i)));
}
return parameters.ToString();
}
#endregion
}
}