发起呼叫,录制并播放录音

时间:2016-10-03 03:15:00

标签: python twilio

我正在为想要进行基于手机测试的客户整理POC。在POC中,我们只是想让用户在网页上输入电话#。然后我们会显示一个问题并拨打他们的号码。我们会记录他们对问题的回答并将其播放给他们。

我可以发起通话,但无法弄清楚如何表明我想录制它。理想情况下,我想说些什么并在哔哔声后开始录音。

我对Twilio有3个小时的经验,所以请原谅我的无知。

到目前为止,这是我的代码:

import logging

# [START imports]
from flask import Flask, render_template, request
import twilio.twiml
from twilio.rest import TwilioRestClient
# [END imports]

app = Flask(__name__)


# [START form]
@app.route('/form')
def form():
    return render_template('form.html')
# [END form]


# [START submitted]
@app.route('/submitted', methods=['POST'])
def submitted_form():
    phone = request.form['phone']

    account_sid = "AC60***********************"
    auth_token = "27ea************************"
    client = TwilioRestClient(account_sid, auth_token)
    call = client.calls.create(to=phone,  # Any phone number
        from_="+160#######", # Must be a valid Twilio number
        url="https://my-host/static/prompt.xml")

    call.record(maxLength="30", action="/handle-recording")

    return render_template(
        'submitted_form.html',
        phone=phone)
    # [END render_template]

@app.route("/handle-recording", methods=['GET', 'POST'])
def handle_recording():
    """Play back the caller's recording."""

    recording_url = request.values.get("RecordingUrl", None)

    resp = twilio.twiml.Response()
    resp.say("Thanks for your response... take a listen to what you responded.")
    resp.play(recording_url)
    resp.say("Goodbye.")
    return str(resp)

@app.errorhandler(500)
def server_error(e):
    # Log the error and stacktrace.
    logging.exception('An error occurred during a request.')
    return 'An internal error occurred.', 500
# [END app]

1 个答案:

答案 0 :(得分:1)

Twilio开发者传道者在这里。

创建呼叫时,会将URL传递给呼叫。该URL将是用户接听电话时调用的URL。对该请求的回复应该是TwiML,以指示Twilio对say the messagerecord的回复。像这样:

@app.route("/handle-call", methods=['GET', 'POST'])
def handle_call():
    resp = twilio.twiml.Response()
    resp.say("Please leave your message after the beep")
    resp.record(action="/handle-recording", method="POST")
    return str(resp)

然后,您只需更新您的通话创建以指向该网址

call = client.calls.create(to=phone,  # Any phone number
        from_="+160#######", # Must be a valid Twilio number
        url="https://my-host/handle-call")

您的/handle-recording路径看起来好像已经做了您想做的事。

快速提示,因为您是Twilio的新用户,在使用webhook进行开发时,我建议使用ngrok隧道到您的开发机器并将您的应用程序暴露给Twilio。我写了blog post about how to use ngrok和我喜欢的一些功能。

让我知道这是否有帮助。