David
David

Reputation: 67

Discord.js: How to find server member (to assign roles in Discord) by Discord User-ID?

I am building a web-application that authenticates users with discords oauth. When a user is registered in the laravel app, the given data from discords oauth is saved into an sql database. In this data is the Username, discriminator and the unique discord user ID. I now have a seperate node.js server that runs discord.js and forms a bot. I want this bot to assign a "registered" role to the authenticated user on a discord server. At the moment I am only able to assign roles to a user that messages the bot on the server via accessing the discord.js message object like below.

bot.on("messageCreate", (message) => {
    if (message.content.toLowerCase().startsWith("!role add")) {
        let member = message.mentions.members.first();
        let role = message.mentions.roles.first()
        member.roles.add(role)
    }
}) //this works. But how can a member be found only using the Discord User ID?

Here is the question: Is there a way in Discord.js to find the member by giving the discord user ID (Given by OAuth and saved into my DB) instead of retrieving it from a message, that the user has to send?

I hope my question is clear and does not confuse. I am not asking about anything regarding http / server-server communication or the Operations with Laravel/Oauth/DB because this works already. I just cant find a function like

let member = bot.findGuildMemberByID("USER-ID HERE");

Here is a visualisation of the general architecture to make it more clear. Architecture. The messy thing on the bottom is a line of the database for showing the user id

Upvotes: 0

Views: 645

Answers (2)

MrMythical
MrMythical

Reputation: 9041

You in fact only need ids to add a role to a member. Discord API has an endpoint for that.

discord.js doesn't currently have a "built-in" method for this, but I've made a pull request for this, but it's not ready yet

Instead, you can use rest, which is used there too, internally

const { REST } = require("discord.js") // will need to use @discordjs/rest if not using v14

// ...

const rest = new REST({ version: "9" }).setToken(client.token)
await rest.put(Routes.guildMemberRole(guildId, userId, roleId), {
  reason // optional - reason for adding the role
})

Upvotes: 1

Crytek1012
Crytek1012

Reputation: 763

Simply get the guild where you want to find the member:

const guild = client.guilds.cache.get("GUILD-ID HERE"); // or message.guild

then you can get a member by their ID by:

Using get:

const member = guild.members.cache.get("USER-ID HERE");

Filtering all the guild's members

const member = guild.members.cache.find(member => member.id === "USER-ID HERE");

Fetching the member:

const member = guild.members.fetch("USER-ID HERE");

Upvotes: 0

Related Questions