DEV Community

Cover image for How can you send automated messages via WhatsApp with Node.js
Carlos Sánchez
Carlos Sánchez

Posted on

 

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.

Alt Text

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
Enter fullscreen mode Exit fullscreen mode
npm install twilio@3.30.0 dotenv
Enter fullscreen mode Exit fullscreen mode

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);

client.messages.create({
    from: 'whatsapp:+14155238886',
    body: 'Hello world this is CarlosVldz!!!',
    to: 'whatsapp:+5215555555555'
}).then(message => console.log(message.sid));
Enter fullscreen mode Exit fullscreen mode

(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.

.env.example

TWILIO_ACCOUNT_SID = "Your account sid"

TWILIO_AUTH_TOKEN = "Your auth token"
Enter fullscreen mode Exit fullscreen mode

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

node index.js
Enter fullscreen mode Exit fullscreen mode

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

Alt Text

Hope you liked! (:

Top comments (1)

Collapse
 
sonai95 profile image
Suvadeep Majumdar

Whenever I try to message somebody who has not joined sandbox, it throws error. Is there a way to bypass this?

Regex for lazy developers

regex for lazy devs

You know who you are. Sorry for the callout 😆