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.');
}
});
Related
Im trying to make discord.js code. When a member joins the voice channnel I want the bot to give them a role, when the member leaves, i want the role to be removed. thanks for your help.
const newChannelID = newState.channelID;
const oldChannelID = oldState.channelID;
if (oldChannelID === "835280102764838942"){
member.send('role given');
let role = message.guild.roles.cache.find(r => r.id === "835279162293747774");
member.roles.add(835279162293747774);
} else if(newChannelID === "835280102764838942"){
member.send('role removed');
member.roles.remove(835279162293747774);
}
})
There's a couple of things you need to clean up in your code. I'm going to assume you're using the voiceStateUpdate event to trigger your command.
Most importantly, (logic-wise) you actually need to flip-flop the way you add and remove roles. Currently, the general code states that if the user left the voice channel (thus oldChannelID = actual vc ID), then it would actually give the user a role. This seems to be the opposite of your intention, thus you'd simply swap out the code in each if/else if statement.
Second, the way you're assigning roles and adding them is incorrect. I'd recommend this resource for more info.
Third, you cannot access message if you were indeed using voiceStateUpdate as your event, since it only emits an oldState and a newState.
Lastly, you need to designate a text channel to send the message to. In my code, I manually grabbed the ID of the channel I wanted and plugged it into the code. You'll have to do the same by replacing the number strings I have with your own specific ones.
With that being said, here's the correct modified code:
client.on('voiceStateUpdate', (oldState, newState) => {
const txtChannel = client.channels.cache.get('803359668054786118'); //manually input your own channel
const newChannelID = newState.channelID;
const oldChannelID = oldState.channelID;
if (oldChannelID === "800743802074824747") { //manually put the voice channel ID
txtChannel.send('role removed');
let role = newState.guild.roles.cache.get("827306356842954762"); //added this
newState.member.roles.remove(role).catch(console.error);
} else if (newChannelID === "800743802074824747") {
txtChannel.send('role given');
let role = oldState.guild.roles.cache.get("827306356842954762"); //change this somewhat
oldState.member.roles.add(role).catch(console.error); //adding a catch method is always good practice
}
})
This is my code and It seems the random user selection is broken although it works completely fine in another command I have that pings a random user
client.on('message', message => {
if (message.content.toLowerCase() === `${prefix}command`) {
const userList = message.guild.members.cache.array();
var randomNumber = Math.floor(Math.random() * userList.length)
var dm = userList[randomNumber]
console.log(dm.user.id)
dm.send("123");
}
ok, so the code you have written works just fine. The problem is that your bot cannot send a message to its self. There is a very easy solution to this. Just check if the selected member is a bot and return if that's the case. Note: I put your random number inside the array field of the userList.
const userList = message.guild.members.cache.array();
var dm = userList[Math.floor(Math.random() * userList.length)];
if (dm.user.bot) return;
console.log(dm.user.username);
dm.send("123");
Note: If you only have yourself and the bot on your test server then this will only ever send a DM to you. In that case I would recommend getting a secondary account and inviting some friends to the test server.
Have you enabled the members intent? The members list only shows you and the bot if you don't have that intent enabled. Read the docs for intents for more information.
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.
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
I'd like to auto set roles for new users when they join server X, problem is that this bot is on server Y as well, and server Y doesn't have the role.
client.on('guildMemberAdd', member => {
console.log('User ' + member.user.tag + ' has joined Steampunk.');
var role = member.guild.roles.find(x => x.name === "name");
member.addRole('247442955651121154');
})
I was hoping that I could do a simple check before applying the role, if user have joined server X, add the role, if else, do nothing. So far my attempts have failed.
Any input would be appreciated!
The original code is trying add a specific role you put in, and not the role you just looked up a line before that. There shouldn't be any issues with other servers the bot is in, because member.guild gives the guild of the member object, and since this member object is coming from a guildMemberAdd it means that member.guild will only return the guild that was just joined. The code in the edit has a lot of strange things going on, though.
The first issue I see is that in order to look through the channels in a guild, you have to use guild.channels.cache.find(), guild.channels.find() is old now and doesn't work in v12. Same goes for client.guild, guild.roles, etc. The part at the bottom of your edited code doesn't seem to make much sense at all. The code should get the roles of the newly joined guild (member.guild.roles.cache), look through them to find the role you want (you did this correctly with the .find()) and then apply the role to the member. Neither server nor role ever get used in your code, and guild.id is a property, not a method.
Let me know if you need help following these instructions, although it looks like you should be able to do it now. Always look at the discord.js docs first to check properties, methods, etc.
I ended up defining the guild in question by name, saved it as a const, and made a check for the specific guild.
If your bot is on several servers but you only want the greet/addRole on a specific one, all integrated into the message displayed on joining;
//Welcome message and autorole for specific server and channel.
client.on('guildMemberAdd', member => {
const = client.guilds.find(guild => guild.name === "Steampunk");
if (!guild) return;
const channel = member.guild.channels.find(ch => ch.name === "greetings");
if (!channel) return;
let botembed = new Discord.RichEmbed()
.setColor("#ff9900")
.setThumbnail(member.user.avatarURL)
.setDescription(`${member} Welcome to the Ark Steampunk Sponsored Mod Discord!\nPlease report all <#244843742568120321> and if u need any help view or ask your question in <#334492216292540417>. Have any ideas we got a section for that too <#244843792132341761>. Enjoy!:stuck_out_tongue: Appreciate all the support! <http://paypal.me/ispezz>`)
.setTimestamp()
.setFooter("Steampunk Bot", client.user.avatarURL);
channel.send(botembed);
console.log('User ' + member.user.tag + ' has joined ' + member.guild.name + '.');
var role = member.guild.roles.find(x => x.name === "name");
member.addRole('247442955651121154');
});