When I'm online the bot gives me a role, as soon as I go offline the bot removes that role from me.
When it removes the role, I want the bot to give the role to a specific user. How can I do that?
I have my current code below:
client.on('presenceUpdate', (oldPresence, newPresence) => {
const member = newPresence.member;
if (member.id === 'user.id') {
if (oldPresence.status !== newPresence.status) {
var gen = client.channels.cache.get('channel.id');
if (
newPresence.status == 'idle' ||
newPresence.status == 'online' ||
newPresence.status == 'dnd'
) {
gen.send('online');
member.roles.add('role.id');
} else if (newPresence.status === 'offline') {
gen.send('offline');
member.roles.remove('role.id');
}
}
}
});
You could get the other member by its ID. newPresence
has a guild
property that has a members
property; by using its .fetch()
method, you can get the member you want to assign the role to. Once you have this member, you can use .toles.add()
again. Check the code below:
// use an async function so we don't have to deal with then() methods
client.on('presenceUpdate', async (oldPresence, newPresence) => {
// move all the variables to the top, it's just easier to maintain
const channelID = '81023493....0437';
const roleID = '85193451....5834';
const mainMemberID = '80412945....3019';
const secondaryMemberID = '82019504....8541';
const onlineStatuses = ['idle', 'online', 'dnd'];
const offlineStatus = 'offline';
const { member } = newPresence;
if (member.id !== mainMemberID || oldPresence.status === newPresence.status)
return;
try {
const channel = await client.channels.fetch(channelID);
if (!channel) return console.log('Channel not found');
// grab the other member
const secondaryMember = await newPresence.guild.members.fetch(secondaryMemberID);
if (onlineStatuses.includes(newPresence.status)) {
member.roles.add(roleID);
secondaryMember.roles.remove(roleID);
channel.send('online');
}
if (newPresence.status === offlineStatus) {
member.roles.remove(roleID);
secondaryMember.roles.add(roleID);
channel.send('offline');
}
} catch (error) {
console.log(error);
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.