简体   繁体   中英

I got this error 'TypeError: can only concatenate str (not "NoneType") to str'

What I am trying to achieve is that the user will first ask the bot a question. Let say the user wants to find the nearest money changer he/she will type "I need to find a money changer. Then the bot will reply with 'Please provide the location". Once the user provides the coordinates the bot will then reply with all the nearby locations money changer.

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


app = Flask(__name__)


@app.route('/sms', methods=['POST'])
def bot():

    incoming_msg = request.values.get('Body', '').lower()
    resp = MessagingResponse()
    msg = resp.message()

    if 'moneychanger' in incoming_msg:
        search1 = 'Please provide the location please'
        msg.body(search1)

        message_latitude = request.values.get('Latitude', None)
        message_longitude = request.values.get('Longitude', None)

        responded = True

        if message_latitude == None:
            location = '%20' + message_latitude + '%2C' + message_longitude 
            responded = False


            url = f'https://tih-api.stb.gov.sg/money-changer/v1?location={location}&radius=2000'

            r = requests.get(url)
            if r.status_code == 200:
                data = r.json()
                search = data['data'][0]['name']
            else:
                search = 'I could not retrieve a quote at this time, sorry.'
            msg.body(search)
            responded = True

    return str(resp)

if __name__ == "__main__":
    app.run(debug=True)

Twilio developer evangelist here.

I believe you are working with the Twilio API for WhatsApp , based on your using location parameters.

The issue here is that you are trying to reply to and receive more information within the same webhook request. However, the text message (with "moneychanger" in it) will come in a different request to the request with the location message. So, you need to store some state within your application that says your user is currently looking for a moneychanger.

Here's an example usingFlask Sessions to store the incoming message and then ask for location and if there's a message put that together with the message and respond:

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


app = Flask(__name__)

# Set the secret key to some random bytes. Keep this really secret! 
# Don't use these bytes because they are in the documentation.
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

@app.route('/sms', methods=['POST'])
def bot():
    incoming_msg = request.values.get('Body', '').lower()
    resp = MessagingResponse()
    msg = resp.message()

    message_latitude = request.values.get('Latitude', None)
    message_longitude = request.values.get('Longitude', None)

    if 'moneychanger' in incoming_msg:
        # We're looking for a moneychanger, ask for the location
        response = 'Please provide the location please'
        session['message'] = incoming_msg
    elif message_latitude && message_longitude && 'message' in session && 'moneychanger' in session['message']
        # We have the location and the previous message was asking for a
        # moneychanger.
        location = '%20' + message_latitude + '%2C' + message_longitude 
        url = f'https://tih-api.stb.gov.sg/money-changer/v1?location={location}&radius=2000'

        r = requests.get(url)
        if r.status_code == 200:
            data = r.json()
            response = data['data'][0]['name']
        else:
            response = 'I could not retrieve a quote at this time, sorry.'
        # we're done with the original message so we can unset it now.
        session['message'] = None
    else:
      # In this case, either you have a message that doesn't include 
      # 'moneychanger' or you have latitude and longitude in the request but 
      # no session['message']. You probably want to do something else here, but
      # I don't know what yet.
      response = 'I\'m not sure what you\'re looking for.'

    msg.body(response)
    return str(resp)

if __name__ == "__main__":
    app.run(debug=True)

You may also want to extend this so that if you receive a message with location in before receiving the request ('moneychanger') then you could store the location in the session and then ask what the user is looking for.

Let me know if that helps at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM