如何在Twilio外呼电话中提供用户选项并做出相应响应?
Hey there! The good news is that Twilio's <Gather> verb works perfectly for outbound calls too—you just need to structure your flow a bit differently than the inbound example you found. Let me walk you through how to implement this in PHP:
Step 1: Return TwiML with when the outbound call connects
When you initiate an outbound call via Twilio's API, you'll specify a URL that Twilio will hit once the call is answered. That URL needs to return TwiML that includes the <Gather> verb to prompt the user for input. Here's a sample script:
<?php require_once '/path/to/vendor/autoload.php'; use Twilio\TwiML\VoiceResponse; $response = new VoiceResponse(); // Set up Gather: collect 1 digit, send to /handle-keypress.php via POST $gather = $response->gather([ 'numDigits' => 1, 'action' => '/handle-keypress.php', 'method' => 'POST' ]); $gather->say('Please press 1 to confirm your appointment, or 2 to reschedule.'); // Fallback message if no input is received after timeout $response->say('We didn\'t get any input. Thanks for your time, goodbye!'); echo $response; ?>
Step 2: Handle the collected keypress
Create a second script (handle-keypress.php) that Twilio will send the collected digits to. This is where you can process the user's input and respond accordingly:
<?php require_once '/path/to/vendor/autoload.php'; use Twilio\TwiML\VoiceResponse; // Grab the digits sent by Twilio $userInput = $_POST['Digits']; $response = new VoiceResponse(); switch ($userInput) { case '1': $response->say('Great! Your appointment is confirmed. Have a wonderful day.'); break; case '2': $response->say('No problem. Please give us a call at 555-1234 to reschedule your appointment.'); break; default: $response->say('Sorry, that\'s not a valid option. Goodbye!'); } echo $response; ?>
Key Notes:
- When you initiate the outbound call using Twilio's API, make sure the
urlparameter points to your first script (the one with the<Gather>verb). Twilio will fetch this TwiML as soon as the call is answered. - Adjust
numDigitsor addfinishOnKey(e.g.,finishOnKey: '#') if you need to collect multiple digits or let the user end input manually. - If you prefer a no-code/low-code approach, you can use Twilio Studio to build your outbound flow—just drag a "Gather Input on Call" component into your flow and configure it to route based on user input.
Hope this gets you sorted out! 😊
内容的提问来源于stack exchange,提问作者coder

