Home/InternetNodejs/Twilio Send Notification Messages (Nodejs SDK)

Twilio Send Notification Messages (Nodejs SDK)

Twilio Messaging Services
  • Click Create Messaging Service and add your phone number.
  • Setup a notify service instance. Make note of the SID! You will use this later when you start writing code further down.
    https://www.twilio.com/console/notify/services
    ** There isn’t a menu link fo rnotification service in new Twilio panel.
Twilio create notify service
  • Now choose your new Messaging Service for this Notify Service Instance
  • We need three keys to send Notification message in twilio.
    • accountSid
    • authToken
    • Service Instance SID

Account SID and Auth Token:
Go to Dashboard and click on Messaging Overview:

Get Service Instance ID: We have created SID above. You can go to this link and copy your Instance ID.
https://www.twilio.com/console/notify/services

Note: Service Instance id will start with: ISxxxxxxxxxxxxxx

  • Now we have all the details available, lets get into the code. Get the Official Nodejs sdk from twilio resouces.
    https://github.com/twilio/twilio-node
  • Clone the repo and run:
    npm install
  • Create a file send_sms.js which you’ll run though node to trigger sms (this can be modified as per your usecase).
const twilio = require('twilio');
const accountSid = 'ACXXXXXXXXXXXXXXXXXX';
const authToken = '12sadf2323424232sdfa23';
const notifySID = 'ISXXXXXXXXXXXXXXXXXXX';
const client = require('twilio')(accountSid, authToken);
const data = require('./import-data.js');
/* Lets format the data into desired array :
[
  '{"binding_type":"sms","address":"+44XXXXXXXXXX"}',
  '{"binding_type":"sms","address":"+44XXXXXXXXXxx"}' 
]
*/
let formattedData = [];
data.forEach(function(value){
formattedData.push(JSON.stringify(value));
});
console.log(formattedData);
const notificationOpts = {
toBinding: formattedData,
body: 'YOUR MESSAGE HERE!',
};
client.notify.services(notifySID).notifications.create(notificationOpts).then(binding => console.log(binding.sid))
.catch(error => console.log(error))
.done();

Create import-data.js and add your sms list into that:

module.exports = [
{binding_type: 'sms',address: '+44555555555'},
{binding_type: 'sms',address: '+440777777777'},
];
  • Go to terminal and run:
    node send_sms.js

It will queue all the messages at once and twilio will process the queue.

Leave a Reply

We'll try to resolve your queries asap.

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts

2