Building a WhatsApp bot for smart home alerts using Twilio and ESP32 puts your home automation notifications directly where Indian families communicate most — WhatsApp. With over 500 million active WhatsApp users in India, it is the natural channel for smart home alerts about gas levels, power cuts, security breaches, and sensor readings. This tutorial shows you how to send automated WhatsApp messages from your ESP32 using the Twilio API, and how to receive commands back from WhatsApp to control your smart devices.
Table of Contents
- WhatsApp API Options for Indian Makers
- Twilio WhatsApp API Setup
- ESP32 Code for Sending Messages
- Two-Way Control via WhatsApp
- Free Alternative: CallMeBot API
- Home Assistant WhatsApp Integration
- Indian Smart Home Use Cases
- Frequently Asked Questions
WhatsApp API Options for Indian Makers
Twilio WhatsApp Sandbox (Recommended for Prototyping)
Twilio provides a WhatsApp Sandbox for testing without a formal Meta Business account. Free trial credits (approximately $15) are sufficient for hundreds of messages. The Sandbox uses a shared Twilio WhatsApp number — recipients must opt-in first by sending a specific message to activate the sandbox.
CallMeBot API (Completely Free)
CallMeBot offers a completely free WhatsApp notification API for personal use. No credit card required. Limitation: only works for a single recipient phone number. Perfect for personal projects and home monitoring.
Wati, Interakt, AiSensy (Indian BSP Providers)
For production deployments reaching family members without sandbox opt-in, Indian WhatsApp Business Solution Providers (BSPs) like Wati or AiSensy provide proper WhatsApp Business API access. Pricing: approximately Rs 1,500-3,000/month for small usage.
Twilio WhatsApp API Setup
- Create account at twilio.com (free, no credit card needed initially)
- Navigate to Messaging > Try WhatsApp
- Join the sandbox: Send “join YOUR-SANDBOX-CODE” to +1 415 523 8886 (Twilio’s sandbox number) from your WhatsApp
- Note your Account SID and Auth Token from the Twilio Console
- Your sandbox WhatsApp number: whatsapp:+14155238886
- Your recipient number format: whatsapp:+919876543210 (India country code)
ESP32 Code for Sending WhatsApp Messages
#include <WiFi.h>
#include <HTTPClient.h>
#include <base64.h>
const char* ssid = "YOUR_WIFI";
const char* password = "YOUR_PASS";
// Twilio credentials
const char* accountSid = "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const char* authToken = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const char* twilioNumber = "whatsapp:+14155238886";
const char* recipientNumber = "whatsapp:+919876543210";
void sendWhatsAppMessage(String message) {
if (WiFi.status() != WL_CONNECTED) return;
WiFiClientSecure client;
client.setInsecure(); // Skip cert verification for simplicity
HTTPClient https;
String url = "https://api.twilio.com/2010-04-01/Accounts/" +
String(accountSid) + "/Messages.json";
https.begin(client, url);
// Basic auth: Base64(AccountSID:AuthToken)
String credentials = String(accountSid) + ":" + String(authToken);
String encodedAuth = base64::encode(credentials);
https.addHeader("Authorization", "Basic " + encodedAuth);
https.addHeader("Content-Type", "application/x-www-form-urlencoded");
// URL-encode the message body
String body = "From=" + String(twilioNumber);
body += "&To=" + String(recipientNumber);
body += "&Body=" + urlEncode(message);
int httpCode = https.POST(body);
if (httpCode == 201) {
Serial.println("WhatsApp message sent!");
} else {
Serial.printf("Error: %dn", httpCode);
Serial.println(https.getString());
}
https.end();
}
// URL encoding helper
String urlEncode(String str) {
String encoded = "";
for (int i = 0; i 38.0) {
sendWhatsAppMessage("ALERT: Temperature is " + String(temperature, 1) +
"C - Above threshold! Check cooling.");
delay(3600000); // Don't spam - wait 1 hour before next alert
}
delay(30000);
}
Two-Way Control via WhatsApp
Twilio supports webhooks that receive incoming WhatsApp messages and can trigger actions. Set up a webhook server (can run on a Pi at home or a free service like ngrok for testing):
# Simple Flask webhook server (on Raspberry Pi)
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
import requests
app = Flask(__name__)
# Home Assistant API
HA_URL = "http://192.168.30.100:8123"
HA_TOKEN = "YOUR_HA_LONG_LIVED_TOKEN"
@app.route('/whatsapp-webhook', methods=['POST'])
def webhook():
message = request.form.get('Body', '').lower().strip()
sender = request.form.get('From', '')
resp = MessagingResponse()
if message == 'lights on':
# Call HA API
requests.post(f"{HA_URL}/api/services/light/turn_on",
headers={"Authorization": f"Bearer {HA_TOKEN}"},
json={"entity_id": "light.all"})
resp.message("All lights turned ON")
elif message == 'lights off':
requests.post(f"{HA_URL}/api/services/light/turn_off",
headers={"Authorization": f"Bearer {HA_TOKEN}"},
json={"entity_id": "light.all"})
resp.message("All lights turned OFF")
elif message == 'status':
# Get temperature
r = requests.get(f"{HA_URL}/api/states/sensor.temperature",
headers={"Authorization": f"Bearer {HA_TOKEN}"})
temp = r.json()["state"]
resp.message(f"Home Status:nTemperature: {temp}C")
else:
resp.message("Commands: 'lights on', 'lights off', 'status'")
return str(resp)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
Free Alternative: CallMeBot API
For simpler one-way notifications without Twilio costs, CallMeBot is free and easy:
// CallMeBot setup:
// 1. Add +34 644 81 71 69 to your WhatsApp contacts
// 2. Send: "I allow callmebot to send me messages"
// 3. Receive your API key via WhatsApp reply
void sendWhatsAppCallmebot(String message, String phone, String apiKey) {
HTTPClient http;
String url = "https://api.callmebot.com/whatsapp.php?phone=" +
phone + "&text=" + urlEncode(message) +
"&apikey=" + apiKey;
http.begin(url);
int code = http.GET();
http.end();
Serial.println("CallMeBot status: " + String(code));
}
Home Assistant WhatsApp Integration
Integrate WhatsApp alerts into Home Assistant via custom notify service or MQTT bridge. Add to configuration.yaml:
# Using the Twilio integration for HA
# First install: pip install twilio
notify:
- platform: rest
name: whatsapp_home
resource: https://api.twilio.com/2010-04-01/Accounts/ACXXXX/Messages.json
method: POST_JSON
headers:
Authorization: !secret twilio_auth_header
# Then in automations:
alias: Gas Low WhatsApp Alert
trigger:
- platform: numeric_state
entity_id: sensor.gas_level
below: 20
action:
- service: notify.whatsapp_home
data:
message: >-
Gas Alert: Cylinder at {{ states('sensor.gas_level') }}%.
Please order a new cylinder.
Indian Smart Home Use Cases
Joint Family Security Alert
Send WhatsApp alerts to all family members when the main door opens after 11 PM. Include a camera snapshot if an IP camera is installed at the entrance.
LPG Gas Level Alert
Alert the family WhatsApp group when gas cylinder drops below 20%. Include a link to the IOCL/HPCL booking portal in the message for quick reorder.
Power Cut Notification
When mains power fails and the inverter kicks in, send a WhatsApp message with battery percentage and estimated backup time. Alert again at 30% battery remaining for urgent action.
Water Tank Full Alert
When the overhead water tank reaches 90% capacity, send a WhatsApp alert to stop the motor pump. Prevents overflow and water wastage — extremely relevant in Indian cities with limited municipal water supply.
Frequently Asked Questions
Do I need a WhatsApp Business account to use the API?
For Twilio’s sandbox, only the developer needs a Twilio account. Recipients receive messages without any special account — they receive it as a regular WhatsApp message from the Twilio sandbox number. For production (removing the sandbox limitation and using a custom number), a Meta Business account is required.
Are there rate limits on WhatsApp messages?
Twilio sandbox: 100 messages/day in the free trial. Paid Twilio: no hard limit but messages cost approximately Rs 0.50-0.80 each for India numbers. CallMeBot: approximately 80 messages/day free. For home monitoring with a few alerts per day, all options are sufficient.
Can I send photos from ESP32-CAM via WhatsApp?
Yes. Twilio supports media messages. The ESP32-CAM captures an image, uploads it to a cloud storage URL (or your Pi’s web server), and includes the URL in the Twilio message API call as the MediaUrl parameter. The recipient sees the actual image in WhatsApp.
Is this legal to use for automation in India?
Yes. WhatsApp Business API used through authorised BSPs (Twilio, Wati, etc.) is fully legal for business and personal use in India. The API is designed for exactly this type of notification and customer communication use case. Only scraping WhatsApp or using unofficial APIs is against WhatsApp’s terms of service.
Add comment