Creating a WhatsApp Bot Using Python

In today’s digital age, WhatsApp has become a crucial platform for communication. Businesses and individuals alike can benefit from automating interactions through a WhatsApp bot. In this post, we’ll guide you through creating a WhatsApp bot using Python, utilizing the Twilio API for messaging.

Prerequisites

  1. Python 3.6+: Make sure you have Python installed. If not, download it from python.org.
  2. Twilio Account: Sign up for a Twilio account and get a Twilio phone number.
  3. ngrok: Install ngrok for exposing your local server to the internet.

Step 1: Install Required Libraries

First, install the necessary Python libraries. Open your terminal or command prompt and run:

pip install twilio flask

Step 2: Setting Up Twilio

  1. Create a Twilio Account: If you haven’t already, sign up at Twilio.
  2. Get a Twilio Phone Number: Purchase a phone number from Twilio capable of sending and receiving WhatsApp messages.
  3. Get Your Twilio Credentials: Note down your Account SID and Auth Token from the Twilio console.

Step 3: Setting Up Your Python Project

Create a new directory for your project and navigate into it:

mkdir whatsapp-bot
cd whatsapp-bot

Create a new Python file, app.py, and open it in your favorite code editor.

Step 4: Writing the Bot Code

Here’s a simple example using Flask and Twilio:

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

app = Flask(__name__)

@app.route("/bot", methods=['POST'])
def bot():
    incoming_msg = request.values.get('Body', '').lower()
    resp = MessagingResponse()
    msg = resp.message()

    if 'hello' in incoming_msg:
        msg.body('Hi there! How can I help you today?')
    elif 'bye' in incoming_msg:
        msg.body('Goodbye! Have a great day!')
    else:
        msg.body('I am a simple bot. Say "hello" to start a conversation.')

    return str(resp)

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

Step 5: Exposing Your Local Server

To test the bot, we need to expose our local server to the internet. We’ll use ngrok for this. In your terminal, run:

ngrok http 5000

Copy the URL provided by ngrok (e.g., http://abc123.ngrok.io).

Step 6: Configuring Twilio Webhook

  1. Go to your Twilio console.
  2. Navigate to the WhatsApp sandbox settings.
  3. Set the “WHEN A MESSAGE COMES IN” webhook to your ngrok URL followed by /bot (e.g., http://abc123.ngrok.io/bot).

Step 7: Testing Your Bot

Send a WhatsApp message to your Twilio number. You should receive automated responses based on the logic defined in app.py.

Conclusion

You now have a basic WhatsApp bot up and running using Python, Flask, and Twilio. This bot can be extended with more complex logic, integrated with databases, or connected to other APIs to enhance its functionality. Happy coding!

If you have any questions or need further assistance, feel free to reach out in the comments below.

Categorized in:

ChatBot, Python,