MicroPython: Send Messages to WhatsApp with the ESP32/ESP826

Learn how to program your ESP32 and ESP8266 boards with MicroPython to send messages to your WhatsApp account. This can be useful to receive notifications from your board with sensor readings, alert messages when a sensor reading is above or below a certain threshold, when motion is detected, and many other applications. We’ll use a free API called CallMeBot.

MicroPython Send Messages to WhatsApp with the ESP32 ESP826 NodeMCU

If you prefer to program your boards using Arduino IDE, you can check the following tutorials instead:

Prerequisites

New to MicroPython? You can get started here: Getting Started with MicroPython on ESP32 and ESP8266.

To follow this tutorial you need MicroPython firmware installed in your ESP32 or ESP8266 boards. You also need an IDE to write and upload the code to your board. We suggest using Thonny IDE or uPyCraft IDE:

Or, if you’re familiar with VS Code, you may want to use the PyMakr extension:

Learn more about MicroPython: MicroPython Programming with ESP32 and ESP8266 eBook.

Introducing WhatsApp

WhatsApp logo

“WhatsApp Messenger, or simply WhatsApp, is an internationally available American freeware, cross-platform centralized instant messaging and voice-over-IP service owned by Meta Platforms.” It allows you to send messages using your phone’s internet connection, so you can avoid SMS fees.

WhatsApp is free and is available for Android and iOS. Install WhatsApp on your smartphone if you don’t have it already.

CallMeBot WhatsApp API

To send messages to your WhatsApp account with the ESP32 and ESP8266 boards, we’ll use a free API service called CallMeBot. You can learn more about CallMeBot at the following link:

Basically, it works as a gateway that allows you to send a message to yourself. All the information about how to send messages using the API can be found here.

Getting the CallMeBot API KEY

Before starting using the API, you need to get the CallmeBot WhatsApp API key. Follow the next instructions (check this link for the instructions on the official website).

  1. Add the phone number +34 621 331 709 to your Phone Contacts. (Name it as you wish) — please double-check the number on the CallMeBot website, because it sometimes changes.
  2. Send the following message: “I allow callmebot to send me messages” to the new Contact created (using WhatsApp of course);
  3. Wait until you receive the message “API Activated for your phone number. Your APIKEY is XXXXXX” from the bot.
Get CallMeBot API key

Note: If you don’t receive the API key in 2 minutes, please try again after 24hs. The WhatsApp message from the bot will contain the API key needed to send messages using the API.

CallMeBot API

To send a message using the CallMeBot API you need to make a POST request to the following URL (but using your information):

https://api.callmebot.com/whatsapp.php?phone=[phone_number]&text=[message]&apikey=[your_apikey]
  • [phone_number]: phone number associated with your WhatsApp account in international format;
  • [message]: the message to be sent, should be URL encoded.
  • [your_apikey]: the API key you received during the activation process in the previous section.

For the official documentation, you can check the following link: https://www.callmebot.com/blog/free-api-whatsapp-messages/

To make HTTP requests with the ESP32 and ESP8266 using MicroPython, you can use the methods provided by the urequests library.

Send Messages to WhatsApp – MicroPython Script (ESP32/ESP8266)

Copy the following code to your MicroPython project main.py file. The code is compatible with both the ESP32 and ESP8266 boards.

Before uploading the code to your board, you need to insert your network credentials, your phone number in international format, and the API key.

# Complete project details at https://RandomNerdTutorials.com/micropython-whatsapp-esp32-esp826/

try:
  import urequests as requests
except:
  import requests
  
import network

import esp
esp.osdebug(None)

import gc
gc.collect()

#Your network credentials
ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_SSID'

#Your phone number in international format
phone_number = 'YOUR_PHONE_NUMER_INTERNATIONAL_FORMAT'
#Your callmebot API key
api_key = 'CALLMEBOT_API_KEY'

def connect_wifi(ssid, password):
  #Connect to your network
  station = network.WLAN(network.STA_IF)
  station.active(True)
  station.connect(ssid, password)
  while station.isconnected() == False:
    pass
  print('Connection successful')
  print(station.ifconfig())

def send_message(phone_number, api_key, message):
  #set your host URL
  url = 'https://api.callmebot.com/whatsapp.php?phone='+phone_number+'&text='+message+'&apikey='+api_key

  #make the request
  response = requests.get(url)
  #check if it was successful
  if response.status_code == 200:
    print('Success!')
  else:
    print('Error')
    print(response.text)

# Connect to WiFi
connect_wifi(ssid, password)
# Send message to WhatsApp "Hello"
message = 'Hello%20from%20ESP32%20%28micropython%29' #YOUR MESSAGE HERE (URL ENCODED)https://www.urlencoder.io/ 
send_message(phone_number, api_key, message)

View raw code

How the Code Works

The code is pretty straightforward to understand.

We start by including the required libraries. The urequests library to make HTTP requests and the network library to set the ESP32/ESP8266 as a WiFi station and connect it to your local network.

try:
  import urequests as requests
except:
  import requests
  
import network

import esp
esp.osdebug(None)

import gc
gc.collect()

Insert your network credentials in the following variables so that the ESP can connect to your local network and have access to internet.

#Your network credentials
ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_SSID'

Insert your phone number in international format (including the + sign) in the following line:

#Your phone number in international format
phone_number = 'YOUR_PHONE_NUMER_INTERNATIONAL_FORMAT

Then, insert the callmebot API key you’ve got previously.

#Your callmebot API key
api_key = 'CALLMEBOT_API_KEY'

We created a function called connect_wifi() that accepts as arguments the SSID and password of the network you want to connect to. You should call this function later to actually connect the ESP board to the internet.

def connect_wifi(ssid, password):
  #Connect to your network
  station = network.WLAN(network.STA_IF)
  station.active(True)
  station.connect(ssid, password)
  while station.isconnected() == False:
    pass
  print('Connection successful')
  print(station.ifconfig())

To make it easier to adapt the code to your projects, we created a function called send_message() that contains all the necessary instructions to send the messages to WhatsApp. This function accepts as arguments the phone number, callmebot API key and the message you want to send. You just need to call this function with the required arguments when you want to send a message.

def send_message(phone_number, api_key, message):
  #set your host URL
  url = 'https://api.callmebot.com/whatsapp.php?phone='+phone_number+'&text='+message+'&apikey='+api_key

  #make the request
  response = requests.get(url)
  #check if it was successful
  if response.status_code == 200:
    print('Success!')
  else:
    print('Error')
    print(response.text)

Now that we’ve created all the necessary functions, call the connect_wifi() function to connect the ESP to your local network.

connect_wifi(ssid, password)

We created a variable called message that contains the text that we want to send. The message should be in URL encoded format. You can use this tool to convert your text to URL encoded format. We’re sending the following message: Hello from ESP32 (micropython). You can send whatever text makes sense for your project including values from sensor readings, for example.

message = 'Hello%20from%20ESP32%20%28micropython%29' #YOUR MESSAGE HERE (URL ENCODED)https://www.urlencoder.io/ 

Finally, call the send_message() function to send the message.

send_message(phone_number, api_key, message)

As you can see, sending a message to WhatsApp using MicroPython is pretty straightforward. You can use the send_message() function in your projects to send messages using your boards.

Demonstration

After inserting your credentials, phone number and API key, you can upload the main.py file to your board using your favorite MicroPython IDE.

Reset the board to start running the code. You should get a success message on the shell.

MicroPython Send Messages to WhatsApp with the ESP32 ESP826 NodeMCU Demonstration

After receiving that success message, you should receive a message from the WhatsApp Bot with the content you’ve set on the code.

MicroPython Send Messages to WhatsApp with the ESP32 ESP826 NodeMCU Demonstration Testing

Congratulations! You’ve successfully sent messages to your WhatsApp account with the ESP32 and ESP8266 boards (programmed with MicroPython).

Wrapping Up

In this tutorial, you learned how to send messages to your WhatsApp account using the ESP32 and ESP8266 programmed with MicroPython firmware.

To send the messages we used a free API called callmebot that allows you to send messages to yourself for personal projects. To send a message, we just need to make a request to a URL with the required parameters. Making a request with MicroPython is very straightforward using the urequests library.

We hope you’ve found this tutorial useful. We have other tutorials (using Arduino IDE) showing how to send different types of notifications. You can check the tutorials below.

You can check all our MicroPython projects here.

If you want to learn more about programming the ESP32 and ESP8266 boards with MicroPython, check out our eBook: MicroPython Programming with ESP32 and ESP8266.

Thanks for reading



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.