How to create WhatsApp Bot in any languages for free!

WAHA
5 min readJan 4, 2021

--

Introduction

On the Internet you can find many articles where you can “make a WhatsApp bot in 5 minutes”, but they are more ads than helpful articles. To keep using these solutions you either will have to pay every month or you have to be a large business (to use official WhatsApp HTTP API) and (have a monthly subscription) pay every month.

On the other hand, we have a lot of language specific libraries in Github but they require knowledge of j̶a̶v̶a̶s̶c̶r̶i̶p̶t̶ ̶g̶o̶ ̶p̶y̶t̶h̶o̶n language that you don’t like or are not very familiar with.

We’re going to use WAHA — WhatsApp HTTP API that you can configure in a click!

You are going to send a message to WhatsApp via HTTP API and it’ll cost you nothing (except your priceless time)! You can create an “echo” bot that responds to you with the same text you’ve sent to it.

We’re using Python but the WhatsApp HTTP API is language agnostic. You can easily repeat it in your favorite language. At the end you will see a real “Voice to Text Bot” that uses this API.

Requirements

Only thing that you must have — installed docker. Please follow the original instruction how to install docker ->.

When you are ready — come back and follows the below steps to send the first text message to WhatsApp via HTTP API!

Send your first message

Let’s go over steps that allow you to send your first text message via WhatsApp HTTP API!

1. Download image

Assuming you have installed Docker, let’s download the image.

docker pull devlikeapro/whatsapp-http-api

2. Run WhatsApp HTTP API

Run WhatsApp HTTP API:

docker run -it --rm -p 127.0.0.1:3000:3000/tcp --name whatsapp-http-api devlikeapro/whatsapp-http-api
# It prints logs and the last line must be
# WhatsApp HTTP API is running on: http://[::1]:3000

Open the link in your browser http://localhost:3000/ and you’ll see API documentation (Swagger).

👉We don’t recommend expose the API in the internet without authentication!

3. Start a new session

To start a new session you should have your mobile phone with installed WhatsApp application close to you.

Please go and read how what we’ll need to a bit later: How to log in — the instruction on WhatsApp site

When your ready — find POST /api/session/start, click on Try it out, then Execute a bit below.

The example payload:

{
"name": "default"
}

4. Get and scan QR

Find GET /api/screenshot and execute it, it shows you QR code.

Scan the QR with your cell phone’s WhatsApp app.

5. Get the screenshot

Execute GET /api/screenshot after a few seconds after scanning the QR - it’ll show you the screenshot of you Whatsapp instance. If you can get the actual screenshot - then you’re ready to start sending messages!

6. Send a text message

Let’s send a text message — find POST /api/sendText in swagger and change chatId this way: use a phone international phone number without + symbol and add @c.us at the end.

For phone number 12132132131 the chatId is 12132132131@c.us.

The example payload:

{
"chatId": "12132132130@c.us",
"text": "Hi there!",
"session": "default"
}

Also, you can use curl and send POST request like this:

# Phone without +
export PHONE=12132132130
curl -d "{\"chatId\": \"${PHONE}@c.us\", \"text\": \"Hello from WhatsApp HTTP API\" }" -H "Content-Type: application/json" -X POST http://localhost:3000/api/sendText

Python — create an echo WhatsApp bot

Let’s create a real (but dumb) bot. It does two things:

  1. When the bot receives a text — it sends the text back
  2. When the bot receives a message with a file (an image, a voice message) — the bot downloads it and sends the path back.

The mechanism of how we receive incoming messages from WhatsApp HTTP API is via HTTP webhooks. So we need to create a simple HTTP server to receive HTTP POST requests from WhatsApp HTTP API and send POST requests back, to send a text message. Create a file echo.py and fill it with the code below:

from pprint import pprint

import requests
from flask import Flask
from flask import request

app = Flask(__name__)


@app.route("/")
def whatsapp_echo():
return "WhatsApp HTTP API Echo server is ready!"


@app.route("/message", methods=["GET", "POST"])
def whatsapp_webhook():
data = request.get_json()
if not data:
return "WhatsApp HTTP API Echo server is ready!"
pprint(data)
if data['event'] != "message":
return f"Unknown event {data['event']}"

payload = data["payload"]
# The text
text = payload["body"]
# Number in format 791111111@c.us
from_ = payload["from"]

if payload.get("mediaUrl", None):
# Download file and set text to path
client_url = payload["mediaUrl"]
filename = client_url.split("/")[-1]
path = "/tmp/" + filename
r = requests.get(client_url)
open(path, "wb").write(r.content)
text = f"We have downloaded file here: {path}"

# Send a text back via WhatsApp HTTP API
response = requests.post(
"http://localhost:3000/api/sendText", json={"chatId": from_, "text": text}
)
response.raise_for_status()
return "OK"

Run echo.py (in one terminal):

python -mpip install flask requests
export FLASK_APP=echo.py
flask run

Stop the previous docker instance for WhatsApp HTTP API and run the new one with configured network and webhook “on message”:

docker run -it --network=host -e WHATSAPP_HOOK_URL=http://localhost:5000/message -e WHATSAPP_HOOK_EVENTS=* -e WHATSAPP_START_SESSION=default allburov/whatsapp-http-api

Check this out — send a message and an image!

What is next?

Is it a stable API?

It’s not. The API that we are using here is not official so it can be broken anytime.

Thanks for reading and please feel free to comment, give advice and create a Pull Request in these repositories:

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response