I am trying to randomize users into two teams, team 1 and team 2. However, in some scenarios it repeats the same user on both teams.
For example:
Team 1: User 1
Team 2: User 1
The same user would be present on both teams instead of the other users' in the voice channel.
Is there a way to not present the same user twice or just once on one team.
try {
let users = message.member.voice.channel.members.map(member => `<#${member.user.id}>`)
let team1 = users.sort(() => Math.random() - 0.5).slice(0, Math.floor(users.length / 2))
let team2 = users.sort(() => Math.random() - 0.5).slice(Math.floor(users.length / 2))
const embed = new MessageEmbed()
.setTitle("Teams Created")
.setDescription(`Team 1: ${team1.join(', ')}\nTeam 2: ${team2.join(', ')}`)
.setColor("#36393E")
.setTimestamp()
message.channel.send(embed)
} catch (error) {
console.log(error)
const errorembed = new MessageEmbed()
.setTitle("⚙️ Error")
.setDescription(`An error has occured. Please try again`)
.setColor("#36393E")
.setFooter("If this error has occured multiple times, please contact the developer.")
.setTimestamp()
await message.channel.send("There was an error. Please try again.")
}
Once you have filled team1, you shouldn't users.sort() again, because once the first team is defined, the second one is also defined. If you sort again, you are giving the chance for that to happen. You just have to put in team2 the users that are not in team1.
let team2=users.filter(!(user=> team1.includes(user)));
I dont know right now if that line is correct, but it should be something like that.
Related
if(message.content == `${config.prefix}mods`) {
const ListEmbed = new Discord.MessageEmbed()
.setTitle('Mods:')
.setDescription(message.guild.roles.cache.get('813803673703809034').members.map(m=>m.user.tag).join('\n'));
message.channel.send(ListEmbed);
}
Hey so iam making a command which displays all the members with that role but it only seems to be sending 1 of the mods
await message.guild.roles.fetch();
let role = message.guild.roles.cache.find(role => role.id == args[0]);
if (!role) return message.channel.send('Role does not exist'); //if role cannot be found by entered ID
let roleMembers = role.members.map(m => m.user.tag).join('\n');
const ListEmbed = new Discord.MessageEmbed()
.setTitle(`Users with \`${role.name}\``)
.setDescription(roleMembers);
message.channel.send(ListEmbed);
};
Make sure your command is async, otherwise it will not run the await message.guild.roles.fetch(); - this fetches all roles in the server to make sure the command works reliably.
In Discord.jsV12 the get method was redacted and find was implemented.
Aswell as this, I would highly recommend defining variables to use in embeds and for searching since it is much more easy to error trap.
If you have many members with the role, you will encounter the maximum character limit for an embeds description. Simply split the arguments between multiple embeds.
I'm somewhat new to coding and I am making a bot in discord.js v12 and I was wondering how I could add verification for new users who join the server. Weather than be sending them a captcha they must complete or just adding a reaction role that they click and it gives them x role such as "member" or "verified." Thanks in advance :D
I have actually just recently created one of those using a very simple method of creating two questions and answers arrays and checking if the user's input matches the answer.
So, first off you'll want to create 2 arrays:
const questions = ['Do you like melon?', 'Do you want melon?']
const answers = ['Yes!', 'What do you want from me...']
Then you can get a randomized question that would match the answer:
var randomIndex = Math.floor(Math.random() * questions.length)
var randomQuestion = questions[randomIndex]
var randomAnswer = answers[randomIndex]
And finally, you can send the question and check if the answer matches:
message.channel.send(randomQuestion)
client.on('message', message => {
if (message.content === randomAnswer) {
let role = message.guild.roles.cache.find(r => r.name === "Member")
message.member.roles.add(role)
message.channel.send('Congratulations! you've completed the verification!');
} else {
message.channel.send('Verification failed. Incorrect answer.');
}
});
im making discord bot with discord.js v12 and im trying to give role when member has 10 invites
i found invitation code from here and modified it:
if(message.channel.type != "dm" && message.channel.id === '768475421953915093') {
message.delete();
var user = message.author;
message.guild.fetchInvites()
.then
(invites =>
{
const userInvites = invites.array().filter(o => o.inviter.id === user.id);
var userInviteCount = 0;
for(var i=0; i < userInvites.length; i++)
{
var invite = userInvites[i];
userInviteCount += invite['uses'];
}
if(userInviteCount >= 10){
const guildMember = message.member;
guildMember.addRole('767542365812886656');
message.author.send(`you have access now`)
}else {
message.author.send(`sry u have ${userInviteCount} invitations. u need at least five`)
}
}
)
}
yes, it works but you can trick the system easily. If you keep rejoining from the server, the invite counter increases. How can i stop that?
To do this, you will need an external database since Discord API doesn't provide any information about who used that invite and how many times.
ALERT: It's a simple feature but can be very hard for people that don't have any coding experience, so if it's your first project, don't give up and keep trying! :D
You can use MongoDB Atlas, which is very simples and free.
And the logic will be very simple:
1 - Create a collection to store the invites data, you can do something like in this example
2 - Create a collection (you can give any name, but in this example, I will refer to this collection as new_members) to store the new members data, it should have the fields serverId (to store the guild ID), userId (to store the user ID) and inviteCode (to store the invite code or url)
3 - When a user joins the discord server, it will trigger the "guildMemberAdd" event, and you will get the invite that was used (with the example that I give in the first step), and create a new doc in the new_members collection.
4 - After creating this new data, you will search for all the docs from the same invite, and filter them by userId (there are many ways to do this, this is one of them).
5 - With this array of docs, you can use his length to determine how many people were invited, and give the role.
VERY SIMPLE EXAMPLE, THAT SHOULDN'T BE USED:
DiscordClient.on("guildMemberAdd", async (member) => {
/**
* https://github.com/AnIdiotsGuide/discordjs-bot-guide/blob/master/coding-guides/tracking-used-invites.md
* Here you will get the invite that was used, and store in the "inviteCode" variable
*/
const inviteCode = await getInviteUsed()
await NewMemberRepository.insert({
serverId: member.guild.id,
userId: member.id,
inviteCode: inviteCode
});
const joinedMembersFromTheInvite = await NewMemberRepository.find({
inviteCode: inviteCode
});
/**
* https://stackoverflow.com/questions/43374112/filter-unique-values-from-an-array-of-objects
* Here you will filter the results by userId
*/
const invitesWithUniqueUsers = filterJoinedMembersByUserId(joinedMembers)
if (invitesWithUniqueUsers >= REQUIRED_INVITES_QTD) {
/**
* Gives the role to the creator of the invite
*/
}
});
Hope it helps, good luck! :D
OBS:
Yes, Discord API provides how many times an invite was used, but not how many a specific person used this invite.
In the examples, I used something like TypeORM, but if you are using JavaScript instead TypeScript, you can use Mongoose
Currently, I have a command in my bot where it will react to anything with discord.gg in the message. I want the bot to be able to post the embed message each time a discord invite is posted, but delete the last embed message it sent so it would look like the bot is keeping one specific message at the end of a channel.
This is what the code looks like right now, thank you for your help!
let keyword15 = ["discord.gg"];
if (msg.author.bot) return;
if((msg.content.toLowerCase().includes(keyword15) )
){
const embed2 = new Discord.MessageEmbed()
.setDescription('Promotion Operator \n ▫️ **Do not post outside the advertisement channel.** \n ▫️ **Do not advertise your server via DM.**')
.setColor(0x000000)
msg.channel.send(embed2);
}
I wouldn't know how to delete the last embed but, I have came up with another solution you could try.
let keyword15 = ["discord.gg"];
if (msg.author.bot) return;
if((msg.content.toLowerCase().includes(keyword15) )
){
const embed2 = new Discord.MessageEmbed()
.setDescription('Promotion Operator \n ▫️ **Do not post outside the advertisement channel.** \n ▫️ **Do not advertise your server via DM.**')
.setColor(0x000000)
msg.channel.send(embed2).then(msg => {
msg.delete(300000)
});
}
that there will delete the embed after 5 minutes, You can always change the time, Just keep in mind discord uses milliseconds so if you want to use 10 minutes you would have to put in 600000, etc.
I'm making a discord bot that will has a feature to move user's to a random voice channel if they want. I searched the internet 3 hours straight and checked the whole documentation. But still can't find anything.
note : I know this bot idea looks useless. But that's what I need.
code :
let voiceChannels = message.guild.filter(g => **idk how to check if it's vc** );
that's what I just found in 3 hours.
You'd need to access the guild's channels and then choose a random channel of type voice.
So in your case, it'd be:
let voiceChannel = message.guild.channels.cache.filter((channel) => channel.type === "voice").random();
if (!message.member.voice.channel) return message.reply("User is not in a voice channel");
await message.member.voice.setChannel(voiceChannel);