python - Twilio - 如何处理 <gather> 上没有输入的情况

标签 python flask twilio twilio-twiml

我正在使用 Python Flask 和 twillo-python helper library 构建一个简单的 Twillo(可编程语音)应用程序。语音菜单有几个步骤,但第一个步骤要求调用者输入 PIN 码。

我正在尝试找出处理 TwiML 没有调用者输入的最佳实践 <Gather>动词以 DRY 方式。我做了一个函数process_no_input_response它接收并返回 tllio resp具有适当的对象<Say>消息取决于是否已达到允许重试的最大次数。代码示例如下。

有没有更好的方法来处理这些情况?热衷于获得有关此代码的任何建议或反馈。

def process_no_input_response(resp, endpoint, num_retries_allowed=3):
    """Handle cases where the caller does not respond to a `gather` command.
       Determines whether to output a 'please try again' message, or redirect 
       to the hand up process

    Inputs:
      resp -- A Twillo resp object
      endpoint -- the Flask endpoint
      num_retries_allowed -- Number of allowed tries before redirecting to 
        the hang up process

    Returns:
      Twillo resp object, with appropriate ('please try again' or redirect) syntax
    """

    # Add initial caller message
    resp.say("Sorry, I did not hear a response.")

    session['num_retries_allowed'] = num_retries_allowed

    # Increment number of attempts
    if endpoint in session:
        session[endpoint] += 1
    else:
        session[endpoint] = 1

    if session[endpoint] >= num_retries_allowed:
        # Reached maximum number of retries, so redirect to a message before hanging up
        resp.redirect(url=url_for('bye'))
    else:
        # Allow user to try again
        resp.say("Please try again.")
        resp.redirect(url=url_for(endpoint))

    return resp

@app.route('/', methods=['GET', 'POST'])
def step_one():
    """Entry point to respond to incoming requests."""

    resp = twilio.twiml.Response()
    with resp.gather(numDigits=6, action="/post_step_one_logic", method="POST") as gather:
        gather.say("Hello. Welcome to my amazing telephone app! Please enter your pin.")

    return str(process_no_input_response(resp, request.endpoint))    

@app.route('/bye', methods=['GET', 'POST'])
def bye():
    """Hangup after a number of failed input attempts."""

    resp = twilio.twiml.Response()
    resp.say("You have reached the maximum number of retries allowed. 
       Please hang up and try calling again.")
    resp.hangup()

    return str(resp)

最佳答案

我实际上找到了一种更简洁的方法来做到这一点,而不需要辅助函数。在此方法中,所有超时逻辑(即“请重试”或挂断)都位于 /timeout 端点中。

这似乎是超时的隐含建议,在 Advanced use section of the Twillo documentation 中看到了示例。 .

@app.route('/', methods=['GET', 'POST'])
def step_one():
    """Entry point to respond to incoming requests."""

    resp = twilio.twiml.Response()
    with resp.gather(numDigits=6, action="/post_step_one_logic", method="POST") as gather:
        gather.say("Hello. Welcome to my amazing telephone app! Please enter your pin.")
    resp.redirect(url=url_for('timeout', source=request.endpoint))

    return str(resp)


@app.route('/timeout', methods=['GET', 'POST'])
def timeout():
    """Determines whether to output a 'please try again' message, or if they
       should be cut off after a number of (i.e. 3) failed input attempts.
       Should include 'source' as part of the GET payload.
    """

    # Get source of the timeout
    source = request.args.get('source')

    # Add initial caller message
    resp = twilio.twiml.Response()
    resp.say("Sorry, I did not hear a response.")

    # Increment number of attempts
    if source in session:
        session[source] += 1
    else:
        session[source] = 1

    # Logic to determine if user should be cut off, or given another chance
    if session[source] >= 3:
        # Reached maximum number of retries, so redirect to a message before hanging up
        resp.say("""
            You have reached the maximum number of retries allowed. Please hang up 
            and try calling again.
            """)
        resp.hangup()
    else:
        # Allow user to try again
        resp.say("Please try again.")
        resp.redirect(url=url_for(source))

    return str(resp)

关于python - Twilio - 如何处理 <gather> 上没有输入的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39379541/

相关文章:

python - 在 Python 中运行 ioctl 返回 ENOTTY - 不适合设备的 ioctl

javascript - 如何使用 jquery ajax 将 json 对象正确传递给 Flask 服务器

java - 用mockito模拟twilio

python - 在 VSCode 中运行 flask 每次都会导致 HTTPServer.serve_forever(self) 断点

python - 平衡数据后 KNN 找不到类

python - 当从 fetch 发送请求时, session 消失

python - Twilio 语音调用 Django/python 中的应用程序错误

sms - 如何批量重发失败短信

python - Pandas 日期列减法

javascript - 使用js将文件从html &lt;input&gt;上传到flask服务器