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

#Jeffery Hicks
#blog.sapien.com
#http://blog.sapien.com/index.php/2008/06/23/out-twitter/

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

# code cleaned up by Noah Coad on 5/16/09, http://noahcoad.com

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\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?"

     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