Discord Profil Picture Update from ElectronJS using request PATCH - node.js

I'm trying to code an application into Electron JS to allow the person to change their profile picture at the same time on several applications.
For this I use the APIs of each platform.
For Twitter it works correctly, but I block at the level of Discord.
I can make a GET request on the profile, but I can't do a : PATCH/users/#me
https://discordapp.com/developers/docs/resources/user#modify-current-user
I do not know if it's the token that does not offer enough power, because I only asked for Identity as permission on my application.
I tried to pass JSON between true and false,
to add a content type, but I still have the same answer: {code: 0, message: '401: Unauthorized'}
function postDiscord(image) {
const imageDataURI = require('image-data-uri')
let {token} = store.get('discordToken') //get stored token
imageDataURI.encodeFromFile(image)
.then(res => {
request({
method: 'PATCH',
url: 'https://discordapp.com/api/v6/users/#me',
headers: {
'Authorization': 'Bearer '+token,
'User-Agent': 'someBot (site, v0.1)'
},
body: {
'avatar': res
},
json: true
}, function(err, res) {
if(err) {
console.error(err);
} else {
console.log(res.body)
}
}
);
})
}
{code: 0, message: '401: Unauthorized'}

Refering to Discord :https://github.com/discordapp/discord-api-docs/issues/1057
Cannot upload new pics with Oauth :/

Related

ReCAPTCHA siteverify not returning JSON response

I am implementing recaptcha into a user submittable form. After attempting to validate the token using the url
https://www.google.com/recaptcha/api/siteverify
The response given is something similar to
▼���RPP*.MNN-.V�RHK�)N�☺��▬§�↨�&秤�ģ�B#�̼�Ĝ�¶�̼��↕ݢ�����T%�d,W-�
� K
The code used to attempt to validate the response is as follows
var data = JSON.stringify({
secret: process.env.RECAPTCHA_SECRET,
response: req.body.gcaptcha_response,
});
var config = {
method: "post",
url: "https://www.google.com/recaptcha/api/siteverify",
headers: {
"Content-Type": "application/json",
},
data: data,
};
axios(config)
.then(function (response) {
res.json({
success: true,
body: response.data,
});
})
.catch(function (error) {
console.log(error);
});
I have also attempted with other content types to no success. I have also attempted to follow the answer given in this thread
This is a workaround for now
I just realised this is happening for the latest version of axios.
If you install axios version 1.1 it returns the data as json.
Thread: https://github.com/axios/axios/issues/5298

API call from https node application never reaches the destination

I have a node.js application served over https. I would like to call an API from that application. The API is also served over https and it has been generated using the express-generator.
Unfortunately the call never works. There is no error message. The call never reaches the API.
Strangely enough if I try to call another public API (e.g. https://api.publicapis.org/entries') that is working perfectly.
Here is my call:
const requestBody = {
'querystring': searchQuery,
};
const options = {
rejectUnauthorized: false,
keepAlive: false, // switch to true if you're making a lot of calls from this client
};
return new Promise(function (resolve, reject) {
const sslConfiguredAgent = new https.Agent(options);
const requestOptions = {
method: 'POST',
body: JSON.stringify(requestBody),
agent: sslConfiguredAgent,
redirect: 'follow',
};
fetch('https://192.168.112.34:3003/search', requestOptions)
.then(response => response.text())
.then(result => resolve(result))
.catch(error => console.log('error', error));
});
};
And here is the API which I would like to call:
router.post('/', cors(), async function(req, res, next) {
req.body;
queryString = req.body.querystring;
let data = JSON.stringify({
"query": {
"match": {
"phonetic": {
"query": queryString,
"fuzziness": "AUTO",
"operator": "and"
}
}
}
});
const { body } = await client.search({
index: 'phoneticindex',
body: data
});
res.send(body.hits.hits)
});
What is wrong with my API and/or the way I am trying to communicate with it?
UPDATE: I receive the following error in the fetch catch block: 'TypeError: Failed to fetch'
When I create a request in Postman I receive the expected response.
UPDATE 2: This is most probably an SSL related issue. The webapp is expecting an API with a valid certificate. Obviously my API can only have a self signed cert which is not enough here. How can I generate a valid cert for an API which is running on the local network and not publicly available?
UPDATE 3: I managed to make it work by changing the fetch parameters like this:
fetch(url, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
mode: 'cors',
body: raw,
agent: httpsAgent,
redirect: 'follow',
})
and on the API side I added the following headers:
'Content-Type': 'application/json',
'Access-Control-Allow-Origin' : 'https://localhost:2200',
'Access-Control-Allow-Methods' : 'POST',
'Access-Control-Allow-Headers' : 'Content-Type, Authorization'
I also added app.use(cors()) and regenerated the self-signed certificates.

How to add a contact to ActiveCampaign using API v1 contact_sync/contact_add

I am having trouble adding a contact to ActiveCampaign. I read a post in here: How to add a contact to a list in ActiveCampaign API v3 and am using v1 of the API. I used their contact_sync documentation to the best of my availability.
I'm developing using Gatsby/React --> GitHub --> Netlify, using a lamda function for the POST request.
Here is my axios POST:
{
method: 'post',
url: 'https://ACCOUNT.api-us1.com/admin/api.php?api_key=xxxxxxxxxxxx&api_action=contact_sync&api_output=json',
headers: { 'Content-Type': 'Content-Type: application/x-www-form-urlencoded' },
body: {
email: 'email#email.com',
first_name: 'John'
}
}
And received the following response:
{
result_code: 0,
result_message: 'Could not add contact; missing email address',
result_output: 'json'
}
I'm talking to their endpoint. I just can't figure out how to feed the endpoint the email address?
Does anyone have a working example they would be kind enough to share? Guidance of any kind would be greatly appreciated!
I wanted to make sure to close this and share my answer.
Thanks so much to #reza jafari for his comment in this post where he brought to my attention the code window on the right margin of Postman where you can choose the language/server from a dropdown and it provides the correctly formatted response.
(I don't have enough reputation to upvote #reza's response so wanted to acknowledge it here.)
I was able to get my post working in Postman, and this little trick squared me away. I'll go ahead and post my solution to close this post.
const axios = require("axios")
const qs = require("qs")
exports.handler = async function (event) {
const { email, first_name } = JSON.parse(event.body)
const data = qs.stringify({
email: email,
first_name: first_name,
tags: '"api"',
"p[1]": "1",
})
const config = {
method: "post",
url: "https://ACCOUNT.api-us1.com/admin/api.php?api_key=xxxxxxxxx&api_action=contact_sync&api_output=json",
headers: {
"Api-Token":
"xxxxxxxxx",
"Content-Type": "application/x-www-form-urlencoded",
},
data: data,
}
try {
const response = await axios(config)
return {
statusCode: 200,
body: JSON.stringify(response.data),
}
} catch (err) {
return {
statusCode: 500,
body: JSON.stringify(err),
}
}
}

Got npm module: How to add bearer token to POST request

I recently found out that request is no longer maintained, so the best alternative I found is got. I am trying to make an external API call to a REST Server but I am unsure as to how I can add a Bearer token in the authorization header of the POST request.
This is my code:
const response = await got.post(
"https://${SERVER}/${SOME_ID}/conversations/${CONVERSATION_ID}/messages",
{
json: [
{
text: req.body.message,
type: "SystemMessage",
}
],
responseType: "json",
headers: {
token: "Bearer pXw4BpO95OOsZiDQS7mQvOjs"
}
}
);
This results in a 401 Unauthorized. I was unable to find direction to such implementation in the documentation provided by GOT. And since there are not a lot of queries regarding this package, I was unsuccessful in finding anything on Google as well. If anyone can help me out in this regard, that would be very helpful!
Are you sure that the header name is "token" ?
Usually in API, the Bearer is in a header called "Authorization"
const response = await got.post(
"https://${SERVER}/${SOME_ID}/conversations/${CONVERSATION_ID}/messages",
{
json: [
{
text: req.body.message,
type: "SystemMessage",
}
],
responseType: "json",
headers: {
"Authorization": "Bearer pXw4BpO95OOsZiDQS7mQvOjs"
}
}
);
Here is the code
npm i postman-request link for npm package
const request = require('postman-request');
request({
url: 'your url',
headers: {
'Authorization': 'Bearer 71D50F9987529'
},
rejectUnauthorized: false
}, function(err, res) {
if(err) {
console.error(err);
} else {
console.log(res.body);
}
});

Problem setting the name of a file when using the Google Drive REST API for resumable uploads

async function createResumableSession(filePath, authClient){
try {
const fileStats = await statsAsync(filePath);
const fileSize = fileStats.size;
const postResult = await new Promise((resolve, reject)=>{
request({
method: 'post',
url: 'https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable',
followAllRedirects: true,
headers: {
Authorization: "Bearer " + authClient.credentials.access_token,
"X-Upload-Content-Length": `${fileSize}`,
"Content-Length": "0",
"Content-Type": "application/json; charset=UTF-8"
},
body:JSON.stringify({
title: "myfile.backup"
})
}, function (error, response) {
if (error)
return reject(error);
resolve({
statusCode: response.statusCode,
location: response.headers.location,
body: response.body
});
})
})
return {
postResult,
fileSize
}
} catch (error) {
throw error;
}
}
I have this function to create a resumable upload on the Google Drive API, its creating the session correctly but I cant set the file name, after the upload is completed the file name always end as "untitled"
How about this modification?
Modification points:
In your script, from the endpoint of https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable, it is found that you are using Drive API v3. In this case, in order to set the filename, it is required to use the property of name. In your script, title is used. In this case, it is for Drive API v2. So please modify as follows.
Modified script:
Please modify your script as follows.
From:
title: "myfile.backup"
To:
name: "myfile.backup"
Reference:
Files: create
If this was not the direct solution of your issue, I apologize.
Added:
As a simple sample script, I added a sample script. In this sample script, a text file is uploaded using the resumable upload. In this case, the file is uploaded as the filename of "sample". And you can see the text of foo in the uploaded file.
Sample script:
const request = require('request');
const accessToken = "###"; // Please set your access token.
request({
method: 'POST',
url: 'https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable',
headers: {
"Authorization": `Bearer ${accessToken}`,
"Content-Type": "application/json"
},
body: JSON.stringify({name: "sample", mimeType: "text/plain"})
}, (err, res) => {
if (err) {
console.log(err);
return;
}
request({
method: 'PUT',
url: res.headers.location,
headers: {"Content-Range": "bytes 0-2/3"},
body: Buffer.from("foo")
}, (err, res) => {
if (err) {
console.log(err);
return;
}
console.log(res.statusCode)
console.log(res.body)
});
});
Using the property of name, the metadata of file has the filename of sample.
But unfortunately, from your replying, I cannot understand about your current issue. So can I ask you about the detail information about the problem persists? And in order to correctly understand about your situation, can you provide the detail flow and whole script for replicating your issue? Of course, please remove your personal information. By this, I would like to confirm it. If you can cooperate to resolve your issue, I'm glad.

Resources