首页 > 解决方案 > 我收到此错误“TypeError:只能将 str(不是“NoneType”)连接到 str'

问题描述

我想要实现的是用户首先会问机器人一个问题。假设用户想要找到最近的货币兑换商,他/她将输入“我需要找到货币兑换商。然后机器人将回复“请提供位置”。一旦用户提供坐标,机器人就会回复所有附近位置的货币兑换商。

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)

标签: pythonpython-3.xstringpython-requeststwilio

解决方案


Twilio 开发人员布道者在这里。

我相信您正在使用WhatsApp 的 Twilio API,基于您使用的位置参数。

这里的问题是您试图在同一个 webhook 请求中回复并接收更多信息。但是,文本消息(其中包含“moneychanger”)将来自与带有位置消息的请求不同的请求。因此,您需要在应用程序中存储一些状态,表明您的用户当前正在寻找货币兑换商。

这是一个使用Flask Sessions存储传入消息然后询问位置的示例,如果有消息将其与消息放在一起并响应:

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)

您可能还想扩展它,以便如果您在收到请求('moneychanger')之前收到带有位置的消息,那么您可以将位置存储在会话中,然后询问用户正在寻找什么。

让我知道这是否有帮助。


推荐阅读