twilio sms keyword autoresponder search incoming b

2019-08-10 09:05发布

问题:

Can someone help to revise the suggested code from Twilio to search through the incoming sms body to send different responses? https://www.twilio.com/help/faq/sms/how-do-i-build-a-sms-keyword-response-application

Need to alter code so that it searches the incoming SMS for keyword "logging" e.g. "Need help logging in", then the a different response will send.

/* Controller: Match the keyword with the customized SMS reply. */
function index(){
$response = new Services_Twilio_Twiml();
$response->sms("Hi. Received your message. We will contact you via email on file.");
echo $response;
}
function password(){
$response = new Services_Twilio_Twiml();
$response->sms("Hi. Received your message. We will contact you via email on file. #Password");
echo $response;
}

function logging(){
$response = new Services_Twilio_Twiml();
$response->sms("Hi. Received your message. We will contact you via email on file. #Logging");
echo $response;
}

/* Read the contents of the 'Body' field of the Request. */
$body = $_REQUEST['Body'];
/* Remove formatting from $body until it is just lowercase 
characters without punctuation or spaces. */
$result = preg_replace("/[^A-Za-z0-9]/u", " ", $body);
$result = trim($result);
$result = strtolower($result);

/* Router: Match the ‘Body’ field with index of keywords */
switch ($result) {
case 'password’':
    password();
    break;
case 'logging':
    logging();
    break;

/* Optional: Add new routing logic above this line. */
default:
    index();

}

回答1:

Ricky from Twilio here again.

Glad you got things working on your host! As you've seen, the current code sample only will match if someone sends the exact word "logging" as their message body. If you want to match the text in a string (ex: "need help logging in") I would use PHP's stripos function. With that you could do something like this:

/* Read the contents of the 'Body' field of the Request. */
$body = $_REQUEST['Body'];
// Check to see if contains the word "logging"
if(stripos($body, "logging") !== FALSE) {
  // message contains the word "logging"
} else {
  // message does not contain the word "logging"
}