I send messages to users when they connect to my server, and I want to continue authorization by clicking on reactions.
How can I create this? I'm using the following code:
robot.on("guildMemberAdd", (gMembAdd) =>
{
gMembAdd.send(`Hi ${gMembAdd.toString()} welcome to the server Test`).then(msg => {
msg.react('✅')
.then(() => msg.react('❎'));
//--------------------Developmend-------------------------------------
let filter = (reaction, user) => reaction.emoji.name === '✅' || reaction.emoji.name === '❎';
let col = msg.createReactionCollector(filter);
col.on('collect', r =>
{
if (r.users.last().id !== msg.author.id)
{
gMembAdd.addRole(gMembAdd.guild.roles.find("name", "Autorize")).catch(console.error)
r.remove(r.users.last().id);
console.log(` ${gMembAdd.user.id} и ${gMembAdd.user.username} and ${r.emoji}`);
}
});
//--------------------------------------------------------------------
});
I need a reaction check and role assignment if the response is positive and kick if not. I don't understand how to continue.
Will this code be used correctly?
To check the reaction you can use MesssageReaction.emoji.name, as you did above.
For the other thing, you can use GuildMember.addRole() & GuildMember.kick().
Here's a sample you can check out:
robot.on('guildMemberAdd', async member => {
let msg = await member.send(`Hi ${member} welcome to the server Test`);
await msg.react('✅');
await msg.react('❎');
msg.createReactionCollection(r => ['✅', '❎'].includes(r.emoji.name))
.on('collect', r => {
if (r.emoji.name == '✅')
member.addRole(member.guild.roles.find("name", "Authorize"))
.then(() => { console.log(`Added ${member.user.username} (${member.id}).`); })
.catch(console.error);
else if (r.emoji.name == '❎') member.kick("You got rejected.");
r.remove(r.users.last());
});
});
You can also use Message.awaitReactions(), which is better because it doesn't go on after the reaction is added:
robot.on('guildMemberAdd', async member => {
let msg = await member.send(`Hi ${member} welcome to the server Test`);
await msg.react('✅');
await msg.react('❎');
msg.awaitReactions(r => ['✅', '❎'].includes(r.emoji.name), {max: 1})
.then(collected => {
let r = collected.first();
if (r.emoji.name == '✅')
member.addRole(member.guild.roles.find("name", "Authorize"))
.then(() => { console.log(`Added ${member.user.username} (${member.id}).`); })
.catch(console.error);
else if (r.emoji.name == '❎') member.kick("You got rejected.");
r.remove(r.users.last())
});
});
Related
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);
I want people to be able to react to a message and then be contacted by the bot with 3 questions. The problem is that it skips all questions for its own and answers it for its own.
I would be happy if you can describe the problem to me well so that it no longer occurs. Here is my code:
client.on('messageReactionAdd', async (reaction, user) => {
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
if (user.bot) return;
if (reaction.message.channel.id === '809490905236373558') {
if (reaction.emoji.name === '✅') {
const questions = [`Test1`, `Test2`, `Test3`];
const dmChannel = await reaction.message.guild.members.cache
.get(user.id)
.send('**Beantworte die Fragen du keks**');
const collector = dmChannel.channel.createMessageCollector(() => true);
let i = 0;
const res = [];
dmChannel.channel.send(questions[0]);
collector.on('collect', async (msg) => {
if (questions.length == i) return collector.stop('MAX');
const answer = msg.content;
res.push({ question: questions[i], answer });
i++;
if (questions.length == i) return collector.stop('MAX');
else {
dmChannel.channel.send(questions[i]);
}
});
collector.on('end', async (collected, reason) => {
if (reason == 'MAX') {
const data = reaction.message.guild.channels.cache.find(
(ch) =>
ch.name.toLowerCase() == 'apply-final-bewerbungen' &&
ch.type == 'text',
);
await data.send(
`${reaction.message.member || reaction.message.author} (${
reaction.message.author.tag
}) hat eine Bewerbung abgegeben!\n\n${res
.map((d) => `**${d.question}** \n ${d.answer}`)
.join('\n\n')}`,
);
}
});
}
}
});
It sends all questions without waiting because you don't check if the incoming message in your message collector is coming from the member. As the bot sends the first question, there is an incoming message your collector catches (the bot's message) and it sends the next ones till it reaches the end.
You can check if the msg.author is a bot in your collector and stop responding if it is. The following should work:
collector.on('collect', async (msg) => {
if (msg.author.bot) return;
if (questions.length == i) return collector.stop('MAX');
I currently have a Discord bot which reads information of a API that deals with a game server panel.
In this Bot there is tasks that are to start/restart/stop/kill the server. i want to give the option for the end user to react to a embed posted by a bot with a certain reaction to trigger these tasks.
The Command and embed that are posted by the bot are:
The code which currently checks which reaction has been triggered looks like this:
message.channel.send(embed).then(async (sentEmbed) => {
sentEmbed.react("🟩")
sentEmbed.react("🔁")
sentEmbed.react("🟥")
sentEmbed.react("❌")
const filter = (reaction, user) => {
console.log(reaction.emoji.name)
return reaction.emoji.name === '🟩' && user.id === message.author.id;
};
const collector = sentEmbed.createReactionCollector(filter, {time: 20000});
collector.on('collect', (reaction, user) => {
Client.startServer(args[0]).then((response) => {
const start_embed = new Discord.MessageEmbed()
.setTitle(response)
.setColor(settings.embed.color.default)
.setFooter(settings.embed.footer);
message.channel.send(start_embed);
}).catch((error) => {
message.channel.send(client.embederror(error))
});
});
const filter2 = (reaction, user) => {
return reaction.emoji.name === '🔁' && user.id === message.author.id;
};
const collector2 = sentEmbed.createReactionCollector(filter2, {time: 20000});
collector.on('collect', (reaction, user) => {
Client.restartServer(args[0]).then((response) => {
const restart_embed = new Discord.MessageEmbed()
.setTitle(response)
.setColor(settings.embed.color.default)
.setFooter(settings.embed.footer);
message.channel.send(restart_embed);
}).catch((error) => {
message.channel.send(client.embederror(error))
});
});
const filter3 = (reaction, user) => {
return reaction.emoji.name === '🟥' && user.id === message.author.id;
};
const collector3 = sentEmbed.createReactionCollector(filter3, {time: 30000});
collector.on('collect', (reaction, user) => {
console.log(`User Stopped There Server`);
});
const filter4 = (reaction, user) => {
return reaction.emoji.name === '❌' && user.id === message.author.id;
};
const collector4 = sentEmbed.createReactionCollector(filter4, {time: 30000});
collector.on('collect', (reaction, user) => {
console.log(`User Killed There Server`);
});
})
This code works for detecting the reactions onto the message, however when a user reacts with any reaction it runs all of the trigger code, so the bot posts two embeds which i have defined as what the bot should output when a reaction is triggered.
I just want the user to click one reaction, then the bot does something, then the use can click another and the bot does something else.
Thanks in advance
The issue was you used collector.on("collect") 4 times instead of using collector2, collector3 and collector4
It's best not to have variables like that since like it shows you might get confused
Plus you should not have 4 different filters and collectors, especially since you repeat a lot of the code
const validEmojis = ['🟩', '🔁', '🟥', '❌'];
const filter = (reaction, user) => {
return validEmojis.includes(reaction.emoji.name) && user.id === message.author.id;
};
const collector = sentEmbed.createReactionCollector(filter, { time: 20000, maxEmojis: 1 });
collector.on('collect', (reaction, user) => {
const name = reaction.emoji.name;
//you only use it in two cases but I assume you will use it for all later on
const embed = new Discord.MessageEmbed()
.setColor(settings.embed.color.default)
.setFooter(settings.embed.footer);
if (name === '🟩' || name === '🔁') {
const method = name === '🟩' ? "startServer" : "restartServer";
Client[method](args[0])
.then(response => {
embed.setTitle(response);
message.channel.send(start_embed);
}).catch((error) => {
message.channel.send(client.embederror(error))
});
} else if (name === '🟥') {
console.log(`User Stopped There Server`);
} else if (name === '❌') {
console.log(`User Killed There Server`);
}
});
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();
});
};
I am unable to collect a DM in discord.js when i try to use discord message collector
i have tried changing "message.channel" to message.author but it won't work
const collector = new discord.MessageCollector(message.channel, m => m.author.id === message.author.id, { time: 30000 });
collector.on('collect', message => {
if (message.content == strng) {
message.channel.send(`Successfully Verified User: <#${message.author.id}>`).then(m => {
m.delete(30000)
message.member.addRole('470615991555063808')
}).catch(err => console.log(err));
}
})
expected: user DMs bot with correct string and it verifies them
actual: user has to put the string in the same channel as the user originally said !verify
The user has to put the string in the same channel because you're collecting messages in said channel with message.channel as the first MessageCollector argument.
Instead, what you could do is open a DMChannel with the user and return it with .then() like so:
message.author.createDM().then(dmchannel => {
const collector = new discord.MessageCollector(dmchannel, m => m.author.id === message.author.id, { time: 30000 });
collector.on('collect', m => {
if (m.content == strng) {
message.channel.send(`Successfully Verified User: <#${message.author.id}>`)
.then(m => {
m.delete(30000)
message.member.addRole('470615991555063808')}).catch(err => console.log(err))}
})
})
i have worked it out...
i used
message.author.createDM().then(c => {
var verified = new discord.RichEmbed()
.setTitle("Verification Started")
.addField("**User**", `${message.author}`, false)
.setFooter("Goriko Bot")
.setColor(0xfffb00)
.setTimestamp();
message.guild.channels.get('470619175547830315').send(verified).catch(err => console.log(err));
console.log("DM Created")
c.send(verifyEmbed)
console.log(`Embed Sent to ${message.author.tag}`)
const filter = m => m.content.includes("~");
const collector = c.createMessageCollector(filter, { time: 30000 })
console.log("Collector Created")
collector.on('collect', m => {
console.log('Reply Collected')
if (m.content === strng) {
console.log('Success')
c.send("Successfully Verified")
if (message.channel.type == "dm") return;
message.member.addRole('470615991555063808').catch(err => console.log(err));
var successEmbed = new discord.RichEmbed()
.setTitle("Verification Successful")
.addField("**User**", `${message.author}`, true)
.addField("**String**", `\`\`${strng}\`\``, true)
.setFooter("Goriko Bot")
.setColor(0x00ff00)
.setTimestamp();
message.guild.channels.get('470619175547830315').send(successEmbed).catch(err => console.log(err));
} else {
var failEmbed = new discord.RichEmbed()
.setTitle("Verification Failed")
.addField("**User:**", `${message.author}`, true)
.addField("**Correct Token:**", `${strng}`, true)
.addField("**Token Given:**", `${m.content}`, true)
.setColor(0xff0000)
.setFooter("Goriko Bot")
.setTimestamp();
message.guild.channels.get('470619175547830315').send(failEmbed).catch(err => console.log(err));
m.reply("Invalid Token! Please Try Again")
}
})
})