Published on

Creating a WhatsApp Bot for Automation

Authors
  • avatar
    Name
    how-to.digital
    Twitter

Creating a WhatsApp Bot for Automation

With over 2 billion active users, WhatsApp is one of the most popular messaging platforms globally. Building a WhatsApp bot for automation can help streamline communication and automate various tasks. In this tutorial, we will walk you through the process of creating a WhatsApp bot using Python and the Twilio API.

Prerequisites

Before we begin, make sure you have the following:

  1. Python installed on your machine
  2. Twilio account (sign up for a free account at https://www.twilio.com/try-twilio)
  3. A valid WhatsApp-enabled phone number

Step 1: Setting up the Project

  1. Create a new directory for your project.

  2. Open a terminal or command prompt and navigate to the project directory.

  3. Initialize a Python virtual environment by running the following command:

    python3 -m venv venv
    
  4. Activate the virtual environment:

    • On macOS and Linux:
      source venv/bin/activate
      
    • On Windows:
      venv\Scripts\activate
      
  5. Now we need to install the required libraries. Run the following command:

    pip install twilio flask
    

Step 2: Setting up Twilio

  1. Navigate to https://www.twilio.com/console and sign in with your Twilio account credentials.
  2. Once logged in, click on the "Get a Trial Number" button to obtain a WhatsApp-enabled phone number. Note down this number as we will need it later.
  3. Under the Twilio dashboard, click on the "Settings" tab and copy the Account SID and Auth Token. We will also need these credentials later.

Step 3: Writing the Code

  1. Create a new Python file in the project directory, for example, bot.py.

  2. Import the necessary libraries:

    from flask import Flask, request
    from twilio.twiml.messaging_response import MessagingResponse
    
  3. Initialize the Flask application:

    app = Flask(__name__)
    
  4. Create a route to handle incoming WhatsApp messages:

    @app.route("/webhook", methods=["POST"])
    def webhook():
        # Get the incoming message
        message_body = request.form["Body"]
    
        # Process the message and generate a reply
        reply = process_message(message_body)
    
        # Prepare the TwiML response
        twiml_response = MessagingResponse()
        twiml_response.message(reply)
    
        return str(twiml_response)
    
  5. Implement the process_message function to handle the incoming message and generate a reply based on your desired automation task.

  6. Add the main section to run the Flask application:

    if __name__ == "__main__":
        app.run(debug=True)
    

Step 4: Testing the WhatsApp Bot

  1. Run the Flask application by executing the following command in the terminal:

    python bot.py
    
  2. Ngrok is a useful tool that allows you to expose your local development server to the internet. Download and install ngrok from https://ngrok.com.

  3. Launch ngrok by running the following command in a separate terminal window:

    ngrok http 5000
    
  4. Ngrok will provide you with a forwarding URL. Copy the URL that starts with "https://" and ends with ".ngrok.io".

  5. Go back to your Twilio dashboard and navigate to the "WhatsApp Sandbox" page.

  6. In the "WHEN A MESSAGE COMES IN" field, enter the ngrok URL followed by "/webhook". For example:

    https://abcd1234.ngrok.io/webhook
    
  7. Save the configuration.

  8. Now, send a message to your WhatsApp-enabled Twilio number to test the bot. You should receive a reply based on the automation logic you implemented.

Congratulations! You have successfully created a WhatsApp bot for automation using Python and the Twilio API. Feel free to enhance and customize your bot according to your specific requirements.