Azure Function snippet for sending text messages with 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
[FunctionName("SendSms")] | |
public static async Task<IActionResult> Run( | |
// This is an HTTP trigger accepting POST requests. That's why we are able to invoke it using Postman. | |
[HttpTrigger(AuthorizationLevel.Function, "post", Route = "tygerbytes/sygnal")] HttpRequest req, | |
ILogger log, | |
ExecutionContext context) | |
{ | |
// The FuncConfig class encapsulates environment-specific settings like those | |
// TWILIO... environment variables. | |
var funcConfig = new FuncConfig(context); | |
// Grab the request body, the thing we added as "raw" JSON content in Postman. | |
string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); | |
// "Deserialize" the JSON string into an SendSmsRequest object. | |
var request = JsonConvert.DeserializeObject<SendSmsRequest>(requestBody); | |
if (!request.IsValid()) | |
{ | |
// If this request is malformed, return a 400 Bad Request HTTP code. | |
// See the SendSmsRequest class for more info. | |
return new BadRequestObjectResult(request.InvalidRequestReason()); | |
} | |
// Convert the request object back to JSON (serialize) and log it. | |
// Wasteful? Perhaps. But very useful when debugging. :) | |
log.LogInformation(Utils.ToJson(request)); | |
// Initialize the Twilio engine. Vroooom! | |
await funcConfig.TwilioInitAsync(); | |
try | |
{ | |
// Convert the semi-colon delimited list of phone numbers to an array | |
// of PhoneNumber objects, then send an SMS to each one. | |
foreach (var number in Utils.SplitTo<PhoneNumber>(request.ToPhoneNumbers)) | |
{ | |
// Creating the MessageResource sends the SMS. | |
var messageResource = MessageResource.Create( | |
// Note that we append the SMS signature to the end of the message. | |
body: $"{request.Message}\n{funcConfig.SmsSignature}", | |
from: funcConfig.TwilioPhoneNumber, | |
to: number | |
); | |
// Log it along with the status message returned. | |
log.LogInformation($"SMS to {number} has been {messageResource.Status}."); | |
} | |
} | |
catch (Exception ex) | |
{ | |
// Uh-oh. Something went wrong. Send a HTTP 500 Internal Server error code, | |
// including the exception message. | |
return new ObjectResult(ex.Message) | |
{ | |
StatusCode = 500 | |
}; | |
throw; | |
} | |
// Yay! Everything worked. Return an HTTP 200 OK. | |
return new OkObjectResult($"Message sent."); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment