首页 > 解决方案 > 如果成员在自定义状态中有邀请,则添加角色

问题描述

我希望我的机器人给一个成员一个角色,如果他们有服务器邀请在他们的状态。有谁知道我该怎么做?也许您可以获取成员信息或其他内容?我试着在谷歌上搜索,但我什么也没找到。非常感谢:)

标签: discorddiscord.js

解决方案


获取自定义状态

正如 Squidleton 所说,您可以使用 的.activities属性Presence来获取用户的自定义状态。此属性是一个Activitys 数组,您可以通过查找其.type为的活动来获取自定义状态CUSTOM_STATUS

自定义状态的活动如下所示:

Activity {
  name: 'Custom Status',
  type: 'CUSTOM_STATUS',
  url: null,
  details: null,
  state: 'this is the status message',
  applicationID: null,
  timestamps: null,
  party: null,
  assets: null,
  syncID: undefined,
  flags: ActivityFlags { bitfield: 0 },
  emoji: null,
  createdTimestamp: 1625478958735
}

如您所见,状态消息存储在state属性中。

/**
 * The custom status message of `member`,
 * or `undefined` if the member does not have a custom status.
 * @type {string | undefined}
 */
const customStatus = member.presence.activites
  .find(activity => activity.type === 'CUSTOM_STATUS')
  ?.state

检查状态是否包括邀请

您可以使用该String.prototype.includes方法来测试一个字符串是否包含另一个字符串:

const inviteLink = 'https://discord.gg/blahblah'

if (customStatus) {
  /**
   * Whether `customStatus` has the invite link `inviteLink`.
   * @type {boolean}
   */
  const hasInviteLink = customStatus.includes(inviteLink)
}

如果您愿意,您可以更进一步,测试自定义状态是否包含来自服务器的任何邀请,使用Guild#fetchInvitesinviteCreate客户端事件的组合。

添加角色

现在您需要做的就是为该成员添加角色

if (hasInviteLink) {
  member.roles.add(theRoleYouWantToAdd)
    // Don't forget to handle errors!
    .catch(console.error)
}

theRoleYouWantToAdd可以是 aRole或角色的 ID。

我把这段代码放在哪里?

Discord.js 有一个presenceUpdate事件,当成员的状态(例如他们的自定义状态)更新时触发。请注意,您需要启用GUILD_PRESENCES接收此事件的意图(有关更多信息,请参阅此答案)。

最终代码可能如下所示:

const roleID = // ...
const inviteLink = // ...

client.on('presenceUpdate', (_oldPresence, newPresence) => {
  const member = newPresence.member
  if (member) {
    // Ignore members who already have the role
    if (!member.roles.cache.has(roleID)) {
      const customStatus = newPresence.activites
        .find(activity => activity.type === 'CUSTOM_STATUS')
        ?.state
      if (customStatus) {
        if (customStatus.includes(inviteLink)) {
          member.roles.add(roleID)
            .catch(console.error)
        }
      }
    }
  }
})

推荐阅读