How do I delete a user's new message - javascript

I'm pretty trash at coding so I need a little bit of help. I'm trying to code my discord bot to delete someone's messages for one minute after they click a react emoji. It sounds simple but for my tiny pea brain, it's not. This is what I have got so far. It deletes all messages from different users and guilds it's in, forever. I want it so it only delete messages in one channel for one minute.
client.once('message', async userMessage => {
if (userMessage.content.startsWith(''))
{
botMessage = await userMessage.channel.send('Who here likes goats?')
await botMessage.react("πŸ‘")
await botMessage.react("πŸ‘Ž")
const filter = (reaction, user) => {
return (
["πŸ‘", "πŸ‘Ž"].includes(reaction.emoji.name) && user.id === userMessage.author.id
);
};
botMessage
.awaitReactions(filter, { max: 1, time: 60000, errors: ["time"] })
.then((collected) => {
const reaction = collected.first();
if (reaction.emoji.name === "πŸ‘Ž") {
userMessage.channel.send(`${userMessage.author}, how dare you. I guess no on here likes me. Hmmm, because of that I shall now eat all your messages! BAAAAAHAHAHHAHAHA!`)
setTimeout(() => {
client.on("message", async msg => {
if (author.msg.content.startsWith("")) {
userMessage.channel = await msg.delete();
}
});
}, 2000);
} else {
userMessage.reply("Thanks!");
}
})
.catch((_collected) => {
userMessage.channel.send("Hehe")
});
}
});
Btw, the code is in discord.js!

Your problem is this chunk of code
setTimeout(() => {
client.on("message", async msg => {
if (author.msg.content.startsWith("")) {
userMessage.channel = await msg.delete();
}
});
}, 2000);
This is not how you use events.
A) Your message event is nested within another which could cause memory leaks.
B) To get the content you need to use msg.content, author.msg Is not a thing.
C) I assume your intention here: msg.content.startsWith("") is to always fire the if statement, in that case why not do if (true).
Here's how I would do it:
Create a Set in the namespace which will hold id's of users who's messages should be deleted
const toDelete = new Set();
If they react with a πŸ‘Ž add them to the set.
if (reaction.emoji.name === "πŸ‘Ž") {
userMessage.channel.send('Your message here');
if (!toDelete.has(userMessage.author.id)) {
toDelete.add(userMessage.author.id);
}
}
On each message event check if the author of the message has their id in the set, If so delete their message
client.once('message', async userMessage => {
if (toDelete.has(userMessage.author.id)) {
return userMessage.delete()
.catch(console.error);
}
if (userMessage.content.startsWith('')) {
// Rest of your code

I think your problem in understanding how everything works.
I took everything from discord.js documentation.
Type reaction command to see how it works.
const Discord = require("discord.js");
require("dotenv").config();
const TOKEN = process.env.TOKEN||"YOUR TOKEN";
const PREFIX = process.env.PREFIX||"YOUR PREFIX";
const bot = new Discord.Client();
bot.on("ready", async function(e) {
console.log("Loaded!");
})
bot.on("message", async function(message) {
if (message.author.bot) return;
if (!message.content.startsWith(PREFIX)) return;
let args = message.content.slice(PREFIX.length).trim().split(/\s+/);
let command = args.splice(0, 1).toString().toLowerCase();
if (command == "reaction") {
message.delete();
let msg = await message.channel.send("Click on the reaction");
await msg.react("πŸ‘");
await msg.react("πŸ‘Ž");
let filter = (reaction, user) => {
return ["πŸ‘", "πŸ‘Ž"].includes(reaction.emoji.name) && user.id == message.author.id;
}
msg.awaitReactions(filter, {max: 1, time: 10000, errors: ["time"]}).then(collected => {
let reaction = collected.first();
if (reaction.emoji.name == "πŸ‘Ž") {
return message.channel.send("downvote");
}
return message.channel.send("upvote");
}).catch(e => {
message.channel.send("user didn't vote");
})
}
})
bot.login(TOKEN);

Related

How to move back and forth for help page using awaiting reactions discord.js

This is my sample code:
const Discord = require('discord.js')
module.exports = {
name: 'help',
description: 'help',
execute(message, args) {
const embed = new Discord.MessageEmbed()
.setTitle('Page One')
.setDescription('This is page one')
message.channel.send(embed).then((msg) => {
msg.react('⬅️')
msg.react('➑️')
const filter = (reaction, user) => {
return ['⬅️', '➑️'].includes(reaction.emoji.name) && user.id === message.author.id;
};
msg.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
.then(collected => {
const reaction = collected.first()
if (reaction.emoji.name === '⬅️') {
message.channel.send(embed)
}
else {
const secEmbed = new Discord.MessageEmbed()
.setTitle('Help')
.setDescription('This is help page 2')
msg.edit(secEmbed);
}
})
})
}
}
This is working, but when i try to move it backwards to the previous page after i have moved to the second page, the thing stops working.... I meant, then the embed pages won't move forth or back. Is there anyway to solve this prob? Thank You.
You could simply call msg.awaitReactions() again; wrap it in a function to make it easier to repeat the reaction collection.
Using msg.awaitReactions():
message.channel.send(embed).then((msg) => {
msg.react("⬅️");
msg.react("➑️");
function handleReactions() {
const filter = (reaction, user) => {
return ['⬅️', '➑️'].includes(reaction.emoji.name) && user.id === message.author.id;
};
msg.awaitReactions(filter, {max: 1, time: 60000, errors: ["time"]})
.then((collected) => {
const reaction = collected.first();
const name = reaction.emoji.name;
if (name === "⬅️") {
// edit page a certain way
handleReactions();
} else if (name === "➑️") {
// edit page another way
handleReactions();
}
});
}
handleReactions();
});
Another way would be to listen for reaction events:
message.channel.send(embed).then((msg) => {
msg.react("⬅️");
msg.react("➑️");
// handles reactions
function handleReaction(reaction, user) {
// ignore the reaction if the reaction is on a different message
if (reaction.message.id !== msg.id && user.id === message.author.id) {return;}
const name = reaction.emoji.name;
if (name === "⬅️") {
// move page a certain way
} else if (name === "➑️") {
// move page another way
}
}
// add a listener for message reactions
message.client.on("messageReactionAdd", handleReaction);
// wait a specific amount of time to stop listening
setTimeout(() => {
// remove the listener
message.client.off("messageReactionAdd", handleReaction);
}, 60000); // 60 seconds
/*
You could add functions to reset the timeout after each reaction as well.
*/
});

How can i count the reactions in discord.js and after that display it (slappey version)

I'm trying to display who win the poll but i run into a problem. While I want to get the number of the reactions with
.addField("πŸ”΄:", `${results.get("πŸ”΄").count}`)
My console says that the count is undefined. I've tried to search it but I didn't find anything and I tried so many ways but nothing.
The code:
const BaseCommand = require('../../utils/structures/BaseCommand');
const Discord = require("discord.js")
module.exports = class HelpCommand extends BaseCommand {
constructor() {
super('vote', 'moderation', []);
}
async run(client, message, args) {
const filter = m => m.author.id == message.author.id;
let embed = new Discord.MessageEmbed()
.setFooter(`${message.author.tag} started the poll`)
.setTimestamp();
message.channel.send('what the question is?');
try {
let msg = await message.channel.awaitMessages(filter, { max: 1, time: 15000, errors: ['time'] });
console.log(msg.first().content);
embed.setTitle(msg.first().content);
} catch (err) {
console.log(err);
message.channel.send('You run out of time! Pls type again the command \`~prefix~ vote\`');
}
message.channel.send('first option?');
try {
let msg = await message.channel.awaitMessages(filter, { max: 1, time: 15000, errors: ['time'] });
console.log(msg.first().content);
embed.addField(`[πŸ”΄] the first option:`, msg.first().content);
} catch (err) {
console.log(err);
message.channel.send('You run out of time! Pls type again the command \`~prefix~ vote\`');
}
message.channel.send('second option?');
try {
let msg = await message.channel.awaitMessages(filter, { max: 1, time: 15000, errors: ['time'] });
console.log(msg.first().content);
embed.addField(`[πŸ”΅] the second option`, msg.first().content);
} catch (err) {
console.log(err);
message.channel.send('You run out of time! Pls type again the command \`~prefix~ vote\`');
}
try {
await message.channel.bulkDelete(7)
.then(message.channel.send(embed).then(sentMessage => sentMessage.react('πŸ”΄')).then(reaction => reaction.message.react('πŸ”΅')));
} catch (err) {
console.log(err);
}
const filters = (reaction) => reaction.emoji.name === "πŸ”΄" || reaction.emoji.name === "πŸ”΅";
const results = await message.awaitReactions(filters, { time: 15000 })
let resultsEmbed = new Discord.MessageEmbed()
.setTitle(`the poll result`)
.setDescription(`the result of the poll: ${args.join(" ")}`)
.addField("πŸ”΄:", `${results.get("πŸ”΄").count}`)
.addField("πŸ”΅:", `${results.get("πŸ”΅").count //if i dont type here the .count then i've got this embed but after the "πŸ”΅": says'undefined' }`)
.setColor("#84daf8")
.setTimestamp()
message.channel.send(resultsEmbed);
}
}
A szavazΓ‘s eredmΓ©nye = The poll result in my language. I see this when i dont write the .count there: .addField("πŸ”΄:", `${results.get("πŸ”΄").count}`)
and i see this when i write .count
The problem was that the bot was trying to retrieve the reactions of a deleted message I believe. In order to fix this, you'll have to put your resultsEmbed code inside of your chained then methods.
Code:
try {
await message.channel.bulkDelete(7)
.then(message.channel.send(embed)
.then(sentMessage => sentMessage.react('πŸ”΄'))
.then(reaction => reaction.message.react('πŸ”΅'))
.then(reaction => {
const filters = (reaction) => reaction.emoji.name === "πŸ”΄" || reaction.emoji.name === "πŸ”΅";
reaction.message.awaitReactions(filters, { time: 15000 }).then(collected => {
console.log(collected);
if (collected.get("πŸ”΄") !== undefined && collected.get("πŸ”΅") !== undefined) {
let optionOne = collected.get("πŸ”΄").count;
let optionTwo = collected.get("πŸ”΅").count;
let resultsEmbed = new Discord.MessageEmbed()
.setTitle("the poll result")
.setDescription(`the result of the poll: ${args.join(" ")}`)
.addField("πŸ”΄:", `${optionOne}`)
.addField("πŸ”΅:", `${optionTwo}`)
.setColor('#')
.setTimestamp()
message.channel.send(resultsEmbed);
} else {
//there were no votes for one of the options, thus it will not be able to get property
message.channel.send("There were no votes for one of the options.");
}
})
})
);
} catch (err) {
console.log(err);
}

why does my discord bot don't seem to hear?

Well, I would create a discord bot that will stock given data in a database, .then I began to learn js
Until now i haven't any problem and found a lot of help in the web, before to create the database i tried to show detected data on the console but now I'm blocked and can't understand by myself where is the problem.
here is my code
const Discord = require('discord.js')
const client = new Discord.Client();
const { promisify } = require('util')
const sleep = promisify(setTimeout)
require('dotenv').config();
const BOT_TOKEN = '******'
client.on('ready', async () => {
console.log(`The bot is now working !\n\n`);
});
client.on('message', async (receivedMessage) => {
// Prevent bot from responding to its own messages
if (receivedMessage.author == client.user) {
return;
}
const { author, content, channel } = receivedMessage;
const { id } = author;
const trimmedContent = content.trim();
if (trimmedContent.startsWith('!ins')) {
console.log('Inside ins');
module.exports = {
prefix: "!ins",
fn: (msg) => {
let application = {}
let filter = (msg) => !msg.author.bot;
let options = {
max: 1,
time: 15000
};
msg.member.send("nom ?")
.then(dm => {
// After each question, we'll setup a collector on the DM channel
return dm.channel.awaitMessages(filter, options)
})
.then(collected => {
// Convert the collection to an array & get the content from the first element
application.name = collected.array()[0].content;
// Ask the next question
return msg.member.send("Parfait, maintenant votre mail ?")
})
.then(dm => {
return dm.channel.awaitMessages(filter, options)
})
.then(collected => {
application.emailAddress = collected.array()[0].content;
return msg.member.send("Excellent. Enfin, quel est votre Γ’ge ?")
})
.then(dm => {
return dm.channel.awaitMessages(filter, options)
})
.then(collected => {
application.pitch = collected.array()[0].content;
console.log(application)
})
}
}
}
});
// client.login logs the bot in and sets it up for use. You'll enter your token here.
client.login(' ');
The problem is that bot doesn't react to !ins command and on the console I only have the console.log 2 and 3
if you need any more info, feel free to ask them and thanks for taken time
I do think that you should code your main structure like mine because yours is a bit messy.
const Discord = require('discord.js');
const client = new Discord.Client();
const BOT_TOKEN = '...';
client.on('ready', async () => {
console.log(`The bot is now working !\n\n`);
});
client.on('message', async (receivedMessage) => {
// Prevent bot from responding to its own messages
if (receivedMessage.author == client.user) {
return;
}
const { author, content, channel } = receivedMessage;
const { id } = author;
// Removes whitespace from both ends of a string, "I personally do like this"
const trimmedContent = content.trim();
if (trimmedContent.startsWith('!ins')) {
console.log('Inside ins');
}
});
client.login(BOT_TOKEN);
process.on('exit', () => {
client.destroy();
console.log(`The bot is now disconnected !\n\n`);
});

is there can delete message when click this reaction emoji DIscord.js

How to fix this ? i want to delete message when user click reaction X
client.on('message', async message => {
if (message.channel.id === emojiChannelID) {
try {
await message.react('βœ…');
await message.react('βœ–');
} catch(err) {
console.error(err);
}
}
});```
There's an message.awaitReaction() in discord.js, that will return reactions from users
// Filter for only
const filter = function(reaction, user) {
return reaction.emoji.name === 'βœ…' || reaction.emoji.name === 'βœ–';
}
// {...}
let reactionMessage = await message.react('βœ…');
// Make sure to set max: 1 so that the promise returns after the first reaction
let reactionCollection = await reactionMessage.awaitReactions(filter, { max: 1});
// reactionCollection is a Collection<string, MessageReaction>
// Use first() to get the first (and only)
let reaction = reactionCollection.first();
Kian here,
This code should work for you,
if you would like I can go through and explain each line :)
Have a good day chief!
async function emojiMessage(message, validReactions) {
for (const reaction of validReactions) await message.react(reaction);
const filter = (reaction, user) => validReactions.includes(reaction.emoji.name) && (!user.bot)
return message
.awaitReactions(filter, {
max: 1,
time: 42000
})
.then(collected => collected.first() && collected.first().emoji.name);
}
async function deleteMessage(message) {
const emoji = await emojiMessage(message, ["βœ…", "❌"]);
console.log(emoji)
// if the emoji is a tick:
if (emoji === "βœ…") {
// delete their message
console.log("tick")
if (message.deletable == true) {
console.log("can delete")
console.log("attempting to delete")
message.delete()
}
if (!message.deletable == false) {
"cannot delete"
}
} else if (emoji === "❌") { // if the emoji is a cross
/*
* do something else
*/
return;
}
}
client.on('message', message => {
if (message.channel.id === emojiChannelID) {
// runs the function
deleteMessage(message)
}
/*
* do something else
*/
})
Note:
First upload πŸŽ‰
I've tried my best to make the code understandable/work , if there is any issues feel free to comment, I'll fix it :)
Example Usage:
const m = await message.channel.send('hi!');
reactionDelete(m, message, 20000); // assuming 'message' is the actual sent message
async function reactionDelete (botMessage, playerMessage, timeout) {
const filter = (reaction, user) => {
return ['πŸ—‘οΈ'].includes(reaction.emoji.name) && user.id === playerMessage.author.id;
};
botMessage.react('πŸ—‘οΈ');
botMessage.awaitReactions(filter, { max: 1, time: timeout})
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === 'πŸ—‘οΈ') {
botMessage.delete();
}
})
.catch(collected => {
if (botMessage.deletable) botMessage.reactions.removeAll();
});
};

Why does the bot react itself? (discord.js)

I'm setting up a bot, who will await for a user's reaction to write a short message. Currently, the bot responds itself to his reaction! Why?
const { Client, RichEmbed, Discord } = require('discord.js');
const config = require('./config.json');
const client= new Client();
client.on('ready', () => {
console.log('je suis pret!');
client.user.setActivity("/help pour appeler de l'aide (avec le code NOMAD bien sur)", { type: 'WATCHING' });
})
client.on('messageReactionAdd', (reaction, user) => {
console.log(`${user.username} reacted with "${reaction.emoji.name}".`);
});
client.on('messageReactionRemove', (reaction, user) => {
console.log(`${user.username} removed their "${reaction.emoji.name}" reaction.`);
});
client.on('message', async message => {
if (message.author.bot) return;
if (message.content.toLowerCase().startsWith('!rea')) {
try {
const sentMessage = await message.channel.send('Select a number.');
for (let n = 1; n <= 5; n++) await sentMessage.react(`${n}⃣`);
const filter = (reaction, user) => ['1', '2', '3', '4', '5'].includes(reaction.emoji.name.slice(0, 1)) && user.id === message.author.id;
const collected = await sentMessage.awaitReactions(filter, { maxMatches: 1, time: 60000 });
if (collected.size === 0) {
await sentMessage.clearReactions();
await message.channel.send('Your time ran out.');
} else {
const reaction = collected.first();
switch(reaction.emoji.name.slice(0, 1)) {
case '1':
await message.channel.send('You chose `one`.');
break;
}
}
} catch(err) {
console.error(err);
}
}
});
client.login(config.token);
I found the problem: the bot considers the first message: "!rea", so if I add the reaction below !rea, it answers!
How can I fix this, because I want that he considered the embed reactions!
Thank you for your help
Your client's message event is emitted by any message, including those sent by itself.
To prevent bots (and therefore your client as well) from triggering the code, add a condition checking the author's User.bot property at the beginning of the callback, and return if it's true.
if (message.author.bot) return; // Stop if the author is a bot.
// Continue with your code.
Additionally, you're collecting reactions on the wrong message, and on every one. message outside of your first then() callback is the one the bot received.
To make things much more simple and readable, we can use the await keyword (note that it can only be used asynchronous context, like in a function declared as async).
Combining these changes...
client.on('message', async message => {
if (message.author.bot) return;
if (message.content.toLowerCase().startsWith('!rea')) {
try {
const sentMessage = await message.channel.send('Select a number.');
for (let n = 1; n <= 5; n++) await sentMessage.react(`${n}⃣`);
const filter = (reaction, user) => ['1', '2', '3', '4', '5'].includes(reaction.emoji.name.slice(0, 1)) && user.id === message.author.id;
const collected = await sentMessage.awaitReactions(filter, { maxMatches: 1, time: 60000 });
if (collected.size === 0) {
await sentMessage.clearReactions();
await message.channel.send('Your time ran out.');
} else {
const reaction = collected.first();
switch(reaction.emoji.name.slice(0, 1)) {
case '1':
await message.channel.send('You chose `one`.');
break;
}
}
} catch(err) {
console.error(err);
}
}
});

Categories

Resources