Category Archives: Twitter API

Update To The YOURLS – Twitter – Google Reader Script

I recently blogged, Using YOURLS And The Twitter API With Google Reader’s Custom SendTo Link. Since then, I have made a few improvements to the script, mostly in the error-trapping line.

  • I broke out the variables for the YOURLS API signature, plus the Twitter API consumer key, consumer secret, access key and access secret, and converted them to constants.
  • I removed urldecode() from the formation of the YOURLS API request. It’s not necessary.
  • I have added code to trap any errors in when making the short URL.
    • I am now getting the statusCode and message node contents, in case something goes wrong with the shortening.
    • I set the script to die on a URL shortening error, which is determined by the short URL being an empty string or the statusCode node having a value other than 200.
    • The code, coupled with the message, should explain any problems adequately enough to debug shortening issues. If you find you are getting zero-length responses from your URL shortening, that’s probably due to a server misconfiguration; possibly from bad mod_rewrite rules, possibly due to a messed-up cookie on your PC.
  • I strip HTML tags from the title.
    • I discovered today that some Google Reader items will have HTML markup in their titles, such as <em>.
  • I check for failure in the Twitter API request.
    • TwitterOAuth will return Boolean false if it could not complete its curl request to the API, and will return an XML document in any other case, including failure of the tweet to go through.
    • If the cUrl request is good but the tweet doesn’t go through, Twitter responds with an HTTP status code other than 200. We can capture the last status code returned by our request, test it, and print the XML response describing what happened.

Continue reading

Using YOURLS And The Twitter API With Google Reader’s Custom SendTo Link

Update, January 3, 2011: There is a revision of this script at http://www.dougv.com/2011/01/03/update-to-the-yourls-twitter-google-reader-script/.

I love me some Google Reader. As I noted in the past, now that I understand it, I don’t know how I ever managed to get by without it.

One of my favorite Reader features is the ability to send a link of the content to several social media sources, such as Facebook, Twitter, Digg, Reddit and more. Even better, you can create a custom link to which you’d like to send Reader items.

I use a custom install of YOURLS to shorten links, in part because there have been some scares surrounding the long-term viability of many online link shorteners; in part, because I don’t like trusting that these link-shortening services won’t hijack my links, employ interstitial ads or do bad things with the data they collect; and in part because I want to see link-click statistics myself, including the underlying data.

Thanks to the custom link option in Reader, coupled with the Twitter API, I’ve come up with a PHP script that effectively replaces the built-in Twitter send to link in Reader, allowing me to use my install of YOURLS and to post automatically. (The Reader send to Twitter link actually opens the Twitter home page, pasting the title and Google-shortened link into the status tweeting box at the top of the page.)

Continue reading

Shortening URLs With The bit.ly API Via ASP.NET

After yesterday’s post on using the Twitter API to post status updates on Twitter from an ASP.NET application, a follower of my client suggested using a URL shortening service to link to the articles headlines being posted as tweets.

That was an excellent idea of which I should have thought in the first place. And thanks to the extreme simplicity of the REST-like bit.ly API, shortening URLs is as simple as sending a request URL laced with querystring variables.

So here is a quick and simple ASP.NET subroutine, written in VB.NET, to shorten URLs with the bit.ly API:

Sub BitlyIt(ByVal strUser As String, ByVal strAPIKey As String, ByVal strLongUrl As String)
	'This subroutine requires your page to have a label control named lblStatus

	'build URL to shorten method resource
	Dim strUri As New StringBuilder("http://api.bit.ly/shorten?")
	strUri.Append("version=2.0.1")
	'we want to get an XML response back from bit.ly, not the default JSON
	strUri.Append("&format=xml")
	strUri.Append("&longUrl=")
	strUri.Append(Server.HtmlEncode(strLongUrl))
	strUri.Append("&login=")
	strUri.Append(Server.HTMLEncode(strUser))
	strUri.Append("&apiKey=")
	strUri.Append(Server.HTMLEncode(strAPIKey))

	'create request for shorten resource
	Dim objRequest As HttpWebRequest = WebRequest.Create(strUri.ToString())
	'since we are passing querystring variables, our method is get
	objRequest.Method = "GET"
	'act as though we are sending a form
	objRequest.ContentType = "application/x-www-form-urlencoded"
	'don't wait for a 100 Continue HTTP response from bit.ly
	objRequest.ServicePoint.Expect100Continue = False
	'since we are using get, we need not send a request body; set content-length to 0
	objRequest.ContentLength = 0

	'we need to capture the XML being sent in response
	'read the response into a new XML document
	Dim objResponse As WebResponse = objRequest.GetResponse()
	Dim objXML As New XmlDocument()
	objXML.Load(objResponse.GetResponseStream())

	'the response will have three node values we're primarily interested in
	'the errorCode node will contain a numeric error code; 0 means success
	Dim nErrorCode As XmlNode = objXML.SelectSingleNode("//errorCode")
	'if there was an error, the errorMessage node will contain a user-friendly message useful for debugging
	Dim nErrorMsg As XmlNode = objXML.SelectSingleNode("//errorMessage")
	'if all went well, shortUrl will contain the full short URL created for our link
	Dim nShortUrl As XmlNode = objXML.SelectSingleNode("//shortUrl")

	'if we didn't get an errorCode value of 0, there was a problem; report the user-friendly message
	'on success, report the short URL for our resource
	If nErrorCode.InnerText <> "0" Then
		lblStatus.Text = "Error returned. Code: " & nErrorCode.InnerText & "; Message: " & nErrorMsg.InnerText
	Else
		lblStatus.Text = nShortUrl.InnerText
	End If
End Sub

Continue reading

Posting Status Updates (Tweets) To A Twitter Profile Via ASP.NET

Update, 16 Feb 2011: Please note that this routine will no longer work with the Twitter API. It is retained solely to prevent negative search engine rankings.

I have a client that posts several news stories to its Web site every day. So it makes tremendous sense for them to post the headlines to Twitter as tweets, so that followers might be informed of breaking news, or just what’s new on the site.

The Twitter API makes posting status updates (tweets) to Twitter as simple as invoking a WebRequest. Unfortunately, most of the ASP.NET examples on the Web that aim to show you how to post status updates are either written in C#, have coding errors, simply will not work, or all three.

So here’s a simple VB.NET subroutine that will post tweets.

Sub TwitIt(ByVal strUser As String, ByVal strPass As String, ByVal strMessage As String)
	'this subroutine requires your ASP.NET page to have a label control with an ID of lblStatus

	'create post variable for tweet
	Dim strTweet As String = "status=" & Server.HtmlEncode(strMessage)
	'convert post variable to byte array for transmission purposes
	Dim bRequest As Byte() = System.Text.Encoding.ASCII.GetBytes(strTweet)

	Try
		'create HttpWebRequest to status update API resource
		Dim objRequest As HttpWebRequest = WebRequest.Create("http://twitter.com/statuses/update.xml")
		'pass basic authentication credentials
		objRequest.Credentials = New NetworkCredential(strUser, strPass)
		'set method to post and pass request as a form
		objRequest.Method = "POST"
		objRequest.ContentType = "application/x-www-form-urlencoded"
		'tell the server it will not receive a 100 Continue HTTP response
		objRequest.ServicePoint.Expect100Continue = False
		'set content length of request
		objRequest.ContentLength = bRequest.Length

		'capture the stream (content) of the request
		Dim objStream As Stream = objRequest.GetRequestStream()
		'put the bytes into request
		objStream.Write(bRequest, 0, bRequest.Length)
		'close the stream to complete the request
		objStream.Close()

		'uncomment line below to report success
		'lblStatus.Text = "Tweet sent!"

		'You can also capture the XML response Twitter sends back
		'uncomment lines below to capture responses
		'Dim objResponse As WebResponse = objRequest.GetResponse()
		'Dim objReader As New StreamReader(objResponse.GetResponseStream())
		'lblStatus.Text = objReader.ReadToEnd()

	Catch ex As Exception
		'uncomment line below to report ASP.NET errors
		'lblStatus.Text = ex.Message
	End Try
End Sub

Continue reading