Python Twilio – Automate WhatsApp Business API Messages

Automatic Whatsapp Message Sending Using API

In this article, we’ll explore a better way to automate WhatsApp messaging using the Python Twilio module. We’ll discuss how to set things up, and what are the caveats to this method.

What is Twilio?

Twilio is a cloud communication platform that allows its clients to make and receive calls, text messages, social media messages, and a wide variety of functions over the internet. Twilio along with its API can be programmatically used to send automated messages and calls as required for personal or business purposes.

Its latest feature is the integration with Whatsapp Business API which allows business owners to automate communication with their customers.

Advantages of using Messaging Service Provider (like Twilio)

A large number of individuals and businesses are using messaging apps to send notifications/alerts of their business offers, purchases, etc. Even some serve queries to fetch user and account information even.

Why use a massage service API?

  • The message/notification/response can be sent at any time of the day when the script is running on a server
  • No or very less down time
  • Easy to implement as we only need to take care of passing the parameters and the API handles the rest for us.

How to Automate WhatsApp Business API Messages using Python Twilio

Let’s now go over the steps to automate the messages using the WhatsApp Business API with the Python Twilio library. This method is better than our previous way of sending messages using Pywhatkit since you do not need to keep your WhatsApp web open and logged in.

Also, once you have access to the API, there’s a lot more automation that you can perform including creating full-fledged WhatsApp bots.

Step 1. Create Account

Create an account on Twilio, with the Free trial version account, which doesn’t even require a credit/debit card authorization.

Verify your e-mail and phone number to enable the use of all the tools and features(free) available. Feel free to complete other formalities for account setup, which is completely free and you get $15.50 as a trial account bonus.

When you create your Twilio account, the Whatsapp must be approved by your Facebook Business Manager Account in order to have your Twilio number associated with the Whatsapp Business Profile.

Step 2. Get Account Details

Once your Twilio number has been approved, you can use the python library to send and receive messages.

Follow these step-by-step guides to send WhatsApp messages automatically:

  1. Get Your Account SID and Authentication Token from the Twilio Console, which is shown in the Project info section of your account on the homepage.
Account SID And Authentication In Twilio to send WhatsApp message using Python
Account SID And Authentication In Twilio

3. Install the required library [Code Implementation]

Install Twilio library into your computer using the pip package manager, in your command prompt or terminal window. If you do not have access to PIP, there are other ways to install it here.

pip install twilio

Now as we have installed the required library, we need to import it into our code.

Create a new python file (Ex. whatsapp-msg.py). Import the client function from the helper library at the top of the file you just created.

#import the Client function from the helper library
from twilio.rest import Client

Then import the OS library. We will use this library’s environment variables. These are values that are accessible within the computer’s terminal and are used to store data in a more consistent manner.

#import OS for environment variables
import os

4. Authorize Twilio API in Code

Now, set environment variables for SID and Auth keys. These are the values we got from Twilio Console in step 2. They will help Twilio authorize (confirm) that we are the actual users of their WhatsApp messaging API.

#set the User credentials
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)

In place of ‘TWILIO_ACCOUNT_SID’ and ‘AUTH_TOKEN’, you need to enter Account SID and Auth Token (from the Twilio dashboard) in the code for valid authorization.

5. Send Text Message

To send a standard WhatsApp text message, we use the “messages.create()” method from the client object from the Twilio library, with the following arguments:

  • body: The message that you wish to send/broadcast
  • From_ : The Twilio number that got approved for Whatsapp Web
  • To: The number you want to sent the message on WhatsApp
#send text message

text_message = client.messages.create(
                              body='Hello there!',
                              from_='whatsapp:+14155238886',
                              to='whatsapp:+15005550006'
                          )

6. Send Media (Image/Video) message

To create a media message, call the “messages.create()” function under client object with the following arguments:

Everything remains the same except for the body parameter.

  • media_url: the media file (image/video/gif) that is to be sent (can be file or link)
#send media message

media_message = client.messages.create(
                              media_url=['https://images.unsplash.com/photo-1545093149-618ce3bcf49d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=668&q=80'],
                              from_='whatsapp:+14155238886',
                              to='whatsapp:+15005550006'
                          )

7. Print Response

This is important because it tells us the response Twilio gives back. In case of an error, this is how we would know, what the error is or what part of the code has caused the error

#print response
print(text_message.sid)
print(media_message.sid)

A successful response should look like this

Successful Response From Twilio Api
Successful Response From Twilio API

Conclusion

This method requires additional steps compared to our previous method which used the web browser and simulated keyboard and mouse movements. But if you are a business, and are looking for ways to build advanced response systems for your customer support, this method is absolutely worth a try.