Automating “From the Blog Archives” Tweets using Powershell


INTRODUCTION : 

I’m always short of time and abundant of work since I make PowerShell scripts and write articles about them I’ve to also spend about an hour a day on social media sharing my content/blog posts and engaging in PowerShell communities. But the problem with social media is – Either you are Jeffery Snover himself 🙂 or most of the times nobody cares about your content and the Facts says: your post on Twitter or Facebook feed have an average lifetime 10-15 mins for a set of eyes to catch it or it will disappear in the abundance of noise out there.

So! *Takes a deep breath* You’ve to share the content you are creating multiple times on Twitter to reach out to more and more people = MORE TIME, otherwise, it doesn’t make much sense putting efforts writing those blog posts and creating those scripts if nobody is reading them.

THE IDEA: 

How about if I can automate sharing  Mulitple Random blog posts to twitter, few times a day, without even investing the time I would’ve actually spent doing that manually. Sounds great, right? ( Well, to me 🙂 )
Okay, Enough of talking, let’s begin working. So for better understanding let me break down what we want to achieve in some steps –

  1. Figure out a way get a random Powershell article [Topic and URL] from my blog [http://Geekeefy.wordpress.com]
  2. Shorten the URL because a Tweet has a character limit of 140 words
  3. And yeah! We’ve to #HashTag some keywords Like #PowerShell in our tweet
  4. Then just Tweet the Topic, Shortened URL, and hashtags.

MAKING IT WORK:

Step 1 [Get some random Powershell article]

  • In order to get few random articles from my blog, a simple Invoke-WebRequest on my blog URL would work like a charm, and get me the parsed HTML content of the homepage.
    NOTE:  You’ve to customize the script to handle your blog because you’ve to filter out exact HTML tags to get the data residing within them, which would be different for every website. 
  • You can use static data instead where in you put all Article topics and URLs and utilize it in publishing tweets, but that is not our case because we’ve to regularly update this static data whenever I write a new article.
  • But wait on the homepage on my blog not all links populate at once until you scroll down, so I’m gonna iterate all pages and get the links to the articles I’ve written.

    2

  • Once I get all articles I’ve to use Get-Random cmdlet to select some random articles

Step 2 [Shorten the URL of the article]

  • You can use many Web REST API’s to get a short URL for a long URL because Tweet has a word limit of 140 characters
  • I used Google API’s for this following is the function, but first, you’ve to subscribe the API here and get an API key to make it work.

    1

  • Using the above function you’ll get a short URL something like this

    1

Step 3 [#Hashtag important keywords in your Tweet]

Hashtag your topics so that if people search using a particular Hashtags they get reach your tweet easily, also it’s easier for you to track them.

Step 4 [Tweet the content] 

  • Combine the Article topic and the shortened URL in one string to prep the tweet content
  • To publish the tweet, you can install PoshTwit module from Powershell gallery using below cmdlet

    1

  • Once you have the module on your local machine and you can feed in your Tweet content with secret tokens and keys you get from your twitter account, follow this link to get the exact steps to obtain them

    1

  • Once you are all set, use the Publish-Tweet cmdlet, which will automatically tweet content to your twitter profile

    2

SCRIPT :

Wrapping up all the steps in the script looks something like this

[cmdletbinding()]
param(
[Int] $IntervalInMins = 15,
[Int] $Count = 5
)
if(-not (Get-module poshtwit)) {
Install-Module PoshTwit -Force -Verbose -Scope CurrentUser
}
Function Get-ShortURL
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True, ValueFromPipeline = $true)][string] $URL
)
Write-Verbose "Creating Short URL for $URL"
Invoke-RestMethod -Uri "https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyDne5JQP_6F0aBsnz9RcItd3zeO1v6J734" `
-Body $(''| Select-object @{n='longUrl';e={$URL}}|convertto-json) `
-ContentType 'application/json' `
-Method Post | ForEach-Object ID
}
Function Get-BlogArticle
{
[cmdletbinding()]
param(
[Parameter(Mandatory=$true)] [uri] $URL
)
$Data = @() ; $PageNumber = 1
Write-Verbose "Web requesting $URL for Articles - Topic & URL."
While($true) {
if($PageNumber -eq 1) {
$SubString = ""
}
else {
$SubString = "page/$PageNumber/"
}
Try {
$WebRequest = Invoke-WebRequest -Uri "https://$URL/$SubString"
$Data += ($WebRequest).parsedhtml.all | `
Where-Object {$_.nodename -eq 'a' -and $_.rel -eq 'bookmark' -and $_.innertext -like "*powershell*"} | `
Select-Object @{n='Topic';e={$_.InnerText}}, @{n='URL';e={$_.href}}
}
Catch
{
Break
}
$WebRequest = $null
$PageNumber++
}
$Data
}
$Articles = Get-BlogArticle -URL 'Geekeefy.wordpress.com'
Write-Verbose "$($Articles.count) Articles found & extracted."
Write-Verbose "Selecting $Count random articles."
$HashtagKeywords = "Powershell","Automation","Troubleshooting","DataExtraction","DataWrangling","Exchange","Google","Microsoft","PSTip","Tip","WebScraping","WhatILearnedToday"
$Articles| Get-Random -Count $Count | `
ForEach-Object {
$Topic = $_
$words= Foreach($Word in $Topic.Topic.Split(" ")) {
if($Word -in $HashtagKeywords) {
"#$word"
}
else {
$word
}
}
$TweetContent = $($words -join ' ')+"`n$($Topic.URL| Get-ShortURL -Verbose)"
If($TweetContent.length -le 140)
{
$Tweet = @{
ConsumerKey = 'ConsumerKey';
ConsumerSecret = 'ConsumerSecret';
AccessToken = 'AccessToken';
AccessSecret = 'AccessSecret';
Tweet = $TweetContent;
}
Write-Verbose "Tweeting the text > $TweetContent ."
Publish-Tweet @Tweet
Write-Verbose "Done."
}
Write-Verbose "Waiting for $IntervalInMins mins until next Tweet."
Start-Sleep -Seconds (60*$IntervalInMins)
}

HOW TO RUN :

Run the script with parameters like in the below animation

gif

and you’ll see random blog posts from your archives getting tweeted in the defined interval on you Twitter Profile. If you want you can also Prefix something like “From the Blog Archives: Topic” for your twitter followers.

2

NOTE : 

There are plenty of tools Like IFTTT already on the internet, that may provide you recipes to achieve this, but again it’s something you can’t customize per your needs, moreover creating your own thing is far more fun and satisfying 🙂

 

POSSIBILITIES :

What if we can schedule one such script on a physical machine that is running 24X7 or a cloud instance which is always up?
It would definitely increase social media interactions and visibility to the work you are producing! Your content would be shared on social media even when you are sleeping and working on other things and for sure it will save you some time 🙂 which is scarce.

Hope you’ll find it useful, give me a shout on twitter if you like the content I share. Thank you very much for reading!

signature

5 thoughts on “Automating “From the Blog Archives” Tweets using Powershell

Leave a comment