Benny
Benny

Reputation: 226

Configuring Twilio SMS from Azure Functions v2

I have some code where I'm reading messages off of an Azure Event Hub that I want to either send an email or send an SMS.

The email is working through send grid, but I'm not sure how to configure the SMS part though.

I think I'd want to use Twilio and here's a sample of what my code's like. The "messageCollector" works for sending Email since there's some configuration for SendGrid in the local json. How do I configure Twilio?

    [FunctionName("SendAlert")]
    public static async Task Run(
        [EventHubTrigger("v1-email-hub", Connection = "EventHubConnection")] EventData[] events,
        [SendGrid] IAsyncCollector<SendGridMessage> messageCollector,
        [TwilioSms] IAsyncCollector<CreateMessageOptions> smsCollector,
        [Inject] NotificationEventLogic eventLogic,
        ILogger log)
    {

        foreach (EventData eventData in events)
        {

            string messageBody = Encoding.UTF8.GetString(eventData.Body.Array, eventData.Body.Offset, eventData.Body.Count);

            var notificationEvents = JsonConvert.DeserializeObject<List<NotificationEvent>>(messageBody);

            foreach (var ev in notificationEvents)
            {



                if (ev.NotificationEventType == NotificationEventType.Email)
                {
                    var message = new SendGridMessage();

                    // ... ... make message and add it
                    await messageCollector.AddAsync(message);
                }
                else if (ev.NotificationEventType == NotificationEventType.SMS)
                {
                    // Not sure how to get this to work
                    var mobileMessage = new CreateMessageOptions(new PhoneNumber(ev.Data))
                    {
                        Body = $"Notification {ev.NotificationId}"
                    };

                    await smsCollector.AddAsync(mobileMessage);
                }


                // await smsCollector.AddAsync()
                await eventLogic.CreateEventAsync(ev);
            }

        }
    }

Upvotes: 1

Views: 518

Answers (1)

Vova Bilyachat
Vova Bilyachat

Reputation: 19514

You will need to configure it in attribute

[TwilioSms(AccountSidSetting = "TwilioAccountSid", AuthTokenSetting = "TwilioAuthToken", From = "+1425XXXXXXX")]

as it mentioned in documentation

TwilioAccountSid This value must be set to the name of an app setting that holds your Twilio Account Sid e.g. TwilioAccountSid. If not set, the default app setting name is "AzureWebJobsTwilioAccountSid".

TwilioAuthToken This value must be set to the name of an app setting that holds your Twilio authentication token e.g. TwilioAccountAuthToken. If not set, the default app setting name is "AzureWebJobsTwilioAuthToken".

Upvotes: 2

Related Questions