【问题标题】:Discord Bot - How to check roles in a DMDiscord Bot - 如何检查 DM 中的角色
【发布时间】:2022-01-16 11:05:13
【问题描述】:

我正在使用 Discord v13,并在此处关注 docs,以验证向机器人发送 DM 消息的用户是否具有 Admin 角色。

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

如果我从频道向我的机器人发送消息,它工作正常,这不是我想要的。当用户向机器人发送 DM 时,我需要机器人检查角色。但是,当我向机器人发送 DM 时,member 属性会返回 null

我有什么遗漏的吗?一些意图或部分?到目前为止,这些是我的意图/部分:

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

我还尝试访问属性channel 以查看是否可以获取角色,但没有成功。有什么提示吗?如果有人可以在这里帮助我,我将不胜感激。这是当机器人收到 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
}

【问题讨论】:

    标签: javascript discord.js


    【解决方案1】:

    你的意图和部分在我看来没问题。但是,在 DM 中,属性 guildguildIdmembernull。您可以通过阅读文档来了解这一点。

    如果你知道公会ID,你可以通过它的IDfetch the member。您可以从message.author 获取此用户 ID。

    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);
      }
    });
    

    【讨论】:

    • 非常感谢!!它就像一个魅力!
    • 不客气,我很高兴它成功了
    猜你喜欢
    • 1970-01-01
    • 2020-09-02
    • 2021-06-04
    • 2020-06-29
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    相关资源
    最近更新 更多