Out-Twitter

I finally finished my version of a PowerShell Out-Twitter function. This allows me to send a quick tweet directly from the PowerShell console. The original and inspiring Out-Twitter can be found at http://cid-5dec3b62d9308943.skydrive.live.com/browse.aspx/PowerShell%20Scripts/Twitter. My version will used cached credentials, check for tweet length and replace any URLs with Snurl’d URLs.

Here’s the function, which is also attached.

#Out-Twitter.ps1
#v1.0  June 23, 2008

#Jeffery Hicks
#blog.sapien.com

#Originally downloaded from
#http://cid-5dec3b62d9308943.skydrive.live.com/browse.aspx/PowerShell%20Scripts/Twitter

Function Out-Twitter {

    BEGIN {
            #check for global Twitter credential
            if (!$global:Twitter_Credential) {
                $global:Twitter_Credential=Get-Credential
                }
    }

    PROCESS {
        #turn off error pipeline
        $erroractionpreference="SilentlyContinue"
        [string]$tweet=$_


        Function Get-Snurl {
            Param([string]$link="
http://www.google.com")
            $webclient=New-Object Net.WebClient
            $url="
http://snipurl.com/site/snip?r=simple&link=$link"
            $response=$webclient.DownloadString("$url")
            write $response
    }   
        #search for web links using Regex
        [regex]$regex="(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?"
         If ($tweet -match $regex) {
                  $link=$matches[0]
          }
         #if an embedded url was found, convert it to a snurl link
         if ($link) {
            $snurl=Get-Snurl $link
            $tweet=$tweet.Replace($link,$snurl)
         }
        if ($tweet.Length -gt 140) {
            Write-Warning ("Your message is " + (($tweet.length)-140)  + " characters too long.")
            $clear=$True
            return
        }
        $url = "http://twitter.com/statuses/update.xml"
        $data = "status={0}" -f $tweet
        $request = [Net.WebRequest]::Create($url)
        $username=$global:Twitter_Credential.GetNetworkCredential().Username
        $password=$global:Twitter_Credential.GetNetworkCredential().Password
        $request.Credentials = New-Object System.Net.NetworkCredential($username,$password)
        $request.ContentType = "application/x-www-form-urlencoded"
        $request.Method = "POST"
        $bytes = [System.Text.Encoding]::UTF8.GetBytes($data)
        $request.ContentLength = $bytes.Length
        $requestStream = [System.IO.Stream]$request.GetRequestStream()
        $requestStream.write($bytes, 0, $bytes.Length)
        $response = $request.GetResponse()   
         if ($response) {
             $reader = [System.IO.StreamReader]$response.GetResponseStream()
             ([xml]$reader.ReadToEnd()).status | select Created_At,id
            }
          else {
            Write-Warning "Oops! There was a problem with your tweet."
            Write-Warning $error[0] | select *
            $clear=$True
          }
      }
    END {
        #if there was an error, then don’t keep the global Twitter
        #credential
        if ($clear) {
            Remove-Variable Twitter_Credential -scope Global
            }
        }
} #end Function

 

The function is designed to take a string of text from the PowerShell console and accept it as pipelined input;

PS C:\> "Drinking coffee" | out-twitter

The first time you use it you will be prompted for your Twitter credential using Get-Credential. Enter your Twitter name and password.  This information is saved as a global variable. The Begin script block checks if the variable exists and prompts you if it doesn’t.

The Process script block takes each piped in string and uses a regular expression pattern to see if it has a URL. If so, the link is sent to the Get-Snurl function which returns the short url, which in turn is inserted into the tweet, replacing the original URL. As written, this will only convert the first URL it finds.

The tweet length is checked and if less than 140 characters it is sent using the Webclient object.  If there is an error, it will be displayed and the saved credential variable will be cleared.  I didn’t want to save the variable unless the tweet was successful.  The credential variable will also be cleared if your tweet is too long. This is done in the End script block.

One thing I like about this is that you can send a long message to Twitter by breaking it up into smaller tweets:

PS C:\> "I have a lot to say.","Here is the second part","Here is the third part" | out-twitter

If the tweet is successful you’ll get some information from the web response:

created_at                                                  id
———-                                                  —
Mon Jun 23 13:56:25 +0000 2008                              841650275

I’m sure you can come up with additional improvements and enhancements. I’d love for the Tweet to say "From Out-Twitter", but there’s no web app that I’m using, just a script that uses the WebClient object to send via the Twitter web site, which is why tweets say "from web".

You can follow me on Twitter @JeffHicks

Enjoy!