这里是 Twilio 开发者宣传员。
您可能在呼入电话中看到了这个documentation on gathering user input via keypad in Python。
当您接到入站电话时,Twilio 会发出 webhook 请求以了解下一步要做什么,然后您会使用 TwiML 进行响应,例如,当您想要获取信息时使用 <Gather>。
当您进行出站呼叫时,您 initiate the call with the REST API,然后当呼叫连接时,Twilio 向您的 URL 发出 webhook 请求。然后,您可以回复 TwiML 来告诉 Twilio 要做什么,您也可以在此阶段回复 <Gather>。
让我们从outbound call as shown in this documentation 收集输入。
首先,您购买一个 Twilio 电话号码并使用 Ngrok URL 对其进行配置:这是一个方便的工具,可通过公共 URL 将您的本地服务器打开到网络。当您拨打外线电话时,您会将这个 URL 传递给它:your-ngrok-url.ngrok.io/voice。
from twilio.rest import Client
account_sid = 'your-account-sid'
auth_token = 'your-auth-token'
client = Client(account_sid, auth_token)
call = client.calls.create(
url='https://your-ngrok-url.ngrok.io/voice',
to='phone-number-to-call',
from_='your-twilio-number'
)
client.calls.create 中的 URL 返回 TwiML,其中包含有关用户接听电话时应该发生的情况的说明。让我们创建一个 Flask 应用程序,其中包含在用户接听电话时运行的代码。
from flask import Flask, request
from twilio.twiml.voice_response import VoiceResponse, Gather
app = Flask(__name__)
@app.route("/voice", methods=['GET', 'POST'])
def voice():
# Start a TwiML response
resp = VoiceResponse()
您将通过带有 TwiML Gather 动词的键盘接收用户输入,该动词用于在通话期间收集数字或转录语音。 Action attribute 将绝对或相对 URL 作为值,一旦调用者完成输入数字(或达到超时),Twilio 就会发出 HTTP 请求。该请求包括用户的数据和 Twilio 的标准请求参数。
如果您从调用者那里收集数字,Twilio 会包含 Digits 参数,其中包含调用者输入的数字。
gather = Gather(num_digits=1, action='/gather')
gather.say('For sales, press 1. For support, press 2.')
resp.append(gather)
如果收件人没有选择选项,我们让他们循环回到开头,这样他们就可以再次听到指示。
resp.redirect('/voice')
return str(resp)
但是,如果他们确实选择了一个选项并在键盘中输入了一个数字,Twilio 将使用他们输入的数字向托管您的 TwiML 的 URL 发送一个 POST 请求。这就是您通过接收者按下按钮获取用户输入并将其引导回您的 Python 程序的方式:使用request.values['Digits']。根据该值(在choice 变量中,您可以相应地更新数据库或其他内容,如下面的条件所示。
@app.route('/gather', methods=['GET', 'POST'])
def gather():
"""Processes results from the <Gather> prompt in /voice"""
# Start TwiML response
resp = VoiceResponse()
# If Twilio's request to our app included already gathered digits,
# process them
if 'Digits' in request.values:
# Get which digit the caller chose
choice = request.values['Digits']
# <Say> a different message depending on the caller's choice
if choice == '1':
resp.say('You selected sales. Good for you!')
return str(resp)
elif choice == '2':
resp.say('You need support. We will help!')
return str(resp)
else:
# If the caller didn't choose 1 or 2, apologize and ask them again
resp.say("Sorry, I don't understand that choice.")
# If the user didn't choose 1 or 2 (or anything), send them back to /voice
resp.redirect('/voice')
return str(resp)
希望这会有所帮助!