Building WhatsApp bot on Python

Configurare noua (How To)

Situatie

Solutie

Pasi de urmat
System Requirements:
  • A Twilio account and a smartphone with an active phone number and WhatsApp installed.
  • Must have Python 3.9 or newer installed in the system.
  • Flask: We will be using a flask to create a web application that responds to incoming WhatsApp messages with it.
  • ngrok: Ngrok will help us to connect the Flask application running on your system to a public URL that Twilio can connect to. This is necessary for the development version of the chatbot because your computer is likely behind a router or firewall, so it isn’t directly reachable on the Internet.

Set up the Twilio account using the Twilio WhatsApp API

  • After login, select the Develop option from the left menu and then further select the Messaging subject then select the Try it out option, and in the last click on Send a WhatsApp message. This will open up a new webpage for setting up the WhatsApp Sandbox.

Configure the Twilio WhatsApp Sandbox by sending a message to this WhatsApp number with the secrete unique security code as shown in the below images:

  • Send the code as below format to the following number: +14155238886
  • secret code : join <secret-code>

Open up the terminal and run the following command to create a directory for the bot, to create a virtual environment for python, to install all the necessary packages.

  • To create  the directory and navigate to that directory: mkdir geeks-bot && cd geeks-bot
  • To create and activate the python virtual environment: python3 -m venv geek-bot-env && source geek-bot-env/bin/activat
  • To install Twilio, flask and requests:
  • pip3 install twill flask request
  • Here are the above commands in just one line : mkdir geek-bot && cd geek-bot && python3 -m venv geek-bot-env && source geek-bot-env/bin/activate && pip3 install twilio flask requests
Creating a Flask Chatbot Service for running the bot locally:

Step 1: Import the necessary files needed to run this flask app.

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

Receiving message entered by the user and sending the response. We can access the user response that is coming in the payload of the POST request with a key of ’Body’.

from flask import request

incoming_msg = request.values.get(‘Body’, ”).lower()

To send messages/respond to the user, we are going to use MessagingResponse()function from Twilio.

from twilio.twiml.messaging_response import MessagingResponse

response = MessagingResponse()
msg = response.message()
msg.body(‘this is the response/reply from the bot.)

Tip solutie

Permanent

Voteaza

(7 din 9 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?