All Articles

Twilio Conversations - Receive Messages on Your Webhook

Published by Tony Vu on Jun 23, 2021

This article is part of the Twilio Conversations API series

In this article, you will learn how to receive a message sent by another Participant in a Conversation. At this point, you should have a Conversation created with two SMS Participants in it. One participant has a mobile number and the other Participant is you sending a message from a Twilio phone number.

The first thing you need to do is turn on webhook events when a new message arrives in a Conversation. You would just need to turn on the “onMessageAdded” webhook under the Conversations API Webhook config panel within your Twilio Console

Twilio Webhook Conversations

Then you will need to set up a URL to receive these webhook events from Twilio. To quickly get started, let’s setup a default Node.js project with the defaults

npm init -y

This should create a package.json and index.js file. Following that, let’s install express and some necessary packages for standing up a webhook URL

npm i express body-parser nodemon http

Add the start script to the “scripts” section of package.json

"start": "node index.js"

Next, you’re going to add this boilerplate code and a route for receiving webhooks. For now, we’re just going to do a quick test to ensure Twilio’s webhooks are coming through to our Node.js server.

const express = require("express");
const bodyParser = require("body-parser");
const http = require("http");
const app = express();
let port = process.env.PORT || 3001;
const server = http.createServer(app);

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: true }));

app.post("/conversations/webhook", (req, res) => {
  console.log(req.body);
});

server.listen(port, () => console.log(`Listening on port ${port}`));

This article is part of the Twilio Conversations API series

You should already have a Participant with a mobile phone number and a Twilio phone number participant added to a Conversation at this point. If not, check out previous articles to learn how to do this.

If you send a text message from your phone to the Twilio number you added as a Participant to the Conversation, you should see a JSON payload similar to the below come through on your webhook. I have put in dummy values for the unique identifiers for obvious reasons.

{
  "RetryCount": "0",
  "EventType": "onMessageAdded",
  "Attributes": "{}",
  "DateCreated": "2021-06-18T15:19:56.205Z",
  "Author": "+1XXXXXXXXXX",
  "Index": "9",
  "MessageSid": "IMXXXXXXXXXXX1XXXXXXXXXX",
  "ParticipantSid": "MBXXXXXXXXXXX1XXXXXXXXXX",
  "Body": "This is the text message from my phone",
  "AccountSid": "ACXXXXXXXXXXXX1XXXXXXXXXX",
  "Source": "SMS",
  "ConversationSid": "CHXXXXXXXXXXX1XXXXXXXXXX"
}

Interested in learning more about Twilio Conversations? Check out my upcoming eBook on Twilio Conversations and other articles.