Skip to content

Instantly share code, notes, and snippets.

@Nuxij
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nuxij/072e67a8033b1b983d8f to your computer and use it in GitHub Desktop.
Save Nuxij/072e67a8033b1b983d8f to your computer and use it in GitHub Desktop.
Twilio message forwarder
<?php
require 'twilio-php/Services/Twilio.php';
include 'marg/marg.php';
class Messenger {
private $AccountSid = "guff";
private $AuthToken = "junk";
private $ourNumber = "+440987654321";
private $validSenders = array(
"+441234567890" => "Joe Eaves"
);
private $Members = array(
"+441234567890" => "Joe Eaves"
);
private function debugPrint($data) {
$fp=fopen('/tmp/debug.txt','w');
fwrite($fp, $data . "\n");
fclose($fp);
}
private function receiveMessage($request) {
$client = new Services_Twilio($this->AccountSid, $this->AuthToken);
$reqBody = $request->request_body;
$this->debugPrint("Function called");
if ($request->verb == 'POST') {
if(!isset($reqBody["Body"]) || !isset($reqBody["To"]) ||
!isset($reqBody["From"]) || !isset($reqBody["MessageSid"]) ||
!isset($reqBody["AccountSid"]))
return response("There was an error processing your message.");
$body = $reqBody['Body'];
$from = $reqBody['From'];
$this->debugPrint($reqBody['From'] . " " . $reqBody['Body']);
if (array_key_exists($from, $this->validSenders)) {
$failedNumbers = array();
$returnMessage = "Thank you for your message!";
foreach ($this->Members as $number => $name) {
try {
$message = $client->account->messages->create(array(
"From" => $this->ourNumber,
"To" => $number,
"Body" => "Message System\nSender: " .
$this->validSenders[$from] . "\n" . $body
));
} catch (Services_Twilio_RestException $e) {
$failedNumbers[] = $number;
}
}
if (count($failedNumbers) > 0) {
$returnMessage = $returnMessage . "\nThe following numbers failed:";
foreach ($failedNumbers as $f_number) {
$returnMessage = $returnMessage . "\n" .
$this->Members[$f_number] . ": " . $f_number;
}
}
$this->response($returnMessage);
}
}
}
private function response($message) {
header("content-type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<Response><Message>" . $message . "</Message></Response>";
return true;
}
public function post() {
global $request;
$this->receiveMessage($request);
}
}
$margRoutes = array(
"/message" => "Messenger",
);
Marg::run($margRoutes);
?>
@Nuxij
Copy link
Author

Nuxij commented Mar 13, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment