Tweeting a random blog post from Rss feed using PowerShell Azure Function

Previously I blogged “Using PowerShell to automatically Tweet a random Blog Post from Table Storage” which resulted in a couple of Azure PowerShell Functions, this is a complex setup and possibly not required if all you are looking to do is Tweet a random blog post at a scheduled time.

In this blog, I will be creating a PowerShell Azure Function to randomly Tweet a blog post from my blog, data will be taken from RSS feed.

Throughout the creation, I will be using VSCode and using the Azure Functions extension – its great!

Creating Azure Function

In vscode, select Azure icon – on the Functions line, create new project and select location of folder

Select PowerShell (Preview)

Azure Functions v2

For this example, it will be a Timed Trigger, (Running 3 times a week, Monday, Wednesday and Friday at 11.30am) using cron expression:-
“0 30 11 * * 1,3,5”

Now Open the newly created local project, it will look similar to the below

For Invoking the Twitter API , I used a third-party PowerShell module created by MeshkDevs – InvokeTwitterAPIs

Download the contents from above link and place inside folder called Modules\InvokeTwitterAPIs and copy folders into RssTwitterFunction as below

The PowerShell script below is what I have created

# Input bindings are passed in via param block.
param($Timer)

#Import InvokeTwitterAPIs module
import-module ‘D:\Home\site\wwwroot\rssTwitterFunction\Modules\InvokeTwitterAPIs\InvokeTwitterAPIs.psm1’


$twitterAccessToken = $env:twitterAccessToken
$twitterAccessTokenSecret = $env:twitterAccessTokenSecret
$twitterAPIKey = $env:twitterAPIKey
$twitterAPISecret = $env:twitterAPISecret

    #Queries RssFeed of my blog
    $rssfeed = [xml](Invoke-WebRequest "https://thomasthornton.cloud/feed/" -UseBasicParsing) 
    $Tweetdata = ($rssfeed.rss.channel.item) | Get-Random


    #Setup Twitter OAuth Hashtable
    $TwitterOAuthConfig = @{ 'ApiKey' = $twitterAPIKey; 'ApiSecret' = $twitterAPISecret; 'AccessToken' = $twitterAccessToken; 'AccessTokenSecret' = $twitterAccessTokenSecret}
    $CombineTweet = ("From the Blog:",$Tweetdata.title,$Tweetdata.link,"#Microsoft #Azure #AzureFamily #Blog") 

    Write-Output "Tweeting: $CombineTweet" 
    
    $Parameters = @{ 'status' = $CombineTweet} 

    Invoke-TwitterRestMethod -ResourceURL 'https://api.twitter.com/1.1/statuses/update.json' -RestVerb 'POST' -Parameters $Parameters -OAuthSettings $TwitterOAuthConfig

Before including in Azure Function, lets have a quick look at the script – split into four snippets

The first part, imports PowerShell module that was placed inside folder Modules\InvokeTwitterAPIs

#Import InvokeTwitterAPIs module
import-module ‘D:\Home\site\wwwroot\rssTwitterFunction\Modules\InvokeTwitterAPIs\InvokeTwitterAPIs.psm1’

The second snippet is 4 parameters, created from environment variables that will be uploaded later, these variables are the Twitter details of my Twitter account

$twitterAccessToken = $env:twitterAccessToken
$twitterAccessTokenSecret = $env:twitterAccessTokenSecret
$twitterAPIKey = $env:twitterAPIKey
$twitterAPISecret = $env:twitterAPISecret

Third part, creates a parameter $Tweetdata from the RssFeed data, will demo what it shows

    #Queries RSSFeed of my blog
    $rssfeed = [xml](Invoke-WebRequest "https://thomasthornton.cloud/feed/" -UseBasicParsing) 
    $Tweetdata = ($rssfeed.rss.channel.item) | Get-Random

Output of $rssfeed.rss.channel.item shows an array of Blog Posts in rss format
Get-Random will select a random item from this array that will be used to create the Tweet

title       : Enabling Alerting for Azure Recovery Services  Vault
link        : https://thomasthornton.cloud/2019/07/24/enabling-alerting-for-azure-recovery-services-vault/
comments    : {https://thomasthornton.cloud/2019/07/24/enabling-alerting-for-azure-recovery-services-vault/#comments, 1}
pubDate     : Wed, 24 Jul 2019 09:41:24 +0000
creator     : creator
category    : {category, category, category, category...}
guid        : guid
description : description
encoded     : encoded
commentRss  : https://thomasthornton.cloud/2019/07/24/enabling-alerting-for-azure-recovery-services-vault/feed/
post-id     : post-id

title       : Creating Azure Service Health Alerts in PowerShell
link        : https://thomasthornton.cloud/2019/07/18/creating-azure-service-health-alerts-in-powershell/
comments    : {https://thomasthornton.cloud/2019/07/18/creating-azure-service-health-alerts-in-powershell/#comments, 5}
pubDate     : Thu, 18 Jul 2019 11:05:25 +0000
creator     : creator
category    : {category, category, category, category...}
guid        : guid
description : description
encoded     : encoded
commentRss  : https://thomasthornton.cloud/2019/07/18/creating-azure-service-health-alerts-in-powershell/feed/
post-id     : post-id

Final part, building the Tweet and tweeting via the third party PowerShell module

#Setup Twitter OAuth Hashtable
    $TwitterOAuthConfig = @{ 'ApiKey' = $twitterAPIKey; 'ApiSecret' = $twitterAPISecret; 'AccessToken' = $twitterAccessToken; 'AccessTokenSecret' = $twitterAccessTokenSecret}
    $CombineTweet = ("From the Blog:",$Tweetdata.title,$Tweetdata.link,"#Microsoft #Azure #AzureFamily #Blog") 

    Write-Output "Tweeting: $CombineTweet" 
    
    $Parameters = @{ 'status' = $CombineTweet} 

    Invoke-TwitterRestMethod -ResourceURL 'https://api.twitter.com/1.1/statuses/update.json' -RestVerb 'POST' -Parameters $Parameters -OAuthSettings $TwitterOAuthConfig

Lets look at $CombineTweet, it creates a string from $Tweetdata.tile & $Tweetdata.link which is taken from the above array item and finished with hard-coded hashtags

Creating the Azure Function

Using Source Control: Git – commit all changes

Deploy Function App to Azure using this article I cannot show this as the icons don’t show when trying to screenshot. I have created function rssTwitterBlog

Once the function has been created, you now need to configure environment variables in the app settings of the function, I created the below script for this. For Twitter access for the below variables are generated by created by Twitter Access Tokens, I used this tutorial to create an app within the Twitter API

    $ResourceGroupName = "rssTwitterBlog"
    $FunctionName = "rssTwitterBlog"

    $AppSettingsHash = @{
    twitterAccessToken = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    twitterAccessTokenSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    twitterAPIKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    twitterAPISecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    }

    foreach ($AppSettingAdd in $AppSettingsHash.GetEnumerator()) {
    az functionapp config appsettings set --resource-group $ResourceGroupName --name $FunctionName --settings "$($AppSettingAdd.Name) = $($AppSettingAdd.Value)"
    }

Open Function in Azure Portal and run it with a verbose output, you will see a successful Tweet

2019-10-16T19:01:49.657 [Information] Executing 'Functions.RssTwitterFunction' (Reason='This function was programmatically called via the host APIs.', Id=7e10d3a5-6cae-401e-9812-eced33a66304)
2019-10-16T19:01:52.663 [Information] OUTPUT: Tweeting: From the Blog: Creating automated reports using Logic Apps for Log Analytics queries https://thomasthornton.cloud/2019/08/30/creating-automated-reports-using-logic-apps-for-log-analytics-queries/ #Microsoft #Azure #AzureFamily #Blog
2019-10-16T19:01:53.116 [Information] OUTPUT:
2019-10-16T19:01:53.116 [Information] OUTPUT: created_at                : Wed Oct 16 19:01:52 +0000 2019
2019-10-16T19:01:53.122 [Information] OUTPUT: id                        : 1184484612325679106
2019-10-16T19:01:53.123 [Information] OUTPUT: id_str                    : 1184484612325679106
2019-10-16T19:01:53.123 [Information] OUTPUT: text                      : From the Blog: Creating automated reports using Logic Apps for Log Analytics queries https://t.co/Yb4g5P05sP… https://t.co/z5RgbJBL8j
2019-10-16T19:01:53.123 [Information] OUTPUT: truncated                 : True
2019-10-16T19:01:53.123 [Information] OUTPUT: entities                  : @{hashtags=System.Object[]; symbols=System.Object[]; user_mentions=System.Object[]; urls=System.Object[]}
2019-10-16T19:01:53.124 [Information] OUTPUT: source                    : <a href="https://thomasthornton.cloud" rel="nofollow">testtestst</a>
2019-10-16T19:01:53.124 [Information] OUTPUT: in_reply_to_status_id     :
2019-10-16T19:01:53.124 [Information] OUTPUT: in_reply_to_status_id_str :
2019-10-16T19:01:53.125 [Information] OUTPUT: in_reply_to_user_id       :
2019-10-16T19:01:53.125 [Information] OUTPUT: in_reply_to_user_id_str   :
2019-10-16T19:01:53.125 [Information] OUTPUT: in_reply_to_screen_name   :
2019-10-16T19:01:53.125 [Information] OUTPUT: user                      : @{id=145447219; id_str=145447219; name=Thomas Thornton; screen_name=tamstar1234; location=Belfast, Northern Ireland; description=@kainossoftware - MSFT
2019-10-16T19:01:53.125 [Information] OUTPUT:                             Azure Solutions Architect Expert,
2019-10-16T19:01:53.126 [Information] OUTPUT:                             MCSA: Cloud Platform & MSFT Certified: Azure Administrator & Azure Security Engineer; url=https://t.co/E39kjovqNd; entities=; protected=False; followers_count=1097; friends_count=1337; listed_count=22; created_at=Wed May 19 00:44:11 +0000 2010; favourites_count=3377; utc_offset=; time_zone=; geo_enabled=True; verified=False; statuses_count=4591; lang=; contributors_enabled=False; is_translator=False; is_translation_enabled=False; profile_background_color=FFF04D; profile_background_image_url=http://abs.twimg.com/images/themes/theme1/bg.png; profile_background_image_url_https=https://abs.twimg.com/images/themes/theme1/bg.png; profile_background_tile=False; profile_image_url=http://pbs.twimg.com/profile_images/1161734269775073280/0yapXacv_normal.jpg; profile_image_url_https=https://pbs.twimg.com/profile_images/1161734269775073280/0yapXacv_normal.jpg; profile_banner_url=https://pbs.twimg.com/profile_banners/145447219/1545600680; profile_link_color=0099CC; profile_sidebar_border_color=FFF8AD; profile_sidebar_fill_color=F6FFD1; profile_text_color=333333; profile_use_background_image=True; has_extended_profile=False; default_profile=False; default_profile_image=False; following=False; follow_request_sent=False; notifications=False; translator_type=none}
2019-10-16T19:01:53.126 [Information] OUTPUT: geo                       :
2019-10-16T19:01:53.126 [Information] OUTPUT: coordinates               :
2019-10-16T19:01:53.133 [Information] OUTPUT: place                     :
2019-10-16T19:01:53.133 [Information] OUTPUT: contributors              :
2019-10-16T19:01:53.133 [Information] OUTPUT: is_quote_status           : False
2019-10-16T19:01:53.133 [Information] OUTPUT: retweet_count             : 0
2019-10-16T19:01:53.134 [Information] OUTPUT: favorite_count            : 0
2019-10-16T19:01:53.134 [Information] OUTPUT: favorited                 : False
2019-10-16T19:01:53.134 [Information] OUTPUT: retweeted                 : False
2019-10-16T19:01:53.134 [Information] OUTPUT: possibly_sensitive        : False
2019-10-16T19:01:53.135 [Information] OUTPUT: lang                      : en
2019-10-16T19:01:53.135 [Information] OUTPUT:
2019-10-16T19:01:53.135 [Information] OUTPUT:
2019-10-16T19:01:53.183 [Information] Executed 'Functions.RssTwitterFunction' (Succeeded, Id=7e10d3a5-6cae-401e-9812-eced33a66304)

A successful Tweet from the Azure Function!

Leave a Reply

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

%d bloggers like this: