discord - 如果成员在自定义状态中有邀请,则添加角色
问题描述
我希望我的机器人给一个成员一个角色,如果他们有服务器邀请在他们的状态。有谁知道我该怎么做?也许您可以获取成员信息或其他内容?我试着在谷歌上搜索,但我什么也没找到。非常感谢:)
解决方案
获取自定义状态
正如 Squidleton 所说,您可以使用 的.activities
属性Presence
来获取用户的自定义状态。此属性是一个Activity
s 数组,您可以通过查找其.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#fetchInvites
和inviteCreate
客户端事件的组合。
添加角色
现在您需要做的就是为该成员添加角色:
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)
}
}
}
}
})
推荐阅读
- performance - Unable to release GPU memory after training a CNN model using keras
- c++ - Synchronize object
- javascript - Recursion logic is not working in Javascript
- php - 使用 PHP 读取大型 .xls 文件
- url - If it is valid that Wikipedia uses Chinese characters (and other unicode characters) in URL
- c# - how to get singleton instance in another class
- python - 使用多个条件语句逐行矢量化 pandas df
- c# - 如何在 Open API Specification 3.0 中添加 allof 类型?
- python-3.x - Only One Pod is consuming all the computing resource although specified the limits and requests resources in pod template
- javascript - 数据表排序问题