Build a WhatsApp Chatbot With Python, Flask and Twilio
A chatbot is a software application that is able to conduct a conversation with a human user through written or spoken language. The level of “intelligence” among chatbots varies greatly. While some chatbots have a fairly basic understanding of language, others employ sophisticated artificial intelligence (AI) and machine learning (ML) algorithms to achieve an almost human conversational level.
In this tutorial I’m going to show you how easy it is to build a chatbot for WhatsApp using the Twilio API for WhatsApp and the Flask framework for Python. Below you can see an example interaction I had with this chatbot:
In the example we build a very easy Whatsapp Bot with Python Flask Chatterbot und Twillio API.
The Chatbot can be build in just some few lines of python code.
|from flask import Flask, render_template, request|
|from chatterbot import ChatBot|
|from chatterbot.trainers import ChatterBotCorpusTrainer|
|from twilio.twiml.messaging_response import MessagingResponse|
|app = Flask(__name__)|
|german_bot = ChatBot("Chatterbot", storage_adapter="chatterbot.storage.SQLStorageAdapter")|
|trainer = ChatterBotCorpusTrainer(german_bot)|
|userText = request.args.get('msg')|
|incoming_msg = request.values.get('Body', '').lower()|
|resp = MessagingResponse()|
|msg = resp.message()|
|antwort = german_bot.get_response(incoming_msg)|
|if __name__ == "__main__":|
Configure the Twilio WhatsApp Sandbox
Twilio provides a WhatsApp sandbox where you can easily develop and test your application. Once your application is complete you can request production access for your Twilio phone number, which requires approval by WhatsApp.
Let’s connect your smartphone to the sandbox. From your Twilio Console, select Programmable SMS and then click on WhatsApp. The WhatsApp sandbox page will show you the sandbox number assigned to your account, and a join code.
To enable the WhatsApp sandbox for your smartphone send a WhatsApp message with the given code to the number assigned to your account. The code is going to begin with the word join, followed by a randomly generated two-word phrase. Shortly after you send the message you should receive a reply from Twilio indicating that your mobile number is connected to the sandbox and can start sending and receiving messages.
Note that this step needs to be repeated for any additional phones you’d like to have connected to your sandbox.