Remove users reaction when they have clicked on the ReactionCollector - discord.js

I have a ReactionCollector and as soon as I click on the right arrow reaction, I want it to remove my reaction instantly; so I can react again as soon as possible. How do I go about this? Here's my code boss.
const embed = new MessageEmbed().setDescription(`test`);
const listEmbed = await message.channel.send(embed);
await listEmbed.react("➡️")
const filter = (reaction, user) => ["➡️"].includes(reaction.emoji.name) && (message.member.id == user.id)
const collector = listEmbed.createReactionCollector(filter)
collector.on("collect", async (reaction, user) => {
if (reaction.emoji.name === "➡️") {
//remove user reaction
}
})

Corrent me if I'm wrong, but I'm pretty sure it's:
reaction.users.remove(message.author.id)
You have the reaction, you take the users, and remove the reaction from message.author.id.

Related

Discord JS - Remove role when reaction is added

I should know how to do this. But the code below does not work.
The goal is to remove roles when the user adds a reaction to a message.
client.on('messageReactionAdd', async (reaction, user) => {
const message = await reaction.message.fetch(true);
const channelStockSettings = '961958948976607243';
const fundamentalPlays = '⭐️';
const fundamentalPlaysRoleSE = message.guild.roles.cache.find(role => role.name === '⭐🇸🇪');
const fundamentalPlaysRoleUS = message.guild.roles.cache.find(role => role.name === '⭐🇺🇸');
const longTerm = '⛰';
const longTermRoleSE = message.guild.roles.cache.find(role => role.name === '⛰🇸🇪');
const longTermRoleUS = message.guild.roles.cache.find(role => role.name === '⛰🇺🇸');
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
if (user.bot) return;
if (!reaction.message.guild) return;
if (reaction.message.channel.id === channelStockSettings) {
if (reaction.emoji.name === fundamentalPlays) {
await reaction.message.guild.members.cache.get(user.id).roles.remove(fundamentalPlaysRoleSE);
await reaction.message.guild.members.cache.get(user.id).roles.remove(fundamentalPlaysRoleUS);
} else if (reaction.emoji.name === longTerm) {
await reaction.message.guild.members.cache.get(user.id).roles.remove(longTermRoleSE);
await reaction.message.guild.members.cache.get(user.id).roles.remove(longTermRoleUS);
} else {
return;
}
}
});
This is the way I've coded this before. What the ... is wrong?
After testing your code, it appears that the issue is that you have the wrong unicode emotes, assuming you're trying to use the default Discord emotes for star and mountain. In other words, reaction.emoji.name === fundamentalPlays and reaction.emoji.name === longTerm both were returning false.
I'm not sure how this happened or where you got these unicode emotes from (perhaps an older version of discord, or from a third-party website?), but neither correctly matches the Discord unicode emote (the star emotes seem to look exactly the same but are not equal, and the mountain emotes both do not look the same and are not equal). The best way to get the unicode form of any Discord emote is to put a backslash before a Discord emote when sending it. Then, copy the unicode emote that it gives you.
Here's your code, modified to have the correct unicode emotes. I tested it, and it is working for me:
client.on('messageReactionAdd', async (reaction, user) => {
console.log("Reaction received");
const message = await reaction.message.fetch(true);
const channelStockSettings = '883731756438671391';
const fundamentalPlays = '⭐';
const fundamentalPlaysRoleSE = message.guild.roles.cache.find(role => role.name === 'Member');
const fundamentalPlaysRoleUS = message.guild.roles.cache.find(role => role.name === 'Youtuber');
const longTerm = '⛰️';
const longTermRoleSE = message.guild.roles.cache.find(role => role.name === 'Testor');
const longTermRoleUS = message.guild.roles.cache.find(role => role.name === 'Co-op');
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
if (user.bot) return;
if (!reaction.message.guild) return;
if (reaction.message.channel.id === channelStockSettings) {
if (reaction.emoji.name === fundamentalPlays) {
await reaction.message.guild.members.cache.get(user.id).roles.remove(fundamentalPlaysRoleSE);
await reaction.message.guild.members.cache.get(user.id).roles.remove(fundamentalPlaysRoleUS);
} else if (reaction.emoji.name === longTerm) {
await reaction.message.guild.members.cache.get(user.id).roles.remove(longTermRoleSE);
await reaction.message.guild.members.cache.get(user.id).roles.remove(longTermRoleUS);
} else {
return;
}
}
});
Note that there could be numerous additional issues responsible for this code not working, however:
a) The messageReactionAdd event only fires for reactions added to cached messages. Therefore, it will not fire if you add a reaction to a message sent before the bot started. If you are trying to do this with such an uncached message, you will need to specifically fetch the message immediately when your bot starts up (most likely in your ready event handler).
b) Make sure you have the correct intents for receiving messages and message reactions. I assume you do, but double-check, otherwise the messageReactionAdd event will not fire at all.
I had the same problem with my bot. Can you try delete the embed message and add it again. Then try it again.

How do we make a kick command with userid?

So how do we detect the userID with the kick command below?
So below is my kick command and whenever I kick a person I need to mention them (?kick #test) I want to kick a user by their user id (?kick 354353) and their mentions.
const client = new Discord.Client();
client.on('ready', () => {
console.log('I am ready!');
});
client.on('message', message => {
// Ignore messages that aren't from a guild
if (!message.guild) return;
if (message.content.startsWith('?kick')) {
if (member.hasPermission(['KICK_MEMBERS', 'BAN_MEMBERS']))
return;
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member
.kick('Optional reason that will display in the audit logs')
.then(() => {
message.reply(`Successfully kicked ${user.tag}`);
})
.catch(err => {
message.reply('I was unable to kick the member');
// Log the error
console.error(err);
});
} else {
// The mentioned user isn't in this guild
message.reply("That user isn't in this guild!");
}
// Otherwise, if no user was mentioned
} else {
message.reply("You didn't mention the user to kick!");
}
}
});
client.login('TOKEN');
I recommend setting up Arguments if you plan to make more commands that take user input.
However if you're not interested in fully setting up arguments, you can just slice the message and grab the id. You will then need to fetch the member object, make sure to make your function is async for this, or use Promise#then if you prefer.
if (message.content.startsWith('?kick')) {
if (member.hasPermission(['KICK_MEMBERS', 'BAN_MEMBERS']))
return;
const memberId = message.content.slice(' ')[1];
if (memberId) {
const memberToKick = await message.guild.members.cache.fetch(userId);
memberToKick.kick('Optional reason that will display in the audit logs')
.then(() => {
message.reply(`Successfully kicked ${user.tag}`);
})
.catch(err => {
message.reply('I was unable to kick the member');
// Log the error
console.error(err);
});
}
}

Giving roles on discord

I'm making a discord murder mystery bot.
const Discord = require('discord.js');
const client = new Discord.Client();
client.on("message", (message) => {
msg = message.content.toLowerCase();
if (message.author.bot) {
return;
}
mention = message.mentions.users.first();
if (msg.startsWith("kill")) {
if (mention == null) {
return;
}
message.delete();
mention.send('you are dead');
message.channel.send("now done");
}
});
client.login('my token');
What would I add to the code so after the person who was tagged got there role changed from alive to dead?
// First, make sure that you're in a guild
if (!message.guild) return;
// Get the guild member from the user
// You can also use message.mentions.members.first() (make sure that you check that
// the message was sent in a guild beforehand if you do so)
const member = message.guild.members.cache.get(mention.id);
// You can use the ID of the roles, or get the role by name. Example:
// const aliveRole = message.guild.roles.cache.find(r => r.name === 'Alive');
const aliveRole = 'alive role ID here';
const deadRole = 'dead role ID here';
// You can also use try/catch with await if you make the listener and async
// function:
/*
client.on("message", async (message) => {
// ...
try {
await Promise.all([
member.roles.remove(aliveRole),
member.roles.add(deadRole)
]);
} catch (error) {
console.error(error);
}
})
*/
Promise.all([
member.roles.remove(aliveRole),
member.roles.add(deadRole)
]).catch(console.error);
The Promise.all means that the promises for adding and removing the roles are started at the same time. A promise is an object that can resolve to a value or reject with an error, so the .catch(console.error) logs all errors. I recommend that you handle errors for message.delete(), mention.send('you are dead'), and message.channel.send("now done") as well.
For more information on member.roles.remove() and member.roles.add(), see the documentation for GuildMemberRoleManager.

How to transfer reaction to original message, discord.js

I am trying to make a suggestion feature for one of my bots. I have searched online but nothing really helps with it. The suggestion part is working but I want to add a feature where if i react to the message in the log channel it sends the reaction to the original message. Here is my code:
bot.on('message', message => {
if (message.content.startsWith("/suggest")){
message.reply(`Your response has been recorded.`)
var yes = message.content
const channel1 = bot.channels.cache.get('722590953017442335');
channel1.send(`${message.author} suggests: ${yes.slice(9)}`)
if (chanell1.reaction.emoji.name === '✅'){
const channel2 = bot.channels.cache.get('722595812462297139');
channell2.react.author.message('✅')
}
}
})
I am using v12 of node.
You can use the awaitReactions() function:
bot.on("message", (message) => {
if (message.content.startsWith("/suggest")) {
message.reply(`Your response has been recorded.`);
var yes = message.content;
bot.channels.cache
.get("722590953017442335")
.send(`${message.author} suggests: ${yes.slice(9)}`)
.then(async (msg) => {
msg
.awaitReactions((reaction) => reaction.emoji.name === "✅", {
time: 15000,
})
.then((collected) => message.react("✅"))
.catch(console.error);
});
}
});
Please read the official documentation at https://discord.js.org/#/docs/main/v12/general/welcome for v12 help. You ought to use the Client#messageReactionAdd event to track reactions - your code isn't too far off, however it is missing that key event. Please note that to track reactions you'll need persistent storage if you want the reactions to work after restart. Alternatively, you could try awaiting the reactions or using a reaction collector if only short term.
Try this instead:
const { Client } = require('discord.js');
const bot = new Client({ partials: ['REACTION', 'USER'] });
const prefix = '/';
const suggestionsCache = {};
bot.on('message', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.split(' '),
command = args.shift().slice(prefix.length);
if (command == 'suggest') {
const suggestion = args.join(' '),
suggestionMessage = `${message.author} suggests: ${suggestion}`,
suggestionChannel = bot.channels.cache.get('722590953017442335'),
logChannel = bot.channels.cache.get('722595812462297139');
if (!suggestionChannel || !logChannel) return message.reply('Oops! Something went wrong.');
try {
const suggestionMessage = await suggestionChannel.send(suggestionMessage);
const logMessage = await logChannel.send(suggestionMessage);
suggestionsCache[logMessage.id] = suggestionMessage.id; // Save the ID for later.
message.reply('Your response has been recorded.');
} catch {
message.reply('Oops! Something went wrong.');
};
};
});
bot.on('messageReactionAdd', async (reaction, user) => {
if (reaction.partial) {
try {
await reaction.fetch();
} catch {}
}
const messageID = suggestionsCache[reaction.message.id];
if (!messageID || reaction.emoji.name !== '✅') return; // If not found in cache, ignore and if the emoji isn't the check, ignore it.
try {
const channel = await client.channels.fetch('722590953017442335');
if (!channel) return;
const message = channel.messages.fetch(messageID);
if (!message) return; // Message deleted.
message.react('✅');
} catch {
return;
};
});
Please note that I am new to v12 and normally use v11! The code above is not tested and may contain bugs as a result. Please feel free to edit/update the code.

How can a Discord bot reply to only certain users?

I am looking for a way to make a Discord bot which either reacts or replies to only certain users. It can choose the user by either role or ID, but I can not seem to get it working. This is what I have tried:
if (message.author.id === 'myDiscordID') {
message.reply('hello!').then(r => {
});
}
I am coding in Discord JS, if that helps. This is the entire index.js file:
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', message => {
if (message.author.id === 'myDiscordID') {
message.reply('hello!').then(r => {
});
}
});
client.login(token);
The file runs fine, the bot comes online, and then it prints 'Ready!' to the console, however, the rest of the code doesn't seem to work.
I`ts look like this must work.
Are you sure bot in your server and have permissions to read message ?
Try this ready block
client.once('ready', () => {
console.log('Ready!');
const guildList = client.guilds.cache.map(guild => guild.name)
console.join(`Bot go online in ${guildList.length}`)
console.log(guildList.join('\n'))
});
And some solutin to check user.id or roles includes:
console.log(message.content) for check is this event triggeret.
client.on('message', message => {
console.log(message.content)
if (message.author.id === '') {
message.reply('author contain')
}
if (message.member.roles.cache.has('ROLE ID')) {
message.reply('role contain')
}
if(message.member.roles.cache.some(role => ['ID1', 'ID2'].includes(role.id)) {
message.reply('some role contain')
}
});
I was also having a problem with that. Here is the solution that worked for me.
const userID = "The_user's_id";
bot.on("message", function(message) {
if(message.author.id === userID) {
message.react('emoji name or id');
}
});
Note: to find the id of a user, just right click him and press "copy ID".

Resources