Set Up IBM Watson
- Create an IBM Cloud account and log in.
- Navigate to the IBM Watson services dashboard.
- Create a new instance of Watson Assistant by selecting "Create Resource" and choose Watson Assistant under the AI section.
- Once the instance is created, navigate to the "Service Credentials" section to view the API key and URL.
Build a Watson Assistant Workspace
- Open Watson Assistant and create a new workspace for your Twilio integration.
- Define your intents, entities, and dialogue to train Watson on recognizing commands and responding appropriately.
- Test your setup locally using Watson Assistant's built-in testing tools.
Setting Up Twilio
- Create a Twilio account and log in to the Twilio Console.
- Purchase a phone number from which you will send and receive messages.
- Access your Twilio Dashboard to find your Account SID and Auth Token, which are required for authentication.
Set Up Your Local Development Environment
- Ensure you have Node.js and npm installed on your machine.
- Create a new directory for your project and initialize it using the following command:
npm init -y
- Install the Watson Developer Cloud and Twilio NPM packages using:
npm install watson-developer-cloud twilio
Write the Integration Code
- Create an `index.js` file and load the required packages and configuration.
const AssistantV1 = require('watson-developer-cloud/assistant/v1');
const twilio = require('twilio');
require('dotenv').config();
- Initialize Watson Assistant with your credentials:
const assistant = new AssistantV1({
iam_apikey: process.env.WATSON_API_KEY,
url: process.env.WATSON_URL,
version: '2019-02-28'
});
- Initialize Twilio with your credentials:
const client = twilio(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
- Write a function to handle incoming messages via Twilio, send to Watson, and respond:
const handleMessage = (incomingMessage) => {
assistant.message({
workspace_id: process.env.WATSON_WORKSPACE_ID,
input: { text: incomingMessage }
}, (err, response) => {
if (err) {
console.error(err);
} else {
const responseText = response.output.text[0];
client.messages.create({
body: responseText,
from: process.env.TWILIO_PHONE_NUMBER,
to: process.env.USER_PHONE_NUMBER
})
.then(message => console.log("Message sent: ", message.sid))
.catch(error => console.error(error));
}
});
};
Set Up Webhook on Twilio
- In the Twilio Console, navigate to your purchased phone number's settings.
- Under "Messaging", set the webhook URL to point to your server endpoint handling incoming messages.
- Ensure your server is accessible over the internet (for example, by using a service like ngrok during development).
Deploy and Test
- Start your application with:
node index.js
- Send a message to your Twilio number and ensure it correctly forwards to Watson and receives a response.
- Check logs for any errors and adjust your configuration or logic accordingly.