I was working on a discord bot and for a verification channel. I want users to type only the /verify command: every message or command except /verify they type should get deleted automatically. How can I do this?
Current code:
if (command === "verify") {
if (message.channel.id !== "ChannelID") return;
let role = message.guild.roles.find(rol => rol.name === 'Member')
const reactmessage = await message.channel.send('React with 👌 to verify yourself!');
await reactmessage.react('👌');
const filter = (reaction, user) => reaction.emoji.name === '👌' && !user.bot;
const collector = reactmessage.createReactionCollector(filter, {
time: 15000
});
collector.on('collect', async reaction => {
const user = reaction.users.last();
const guild = reaction.message.guild;
const member = guild.member(user) || await guild.fetchMember(user);
member.addRole(role);
message.channel.send(`Verification Complete.. ${member.displayName}. You have got access to server. `)
});
message.delete();
}
You can add a check at the top of your client.on('message') listener:
client.on('message', message => {
let verified = !!message.member.roles.find(role => role.name == 'Member');
// ... command parsing ect...
if (!verified && command == 'verify') {...}
else if (verified) {
// other commands...
}
});
Related
I am trying to make it so when you get to a certain amount of reactions my bot will send a message and if somebody can help here is my code
.then(function(sentMessage) {
sentMessage.react('👍').catch(() => console.error('emoji failed to react.')).message.reactions.cache.get('👍').count;
const filter = (reaction, user) => {
return reaction.emoji.name === '👍' && user.id === message.author.id;
};
message.awaitReactions(filter, { max: 2, time: 00, errors: ['time'] })
.then(collected => console.log(collected.size))
.catch(collected => {
console.log(`After a minute, only ${collected.size} out of 4 reacted.`);
});
});
})
Instead of awaitReactions, you could also use createReactionCollector which is probably easier to use and its collector.on() listeners are more readable than awaitReactions's then() and catch() methods.
You won't need to use message.reactions.cache.get('👍').count to check the number of reactions, as the end event fires when you reached the maximum and you can send a message inside that.
Also, in your filter, you don't need to check if user.id === message.author.id as you will want to accept reactions from other users. However, you can check if !user.bot to make sure that you won't count the bot's reaction. You can also remove the time option if you don't want to limit the time your bot collects reactions.
Another error was that you called .awaitReactions() on the message itself not the sentMessage.
Check out the working code below:
// v12
client.on('message', async (message) => {
if (message.author.bot || !message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
const MAX_REACTIONS = 2;
if (command === 'react') {
try {
// send a message and wait for it to be sent
const sentMessage = await message.channel.send('React to this!');
// react to the sent message
await sentMessage.react('👍');
// set up a filter to only collect reactions with the 👍 emoji
// and don't count the bot's reaction
const filter = (reaction, user) => reaction.emoji.name === '👍' && !user.bot;
// set up the collecrtor with the MAX_REACTIONS
const collector = sentMessage.createReactionCollector(filter, {
max: MAX_REACTIONS,
});
collector.on('collect', (reaction) => {
// in case you want to do something when someone reacts with 👍
console.log(`Collected a new ${reaction.emoji.name} reaction`);
});
// fires when the time limit or the max is reached
collector.on('end', (collected, reason) => {
// reactions are no longer collected
// if the 👍 emoji is clicked the MAX_REACTIONS times
if (reason === 'limit')
return message.channel.send(`We've just reached the maximum of ${MAX_REACTIONS} reactions.`);
});
} catch (error) {
// "handle" errors
console.log(error);
}
}
});
If you're using discord.js v13, there are a couple of changes:
you'll need to add the GUILD_MESSAGE_REACTIONS intents
the message event is now messageCreate
the collector's filter is inside the options object
// v13
const { Client, Intents } = require('discord.js');
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
],
});
const prefix = '!';
client.on('messageCreate', async (message) => {
if (message.author.bot || !message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
const MAX_REACTIONS = 2;
if (command === 'react') {
try {
// send a message and wait for it to be sent
const sentMessage = await message.channel.send('React to this!');
// react to the sent message
await sentMessage.react('👍');
// set up a filter to only collect reactions with the 👍 emoji
// and don't count the bot's reaction
const filter = (reaction, user) => reaction.emoji.name === '👍' && !user.bot;
// set up the collecrtor with the MAX_REACTIONS
const collector = sentMessage.createReactionCollector({
filter,
max: MAX_REACTIONS,
});
collector.on('collect', (reaction) => {
// in case you want to do something when someone reacts with 👍
console.log(`Collected a new ${reaction.emoji.name} reaction`);
});
// fires when the time limit or the max is reached
collector.on('end', (collected, reason) => {
// reactions are no longer collected
// if the 👍 emoji is clicked the MAX_REACTIONS times
if (reason === 'limit')
return message.channel.send(`We've just reached the maximum of ${MAX_REACTIONS} reactions.`);
});
} catch (error) {
// "handle" errors
console.log(error);
}
}
});
And the result:
You want to check the collected.size with an if statement like so:
let amount = 4; // any integer
if (collected.size /* returns an integer */ === amount) {
console.log(`Got ${amount} reactions`)
}
Hope I got the issue right.
If I understand it correctly, then you can just change the parameters for the awaitMessage method. You can remove the time: 00, errors: ['time'] arguments since they're optional and keep the max: 2. That way, the function will only finish once there are 2 reactions (in this case).
I would recommend removing the user.id === message.author.id; from the filter since it seems like you want multiple users to react to the message.
For more information, you can check the discord.js guide or the documentation for awaitReactions.
Code:
message.channel.send("Message reacting to.").then(function (sentMessage) {
sentMessage.react('👍').catch(() => console.error('emoji failed to react.'));
const filter = (reaction, user) => {
return reaction.emoji.name === '👍';
};
message.awaitReactions(filter, { max: 2 })
.then(collected => console.log(collected.size))
});
What I'm trying to do is to get username for users who reacts on that message. It's working good but when the bot restarts only new reactions work.
how to make it send all users reactions
client.on('ready', () => {
client.guilds.get('guild_id').channels.get('chnl_id').fetchMessage('msg_id');
});
client.on('messageReactionAdd', (reaction, user) => {
const { message} = reaction;
if(message.channel.id == 'chnl_id'){
if(reaction.emoji.name === "✅") {
message.guild.fetchMember(user.id).then(member => {
if(user.bot) return;
else {
message.channel.send(reaction.users.map(u => u.username.toString()))
}
})
}}});
If you have the message, then you can filter the reaction of that message by emojis:
const reaction = await message.reactions.cache.filter(r=> r.emoji.name === '✅').first().fetch();
Then you can fetch all reactions with that specific emoji:
await reaction.users.fetch();
Then you can filter from that if you want to (for example your own bot), with:
const filteredReactions = reaction.users.cache.filter(r=> !r.bot);
And don't forget to put these in an async function.
I want my staff role can edit, delete this created channel.
client.on('message', message =>{
if (!message.content.startsWith('*open-channel')) return; //This line for some bug happens in my bot
if (message.channel.id !== '759430340972118026') return; // I set a channel for the users can only use
//this command in
if(message.author.bot || message.channel.type === "dm") return; //For bugs again
if(!message.member.roles.cache.some(role => role.name === 'OWNER')) { //This command only
//for owner role now.
return message.reply('You should be OWNER for using this command.').then(message => {
message.delete({ timeout: 8000 })
})
}
const messageArray = message.content.split(' ');
const cmd = messageArray[0];
const args = messageArray.slice(1).join(' ').toUpperCase();
if (message.content.startsWith('*open-channel'))
var kanal = message.guild.channels.create(`${args} - ${message.author.tag}`,{type : 'voice'})
.then(channel => channel.setParent(message.guild.channels.cache.find(channel => channel.name === "USER CHANNELS"))); //setParent moves my channel to choosen catagory. And 'args - message.author.tag' is channel name
message.channel.send("Its done now buddy :3");
})
Sorry for my bad english if i wrote something wrong. :(
You can use GuildChannelManager.create.options.permissionOverwrites(). Also, you can set the channel parent directly when creating it.
message.guild.channels.create(`${args} - ${message.author.tag}`, {
type: 'voice',
permissionOverwrites: [
{
id: '<Staff Role ID>',
allow: ['MANAGE_CHANNELS'],
},
],
parent: message.guild.channels.cache.find(
(channel) => channel.name === 'USER CHANNELS'
),
});
How do I make it so that when someone reacts with the first emoji in this command, the bot deletes the message and sends it to another channel?
Current Code:
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
if (!message.member.hasPermission("MANAGE_MESSAGES"))
return message.channel.send("You are not allowed to run this command.");
let botmessage = args.join(" ");
let pollchannel = bot.channels.cache.get("716348362219323443");
let avatar = message.author.avatarURL({ size: 2048 });
let helpembed = new Discord.MessageEmbed()
.setAuthor(message.author.tag, avatar)
.setColor("#8c52ff")
.setDescription(botmessage);
pollchannel.send(helpembed).then(async msg => {
await msg.react("715383579059945512");
await msg.react("715383579059683349");
});
};
module.exports.help = {
name: "poll"
};
You can use awaitReactions, createReactionCollector or messageReactionAdd event, I think awaitReactions is the best option here since the other two are for more global purposes,
const emojis = ["715383579059945512", "715383579059683349"];
pollchannel.send(helpembed).then(async msg => {
await msg.react(emojis[0]);
await msg.react(emojis[1]);
//generic filter customize to your own wants
const filter = (reaction, user) => emojis.includes(reaction.emoji.id) && user.id === message.author.id;
const options = { errors: ["time"], time: 5000, max: 1 };
msg.awaitReactions(filter, options)
.then(collected => {
const first = collected.first();
if(emojis.indexOf(first.emoji.id) === 0) {
msg.delete();
// certainChannel = <TextChannel>
certainChannel.send(helpembed);
} else {
//case you wanted to do something if they reacted with the second one
}
})
.catch(err => {
//time up, no reactions
});
});
So i want that my poll command asks for the channel and the question in a conversation, but i haven't figured out how to get the channel when the user only gives the ID, i have figured out that i have to use .content but i still don't know how to implement it.
My code:
run: async(message, client, args) => {
// Channel where the poll should take palce
await message.channel.send(`Please provide a channel where the poll should take place or cancel this command with "cancel"!`)
const response1 = await message.channel.awaitMessages(m => m.author.id === message.author.id, {max: 1});
const channel = response1.first().mentions.channels.first() || response1.content.guild.channels.cache.get()
if (!channel) {
return message.channel.send(`You did not mention or provide the ID of a channel where the poll should take place!`)
}
// Channel where the poll should take palce
await message.channel.send(`Please provide a question for the poll!`)
const response2 = await message.channel.awaitMessages(m => m.author.id === message.author.id, {max: 1});
let question = response2.first();
if (!question) {
return message.channel.send(`You did not specify your question!`)
}
const Embed = new Discord.MessageEmbed()
.setTitle(`New poll!`)
.setDescription(`${question}`)
.setFooter(`${message.author.username} created this poll.`)
.setColor(`0x0099ff`)
let msg = await client.channels.cache.get(channel.id).send(Embed)
await msg.react("👍")
await msg.react("👎")
}
And it is this line: response1.content.guild.channels.cache.get() that is writte wrong by me but idk what i have to change/where to add the .content so that it works.
Would be nice if someone can help me.
My message event for the args:
module.exports = async (client, message) => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
if (!message.guild) return;
if (!message.member) message.member = await message.guild.fetchMember(message);
const args = message.content.slice(prefix.length).split(/ +/g);
const cmd = args.shift().toLowerCase();
if (cmd.length == 0) return;
let command = client.commands.get(cmd)
if (!command) command = client.commands.get(client.aliases.get(cmd));
if (command) {
try {
command.run(message, client, args)
} catch (error) {
console.error(error);
message.reply('There was an error trying to execute that command!');
}
}
}
You need the content to grab the id, but I assume that's already handled by the code that generates the args parameter.
To get the guild you can use Message.guild, and then just Guild.channels.cache.get()
That means that your code would look like this:
const channel = response1.first().mentions.channels.first()
|| response1.first().guild.channels.cache.get(args[0]) // Assuming args[0] is your id
So i went around it with making another constructor means:
const ID = client.channels.cache.get(response1.first().content)
const channel = response1.first().mentions.channels.first() || ID
It works fine now