Created
October 19, 2014 03:55
-
-
Save marcusmoore/eb508fc0a60a9661e472 to your computer and use it in GitHub Desktop.
Send quotes via Twilio
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Within a Laravel controller function | |
*/ | |
# Get Twilio sid, token and number from environment variables | |
$sid = getenv("twilio_sid"); | |
$token = getenv("twilio_token"); | |
$twilio_number = getenv("twilio_number"); | |
# Get the phone number of the sender | |
$from = $_POST['From']; | |
# Get the body of the sender's message | |
$body = strtolower($_POST["Body"]); | |
# Create Twilio Client | |
$twilio = new Services_Twilio($sid, $token); | |
# Check to see if the text's body contains "quote" using regex but strpos isn't fun. | |
if ( ! preg_match("/quote/", $body) ) | |
{ | |
# They didn't ask for a quote. Let them know via text. | |
$twilio->account->messages->sendMessage( | |
$twilio_number, | |
$from, | |
"You didn't ask for a quote!" | |
); | |
# Well...they didn't want a quote. Let's get outta here. | |
exit(); | |
} | |
/* | |
* Set our array of quotes... | |
* This is a mixed array that are either strings or sub-arrays that contain multiple strings | |
* | |
* I removed the actual quotes for mystery. | |
*/ | |
$quotes = [ | |
"quote 1", | |
"quote 2", | |
"quote 3", | |
"etc...", | |
[ | |
"quote 1", | |
"quote 2" | |
], | |
[ | |
"quote 1", | |
"quote 2", | |
"quote 3" | |
], | |
]; | |
# Select random number | |
$randomNumber = mt_rand(0, count($quotes) - 1); | |
# Pick a quote using random number | |
$choice = $quotes[$randomNumber]; | |
/* | |
* If the selected quote from above is an array we need to loop | |
* through it and send the message one at at time | |
*/ | |
if ( is_array($choice) ) | |
{ | |
foreach ( $choice as $quote ) | |
{ | |
# Send message off! | |
$twilio->account->messages->sendMessage( | |
$twilio_number, | |
$from, | |
$quote | |
); | |
} | |
# Messages sent...let's have a beer. | |
exit(); | |
} | |
/* | |
* If we made it this far then only one quote needs to be sent. | |
* Send it... | |
*/ | |
$twilio->account->messages->sendMessage( | |
$twilio_number, | |
$from, | |
$choice | |
); | |
# All is good! Let's get on with the day. | |
exit(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment