Search code examples
javascriptnode.jsdiscorddiscord.js

Discord Bot - How to check roles in a DM


I'm using Discord v13 and I'm following the docs here in order to verify if the user that sent a DM message to the bot has the Admin role or not.

client.on('messageCreate', (message) => {
  if (message.member.roles.cache.has('role-id') {
    console.log('User is an admin')
  }
})

It works fine if I send a message to my bot from a channel, which is not what I want. I need the bot to check for the role when the user sends a DM to the bot. However, the member property returns null when I send a DM to the bot.

Is there something that I'm missing? Some intent or partial? These are my intents/partials so far:

const client = new Client({
  intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.DIRECT_MESSAGES],
  partials: ['CHANNEL']
});

I also tried to access the property channel to see if I could fetch the roles but no success. Any hints guys? I would appreciate a lot if someone could help me here. This is the message object that I get when the bot receives a DM:

<ref *1> Message {
channelId: 'channel-id',
guildId: null,
deleted: false,
id: '919665813525495879',
createdTimestamp: 1639335816509,
type: 'DEFAULT',
system: false,
content: '!get-comic',
author: User {
  id: '611561522673745931',
  bot: false,
  system: false,
  flags: UserFlags { bitfield: 0 },
  username: 'deric',
  discriminator: '6024',
  avatar: '0277c05b2fe81cd286dc403b5e88c7ba',
  banner: undefined,
  accentColor: undefined
},
pinned: false,
tts: false,
nonce: '919665812787167232',
embeds: [],
components: [],
attachments: Collection(0) [Map] {},
stickers: Collection(0) [Map] {},
editedTimestamp: null,
reactions: ReactionManager { message: [Circular *1] },
mentions: MessageMentions {
  everyone: false,
  users: Collection(0) [Map] {},
  roles: Collection(0) [Map] {},
  _members: null,
  _channels: null,
  crosspostedChannels: Collection(0) [Map] {},
  repliedUser: null
},
webhookId: null,
groupActivityApplication: null,
applicationId: null,
activity: null,
flags: MessageFlags { bitfield: 0 },
reference: null,
interaction: null
}

Solution

  • Your intents and partials look okay to me. However, in DMs the properties guild, guildId, and member are null. You can see that by reading the docs.

    If you know the guild ID, you can fetch the member by its ID. You can get this user ID from message.author.

    client.on('messageCreate', async (message) => {
      // the ID of the guild the message.author is a member of
      let guildId = '630136153909678321';
      let roleId = '869192198029209314';
    
      try {
        let guild = await client.guilds.fetch(guildId);
        let member = await guild.members.fetch(message.author.id);
    
        if (member.roles.cache.has(roleId)) {
          console.log('User is an admin');
        }
      } catch (err) {
        console.log(err);
      }
    });