Code works for twillo, but its not connecting

Viewed 34

I tried to code a simple sms chatbot using Twilio & Flask. The code runs fine, and the console connects, but Twilio doesn't. Some website also said something about ngrok? When I text the Twilio phone number it says, "Thanks for the message. Configure your number's SMS URL to change this message. Cheers, Londo.

try:

    from flask import Flask, request
    import requests
    from twilio.twiml.messaging_response import MessagingResponse
    import datetime
except ModuleNotFoundError:
    from subprocess import call
    modules = ["flask","datetime"]
    call("pip install " + ' '.join(modules), shell=True)


app = Flask(__name__)

x = datetime.datetime.now()

@app.route('/bot', methods=['POST'])
def bot():
    incoming_msg = request.values.get('Body', '').lower()
    resp = MessagingResponse()
    msg = resp.message()
    responded = False
    if 'Hi' in incoming_msg:
        msg.body("Hello Londo! *Type: 'Yo*")
        responded = True
    if 'Yo' in incoming_msg:
        msg.body(f'Good morning!, the date is {x.strftime("%X")}. *Type: I am up*')
        responded = True
    if 'I am up' in incoming_msg:
        msg.body('Do 10 pushups and 5 pullups! *Type: Done*')
        responded = True
    if 'Done' in incoming_msg:
        msg.body('Now make the bed. *Type: Ok')
        responded = True
    if 'Ok' in incoming_msg:
        msg.body('Wake TF up!')
        responded = True
    if not responded:
        msg.body('I only respond to certian commands')
    return str(resp)


if __name__ == '__main__':
    app.run()
1 Answers

You need two things here.

First, you need your application to have a publicly accessible URL. Using ngrok is one way to achieve that, though there are others. To do so, download and install ngrok, then run ngrok http PORT where PORT is the port number your application is running on. When you do this, ngrok will give you a URL which your application is now available on.

Second, you need to configure your Twilio phone number with this URL. Open the Twilio console, navigate to your number and configure it. In the messaging section, add your URL (https://RANDOM_SUBDOMAIN.ngrok.io/bot) to the field for the webhook when you receive a message. Save the number and text it again, you should be good.

Do note that every time you start ngrok you will get a different subdomain, so you may have to update your number again. You can overcome this by paying for an ngrok account that allows for you to choose a subdomain, or by using the Twilio CLI to create the proxy to your localhost.

Related