Search code examples
twiliotwilio-functionstwilio-studio

Twilio Functions - Pass in parameters and format SMS body to include parameters


I am using Twilio to create an 'attendance line' where employees can provide information about why they will be absent and then Twilio will send separate, curated messages to supervisors and human resources.

To do this, I've created a Flow in Twilio Studio and I would like to use a Twilio Function to handle sending the mass SMS messages notifying users of a new absence.

I am passing parameters to the function like name, dept, shift, reason, etc with the intent to then share these values via SMS.

I am having the hardest time getting all of these different values properly into the body of the message.

exports.handler = function(context, event, callback) {

 // Create a reference to the user notification service

 const client = context.getTwilioClient();

 const service = client.notify.services(
   context.TWILIO_NOTIFICATION_SERVICE_SID
 );


 const notification = {
   toBinding: JSON.stringify({
    binding_type: 'sms', address: '+1XXXXXXXXXX',
    binding_type: 'sms', address: '+1XXXXXXXXXX',

  }),

  body: 'New Attendance Notification',
        event.question_name,
        event.question_dept,
        event.question_reason,
        event.contactChannelAddress,


 };

 console.log(notification);

 // Send a notification
 return service.notifications.create(notification).then((message) => {
   console.log('Notification Message',message);
   callback(null, "Message sent.");
 }).catch((error) => {
   console.log(error);
   callback(error,null);
 });
};

Now I know the 'body' of the message above will not work but I'm a bit lost...

The text below is how I would like my SMS message to read out when sent.

New Attendance Notification
Name: event.Name
Dept: event.Dept
Reason: event.Reason
Contact: event.ContactChannelAddress

Is what I am trying to accomplish even possible?


Solution

  • Something like this...

    exports.handler = function(context, event, callback) {
    
     // Create a reference to the user notification service
    
     const client = context.getTwilioClient();
    
     const service = client.notify.services(
        context.TWILIO_NOTIFICATION_SERVICE_SID
     );
    
    
     const bindings = [
        '{ "binding_type": "sms", "address": "+14071234567" }',
        '{ "binding_type": "sms", "address": "+18021234567" }'
        ];
    
     const notice = `New Attendance Notification\nName: ${event.question_name}\nDept: ${event.question_dept} \nReason: ${event.question_reason}\nContact: ${event.contactChannelAddress} \n`;
    
     // Send a notification
      service.notifications.create({ toBinding: bindings, body: notice }).then((message) => {
        console.log('Notification Message',message);
        callback(null, "Message sent.");
      })
      .catch((error) => {
       console.log(error);
       callback(error,null);
     });
    };