Sending Bulk SMS using Africas Talking, Python and CSV
Tags: python, sms, africastalking, tutorial
Published: 2021-03-05 14:51:44

Sending messages using Africas Talking api is relatively easy and straightforward. Primarily thanks to their awesome [documentation](https://developers.africastalking.com/) and [tutorials](https://developers.africastalking.com/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](https://africastalking.com/)
## 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](https://account.africastalking.com/auth/register/).
  - Api Key and username from your account.

Alternatively check the completed code on [Github](https://github.com/KenMwaura1/Africas-Talking-Multiple-SMS)
Once you've got the above sorted, create a new directory to work with and install the modules we'll need.

```shell
mkdir at-project 
cd at-project
python -m venv .
source bin/activate
pip install africastalking python-dotenv
pip freeze > requirements.txt 
```
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](https://github.com/pyenv/pyenv) is a great alternative I would
recommend or [pyenv-win](https://github.com/pyenv-win/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](https://www.nylas.com/blog/making-use-of-environment-variables-in-python/)
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
```
Finished with all that. Now let's send some messages!

## Messages for Everyone
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fv4s0ni1jpej02ewijb0.gif)

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

```python
# 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
```
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.

```python
# 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()
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4n7n00goryf64kkn5zey.jpg)
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](https://twitter.com/Ken_Mwaura1)