MyTwitter: A Twitter Module for Powershell

09/23/14 UPDATE: I’ve created a Github repo for this module. I realize it needs a lot of work if it’s going to be a full-fledged Twitter client so please help me make it great!

Twitter moduleI don’t know about you but I’m on Twitter all the time. It’s a great way to connect with like-minded people. You can use Twitter simply through Twitter.com or through the slew of Twitter clients out there. Just like any other major web service, Twitter provides an API. In a nutshell, an API is the way most companies allow others to interact with their service. In Twitter’s case, APIs are the reason you’re probably not tweeting from twitter.com all the time and instead you’ve got 3 Twitter clients on your phone, a Twitter client on your Mac and one on your PC. These clients are all making API calls to Twitter’s servers to interact with any number of Twitter services. In the example I’m about to talk about, Twitter’s API allowed me to send tweets and DMs from my account with Powershell.

If you go looking on the web you’ll find a lot of references to using Twitter with Powershell. I didn’t set out to create my own module but after trying out the various scripts out there and failing miserably at getting any to work I decided to just create my own. Twitter’s API has went through a few revisions. At the time of this writing, they are up to v1.1 which includes a much more secure feature called OAuth. OAuth drastically changed the way you interact with Twitter’s APIs because you now had to authenticate and authorize yourself ahead of time. I won’t get into the specifics but needless to say, it requires a TON more code than it did.

The majority of the links I found were for previous API versions which simply wouldn’t work at all. Some looked similar but simply would give me “Not Authorized” or “Failed to authenticate” errors when I attempted to use them. The closest example I could find was Ian Chiver’s blog post entitled Tweet from Powershell Using OAuth but it was built for API v1 and not 1.1. I’ve discovered that OAuth is extremely picky and I just couldn’t get anything to work so I decided to take the leap and learn about Oauth and Twitter’s APIs.

As I alluded to earlier, I’ve created a Powershell module called MyTwitter that (as of this writing) allows you to send tweets and DMs to other Twitter users from your own Twitter account.  Maybe one of these days I’ll tack on some other functionality since I’ve got OAuth handled… Unlike my other scripts/modules you can’t just simply import and go off tweeting.  You first need to perform a few prerequisite steps to get your Twitter account prepped to use Twitter’s APIs.

Before I get to the module, if you’d like to tweet or send DMs from your Twitter account in Powershell you’re going to have to create a Twitter application first. I promise it’s not as daunting as it seems. I created my first application this weekend and it was really easy. Here’s what you need to do prior to importing this module to get tweeting ASAP.

  1. Go to Twitter’s application page and click Sign In (if you’re not already)
    signinlink
  2. Click on Create a new App.
    createnewapp
  3. Fill in your App’s details. What you put here really doesn’t matter. I’ve included a screenshot of what mine looks like.
    createanapplication
  4. Scroll down a little bit, confirm your life away and create your application.
    confirmcreation
  5. You’ll then come to a screen like this. Whenever your app is built, it will be read-only which means you’ll only be able to read tweets and other things but can’t actually send a tweet or a DM. We need to change the app to either Read and Write or Read, Write and Access Direct Messages.
    Screen Shot 2014-08-30 at 10.45.39 PM
  6. When I was testing I thought the app needed Read, Write and Access Direct Messages but I was wrong. Your app only needs Read and Write permission. Click Update Settings
    Screen Shot 2014-08-30 at 10.46.04 PM
  7. Click Details a few times now and your details page should eventually show Read and Write as it’s Access Level.
  8. You’re going to need a few things to insert into the module now that the app is created. The first set of attributes you need are the API Key and API Secret. You can find these by clicking on the API Keys section. Be sure to copy these out. You’ll need them later.
    Screen Shot 2014-08-30 at 10.50.19 PM
  9. Next, you need to create an Access Token. This is a token that your module will use to prove who you say you are. To do this, scroll down a little bit on the API Keys page and click on Create my Access Token.
    Screen Shot 2014-08-30 at 10.51.42 PM
  10. Wait a little bit and this screen will come up. You will need the access token and access token secret for the module.
    Screen Shot 2014-08-30 at 10.52.38 PM

That wasn’t so bad, was it?  After you’ve successfully created your first Twitter application you should have come away with 4 key pieces of information; the API key, the API secret, an Access token and an Access token secret.  You’ve got these, right?  Good!  Now, let’s put them into the Get-OAuthAuthorization function so you can begin tweeting away!

I’ve uploaded the module to the Technet Script Repository so go ahead and download it. Once you’ve downloaded it, go to the Get-OAuthAuthorization function and paste in those 4 pieces of information you got from your Twitter application.

twitterparams

Once you do that, you’re good to go!  If you made it to the end of this post kudos to you!  Now, the only thing I ask for you to do for me in return for my hard work here is to tweet me as your first tweet with this module.  Once you’ve got it imported, just do a

Adam Bertram

Chief Automator at Adam the Automator, LLC
Adam Bertram is an independent consultant, technical writer, trainer and presenter. Adam specializes in consulting and evangelizing all things IT automation mainly focused around Windows PowerShell. Adam is a Microsoft Windows PowerShell MVP, 2015 powershell.org PowerShell hero and has numerous Microsoft IT pro certifications. He authors IT pro course content for Pluralsight, is a regular contributor to numerous print and online publications and presents at various user groups and conferences.You can find Adam here on the blog or on Twitter at @adbertram.

29 comments

  • Pingback: MyTwitter: A Twitter Module for Powershell – Powershell

  • Pingback: Twitter from Powershell | Powershell Faq

  • Pingback: Use PowerShell to make Rest API calls using JSON & OAuth – Marc Kean

  • Hello,
    I use your module without problems in Powershell prompt BUT (there is always a ‘BUT’ in the blog’s comments) ,when I try in a bat file like this

    Powershell.exe -executionpolicy remotesigned -command import-module ‘C:\Users\pm\Documents\WindowsPowerShell\Modules\MyTwitter’ ;Send-Tweet -Message ‘Message_ Twitter2’

    I have an error like this

    Invoke-RestMethod : {“errors”:[{“code”:32,”message”:”Could not authenticate
    you.”}]}
    Au caractère
    C:\Users\pm\Documents\WindowsPowerShell\Modules\MyTwitter\MyTwitter.psm1:289 :
    3
    + Invoke-RestMethod -URI $HttpEndPoint -Method Post -Body $Body
    -Headers @{ ‘Aut …
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    ~~~~~~~~~
    + CategoryInfo : InvalidOperation : (System.Net.HttpWebRequest:Ht
    tpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShe
    ll.Commands.InvokeRestMethodCommand

    I don’t understand where is the trick
    Have you got an explanation

    Thanks

    Patrice

    • I believe you need to surround your command in curly braces like this: Powershell.exe -executionpolicy remotesigned -command { import-module ‘C:\Users\pm\Documents\WindowsPowerShell\Modules\MyTwitter’ ;Send-Tweet -Message ‘Message_ Twitter2’}

      • Hi Adam
        Thanks for your reply
        I try with

        Powershell.exe -executionpolicy remotesigned -Command “”

        but I always got the same error “invoke-RestMethod” as you see :

        Invoke-RestMethod : {“errors”:[{“code”:32,”message”:”Could not authenticate
        you.”}]}
        Au caractère
        C:\Users\pm\Documents\WindowsPowerShell\Modules\MyTwitter\MyTwitter.psm1:289 :
        3
        + Invoke-RestMethod -URI $HttpEndPoint -Method Post -Body $Body
        -Headers @{ ‘Aut …
        + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        ~~~~~~~~~
        + CategoryInfo : InvalidOperation : (System.Net.HttpWebRequest:Ht
        tpWebRequest) [Invoke-RestMethod], WebException
        + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShe
        ll.Commands.InvokeRestMethodCommand

        Directly from a PS prompt the Sent-Twitt command works fine

        Maybe it’a another way to send tweets from a .bat file ?
        (I need to use a bat file in my software to launch powershells scripts)

        Thanks
        Patrice

        • I still do not see that you’re using curly bases to enclose the Command parameter argument.

        • Hi Adam

          To simplify the script because I think the ‘import-module’ is not necessary

          I just try : Powershell.exe -executionpolicy remotesigned -Command “Send-Tweet -Message ‘MessageTwitter2′”

          The error message is the same with Invoke-Rest Method in the module MyTwitter.psm1 289

          Invoke-RestMethod : {“errors”:[{“code”:32,”message”:”Could not authenticate
          ou.”}]}
          u caractère C:\windows\system32\windowspowershell\v1.0\Modules\MyTwitter\MyTwi
          ter.psm1:289 : 3
          Invoke-RestMethod -URI $HttpEndPoint -Method Post -Body $Body
          Headers @{ ‘Aut …
          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          ~~~~~~~~
          + CategoryInfo : InvalidOperation : (System.Net.HttpWebRequest:Ht
          tpWebRequest) [Invoke-RestMethod], WebException
          + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShe
          ll.Commands.InvokeRestMethodCommand

  • Hello,
    Just setup your awesome Twitter PowerShell module on our company’s Twitter account with a very to sending out automated tweets; As a test, I can read our timeline fine with “Get-TweetTimeline” but I’m afraid that the Send-Tweet function is bombing out with the following, I’m wondering if there’s some extra bit of setup/authorisation outside of your module I need to setup?

    Invoke-RestMethod : The request was aborted: Could not create SSL/TLS secure channel.
    At C:\Users\Administrator\Documents\WindowsPowerShell\Modules\MyTwitter\MyTwitter.psm1:289 char:3
    + Invoke-RestMethod -URI $HttpEndPoint -Method Post -Body $Body -Headers @{ ‘Aut …
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebExc
    eption
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

    • That’s a new error message I haven’t seen before. As long as you’ve created the Twitter application on their end and am using the right API keys, it should work. I’d try it on another computer just to see if it’s not something with the computer you’re on. For example, I know sometimes if you’re clock is off a little bit, the TLS channel cannot be established. That’s just a guess though.

  • Great script, im having som issues with it. It works great on my WIndows 10 machine (Powershell 5) but fails on both my WIndows 8 (powershell 4) and 2012 R2 server (powershell 4).
    This is what fails on those machines;

    Get-OAuthAuthorization : Exception calling “ParseExact” with “3” argument(s): “String was not recognized as a valid DateTime.”
    At C:\powershell\modules\MyTwitter.psm1:178 char:26
    + $AuthorizationString = Get-OAuthAuthorization -TweetMessage $Message -HttpEndP …
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-OAuthAuthorization

    Should i pursue getting powershell up to 5 (preview) on those machines or what do you think is wrong?

  • Hi, I’ve just posted a Powershell Twitter REST API 1.1 Module on TechNet Gallery… go check it out at tell me what you think! https://goo.gl/s7pmmA

  • Pingback: Brewing coffee with Azure Automation | DollarUnderscore

  • Very Interesting! Thanks for the share Adam, this is definitely something I will look into on the next raining sunday

  • Thanks, for the excellent article! The article was helpful in creating this powershelll module that can access any of the Twitter APIs: https://github.com/MeshkDevs/InvokeTwitterAPIs.

  • Works now! Awesome, thanks for sharing!

  • This is awesome! I did everything as you instructed, but I keep getting this error:

    Invoke-RestMethod : {“errors”:[{“message”:”Could not authenticate you”,”code”:32}]}
    At C:\Program Files\WindowsPowerShell\Modules\MyTwitter\MyTwitter.psm1:184 char:3
    + Invoke-RestMethod -URI $HttpEndPoint -Method Post -Body $Body -Headers @{ ‘Aut …
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

    Am I missing something?

  • Ohhhh I love the screenshots. 🙂

Leave a Reply