【问题标题】:Twilio: How to reply to a users message with a customized message based on the user's previous message in python?Twilio:如何根据用户在python中的先前消息使用自定义消息回复用户消息?
【发布时间】:2026-02-08 17:40:02
【问题描述】:

我有一个 android 应用程序,它向我的 twilio 号码发送一条带有 json 内容的短信。我有一个 twiml flask python 应用程序,它应该从 android 应用程序读取用户以前的短信,并且它应该返回一个自定义的回复消息,说明用户在文本中所说的重复。

所以如果用户说“圣何塞”。 twiml 应用程序(托管在 heroku 服务器上)会回复“你想去”“吗?”。所以在这种情况下,它会回复“你想去圣何塞吗?”

我应该怎么做才能阅读用户的消息并根据他的消息进行回复?

附:我对 python、flask 和 twilio 有点陌生,所以任何带有代码的答案都会有所帮助。

这是我的代码:

from flask import Flask, request, redirect
from twilio.rest import TwilioRestClient
import twilio.twiml
import requests
import json
import httplib

app = Flask(__name__)

# Try adding your own number to this list!
callers = {
    "+14151234556": "The Hunter",
    "+14158675310": "The Best",
    "+14158675311": "Virgil",
}

@app.route("/", methods=['GET', 'POST'])
def hello_monkey():

ACCOUNT_SID = "askdfjhaksjdfklajsdlfjaslkdfjals"
    AUTH_TOKEN = "kasjdkjaSDKjaskdjkasJDkasjdkljAS"

    """Respond and greet the caller by name."""

    from_number = request.values.get('From', None)
    if from_number in callers:
        message = callers[from_number] + ", follow these directions to get to your destination: "
    else:
        message = "User, thanks for the message!"

    resp = twilio.twiml.Response()
    resp.message(message)

    return str(resp)

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

【问题讨论】:

    标签: android python heroku twilio twilio-twiml


    【解决方案1】:

    此处是 Twilio 开发人员宣传员。您似乎走在正确的道路上,而且几乎是正确的。

    您需要做的就是将以下代码 sn-p 更改为:

    from_number = request.values.get('From', None)
    if from_number in callers:
        message = callers[from_number] + ", follow these directions to get to your destination: "
    else:
        message = "User, thanks for the message!"
    

    收件人:

    from_number = request.values.get('From', None)
    if from_number in callers:
        message = callers[from_number] + ", follow these directions to get to your destination: " + request.values.get('Body', None)
    else:
        message = "User, thanks for the message!"
    

    请注意我是如何将request.values.get('Body', None) 添加到其中的,因此它会拾取该变量并在生成 TwiML 时使用它。让我知道这是否能解决您的问题。

    【讨论】:

      最近更新 更多