Push Twilio alerts to Slack Channel directly - twilio

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.

Related

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.

Twilio function to call external API - invalid Content-Type error code 12300

I have a twilio phone # that receives an SMS, which calls a Twilio protected function, which calls an external (Hologram.io) API. The call to the Twilio function succeeds, the call to Hologram.io succeeds, everything is working, but I always get this error and it's just really annoying. I do not get what is wrong.
Part of the body of the Twilio function:
Twilio developer evangelist here.
Your Function is called by Twilio when you receive an SMS, so the response of the Function is going back to Twilio to tell it what to do. You do so by returning TwiML. This means that if you return TwiML like this, you will get a message sent back from the Twilio number:
const twiml = new Twilio.twiml.MessagingResponse();
twiml.message("Hello from your function");
callback(null, twiml);
In your code, you are returning the result of your API call to Hologram straight to Twilio. Since that result is JSON instead of TwiML, Twilio doesn't know what to do with it and you get an error.
If you don't want to respond to the incoming text message, you can return empty TwiML, like this:
instance.post('/api/1/sms/incoming', {
// hologram data
})
.then((response) => {
const twiml = new Twilio.twiml.MessagingResponse();
callback(null, twiml);
});
Let me know if this helps.
You need to return TwiML to Twilio rather then JSON, reference:
TwiML™ for Programmable SMS

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