Whatsapp is an incredible tool for engaging in a text conversation. With the global crisis around the COVID-19 looming large, WhatsApp is also a congregation point for people to share knowledge and information related to the pandemic. But, as we all experience, too much information is hard to follow.
So we asked ourselves this question. How can we use WhatsApp effectively to tackle this situation without getting into reckless arguments or information overload?
With the help of an API, we can automate WhatsApp conversations. With an automated WhatsApp session, a text conversation takes the form of a workflow. Further, the workflow can be designed around solving a problem.
Maytapi WhatsApp API provides the tools for programmatically managing a WhatsApp number. This API has some great use for building automated workflows. If you are wondering how this is possible, then in this blog post, we take a look at one such use case. We will build a quick demo of a concept application using Python to monitor a person under quarantine, using WhatsApp.
View the Best Whatsapp APIs List
Overview of the WhatsApp API
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.
1. Sign up for RapidAPI Account
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.
2. Access the WhatsApp API
Once signed in, log in to your RapidAPI account.
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.
How to use the WhatsApp API
To use Maytapi WhatsApp API, you first have to set it up to mirror a WhatsApp account associated with a phone number. This phone number is the designated phone number whose WhatsApp account is controlled by the API. To test the message sending capabilities of the API, you should also have a second phone with an active WhatsApp account.
Follow these steps to set up the designated phone number and test the API.
Prerequisites
Before you proceed, make sure that
- Both the designated phone and the second phone have an active WhatsApp account associated with the respective phone numbers, and the numbers are known to you.
- The WhatsApp account of the designated phone number is accessible and active on the WhatsApp web.
- You have access to both the phones and can check the WhatsApp messages on them.
- Both phones are connected to the Internet.
Step 1: Add Phone Number
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.
Step 2: Get Phone Id Status
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.
Step 3: Scan QR Code to Activate Phone Number
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.
It is similar to how a WhatsApp web session starts by scanning the QR code of the WhatsApp web app on the WhatsApp phone app. In the case of the Maytapi WhatsApp API, you generate a QR code using the “GET getQRCode” endpoint under the Session Information Getters category of endpoints.
Set the value of the ‘phone_id’ parameter with the phone id generated in the first step and trigger the API.
The API response returns a QR code.
Scan this code with the WhatsApp app of the designated phone. Now the API is linked with the WhatsApp account of the phone.
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.
Step 4: Verify Linkage with Phone Number
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.
Step 5: Sending WhatsApp Message
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.
Step 6: Receiving WhatsApp Message
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.
Set the value of ‘page’ as 1 and trigger the API.
From the response, you can make out that there are a total of 1206 messages available in the logs. Additionally, the API response returns the first 50 logs. Now, if you trigger the API with the parameter ‘page’ set to 2, then you get the next 50 logs, and so on.
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.
How to Use the WhatsApp API with Python (to Build a COVID-19 Tracking Workflow)
With the programmable access to send and receive WhatsApp messages, you can think of leveraging WhatsApp conversations to build automated workflows.
One of the solutions is automated interaction between a healthcare official and a person under quarantine due to COVID-19.
Let’s define the scenario and the problem statement.
Imagine yourself as a health department’s official. You have been appointed by your local jurisdictional authority to enforce strict home quarantine rules on an asymptomatic person who is suspected to be in contact with a COVID-19 positive patient. If you do the monitoring of home quarantine remotely, with the help of WhatsApp, then the most inexpensive way to achieve it is to ask the person to send his selfie every hour via WhatsApp. Additionally, he must enable the location and capture time on his camera while capturing the selfie. This way, the persons’ whereabouts can be verified, and the location data is the evidence for his presence within his home’s premises.
To streamline the process, you can build a quarantine monitoring workflow to interact with the persons, via WhatsApp conversation. The sequence of steps in this workflow, to be performed every day, can be as follows:
- At 9 am, send a one-to-one broadcast message to remind all the monitored persons to send their selfie picture every one hour.
- Wait for an hour, and gather all images received from all monitored persons’ WhatsApp numbers.
- Check each image to identify the person.
- Check the timestamp of image data to verify that the image is created within the last hour.
- Check location data in the image to verify the person’s home location.
- Send individual reminders if there is any mismatch in steps 3, 4, or 5.
- Send a warning message if an image is not received from any of the monitored persons.
- Repeat step 2 until 10 p.m.
This workflow establishes a stringent monitoring regime for every monitored person under home quarantine from morning 9 am till evening at 10 pm.
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" broadcast_message = "REMINDER: Please send your self captured picture every one hour, for the next 12 hours. Make sure that you enable location tagging & capture time on your camera setting so that we can verify your quarantine location. Stay safe and stay indoors. Thank You." payload = "{ "to_number": " " + QUARANTINE_MONITORED_PHONE + "","type":"text","message":"" + broadcast_message + ""}" headers = { 'x-rapidapi-host': YOUR_RAPIDAPI_HOST, 'x-rapidapi-key': YOUR_RAPIDAPI_KEY, 'content-type': "application/json", 'accept': "application/json" } response = requests.request("POST", url, data=payload, headers=headers) 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.
<YOUR_RAPIDAPI_KEY> : Replace this placeholder with your RapidAPI subscription key.
<YOUR_MAYTAPI_PHONE_ID> : Replace this placeholder with the phone_id assigned to your designated phone while adding the phone in Maytapi WhatsApp API.
<YOUR_DESTINATION_NUMBER> : Replace this placeholder with the phone number which will receive the message. Make sure to add the country code without the ‘+’ sign.
Save this file as ‘MessageBroadcast.py’
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 } response = requests.request("GET", url, headers=headers, params=querystring) t = datetime.utcnow() l = json.loads(response.text)["data"]["list"] image_found = False for d in l: hours, remainder = divmod((t - datetime.strptime(d["created_at"],'%Y-%m-%dT%H:%M:%S.%fZ')).seconds, 3600) 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 res = requests.request("GET", d["data"]["body"]["message"]["url"]) 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")
Replace the following placeholders in the script
<YOUR_RAPIDAPI_KEY> : Replace this placeholder with your RapidAPI subscription key.
<YOUR_MONITORING_NUMBER> : Replace this placeholder with the phone number from which image will be received. Make sure to add the country code without the ‘+’ sign.
Now save the file as ‘MessageReceive.py’.
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.
Quarantine Monitoring Workflow Trial
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.
Run the ‘MessageBroadcast.py’ script with the Python3 interpreter, by setting the <YOUR_DESTINATION_NUMBER> as the second number. You should get the API response as script output. Additionally, check the WhatsApp message on the destination phone number, which is the second phone.
Now run the “MessageReceive.py” by setting the <YOUR_MONITORING_NUMBER> as the second number. Assuming that the second phone has not sent any image to the designated phone within the last one hour, you should get a script output indicating that picture is not received.
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!
Both the scripts are now working as intended.
Commissioning the Workflow as an Automated Process
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.
Here is a close to real-world, server deployment setup, for automating the quarantine workflow.
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.
Leave a Reply