DEV Community

Cover image for Building Your First WhatsApp Bot in Python: A Beginner’s Guide
WhatsApp API for developers
WhatsApp API for developers

Posted on • Edited on

Building Your First WhatsApp Bot in Python: A Beginner’s Guide

Introduction

Creating a WhatsApp bot might initially feel overwhelming, but with clear instructions, it transforms into an accessible and manageable project. For Python developers new to API integrations, this guide simplifies the process, offering step-by-step instructions for building a basic WhatsApp bot. You'll learn everything from obtaining an API token to setting up webhooks for automated responses.

This tutorial serves as a beginner-friendly starting point, making it an excellent resource for developers looking to explore WhatsApp API capabilities and lay the groundwork for building more advanced chatbot solutions in the future.

Features of This WhatsApp Bot

This basic bot showcases how to handle incoming messages by responding with predefined text or media, such as images, depending on the message's content. It’s a valuable learning tool for developers eager to understand the fundamentals of API interactions and automated messaging workflows.

A standout feature of this bot is its ability to function effortlessly within WhatsApp Groups and Communities, making it an effective solution for automating interactions and enhancing productivity within the messenger.

Prerequisites

Before you begin, ensure you have the following:

1. Obtain Your API Token

  1. Register on Whapi.Cloud. This platform provides an easy-to-use API gateway compatible with Python and other programming languages, enabling you to connect your app, website, or CRM with WhatsApp. That said, this system works with Groups, Channels, Statuses, and more.
  2. Retrieve your API token by following the detailed instructions provided in Whapi.Cloud’s documentation.
  3. Download the source code for the bot from GitHub: [GitHub Repository].
  4. Save the token in a .env file for secure access within your bot script.

2. Set Up Your Webhook URL

A webhook is a mechanism that allows one application to deliver real-time information to another. In the case of this WhatsApp bot, the webhook URL acts as the endpoint where WhatsApp forwards incoming messages, enabling your bot to process and respond accordingly.

To enable your bot to handle messages, setting up a webhook URL is essential.

This [guide] provides detailed instructions on locating your webhook URL, recommended server configurations, and popular options for setup. If you’re working in a local environment, deploying to a live server isn’t required. Instead, you can use a tunneling tool to expose your local server and allow external requests to reach it.

Testing Locally: For local testing, use Ngrok to expose your server online temporarily, allowing you to simulate bot functions without needing to deploy on a live server.

Download and unzip Ngrok, then run: ./ngrok http PORT_NUMBER
Replace PORT_NUMBER with the port where your server is running.

Set Webhook URL in Dashboard: Copy the Ngrok-generated link as your webhook URL in the Whapi.Cloud dashboard. This directs incoming messages to your bot’s local server, allowing real-time interaction with WhatsApp.

Settings of your channel in the dashboard

3. Setting Up Your Bot

Follow these steps to get the bot running:

  1. Navigate to the directory containing the bot’s files: cd /path/to/bot
  2. Install the required dependencies: pip install -r requirements.txt
  3. Run the bot: python index.py

If everything is done correctly, your bot is ready to go. Just write the test command “help” to the number connected to the API from another number.

Understanding the Structure of Your WhatsApp Bot

The bot is designed with simplicity in mind, making it easy for beginners to understand. The directory structure includes:

  • files/: Stores media files, such as images, that the bot sends.
  • .env: Contains configuration variables like the API token and base URL.
  • index.py: The main Python script where the bot’s logic resides.
  • requirements.txt: Lists all necessary Python packages.

Customizing and Enhancing Your WhatsApp Bot

Once the basic setup is in place, you can start expanding your bot's functionality to make it more versatile and tailored to specific needs.

Here are some ideas for extending its capabilities:

Add New Commands and Responses

Modify the index.py file to include additional commands and features. Extend the conditional logic to recognize new keywords or phrases and define unique responses. These could range from simple text and images to more complex content types.

Send a Variety of Content
Move beyond basic messages by leveraging Whapi.Cloud’s API to send a diverse range of content. Here are some options you can integrate:

  • Files in various formats
  • Shared locations
  • Contact cards
  • Stickers and polls
  • Product details in messages
  • Interactive buttons for user actions

Introduce Message Reactions

Enhance user interaction by adding message reaction features. Your bot can:

  • Quote incoming messages
  • Respond with emoji reactions
  • Mark messages as read
  • Simulate typing indicators in real-time

These additions not only make the bot more engaging but also provide a human-like experience, improving interaction quality.

Automated WhatsApp Group Management

Whapi.Cloud’s API offers extensive tools for automating WhatsApp Group management, transforming your bot into an efficient group coordination assistant. Here are some of the tasks you can automate:

  • Create, update, or delete groups programmatically.
  • Retrieve group details, such as member lists, participant numbers, and other metadata.
  • Manage group membership by adding or removing users, assigning admin roles, or blocking members as needed.
  • Adjust group settings, including the group name, avatar, and permissions.
  • Generate and distribute group invitation links with ease.

For detailed implementation instructions and code samples, refer to Whapi.Cloud’s comprehensive documentation. Each feature is clearly explained, complete with practical examples to help you make the most of your bot’s potential.

With these advanced capabilities, you can build a robust WhatsApp bot that goes far beyond basic message automation, delivering a solution tailored to your specific requirements.

ChatGPT Integration: Bring AI into Your WhatsApp Bot

Adding ChatGPT support is a powerful way to enhance your WhatsApp bot with AI-driven, human-like responses. In this example, we’ll keep things simple: when a user sends a message like /ai [your question], the bot replies using ChatGPT.

Step 1: Install Dependencies
To enable ChatGPT, add the following packages to your requirements.txt:

openai>=1.91.0,<2.0.0
httpx>=0.28.1,<1.0.0
httpcore>=1.0.9,<2.0.0
Enter fullscreen mode Exit fullscreen mode

Install them using: pip install -r requirements.txt

Step 2: Set Your OpenAI API Key
Register at platform.openai.com, generate your secret API key, and add it to your .env file: OPENAI_API_KEY=your_api_key_here

Step 3: Implement AI Logic
Next, create a basic Flask app (index.py) that:

  • Receives webhook events from Whapi.Cloud
  • Detects messages starting with /ai
  • Sends the prompt to ChatGPT
  • Replies to the user via the WhatsApp API

This structure provides a clean, minimal foundation for integrating AI into your bot.

# Import necessary libraries for web server, HTTP requests, OpenAI API, environment variables, and .env file loading
from flask import Flask, request, jsonify  # Flask is used to create the web server and handle HTTP requests
import requests  # Used to send HTTP requests to the WhatsApp API
from openai import OpenAI  # OpenAI client for interacting with ChatGPT
import os  # For accessing environment variables
from dotenv import load_dotenv  # For loading variables from a .env file

# Load environment variables from a .env file into the environment
load_dotenv()
# Create a Flask web application instance
app = Flask(__name__)

# Retrieve required configuration values from environment variables
API_TOKEN = os.getenv("API_TOKEN")  # Token for authenticating with WhatsApp API
API_URL = os.getenv("API_URL")      # Base URL for WhatsApp API
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")  # API key for OpenAI

# Ensure all required environment variables are set, otherwise stop the program with an error
if not API_TOKEN or not API_URL or not OPENAI_API_KEY:
    raise RuntimeError("Missing required environment variables: API_TOKEN, API_URL, or OPENAI_API_KEY")

# Initialize the OpenAI client with the provided API key
openai_client = OpenAI(api_key=OPENAI_API_KEY)

# Function to send a prompt to ChatGPT and get a response
# Takes a string prompt and returns the model's reply as a string
def ask_openai(prompt):
    response = openai_client.chat.completions.create(
        model="gpt-3.5-turbo",  # Specify which OpenAI model to use
        messages=[{"role": "user", "content": prompt}]  # Provide the user's message to the model
    )
    # Extract and return the text of the model's reply
    return response.choices[0].message.content.strip()

# Function to send a text message to a WhatsApp user via the WhatsApp API
# 'to' is the recipient's chat ID, 'body' is the message text
def send_message(to, body):
    headers = {
        "Authorization": f"Bearer {API_TOKEN}",  # Add authentication token to the request
        "Content-Type": "application/json"        # Specify that we're sending JSON data
    }
    payload = {"to": to, "body": body}  # Prepare the message data
    # Send the message to the WhatsApp API endpoint
    response = requests.post(f"{API_URL}/messages/text", json=payload, headers=headers)
    print("Whapi response:", response.status_code, response.text)  # Log the API response for debugging

# Define a webhook endpoint to receive incoming WhatsApp messages
@app.route("/hook/messages", methods=["POST"])
def webhook():
    data = request.json  # Parse the incoming JSON data
    print("Incoming:", data)  # Log the incoming data for debugging

    # Loop through all received messages (could be more than one in a single webhook call)
    for msg in data.get("messages", []):
        if msg.get("from_me"):
            continue  # Skip messages sent by the bot itself

        sender = msg.get("chat_id")  # Get the sender's chat ID
        # Safely extract the message text, handling cases where 'text' might be missing
        text = (msg.get("text") or {}).get("body", "").strip()

        # If the message starts with '/ai ', treat it as a prompt for ChatGPT
        if text.lower().startswith("/ai "):
            prompt = text[4:].strip()  # Extract the user's prompt after '/ai '
            if not prompt:
                send_message(sender, "Please provide a prompt after /ai.")  # Ask user to provide a prompt
            else:
                try:
                    reply = ask_openai(prompt)  # Get response from ChatGPT
                    send_message(sender, reply)  # Send the response back to the user
                except Exception as e:
                    send_message(sender, f"Error: {e}")  # Inform user if something went wrong
        else:
            # If the message doesn't start with '/ai ', send instructions to the user
            send_message(sender, "Hi! To ask me something, type:\n/ai your question")

    # Respond to WhatsApp API to confirm receipt of the webhook
    return jsonify({"status": "received"})

# Optional: health check endpoint to verify the bot is running
@app.route("/", methods=["GET"])
def index():
    return "Bot is running"

# Function to register the webhook URL with the WhatsApp API
def register_webhook():
    if os.getenv("BOT_URL"):
        headers = {"Authorization": f"Bearer {API_TOKEN}"}
        payload = {
            "webhooks": [
                {
                    "url": os.getenv("BOT_URL"),  # The public URL where Whapi should send messages
                    "events": [{"type": "messages", "method": "post"}],  # Listen for message events
                    "mode": "method"
                }
            ]
        }
        # Register the webhook
        response = requests.patch(f"{API_URL}/settings", json=payload, headers=headers)
        print("Webhook setup:", response.status_code, response.text)  # Log the result

# If this script is run directly (not imported), start the bot
if __name__ == "__main__":
    register_webhook()  # Optionally register the webhook on startup
    port = int(os.getenv("PORT", 80))  # Use the PORT environment variable or default to 80
    app.run(host="0.0.0.0", port=port)  # Start the Flask web server, accessible from any network interface
Enter fullscreen mode Exit fullscreen mode

This basic bot processes incoming messages, filters out messages from itself, and searches for messages beginning with /ai. If such a command is found, it extracts the question, sends it to ChatGPT, and responds using the WhatsApp API with an AI response. This script is ready for testing. And its useful part has already been implemented in our chatbot example on GitHub to make it easier for you to get started!


FAQs and Troubleshooting

Setting up and operating a WhatsApp bot may occasionally present challenges. Here are some common issues and steps you can take to resolve them:

The Bot Is Not Responding to Incoming Messages
1. Verify Your Testing Method
Ensure you’re testing with a phone number different from the one assigned to the bot. The bot is programmed to respond only to messages received from external sources, so messages sent from the same number will be ignored.

2. Check Your Webhook Configuration
If the bot isn’t responding to messages from other numbers, the issue might be with the webhook setup. Follow these steps to troubleshoot:

  • Simulate Webhook Requests: Use tools like Webhook Request Debugger to test incoming requests and verify that the webhook URL matches the one expected by the API.
  • Server Response Validation: Confirm that your server is returning a 200 OK response, which indicates the webhook is active and properly receiving requests.
  • Endpoint Testing: Use an endpoint tester to send mock callbacks to your webhook URL and ensure it is correctly configured.

3. Reach Out for Support
If you’ve tried the above steps and the issue persists, don’t hesitate to contact our technical support team. You can reach us via the chat widget on our website or email care@whapi.cloud. Our team is ready to help resolve webhook or configuration issues and get your bot running smoothly.

Conclusion

This Python-based WhatsApp bot serves as the perfect entry point for developers exploring API integration and chatbot development. By following this step-by-step guide, you’ll acquire the foundational skills needed to create more sophisticated bots that can process diverse commands, handle media interactions, and automate messaging tasks.

Whether you’re new to Python programming or looking to expand your expertise in chatbot development, this project equips you with the essential tools to master WhatsApp API integration. Start building your custom bots today and pave the way for advanced Python automation projects in the future.

Top comments (2)

Collapse
 
whapicloud profile image
WhatsApp API for developers

Made by developers for developers <3

For DEV Community members we will be ready to make a discount :)
While we are developing a system of promo codes, but if someone is interested, just write in the support chat that you are from here (dev.to) and you will get a 20% discount on the first payment

Collapse
 
whapicloud profile image
WhatsApp API for developers

The article has been updated! AI integration has been added and code examples have been updated. Thank you all!