How can I add role to user for specified time? - discord

How can I add role to user for specified time?
E.g: user get role and after 24h bot remove this role from user.

// <member> is a placeholder for a GuildMember object.
// See link below to find the difference between user object and guildmember object.
// You can get a member with guild.fetchMember(),
// Or with guild.member() if the member is already cached.
<member>.roles.add(role); // GuildMember .add() method (add role to member)
setTimeout(() => { // evaluates expression after x number of miliseconds
<member>.roles.remove(role) // function to evaluate (GuildMember .remove() method)
// do something else maybe
}, 86400000) // 24 hours in ms
GuildMember Info
guild.FetchMember() Method
guild.member() Method
GuildMember .add() and .remove() Method Docs
setTimeout() Method

Related

Trying to delete all messages sent by a user with a certain role unless the message is !verify

I'm trying to make a verification system. Members are supposed to type !verify. If they don't type that, I want my bot to delete the sent message.
module.exports = {
client.on('message', (message) => {
if (message.member.roles.cache.has('793205873949278279')){
if (!message.content === '!verify') {
message.delete({ timeout: 1 });
}
}
})
}
'message.member.roles' returns an array of role objects the message author has.
If you'd like to find out whether the user has the corresponding role or not, you would first want to get the role using its ID (or name if preferred) and only then check if the user has it.
const role = message.guild.roles.cache.get('role id here') // Gets the role object using it's ID
if (!message.member.roles.cache.has(role)) return // The command will not be executed if the user does not have the corresponding role
One more thing to note: It seems like you're trying to delete the message after one millisecond - Which let's be honest is quite useless since you'll never notice the difference if it's 0 or 1 milliseconds - So my advice is to either delete it after 1000 milliseconds (1 second) if that's what you wanted to do, or not set a timeout at all.

How to check the role of a reacting member discord.js

I'm fairly new to discord.js and have recently ran into a problem with a section of my code.
if (reaction.message.member.roles.cache.some(role => role.name == "Goof Archivist 📚")) {
This section is supposed to check if a reacting member has the role "Goof Archivist 📚". But instead checks the role of the person that sent the message that is being reacted to. if that makes sense. any help would be appreciated.
You can use the second parameter of the messageReactionAdd event, the User that reacted, and the Guild.member() method.
Guild.member() can convert a global user object to a guildmember object in which you can see the roles of. To learn the difference between the two, check out What is the difference between a User and a GuildMember in discord.js?.
if (
reaction.message.guild
.member(user)
.roles.cache.some((role) => role.name == 'Goof Archivist 📚')
)

Add / Remove user from role by ID [DISCORD.JS]

Hey today I'd like give and remove roles from a user by their ID
First try:
const user = '5454654687868768'
const role = '451079228381724672'
user.roles.remove(role)
Second Try:
const user = '5454654687868768'
const role = '451079228381724672'
user.removeRole(role)
Neither one of these methods seems to work, however.
const user = '5454654687868768'
const role = '451079228381724672'
These are just numbers which happen to be the id of your user and role object. They are nothing on their own and you can't call any Discordjs methods on them. To get the user and role object you will first have to get them using their respective ID.
Let's assume you want to add a role when someone joins the server, you can do the same thing in any type of event but we will use guildMemberAdd event for example:
bot.on('guildMemberAdd', async member => {
const memberID = '5454654687868768'; // you want to add/remove roles. Only members have roles not users. So, that's why I named the variable memberID for keeping it clear.
const roleID = '451079228381724672';
const guild = bot.guilds.cache.get('guild-ID'); // copy the id of the server your bot is in and paste it in place of guild-ID.
const role = guild.roles.cache.get(roleID); // here we are getting the role object using the id of that role.
const member = await guild.members.fetch(memberID); // here we are getting the member object using the id of that member. This is the member we will add the role to.
member.roles.add(role); // here we just added the role to the member we got.
}
See these methods are only working because they are real discordjs objects and not some numbers like you were trying to do. Also the async/await thing is there because we need to wait for the bot to get the member object from the API before we can add role to it.
Your first try was actually not that far off. The only problem is that roles.remove() is a guildMember function.
So first we need to define the member.
const member = message.guild.members.cache.get("member ID here");
Now we can remove or add a role. Source
member.roles.remove("role ID here");

How to make code that removes roles from people randomly by guild position

I'm developing a bot where at a set interval, like every hour the bot will pick a random user and remove a role from them, it will be using the positioning on the side to do this. The problem was I couldn't really find a function in Discord.JS that had a property for a guild member's position on the side.
I've tried finding other bots that do this and try to mimic them, but I didn't find anything.
I double checked the documentation but didn't find anything.
var thatguild = message.guild.id.find(`576463944298790929`);
thatguild.fetchMembers();
setInterval(function() {
let sizes = thatguild[Math.floor(Math.random() * thatguild.members.size())];
if(thatguild.member.id == `userid1` || `userid2`)
return(thatguild.member.removeRole('roleid'))
}, 1000)
I expect a bot where it randomly picks a user by the position, and remove a role from the member.
What I actually get is code and no way of knowing if it works or not.
Explanation:
Let's go through what we need to do if we want to accomplish what you want.
Acquire the desired guild.
A collection of guilds (GuildStore in master) a client is handling is available with Client.guilds.
To find a value by its key, use Map.get().
To find a value by another property or testing of an expression, use Collection.find().
To simply use the guild the message was sent in within a message event, use message.guild.
Acquire the desired role.
A collection of roles within a guild (GuildMemberRoleStore in master) a client is handling is available with Guild.roles.
Refer to the options previously listed to obtain a value from the collection.
Select a random member.
A collection of a guild's members (GuildMemberStore in master) is available with Guild.members.
Before selecting a member, the possible choices need to be limited to those with the role, so use Collection.filter().
To select a random value from a collection, use Collection.random().
Remove the role from the member.
To remove a role from a member, use GuildMember.removeRole() (GuildMember.roles.remove() in master).
If something goes wrong, make sure to catch the returned promise with a try...catch statement or catch() method.
Set an interval.
To set an interval, use setInterval().
In case something goes wrong, assign it to a variable so it can be cleared later.
Code:
function roleRoulette(guild, role) {
const possible = guild.members.filter(m => m.roles.has(role.id));
if (possible.size === 0) return clearInterval(interval);
const member = possible.random();
member.removeRole(role)
// MASTER: member.roles.remove(role)
.then(() => console.log(`Removed ${role.name} from ${member.tag}.`))
.catch(err => {
console.error(err);
clearInterval(interval);
});
}
const guild = client.guilds.get('576463944298790929');
if (!guild) return;
const role = guild.roles.get('576464298088333323');
if (!role) return;
const interval = setInterval(roleRoulette(), 60 * 1000, guild, role);
Discord.js Docs:
stable
master
It's honestly a bit hard to understand what you exactly want. I understand you want the bot to remove a random role from a random member at a set interval. Also, you want to do that based on the role hirarchy somehow, I'm guessing the highest role first? If that is the case, what you could try is this:
let randomMember = message.guild.members.cache.random()
if(randomMember.roles.cache.length === 0) return
let roleToRemove = randomMember.roles.cache.first()
for (let r in randomMember.roles.cache){
if(r.position < roleToRemove.position) roleToRemove = r;
}
await randomMember.roles.remove(roleToRemove)
Well, no matter what, if you are looking to remove roles based on their position then role.position will be required for your code in some way.
https://discord.js.org/#/docs/discord.js/main/class/Role?scrollTo=position
Good luck :)
Edit: Don't forget to exclude bots and bot roles from the removal when you implement something like this!
This is probably what I wanted:
Every hour, the bot picks a random user from the entire guild, removes a specific role from them, and repeats.
It's still hard to understand what past-me actually wanted, but here's another answer.
I don't know what version of D.JS was hot at the time, but I'm gonna use v9 in my answer.
You want an interval removing members every hour, so 1000 * 60 * 60 means 1000 milliseconds, 60 times -> 60 seconds(1 minute) * 60 times -> 1 hour.
This function inside the interval needs* to be async, so we can request a guild with ALL the members.
Then, we get the members collection and filter it in a way to remove users that don't have the role we're looking for OR if they are in an ignore list.
If no members have a role, don't do anything.
Else, pick a random member and remove the role. Repeat.
var ignore = ['...'];
var guildSel = client.guilds.get('...');
var role2Remove = '...';
setInterval(async () => {
var guild = await guildSel.fetchMembers();
var members = guild.members.filter(m=>m.roles.has(role2Remove) && !ignore.includes(m.id));
if(members.size > 0) {
var randUsr = members.random();
randUsr.removeRole(role2Remove);
} else return;
}, 1000 * 60 * 60);

Using emotes to give roles Discord.js

In my discord server, as a verification method, I want my bot to have all users react to the message and then get given the verified role, and remove the old role. The current code I have doesn't grant or remove roles, but doesn't error.
client.on("messageReactionAdd", function(users) {
users.addRole(users.guild.roles.find("name", setup.verify));
users.removeRole(users.guild.roles.find("name", setup.default));
});
There is a problem in the current code. The messageReactionAdd event returns a User object, which does not contain the property .guilds which you attempt to access: users.guilds.r- .
Instead of this perhaps you should the id of the User object and plug that into message.guild.members.get("id here"). Then use the returned Member object with your current code. That should work!
References:
Guild Member
, Message Reaction Event, User Object
Would something like this work?
I'm not sure it will I haven't tested it. This should add the role if the message they reacted to consists of the word "role1" and if they react to a different message it will remove the role. I don't know if this is what you're going for but in theory this should work.
client.on("MessageReactionAdd", function(users) {
if (message.content === "role1") {
users.addRole(users.guild.roles.find("name", setup.verify))
} else if (!message.content === "role1") {
user.removeRole(users.guild.role.find("name", setup.default))
}
});
Are the names of the roles; setup.verify & setup.default?
If not, that's why it is not working.
Try:
client.on("messageReactionAdd", function(users) {
users.addRole(users.guild.roles.find("id", ROLEIDHERE));
users.removeRole(users.guild.roles.find("id", ROLEIDHERE));
});
where ROLEIDHERE put the role id to find the role id just tag the role and before you hit send put \ before the tag and it will supply the id

Resources