如果成员具有自定义状态的邀请,则添加角色

时间:2021-07-03 17:40:54

标签: discord discord.js

如果服务器处于邀请状态,我希望我的机器人为成员提供一个角色。有谁知道我怎么能做到这一点?也许你可以获取会员信息之类的?我尝试在谷歌上搜索,但一无所获。 非常感谢:)

1 个答案:

答案 0 :(得分:0)

获取自定义状态

正如 Squiddleton 所说,您可以使用 Presence.activities 属性来获取其用户的自定义状态。此属性是一个 Activity 数组,您可以通过查找 .typeCUSTOM_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 客户端的组合测试自定义状态是否包含来自服务器的any邀请活动。

添加角色

现在您只需为该成员add the role

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

theRoleYouWantToAdd 可以是 Role 或角色的 ID。

我把这个代码放在哪里?

Discord.js 有一个 presenceUpdate 事件,当成员的状态(例如他们的自定义状态)更新时会触发该事件。请注意,您需要启用 GUILD_PRESENCES Intent 才能接收此事件(有关详细信息,请参阅 this answer)。

最终代码可能如下所示:

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