Using Sendgrid with node.js attachments are empty / broken - javascript

Although I have verified that the file does exist and is accessible, the email that is sent attaches an empty file. I have tried 3 different ways to attach the file, all that return success from the send json response. The code I'm currently using is as follows. The rk object is simply a namespace.
console.log(call.recording);
var email = new rk.sendgrid.Email({
to: '4namlet#gmail.com',
from: rk.config.email_address,
subject: 'RoadKid Feedback',
text: 'Someone left feedback on your driver.'//,
//files: [
// {
// contentType: 'audio/mpeg',
// url: call.recording
// }
//]
});
email.addFile({
filename: 'feedback.mp3',
contentType: 'audio/mpeg',
url: call.recording
});
rk.sendgrid.send(email, function(err, json) {
if (err) { return console.error(err); }
console.log(json);
});
An example url value is:
http://api.twilio.com/2010-04-01/Accounts/AC4a36110ce12a9cd68a947c87a3a6ab36/Recordings/RE568ecf17e4960105cd131507d49e182f.mp3

Turns out Sendgrid was working fine. (thanks guys for the quick response!) It was a scoping issue. For some reason call.recording was getting clobbered or called weird or something. After the console log I added a:
var recording_url = call.recording;
and theeen...
url: recording_url
And it all worked. :-/

Related

How to make loop function using multiple input value to JSL in Groovy

I'm using the below function in Jenkins Shared Library.
/* The below function delete uploads that exist in the server. */
def delete_upload(server_url,each_upload_id,authentication){
def delete_upload_url = server_url + "/api/v1/uploads/" + each_upload_id
def response = httpRequest consoleLogResponseBody: true,
contentType: 'APPLICATION_JSON',
customHeaders: [[maskValue: false, name: 'id ', value: each_upload_id],
[maskValue: false, name: 'Authorization', value: authentication]],
httpMode: 'DELETE', ignoreSslErrors: true, responseHandle: 'NONE', url: delete_upload_url,
validResponseCodes: '100:599'
if(response.status == 202){
def result = readJSON text: """${response.content}"""
return result['message'].toString()
}
else {
throw new Exception("Incorrect upload id! Please give the correct upload id.")
}
}
====================================================================================================
I'm getting below response,
Response Code: HTTP/1.1 202 Accepted
Response:
{"code":202,"message":"Delete Job for file with id 2","type":"INFO"}
Success: Status code 202 is in the accepted range: 100:599
====================================================================================================
Purpose: I'm using the above JSL function to delete a uploads in the web server using upload id.
Requirement:
I need to delete multiple uploads by using multiple upload id's (like each_upload_id in 1,2,3 etc) using this JSL delete function.
Need to pass the upload id's in loops and delete the uploads in the web server.
Any suggestions, please ?
Are you looking for something like this?
def idList = ["1", "2", "3"]
try {
idList.each{ id =>
delete_upload(server_url,id,authentication)
}
} catch(e) {
println "Error occurred!"
}

How to setup greeting text or get_started in JavaScript

I am trying to develop a bot for FB Messenger and I'm always getting stuck with their documentation. Currently, I tried to add a Greeting Text and a Get_Started button in JavaScript, so I will be able to modify it easily. It seems like most of their documentation is in PHP or they just telling you to add it by sending a POST request using CURL, which worked for me, but again, it's not so modular.
I can't find proper documentation in JavaScript. and the only one is this:
https://www.techiediaries.com/build-messenger-bot-nodejs/
But I can't find the place where you actually call the greeting or get started functions.
there is also this https://github.com/fbsamples/original-coast-clothing
but I still can't find where they trigger the Greetings and the Get_Started postbacks. Only the json file where they store it /locales/en_US.json "profile".
My code currently has
// Accepts POST requests at /webhook endpoint
app.post('/webhook', (req, res) => {
// Parse the request body from the POST
let body = req.body;
// Check the webhook event is from a Page subscription
if (body.object === 'page') {
// Iterate over each entry - there may be multiple if batched
body.entry.forEach(function(entry) {
// Get the webhook event. entry.messaging is an array, but
// will only ever contain one event, so we get index 0
let webhook_event = entry.messaging[0];
console.log(webhook_event);
// Get the sender PSID
let sender_psid = webhook_event.sender.id;
console.log('Sender PSID: ' + sender_psid);
// Check if the event is a message or postback and
// pass the event to the appropriate handler function
if (webhook_event.message) {
handleMessage(sender_psid, webhook_event.message);
} else if (webhook_event.postback) {
handlePostback(sender_psid, webhook_event.postback);
}
});
// Return a '200 OK' response to all events
res.status(200).send('EVENT_RECEIVED');
} else {
// Return a '404 Not Found' if event is not from a page subscription
res.sendStatus(404);
}
});
function setupGreetingText(res){
var messageData = {
"greeting":[
{
"locale":"default",
"text":"Greeting text for default local !"
}, {
"locale":"en_US",
"text":"Greeting text for en_US local !"
}
]};
request({
"uri": "https://graph.facebook.com/v2.6/me/messages",
"qs": { "access_token": process.env.PAGE_ACCESS_TOKEN },
"method": 'POST',
"headers": {'Content-Type': 'application/json'},
"form": messageData
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
res.send(body);
} else {
// TODO: Handle errors
res.send(body);
}
});
}
but I still dont know how to trigger it.
Examples on the documentation look like this. This is how you break it down. Final result can be found below.
curl -X POST -H "Content-Type: application/json" -d '{
"get_started": {"payload": "<postback_payload>"}
}' "https://graph.facebook.com/v2.6/me/messenger_profile?access_token=<PAGE_ACCESS_TOKEN>"
Third word is the type of request you'll send and should be defined inside the method property.
Between the curly braces, is how the content inside the json property should be formatted.
The link on the last line is the link you should provide to the uri property minus the query part ?access_token=<PAGE_ACCESS_TOKEN>
SendAPI's uri is https://graph.facebook.com/v8.0/me/messages (you're using this)
MessengerProfileAPI's uri is https://graph.facebook.com/v2.6/me/messenger_profile (use this instead)
In the end, your request function should look something like this:
request(
{
"uri": "https://graph.facebook.com/v2.6/me/messenger_profile",
"qs": { "access_token": process.env.PAGE_ACCESS_TOKEN },
"method": "POST",
"json": {
"get_started": {"payload": "start"}
},
},
(err) => {
if (!err) {
console.log('request sent!');
} else {
console.error("Unable to send message:" + err);
}
}
);
Even though its been almost 3 months since this question has been asked. I hope this will still come useful.
Was struggling and frustrated as you trying to implement the examples on facebook for developers documentation but I finally got to understand it after some looking and observation at other developers webhook on github.

Node js http server accept POST and accept JSON

I am trying to create one Node js server with http package. I want to receive only POST request which I have already implemented it. The problem which I am facing is that I am not able to parse JSON correctly (I am expecting one JSON to be attached).
I tried using JSON.parse but that doesn't parse whole json content. It leaves some values as [Object] which is wrong. I saw few packages which is JSONStream but I am not sure how to implement in this case.
server.on('request', function(req, res){
if(req.method == 'POST')
{
var jsonString;
req.on('data', function (data) {
jsonString = JSON.parse(data);
});
req.on('end', function () {
serverNext(req, res, jsonString);
});
}
else
{
res.writeHead(405, {'Content-type':'application/json'});
res.write(JSON.stringify({error: "Method not allowed"}, 0, 4));
}
res.end();
});
Request example:
Here d = JSON file content. (I did this in Python to make this example request)
r = requests.post('http://localhost:9001', headers = {'content-type': 'application/json'}, data = json.dumps(d))
Note: I am able to parse JSON correctly but there are some cases when it shows something like this:
{ 'Heading':
{ 'Content':
{ sometext: 'value',
List: [Object], // Wrong
test: [Array] } } } // Wrong
Update:
Inside serverNext() I am getting few values like:
var testReq = Object.keys(jsonData)[0];
var testId = Object.keys(jsonData[testRequest])[0];
var test = jsonData[testRequest][testId]
Further if I keep on extracting values then at some point it encounters [Objects] value and get crashed.
I can reproduce this "problem" with data as { "Foo": {"Bar": {"Some data": [43, 32, 44]} } } -- it returns the following result: { Foo: { Bar: { 'Some data': [Object] } } }.
As OP mentioned in question, the JSON is parsed correctly, the reason why [Object] is displayed in result is: when JavaScript Object is returned to display, it would be converted to String first by toString() automatically, which will make all object (including array) as [Object] in text.
To display the real content, JSON.stringify() need to be invoked. In your case, the code would be:
req.on('end', function () {
serverNext(req, res, JSON.stringify(jsonString));
});
Please note it is better to rename variable jsonString as jsonObject.

Connect through url, testMe function gives error and no welcome message

I work on a domain management software through the OVH's API.
I use nodejs and node-webkit and I downloaded the official Node.js wrapper for OVH.
Then, I followed the documentation here: https://www.npmjs.com/package/ovh and here: https://eu.api.ovh.com/g934.first_step_with_api, and I came with the following code:
// set the ovh object with the right configuration
var ovh = require('ovh')({
endpoint: 'ovh-eu',
appKey: 'APP_KEY', // replace it with my key
appSecret: 'APP_SECRET' // replace it with my key
});
ovh.request('POST', '/auth/credential', {
// set access rules
'accessRules': [
{'method': 'GET', 'path': '/*'},
{'method': 'POST', 'path': '/*'},
{'method': 'PUT', 'path': '/*'},
{'method': 'DELETE', 'path': '/*'},
]
}, function (error, credential) {
// print the error if the request failed, else, print the response
console.log(error || credential);
// set the consumerKey in the ovh object
ovh.consumerKey = credential.consumerKey;
// connect on the credential.validationUrl to validate the consumerKey
console.log(credential.validationUrl);
testMe();
});
function testMe() {
/*
This fonction test a request every second
to check if the user connected himself
*/
ovh.requestPromised('GET', '/me')
.then (function (me) {
// if the user is connected, tell him welcome
console.log('Welcome ' + me.firstname);
}
)
.catch (function (err) {
console.log(err);
// while the user is not connected, retry the request
setTimeout(testMe, 1000);
}
);
}
Well, when I execute this, everything is fine until I try to connect through the url, the testMe function keeps telling me an error and I don't get the welcome message.
In order to fix my problem, I tried to use different way to write my code and even checked in OVH's module sources if the signature was right before and after hashing, but it all seems to be good...
If someone already had this issue or if anybody see a error in my code, I would really appreciate your help. Thanks
you've got a syntax error :
then (function (response) {
// if the user is connected, tell him welcome
console.log('Welcome ' + me.firstname);
})
try this instead (renamed the parameter):
then (function (me) {
// if the user is connected, tell him welcome
console.log('Welcome ' + me.firstname);
})
Anyway, it it doesn't work properly please tell us the error you are getting.

jquery.couchdb.js Ajax success/error not being called

I'm using jquery.couchdb.js to query my CouchDB database. The view I want to query has both map and reduce functions within. When sending the basic query as shown below:
$(document).ready(function() {
view_name = db_name+'/jobs_by_mod_stat'
options = {'group': 'true' , 'reduce': 'true' };
mod_stat = {};
$db.view(view_name , {
success: function(data) {
console.log(data)
for (i in data.rows) {
console.log(data.rows[i].value);
}
},
error: function(e) {
alert('Error loading from database: ' + e);
}
});
});
I see a sensible log for the data, indicating the query has been successful. However, changing the line:
$db.view(view_name , {
To
$db.view(view_name , options, {
I don't get a success outcome from the Ajax query, but an error message is not shown either. Firebug shows the query being sent, and the JSON data returned looks sensible:
{"rows":[
{"key":["template","completed"],"value":2},
{"key":["template","running"],"value":2},
{"key":["template","waiting"],"value":6}
]}
But the success function is not entered. Any ideas why I'm seeing this behaviour, I did wonder if it's a bug in jquery.couch.js (I have couchdb 1.1.0).
Cheers.
I've had a bit of trouble myself with the list function, until I went and looked through the source code of jquery.couch.js (the online documentation I found at http://bradley-holt.com/2011/07/couchdb-jquery-plugin-reference/ seems to be outdated).
Basically, the parameters for view and list are different, the list having an extra parameter for the options, instead of having everything under the same parameter as with views.
View:
$.couch.db('yourdb').view('couchapp/' + viewName, {
keys: ['keys here'],
success: function (data) {
}
});
List:
$.couch.db('yourdb').list('couchapp/' + listName, viewName, {
keys: ['keys here']
}, {
success: function (data) {
}
});

Categories