All Together!
All the aspects of the chatbot implementation can be put together in the bot.py file.
from flask import Flask, request
import requests
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()
responded = False
if 'hello' in incoming_msg:
msg.body("Hi, how can I help you today?")
if 'quote' in incoming_msg:
# return a quote
r = requests.get('https://api.quotable.io/random')
if r.status_code == 200:
data = r.json()
quote = f'{data["content"]} ({data["author"]})'
else:
quote = 'I could not retrieve a quote at this time, sorry.'
msg.body(quote)
responded = True
if 'dog' in incoming_msg:
# return a dog pic
msg.media("https://dog.ceo/api/breeds/image/random")
responded = True
if not responded:
msg.body('I only know about famous quotes and dogs, sorry!')
return str(resp)
if __name__ == '__main__':
app.run()
Now, all we need to do is see our chatbot in action.
5
