DIscord API - add a guild member with node js express
I have created a Discord bot with a couple of commands in it, all fine until here.
The idea is now to ask users for their ID manually, and once this info is in, I'd like to add them as members of my guild via the endpoint described in the API "/guilds/{guild.id}/members/{user.id}".
Therefore I'll recap:
- Ask the user to provide his/her ID,
- Enter the following URL http://localhost:3000/add-member/:userID
- Add the member to the guild.
Everything works well if I auto add myself. The error comes when I use an ID of an external user.
The error is:
There was an error DiscordAPIError[50025]: Invalid OAuth2 access token.
The application has all the necessary permissions as guilds.join, application.commands and bot. And the bot has Admin permission.
This my repo in github: https://github.com/Srizza93/harry-botter
For the last 2 days I'm struggling and online there is not much in detail.
Thanks in advance for your replies.
So far this is my code in sever.js:
// Adding Members
app.get(`/add-member/:userId`, async (req, res) => {
try {
await rest.put(Routes.guildMember(guildId, req.params.userId), {
headers: {
["Content-Type"]: "application/json",
Authorization: `${token}`,
},
body: {
access_token: accessToken,
nick: "New",
},
});
console.log("Successfully added memeber id " + req.params.userId);
} catch (error) {
console.log("There was an error " + error);
}
});
And this is my first point index.js:
const server = require("./server");
const fs = require("node:fs");
const path = require("node:path"); // Require the necessary discord.js classes
const { Client, Collection, Events, GatewayIntentBits } = require("discord.js");
const { token } = require("./config.json");
// Create a new client instance
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers],
});
server(client);
client.commands = new Collection();
const commandsPath = path.join(__dirname, "commands");
const commandFiles = fs
.readdirSync(commandsPath)
.filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
// Set a new item in the Collection with the key as the command name and the value as the exported module
if ("data" in command && "execute" in command) {
client.commands.set(command.data.name, command);
} else {
console.log(
`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`
);
}
}
// When the client is ready, run this code (only once)
// We use 'c' for the event parameter to keep it separate from the already defined 'client'
client.once(Events.ClientReady, (c) => {
console.log(`Ready! Logged in as ${c.user.tag}`);
});
// Once ready, listen for events
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand()) return;
const command = interaction.client.commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({
content: "There was an error while executing this command!",
});
}
});
// Add a Default role to each new member
client.on(Events.GuildMemberAdd, (member) => {
try {
const role = member.guild.roles.cache.find(
(role) => role.name === "discorder"
);
if (role) {
member.roles.add(role);
console.log(member.user.id + " is in da house");
} else {
console.log(
`The role discorder was not assigned to '${member}' as it wasn't created`
);
}
} catch (error) {
console.error(error);
}
});
// Log in to Discord with your client's token
client.login(token);
EDIT
I managed to exchange the OAuth2 and send my request with the below code:
app.get("/login", (req, res) => {
// Redirect the client to the authorization URL
res.redirect(
`https://discord.com/api/oauth2/authorize?client_id=1055994237243637812&permissions=8&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fcallback&response_type=code&scope=bot%20guilds.join%20applications.commands`
);
});
app.get("/callback", async (req, res) => {
// Get the OAuth2 token from the query parameters
const code = req.query.code;
// Exchange the code for an OAuth2 token
if (code) {
try {
const tokenResponseData = await request(
"https://discord.com/api/oauth2/token",
{
method: "POST",
body: new URLSearchParams({
client_id: clientId,
client_secret: clientSecret,
code,
grant_type: "authorization_code",
redirect_uri: redirectUri,
scope: "guilds.join",
}).toString(),
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
}
);
const oauthData = await tokenResponseData.body.json();
await rest.put(Routes.guildMember(guildId, oauthData.owner_id), {
headers: {
["Content-Type"]: "application/json",
Authorization: `${token}`,
},
body: {
access_token: oauthData.access_token,
nick: "New",
},
});
console.log(`Successfully added user ${oauthData.owner_id}`);
} catch (error) {
// NOTE: An unauthorized token will not throw an error
// tokenResponseData.statusCode will be 401
console.error(error);
}
}
});
However, the error is now:
DiscordAPIError[20001]: Bots cannot use this endpoint
But I'm actually using a server and not the bot. At this point my question is, is it even possible to add members via a server?
Comments
Post a Comment