How To Use the WhatsApp API with Python_ Send & Receive Messages
How To Use the WhatsApp API with Python_ Send & Receive Messages
Docs
API Glossary
Blog Sign Up
The Maytapi WhatsApp API is an unofficial WhatsApp API. With this API, you
can send messages on behalf of a WhatsApp number. You can also see all the
WhatsApp messages received by the number.
Just like the WhatsApp web app, which runs a parallel WhatsApp session that
mirrors the WhatsApp app running on a phone, the Maytapi WhatsApp API also
runs a parallel session. This allows you to build programmable conversations
workflows for applications such as bots. However, with this API, you can
achieve much more than a typical bot.
To get started with the Maytapi WhatsApp API, follow the steps below to sign
up for a RapidAPI account and subscribe to the API.
To access the Maytapi WhatsApp API, you’ll first have to sign up for a free
RapidAPI developer account. With this account, you get a universal API Key to
access all APIs hosted in RapidAPI.
RapidAPI is the world’s largest API marketplace, with over 10,000 APIs and a
community of over 1,000,000 developers. Our goal is to help developers find
and connect to APIs to help them build amazing apps.
To access the API console of Maytapi WhatsApp API, you can either search with
the query “Maytapi whatsapp api,” or alternatively, you can directly access the
API console here.
3. Subscribe to the WhatsApp API
Once inside the API console, click on the “Pricing” tab to access the pricing plan.
Maytapi WhatsApp API is a paid API. It has a Pro plan which gives you unlimited
API usage for USD 29.00 per month.
Make sure that you enter your billing details correctly and subscribe to this API.
You will be billed immediately for the API subscription and taken back to the
API console.
Follow these steps to set up the designated phone number and test the API.
Prerequisites
1. Both the designated phone and the second phone have an active
WhatsApp account associated with the respective phone numbers, and the
3. You have access to both the phones and can check the WhatsApp messages
on them.
The very first step is to add the phone number to your Maytapi WhatsApp API.
This is achieved by the “POST addPhone” API endpoint under the Account
Information Retrieval & Edit category of endpoints.
The request body accepts a JSON object with the key “number”. Set it’s value to
the phone number of the designated phone number. Make sure to add the
country code, without the ‘+’ sign.
Trigger the API, and you should get a success response as follows.
This response contains a phone id assigned to the new phone number. Take note
of this phone id as it will be used for other API calls.
Note: If you have already added a phone number then you must remove it
through the “POST deletePhone” endpoint. The Maytapi WhatsApp API allows
you to add only one phone number at a time.
After the phone number is added, you can check the status of the newly
generated phone id. To do this, trigger the “GET getStatus” endpoint under the
Session Information Getters category of endpoints.
Set the value of the ‘phone_id’ parameter with the phone id generated in the
previous step and trigger the API.
The API returns a response containing several status flags for various
operations of the API, that is related to the WhatsApp account of the phone
number.
As you can see, the value of ‘isQR’ is set to true. It means that the API is
expecting you to scan the QR code from the WhatsApp app to activate the
WhatsApp session through the API.
“
With the phone number added to the API, you must now activate it via the API.
This process is essential because it establishes the association between the API
and the phone number through the phone device.
Set the value of the ‘phone_id’ parameter with the phone id generated in the
first step and trigger the API.
Note: The QR code is valid for a limited time. Hence it should be scanned as
soon as it is generated. In case the app displays an error, make sure that the
phone is connected to the Internet, and the WhatsApp web session of this
phone is already active on a browser.
This step is the same as step 2. Here you invoke the “GET getStatus” endpoint
again to get the status.
Since the WhatsApp app on the phone is now associated with the API, you get a
different status now.
You get the value of “loggedIn” as true, and you should also see the phone
number of the designated phone. This means that the phone number, ending
with the digits 177 is now associated with the Maytapi WhatsApp API and is
logged in.
You are now ready to initiate WhatsApp conversation for this number via the
API.
At this point, your designated phone number is linked to the Maytapi WhatsApp
API. Now you can send a message with another WhatsApp number from the API
itself, without using the WhatsApp app on the phone or through the WhatsApp
web session.
Go ahead and select the “POST sendMessage” endpoint under the Message
Sending Operations category of endpoints.
Enter the phone id as the value for ‘phone_id’ parameter. In the JSON structure
for the Request Body, set the ‘to_number’ as the phone number of the second
phone that you have. Trigger the API.
The API response shows a success message with the message id.
The real proof of this operation lies in seeing the message “Hello” on the
WhatsApp app of the second phone. This message should appear within a few
seconds.
Through the Maytapi WhatsApp API, you can get a log of all the messages that
are sent to the API designated phone number. However, the log also includes
the API calls that are triggered, including the ones used for adding the phone
number and scanning the QR code to connect the API with the phone number.
Select the ”GET logs” API endpoint under the Session Information Getters
category on endpoints.
It accepts only one parameter, which is ‘page’. The value of this parameter
signifies the page number of the logs. This is done to ensure that the logs are
arranged and returned by the API response in a paginated manner.
In this way, you can scan through all the historical WhatsApp messages received
by the designated number, from the time the number was activated via the
Maytapi WhatsApp API.
With this step, you have verified both the message sending and receiving
capabilities of the Maytapi WhatsApp API.
Now it’s time to leverage this API for some practical use cases.
Connect to the WhatsApp API
With the programmable access to send and receive WhatsApp messages, you
can think of leveraging WhatsApp conversations to build automated workflows.
4. Check the timestamp of image data to verify that the image is created
5. Check location data in the image to verify the person’s home location.
monitored persons.
If you have to monitor many persons in this way, then it’s too much of a manual
effort to sift through their WhatsApp messages every hour. That is the problem,
and that’s where automation comes in to save your life.
To automate this workflow, you can split it into three phases. The first phase is
for message broadcasting that sends the reminder at the beginning of the day.
The second phase is the message reception, which checks for the received
image from the monitored person. The third and final phase is about verification
of a person’s identity and location, based on the image along with the follow-on
actions in case the person does not adhere to the workflow.
Let’s write a Python script for self-executing the phase one and two. These are
covered by the step1 and 2 of the workflow, respectively. The remaining steps,
which are part of phase 3, are not considered because they are not in the scope
of Maytapi WhatsApp API handling.
Before writing the scripts, make sure that you have a Python3 environment
installed on your computer, which executes these scripts. Additionally, you also
need to install the requests library under your Python 3 environment.
Message Broadcasting
The message broadcast script is responsible for sending the daily reminder to
the person under quarantine. This script relies on the “POST sendMessage”
endpoint. You can check the Python code snippet for this endpoint in the
Maytapi WhatsApp API console.
Based on this snippet, you can write a simple Python script as the broadcast
script for performing step 1 of the quarantine monitoring workflow.
import requests
YOUR_RAPIDAPI_HOST = "maytapi-whatsapp.p.rapidapi.com"
YOUR_RAPIDAPI_KEY = "<YOUR_RAPIDAPI_KEY>"
YOUR_PHONE_ID = "<YOUR_MAYTAPI_PHONE_ID>"
QUARANTINE_MONITORED_PHONE = "<YOUR_DESTINATION_NUMBER>"
url = "https://maytapi-whatsapp.p.rapidapi.com/" +
YOUR_PHONE_ID + "/sendMessage"
print(response.text)
This script is very similar to the snippet, except that the parameters are defined
as constants. You have to replace the placeholders in the script with the value
specific to your API subscription.
This script just sends the pre-formatted message to the WhatsApp number
defined in QUARANTINE_MONITORED_PHONE. To keep things simple, we
have only considered one phone, which means that the broadcast message is
sent only to one person. Also note that we have not added any time-specific
logic to send the message broadcast at 9 am, as stated in the workflow. We will
handle it a little later.
Message Reception
The message reception script is responsible for monitoring the received images
from the person under quarantine. This script relies on the “GET logs” endpoint.
You can check the Python code snippet for this endpoint in the API console.
Similar to ‘MessageBroadcast.py’, write another script that reads the logs and
scans messages from the phone number of the person under quarantine. If
found, the script checks for images and extracts them.
import requests
import json
from datetime import datetime
YOUR_RAPIDAPI_HOST = "maytapi-whatsapp.p.rapidapi.com"
YOUR_RAPIDAPI_KEY = "<YOUR_RAPIDAPI_KEY>"
QUARANTINE_MONITORED_PHONE = "<YOUR_MONITORING_NUMBER>"
url = "https://maytapi-whatsapp.p.rapidapi.com/logs"
querystring = {"page":"1"}
headers = {
'x-rapidapi-host': YOUR_RAPIDAPI_HOST,
'x-rapidapi-key': YOUR_RAPIDAPI_KEY
}
t = datetime.utcnow()
l = json.loads(response.text)["data"]["list"]
image_found = False
for d in l:
if(d["type"] == "outgoing"):
if("user" in d["data"]["body"]):
if(d["data"]["body"]["user"]["phone"] ==
QUARANTINE_MONITORED_PHONE and hours < 1 and d["data"]
["body"]["message"]["type"] == "image"):
image_found = True
if res.status_code == 200:
with open(QUARANTINE_MONITORED_PHONE+".jpg",
'wb') as f:
f.write(res.content)
break
if(image_found):
print(QUARANTINE_MONITORED_PHONE + ": Picture Received
Within Last Hour")
else:
print(QUARANTINE_MONITORED_PHONE + ": Picture Not
Received Within Last Hour")
This script iterates through all the WhatsApp messages in the logs to look for
the monitored phone number of the person under quarantine. If found, a
comparison is done to ascertain if the message is of type image, and the
message is sent in the last one hour from the time the script was run.
If an image is found, then it is extracted and saved as a file in the same directory
as the script. Again note, this script does not consider the scanning of message
logs every hour, as per the workflow. This is addressed separately.
To test these scripts, you can do a mock trial with the two WhatsApp numbers
that you used earlier to test the Maytapi WhatsApp API.
Try to run the “MessageReceive.py” script again. But this time, run it after
sending an image from the second phone to the designated phone. Now you
should get a script output indicating that picture is received.
You can also check the image file saved with the same name as the phone
number of the second phone.
That’s it!
Now comes the exciting part. Since both the scripts do not maintain any logic to
keep track of time, you need to manage this externally, outside the scope of the
scripts. By running these scripts as part of a cron job on a server, you can quickly
achieve that.
The server acts as the controller of the WhatsApp session on behalf of the
designated phone. By configuring the ‘MessageBroadcast.py’ to execute as a
cron job every day at 9 am, and configuring the ‘MessageReceive.py’ to execute
as a cron job every hour between 10 am to 10 pm, you can achieve the message
scheduling requirements of the workflow.
The flow of data for message broadcast, as well as image reception, is depicted
in the figure. Remember the prerequisites to execute the scripts. The server
also must have the Python 3 environment installed with the requests library and
must be connected to the Internet.
In this way, you can automate the conversation between the health officials
monitoring the persons under quarantine without any manual SMS texting and
follow-ups.
Conclusion
As stated earlier, the identification and location verification of the images is not
covered by the scripts. You have to write additional logic to perform those steps
on the ‘MessageReceive.py’ script. That would make this a fully automated
workflow for quarantine monitoring. So why not take it as a challenge and see if
you can help your local authorities in tackling the menace of COVID-19?
Go ahead and subscribe to the Maytapi WhatsApp API and give it a shot. In case
you have a query and face any issues, then put a comment below, and we will
respond at the earliest.
Team RapidAPI
Search
Browse APIs »
APIs mentioned in this article
API Guides
API Courses
API Glossary
API Testing
API Management
Build API’s
About
Build APIs
Careers
Contact Us
Write for Us
API Directory
Press Room
Privacy Policy
Terms of Use