For an index to all my stories click this text
Long time ago, I wrote about Callmebot. A service that allows you to send messages from your microcontroller (ESP32 or Raspberry Pi Pico) to Whatsapp. You can find that story here: https://lucstechblog.blogspot.com/2021/05/esp8266-and-esp32-sending-messages-to.html
Last time I wrote about a similar service which is my favorite now. It's called Whatabot.
You can find it's homepage here: https://whatabot.io/
The idea is the same but Whatabot offers something extra. To use this service you need to create an account to obtain an API key. It's easy and the first 200 messages are free !! I urge you to read that story because this story leans heavily on it. You can find the story here:
https://lucstechblog.blogspot.com/2026/09/send-messages-to-whatsapp-with-pico-w.html
From Whatsapp to your microcontroller.
The previous story showed how to send text and data from your Raspberry Pi Pico to Whatsapp. I used a MicroPython program for that.
This time I am going to show you how to send data and text from Whatsapp to your microcontroller. For this I created a special websocket client library. This is especially written in MicroPython for the Raspberry Pi Pico W.
The library
Copy the code below.
Then paste it into an empty tab in Thonny and then save it in the lib folder on your Raspberry Pi Pico.
Please make sure to save it using the name websocket_client.py
import uasyncio as asyncio import ubinascii import urandom import usocket as socket import ssl class WebSocketClient: """ Minimal async WebSocket client with SSL support for Pico W. """ def __init__(self, url, headers=None): self.url = url self.headers = headers or {} self.reader = None self.writer = None async def connect(self): proto, host, path = self._parse_url(self.url) port = 443 # ---- TCP socket ---- addr = socket.getaddrinfo(host, port)[0][-1] sock = socket.socket() sock.connect(addr) # ---- SSL wrap ---- sock = ssl.wrap_socket(sock, server_hostname=host) # Bind to uasyncio self.reader = asyncio.StreamReader(sock) self.writer = asyncio.StreamWriter(sock, {}) # ---- Generate Sec-WebSocket-Key ---- key_bytes = bytes([urandom.getrandbits(8) for _ in range(16)]) key = ubinascii.b2a_base64(key_bytes).strip().decode() # ---- Handshake ---- req = ( "GET {} HTTP/1.1\r\n" "Host: {}\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Key: {}\r\n" "Sec-WebSocket-Version: 13\r\n" ).format(path, host, key) for k, v in self.headers.items(): req += "{}: {}\r\n".format(k, v) req += "\r\n" await self.writer.awrite(req) # ---- Read handshake response ---- status = await self.reader.readline() if b"101" not in status: raise Exception("Handshake failed: " + status.decode()) # Skip headers while True: line = await self.reader.readline() if line == b"\r\n": break async def send(self, msg): payload = msg.encode() await self.writer.awrite(bytes([0x81])) # FIN + text frame ln = len(payload) if ln < 126: await self.writer.awrite(bytes([ln])) else: raise Exception("Payload too large") await self.writer.awrite(payload) async def recv(self): hdr = await self.reader.readexactly(2) opcode = hdr[0] & 0x0F length = hdr[1] & 0x7F if length >= 126: raise Exception("Extended lengths unsupported") data = await self.reader.readexactly(length) return data.decode() def _parse_url(self, url): if not url.startswith("wss://"): raise ValueError("Only wss:// URLs supported") no_proto = url[6:] parts = no_proto.split("/", 1) host = parts[0] path = "/" + parts[1] if len(parts) > 1 else "/" return "wss", host, path
This is obvious a long and complicated code. It took me quite some time and effort to create it. Explaining it would take a lot of space on this weblog, so I am not going to do that.
Just copy it and save it in your Pico's lib folder using the name websocket_client.py
The program for recieving Whatsapp messages.
Next to the library we need a program that opens a websocket and constant listens for incoming commands. Here is that program.
import uasyncio as asyncio import ujson from websocket_client import WebSocketClient # use the class above import network import time import gc gc.enable() gc.collect() print("Start memory free: "+str(gc.mem_free())) ssid = "YOUR-ROUTERS-NAME" pw = "PASSWORD" print("Connecting to wifi...") # wifi connection wifi = network.WLAN(network.STA_IF) wifi.active(True) wifi.connect(ssid, pw) print('Waiting for connection.',end="") while wifi.isconnected() == False: time.sleep(1) print('', end='.') print("") ip = wifi.ifconfig()[0] print("Connected with IP adress : "+ip) class WhatabotRealtimeClient: def __init__(self): self.api_key = "YOUR-API-KEY" self.chat_id = "YOUR-PHONE-NUMBER" self.url = "wss://api.whatabot.io/realtimeMessages" self.connect_message = ( ujson.dumps({"protocol": "json", "version": 1}) + '\u001e' ) async def run_websocket(self): while True: try: print("Connecting...") ws = WebSocketClient( self.url, headers={ "x-api-key": self.api_key, "x-chat-id": self.chat_id, "x-platform": "whatsapp" } ) await ws.connect() print("Connected!") await ws.send(self.connect_message) while True: msg = await ws.recv() await self.handle_message(ws, msg) except Exception as e: print("ERROR:", e) print("Reconnecting in 10 seconds...") await asyncio.sleep(10) async def handle_message(self, ws, message): message = message.rstrip('\u001e') try: data = ujson.loads(message) except: print("Invalid JSON:", message) return target = data.get("target") args = data.get("arguments") if target == "ReceiveMessage" and args: txt = args[0] up = txt.upper() # --- your command handling --- if up == "START": print("Starting…") elif up == "STOP": print("Stopping…") elif up == "PAUSE": print("Pausing…") elif up == "RESUME": print("Resuming…") else: print("Unknown:", txt) # reply reply = ujson.dumps({ "type": 1, "target": "SendMessage", "arguments": [f"Pong: {txt}"] }) + '\u001e' await ws.send(reply) print("Sent:", reply) asyncio.run(WhatabotRealtimeClient().run_websocket())
Again I am just giving you the program without an explanation as that would take up to uch space.
I do want you to pay special attention to the following lines:
ssid = "YOUR-ROUTERS-NAME" pw = "PASSWORD"
You will need to replace these with your actual routers name and password.
class WhatabotRealtimeClient: def __init__(self): self.api_key = "YOUR-API-KEY" self.chat_id = "YOUR-PHONE-NUMBER" self.url = "wss://api.whatabot.io/realtimeMessages"
Further on in the program you need to replace these with your actual API key and phone number.
How does it work in real life.
In Whatsapp look for your Whatabot contact.
I am using the Whatsapp web version here for easily making screenshots.
Click on that contact and the message screen opens.
Now make sure the Raspberry Pi Pico W is running the above program and is connected to Whatabot.
Thonny's shell shows when there is a firm connection to Whatabot.
You can now type anything you like in Whatsapp and it will be send to your Raspberry Pi Pico W. Here I am sending: this is a test from Whatabot
And this is what your Raspberry Pi Pico receives.
Unknown: This is a test from whatabot
Sent: {"arguments": ["Pong: This is a test from whatabot"], "type": 1, "target": "SendMessage"}
At the end of the program you'll find this code:
if target == "ReceiveMessage" and args: txt = args[0] up = txt.upper() # --- your command handling --- if up == "START": print("Starting…") elif up == "STOP": print("Stopping…") elif up == "PAUSE": print("Pausing…") elif up == "RESUME": print("Resuming…") else: print("Unknown:", txt)
This is where I provided some words that are filtered by the program to help you getting started.
In this example I send the word "start"
Then the Pico reacts with the word Starting.
You can replace this easily with your own commands like "Lamp on", "Lamp off", "Fan on", "Fan off" etc. etc.
You can then add your desired action after the print command.
How many credits left
As said before you get credits with your free account.
200 Credits to send from your microcontroller to Whataspp
100 Credits to send from Whatsapp to your microcontroller
You can send a command to Whatabot to show how many credits you have left:
The command is : "Remaining messages"
As you can see I can still send 191 messages from my Pico to Whatsapp and receive 96 messages.
Multiple Raspberry Pi Pico's or ESP's ????
Well I still have to do some testing but I presume it would be possible to have multiple Raspberry Pi Pico's sending data to Whatsapp and multiple other Raspberry Pi Pico's receiving messages.
I should also be possible to combine the send and receive program into one. So a single Raspberry Pi Pico would be able to send and receive commands to Whatsapp.
However I would recommend using another service as intermedeair if you need to send a lot of messages. Dweet for example would be better suited for that. You can read about Dweet here: https://lucstechblog.blogspot.com/2025/08/dweet-is-dead-long-live-dweet.html
That's it for now.
Till next time
have fun !
Luc Volders