Twilio Forward SMS to email - Cannot find module 'got' - twilio

I'm new to Twilio. I'm attempting to forward an SMS to an email address using this tutorial:
https://www.twilio.com/blog/2017/07/forward-incoming-sms-messages-to-email-with-node-js-sendgrid-and-twilio-functions.html
I feel certain I've done everything it says to do, but I get an error 11200 HTTP retrieval failure every time, with these details:
{
"message": "Cannot find module 'got'",
"name": "Error",
"stack": "Error: Cannot find module 'got'\n at Function.Module._resolveFilename (module.js:547:15)\n at
Function.Module._load (module.js:474:25)\n at Module.require
(module.js:596:17)\n at Module.twilioRequire [as require]
(/var/task/node_modules/enigma-lambda/src/dependency.js:28:21)\n at
require (internal/module.js:11:18)\n at Object.
(/var/task/handlers/ZFa37cc3db9fd8db0501c2e5fc92137969.js:1:75)\n
at Module._compile (module.js:652:30)\n at
Object.Module._extensions..js (module.js:663:10)\n at Module.load
(module.js:565:32)\n at tryModuleLoad (module.js:505:12)" }
I've tried making absolutely sure I have the function written the same as the tutorial. I copied it directly from the github page to be sure. I'm not sure how to proceed in troubleshooting this, it seems it's telling me that 'got' isn't found but it's supposed to be available in Twilio functions. Any ideas? Thanks.
Edit: Here is the code:
const got = require('got');
exports.handler = function(context, event, callback) {
const requestBody = {
personalizations: [{ to: [{ email: context.TO_EMAIL_ADDRESS }] }],
from: { email: context.FROM_EMAIL_ADDRESS },
subject: `New SMS message from: ${event.From}`,
content: [
{
type: 'text/plain',
value: event.Body
}
]
};
got
.post('https://api.sendgrid.com/v3/mail/send', {
headers: {
Authorization: `Bearer ${context.SENDGRID_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
})
.then(response => {
let twiml = new Twilio.twiml.MessagingResponse();
callback(null, twiml);
})
.catch(err => {
callback(err);
});
};

After a little more research, I found some comments on GitHub that indicate 'got' is no longer included by default in the Twilio dependencies. Per the instructions there I went to the Runtime Functions Config section of the Twilio console and added got version 6.7.1 and now the original source code works!
I prefer Alex's solution however since it works "out of the box" and I'm keeping it as the accepted answer.

First, the above code with got works with my Twilio and SendGrid accounts, I just tested, I don't know why you're having trouble..., maybe try to create a Twilio subaccount and run from there.
Second, if you still can't get got to work, here is some code, you could try,
and I'we also tested and it works. It's using https instead:
const https = require('https');
exports.handler = function (context, event, callback) {
let postData = JSON.stringify({
personalizations: [{
to: [{
email: 'somebody#gmail.com'
}]
}],
from: {
email: 'somebody#gmail.com'
},
subject: `New SMS message from: ${event.From}`,
content: [{
type: 'text/plain',
value: event.Body
}]
});
let postOptions = {
host: 'api.sendgrid.com',
port: '443',
path: '/v3/mail/send',
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData),
}
};
let req = https.request(postOptions, function (res) {
// some code to handle the async response if needed
let twiml = new Twilio.twiml.MessagingResponse();
callback(null, twiml);
});
req.write(postData);
req.end();
};
Good luck!

I was able to get this to work by making sure that "got" is installed as a dependency under these settings here:
https://www.twilio.com/console/runtime/functions/configure
Functions Screenshot

Related

OAuth2 Discord 'unsupported_grant_type'

So, I was making a website and I needed Discord's OAuth2
However, this error keeps popping up for me:
data: { error: 'unsupported_grant_type' }
This here is my code:
function getToken(code) {
const data = new URLSearchParams({
client_id: 'ops',
client_secret: 'ops',
code: code,
grant_type: 'authorization_code',
redirect_uri: 'http://localhost:5500/callback',
scope: 'identify'
})
axios({
url: 'https://discord.com/api/oauth2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: data.toString()
}).then(response => {
return response.data
})
}
Just tried looking it up on the internet about. Since I was used to the old OAuth, I tried the old way. As I couldn't, I went after information in the Discord documentation. And I got this information.
However, without success.

Error 504 - Using Twilio Functions to Send Alerts to Slack

I'm using Twilio Functions as a webhook to send Slack messages anytime an error occurs. The error message is successfully sent to Slack. However, this triggers Error code 504 (runtime application timed out) in Twilio. From the Twilio documentation, it seems I'm not properly implementing the callback method. Is there something I'm missing?
const https = require("https");
// Make sure to declare SLACK_WEBHOOK_PATH in your Environment
// variables at
// https://www.twilio.com/console/runtime/functions/configure
exports.handler = function(context, event, callback) {
const { AccountSid } = event;
const message = `New error for Twilio Account ${AccountSid}.`
const slackBody = JSON.stringify({
channel: "#channel",
icon_emoji: ":test_tube:",
username: "Twilio Alert",
attachments: [{
fallback: "twilio alert",
color: "#d00000",
pretext: "",
text: message
}]
});
// Form our request specification
const options = {
host: "hooks.slack.com",
port: 443,
path: context.SLACK_WEBHOOK_PATH,
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": slackBody.length
}
};
// send the request
const post = https.request(options, res => {
// only respond once we're done, or Twilio's functions
// may kill our execution before we finish.
res.on("end", () => {
// respond with an empty message
return callback(null);
});
});
post.on('error', (e) => {
console.log(e);
});
post.write(slackBody);
post.end();
}

Tampermonkey GM_xmlhttpRequest not sending Request properly

I am trying to implement a tampermonkey script that triggers an API call to a Jira instance to create a ticket with some information found in the page I am on (on a different domain).
Here's what I've tried:
async function createJiraTicket() {
let elements = await obtainThingsForCreatingJiraTicket();
let createJiraTicketUrl = `https://${jiraDomain}/rest/api/latest/issue`;
let requestDataForCreation =`
{
"fields": {
"project": { "key": "${elements.project}" },
"summary": "${elements.title}",
"description": "nothing",
"issuetype": {"name": "Issue" }
}
}`;
GM_xmlhttpRequest ( {
method: "POST",
url: `${http}://${createJiraTicketUrl}`,
user: 'user:pwd', // also tried user:'user', password:'pwd',
data: requestDataForCreation,
header: 'Accept: application/json',
dataType: 'json',
contentType: 'application/json',
onload: function (response) {
jiraTicketLog(`[Ajax] Response from Ajax call Received: `);
}
} );
However, when I run createJiraTicket(), I am getting the following error:
Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
at <anonymous>:1:7
I have established the correct #connect tags on the script, so I am pretty blind on where the problem may be...
Can someone help?
Thanks
So I came up with the answer to fix it, apparently it was a number of different details:
So,
Authorization had to be included onto the headers, coded on base64 and keyworded "Basic".
User-Agent needs to be overriden on headers, with any dummy string.
overrideMimeType needed to be set to json.
That all made the trick.
This was the working code.
let createJiraTicketUrl = `//${jiraDomain}/rest/api/latest/issue`;
let authentication = btoa('admin:foobar1');
GM.xmlHttpRequest({
method: "POST",
headers: {
'Accept': 'application/json',
"Content-Type": "application/json",
"Authorization": `Basic ${authentication}`,
"User-Agent": "lolol"
},
url: `${http}:${createJiraTicketUrl}`,
data: JSON.stringify(requestDataForCreation),
dataType: 'json',
contentType: 'application/json',
overrideMimeType: 'application/json',
onload: function (response) {
let url = `${http}://${jiraDomain}/browse/${JSON.parse(response.response).key}`;
log(`${JSON.parse(response.response).key} ticket created: ${url}`);
openJiraTicket(url);
}

Twilio - Send email from function

Is there a way to send email from Twilio function? I understand that we can use sendgrid. I am looking a simpler solution.
Twilio evangelist here. 👋
As of now, you can use SendGrid from within a Twilio Function. The code below does the job for me and I just sent an email via a function
exports.handler = function(context, event, callback) {
const sgMail = require('#sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: 'sjudis#twilio.com',
from: 'test#example.com',
subject: 'Sending with SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
sgMail.send(msg)
.then(() => {
callback(null, 'Email sent...');
})
.catch((e) => {
console.log(e);
})
};
The above email will most like end up in spam as test#example.com is not a very trust worthy email address. If you want to send emails from your own domains additional configuration is needed.
To run the code inside of the function, you have to make sure to install the sendgrid/mail mail dependency and provide the sendgrid token in the function configuration.
If you want to use this function to power e.g. messages you have to make sure that your return valid TwiML. :) When you create a new function you will get examples showing on how to do that.
Hope that helps. :)
Another way is to use the SendGrid API
const got = require('got');
exports.handler = function(context, event, callback) {
const requestBody = {
personalizations: [{ to: [{ email: context.TO_EMAIL_ADDRESS }] }],
from: { email: context.FROM_EMAIL_ADDRESS },
subject: `New SMS message from: ${event.From}`,
content: [
{
type: 'text/plain',
value: event.Body
}
]
};
got.post('https://api.sendgrid.com/v3/mail/send', {
headers: {
Authorization: `Bearer ${context.SENDGRID_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
})
.then(response => {
let twiml = new Twilio.twiml.MessagingResponse();
callback(null, twiml);
})
.catch(err => {
callback(err);
});
};
};
Source: https://www.twilio.com/blog/2017/07/forward-incoming-sms-messages-to-email-with-node-js-sendgrid-and-twilio-functions.html

React Native fetch "unsupported BodyInit type"

I'm trying to send a POST request to the OneSignal REST API using fetch:
var obj = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
'app_id': '(API KEY)',
'contents': {"en": "English Message"},
'app_ids': ["APP IDS"],
'data': {'foo': 'bar'}
})
}
fetch('https://onesignal.com/api/v1/notifications', obj)
I know you're not really supposed to put your API key in client code, but this is just a test to see if it would work. Besides, the error I'm getting isn't a bad response from the server, it's:
Possible Unhandled Promise Rejection (id: 0):
unsupported BodyInit type
I've tried putting a catch method on the fetch, but it doesn't get called.
At a bit of a loss, not really sure how to proceed.
Thanks in advance!
Even I tried the same POST request for One-Signal REST API for creating notifications,the below worked for me fine.
const bodyObj = {
app_id: "**********",
included_segments: ["All"],
data: {"foo": "bar"},
contents: {"en": "Hi good morning"}
}
fetch('https://onesignal.com/api/v1/notifications',{
method:'POST',
headers:{
'Authorization':'Basic **********',
'Content-Type':'application/json'
},
body:JSON.stringify(bodyObj)
})
.then((response) => response.json())
.then((responseJson) => {
console.log("success api call");
})
.catch((error) => {
console.error(error);
});
Have you tried to change your json to the one below?
JSON.stringify({
app_id: '(API KEY)',
contents: {en: "English Message"},
app_ids: ["APP IDS"],
data: {foo: 'bar'}
})
Or even tried a simpler json?

Resources