Discord.js Get user from reactions **Updated** - javascript

Update
I have updated the code that is currently working for me, It will now create the channel and then check to see if the channel is create. It will only allow 1 user to create a channel you will not be able to create a T5 channel and a T4 channel as the same user.
Thank you and I hope you all have a great Christmas.
Client.on("message", async (message) => {
if (message.author.Client || message.channel.type === "dm") return;
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = message.content.substring(message.content.indexOf(" ") + 1);
if (cmd === `${prefix}battle`) {
let embed = new Discord.MessageEmbed()
.setTitle("โš”๏ธ 1657 Battles! โš”๏ธ")
.setDescription("React to this message to join the battle.")
.addFields(
{ name: "๐Ÿฅ‡", value: "T5" },
{ name: "๐Ÿฅˆ", value: "T4" },
{ name: "๐Ÿฅ‰", value: "T3" },
{ name: "๐Ÿ…", value: "T2" },
{ name: "๐ŸŽ–", value: "T1" }
)
.setColor("#0099ff")
.setTimestamp()
.setFooter("Please pick the troop type you want to battle with!");
let msgEmbed = await message.channel.send(embed);
msgEmbed.react("๐Ÿฅ‡"); // T5
msgEmbed.react("๐Ÿฅˆ"); // T4
msgEmbed.react("๐Ÿฅ‰"); // T3
msgEmbed.react("๐Ÿ…"); // T2
msgEmbed.react("๐ŸŽ–"); // T1
}
});
Client.on("messageReactionAdd", async (reaction, user, message) => {
//Add an event listener
if (reaction.message.partial) await reaction.message.fetch();
if (user.id === Client.user.id) return; //If the reaction was from the bot, return
if (!reaction.message.guild) return; //If the reaction was not in a guild
const guild = Client.guilds.cache.get("644295524404428832");
if (
guild.channels.cache.find((channel) => channel.name === "t5-battle-channel")
)
return;
if (reaction.emoji.name === "๐Ÿฅ‡") {
let guild = reaction.message.guild;
guild.channels.create("T5 Battle Channel", {
//Creating the channel
type: "text", //Make sure the channel type is text
permissionOverwrites: [
//Set overwrites
{
id: guild.id,
deny: "VIEW_CHANNEL",
},
{
id: "788400016736780338",
allow: ["VIEW_CHANNEL"],
},
],
});
}
if (
guild.channels.cache.find((channel) => channel.name === "t4-battle-channel")
)
return;
if (reaction.emoji.name === "๐Ÿฅˆ") {
let guild = reaction.message.guild;
guild.channels.create("T4 Battle Channel", {
//Creating the channel
type: "text", //Make sure the channel type is text
permissionOverwrites: [
//Set overwrites
{
id: guild.id,
deny: "VIEW_CHANNEL",
},
{
id: "788400619114463275",
allow: ["VIEW_CHANNEL"],
},
],
});
}
if (
guild.channels.cache.find((channel) => channel.name === "t3-battle-channel")
)
return;
if (reaction.emoji.name === "๐Ÿฅ‰") {
let guild = reaction.message.guild;
guild.channels.create("T3 Battle Channel", {
//Creating the channel
type: "text", //Make sure the channel type is text
permissionOverwrites: [
//Set overwrites
{
id: guild.id,
deny: "VIEW_CHANNEL",
},
{
id: "788400701130670110",
allow: ["VIEW_CHANNEL"],
},
],
});
}
if (
guild.channels.cache.find((channel) => channel.name === "t2-battle-channel")
)
return;
if (reaction.emoji.name === "๐Ÿ…") {
let guild = reaction.message.guild;
guild.channels.create("T2 Battle Channel", {
//Creating the channel
type: "text", //Make sure the channel type is text
permissionOverwrites: [
//Set overwrites
{
id: guild.id,
deny: "VIEW_CHANNEL",
},
{
id: "788400738727624704",
allow: ["VIEW_CHANNEL"],
},
],
});
}
if (
guild.channels.cache.find((channel) => channel.name === "t1-battle-channel")
)
return;
if (reaction.emoji.name === "๐ŸŽ–") {
let guild = reaction.message.guild;
guild.channels.create("T1 Battle Channel", {
//Creating the channel
type: "text", //Make sure the channel type is text
permissionOverwrites: [
//Set overwrites
{
id: guild.id,
deny: "VIEW_CHANNEL",
},
{
id: "788400784420372490",
allow: ["VIEW_CHANNEL"],
},
],
});
}
});

If you want to get all of the reactions on a message, you can use the reactions property on a message, if you already have the message object. This will return a ReactionManager which you can use.

You should use a reaction collector.
These work quite similarly to message collectors, except that you
apply them on a message rather than a channel. The following is an
example taken from the documentation, with slightly better variable
names for clarification. The filter will check for the ๐Ÿ‘ emoji - in
the default skin tone specifically, so be wary of that. It will also
check that the person who reacted shares the same id as the author of
the original message that the collector was assigned to.
const filter = (reaction, user) => {
return reaction.emoji.name === '๐Ÿ‘' && user.id === message.author.id;
};
const collector = message.createReactionCollector(filter, { time: 15000 });
collector.on('collect', (reaction, user) => {
console.log(`Collected ${reaction.emoji.name} from ${user.tag}`);
});
collector.on('end', collected => {
console.log(`Collected ${collected.size} items`);
});
Read it's documentation here.
I would like to also know if it is possible to the randomly pair each users that have reacted to a specific role.
The collected property should be handy for this task.
As for adding a role/roles to a GuildMember, use the add method. Read about how you can add a role to a member here.

Related

Ticket bot only saying the id's

I am back again with a question :). I am building my own ticket function, and I just started but if I create a channel for a ticket, its only saying ticket-(Discord account ID) And thats also the case by the embed. Anyone who can look at it?
const discord = require("discord.js");
const { MessageEmbed, Collection, Permissions} = require('discord.js');
const { execute } = require("./ticket");
module.exports = {
name: 'create',
description: 'create your own ticket.',
execute(message, client, args){
if(message.guild.channels.cache.find(channel => channel.name === "Ticket from <#" + message.author + ">")) {
message.reply(`${message.member.user.toString()} **You have successfully created a ticket, Please click on ${channel} to view your ticket**`).then(m => m.delete({ timeout: 14000 }).catch(e => {}));
if(message.guild.channels.cache.find(channel => channel.name === `ticket-${message.author.id}`)) {
return message.reply('<a:no:784463793366761532> **You already have a ticket, please close your exsisting ticket first before opening a new one**');
}
message.delete();
message.guild.channels.create(`Ticket ${message.author}`, {
permissionOverwrites: [
{
id: message.author.id,
allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
},
{
id: message.guild.roles.everyone,
deny: ['VIEW_CHANNEL'],
},
],
type: 'text',
}).then(async channel => {
const embed = new MessageEmbed()
.setTitle("<#" + message.author + "> Ticket")
.setDescription(`**${message.author}, Welcome to your channel! Support will be arriving soon**\n**While you wait please tell us what your problem is**\n**If you want to close the ticket please type .close\`**`)
.setColor("BLUE")
channel.send({ embeds: [embed] })
});
}
}
}
I cleaned up the code a fair bit, less is more. Text channels do not have spaces in them so I replaced them with what Discord uses, hypens. The below code will check if a channel already exists and create one if it doesn't.
const {
MessageEmbed,
} = require('discord.js');
module.exports = {
name: 'create',
description: 'create your own ticket.',
async execute(message, client, args) {
const channelName = `ticket-${message.author.username}`
const existing = message.guild.channels.cache.find(channel => channel.name === channelName.toLowerCase());
if (existing) {
return message.reply({
content: `<a:no:784463793366761532> **You already have a ticket, please close your exsisting ticket first before opening a new one**\n${existing}.`,
}).then((m) => {
setTimeout(() => {
m.delete();
}, 14000);
})
}
message.delete();
message.guild.channels.create(channelName, {
type: 'GUILD_TEXT',
permissionOverwrites: [{
id: message.guild.id,
deny: ['VIEW_CHANNEL'],
}, {
id: message.author.id,
allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
}],
}).then(async channel => {
const embed = new MessageEmbed()
.setColor("BLUE")
.setTitle(`${message.author.username} Ticket`)
.setDescription(`**${message.author}, Welcome to your channel! Support will be arriving soon**\n**While you wait please tell us what your problem is**\n**If you want to close the ticket please type .close\`**`)
channel.send({
embeds: [embed]
})
});
}
}

Setting perms and giving roles to user

I am trying to make a mute command for my bot and ran into these issues. I have been getting them for a very long time now.
const { Guild } = require("discord.js");
module.exports = {
name: "mute",
description: "Mutes a member",
execute(message,args,Mention){
if (message.member.hasPermission("ADMINISTRATOR") || message.author.username === "creepersaur"){
let targetMember = message.mentions.members.first();
const guild = message.guild
let myRole = message.guild.roles.cache.find(role => role.name === "Muted");
if (!myRole) {
newRole = message.guild.roles.create({
data: {
name: 'Muted',
color: 'BLUE',
Permissions: '',
},
reason: `Make a muted role if it doesn't exist.`
})
.then(console.log)
.catch(console.error);
//message.guild.roles.Muted.setPermissions({'SEND_MESSAGES': true})
targetMember.roles.add(newRole).catch(console.error);
message.channel.send(`${targetMember.username} has been muted!`);
} else if (myRole) {
targetMember.roles.add(myRole).catch(console.error);
message.channel.send(`${targetMember.username} has been muted!`);
}
}
}
};
It will see if there is a mute role in the server and if not, then it will create a mute role to give the user. Except the permissions don't work. And because of that, it is not giving the role itself to the user I want. :(
bump x1
I don't really see anything bad in the role section but this code should have the permissions fixed.
const { Guild } = require("discord.js");
module.exports = {
name: "mute",
description: "Mutes a member",
execute(message,args,Mention){
if (message.member.hasPermission("ADMINISTRATOR") || message.author.username === "creepersaur"){
let targetMember = message.mentions.members.first();
const guild = message.guild
let myRole = message.guild.roles.cache.find(role => role.name === "Muted");
if (!myRole) {
newRole = message.guild.roles.create({
data: {
name: 'Muted',
color: 'BLUE',
Permissions: '',
},
reason: `Make a muted role if it doesn't exist.`
})
.then(console.log)
.catch(console.error);
message.guild.channels.cache.forEach(ch =>
{
if(ch.type == "text") {
ch.updateOverwrite(
newRole, {
SEND_MESSAGES: false
}
targetMember.roles.add(newRole).catch(console.error);
message.channel.send(`${targetMember.username} has been muted!`);
} else if (myRole) {
targetMember.roles.add(myRole).catch(console.error);
message.channel.send(`${targetMember.username} has been muted!`);
}
}
}
};

Permission overwrite isn't setting permissions

I don't know why is permissionOverwrites not working for me. No error here. No permissions will change for anyone. I think the problem is here: {allow: 'VIEW_CHANNEL', id: userId,}. I think the problem will be in the id. I hope someone finds out where I made a mistake.
module.exports = (client, Discord, chalk, message, args) => {
const channelId = '799339037306912808'
const getEmoji = (emojiName) =>
client.emojis.cache.find((emoji) => emoji.name === emojiName)
const emojis = {
golden_ticket: 'rules',
}
const handleReaction = (reaction, user, add) => {
if (user.id === '799652033509457940') {
return
}
const emoji = reaction._emoji.name
const { guild } = reaction.message
const userName = user.username
const userId = guild.members.cache.find((member) => member.id === user.id)
const categoryId = '802172599836213258';
if (add) {
reaction.users.remove(userId)
reaction.message.guild.channels
.create(`${userName}`, {
type: 'text',
permissionOverwrites: [
{
allow: 'VIEW_CHANNEL',
id: userId,
}
],
})
.then((channel) => {
channel.setParent(categoryId)
channel => ticketChannelId = channel.id;
message.ticketChannelId.send('cs');
})
} else {
return;
}
}
client.on('messageReactionAdd', (reaction, user) => {
if (reaction.message.channel.id === channelId) {
handleReaction(reaction, user, true)
}
})
}
Here, it is better to specify the type of the overwrite. Plus, "allow" should be an array.
permissionOverwrites: [
{
allow: [ 'VIEW_CHANNEL' ],
id: userId,
type: 'member'
}
],
it should resolve your issue. Note that by default, your channel will be readable by everyone, use:
permissionOverwrites: [
{
deny: ['VIEW_CHANNEL'],
id: reaction.message.guild.id,
type: 'role'
},
{
allow: ['VIEW_CHANNEL'],
id: userId,
type: 'member'
}
],
so everyone can't see the channel except admins and the user

Cannot set permissions on newly created channel

I want to make my bot able to create private tickets. It can create the channel just fine, but when I try to set the permissions on that channel, it says that #everyone is the only role (therefore having default permissions). Also, the console doesn't report any error messages.
To clarify, I can't get the bot to apply permissions to a channel.
const client = new discord.Client();
const config = require("./config.json");
var userTickets = new Map();
client.login(config.token);
client.on("ready", () => {
console.log(client.user.username + "has logged in.")
});
client.on("message", message => {
if(message.author.bot) return;
if(message.content.toLowerCase() === "?crearticket" && message.channel.id === "729851516667691058") {
if(userTickets.has(message.author.id) || message.guild.channels.cache.some(channel =>
channel.name.toLowerCase() === message.author.username + "-ticket")) {
message.author.send("ยกYa tienes un ticket!");
}
else {
let guild = message.guild;
message.guild.channels.create(`${message.author.username}-ticket`, {
type: "text",
permissionsOverwrites: [
{
id: message.author.id,
allow: ["VIEW_CHANNEL"]
},
{
id: message.guild.id,
deny: ["VIEW_CHANNEL"] //This is the part I mentioned.
},
{
id: "729481759955222538",
allow: ["VIEW_CHANNEL"]
},
],
}).then(ch => {
console.log("Creado el canal" + ch.name)
userTickets.set(message.author.id, ch.id);
console.log(userTickets);
}).catch(err => console.log(err));
}
}
else if(message.content.toLowerCase() == "?closeticket"){
if(userTickets.has(message.author.id)) {
if(message.channel.id === userTickets.get(message.author.id)) {
message.channel.delete("Cerrando Ticket")
.then(channel => {
console.log("Eliminado el canal " + channel.name);
userTickets.delete(message.author.id);
})
.catch(err => console.log(err));
}
}
}
});
Change permissionsOverwrites to permissionOverwrites (you had an extra s).
Happy coding!

Discord js quiz bot breaks as soon as multiple users use it

I am a total noob regarding discord bots, but I am trying my best to learn and just try to do the best I can. I am trying to program a bot which lets you take a test in a channel. If you solve 4/5 questions you gain a special role. It seems to work fine if one user is doing it, but as soon as 2 or more users try to take a quiz at the same time, the answers of the questions will be wrong and the amount of questions send into the channel may also vary and I can not figure out why. As far as I understand the message variable gets overwritten as soon as a message will input. But as far as I am concerned javascript runs on a single thread so I do not understand why this is happening. If anyone would be able to help me and/or has some constructive critism i would gladly appreciate it. :)
const meineid = '202469056668762113'
const quiz = require('../quiz.json')
const standartEmbed = new Discord.MessageEmbed()
.setColor('#0099ff')
module.exports = {
name: 't',
description: 't',
execute(message, client) {
let x = message.member.roles.cache.find(role => role.name === 'Regeln')
if (x===undefined) {
assign(message, client)}
else {message.channel.send("bruder was los mit dir")}
}
}
async function assign (message, client) {
if (message.guild.channels.cache.find(c => c.name === message.author.id)) {
message.reply("Channel existiert bereits")
}
else {
await message.guild.channels.create(message.author.id, {
type: 'text',
permissionOverwrites: [
{
id: message.guild.id,
deny: ['VIEW_CHANNEL'],
},
{
id: meineid,
allow: ['VIEW_CHANNEL'],
},
{
id: client.user.id,
allow: ['VIEW_CHANNEL'],
},
{
id: message.author.id,
deny: ['SEND_MESSAGES'],
allow: ['VIEW_CHANNEL'],
},
],
})
message.guild.channels.cache.find(c => c.name === message.author.id).send("<#" + message.author.id + ">")
test(message)
standartEmbed.fields = []
message.guild.channels.cache.find(c => c.name === 'bot-log').send(standartEmbed
.addFields(
{ name: "Created channel: ", value: message.author.id },
)
.setTimestamp())
}
}
async function test(message) {
let y=0
for (z=0; z < 5; z++) {
let i = Math.floor(Math.random() * quiz.length)
item = quiz[i]
quiz.splice(i, 1)
const reactions = ['๐Ÿ‡ฆ','๐Ÿ‡ง','๐Ÿ‡จ']
const quizEmbed = new Discord.MessageEmbed()
.setColor('#0099ff')
const filter = (reaction, user) => {
return reactions.includes(reaction.emoji.name) && user.id === message.author.id
}
await message.guild.channels.cache.find(c => c.name === message.author.id.toString()).send(quizEmbed
.setTitle(item.question)
.addFields(
{ name: reactions[0], value: item.options[0] },
{ name: reactions[1], value: item.options[1] },
{ name: reactions[2], value: item.options[2] },
)
.setTimestamp()
)
.then(async function(message) {
reactions.forEach(r => message.react(r))
await message.awaitReactions(filter, {max:1, time: 11110000})
.then(function(collected) {
if (collected.first().emoji.name == item.answer) {
message.channel.send("Richtig! :)")
y++
return y
} else message.channel.send("Falsch! :(")
return y
}).catch(collected => {
z=5
})
return y
})
}
}```
where are you closing this for statement?
for (z=0; z < 5; z++) {

Categories