How to transfer reaction to original message, discord.js - 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.

Related

Discord bot not coming online despite no error messages?

I have recently spent a long time making a discord ticket bot, and all of a sudden now, it isnt turning on. There are no error messages when I turn the bot on, and the webview says the bot is online. I am hosting on repl.it
Sorry for the long code, but any genius who could work this out would be greatly appreciated. Thanks in advance.
const fs = require('fs');
const client = new Discord.Client();
const prefix = '-'
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles){
const command = require(`./commands/${file}`)
client.commands.set(command.name, command);
}
require('./server.js')
client.on("ready", () => {
console.log('Bot ready!');
client.user.setActivity('-help', { type: "LISTENING"} ).catch(console.error)
})
client.on("message", async (message) => {
if (message.author.bot) return;
const filter = (m) => m.author.id === message.author.id;
if (message.content === "-ticket") {
let channel = message.author.dmChannel;
if (!channel) channel = await message.author.createDM();
let embed = new Discord.MessageEmbed();
embed.setTitle('Open a Ticket')
embed.setDescription('Thank you for reaching out to us. If you have a question, please state it below so I can connect you to a member of our support team. If you a reporting a user, please describe your report in detail below.')
embed.setColor('AQUA')
message.author.send(embed);
channel
.awaitMessages(filter, {max: 1, time: 1000 * 300, errors: ['time'] })
.then ( async (collected) => {
const msg = collected.first();
message.author.send(`
>>> ✅ Thank you for reaching out to us! I have created a case for your inquiry with out support team. Expect a reply soon!
❓ Your question: ${msg}
`);
let claimEmbed = new Discord.MessageEmbed();
claimEmbed.setTitle('New Ticket')
claimEmbed.setDescription(`
New ticket created by ${message.author.tag}: ${msg}
React with ✅ to claim!
`)
claimEmbed.setColor('AQUA')
claimEmbed.setTimestamp()
try {
let claimChannel = client.channels.cache.find(
(channel) => channel.name === 'general',
);
let claimMessage = await claimChannel.send(claimEmbed);
claimMessage.react('✅');
const handleReaction = (reaction, user) => {
if (user.id === '923956860682399806') {
return;
}
const name = `ticket-${user.tag}`
claimMessage.guild.channels
.create(name, {
type: 'text',
}).then(channel => {
console.log(channel)
})
claimMessage.delete();
}
client.on('messageReactionAdd', (reaction, user) => {
const channelID = '858428421683675169'
if (reaction.message.channel.id === channelID) {
handleReaction(reaction, user)
}
})
} catch (err) {
throw err;
}
})
.catch((err) => console.log(err));
}
})
client.login(process.env['TOKEN'])
Your problem could possibly be that you have not put any intents. Intents look like this:
const { Client } = require('discord.js');
const client = new Client({
intents: 46687,
});
You can always calculate your intents with this intents calculator: https://ziad87.net/intents/
Side note:
If you are using discord.js v14 you change client.on from message to messageCreate.

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.

Why is data not being saved in the array? | discord.js v13

Whenever I'm attempting to push data into an array, then log it after the for loop it just prints an empty array. Why is that?
const discord = require('discord.js');
const db = require('quick.db');
const fs = require('fs');
module.exports = {
name: 'XYZ',
run: async (client, message) => {
var array_V = ['ID1', 'ID2'];
var snowflakes = [];
var i = 0;
message.guild.channels.cache.forEach(channel => {
if (!channel.isText()) return;
for (const channel of message.guild.channels.cache.values()) {
let messages = await channel.messages.fetch()
messages.each((msg) => {
if (msg.author.id === array_V[i]) {
snowflakes.push(msg.createdTimestamp)
}
})
}
});
}
}
Now outputs SyntaxError: await is only valid in async functions and the top level bodies of modules although it is already declared as an async function in the header.
You are pushing it in a .then. Use await and for loops to have it update and then run the next code
for (const channel of message.guild.channels.cache.filter(c => c.type === "GUILD_TEXT").values()) {
let messages = await channel.messages.fetch()
messages.each((msg) => {
if (msg.author.id === array_V[i]) {
snowflakes.push(msg.createdTimestamp)
}
})
}
This should work since everything asynchronous is being awaited in the for loop

DM Specific User ID on Discord.js Bot

i'm new to coding bots and i need help on how to add a command on messaging a certain person a customized message. this is what i have so far. what should i do?
const Discord = require('discord.js');
const config = require("./Data/config.json")
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] })
client.once('ready', () => {
console.log('Ready!');
});
client.login('TOKEN');
client.on('message', async message => {
if (message.author.bot) return;
let prefix = '??'
if (!message.content.startsWith(prefix)) return;
let args = message.content.slice(prefix.length).trim().split("/ +/g");
let msg = message.content.toLowerCase();
let cmd = args.shift().toLowerCase();
if (msg.startsWith(prefix + 'ping')) {
message.channel.send('pong');
}
if (msg.startsWith(prefix + 'hello')) {
message.channel.send('hewwo uwu');
}
});
To fetch a user by id, you can use bot.users.fetch()
To direct message a user, you can use User.send():
const user = await client.users.fetch(userId);
user.send("This is a DM!");
This simple function will easily resolve the user (you can provide a user object or user ID so it’s very helpful)
async function DMUser(resolvable, content, client) {
const user = client.users.resolve(resolvable)
return user.send(content)
}
//returns: message sent, or error
//usage: DMUser(UserResolvable, "content", client)
Related links:
UserManager.resolve
User.send
UserResolvable

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.

Resources