Add Icon to Onesignal push notification using NodeJS Rest API - node.js

I wanted to add icon in push notification from rest API. I am using NodeJS as my backend. I have already tried options mention in following code :
let message = {
app_id: process.env.ONE_SIGNAL_APP_ID,
headings: { "en": "MyAPP" },
contents: { "en": "Hello" },
large_icon: data.picture ? process.env.ONE_SIGNAL_IMAGE_URL + data.picture : "",
include_player_ids: ["playerId"]
};
let headers = {
"Content-Type": "application/json; charset=utf-8",
"Authorization": process.env.ONE_SIGNAL_AUTHORIZATION
};
let options = {
host: "onesignal.com",
port: 443,
path: "/api/v1/notifications",
method: "POST",
headers: headers
};
let req = https.request(options, function (res) {
res.on('data', function (message) {
// console.log(JSON.parse(message));
});
});
req.on('error', function (e) {
// console.log(e);
});
req.write(JSON.stringify(message));
req.end();
I have putted correct image URL which is "https://mydomain/icons/Icon_kitchen.png" and if I hit this URL in browser I get image, too.
I have also tried samll_icon option but not succeed. I am not able to figure out the problem. Kindly help me out. Thanks in advance.

Related

How to save https response to variable and use for another function?

I would like to save nodejs https response for global variable and use it later. I know it is assync function but I'm not fully understand therefore I can not implement it. I would thanksfull if somebody can help me out and show me how to make it work.
The code:
function getPageContent() {
const postData = `some data`;
const options = {
protocol: 'https:',
host: 'sitepage',
path: "/path",
method: 'POST',
headers: {
"Authorization": "Bearer " + 'apikey'
}
};
const req = https.request(options, (res) => {
console.log('getPageContent statusCode:', res.statusCode);
res.on('data', (d) => {
answer += d;
return answer => This is what I would like to save.
});
});
req.write(postData);
req.end();
};
getPageContent()
console.log(answer)
As an answer of console log I would like to see the https answer but with my code it is blank.

Node-Red sending the file in http-request node is not working

I am trying to send the file with the http-request node but it is not working.
Please find the following image of Node-red flow.
In the Request Body node I have added the following code.
const inputFile = msg.payload;
const dataJson =
{
'name': 'testName',
'description':'testdescription',
'inputfile': inputFile
};
msg.payload = dataJson;
msg.url = 'myAPIurl';
msg.headers = {
'authorization': 'Bearer TOKEN Here',
'cookie': 'Cookie here',
'content-type': 'multipart/form-data;'
};
return msg;
This is giving bad request error.
In the Read File node I tried choosing both options A single UTF8-String and a single Buffer Object still I got the same error
But I tried to call the API inside function node using the request module. It is giving the proper response.
const request = global.get("request");
const fs = global.get("fs");
const url = 'API';
const tkn = 'TOken Here';
const cookie = 'cookie here';
const fl = fs.createReadStream('/tmp/node-red/app/data/filename.txt');
var options = {
method: 'POST',
url: url,
headers: {
'Authorization': tkn,
'Cookie': cookie,
},
formData: {
"name": "test121",
"description": "",
inputfile: fl
}
};
request(options, function (err, resp, body) {
console.log(body);
});
return msg;
I am not sure where I am making the mistake if I use http-request node.
From the sidebar docs for the http-request node:
File Upload
To perform a file upload, msg.headers["content-type"] should be set
to multipart/form-data and the msg.payload passed to the node must
be an object with the following structure:
{
"KEY": {
"value": FILE_CONTENTS,
"options": {
"filename": "FILENAME"
}
}
}
The values of KEY, FILE_CONTENTS and FILENAME should be set to the
appropriate values.
Following this doc, your msg.payload is wrong, it should look something like:
msg.payload: {
"name": "testName",
"description": "description",
"inputfile": {
"value": inputfile,
"options": {
"filename": "filename.txt"
}
}
}

CircleCI API + Lambda - triggering a build

I cannot get Lambda to trigger a build/deploy in CircleCI.
How can I convert a curl command to an HTTP request in Lambda?
curl command that works in Postman:
https://circleci.com/api/v1.1/project/:vcs-type/:username/:project/tree/:branch?circle-token=:my-token
content-type: app/json
body:
{
"build_parameters": {
"CIRCLE_JOB": "deploy_docker"
}
}
My appropriate creds are in place and it works great from Postman.
Assuming everything is correct in postman, how would I transfer that to Lambda?
Currently:
var buttonClicked = slackJSON.actions[0].name
const postOptions = {
host: 'api.circleci.com',
path:'/api/v1.1/projects/github/joha0033/scyte-bot-cid/tree/dev?circle-token=:'+ process.env.CIRCLE_TOKEN,
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
build_parameters: {CIRCLE_JOB: "deploy-docker"},
revisions: 'a511d5fcc4ebb09e50239a3f025807860f2a5e2d',
};
const deployInfo = () => {
const deployData = {
build_parameters: {
CIRCLE_JOB: 'deploy_docker'
}
}
return JSON.stringify(deployData)
}
const postHandler = () => {
console.log('postHandler')
const postReq = https.request(postOptions, function(res){
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log('Response: >--> ' + chunk);
});
})
postReq.write(deployInfo())
postReq.end()
}
callback(null, postHandler())
Is this even possible?
I'm getting this as a response:
Response: >--> Oops, no such page.
Or can I create something somewhere in AWS that will trigger a curl command via api POST request?
Postman is sending to project and your code sends it to projects - that might be the problem

HTTP Post request not going through in AWS Lambda

I am trying to add an item to my Todoist project through an Alexa skill in AWS Lambda. I am very new to all of these technologies so forgive me if the fix is incredibly obvious. When I ask Alexa to invoke my addZipcode skill, it fails. This is what I have (excluding some stuff that is in all Alexa Lambda functions):
Alexa stuff
...
const handlers = {
'LaunchRequest': function() {
this.emit('AMAZON.HelpIntent');
},
'addZipcode': function() {
const newZip = this.event.request.intent.slots.zipcode.value;
const speechOutput = newZip;
var http = require("https");
function postZip(newZip) {
var options = {
"method": "POST",
"hostname": [
"beta",
"todoist",
"com"
],
"path": [
"API",
"v8",
"tasks"
],
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer " + token
}
};
var req = http.request(options, function(res) {
var chunks = [];
res.on("data", function(chunk) {
chunks.push(chunk);
});
res.on("end", function() {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write(JSON.stringify({ content: newZip, project_id: XXXXXXXXXX }));
req.end();
}
postZip(newZip);
this.response.cardRenderer(SKILL_NAME, newZip);
this.response.speak(speechOutput);
this.emit(':responseReady');
},
.... cont
I get the resulting error when I try to run the skill with Alexa:
Response:
{
"errorMessage": "hostHeader.replace is not a function",
"errorType": "TypeError",
"stackTrace": [
"Agent.addRequest (_http_agent.js:130:39)",
"new ClientRequest (_http_client.js:159:16)",
"Object.exports.request (http.js:31:10)",
"Object.exports.request (https.js:199:15)",
"postZip (/var/task/index.js:72:28)",
"Object.addZipcode (/var/task/index.js:88:9)",
"emitNone (events.js:86:13)",
"AlexaRequestEmitter.emit (events.js:185:7)",
"AlexaRequestEmitter.EmitEvent (/var/task/node_modules/alexa-sdk/lib/alexa.js:216:10)",
"AlexaRequestEmitter.ValidateRequest (/var/task/node_modules/alexa-sdk/lib/alexa.js:181:23)"
]
}
I tried searching for more information about hostHeader.replace or even just hostHeader but to no avail. When I surround my postZip function with
exports.handler = function(event, context, callback) {}
the skill actually works, but the Post request does not go through (as in, the new zipcode is not added as a new task on my Todoist). I'm pretty sure the Post request code itself is correct because I ran it through Postman and the zipcode was added.
Please help me understand why it doesn't work.
It's hard to tell what causes that error. But the node docs say, that hostname as well as path are supposed to be nothing but strings and not arrays as it's the case in your code.
So what I'd do first is to change your code to this:
var options = {
"method": "POST",
"hostname": "beta.todoist.com",
"path": "/API/v8/tasks",
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer " + token
}

Mailchimp API v3.0 add email to list via NodeJS http

I'm using NodeJS to call the new MailChimp 3.0 API in order to add an email to a list. While I can get it working via POSTman, I'm having a hard time with Node's http:
var http = require('http');
var subscriber = JSON.stringify({
"email_address": "test#test.com",
"status": "subscribed",
"merge_fields": {
"FNAME": "Tester",
"LNAME": "Testerson"
}
});
var options = {
host: 'https://us11.api.mailchimp.com',
path: '/3.0/lists/<myListID>/members',
method: 'POST',
headers: {
'Authorization': 'randomUser myApiKey',
'Content-Type': 'application/json',
'Content-Length': subscriber.length
}
}
var hreq = http.request(options, function (hres) {
console.log('STATUS CODE: ' + hres.statusCode);
console.log('HEADERS: ' + JSON.stringify(hres.headers));
hres.setEncoding('utf8');
hres.on('data', function (chunk) {
console.log('\n\n===========CHUNK===============')
console.log(chunk);
res.send(chunk);
});
hres.on('end', function(res) {
console.log('\n\n=========RESPONSE END===============');
});
hres.on('error', function (e) {
console.log('ERROR: ' + e.message);
});
});
hreq.write(subscriber);
hreq.end();
Rather than getting even some sort of JSON error from Mailchimp, however, I'm getting HTML:
400 Bad Request
400 Bad Request
nginx
Is it clear at all what I"m doing wrong here? It seems pretty simple, yet nothing I've tried seems to work.
A few additional thoughts:
While http's options have an "auth" property, I'm using the headers instead to ensure the authorization is sent without the encoding (as mentioned here). Still, I've also tried with the "auth" property, and I get the same result.
I'm actually making this call from inside an ExpressJS API (my client calls the Express API, that calls the above code - I've edited all that out of this example for simplicity). That's why my variables are "hres" and "hreq", to distinguish them from the "res" and "req" in Express. Is there any reason that could be the issue?
As mentioned above, I am able to get successful results when using POSTman, so I at least know my host, path, list ID, and API key are correct.
It turns out this had a very simple solution: the "host" property of the options object needed to have only the domain name. IE, remove the "https://" protocol:
var options = {
host: 'us11.api.mailchimp.com',
path: '/3.0/lists/<myListID>/members',
method: 'POST',
headers: {
'Authorization': 'randomUser myApiKey',
'Content-Type': 'application/json',
'Content-Length': subscriber.length
}
}
Try this , its working fine for Me.
var request = require('request');
function mailchimpAddListCall(email, cb){
var subscriber = JSON.stringify({
"email_address": email,
"status": "subscribed"
});
request({
method: 'POST',
url: 'https://us13.api.mailchimp.com/3.0/lists/<Your list id>/members',
body: subscriber,
headers:
{
Authorization: 'apikey <your Mailchimp API key>',
'Content-Type': 'application/json'
}
},
function(error, response, body){
if(error) {
cb(err, null)
} else {
var bodyObj = JSON.parse(body);
console.log(bodyObj.status);
if(bodyObj.status === 400){
cb(bodyObj.detail, null);
}
var bodyObj = JSON.parse(body);
cb(null, bodyObj.email_address +" added to list.");
}
});
}
request is a node module, that you'll need to install into your package.json. npm install --save request
You can use the auth properties just fine with API v3, but if you're getting a 400, that's not the problem. The body of the 400 Error should provide more detailed information, but one thing that jumps out immediately: MailChimp doesn't allow fake or fake-looking emails to be added to lists (like test#test.com), so I'd try a real address and see if that works for you.

Resources