Search code examples
javascriptnode.jstwiliotwilio-apitwilio-conversations

How to send a message in a Twilio Conversation


How do you send a new message to a Twilio Conversation in node.js?

I found this sample code from Twilio, but I don't know how to get messagingServiceSid for my Conversation.

// Download the helper library from https://www.twilio.com/docs/node/install
// Your Account Sid and Auth Token from twilio.com/console
// and set the environment variables. See http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);

client.messages
  .create({
     body: 'Revenge of the Sith was clearly the best of the prequel trilogy.',
     messagingServiceSid: 'MG9752274e9e519418a7406176694466fa',
     to: '+441632960675'
   })
  .then(message => console.log(message.sid));

Solution

  • Separate answer for the Conversations API:

    First create a conversation and note down the conversation SID (starts with CH, here outputted with console.log(conversation.sid)):

    const accountSid = process.env.TWILIO_ACCOUNT_SID;
    const authToken = process.env.TWILIO_AUTH_TOKEN;
    const client = require('twilio')(accountSid, authToken);
    
    client.conversations.conversations
                        .create({friendlyName: 'My First Conversation'})
                        .then(conversation => console.log(conversation.sid));
    

    Then add an SMS participant to a Conversation (this is where you need your SMS-enabled Twilio number and the recipient number).

    Now you can use the Conversation Message Resource to create messages which will be received by all participants of the conversation.