Assigning Roles to a Discord Member Already in Guild - javascript

I'm trying to assign a discord role to a member using OAuth2 on my website. They sign in, I get the access token (which works with other requests), and then send the request below with every header and variable being correct.
factionRoleMapping = { OG: "929218237030354994" };
const newRoles = [...currentRoles, factionRoleMapping[faction]];
var rolesInfoFetch = await fetch(
`https://discord.com/api/v9/guilds/${config.GUILD_ID}/members/${req.body.uid}`,
{
method: "PUT",
headers: { Authorization: req.headers.authorization },
body: {
roles: newRoles,
},
}
);
I read the docs and it said that I would get a 204 No Content if the user was already in the discord guild, which I'm guessing should be okay. But I keep getting 401 Unauthorized.
The current permissions are "guilds", "guilds.join", "guilds.members.read", and "identify".
I'm not even sure if this is possible the way I'm doing it, but any help is appreciated!

Authorization header should be in format of Bot your.bot.token
also your question is unrelated to discord.js

Related

Discord.js: can't fetch user's connections (OAuth2)

I have a Discord app/bot with a custom linked role, and before updating metadata and adding the role, I want to fetch user's connections and look at some data from it.
More specifically, I want to assign a custom role only to users who own a specific game on Steam and have certain achievements from it. Currently stuck at fetching connections part - OAuth in general works fine.
Took this example discord oauth app:
https://github.com/discord/linked-roles-sample
And it works, except for this part: I want to fetch user's connections
Added this new function
export async function getUserConnections(tokens) {
const url = 'https://discord.com/api/v10/oauth2/#me/connections';
const response = await fetch(url, {
method: 'GET',
headers: {
Authorization: `Bearer ${tokens.access_token}`,
},
});
if (response.ok) {
const data = await response.json();
return data;
} else {
throw new Error(`Error fetching user connections: [${response.status}] ${response.statusText}`);
}
}
But this fetch always returns 404, even though scope for connections is defined

Slack API keeps telling me channel_not_found when attempting to upload an image

Like the title describes, i can't seem to figure out how to upload a local image and have it posted as a message in slack
Currently i am able to post text messages to slack without issue using the webhook url and axios post seen here:
const res = await axios.post(url, {
text: 'Screenshot',
channel: channelid
}, {
headers: {
authorization: `Bearer ${token}`
}
});
Heres the part of the script that isnt working:
try {
const result = await client.files.upload({
channels: channelid,
initial_comment: "this is the image",
file: fs.createReadStream(fileName)
});
console.log(result);
} catch (error) {
console.error(error);
}
I dont understand how the channelid works in one and not the other.
Calling a method with an xoxb or xoxp token is different than posting a message with a webhook. When you create the webhook on the Slack Developer settings site, you are asked to choose a channel. The webhook will be able to post into that channel without your app being a channel member. When using the xoxb token your bot needs to be a member of the channel that's being passed in the API call. If it's not a member you can expect a channel_not_found or not_in_channel error.
You should add the bot to the channel using
/invite #bot-name

Clash Royale Node Fetch with Key

Im trying to make a discord bot where if you type -cr into the chat, it takes the Arguments of the user (Being the Clash Royale Player's player tag) and would then use the package node-fetch to receive data with my specified endpoint. I am constantly running into the error of { reason: 'accessDenied', message: 'Invalid authorization' }. Im rather new to this stuff, especially API's, but im hoping to access certain data which I can decide later on (Which I know how to do). My code is :
const fetch = require('node-fetch')
module.exports = {
name: 'clash',
aliases: ['cr', 'clashroyale'],
category: 'This',
utilisation: '{prefix}clash',
async execute(client, message) {
var msgArgs = message.content.slice(this.name.length + 1)
var endpoint = `/players/${msgArgs}`
var url = `https://api.clashroyale.com/v1`
var token = `hidingmytoken`
fetch(url + endpoint, {
method: 'POST',
headers: {
"Authorization": token
}
}).then(data => data.json()).then(json => {
console.log(json)
})
},
};
The message parts with msgArgs and discord sides all work but fetching that clash Royale API is a big hurdle for me. The API for Clash Royale can be found here https://developer.clashroyale.com/#/documentation and Im just generally stuck on this whole concept. Im using version 2.6.6 of node-fetch so I can use the require() method which should work if that does matter. In general, how can I pass my token properly to receive that API data?
Since the Clash Royale API uses bearer authentication, you need to specify that it will be a bearer token.
headers: {
'Authorization': `Bearer ${token}`
}
I've implemented the following functionality. The code is written in GO but you can copy the logic and translate into your language.
The library have the following functionality:
Login
Token generation
Token list
Token delete
https://github.com/alessiosavi/GoClashRoyale/blob/master/api/auth.go

Next Js - How to retrieve data from the api requiring authorization (via axios)?

enter image description here
user = Cookies.get("user")
I can't get access to this road. I used cookies to store user data including the token.
Please I need Help
I think your using Strapi CMS and request method for authenticated roots must be POST not GET here the example :
const {data ,status} = await
axios.post('https://localhost:1337/posts',{
headers : {
Authorization: `Bearer ${token}`
}
});
if(status === 200){
setData(data)
}else{
console.log('eeror')
}
make sure to mark the find method from strapi admin otherwise you will get 403 error in strapi user has jwt not token so make sure the token is the jwt which come from strpai when user login!

Send message to discord via google apps script

I'd like to send a bot message in a discord channel via google apps script when a certain event is triggered, but I don't know where to start. Is this even possible? If not, is there a way to do it via github?
EDIT: I have figured out how to get the OAuth tokens, now how do I make the bot send a message?
I know that there's pretty much no chance that the OP still needs this answer, but I'm putting it up here so that others who google this question will be able to find the answer
var webhooks = {
test: "Obtain a webhook for the channel you'd like and put it here."
};
function sendMessage(message, channel)
{
if(webhooks.hasOwnProperty(channel))
var url = webhooks[channel];
else {
Logger.log("Error Sending Message to Channel " + channel);
return "NoStoredWebhookException";
}
var payload = JSON.stringify({content: message});
var params = {
headers: {"Content-Type": "application/x-www-form-urlencoded"},
method: "POST",
payload: payload,
muteHttpExceptions: true
};
var res = UrlFetchApp.fetch(url, params);
Logger.log(res.getContentText());
}
// to call and send a message
sendMessage("Hi!", "test");
This is what I typically use for sending messages. Unfortunately, there's no way to receive triggers from the webhooks to my knowledge.
Note: The above answer references discord.js, which is not compatible with Google Apps Script
To start with, here is a documentation from discord.js.
To let your apps script communicate with discord, you can check the External APIs
Google Apps Script can interact with APIs from all over the web. This
guide shows how to work with different types of APIs in your scripts.
Examples are available in the provided documentations.
See these useful links for further details.
Website (source)
Documentation
Discord.js server
Discord API server
GitHub
NPM
Related libraries (see also discord-rpc)
Super easy. Just go to your Discord channel, choose "Edit Channel" > "Webhooks". You name the bot and set its profile picture. It will give you a webhook URL that already contains the authorization token.
Then you just POST to that public URL. TADA, a message will appear in the given channel, sent by the bot.
function postMessageToDiscord(message) {
message = message || "Hello World!";
var discordUrl = 'https://discordapp.com/api/webhooks/labnol/123';
var payload = JSON.stringify({content: message});
var params = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: "POST",
payload: payload,
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(discordUrl, params);
Logger.log(response.getContentText());
}
Source: https://ctrlq.org/code/20563-post-message-to-discord-webhooks
For anyone still looking and not having luck with previous answers, like me:
After making my message_string, this snippet successfully sent to my desired channel's webhook:
// Send the message to the Discord channel webhook.
let options = {
"method": "post",
"headers": {
"Content-Type": "application/json",
},
"payload": JSON.stringify({
"content": message_string
})
};
Logger.log(options, null, 2);
UrlFetchApp.fetch("your_webhook_url_here", options);
I can't make a comment yet, but if you are having issues with one of the above answers - try changing the content type from:'Content-Type':"application/x-www-form-urlencoded" to 'Content-Type':"application/json".

Categories