Make Request With Node.JS To Change Vanity Discord - node.js

How can I change the vanity url code in Discord? My current code returns a 401 error.
Code:
const fetch = require("node-fetch");
setTimeout(async () => {
await fetch('https://www.discord.com/api/v9/guilds/serverID/vanity-url', {
method: 'POST',
headers: { 'Authorization': 'Bot ' + client.token, 'Content-Type': 'application/json'},
payload: JSON.stringify({
"code":"terbo1"
})
})
.then(async res => await res.json())
.then(json => { console.log(json);});
Response:
{ message: '401: Unauthorized', code: 0 }

I don't understand why you need setTimeout however you were using the wrong HTTP method on the request: the correct method is PATCH.
Additionally, payload isn't an option on the Fetch API, use body instead.
const fetch = require("node-fetch");
const endpoint = `https://www.discord.com/api/v10/guilds/${SERVER_ID}/vanity-url`;
await fetch(endpoint,{
method: "PATCH",
headers: {
Authorization: `Bot ${client.token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
code: "terbo1",
}),
});
Edit: As of 01/12/2022 (12/01/22) Discord have now disabled this ability for bots to "manipulate" this request, however, the above script can be used on a User-Account, there are risks of being banned doing so, so it is NOT recommended, use at your own risk.

Related

how to handle xml response with fetch?

i have a angular project that calls a firebase function, my firebase function uses fetch to get a xml response, the problem is i dont know how to handle the xml response that needs to be sent back to my angular project..can anyone help please
firebase function
app.post('/provider', bodyParser.json(), async (req, res) => {
const response = await fetch(
'https://api.verify.example.com/identification/report_verification/',
{
method: 'POST',
body: req.body,
headers: {
'Content-Type': 'application/json' ,
'Authorization': 'Token 8c708fe3306f3f55644842a4d1f00561aa57b02e' }
})
const str = await response.text()
res.send(str)
})

Discord Ouath2 Access Token 'Grant type None is not supported'

Im trying to make a login system with discord for my website that is made with express. I have made a function to get an access token so that I can use that function in the route.
Im trying to get an access token from: https://discord.com/api/oauth2/token
Here is my code:
async GetToken(code) {
let access_token;
const payload = {
'client_id': client_id,
'client_secret': client_secret,
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': redirect_uri,
'scope': scope,
};
const config = {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
};
fetch(discord_token_url, {
method: 'post',
body: payload,
headers: config.headers,
}).then(response => response.json()).then(json => console.log(json)).catch(err => console.log(err));
return access_token;
},
And here's the err I get:
{
error: 'unsupported_grant_type',
error_description: 'Grant type None is not supported'
}
As you can see I've given the correct grant type yet I get this error.
Forgot to update to add the solution and saw a lot of people looking at this so here's the solution (thanks to #Kira):
You have to use URLSearchParams
// Modules
const fetch = require('node-fetch');
const { url } = require('inspector');
const { URLSearchParams } = require('url');
// Add the parameters
const params = new URLSearchParams();
params.append('client_id', client_id);
params.append('client_secret', client_secret);
params.append('grant_type', 'authorization_code');
params.append('code', code);
params.append('redirect_uri', redirect_uri);
params.append('scope', scope);
// Send the request
fetch('https://discord.com/api/oauth2/token', {
method: 'post',
body: params,
headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' },
}).then(r => r.json()).then(Response => {
// Handle it...
handle()
});

Converting Curl to Nodejs Axios - Obtaining an Access Token

I am currently using curl in order to obtain an access token so I can consume an api with said token. The curl command I use is as follows:
curl --user <client_id>:<client_secret> https://api.ed-fi.org/v3/api/oauth/token --data 'grant_type=client_credentials'
It works and all...but instead of curling I want to utilize the axios library to get this access token instead.
Here's what I have but it doesn't work.
const buff = new Buffer.from('<client_id>:<client_secret>';
const base64data = buff.toString('base64');
axios({
method: 'POST',
url: 'https://api.ed-fi.org/v3/api/oauth/token',
headers: {
Authorization: `Basic ${base64data}`
},
data: { 'grant_type': 'client_credentials' }
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
I can't figure out what I'm missing or doing wrong?
You should change Content-Type (default for axios is JSON) and pass body just like you did in case of curl:
axios({
method: 'POST',
url: 'https://api.ed-fi.org/v3/api/oauth/token',
headers: {
Authorization: `Basic ${base64data}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
data: 'grant_type=client_credentials'
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});

Firebase cloud function http request crashing

I'm trying to send expo push notification via firebase cloud functions, in order to send notifications from the web app to devices that have downloaded the mobile app.
When I send the request from Postman, it works just fine... i get the ok response and the notification shows up on my phone. But when I try to make the request from the web app, i get this in the functions log:
Function execution took 22 ms, finished with status: 'crash'
Any ideas why is this happening? Couldn't find anything to explain this so far.
Here's my function:
exports.reportNotification = functions.https.onRequest((request, response) => {
const tokens = request.body.expoPushToken;
let messages = [];
tokens.forEach((token) =>
messages.push({
to: token,
title: "title",
body: "message",
sound: "default",
_displayInForeground: "true",
})
);
fetch("https://exp.host/--/api/v2/push/send", {
method: "POST",
headers: {
Accept: "application/json",
"Accept-encoding": "gzip, deflate",
"Content-Type": "application/json",
},
body: JSON.stringify(messages),
})
.then((res) => response.status(200).json({ res: res }))
.catch((err) => response.status(400).json({ error: err }));
});
My post request on Postman:
{
"expoPushToken": ["ExponentPushToken[xxx-xxxxxxxxxxxxx]"]
}
And I call the function with axios in the web app:
axios({
url: "reportNotification",
baseURL: functionsBaseURL,
method: "post",
data: {
expoPushToken: tokens,
},
})
I checked and the tokens on this request are in the same format that the one on Postman.
Thanks.
It was a cors problem, solved with this modification:
exports.reportNotification = functions.https.onRequest((request, response) => {
cors(request, response, () => {
const tokens = request.body.expoPushToken;
let messages = [];
tokens.forEach((token) =>
messages.push({
to: token,
title: "title",
body: "message",
sound: "default",
_displayInForeground: "true",
})
);
axios.post("https://exp.host/--/api/v2/push/send", JSON.stringify(messages), {
headers: {
"Accept": "application/json",
"Accept-encoding": "gzip, deflate",
"Content-Type": "application/json",
},
})
.then((res) => response.status(200).json({ res: res }))
.catch((err) => response.status(200).json({ error: err }));
});
});

Error handling axios request.post

We have an axios method like
export function callAcme(message) {
const requestUrl = `/api/acme/message`;
return {
type: ACME_MESSAGE,
promise: request.post(requestUrl, {
data: message
})
};
}
This method is mapped to an express router method, which makes a call to a third party API to get some data.
router.post("/acme/message", (req, res) => {
const { data } = req.body;
const url = "third/party/url/action;
authenticateThirdparty({
user: req.user
}).then(userToken => request({
method: "post",
url,
data: body,
baseURL: url,
"Content-Type": "application/json; charset=utf-8",
"Cache-Control": "no-cache",
headers: {
Authorization: `Bearer ${userToken}`
}
})).then((response) => {
res.status(200).send(response.data);
}).catch((error) => {
res.status(error.status).send(error.data);
});
});
The third party call is made in a try catch block. But id the third party method raises some error then we are are unable to send the error back to the web page who initiated the the axios call.
ie. In the client which invokes callAcme will not get the error object back.

Resources