You dont have javascript enabled! Please enable it!

Tweet a Random Blog Post From RSS Feed Using Azure Functions

7 Min. Read

In today’s digital age, where content consumption happens at lightning speed, promoting your blog posts effectively is crucial. One popular method to boost visibility and reach a wider audience is by leveraging social media platforms like Twitter, LinkedIn, and Facebook. Tweeting your blog posts helps attract readers, generate website traffic, and build a loyal following.

This article will guide you through the process of automating tweets for your blog posts using RSS feeds and Azure Functions, ensuring your content is shared effortlessly with your Twitter audience.

Introduction

RSS (Really Simple Syndication) feeds allow users to access regularly updated web content in a standardized format. Blogs, news websites, and other online platforms use RSS feeds to distribute their content to subscribers. By subscribing to an RSS feed, users receive updates whenever new content is published, making it a convenient way to stay informed without visiting multiple websites manually.

Automating the process of tweeting your blog posts from RSS feeds offers several advantages. Firstly, it saves time and effort by eliminating the need to manually share each post on Twitter. Secondly, it ensures consistency in posting, as tweets are automatically generated whenever new content is published. Lastly, automation allows you to schedule tweets at optimal times for maximum visibility, even when you’re not available.

Previously, I used BluebirdPS: A Twitter Automation Client for PowerShell 7 to tweet a random blog post from an RSS feed using PowerShell and Azure Function. But with the recent changes that happened at Twitter after the acquisition by Elon Musk, the team has changed the API and moved to the new API v2. Therefore, the Dev Team have deprecated their legacy Twitter API access tiers and changed their Free access tier supports.

Furthermore, Twitter decided, on short notice, to dramatically change the terms and pricing of the Twitter API. Then Elon Musk said “Twitter will enable a light, write-only API for bots providing good content that is free“, which looked set to be one of the key losses of Twitter’s recent decision to paywall all API access.

Deprecation of legacy access tiers in the Twitter API
Deprecation of legacy access tiers in the Twitter API

For this, you must create a new Project, App, and Access Tokens under your developer account on Twitter.

Now the challenging part is to authenticate with PowerShell using the new API endpoints. Based on the Twitter API v2 authentication mapping, we could use OAuth 1.0a, or OAuth 2.0 Authorization Code with PKCE to send tweets. Then why not use OAuth 2.0 because it’s also supported, but according to the documentation, sending tweets from OAuth 2.0 with only the Bearer Token is not supported.

Twitter API v2 authentication mapping
Twitter API v2 authentication mapping

This even makes things more complicated to use PowerShell and send a tweet, even ChatGPT wasn’t a big help! If you decided to use OAuth 2.0 Authorization Code with PKCE, which is even more complicated, then good luck!

After a deep investigation, I decided to abandon PowerShell for this purpose and switch to Python, we could leverage the library Tweepy which makes the authentication part very easy and it also works with the Twitter API v2 and make our life easier.

It’s a good example that PowerShell outside of the Windows world quickly begins to stumble and you are quite faster with other languages. Don’t get me wrong, I’m still in favor of PowerShell if you have the nice modules from Microsoft.

In this article, I will walk you through how to create a Python Azure Function App to randomly Tweet a blog post from any RSS feed.

Prerequisites

To follow this article, you need to have the following:

1) Azure subscription – If you don’t have an Azure subscription, you can create a free one here.

2) Azure Resource Group (RG) to deploy this project.

3) Twitter Developer account – If you don’t have an account yet, you could sign up for a developer account for free.

4) Create a Twitter Project and App – If you don’t have one yet, you could follow this step-by-step guide to make your first request to the new Twitter API v2. The good news is that you can use the Free tier, you don’t need Basic or Pro API access. The Free tier allows you to tweet up to 1,500 Tweets per month.

Twitter API v2 Access - Free
Twitter API v2 Access – Free

5) Once you finish creating the Twitter Project/App, you need to get API Key, API Secret, Access Token, and Access Secret. Additionally, at minimum, the application must be given access permissions to Read and Write for full usage.

App authentication settings
App authentication settings

6) You need to have Visual Studio (VS) Code installed on your machine (Windows/Linux/Mac) with the following extensions installed from the marketplace:

7) Azure Function App and App Service plan consumption plan (more on this in the next section). The good news is that we will be using Linux OS for the App Service plan to run Python which is even cheaper than using Windows Operating System to run PowerShell. Check the App Service pricing page for more information.

8) Optionally, but highly recommended is to have an Azure Key Vault to store your Twitter API Key, API Secret, Access Token, and Access Secret. Check how to use Key Vault references for App Service and Azure Functions.

Assuming you have all the prerequisites in place, take now the following steps:

Create Azure Function Project

First, we need to create an Azure Function.

In Visual Studio Code, press (Ctrl+Shift+P) and then search for Azure Functions: Create New Project… and click on it.

Azure Functions: Create New Project...
Azure Functions: Create New Project…

Then Browse and select the folder that will contain your function project.

Select a folder to store your function project
Select a folder to store your function project

Next, select Python as the programming language to be used.

Select Python
Select Python

Next, click on Skip virtual environment and then select the Timer trigger. We will be using a Time trigger to automate the tweet based on a desired schedule.

Then provide a Function name and then press ‘Enter‘ to confirm.

Provide a function name
Provide a function name

Next, for the cron expression, enter the desired schedule as a cron expression format in ‘{second} {minute} {hour} {day} {month} {day of week}’. In this example, we will be tweeting every day from Monday to Friday at 13:30 UTC. Check the following article to learn more about creating a Time trigger for Azure Functions.

0 30 13 * * 1-5

Then press ‘Enter‘ to confirm.

Enter a cron expression
Enter a cron expression

Last, select how you would like to open your project (Open in a new window, Open in the current window, or Add to the workspace).

Python Code

Once the project is opened in Visual Studio Code, you need to add the following Python code to the project:

import tweepy
import os
import feedparser
import random

import datetime
import logging

import azure.functions as func

def get_random_blog(rss_url):
    feed = feedparser.parse(rss_url)
    result = {}

    if not feed.entries:
        raise ValueError("The feed is empty or the URL is not valid.")

    random_entry = random.choice(feed.entries)
    result['title'] = random_entry.title
    result['link'] = random_entry.link
    
    return result

def main(mytimer: func.TimerRequest) -> None:
    utc_timestamp = datetime.datetime.utcnow().replace(
        tzinfo=datetime.timezone.utc).isoformat()

    if mytimer.past_due:
        logging.info('The timer is past due!')

    logging.info('Python timer trigger function ran at %s', utc_timestamp)

    # Get values from app settings with reference to key vault
    client = tweepy.Client(
        consumer_key = os.environ["twitter_api_key"],
        consumer_secret = os.environ["twitter_api_secret_key"],
        access_token = os.environ["twitter_access_token"],
        access_token_secret = os.environ["twitter_access_token_secret"]
    )

    blog = get_random_blog('https://charbelnemnom.com/feed')
    client.create_tweet(text=f'Azure Test Tweet! {blog["title"]} {blog["link"]} #Microsoft #Azure #Blog')
Python Code
Python Code

Please note that you need to update the following variable in the code and set the desired RSS feed that you want:

blog = get_random_blog(‘https://charbelnemnom.com/feed’)

You can also update the tweet text variable:

client.create_tweet(text=f’Test Tweet! {blog[“title”]} {blog[“link”]} #Microsoft #Azure #Blog’)

Create Function App

Next, we need to create an Azure Function App so we can deploy our project in the next step.

In Visual Studio Code, press (Ctrl+Shift+P), and then search for Azure Function App.

Create Function App in Azure
Create Function App in Azure

Then sign in to Azure and select the desired subscription where you want to create the Function App.

Next, enter a globally unique name for the new function app and then press ‘Enter‘ to confirm.

Enter a globally unique name for the new function app
Enter a globally unique name for the new function app

Then select the runtime stack. For this Function App, we will be using the latest Python version 3.10.

Python version 3.10
Python version 3.10

Last, select the desired Azure region where you want to deploy this Function App. In this example, we will be using West Europe.

The Function App will take a couple of minutes to complete.

Create Function App Succeeded
Create Function App Succeeded

Once the Function App is created in Azure, the following services dependency will be deployed in your Resource Group as part of the deployment:

  1. Function App
  2. App Service Plan
  3. Storage account
  4. Application Insights
  5. Action Group
  6. Smart detector alert rule
  7. Log Analytics workspace
Azure Functions Resources
Azure Functions Resources

Deploy To Function App

Once the Function App is deployed successfully in Azure, we can start deploying our function.

In Visual Studio Code, press (Shift+Alt+A), and then under WORKSPACE Local select the Cloud icon Deploy… button as shown in the figure below and then click Deploy to Function App…

Deploy Local Project to Azure Function App
Deploy Local Project to Azure Function App

If you did not sign in to Azure before from VS Code, you need to authenticate again with your account and then select the desired subscription where you want to deploy this project.

Next, you need to select the Function App that you created in the previous step.

Select Azure Function App resource
Select Azure Function App resource

Once you are ready to deploy your function, click the Deploy button.

Deploy To Function App
Deploy To Function App

The deployment will take less than a minute to complete.

Function deployment completed
Function deployment completed

Test Function App

Now before you move on and test your function, there are a couple of things that you need to complete and verify.

Function App Application settings

From the Twitter developer portal, you will need to generate the consumer key, otherwise called the API Key and Secret. The API Key is linked to your application. You will also need to generate an Access Token and Secret. The Access Token is linked to your Twitter user account.

Sign in to the Azure portal and then search for your Function App, then under Settings select Configuration, and under Application Settings make sure to set the Twitter API Key, API Secret, Access Token, and Access Secret (Names) as follows and then add your appropriate secret values:

  • Name: twitter_access_token
  • Name: twitter_access_token_secret
  • Name: twitter_api_key
  • Name: twitter_api_secret_key
Application settings
Application settings

Then on the Top, click the Save button.

Cross-Origin Resource Sharing (CORS)

To test your function manually from the Azure portal, you need to set the Cross-Origin Resource Sharing (CORS) in your Function App. Running your function in the portal requires the app to explicitly accept requests from https://portal.azure.com. This is known as cross-origin resource sharing (CORS).

In your Function App under API, select CORS and then add the Allowed Origins below:

https://portal.azure.com
https://functions.azure.com
https://functions-staging.azure.com
https://functions-next.azure.com
Set Cross-Origin Resource Sharing (CORS) in Azure Function App
Set Cross-Origin Resource Sharing (CORS) in Azure Function App

Then on the Top, click the Save button.

Now we are ready to test the Function. In your Function App under Functions, select the Function that we deployed in the previous step.

Then under the Developer section, select Code + Test. Then on top select Test/Run and then click Run. You should see that the Output code and response 202 are accepted by the Twitter API.

Code/Test Tweet using Azure Functions
Code/Test Tweet using Azure Functions

And here is a successful Tweet from the Azure Function on Twitter :)

Send automated Tweet to Twitter using Azure Function and Python
Send automated Tweet to Twitter using Azure Function and Python

That’s it there you have it!

Conclusion

In this article, we described how to Tweet a random blog post from an RSS feed using Python and Azure Function App by leveraging the latest Twitter API v2 for Free.

Automating the process of tweeting blog posts from RSS feeds streamlines your content promotion efforts and helps you reach a wider audience on Twitter. By following the steps outlined in this article, you can establish an efficient workflow that saves time and effort, increases engagement, and drives more traffic to your blog.

Start automating your tweet posts today and enjoy the benefits of effortless content distribution.

__
Thank you for reading my blog.

If you have any questions or feedback, please leave a comment.

-Charbel Nemnom-

Photo of author
About the Author
Charbel Nemnom
Charbel Nemnom is a Senior Cloud Architect, Swiss Certified ICT Security Expert, Certified Cloud Security Professional (CCSP), Certified Information Security Manager (CISM), Microsoft Most Valuable Professional (MVP), and Microsoft Certified Trainer (MCT). He has over 20 years of broad IT experience serving on and guiding technical teams to optimize the performance of mission-critical enterprise systems with extensive practical knowledge of complex systems build, network design, business continuity, and cloud security.
Previous

5 Methods To Fix 0x8004010F Error In Outlook

3 Methods To Fix Corrupted PST Files In Outlook

Next

Let me know what you think, or ask a question...

error: Alert: The content of this website is copyrighted from being plagiarized! You can copy from the 'Code Blocks' in 'Black' by selecting the Code. Thank You!