const ms = require('ms');
const { MessageEmbed } = require('discord.js')
module.exports = {
name: 'giveaway',
description: 'start a giveaway',
async execute(client, message, cmd, args, Discord){
let author = message.author.username;
var time;
time = args[0];
let title = args.join(" ").slice(3);
if(!message.member.permissions.has(['ADMINISTRATOR'])){
message.channel.send(`Sorry **${author}** But you don't have enough permissions to use this command!`)
} else {
if(message.member.permissions.has(['ADMINISTRATOR'])){
let giveawayEmbed = new MessageEmbed()
.setColor('BLACK')
.setThumbnail(`${message.author.displayAvatarURL()}`)
.setTitle(`${author}'s Giveaway 🎉`)
.setDescription(`**${title}**`)
.addField(`Duration :`, ms(ms(time), {
long: true
}), true)
.setFooter("React to this message with 🎉 to participate !")
var giveawaySent = await message.channel.send({ embeds: [giveawayEmbed] });
giveawaySent.react('🎉');
console.log(giveawaySent.id)
setTimeout(async function(){
const react = await giveawaySent.reactions.cache.find(r => r.emoji.name === '🎉').users.fetch();
let index = Math.map(Math.random() * react.length);
let winner = react[index];
console.log(react)
console.log(index)
console.log(winner)
let winnerEmbed = new MessageEmbed()
.setColor('GREEN')
.setDescription(`Congratulations **${winner}** you won **${title}**`)
message.reply({ embeds: [winnerEmbed] })
}, ms(time))
}
}
}
}
I'm trying to code a giveaway module however the winner result is coming out as undefined and I can't seem to figure out why, If you guys can help me out be greatly appreciated
These were logged by the console if it helps any
index = NaN
winner = undefined
const ms = require('ms');
const { MessageEmbed } = require('discord.js')
module.exports = {
name: 'giveaway',
description: 'start a giveaway',
async execute(client, message, cmd, args, Discord){
let author = message.author.username;
var time;
time = args[0];
let title = args.join(" ").slice(3);
if(!message.member.permissions.has(['ADMINISTRATOR'])){
message.channel.send(`Sorry **${author}** But you don't have enough permissions to use this command!`)
} else {
if(message.member.permissions.has(['ADMINISTRATOR'])){
let giveawayEmbed = new MessageEmbed()
.setColor('BLACK')
.setThumbnail(`${message.author.displayAvatarURL()}`)
.setTitle(`${author}'s Giveaway 🎉`)
.setDescription(`**${title}**`)
.addField(`Duration :`, ms(ms(time), {
long: true
}), true)
.setFooter("React to this message with 🎉 to participate !")
var giveawaySent = await message.channel.send({ embeds: [giveawayEmbed] });
giveawaySent.react('🎉');
console.log(giveawaySent.id)
setTimeout(async function(){
const react = await giveawaySent.reactions.cache.find(r => r.emoji.name === '🎉').users.fetch();
const reactArray = react.map(c => c)
let index = Math.floor(Math.random() * reactArray.length);
let winner = reactArray[index];
console.log(reactArray)
// console.log(react)
console.log(index)
console.log(winner)
let winnerEmbed = new MessageEmbed()
.setColor('GREEN')
.setDescription(`Congratulations **${winner}** you won **${title}**`)
message.reply({ embeds: [winnerEmbed] })
}, ms(time))
}
}
}
}
Seems to have resolved the issue, Added const reactArray = react.map(c => c)
Changed
let index = Math.floor(Math.random() * react.length); to let index = Math.floor(Math.random() * reactArray.length); which made const react = await giveawaySent.reactions.cache.find(r => r.emoji.name === '🎉').users.fetch(); into an array of user id's
Related
const { Client, Message, MessageEmbed, Intents } = require("discord.js");
module.exports = {
name: "sbfeedback",
/**
* #parom {Client} client
* #parom {Message} message
* #parom {String[]} args
*/
async execute(client, message, args) {
const questions = [
"What feedback would you like to give?",
"Anything else you would like to add?"
];
let collectCounter = 0;
let endCounter = 0;
const filter = (m) => m.author.id === message.author.id;
const appStart = await message.author.send(questions[collectCounter++]);
const channel = appStart.channel;
const collector = channel.createMessageCollector(filter);
message.delete({timeout: 100})
collector.on("collect", () => {
if (collectCounter < questions.length) {
channel.send(questions[collectCounter++]);
} else {
channel.send("Thank you for your feedback! If you would like to suggest anything else please do so with `-sbfeedback`.");
collector.stop("fulfilled");
}
});
const appsChannel = client.channels.cache.get("886099865094983691");
collector.on("end", (collected, reason) =>{
if (reason === "fulfilled") {
let index = 1;
const mappedResponses = collected
.map((msg) => {
return `${index++}) ${questions[endCounter++]}\n-> ${msg.content}`;
})
.join("\n\n");
appsChannel.send(
new MessageEmbed()
.setAuthor(message.author.tag, message.author.displayAvatarURL({ dynamic: true}))
.setTitle("!")
.setDescription(mappedResponses)
.setColor(`RANDOM`)
.setTimestamp()
);
message.react('👍').then(() => message.react('👎'));
}
});
},
appsChannel.send returns a Promise and once it's resolved, you can grab the sent message, so you can add your reactions:
collector.on('end', (collected, reason) => {
if (reason === 'fulfilled') {
let index = 1;
const mappedResponses = collected
.map((msg) => {
return `${index++}) ${questions[endCounter++]}\n-> ${msg.content}`;
})
.join('\n\n');
appsChannel
.send(
new MessageEmbed()
.setAuthor(
message.author.tag,
message.author.displayAvatarURL({ dynamic: true }),
)
.setTitle('!')
.setDescription(mappedResponses)
.setColor(`RANDOM`)
.setTimestamp(),
)
.then((sent) => {
sent.react('👍');
sent.react('👎');
});
}
});
I'm trying to make a draft bot that takes the player amount from an interaction in my draftSize.js file and uses that value in my join.js file as a maximum value for my MessageComponentCollector.
Here is draftSize.js
const { SlashCommandBuilder } = require('#discordjs/builders');
const { MessageActionRow, MessageButton } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('size')
.setDescription('Sets the size of total players in your draft.')
.addIntegerOption(option =>
option.setName('players')
.setDescription('Amount of players participating in the draft.')
.setRequired(true)),
async execute(interaction) {
let playerSize = interaction.options.getInteger('players');
await interaction.reply({ content: `You\'ve selected a ${playerSize} player draft. \n Next, type: ` + "```" + '/captains {#FirstCaptain} {#SecondCaptain}' + "```"});
console.log("test " + playerSize)
},
};
And here is join.js:
const { SlashCommandBuilder } = require('#discordjs/builders');
const { MessageActionRow, MessageButton, Message } = require('discord.js');
const { playerSize } = require('./draftSize');
module.exports = {
data: new SlashCommandBuilder()
.setName('join')
.setDescription('Allow players to join your draft.'),
async execute(interaction, channel) {
const row = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId('joinButton')
.setLabel('Join')
.setStyle('SUCCESS'),
);
await interaction.reply({ content: `To join the draft, click the button below. Once the specified player amount has joined, the draft will begin!`, components: [row] });
const filter = i => {
return i.customId === 'joinButton'
};
const playerList = []
const collectChannel = interaction.channel;
const collector = collectChannel.createMessageComponentCollector({
filter,
max: playerSize,
time: 1000 * 30
})
collector.on('collect', (i = MessageComponentInteraction) => {
i.reply({
content: 'you clicked a button',
ephemeral: true
})
console.log(playerSize)
})
collector.on('end', (collection) => {
collection.forEach((click) => {
playerList.push(click.user.username)
})
collectChannel.send({ content: 'testing'})
console.log(playerList);
})
},
};
In my draftSize.js I get my playerSize value, but whenever I try to import the value into my join.js file to use as my collectors max value it always returns undefined.
Sorry if any of this was unclear. Let me know if you need any clarification.
Thanks!
so what I am trying to do is when a user write a command such as
!setchannel #test or !setchannel 86xxxxxxxxxxxxxxx
then the bot will send the random messages to that channel every certain time.
Note that I did the random messages code but I still stuck on creating the !setchannel command.
I am using discord.js v12.5.3
index.js main file
require('events').EventEmitter.prototype._maxListeners = 30;
const Discord = require('discord.js')
const client = new Discord.Client()
require('discord-buttons')(client);
const ytdl = require('ytdl-core');
const config = require('./config.json')
const mongo = require('./mongo')
const command = require('./command')
const loadCommands = require('./commands/load-commands')
const commandBase = require('./commands/command-base')
const { permission, permissionError } = require('./commands/command-base')
const cron = require('node-cron')
const zkrList = require('./zkr.json')
const logo =
'URL HERE'
const db = require(`quick.db`)
let cid;
const { prefix } = config
client.on('ready', async () => {
await mongo().then((mongoose) => {
try {
console.log('Connected to mongo!')
} finally {
mongoose.connection.close()
}
})
console.log(`${client.user.tag} is online`);
console.log(`${client.guilds.cache.size} Servers`);
console.log(`Server Names:\n[ ${client.guilds.cache.map(g => g.name).join(", \n ")} ]`);
loadCommands(client)
cid = db.get(`${message.guild.id}_channel_`)
cron.schedule('*/10 * * * * *', () => {
const zkrRandom = zkrList[Math.floor(Math.random() * zkrList.length)]
const zkrEmbed = new Discord.MessageEmbed()
.setDescription(zkrRandom)
.setAuthor('xx', logo)
.setColor('#447a88')
client.channels.cache.get(cid).send(zkrEmbed);
})
client.on("message", async message => {
if (message.author.bot) {
return
}
try {if (!message.member.hasPermission('ADMINISTRATOR') && message.content.startsWith('!s')) return message.reply('you do not have the required permission') } catch (err) {console.log(err)}
if (!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g)
const cmd = args[0]
if (cmd === "s") {
let c_id = args[1]
if (!c_id) return message.reply("you need to mention the text channel")
c_id = c_id.replace(/[<#>]/g, '')
const channelObject = message.guild.channels.cache.get(c_id);
if (client.channels.cache.get(c_id) === client.channels.cache.get(cid)) return message.reply(`we already sending to the mentioned text channel`);
if (client.channels.cache.get(c_id)) {
await db.set(`${message.guild.id}_channel_`, c_id); //Set in the database
console.log(db.set(`${message.guild.id}_channel_`))
message.reply(`sending to ${message.guild.channels.cache.get(c_id)}`);
cid = db.get(`${message.guild.id}_channel_`)
const zkrRandom = zkrList[Math.floor(Math.random() * zkrList.length)]
const zkrEmbed = new Discord.MessageEmbed()
.setDescription(zkrRandom)
.setAuthor('xx', logo)
.setColor('#447a88')
client.channels.cache.get(cid).send(zkrEmbed);
} else {
return message.reply("Error")
}
}
})
})
client.login(config.token)
zkr.json json file
[
"message 1",
"message 2",
"message 3"
]
You'll have to use a database to achieve what you're trying to do
An example using quick.db
const db = require(`quick.db`)
const prefix = "!"
client.on("message", async message => {
if (!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g)
const cmd = args[0]
if (cmd === "setchannel") {
let c_id = args[1]
if (!c_id) return message.reply("You need to mention a channel/provide id")
c_id = c_id.replace(/[<#>]/g, '')
if (client.channels.cache.get(c_id)) {
await db.set(`_channel_`, c_id) //Set in the database
} else {
return message.reply("Not a valid channel")
}
}
})
Changes to make in your code
client.on('ready', async () => {
let c_id = await db.get(`_channel_`)
cron.schedule('*/10 * * * * *', () => {
const zkrRandom = zkrList[Math.floor(Math.random() * zkrList.length)]
const zkrEmbed = new Discord.MessageEmbed()
.setTitle('xx')
.setDescription(zkrRandom)
.setFooter("xx")
.setColor('#447a88')
.setAuthor('xx#8752')
client.channels.cache.get(c_id).send(zkrEmbed)
})
})
The above sample of quick.db is just an example
If you're using repl.it, I recommend you to use quickreplit
Edit
require('events').EventEmitter.prototype._maxListeners = 30;
const Discord = require('discord.js')
const client = new Discord.Client()
const ytdl = require('ytdl-core');
const config = require('./config.json')
const mongo = require('./mongo')
const command = require('./command')
const loadCommands = require('./commands/load-commands')
const commandBase = require('./commands/command-base')
const cron = require('node-cron')
const zkrList = require('./zkr.json')
const db = require(`quick.db`)
const prefix = "!"
let cid;
client.on('ready', async () => {
await mongo().then((mongoose) => {
try {
console.log('Connected to mongo!')
} finally {
mongoose.connection.close()
}
})
console.log(`${client.user.tag} is online`);
console.log(`${client.guilds.cache.size} Servers`);
console.log(`Server Names:\n[ ${client.guilds.cache.map(g => g.name).join(", \n ")} ]`);
cid = db.get('_channel_')
loadCommands(client)
//commandBase.listen(client);
})
cron.schedule('*/10 * * * * *', () => {
const zkrRandom = zkrList[Math.floor(Math.random() * zkrList.length)]
const zkrEmbed = new Discord.MessageEmbed()
.setTitle('xx')
.setDescription(zkrRandom)
.setFooter("xx")
.setColor('#447a88')
.setAuthor('xx#8752')
client.channels.cache.get(cid).send(zkrEmbed);
})
client.on("message", async message => {
console.log(db.get('_channel_'))
if (!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g)
const cmd = args[0]
if (cmd === "s") {
let c_id = args[1]
if (!c_id) return message.reply("You need to mention a channel/provide id")
c_id = c_id.replace(/[<#>]/g, '')
if (client.channels.cache.get(c_id)) {
console.log('old channel')
console.log(db.get('_channel_'))
await db.set(`_channel_`, c_id); //Set in the database
message.reply(`sending in this channel ${message.guild.channels.cache.get(c_id)}`);
} else {
return message.reply("Not a valid channel")
}
}
})
So I am trying to make a suggestion command using discord buttons in Discord.JS. When I run the command the embed and the buttons send but whenever I click one of the buttons whether it be Upvote, Maybe, or Downvote it edits the embed, but it never updates the number. I've tried upvote_number ++ and upvote_number + 1 but it doesn't work. It would be awesome if somebody could help me with this. Thank you.
const Discord = require('discord.js');
const disbut = require('discord-buttons');
const { MessageActionRow, MessageButton } = require("discord-buttons");
const { Color, Prefix } = require("../../config.js");
const { MessageEmbed } = require("discord.js");
const disbutpages = require("discord-embeds-pages-buttons")
const db = require('quick.db');
module.exports = {
name: "suggest",
aliases: [],
description: "Suggestion Command",
usage: "^suggest <suggestion>",
run: async(client, message, args) => {
const SayMessage = message.content.slice(8).trim();
let upvote_number = 0
let downvote_number = 0
let maybe_number = 0
const embed = new Discord.MessageEmbed()
.setAuthor("Suggestion from: " + message.author.tag, message.author.displayAvatarURL({dynamic: true}))
.setThumbnail(message.author.displayAvatarURL({dynamic: true}))
.setDescription(SayMessage)
.addField(`Votes`, `Upvote: **${upvote_number}**
Downvote: **${downvote_number}**`)
let upvotebutton = new MessageButton()
.setLabel(`Upvote`)
.setID(`upvote`)
.setEmoji(`⬆️`)
.setStyle("green")
let maybebutton = new MessageButton()
.setLabel(`Maybe`)
.setID(`maybe`)
.setEmoji(`🤷`)
.setStyle("blurple")
let downvotebutton = new MessageButton()
.setLabel(`Downvote`)
.setID(`downvote`)
.setEmoji(`⬇️`)
.setStyle("red")
let row = new MessageActionRow()
.addComponents(upvotebutton, maybebutton, downvotebutton)
const MESSAGE = await message.channel.send(embed, { components: [row] })
const filter = ( button ) => button.clicker.user.id === message.author.id
const collector = MESSAGE.createButtonCollector(filter, { time : 120000 });
collector.on('collect', async (b) => {
if(b.id == "upvote") {
await upvote_number + 1
await MESSAGE.edit(embed, { components: [row] });
await b.reply.defer()
}
if(b.id == "downvote") {
downvote_number + 1
MESSAGE.edit(embed, { components: [row] });
await b.reply.defer()
}
if(b.id == "maybe") {
maybe_number + 1
MESSAGE.edit(embed, { components: [row] });
await b.reply.defer()
}
})
collector.on('end', (b) => {
})
}
};
You'd want to use the += operator for your question. By the way, because of how button collectors work, the suggestions will be timing out after some time, which may cause you some issues in the future, so you may want to switch to the event. My only other concerns are that you are using d.js 12 and discord-buttons which are both deprecated. As d.js 12 is losing support soon because of discord's api updates, I'd highly recommend switching to v13, as it has built in buttons, along with many other new features such as menus and slash commands.
let upvote_number = 0
let downvote_number = 0
let maybe_number = 0
/* ... */
collector.on('collect', async b => {
if(b.id == "upvote") {
upvote_number += 1
updateEmbed()
await MESSAGE.edit(embed, { components: [row] })
await b.reply.defer()
} else if (b.id == "downvote") {
downvote_number += 1
updateEmbed()
await MESSAGE.edit(embed, { components: [row] })
await b.reply.defer()
} else if (b.id == "maybe") {
maybe_number += 1
updateEmbed()
await MESSAGE.edit(embed, { components: [row] })
await b.reply.defer()
}
});
updateEmbed(){
embed.fields.find(i=>i.name==='Votes').value = `Upvote: **${upvote_number}**
Downvote: **${downvote_number}**`
}
tldr: Use += to set vars dynamically as well as update the embed object, and update to `discord.js#latest`
I have the below code which is intended to create a new channel with a name. This works fine. It then needs to set the permissions of the channel to making it VIEW_CHANNEL false for all users. It then needs to overwrite permissions for the message author to grant them VIEW_CHANNEL. Im getting stuck on how to make the permissions apply on the channel just created.
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
let botIcon = bot.user.displayAvatarURL;
let ticketEmbed = new Discord.RichEmbed()
.setDescription("TicketBot")
.setColor("#bc0000")
.setThumbnail(botIcon)
.addField("New Ticket", `${message.author} your ticket has been created.`);
let ticketchannel = message.guild.channels.find(`name`, "bot-testing");
if(!ticketchannel) return message.channel.send("Couldn't find bot testing channel.");
ticketchannel.send(ticketEmbed);
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
let ticketid = getRandomInt(10000);
let name = `ticket-${message.author.username}-${ticketid}`;
message.guild.createChannel(name, "text")
.then(
message.channel.overwritePermissions(message.author, {
VIEW_CHANNEL: true
})
);
}
module.exports.help = {
name: "new"
}
The below code works :)
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
let botIcon = bot.user.displayAvatarURL;
let ticketEmbed = new Discord.RichEmbed()
.setDescription("TicketBot")
.setColor("#bc0000")
.setThumbnail(botIcon)
.addField("New Ticket", `${message.author} your ticket has been created.`);
let ticketchannel = message.guild.channels.find(`name`, "bot-testing");
if(!ticketchannel) return message.channel.send("Couldn't find bot testing channel.");
ticketchannel.send(ticketEmbed);
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
let ticketid = getRandomInt(10000);
let name = `ticket-${message.author.username}-${ticketid}`;
message.guild.createChannel(name, "text")
.then(m => {
m.overwritePermissions(message.guild.id, {
VIEW_CHANNEL: false
})
m.overwritePermissions(message.author.id, {
VIEW_CHANNEL: true
})
})
//channel.delete()
}
module.exports.help = {
name: "new"
}