Twilio conversation with chatbot - twilio

I want to know how to use twilio conversation api with autopilot chatbot.
So users start to chat with bot and after answering some questions of bot, the users are hand off to real agent and continue to chat with them.
I've already made the conversation using twilio conversation api and chatbot using autopilot.
Now I want to know how to integrate them.

Twilio developer evangelist here.
Twilio Autopilot doesn't have conversations as a supported channel, only programmable chat. For most of these uses cases, I would suggest using Autopilot + Studio + Flex--then you can build just about anything!
The following workaround is from Twilio Supportability Engineer Adam Taylor:
To create an Autopilot Studio Flow once the Autopilot session ends (i.e. a task is hit without a listen), you can handoff to another widget. You can add a "sendToAgent" indicator in Autopilot's Memory and then use the "Split Based On" widget to check for this indicator, only handing off when appropriate.
Then an example Autopilot Goodbye Task might look like
{
"actions": [
{
"say": "Great. Please reach out again if you have any questions. I'm sending you to an agent to finish up."
},
{
"remember": {
"sendToAgent": true
}
}
]
}
Find your Studio flow SID in the Studio console
To use Conversations, make sure you have an updated version of Twilio for your Functions!
Then your Function's JS code might look something like
exports.handler = function(context, event, callback) {
const client = context.getTwilioClient();
const conversationSid = event.ConversationSid;
client.conversations
.conversations(conversationSid)
.webhooks.create({
"configuration.flowSid": "FWxxxxxxxxxxxxxxxx", //update your flow sid here
"configuration.replayAfter": 0,
target: "studio"
})
.then(webhook => {
let responseObject = { "conversationSid": conversationSid, "webhookSid": webhook.sid };
callback(null, responseObject);
})
.catch(err => {
callback(error);
});
};
Paste that Function URL here to configure Conversations Webhook as the Post-Event URL for Conversations. Select "onConversationAdded" as the Post-Webhook that this url will receive.
Configure Conversations for SMS by making sure that the "Handle Inbound Messages with Conversations" Messaging Feature is enabled for your Account here.
Create a Messaging Service for your Autopilot Studio Flow here to associate the phone number for your Autopilot bot to this messaging service.
Update Integration Settings so that a new conversation is created when a message arrives at this phone number
Create a Function to remove Studio from a conversation. Make a Function that contains code like this:
exports.handler = function(context, event, callback) {
const client = context.getTwilioClient();
const conversationSid = event.ConversationSid;
const webhookSid = event.WebhookSid;
client.conversations
.conversations(conversationSid)
.webhooks(webhookSid)
.remove()
.then(()=> {
let responseObject = { "conversationSid": conversationSid, "webhookSid": webhookSid };
callback(null, responseObject);
})
.catch(err => {
callback(error);
});
};
and another Function to add a participant to the Conversation
exports.handler = function(context, event, callback) {
const client = context.getTwilioClient();
const conversationSid = event.ConversationSid;
const handoffTo = event.HandoffTo;
client.conversations
.conversations(conversationSid)
.participants
.create({
'messagingBinding.address': handoffTo, // the phone number or whatsapp address you want to handoff messaging conversation to
'messagingBinding.proxyAddress': '+14156632326' // the phone number attached to your messaging service
})
.then(participant => {
let responseObject = { "participantSid": participant.sid, "conversationSid": conversationSid };
callback(null, responseObject);
})
.catch(err => {
callback(error);
});
};
Finally, add Studio Widgets to run these Functions and complete the Handoff.
The first widget is RunFunction - removeStudioWebhook
Function Parameters include ConversationSid: {{trigger.message.ConversationSid}} and WebhookSid: {{trigger.message.WebhookSid}}
The second widget is RunFunction - addToConversation
Function Parameters include ConversationSid:{{trigger.message.ConversationSid}} and WebhookSid: +15555551212 (the number you want to handoff to)
The third one sends the message
Widget Configuration:
MessageBody: Customer {{contact.channel.address}} is connected with Agent Adam. (replace with your Agent Name) and
Send Message To: +15555551213 (replace with the number you want to handoff to).
The Conversations API description says "Basic auto-response and chatbot functionality" as some of the automated features" which means you can build your own chatbot with the help of the Conversations APIs.
Let me know if this helps at all!

Related

Push Twilio alerts to Slack Channel directly

I am not sure that there is way but can I send Twilio alerts from Twilio Console to Slack channel directly without using Python or any web framework that will listen to Twilio requests and send the data to Slack channel?
Using Twilio console, I can trigger a webhook from there once there is a new error but the Slack requires a data in the API.
Thank you
Twilio developer evangelist here.
It looks as though Slack expects webhooks to be in JSON format in a particular format, in the simplest form an object with a text property.
Twilio webhooks are sent in application/x-www-form-urlencoded format with the parameters listed here.
In order to turn this into a webhook that Slack will understand you will need some code or service that will translate the form encoded request into a JSON request with the right fields.
It seems you are reticent to build and host something yourself. If the hosting is the problem, can I suggest you look into Twilio Functions to build this. Twilio Functions lets you host JavaScript functions that can respond to incoming HTTP requests.
An example of a Twilio Function that could translate these alert webhooks into a Slack webhook might look like this:
const got = require('got');
exports.handler = async function (context, event, callback) {
const slackUrl = context.SLACK_URL;
const { ErrorCode, Description, AccountSid } = event;
const message = `New error for Twilio Account ${AccountSid}.\n\n${ErrorCode}: ${Description}`
try {
await got(slackUrl, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ text: message })
})
callback(null, "<Response/>");
} catch(error) {
callback(error);
}
}
The above code is untested, but should give you a good a start. It uses got to make the HTTP request to the Slack webhook URL. In this case, the webhook URL is stored in an environment variable.

WhatsAPP - MS Teams integration via Twilio

I would like to integrate WhatsApp business to MS Teams. When I send a message via WhatsApp it is received in Twilio. I set webhook in Teams and in Twilio also, but Twilio can't forward the message to the Teams.
The Twilio give me a
11200 ERROR There was a failure attempting to retrieve the contents of this URL.
I checked the response of Teams and I found this in the body:
"Bad payload received by generic incoming webhook."
I tested the webhook via curl and I received the text in channel of Teams.
Twilio developer evangelist here.
From the MS Teams documentation (emphasis mine):
If Incoming Webhooks are enabled for a team in any channel, it exposes the HTTPS endpoint, which accepts correctly formatted JSON and inserts the messages into that channel.
Twilio webhooks are sent in the format application/x-www-form-urlencoded, so you will need something in the middle to reformat the Twilio webhook into a format that MS Teams can ingest.
From a quick search, it's a bit difficult to find a reference for what JSON that MS Teams actually expects. This page has some examples.
To do the reformatting, you could use a Twilio Function. Code like this might well work for a basic text message into Teams:
const got = require("got");
exports.handler = async function (context, event, callback) {
const teamsWebhookUrl = context.TEAMS_WEBHOOK_URL;
const teamsPayload = {
text: event.Body
};
try {
await got(teamsWebhookUrl, {
method: "POST",
body: JSON.stringify(teamsPayload),
headers: {
"Content-Type": "application/json"
}
);
const response = new Twilio.twiml.MessagingResponse();
callback(null, response);
} catch(error) {
callback(error);
}
}
This is untested, but the idea is that it builds a simple text message using the JSON from this curl example and send it to the Teams webhook URL using got. If there is a successful response from Teams then an empty response is sent back to the original Twilio webhook. If there is an error, then that error is logged in the Twilio debugger.
To use this code you will need to install got in the dependencies and add the Teams webhook URL in the environment variables.

Can I generate a Twilio SMS when a new email is received (email -> SMS)?

I am trying to generate an SMS from Twilio when I receive a new email in my Gmail.
I need to find a way to forward the email to another email address and have that generate the call to Twilio to send the SMS.
Here is a thought!
You could setup an webhook that will post your email data using one of these services:
Services That Cost:
Either
https://automate.io/integration/gmail/webhooks
The Widget you would want to use.
OR
https://zapier.com/apps/gmail/integrations/webhook
Free Service:
This is a bit of a hack, but it is free as far as I can tell:
Forward all Emails To A Slack Channel: https://slack.com/help/articles/206819278-send-emails-to-slack
Create a slack app that listens for new messages, and when it recieves a message, send a post request to a Twilio Function... Instructions below.... Link to slack app building: https://api.slack.com/start/building
THEN: you would post the data to a twilio function that takes the data and sends and SMS with it. the basic started application to send a message in a twilio function looks like this:
exports.handler = function(context, event, callback) {
let twiml = new Twilio.twiml.MessagingResponse();
twiml.message("Hello World");
callback(null, twiml);
};
the event parameter will contain any data that you post to it. as this twilio doc shows:
Here is the twilio documentation for 'function' data posting
if your event looks like this: {"message-content": "Hey Jim I just wanted to send you this fantastic email over the holidays"}, all you would then need to do is as follows:
exports.handler = function(context, event, callback) {
context.getTwilioClient().messages.create({
to: '<ENTER YOUR PHONE NUMBER HERE>',
from: '<ENTER ONE OF YOUR TWILIO PHONE NUMBERS WITH SMS CAPABILITIES>',
body: event.message-content
}).then(msg => {
callback(null, msg.sid);
}).catch(err => callback(err));
};
If you have any questions or get stuck along the way, use this twilio doc to help you: https://www.twilio.com/docs/runtime/quickstart/programmable-sms-functions
Cheers!!

How to integrate audio call(User to User) using twilio API?

I want to integrate user to user audio call feature using Twilio API, is it possible in Twilio? if yes can you please provide a tutorial.
Here I have added the code:
1. For get token from the Twilio
$.post(url, function(data) {
// Set up the Twilio Client Device with the token
Twilio.Device.setup(data.token);
});
and it returns the token using function
public function newToken(Request $request, ClientToken $clientToken)
{
$forPage = $request->input('forPage');
$twilio = config('services.twilio');
$applicationSid = $twilio['applicationSid'];
$clientToken->allowClientOutgoing($applicationSid);
if ($forPage === route('dashboard', [], false)) {
$clientToken->allowClientIncoming('support_agent');
} else {
$clientToken->allowClientIncoming('customer');
}
$token = $clientToken->generateToken();
return response()->json(['token' => $token]);
}
When I make a call following javascript function start
function callCustomer(phoneNumber) {
updateCallStatus("Calling " + phoneNumber + "...");
var params = {"phoneNumber": phoneNumber};
Twilio.Device.connect(params);
}
and then browser ask for the enable microphone and after allowing it plays the small audio say's that "Application error occurred, Good bye!".
Twilio voice call please refer the following documentation step by step
QuickStartDemo
Twilio developer evangelist here.
The TwiML connects the outgoing call to the other user. When you set up the TwiML Application for outgoing calls you need to set a voice URL. When you make the call using Twilio.Device.connect then Twilio Client will connect to Twilio, Twilio will then make an HTTP request to the voice URL of your TwiML app, passing along the parameters that you send, to find out what to do with the call.
You are passing in a phoneNumber parameter, so that will be passed to your application. You've tagged this question with PHP, so here's an example (using the Twilio PHP library) of what you could do to dial onto the phone number that you are passing.
<?php
require_once './vendor/autoload.php';
use Twilio\Twiml;
$phoneNumber = $_REQUEST['phoneNumber'];
$response = new Twiml();
$dial = $response->dial();
$dial->number($phoneNumber);
echo $response;
Check out the documentation on Twilio Client for more details on how this works.

Twilio modify sms message before forwarding using TWIML

Trying to modify a SMS message (adding a name based on the from phone number) before forwarding the message to a phone using TWIML. The phone no list is small so I will use a switch statement I am guessing in a function. I am not sure how can I wire this together w/o my own server and just using Twilio hosted stuff (TWIML, function, ?)?
Twilio developer evangelist here.
You can absolutely modify the message before forwarding it on.
If you're looking to do so without using your own server, then Twilio Functions is your best bet. Twilio Functions gives you access to a Node.js environment in which you can write functions that respond to webhooks.
To forward a message to a number but add a name based on the incoming number, you can do something like this in a function:
contacts = {
"number": "name"
}
exports.handler = function(context, event, callback) {
const name = contacts[event.From];
if (typeof name !== 'undefined') {
const message = `${name} said: ${event.Body}`;
const response = new Twilio.twiml.MessagingResponse();
response.Message({ to: YOUR_NUMBER, from: YOUR_TWILIO_NUMBER }, message);
callback(null, response);
} else {
// handle not having a name in the contacts
}
}
Check out this quick start on using Twilio Functions for more detail.

Resources