Twilio modify sms message before forwarding using TWIML - twilio

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.

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.

Twilio conversation with chatbot

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!

Twilio forward incoming calls based on the incoming phone number

I recently ported my home landline number to Twilio. For now, I created a very basic call forwarding TwiML Bin to forward any incoming calls to this former landline number to my cell phone:
<Response>
<Dial>mycellnumber</Dial>
</Response>
What I'd like to do is have some logic to forward incoming calls to a different cell based on the incoming caller matching a number in a contact list, and default forwarding if the incoming number is not on a contact list.
For example, if the incoming call is from a number on the contact list for Cell-X then forward the call to Cell-X, else if on the contact list for Cell-Y forward to Cell-Y, else maybe go to cloud voice mail or another number.
Is there a way to do something like this as a TwiML Bin or in the Studio or is it too complicated? Maybe TaskRouter? This is residential so I'd like it to be invisible to the caller as opposed to something like an IVR solution where the caller is prompted to press a number for the person they want to reach.
I've not had any luck finding a call forwarding solution with logic like this by looking through the Twilio docs or by searching for examples. Please help!
You could do this with a Twilio function.
Let's say that your Cell-X list looks something like this:
const cellXContactList = ["+17782001001", "+17782001002", "+17782001003"];
and your Cell-Y list looks something like this:
const cellYContactList = ["+17782001004", "+17782001005", "+17782001006"];
then you could distribute incoming calls with something like this:
if (cellXContactList.length && cellXContactList.indexOf(event.From) !== -1) {
// caller number found in Cell-X contact list
destinationPhoneNumber = "+17781001001";
} else if (cellYContactList.length && cellYContactList.indexOf(event.From) !== -1) {
// caller number found in Cell-Y contact list
destinationPhoneNumber = "+17781001002";
}
Below is the entire code for the function (replace with your phone numbers):
// forward calls based on the incoming phone number
exports.handler = function (context, event, callback) {
// reference the Twilio helper library
const twiml = new Twilio.twiml.VoiceResponse();
// contacts lists
const cellXContactList = ["+17782001001", "+17782001002", "+17782001003"];
const cellYContactList = ["+17782001004", "+17782001005", "+17782001006"];
// if not in any contact list forward to this number
let destinationPhoneNumber = "+17781001000";
if (cellXContactList.length && cellXContactList.indexOf(event.From) !== -1) {
// caller number found in Cell-X contact list
destinationPhoneNumber = "+17781001001";
} else if (cellYContactList.length && cellYContactList.indexOf(event.From) !== -1) {
// caller number found in Cell-Y contact list
destinationPhoneNumber = "+17781001002";
}
twiml.dial({}, destinationPhoneNumber);
// return the TwiML
callback(null, twiml);
};
You can create Twilio functions in your Twilio console at (https://www.twilio.com/console/functions/manage). Start with a "Blank" functions template, then replace with the code above.
Once you've created and published your function, you can configure your Twilio number to run it when "A CALL COMES IN" (https://www.twilio.com/console/phone-numbers/incoming).

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.

Resources