How to Schedule Automated SMS Messages Using Twilio and GitHub Actions

January 17, 2023
Written by
Contributor
Opinions expressed by Twilio contributors are their own
Reviewed by
Twilion

How to Schedule Automated SMS Messages Using Twilio and GitHub Actions

This tutorial will teach you how to run a scheduled task using GitHub Actions. We’ll build a Python app that sends you random motivational quotes, deploy this app to GitHub, and then configure GitHub Actions to run the app on a daily basis.

Technical requirements

To follow along, you’ll need the following:

Creating a Python environment

Let’s create a directory where our project will reside. From the terminal, run the following command:

$ mkdir twilio_github_actions

Next, cd into the project directory and run the following command to create a virtual environment.

$ python -m venv venv

To activate the virtual environment on a Mac or Linux machine, run the following command:

$ source venv/bin/activate

If you are using a Windows computer, then the activation command is different:

$ venv\Scripts\activate

Next, we’ll install all the dependencies our project will be needing:

  • twilio: A Twilio helper library for interacting with Twilio’s REST API.
  • python-dotenv: A library for importing environment variables from a .env file.

Next, run the following command to install all of the dependencies at once:

$ pip install twilio python-dotenv

Building the App

For the purpose of this tutorial, you’ll use a JSON file to store all the motivational quotes you’ll be sending to yourself. At the root of your project directory, create a quotes.json file and paste the following into the file:


  {
    "quote": "Watch what you say

All the quotes here were obtained from ZenQuotes.

Next, create a main.py at the root of your project directory and add the following code to the file:

import os
import random
import json
from dotenv import load_dotenv
from twilio.rest import Client

load_dotenv()
twilio_client = Client()

def send_motivational_quote():
    f = open("quotes.json", "r")
    data = json.load(f)
    twilio_from = os.getenv("TWILIO_NUMBER")
    to_phone_number = os.getenv("TO_PHONE_NUMBER")
    message = random.choice(data)["quote"]
    twilio_client.messages.create(body=message, from_=f"{twilio_from}", to=f"{to_phone_number}")
    return

send_motivational_quote()

At the top of this file, all the major dependencies the project will be needing have been imported:

  • The load_dotenv() function is used to load environment variables.
  • The twilio_client object will be used for interacting with the Twilio API to send the SMS notification. The TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN environment variables loaded by the load_dotenv() function will be automatically used to authenticate against the Twilio service.
  • A random quote is then fetched from the quotes.json file you created earlier and is then sent via SMS to a preconfigured phone number.

Create a GitHub Actions workflow file

GitHub Workflows usually reside in a /.github/workflows directory within a repository. Within your project directory, run the following command:

$ mkdir -p ./.github/workflows

This will create a .github/workflows directory. Next, run the following command to create a sms.yml file within that directory:

$ touch ./.github/workflows/sms.yml

Add the following code to the file you just created:

name: Send Daily SMS

on:
  schedule:
    - cron: '0 8 * * *'
  
jobs: 
    daily_sms:
      runs-on: ubuntu-latest
      steps: 
        - name: Setup Python
          uses: actions/setup-python@v3
          with:
            python-version: '3.9'

        - name: Checkout
          uses: actions/checkout@v3

        - name: Send SMS
          run: |
            echo $(pip --version)
            pip install twilio python-dotenv
            python main.py
          env: 
             TWILIO_ACCOUNT_SID: ${{ secrets.TWILIO_ACCOUNT_SID }}
             TWILIO_AUTH_TOKEN: ${{ secrets.TWILIO_AUTH_TOKEN }}
             TWILIO_NUMBER: ${{ secrets.TWILIO_NUMBER }}
             TO_PHONE_NUMBER: ${{ secrets.TO_PHONE_NUMBER }}

The on value of the workflow includes the schedule value which is used to trigger a workflow to run at a scheduled time. You can schedule a workflow to run using the POSIX Cron Syntax. In this case, the workflow will be triggered every day at 8:00 UTC.  You can learn more about the schedule event here.

The daily_sms job installs Python version 3.9 and then subsequently runs the main.py script.

Setting up Twilio

After you sign up for an account on Twilio, head over to your Twilio Console and click on Phone Numbers. If you already have one or more phone numbers assigned to your account, select the number you would like to use for this project. If this is a brand new account, buy a new phone number to use on this project.

On your Twilio Console, take note of your Account SID and Auth Token. You are going to need these values to authenticate with the Twilio service.

Twilio Credentials

Next, head back to the project’s directory and create a .env file. Edit the file with all the credentials and settings we’ve noted thus far:

TWILIO_ACCOUNT_SID=xxxx
TWILIO_AUTH_TOKEN=xxxx
TWILIO_NUMBER=xxxx
TO_PHONE_NUMBER=xxxx

Don’t forget to replace “xxxx” with the actual values.

The TO_PHONE_NUMBER here refers to the actual number that will be receiving the SMS and should be in the canonical E.164 format.

Since you'll be pushing this codebase to GitHub shortly, it’s important to make sure you don’t mistakenly commit sensitive credentials to GitHub. Create a .gitignore file and add the following to the file:

.env
venv

Testing

Before committing all your changes and pushing to GitHub, let’s make sure everything works as expected locally. To start the application, open a terminal window, activate the virtual environment and run the following command:  

(venv) $ python main.py

The phone number you configured earlier in the .env file should have received a random motivational quote via SMS.

Once you confirm everything works as expected, you can create a repository on GitHub and then push the code changes to the repository.

After pushing your changes to GitHub, you need to configure certain environment variables the workflow needs to run. Head over to the main page of your repository and select “Settings”. Under the “Security” section of the sidebar, select “Secrets and variables” and then click “Actions”. Select the “Secrets” tab and then click “New repository secret”. You can now add each of the environment variables you defined earlier and their corresponding values.

Creating a new repository secret

Once you have added all 4 secrets, your workflow will have all it needs to automatically send you a new motivational quote via SMS every day at 8:00 UTC. If you like, feel free to change this to a different time of your choice.

Conclusion

In this tutorial, we’ve seen how, by using Twilio SMS and GitHub Actions, we can run a scheduled task on a predefined interval. This can serve as a low cost way of running a scheduled task without deploying your code on an actual server.

Dotun is a backend software engineer who enjoys building awesome tools and products. He also enjoys technical writing in his spare time. Some of his favorite programming languages and frameworks include Go, PHP, Laravel, NestJS, and Node.

Website: https://dotunj.dev/
GitHub: https://github.com/Dotunj
Twitter: https://twitter.com/Dotunj_