CarlosVldz | Product Eng & Web Dev

CarlosVldz | Product Eng & Web Dev

How can you send automated messages via WhatsApp with Node.Js

How can you send automated messages via WhatsApp with Node.Js

How you can use Node.js to send messages via WhatsApp with Twilio's API.

First, here the things that you need:

  • Node and npm installed
  • Create an account with Twilio (it's free)
  • And finally, Twilio and dotenv library

Once you sign up for the Twilio account, activate the Sandbox for Whatsapp. This enable you a shared phone number and allows you to test with WhatsApp service.

Then you have to opt in sending a message to the phone number provided from the sandbox. The message should say "join mass-there", if everything is ok you will receive a confirmation response.


Now let's start with Node.js

Once you are in the directory where is created the project, in the terminal run the following commands:

npm init -y
npm install twilio@3.30.0 dotenv

The first one to iniciate a package.json and the second one for install the dependencies.

The next step is create the file index.js with the following code:

const { config } = require('./config');

const accountSid = config.sid;
const authToken = config.token;
const client = require('twilio') (accountSid, authToken);

    from: 'whatsapp:+14155238886',
    body: 'Hello world this is CarlosVldz!!!',
    to: 'whatsapp:+5215555555555'
}).then(message => console.log(message.sid));

(Don't forget replace the phone numbers in this example with your sandbox number and a personal number.)

Finally I used dotenv to configure the environment variables TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN with their values from the account credentials. You can find both in your Twilio console.


TWILIO_ACCOUNT_SID = "Your account sid"

TWILIO_AUTH_TOKEN = "Your auth token"

In your terminal run this last command to send the WhatsApp message:

node index.js

In your phone check WhatsApp and you should have a new chat like this.

Image (1).jpeg

Hope you liked! (:

Share this