WhatsApp has become one of the most popular messaging apps with over 2 billion active users worldwide. Its ubiquity and ease of use make it an ideal platform for automated messaging and notifications. Python, with its many robust libraries and frameworks, provides an easy way to programmatically send WhatsApp messages and text.
In this comprehensive guide, we will walk through the steps to send WhatsApp text and media messages using Python. We will cover the requirements, the different methods and APIs available, sample code snippets, and tips and tricks. By the end, you will have the knowledge to build Python scripts and integrations to send automated WhatsApp messages.
Requirements
To send WhatsApp messages from Python applications, you need to fulfill the following requirements:
Python
Python 3 needs to be installed on your system. Python has built-in support for WhatsApp sending via the PyWhatsapp library. Make sure you have the latest version of Python 3.
WhatsApp API or Gateway
Unlike other messaging apps, WhatsApp does not provide an official API for third-party integration. However, there are some unofficial APIs and gateways that enable sending WhatsApp messages from Python. These include:
– WhatsApp Business API – Offers paid plans for businesses to integrate with WhatsApp.
– Twilio API – Provides a WhatsApp API to send messages.
– Infobip – API gateway for businesses to integrate with Whatsapp.
– Chat-API – Provides a webhook interface to connect Python with WhatsApp.
WhatsApp Account
You need access to a WhatsApp account to send out messages. This account acts as the sender ID when messages are delivered. For personal use, your own WhatsApp account will work.
For business purposes, you can use a dedicated Twilio number or WhatsApp Business API account as the sender.
Phone Numbers
The recipient’s phone numbers will be needed to send targeted WhatsApp messages from your Python app. The numbers must be in the proper country code format.
Methods to Send WhatsApp Messages from Python
There are a few different methods and APIs available to send WhatsApp text and media messages from Python:
PyWhatsapp Library
PyWhatsapp is an unofficial Python library that provides a wrapper for WhatsApp Web to enable sending messages. Here are the steps to use it:
1. Install the pywhatkit library – `pip install pywhatkit`
2. Import the library – `import pywhatkit`
3. Use the `sendwhatmsg()` method to send a message – `pywhatkit.sendwhatmsg(“+911234567890”, “Hello!”, 15, 30)`
This will send the text “Hello!” to the number at 15:30 hours.
Twilio API
Twilio provides an API to integrate WhatsApp messaging into apps. Here are the steps to use Twilio:
1. Sign up for a Twilio account and get API credentials.
2. Install Twilio Python library – `pip install twilio`
3. Import library and create client –
“`python
from twilio.rest import Client
client = Client(“TWILIO_SID”, “TWILIO_AUTH_TOKEN”)
“`
4. Send WhatsApp message –
“`python
from twilio.rest import Client
client = Client(“TWILIO_SID”, “TWILIO_AUTH_TOKEN”)
client.messages.create(
body=”Hello there!”,
from_=”whatsapp:+14155238886″,
to=”whatsapp:+15105551234″
)
“`
WhatsApp Business API
The WhatsApp Business API allows businesses to send notifications and messages at scale. Here is how to use it:
1. Create a Business account and get API credentials.
2. Install WhatsApp Business SDK.
3. Import and initialize client –
“`python
from fbwhatsapp import Client
client = Client(auth=”business_account_id”, number_pool=”WHATSAPP_NUMBER”)
“`
4. Send message –
“`python
client.send_message(number_id=”RECIPIENT_NUMBER”,
message=”Hello from WhatsApp Business API”)
“`
Infobip
Infobip provides a WhatsApp messaging API connected to chatbots. Here is how to use it:
1. Create an Infobip account and get API credentials.
2. Install the Infobip Python SDK.
3. Initialize the Infobip client.
4. Send a WhatsApp text message.
Chat-API
Chat-API offers a webhook interface to connect Python applications to WhatsApp. Here are the steps:
1. Create an account on Chat-API and get an API token.
2. Set up a webhook endpoint in Python to receive messages.
3. Register the webhook in Chat-API dashboard.
4. Send WhatsApp messages by making POST requests to Chat-API endpoints.
So in summary, the main methods are:
– PyWhatsapp library – Simple wrapper for WhatsApp Web
– Twilio API – Robust API with business support
– WhatsApp Business API – Official API for businesses
– Infobip – WhatsApp gateway and chatbot integration
– Chat-API – Webhook interface for Python
Code Snippets
Here are some code snippets for sending WhatsApp messages using different Python methods:
PyWhatsapp
“`python
import pywhatkit
pywhatkit.sendwhatmsg(“+91123456789″,”Hello from Python!”,15,30)
“`
Twilio
“`python
from twilio.rest import Client
client = Client(“TWILIO_SID”, “TWILIO_AUTH_TOKEN”)
client.messages.create(
body=”Hello from Twilio!”,
from_=”whatsapp:+14155238886″,
to=”whatsapp:+15105551234″
)
“`
WhatsApp Business API
“`python
from fbwhatsapp import Client
client = Client(auth=”BUSINESS_ID”, number_pool=”WHATSAPP_NUMBER”)
client.send_message(number_id=”RECIPIENT_NUMBER”, message=”Hello!”)
“`
Infobip
“`python
from infobip.api.model.whatsapp.mt.send_message import SendMessage
from infobip.clients import whatsapp_client
message = SendMessage(
from_=”InfoSMS”,
to=”41793026727″,
text=”Hello from Infobip’s WhatsApp API!”
)
info_client = whatsapp_client.WhatsAppClient(“USERNAME”, “PASSWORD”)
info_client.send_message(message)
“`
Chat-API
“`python
import requests
url = “https://api.chat-api.com/instance12345/message?token=abcdef”
data = {
“phone”: “15105551234”,
“body”: “Hello from Chat-API!”
}
requests.post(url, json=data)
“`
These code samples demonstrate the simplicity of sending WhatsApp messages with just a few lines of Python code by using the various APIs and libraries.
Sending Media Messages
In addition to text, WhatsApp also allows sending media messages like images, documents and videos. Here is how to send media files with different methods:
PyWhatsapp
To send a photo:
“`python
import pywhatkit
pywhatkit.sendwhats_image(“+911234567890″,”/path/to/image.png”, “Photo Caption”)
“`
Twilio
To send a video:
“`python
from twilio.rest import Client
client = Client(“TWILIO_SID”, “TWILIO_AUTH_TOKEN”)
client.messages.create(
media_url=[“https://example.com/video.mp4″],
from_=”whatsapp:+14155238886″,
to=”whatsapp:+15105551234”
)
“`
WhatsApp Business API
To send a PDF document:
“`python
from fbwhatsapp import Client, MessageType
client = Client(auth=”BUSINESS_ID”)
client.send_message(number_id=”RECIPIENT_NUMBER”,
filename=”file.pdf”,
caption=”See attached doc”,
messaging_product=MessageType.WHATSAPP)
“`
So you can customize the media type and file to send images, videos, documents and more.
Sending to Multiple Recipients
You can also use Python to send a WhatsApp message to multiple recipients at once. Here is how:
With PyWhatsapp
“`python
import pywhatkit
# List of numbers
numbers = [“+91123456789″,”+91987654321″,”+91789456123″]
for number in numbers:
pywhatkit.sendwhatmsg(number,”Message sent to all!”,15,30)
“`
With Twilio
“`python
from twilio.rest import Client
client = Client(“TWILIO_SID”, “TWILIO_AUTH_TOKEN”)
# List of recipient numbers
recipients = [“whatsapp:+14155238886”, “whatsapp:+15105551234″]
for recipient in recipients:
client.messages.create(
body=”Broadcast Message”,
from_=”whatsapp:+14155238886″,
to=recipient
)
“`
So you can easily customize and scale your WhatsApp messages to reach multiple recipients at once from Python.
Sending Recurring scheduled Messages
For periodic reminders and alerts, WhatsApp messages can also be scheduled and automated using Python scripts.
Here is an example to send a repeated WhatsApp message daily at 7 AM using schedule and time libraries:
“`python
import schedule
import time
import pywhatkit
def send_message():
pywhatkit.sendwhatmsg(“+911234567890″,”Daily 7AM Message”,7,0)
schedule.every().day.at(“07:00”).do(send_message)
while True:
schedule.run_pending()
time.sleep(1)
“`
So you can build powerful workflows to send regular reminders, alerts, digests via WhatsApp using Python’s scheduling capabilities.
Building WhatsApp Chatbots
Python can also be used to build conversational WhatsApp chatbots by integrating NLP libraries like Dialogflow or Rasa:
“`python
# Import Flask and NLP libraries
from flask import Flask, request, Response
import requests
# Initialize Flask app
app = Flask(__name__)
@app.route(‘/webhook’, methods=[‘POST’])
# Function to detect intent and respond
def respond():
msg = extract_msg(request)
response = get_bot_response(msg)
return response
def extract_msg(req):
# Extract WhatsApp msg
return req.json[“message”]
def get_bot_response(msg):
# Send msg to Dialogflow
# Get bot response
return bot_response
if __name__ == “__main__”:
app.run()
“`
The chatbot can have advanced conversational flows using Dialogflow’s NLP training. WhatsApp provides an easy way to build and deploy such bots.
Tips and Tricks
Here are some tips to keep in mind while sending WhatsApp messages from Python:
– Always double check the phone numbers for typos before sending messages. Invalid numbers will fail.
– Follow WhatsApp guidelines and be careful about sending frequent or bulk messages to avoid blocks.
– Use media links with proper MIME types when sending media files like images, videos.
– Prefer using WhatsApp Business API or Twilio over other DIY tools for large scale messaging.
– Store phone numbers in a database rather than hardcoding into scripts for easy management.
– Add error handling, logs and retry mechanisms in your script to handle failures.
– Make use of WhatsApp templates, quick replies and buttons for more interactive messaging.
Conclusion
This guide provided an overview for sending WhatsApp text and media messages from Python scripts using various APIs and libraries. The key methods covered include using the PyWhatsapp library, Twilio API, WhatsApp Business API, Infobip and Chat-API.
We looked at code samples for sending simple text messages, media files, broadcasting to multiple recipients and scheduling recurring messages. WhatsApp chatbots can also be integrated using Python and NLP libraries like Dialogflow.
By learning these techniques, you can build automated WhatsApp messaging bots for personal and business purposes using Python. The possibilities are immense when combining the ubiquity of WhatsApp with the power of Python.
Frequently Asked Questions
Is sending WhatsApp messages using Python legal?
Yes, it is legal to send WhatsApp messages using Python as long as you follow WhatsApp’s Terms of Service and don’t spam people. Make sure to get opt-in consent before sending bulk messages.
Do I need to keep my computer/phone connected to send WhatsApp messages from Python?
For PyWhatsapp library, your computer needs to be connected as it uses WhatsApp Web in the backend. For other APIs like Twilio, your Python script can run standalone without a device being connected.
Can I build a full-fledged WhatsApp chatbot in Python?
Yes, you can use Python to build WhatsApp chatbots with NLP capabilities using libraries like Dialogflow, Rasa, ChatterBot. The chatbot can have sophisticated conversational abilities.
How many WhatsApp messages can I send programmatically per day?
WhatsApp has a limit of sending bulk messages to 1000 unique recipients per day. Beyond that volume, your account may get blocked. For larger volumes, use official WhatsApp Business API.
Is there an official WhatsApp API for Python?
No, WhatsApp does not provide an official API. But the WhatsApp Business API can be used with Python to manage business messaging. Unofficial APIs like Twilio also work well.
Source Code
You can find the full source code for sending WhatsApp messages from Python in this GitHub repo:
https://github.com/user/whatsapp-python-code
It contains examples covered in this article for using different libraries and APIs. Feel free to use it as a starting point for your own WhatsApp bots and scripts.