DEV Community

Cover image for Sending Bulk SMS using Africas Talking, Python and CSV
Zoo Codes
Zoo Codes

Posted on • Edited on

Sending Bulk SMS using Africas Talking, Python and CSV

Sending messages using Africas Talking api is relatively easy and straightforward. Primarily thanks to their awesome documentation and tutorials.
However, what if you had to send 10 messages or 10,000 people specifically contained in a CSV

Recently I was requested to help a Sacco send bulk messages to their members to notify them of an upcoming meeting.
A quick Google search revealed a few sms providers, but being the developer I am,it seemed a good opportunity to use one of favorite platforms Africastalking

Preparation

To follow along with this post and subsequent code, you will need a few prerequisites:

  • Python and pip (I am currently using 3.9.2 ) Any version above 3.5 should work.
  • An Africas Talking account.
    • Api Key and username from your account.

Alternatively check the completed code on Github
Once you've got the above sorted, create a new directory to work with and install the modules we'll need.

mkdir at-project 
cd at-project
python -m venv .
source bin/activate
pip install africastalking python-dotenv
pip freeze > requirements.txt 
Enter fullscreen mode Exit fullscreen mode

I'll breakdown the code above, Line 1 and 2 creates a working directory and changes into the directory.

Following best practices, in line 3 and 4 we create and activate virtual environment to prevent cluttering
the main python system version as well avoid version conflicts. You don't have to use the
default venv module, pyenv is a great alternative I would
recommend or pyenv-win for Windows users.

Line 4 and 5 uses built-in python package manager, pip to install the required modules.
in this case it's the africastalking python sdk and python-dotenv module to aid keeping
our credentials in a separate file for security reasons. You can do further reading
on how to use environment variables in python.

For this use case I am using the python-dotenv package to store the credentials
needed to authenticate with the Africas talking API. Let's add those credentials now.
Create a file called .env and enter the following replacing the placeholders with your account credentials:

# Both can be obtained from your account console on Africas Talking
username=Username-here
api_key=apikey-here
Enter fullscreen mode Exit fullscreen mode

Finished with all that. Now let's send some messages!

Messages for Everyone

Alt Text

Create a new file, multiple-sms-csv.py. Add the following

# multiple-sms-csv.py
import os
import datetime
import csv
import africastalking as at
from dotenv import load_dotenv
# the load_dotenv function gets the environment variables defined in .env file
load_dotenv()
# assigns the variables to the environment variables
api_key = os.getenv("api_key")
username = os.getenv("username")
# Initialize the Africas Talking client with the required credentials
at.initialize(username, api_key)
# assign the sms functionality to a variable
sms = at.SMS
Enter fullscreen mode Exit fullscreen mode

The code above imports the required modules. retrieves the required credentials and initializes the Africas Talking client.

Now we'll write a function to parse the csv and get the numbers and optionally names.
Ensure the csv with the numbers you want to send messages to is in our working directory.

# multiple-sms-csv.py 
# create a function to parse the CSV and send a customized message
def send_messages():
  # parse the provided CSV with the inbuilt csv library
  with open('sample.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
      name = row[1]
      number = row[2]
      if number != "Number":
        print(name, number)
        # Get the current date and time
        local_time = datetime.datetime.now()
        date_difference = datetime.timedelta(days=5)
        meeting_date = local_time + date_difference
        # create a customized message with the required meeting date
        message = f"Hello {name}, this message sent to inform you of a meeting scheduled on {meeting_date}"
        # For each entry send a customized message
        try:
          response = sms.send(message, [number])
          print(response)
        except Exception as e:
          print(f'Uh oh we have a problem: {e}')
      else:
        print("Not a valid number")

send_messages()
Enter fullscreen mode Exit fullscreen mode

The above code creates a function send_messages(). Inside the function we open the csv and use the reader() function from the inbult csv module to parse each row. From each row we get the value of name and numbers using list unpacking, this will ofcourse change based on the layout of your csv.

We then proceed to assign variables to each value. Inorder to send messages to each member we need to iterate over each row, however the first row is just default column headers thus we need to skip them hence: if number != "Number:

The meeting was scheduled for 5 days from the current day, using the datetime module I did quick calculations using the timedelta() function. I could ofcourse have hard-coded the date as a string,however I wanted this script to be reusable and easy make modifications going
forward.

We then create a message variable to hold our customized message. we could go ahead and send it as is. However, its not uncommon for messages to fail due to a variety of reasons hence I added a try block and get notified via the terminal and retry later.

Notifications for all

Alt Text
Now we can Finally run python multiple-sms-csv.py and watch the output on the terminal. using the combined power of Africas Talking and python you can easily handle sending one, a few or a lot of messages. Enabling you to scale up.

If you have any question or comments. Let me know in the comments,
or on Twitter

Top comments (0)