WhatsApp has become one of the most popular messaging platforms in the world, with over 2 billion active users. Given its widespread use, developers are increasingly looking for ways to integrate WhatsApp messaging capabilities into their applications using Python.
In this comprehensive guide, we will walk through the steps to send a WhatsApp message programmatically using Python. We will cover installing the necessary libraries, setting up a WhatsApp webhook, formatting messages, and finally sending messages via a Python script.
Prerequisites
Before we dive into the coding, there are a few prerequisites:
- Python 3.6 or higher installed on your system
- Basic knowledge of Python programming
- WhatsApp account and phone number you want to use for sending messages
- Access to Twilio account or you can sign up for a free trial
Python is cross-platform so you can follow along on Windows, Mac OSX or Linux. We’ll also be using pip to install the Python libraries we need.
Installing the Twilio and HTTP Libraries
We will leverage Twilio’s API to integrate WhatsApp sending capability in Python. Twilio provides a Python helper library to make this integration easy.
Let’s install the Twilio library:
pip install twilio
We’ll also need the Requests library to make HTTP requests:
pip install requests
Getting Credentials from Twilio
To use Twilio’s API, you will need 3 pieces of information:
- Account SID – Identifier for your Twilio account
- Auth Token – Used for authentication
- Phone number – Twilio number that is linked to your account
After signing up for a Twilio account, you can find these credentials on your Twilio console dashboard.
Make sure to copy these and have them handy as we will need them later.
Setting up a WhatsApp Webhook
Now comes the most important part – setting up a webhook that will allow Twilio to communicate with your Python code.
Whenever you send a WhatsApp message via Twilio API, Twilio will make a request to this webhook URL with information about the message status.
There are a few ways to implement this webhook:
- Expose your local development server publicly via ngrok
- Host a serverless function on a cloud provider like AWS Lambda
- Use a platform like BeepBoop or Yurr to manage your webhook
For this guide, we will use ngrok to expose our local Python server.
Install ngrok
Download and install ngrok from here.
Once installed, run the following in a terminal:
ngrok http 5000
This will expose port 5000 and give you a URL like
http://845632167.ngrok.io.
Keep this running and copy the ngrok URL.
Configure Webhook in Twilio
Now let’s setup the webhook in Twilio console:
- Go to WhatsApp section in Twilio console
- Click on “Configure” and scroll to Webhook section
- Set your ngrok URL + ‘/whatsapp’ as webhook URL
- Click Save to apply the webhook config
Building the Python Webhook
With the webhook configured, let’s write a simple Python server that will receive and handle these webhook requests from Twilio.
Create a file called app.py and add the following code:
from flask import Flask, request import twilio app = Flask(__name__) @app.route('/whatsapp', methods=['POST']) def inbound_message(): print('Incoming message: ', request.values.get('Body')) return 'OK', 200 if __name__ == '__main__': app.run(debug=True, port=5000)
This implements a simple Flask server to respond on your /whatsapp route and print any incoming messages.
Now run this server:
python app.py
Keep this running. Your webhook is now ready to receive messages.
Sending a WhatsApp Message
Finally, let’s write the Python code to send an actual WhatsApp message using the Twilio API.
Create a new file send_whatsapp_message.py:
from twilio.rest import Client account_sid = 'ACxxxxxxxxx' auth_token = 'xxxxxxxxxxx' client = Client(account_sid, auth_token) message = client.messages.create( from_='whatsapp:+14155238886', body='Hello there!', to='whatsapp:+15005550006' ) print(message.sid)
Make sure to use your actual Account SID, Auth Token and the WhatsApp Twilio number linked to your account.
Also change the to number to your own WhatsApp number that you want to send a test message to.
Now simply run this script:
python send_whatsapp_message.py
If successful, you should see a message SID printed indicating the message was sent.
You should also see the message arrive on the mobile number you specified!
Additionally, you can check your Flask server terminal to see the webhook request come in when the message was sent.
Handling Incoming Messages
So far we have only handled outgoing messages. To respond to incoming WhatsApp messages, we can modify our Flask webhook.
Update the inbound_message() function in app.py:
@app.route('/whatsapp', methods=['POST']) def inbound_message(): from_number = request.values.get('From') body = request.values.get('Body') response = MessagingResponse() response.message("Thanks for your message!") client.messages.create(from_='whatsapp:+14155238886', body=response.to_xml(), to=from_number) return '', 200
This will send an automated reply message back to the user. The MessagingResponse helps format the Twilio XML response.
You can further enhance the bot by adding conditional logic, integrating with NLP APIs like Dialogflow or Lex, or connecting to a database. The possibilities are endless!
Conclusion
And that’s it! In this guide we covered:
- Installing the Twilio and Flask Python libraries
- Exposing your local server via ngrok
- Configuring a webhook in the Twilio console
- Building a simple Flask webhook to handle requests
- Coding the Python logic to send & receive WhatsApp messages
Twilio provides a powerful set of APIs to integrate messaging across platforms. With just Python and a few lines of code, you can now build WhatsApp bots and automation using Twilio!
Some ideas for next steps:
- Expand the bot with natural language capabilities
- Add support for media messages
- Integrate with an existing database
- Deploy your webhook to a cloud platform
I hope you found this guide useful. Let me know in the comments if you have any other questions!