Create a Tweet on Twitter using PowerShell

In an earlier post about Slack, I showed you how to create a message there, but I also use Twitter a lot (I even met my girlfriend because of that!). In this blog post, I will show you how to create a Tweet using PowerShell 🙂

Preparation

You need to register for API access to post something on Twitter. To do that, follow these steps:

  • Log in to Twitter using your account or create a new account.
  • Go to https://developer.twitter.com/en/portal/petition/use-case to sign-up
  • Select Hobbyist, Making a bot, and select Get Started
  • Fill in the ‘What’s your name?’, What country are you based in’ and the ‘What’s your coding skill level’ field. In my case, I chose my name, Netherlands, and some experience and click Next
  • Fill in the ‘In your words’ section with why you want to use the Twitter API. This has to be done in 200 characters or more.
  • Fill in the ‘Please describe your planned use of these features’ section with how you want to use the Tweet, Retweet, Like, Follow or Direct Message functionality in 100 characters or more.
  • Fill in the ‘Are you planning to analyze Twitter data? ‘, ‘Do you plan to display Tweets or aggregate data about Twitter content outside Twitter?’ and ‘Will your product, service, or analysis make Twitter content or derived information available to a government entity?’ sections too and click Next
  • Review the Basic info and Intended use information and choose Next
  • Select ‘By clicking on the box, you indicate that you have read and agree..’ and select Submit
  • Verify your email by clicking ‘Confirm your email’ in the email sent to the address you provided while registering your account.
  • You will receive another email shortly after confirming your email address that your application has been received and is pending review.

The process could take up to 24 hours. I received my confirmation in 12 hours in an email and a link (https://developer.twitter.com/en/portal/dashboard) to create the app. The registration is a lot more work than in the past, and I received an additional email because I didn’t fill in all the questions (I thought they were not applicable) so… You can see that Twitter is making sure that there are not too many bots on the platform, thanks Elon Musk :P.

Getting the API keys

When opening the developer dashboard page (Link above) it will ask you for an App name, I used PowerShellisfun in this case ;), and you can click on Get Keys

The keys will now appear, and copy/paste them somewhere safe 🙂 (You don’t need the Bearer Token in our case)

User authentication settings

The script needs OAuth 1.0a access. For this, you need to follow these steps:

  • Select Yes
  • Go back to your app and click on the Keys and Tokens tab
  • Click Regenerate in the Access Token and Secret pane, make a note of them, and save them in a safe place!

You should now have an API Key, API Key Secret, Access Token, and Access Token Secret. (The Bearer Token is not needed in our case). You can always regenerate them on your application’s Keys and Tokens tab.

Running the script

You can use the function in your script or add it to your PowerShell profile to have it available in all your PowerShell sessions by running:

Notepad $profile
add . c:\scripts\Send-Tweet.ps1
Quit/Save and start new PowerShell session

You can send a tweet by running (It has to be in between ‘-s ) :

Send-Tweet -Message 'Hello PowerShell world'

And this will look like this: (You can see the App name down at the right)

You can also mention people by running:

Send-Tweet -Message '@username Hello'

And that will look like this:

The script

When writing this blog post, I remembered that I had done this before! Started digging in my GitHub script repository, and… There it was. I downloaded this from https://gallery.technet.microsoft.com/Send-Tweets-via-a-72b97964, but… I can’t find the original creator. The URL is a dead end without redirection 🙁

I changed it to a Function and had to change the api.twitter.com URL from 1.0 to 1.1 and HTTPS 🙂 I removed the keys in the script, and you will have to replace them with your own :

function Send-Tweet {
    param (
        [Parameter(Mandatory = $true, HelpMessage = "Enter the message in 140 characters or less")][string]$Message
    )
    #Validate length of message
    if ($message.Length -gt 140) {
        Write-Warning ("Length of tweet is {0} characters, maximum amount is 140. Aborting..." -f $Message.Length)
        return
    }
    
    try {
        $status = [System.Uri]::EscapeDataString("$($Message)")  
        $oauth_consumer_key = 'xxxxxxxxxxxx'  #API Key
        $oauth_consumer_secret = 'xxxxxxxxxxxx'  #API Key Secret
        $oauth_token = 'xxxxxx-xxxxxxxxxx'  #Access Token
        $oauth_token_secret = 'xxxxxxxxxxxxxxxx'  #Access Token Secret
        $culture = New-Object  -TypeName System.Globalization.CultureInfo -ArgumentList ('en-US')
        $oauth_nonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString()))  
        $ts = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact('01/01/1970', 'dd/MM/yyyy', $culture).ToUniversalTime()  
        $oauth_timestamp = [System.Convert]::ToInt64($ts.TotalSeconds).ToString()  
  
        $signature = 'POST&'  
        $signature += [System.Uri]::EscapeDataString('https://api.twitter.com/1.1/statuses/update.json') + '&'  
        $signature += [System.Uri]::EscapeDataString('oauth_consumer_key=' + $oauth_consumer_key + '&')  
        $signature += [System.Uri]::EscapeDataString('oauth_nonce=' + $oauth_nonce + '&')   
        $signature += [System.Uri]::EscapeDataString('oauth_signature_method=HMAC-SHA1&')  
        $signature += [System.Uri]::EscapeDataString('oauth_timestamp=' + $oauth_timestamp + '&')  
        $signature += [System.Uri]::EscapeDataString('oauth_token=' + $oauth_token + '&')  
        $signature += [System.Uri]::EscapeDataString('oauth_version=1.0a&')  
        $signature += [System.Uri]::EscapeDataString('status=' + $status)  
  
        $signature_key = [System.Uri]::EscapeDataString($oauth_consumer_secret) + '&' + [System.Uri]::EscapeDataString($oauth_token_secret)  
  
        $hmacsha1 = New-Object  -TypeName System.Security.Cryptography.HMACSHA1  
        $hmacsha1.Key = [System.Text.Encoding]::ASCII.GetBytes($signature_key)  
        $oauth_signature = [System.Convert]::ToBase64String($hmacsha1.ComputeHash([System.Text.Encoding]::ASCII.GetBytes($signature)))  
  
        $oauth_authorization = 'OAuth '  
        $oauth_authorization += 'oauth_consumer_key="' + [System.Uri]::EscapeDataString($oauth_consumer_key) + '",'  
        $oauth_authorization += 'oauth_nonce="' + [System.Uri]::EscapeDataString($oauth_nonce) + '",'  
        $oauth_authorization += 'oauth_signature="' + [System.Uri]::EscapeDataString($oauth_signature) + '",'  
        $oauth_authorization += 'oauth_signature_method="HMAC-SHA1",'  
        $oauth_authorization += 'oauth_timestamp="' + [System.Uri]::EscapeDataString($oauth_timestamp) + '",'  
        $oauth_authorization += 'oauth_token="' + [System.Uri]::EscapeDataString($oauth_token) + '",'  
        $oauth_authorization += 'oauth_version="1.0a"'  
  
        $post_body = [System.Text.Encoding]::ASCII.GetBytes('status=' + $status)   
        [System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create('https://api.twitter.com/1.1/statuses/update.json')  
        $request.Method = 'POST'  
        $request.Headers.Add('Authorization', $oauth_authorization)  
        $request.ContentType = 'application/x-www-form-urlencoded'  
        $body = $request.GetRequestStream()  
        $body.write($post_body, 0, $post_body.length)  
        $body.flush()  
        $body.close()  
        $response = $request.GetResponse()  
    }

    catch {
        Write-Warning ("Something went wrong, tweet '{0}' is not tweeted..." -f $Message)
    }
}

Download the script(s) from GitHub here

2 thoughts on “Create a Tweet on Twitter using PowerShell

Leave a Reply to Elizabeth GreeneCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.