Build a working SMS chat-bot in 10 minutes
gk_
17218

Hmmm I think I’m almost there, but Twilio debugger is reporting to me an error:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>405 Method Not Allowed</title>
<h1>Method Not Allowed</h1>
<p>The method is not allowed for the requested URL.</p>

I suppose that’s being returned by Python/Flask. Not sure. My code is below (twilio auth info removed). Any thoughts appreciated. I did research this before posting question.

import json
import apiai
from flask import Flask
import twilio.twiml
from twilio.rest import TwilioRestClient

# Twilio account info
account_sid = “xxx”
auth_token = “xxx”
account_num = “+xxx”
client = TwilioRestClient(account_sid, auth_token)

# api.ai account info
CLIENT_ACCESS_TOKEN = “xxx”
ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)

app = Flask(__name__)

#remove , methods=[‘GET’, ‘POST’]) from function call below
@app.route(‘/hello’, methods=[‘GET’, ‘POST’])
def hello_world():
 return ‘Hello api.ai (from Flask!)’

@app.route(“/”, methods=[‘GET’, ‘POST’])
def server():
 from flask import request
 # get SMS input via twilio
 resp = twilio.twiml.Response()

# get SMS metadata
 msg_from = request.values.get(“From”, None)
 msg = request.values.get(“Body”, None)

# prepare API.ai request
 req = ai.text_request()
 req.lang = ‘en’ # optional, default value equal ‘en’
 req.query = msg

# get response from API.ai
 api_response = req.getresponse()
 responsestr = api_response.read().decode(‘utf-8’)
 response_obj = json.loads(responsestr)
 if ‘result’ in response_obj:
 response = response_obj[“result”][“fulfillment”][“speech”]
 # send SMS response back via twilio
 client.messages.create(to=msg_from, from_= account_num, body=response)
 #resp.message(response)

return str(resp)

if __name__ == “__main__”:
 app.run(debug=True, host=’0.0.0.0', port=5002)

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.