Home > Software design >  How to get user id of interaction with Discord.JS
How to get user id of interaction with Discord.JS

Time:11-13

I'm trying to get the data of a user, which sent an interaction (a / command). The code below sends the reply-message, but I don't get the user ID in the console. I tried this code because I found it online but it doesn't work.

if (interaction?.data?.name === 'test') {
    await interaction.createMessage({
        content: 'test'
    })
    const interactionUser = await interaction.guild.members.fetch(interaction.user.id)

    const nickName = interactionUser.nickname
    const userName = interactionUser.user.username
    const userId = interactionUser.id

    console.log(nickName,userName,userId)
}

can anyone help me?

CodePudding user response:

You still need to have "user" so something like this should work

const userId = interactionUser.user.id

CodePudding user response:

It's because author of the code assumed that the type returned from interaction.guild.members.fetch(interaction.user.id) is User while it's GuildMember . If you do anything regarding Discord bots, you need to be able to keep up with their official documentation for both types and guides, as they make a version after version and code quickly becomes obsolete. This means that googling for pieces of code somewhere else, in most instances mean, that you are getting code for old API versions.

Would also highly recommend using TypeScript for making Discord bots, as instead of having to open docs every time you need to get property of anything you get it all in hints.

if (interaction?.data?.name === 'test') {
    await interaction.createMessage({
        content: 'test'
    })
    // This returns a GuildMember and not User
    const interactionGuildMember= await interaction.guild.members.fetch(interaction.user.id)

    const nickName = interactionGuildMember.nickname
    const userName = interactionGuildMember.user.username
    // This is GuildMember.id
    const guildMemberId = interactionGuildMember.id
    // This is User.id
    const userId = interactionGuildMember.user.id

    console.log(nickName, userName, userId)
}
  • Related