Why can't I programmatically send a templated WhatsApp message using Twilio? - twilio

My code:
const client = require('twilio')(accountSid, authToken);
const issueResolution = 'Hi Malcolm, were we able to solve the issue that you were facing?';
client.messages
.create({
from: senderNumber,
body: issueResolution,
to: receiverNumber,
})
.then(message => {
console.log(JSON.stringify(message , null, 2));
});
The body of the message conforms to the "sample_issue_resolution" WhatsApp template shown in the Twilio web console (at https://console.twilio.com/us1/develop/sms/senders/whatsapp-templates).
I can successfully use the above code to send a message to a number which has opted in to my Twilio WhatsApp sandbox. If I try to send a message to another number which has not opted in to the sandbox, there's no error message, but the message is never received. I get the same results when I use one of my custom approved templates. What could be going wrong / how can I debug this?

I'd assume that this message is not matching any of your templates. There could be multiple reasons, such as a different whitespace character or a typo that differentiates both strings.
The Message Log should tell you why a message couldn't be delivered.

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.

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!!

Twilio SMS sending

await client.messages.create(
{
to: `+${userEntity.telephoneNumber}`,
from: `+${process.env.TWILIO_NUMBER}`,
body: `Your activation code is ${userEntity.activationCode}`,
},
(err, message) => {
if (err) {
throw err
} else {
return this._res.status(200).json({message: message}).end()
}
}
);
Error: The number +xxxxxxx is unverified. Trial accounts cannot send messages to unverified numbers; verify +xxxxxxx at twilio.com/user/account/phone-numbers/verified, or purchase a Twilio number to send messages to unverified numbers.
Hi everyone. I was trying to send a message from Twilio to the user but I've got this error.Who can help me? Maybe I don't understand how does it work. Should I add a number to which I want to send a message to Twilio? Or what does this message mean?
Yes that is exactly what it means, you have to verify the number you want to send your message to. The verification is done by either a call or a text.
Twilio - Verify Phone number
This will also allow you to use this number as a caller id when making a call(does not work with texting).
This is a somewhat common limitation setup for trial accounts.

Is there any way to get messages we send/received by using phone number in twilio?

I would like to make my client to check whether end client is received text or not and what reply he/she has sent? I always going through twilio to see whether client received sms or not? Is there any way to check it from twilio?
Twilio developer evangelist here.
You can get both incoming messages to your Twilio numbers and reports on the status of messages after you send them from Twilio using webhooks.
When you send a message you can include a StatusCallback parameter. The parameter should be a URL in your application.
$client->messages
->create(
$to,
array(
"from" => $from,
"body" => "Let's grab lunch at Milliways tomorrow!",
"statusCallback" => "https://example.com/messageStatus"
)
);
Twilio will send a POST request to the statusCallback URL each time your message status changes to one of the following: queued, failed, sent, delivered, or undelivered. It will include the original message's SID, so you can tie these webhooks back to the message you sent.
Similarly, you can get these webhook notifications for incoming messages to your Twilio numbers. For this you need to set up the incoming webhook URL to the number in your Twilio console. Set it to a URL in your application and you will receive a webhook when someone sends a message to your Twilio number. Check out this quickstart guide on receiving messages to your Twilio number with PHP.
Let me know if that helps at all.
[edit]
Thanks for the comment where you made it clear that this is after the fact, not at the time of sending.
In this case, you can absolutely list the messages by the phone number that sent them. A message resource includes a Status attribute that lists the current message state in the Twilio system, anything from "accepted" and "queued" to "sending", "sent", "delivered", "undelivered" and "failed". You can see more about these statuses in the documentation.
To get the list of messages sent from a number you can use the following code:
use Twilio\Rest\Client;
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$token = "your_auth_token";
$client = new Client($sid, $token);
// Loop over the list of messages and echo a property for each one
foreach ($client->messages->read(array("from" => $FROM_NUMBER) as $message) {
echo $message->status . " - " . $message->to . " = " . $message->body;
}
You can pull data for specific messages https://www.twilio.com/docs/api/messaging/message#delivery-related-errors
or you can simply pull all the logs

Re-send a Twilio SMS Message

I store sent messages in a log table with their unique SIDs. With a periodic console task I iterate over the records having status = undelivered and request the status of it and if it's still undelivered, I'd like to re-send that very message. I don't want a new one as the message contains a verification code and we store only hash of it. Is it possible to re-send the old message having its SID?
Twilio Developer Evangelist here,
There is not a way to automatically resend an undelivered message using the API. You can work around this by grabbing the messages by SID and sending the undelivered ones again to the same number with the same body. When you use the REST API to get a message by SID, you have access to all of the data from that message, including the exact message body.
A quick example using the Twilio PHP Library would look like this:
<?php
$client = new Services_Twilio($AccountSid, $AuthToken);
$messageSIDs = array("Insert", "Array of", "Message SIDs", "here");
foreach ($messageSIDs as $sid) {
$msg = $client->account->messages->get($sid);
if ($msg->status == "undelivered") {
echo "Resending undelivered message for SID: $sid\n";
$sms = $client->account->messages->sendMessage(
// The number we are sending from.
$msg->from,
// The number we are sending to.
$msg->to,
// The sms body.
$msg->body
);
}
}
You can see all of the data that the REST API gives you about messages here

Resources