DEV Community

Cover image for Stop Building Mobile Apps: How to Build a WhatsApp Bot in 30 Minutes with Python
Frank Oge
Frank Oge

Posted on

Stop Building Mobile Apps: How to Build a WhatsApp Bot in 30 Minutes with Python

​I have a rule: If I can solve a problem without forcing a user to download a new app, I will.
​Nobody wants another icon on their home screen. But everyone—literally everyone, especially here in Nigeria—has WhatsApp.
​If you want to build a tool that people actually use (checking prices, booking appointments, customer support), build a WhatsApp Bot.
​Here is how I built one using Python, Flask, and Twilio. It’s cheaper, faster, and easier than React Native.
​The Stack
​We aren't overcomplicating this.
​Python (Flask): To handle the logic.
​Twilio API: The bridge between our code and WhatsApp.
​Ngrok: To expose our local server to the internet (for testing).
​Step 1: The "Hello World" of Twilio
​First, you need a Twilio account. You don't need to pay yet; just use their "Sandbox."
Once you are in, they give you a special code to join the sandbox. It’s usually something like join simple-word. Send that to their number on WhatsApp, and boom—you are connected.
​Step 2: The Server (The Brain)
​We need a webhook. When someone messages the bot, Twilio will hit this URL with the data.
​Here is the absolute bare minimum code to make the bot talk back:

from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse

app = Flask(name)

@app.route("/sms", methods=['POST'])
def sms_reply():
# 1. Get the message the user sent
msg = request.form.get('Body').lower()

# 2. Start our response
resp = MessagingResponse()

# 3. Simple Logic
if 'hello' in msg:
    resp.message("Hi there! I am Frank's AI Assistant.")
elif 'price' in msg:
    resp.message("Our service costs $50/month.")
else:
    resp.message("I didn't catch that. Try saying 'hello' or 'price'.")

return str(resp)
Enter fullscreen mode Exit fullscreen mode

if name == "main":
app.run(debug=True)

Step 3: Connecting the Dots
​Run your Python script. It’s running on localhost:5000. Twilio can't see your localhost.
Fire up Ngrok:
ngrok http 5000
​Copy that URL (e.g., https://random-name.ngrok.io) and paste it into your Twilio Sandbox settings under "When a message comes in." Append /sms to the end.
​Step 4: Test It
​Open WhatsApp. Send "Hello."
If your bot replies "Hi there! I am Frank's AI Assistant," congratulations. You just built a chatbot.
​Where to go from here?
​This is just an if/else statement. But you can connect this to anything:
​Databases: Check user balances.
​AI: Pass the msg to OpenAI's API to have a full conversation.
​E-commerce: Let users order products directly in the chat.
​The barrier to entry is low. The potential leverage is massive.
​Hi, I'm Frank Oge. I build high-performance software and write about the tech that powers it. If you enjoyed this, check out more of my work at frankoge.com

Top comments (0)