I am making my first Discord Bot, using Discord.js - I can make it read a command !makeraid and the bot will ask the first question, and store the response into an array.
I want to be able to ask multiple questions like raid name, description, date, and time. I have not yet got this far, after the first question is asked, as a test i want the bot to create the embed message.
However, i cannot make it trigger/fire the next question.
client.on('message', message => {
if (message.content.toLowerCase().startsWith("!makeraid")) {
const filter = m => m.author.id === message.author.id;
var raid = {};
var color = ((1 << 24) * Math.random() | 0).toString(16);
var raidImages = {'DDS':'https://i.imgur.com/izsm8ri.jpg','GR':'https://i.imgur.com/4S9NKtF.jpg','CR':'https://i.imgur.com/EnYiWka.jpg','OR':'https://i.imgur.com/VOYDUlO.jpg'};
message.reply('Raid Name?').then(r => r.delete(10000));
message.channel.awaitMessages(filter, {
max: 1,
time: 10000,
errors: ['time'],
})
.then((collected) => {
raid.title = collected.first().content;
console.log(raid);
collected.first().delete(5000);
})
.catch(() => {
message.channel.send('Raid Cancelled - Too Slow!').then(r => r.delete(5000));
});
while ( Object.keys(raid).length > 0 ) {
message.reply('Do you want to create the raid? Yes or No.').then(r => r.delete(10000));
message.channel.awaitMessages(filter, {
max: 1,
time: 10000,
errors: ['time'],
})
.then((collected) => {
if (collected.first().content.toLowerCase() === "yes") {
collected.first().delete();
var raidEmbed = new Discord.RichEmbed()
.setColor('#'+color)
.setAuthor('Raid Bot', client.user.avatarURL)
.setTitle(':star::star: '+raid.title+' :star::star:')
.setThumbnail(client.user.avatarURL)
.setDescription('Some description here')
.addField('Date', 'Some value here', true)
.addField('Time', 'Some value here', true)
.setTimestamp()
.setFooter('Raid created by: '+ message.member.user.tag, message.member.user.avatarURL);
message.channel.send(raidEmbed).then(async embedMessage => {
await embedMessage.react('β
');
await embedMessage.react('β');
await embedMessage.react('π½');
});
} else {
collected.first().delete();
message.channel.send('Raid Cancelled').then(r => r.delete(5000));
}
})
.catch(() => {
message.channel.send('Raid Cancelled - Too Slow! (Make)').then(r => r.delete(5000));
});
}
message.delete();
} else if (message.content.toLowerCase().startsWith("!help")) {
message.reply('You Suck π').then(r => r.delete(10000));
message.delete();
}
});
No errors are coming up in the terminal, it just does nothing after the first response has been collected and push into the array.
Related
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);
}
I got a problem with my ticket bot. I have a ticket bot that gives you 5 options, but the bot doesn't really work. Sometimes it does make a ticket on reaction sometimes it just adds the reaction but doesn't make a ticket. I have 2 bots with this issue now so I'm guess I'm just doing it wrong.
Also I'm getting no errors in my console, and I never have the issue my self but other people sometimes do!
bot.on('messageReactionAdd', (reaction, user) => {
if (user.bot) {
return;
}
reaction.users.remove(user.id)
bot.users.fetch(user.id).then((user) => {
let channelId = "";
let query = `SELECT * FROM ticketMessage`;
db.get(query, (err, row) => {
let ticketMessage = row.MessageId;
if (reaction.emoji.name == "π¦") {
const startTicket = async (name) => {
reaction.message.channel.guild.channels.create(user.username + name, {
type: 'text'
})
.then(channel => {
let category = "";
category = reaction.message.channel.guild.channels.cache.find(c => c.id == settings["Categories"].ticketcategory && c.type == "category");
if (!category) {
user.send("Couldn't Process your ticket since there is no category setup for it!")
} else {
channel.setParent(category.id).then(() => {
channelId = channel.id
sendQuestions()
})
}
}).catch(console.error);
}
startTicket(" Dino Lines");
const sendQuestions = async () => {
ticketChannel = bot.channels.cache.get(channelId)
await ticketChannel.updateOverwrite(user, {
VIEW_CHANNEL: true
});
const filter = m => m.author.id === user.id && m.channel === ticketChannel;
embed2 = new Discord.MessageEmbed();
embed2
.setDescription("What are the names of the dino's you would like to buy, Example => (T-rex, Bronto)?")
.setFooter(settings["Embeds"].displayname, settings["Embeds"].image)
.setColor(settings["Embeds"].color)
.setTimestamp()
ticketChannel.send(embed2);
ticketChannel.awaitMessages(filter, {
max: 1,
time: 120000
})
.then(collected => {
let dinoName = collected.first().content
embed3 = new Discord.MessageEmbed();
embed3
.setDescription("How many dino's would you like to buy, Example => (Dino1: 5, Dino2: 3)?")
.setFooter(settings["Embeds"].displayname, settings["Embeds"].image)
.setColor(settings["Embeds"].color)
.setTimestamp()
ticketChannel.send(embed3);
ticketChannel.awaitMessages(filter, {
max: 1,
time: 120000
})
.then(collected => {
let amount = collected.first().content
embed4 = new Discord.MessageEmbed();
embed4
.setDescription("What kind of currency would you like to use, Example => (Money, Items)?")
.setFooter(settings["Embeds"].displayname, settings["Embeds"].image)
.setColor(settings["Embeds"].color)
.setTimestamp()
ticketChannel.send(embed4);
ticketChannel.awaitMessages(filter, {
max: 1,
time: 120000
})
.then(collected => {
let currencyKind = collected.first().content
embed5 = new Discord.MessageEmbed();
embed5
.setDescription("Do you want to submit this ticket? => (Yes, No)")
.setFooter(settings["Embeds"].displayname, settings["Embeds"].image)
.setColor(settings["Embeds"].color)
.setTimestamp()
ticketChannel.send(embed5);
ticketChannel.awaitMessages(filter, {
max: 1,
time: 120000
})
.then(collected => {
let yn = collected.first().content
if (yn.toLowerCase() == "yes") {
embed1 = new Discord.MessageEmbed
ticketChannel.bulkDelete(8, true)
embed1
.setTitle(user.username + "'s Ticket")
.addFields({
name: "Buying Dino Lines",
value: "\u200b \n **Dino Names:** " + dinoName + "\n **Dino Count:** " + amount + "\n **Payment Methode:** " + currencyKind,
inline: true
}, )
.setFooter(settings["Embeds"].displayname, settings["Embeds"].image)
.setColor(settings["Embeds"].color)
.setTimestamp()
ticketChannel.send(embed1)
} else {
ticketChannel.send("Okay ticket canceled!");
}
})
})
})
})
}
Discord only fires events to cached messages. You will either have to fetch the message on startup, or use the raw event instead, for example:
bot.on('raw', (packet) => {
if (packet.t == "MESSAGE_REACTION_ADD") {
// Your code here
}
});
Keep in mind that you would have to re-work it if you used packets, as the data structure is different from what the messageReactionAdd event returns.
Good Evening, I would like some help on how to get the collected users to post in the .setDescription of my embed. For some reason, everything I try to do returns an error or posts object Object or object Map in the description of the embed. As you can see I am getting the console log for the users that have reacted to the post all I want to do now is get all the users and post them in the embed.
At first, u wanted to get all the users and then randomly pair them into a 1v1 battle however I was informed I would need to use a database for them. If anyone could give me some information on that it would be appreciated.
Thank you Ukzs
.then((channel) => {
channel.send(embed).then((embedMessage) => {
embedMessage.react("π");
embedMessage.react("π");
const filter = (reaction, user) => {
return ["π", "π"].includes(reaction.emoji.name) && !user.bot;
};
const collector = embedMessage.createReactionCollector(filter, {
time: 10000,
});
const destination = guild.channels.cache.find(
(channel) => channel.name === "t5-battle-channel"
);
collector.on("collect", (reaction) => {
if (reaction.emoji.name === "π") {
console.log(reaction.users);
}
});
collector.on("end", (collected) => {
if (destination) {
let embed6 = new Discord.MessageEmbed()
.setColor("#0099ff")
.setTitle("βοΈ Members that have joined the T5 Battles! βοΈ")
.setDescription(`${reaction.fetch("π")} Would like to battle!`)
.setTimestamp()
.setFooter("βοΈ 1657 Battles! βοΈ | βοΈ Managed by UkzsβοΈ");
destination.send(embed6);
}
});
});
});
.then((channel) => {
channel.send(embed).then((embedMessage) => {
embedMessage.react("π");
embedMessage.react("π");
const filter = (reaction, user) => {
return ["π", "π"].includes(reaction.emoji.name) && !user.bot;
};
const collector = embedMessage.createReactionCollector(filter, {
time: 10000,
});
const destination = guild.channels.cache.find(
(channel) => channel.name === "t5-battle-channel"
);
collector.on("collect", (reaction) => {
if (reaction.emoji.name === "π") {
console.log(reaction.users);
}
});
collector.on("end", (collected) => {
if (destination) {
let userArr = [];
let users = collected.first().users.cache.filter(u => !u.bot);
users.forEach(user => userArr.push(user.username));
let embed6 = new Discord.MessageEmbed()
.setColor("#0099ff")
.setTitle("βοΈ Members that have joined the T5 Battles! βοΈ")
.setDescription(`${userArr.join(", ")} Would like to battle!`)
.setTimestamp()
.setFooter("βοΈ 1657 Battles! βοΈ | βοΈ Managed by UkzsβοΈ");
destination.send(embed6);
}
});
});
});
I have edited your collector.on("end"..) event. I made an Array where the users get stored in. In users, all users that are no bots get stored. Then we push every username from the users we got from users, into the Array userArr. And now in the description of the embed, every value of userArr (the usernames) gets seperated by , (if there is only one there will be no comma). That is what the function join(", ") does.
I'm having problems while adding multiple reactions to a message (trying to add 8-9).
Basically, the script adds the reactions normally if you wait, but if you react to a emoji before the scripts add them all, it keeps trying to add the rest of the emojis even after the message already got deleted, throwing the error below.
(node:17500) UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Message
at RequestHandler.execute (C:\Users\#######\Documents\project-folder\node_modules\discord.js\src\rest\RequestHandler.js:170:25)
at processTicksAndRejections (internal/process/task_queues.js:89:5)
So, any idea of what I'm doing wrong?
// Context
message.channel.send({ embed: randomEmbed }).then((msg) => {
msg.react(emNumber[0]).then(() => {
for (let i = 0; i < dcArr.length && !msg.deleted; i++) {
if (dcArr[i]["server_id"] == user.server_id) continue;
msg.react(emNumber[i + 1]);
}
});
var filter = (reaction, user) => {
return (
emNumber.slice(0, dcArr.length - 1).includes(reaction.emoji.name) &&
user.id === discId
);
};
msg
.awaitReactions(filter, { max: 1, time: 20000, errors: ["time"] })
.then(async (collected) => {
msg.delete();
message.channel.send({ embed: anotherRandomEmbed }).then((msg) => {
msg.react(emThumbs[1]);
msg.react(emThumbs[0]);
// Something
var filter = (reaction, user) => {
return emThumbs.includes(reaction.emoji.name) && user.id === discId;
};
msg
.awaitReactions(filter, { max: 1, time: 20000, errors: ["time"] })
.then(async (collected) => {
// Something else
});
});
});
});
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")
}
})
})