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('👎');
});
}
});
Related
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")
}
}
})
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
i have a problem sending text from yaml. Saving text works but sending does not. Here's the code:
const { Message, MessageEmbed } = require("discord.js")
const { channel } = require('./kanal')
const db = require('quick.db')
module.exports = {
name: "reklama",
guildOnly: true,
description:
"Change guild prefix. If no arguments are passed it will display actuall guild prefix.",
usage: "[prefix]",
run(msg, args, guild) {
if (!guild) {
const guld = new MessageEmbed()
.setTitle("Błąd!")
.setColor("RED")
.setDescription("Tą komende można tylko wykonać na serwerze!")
.setThumbnail('https://emoji.gg/assets/emoji/3485-cancel.gif')
.setTimestamp()
.setFooter(`${msg.author.tag} (${msg.author.id})`, `${msg.author.displayAvatarURL({dynamic: true})}`)
msg.channel.send(guild)
}
const { settings } = client
const prefixArg = args[0]
if (!settings.get(guild.id)) {
settings.set(guild.id, { prefix: null })
}
if (!prefixArg) {
let Reklama = client.settings.get(guild.id).Reklama
let Kanal = client.settings.get(guild.id).Kanał
const embed = new MessageEmbed()
.setTitle(`Informacje o serwerze: ${msg.guild.name}`)
.addField("Treść reklamy:", Reklama)
.addField("Kanał do wysyłania reklam:", Kanal)
msg.channel.send(embed)
}
setInterval(() => {
Kanal.send(`${Reklama}`)
}, 1000)
},catch(e){
console.log(e)
}
}
Here is a part of command handler:
const args = msg.content.slice(length).trim().split(" ")
const cmdName = args.shift().toLowerCase()
const cmd =
client.commands.get(cmdName) ||
client.commands.find(
(cmd) => cmd.aliases && cmd.aliases.includes(cmdName),
)
try {
cmd.run(msg, args)
} catch (error) {
console.error(error)
}
})
}
The problem is that when I start the bot, it shows me such an error:
let Reklama = client.settings.get(guild.id).Reklama
^
TypeError: Cannot read property 'id' of undefined
The problem is you don't pass the guild variable to your run method. You call cmd.run(msg, args) but run accepts three parameters.
You can either pass the guild or get it from the msg like this:
module.exports = {
name: 'reklama',
guildOnly: true,
description:
'Change guild prefix. If no arguments are passed it will display actuall guild prefix.',
usage: '[prefix]',
run(msg, args) {
// destructure the guild the message was sent in
const { guild } = msg;
if (!guild) {
const embed = new MessageEmbed()
.setTitle('Błąd!')
.setColor('RED')
.setDescription('Tą komende można tylko wykonać na serwerze!')
.setThumbnail('https://emoji.gg/assets/emoji/3485-cancel.gif')
.setTimestamp()
.setFooter(
`${msg.author.tag} (${msg.author.id})`,
`${msg.author.displayAvatarURL({ dynamic: true })}`,
);
return msg.channel.send(embed);
}
const { settings } = client;
const prefixArg = args[0];
if (!settings.get(guild.id)) {
settings.set(guild.id, { prefix: null });
}
if (!prefixArg) {
let Reklama = client.settings.get(guild.id).Reklama;
let Kanal = client.settings.get(guild.id).Kanał;
const embed = new MessageEmbed()
.setTitle(`Informacje o serwerze: ${msg.guild.name}`)
.addField('Treść reklamy:', Reklama)
.addField('Kanał do wysyłania reklam:', Kanal);
msg.channel.send(embed);
}
setInterval(() => {
Kanal.send(`${Reklama}`);
}, 1000);
},
catch(e) {
console.log(e);
},
};
I have been trying to make a function where I tell the bot what channel to deploy the points system in. I am also using MongoDB so that when my bot restarts, it remembers what channel the points system was set in. However, I am getting errors such as 404: Not Found and it does not even update the schema, so as a result, I am looking for available solutions. Here's my code:
const {
prefix,
} = require('./config.json')
const Discord = require('discord.js')
var date = new Date().toLocaleString();
module.exports = (client) => {
const Mongo = require('mongoose')
const LeaderboardSequence = require('./leaderboard.js')
const SLSchema = require('./setLeaderboard.js')
const mongoose = require('mongoose')
mongoose.connect('insert URL here', {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
});
client.on('message', async message => {
if (message.content === `${prefix}setLeaderboardChannel`) {
// Destructure the guild and channel properties from the message object
const { guild, channel } = message
// Use find one and update to either update or insert the
// data depending on if it exists already
await SLSchema.findOneAndUpdate(
{
_id: guild.id,
},
{
_id: guild.id,
channelId: channel.id,
},
{
upsert: true,
}
)
message.reply(`The points channel has been set to <#${channel.id}>!`)
}
});
client.on('message', async message => {
const { guild, channel } = message
const channelId = await SLSchema.find({channelId: channel.id})
if (message.channel.id = channelId) {
if (message.attachments.size > 0) {
message.react('🔼')
message.react('🔽')
} else {
message.delete()
}
}
})
client.on('messageReactionAdd', async (reaction, user) => {
const { guild, channel } = message
const channelId = await SLSchema.find({channelId: channel.id})
if (reaction.partial) await reaction.fetch()
if (reaction.message.partial) await reaction.message.fetch()
if (reaction.message.channel.id !== channelId) return;
if (user.id === client.user.id) return;
if (reaction.message.author.id === user.id) return reaction.users.remove(user)
if (reaction.emoji.name === "🔼") {
await LeaderboardSequence.findOneAndUpdate({ userid: reaction.message.author.id, guildID: reaction.message.guild.id }, { $inc: { points: 1 } }, { upsert: true , new: true , setDefaultsOnInsert: true })
} else if (reaction.emoji.name === "🔽") {
await LeaderboardSequence.findOneAndUpdate({ userid: reaction.message.author.id, guildID: reaction.message.guild.id }, { $inc: { points: -1 } }, { upsert: true , new: true , setDefaultsOnInsert: true})
}
});
client.on('messageReactionRemove', async (reaction, user) => {
const { guild, channel } = message
const channelId = await SLSchema.find({channelId: channel.id})
if (reaction.partial) await reaction.fetch()
if (reaction.message.partial) await reaction.message.fetch()
if (reaction.message.channel.id !== channelId) return;
if (reaction.message.author.id === user.id) return reaction.users.remove(user)
if (user.id === client.user.id) return;
if (reaction.emoji.name === "🔼") {
await LeaderboardSequence.findOneAndUpdate({ userid: reaction.message.author.id, guildID: reaction.message.guild.id }, { $inc: { points: -1 } }, { upsert: true , new: true , setDefaultsOnInsert: true })
} else if (reaction.emoji.name === "🔽") {
await LeaderboardSequence.findOneAndUpdate({ userid: reaction.message.author.id, guildID: reaction.message.guild.id }, { $inc: { points: 1 } }, { upsert: true , new: true , setDefaultsOnInsert: true})
}
});
client.on('message', async message => {
if (message.content === `${prefix}leaderboard`) {
const Users = await LeaderboardSequence.find({guildID: message.guild.id}).sort({ points: -1 })
const embedArray = []
for (var i = 0; i < Users.length % 10 + 1; i++) {
const leaderboard = new Discord.MessageEmbed()
.setTitle(`Here is ${message.guild}'s points leaderboard!`)
.setColor("RANDOM")
.setThumbnail("https://pbs.twimg.com/media/D7ShRPYXoAA-XXB.jpg")
let text = ""
for (var j = 0; j < 10; j++) {
if (!Users[ i * 10 + j ]) break;
text += `${i * 10 + j + 1}. <#${Users[ i * 10 + j ].userid}>: ${Users[ i * 10 + j ].points}\n`
}
leaderboard.setDescription(text)
.setFooter("By (username) and (username), for everyone with the magic of discord.js.")
.setTimestamp()
embedArray.push(leaderboard)
}
paginate(message, embedArray)
}
});
const reactions = ['◀️', '⏸️', '▶️']
async function paginate(message, embeds, options) {
const pageMsg = await message.channel.send({ embed: embeds[0] })
await pageMsg.react(reactions[0])
await pageMsg.react(reactions[1])
await pageMsg.react(reactions[2])
let pageIndex = 0;
let time = 30000;
const filter = (reaction, user) => {
return reactions.includes(reaction.emoji.name) && user.id === message.author.id;
};
if (options) {
if (options.time) time = options.time
}
const collector = pageMsg.createReactionCollector(filter, { time: time });
collector.on('collect', (reaction, user) => {
reaction.users.remove(user)
if (reaction.emoji.name === '▶️') {
if (pageIndex < embeds.length-1) {
pageIndex++
pageMsg.edit({ embed: embeds[pageIndex] })
} else {
pageIndex = 0
pageMsg.edit({ embed: embeds[pageIndex] })
}
} else if (reaction.emoji.name === '⏸️') {
collector.stop()
} else if (reaction.emoji.name === '◀️') {
if (pageIndex > 0) {
pageIndex--
pageMsg.edit({ embed: embeds[pageIndex] })
} else {
pageIndex = embeds.length-1
pageMsg.edit({ embed: embeds[pageIndex]})
}
}
});
collector.on('end', () => pageMsg.reactions.removeAll().catch(err => console.log(err)));
}``
}
In the question, I did not mention that I was also checking for the points channel through an if statement:
(const { guild, channel } = message
const channelId = await SLSchema.find({channelId: channel.id}))
But this does not work as well.
Here is the schema:
const { Schema, model } = require('mongoose')
// We are using this multiple times so define
// it in an object to clean up our code
const reqString = {
type: String,
required: true,
}
const SLSchema = Schema({
_id: reqString, // Guild ID
channelId: reqString,
})
module.exports = model('setLeaderboard', SLSchema)
In the first piece of code, I have pasted the entire script so you guys have an understanding of the thing I am trying to pull off here.
I am trying to make discord bot that will play some music but I can't manage to make search command correctly ( Now I need to type command .f press enter and then put that what I want to search and I want it to just .f [what i want to search]) but doesn't know how to. I tried many guides but still nothing, also I would like to have that after searching and choosin what to I meant to play bot automatically join and play it (I made it buut in weird way and I know there is easier way but I am dumb for it.
TL;DR: Search command that will search and play with ".f [what to search]".
Whole code if it wil help:
const { Client } = require("discord.js");
const config = require('./config.json')
const Discord = require("discord.js");
const ytdl = require('ytdl-core');
const search = require("youtube-search")
const opts = {
maxResults: 25,
key: config.YOUTUBE_API,
type: 'video'
}
const queue = new Map();
const client = new Client({
disableEveryone: true
});
client.on("ready", () => {
console.log(`ŻYJE I JAM JEST ${client.user.username} `);
});
client.on("message", async message => {
console.log(`${message.author.username} mówi: ${message.content}`)
});
client.on("message", async message => {
if (!message.content.startsWith('.')) return;
const serverQueue = queue.get(message.guild.id);
if (message.content.startsWith(`.p`, '.play', '.pla', '.pl')) {
execute(message, serverQueue);
return;
} else if (message.content.startsWith(`.s`, '.skip', '.sk', '.ski')) {
skip(message, serverQueue);
return;
} else if (message.content.startsWith(`.l`, '.leave', '.le', '.lea', '.leav')) {
stop(message, serverQueue);
return;
};
if (message.content.toLowerCase() === '.f') {
let embed = new Discord.MessageEmbed()
.setColor("#00FE0C")
.setDescription("Czego szukasz? Opowiedz mi dokładniej.")
.setTitle("Wyszukiwarka")
.setThumbnail('https://i.imgur.com/vs6ulWc.gif')
let embedMsg = await message.channel.send(embed);
let filter = m => m.author.id === message.author.id;
let query = await message.channel.awaitMessages(filter, { max: 1});
let results = await search(query.first().content, opts).catch(err => console.log(err))
if(results) {
let youtubeResults = results.results;
let i =0;
let titles = youtubeResults.map(result => {
i++;
return i + ") " + result.title;
});
console.log(titles);
message.channel.send({
embed : {
title: "Wybieraj mordo",
description: titles.join("\n")
}
}).catch(err => console.log(err));
filter = m => (m.author.id === message.author.id) && m.content >= 1 && m.content <= youtubeResults.length;
let collected = await message.channel.awaitMessages(filter, { max: 1 });
let selected = youtubeResults[collected.first().content - 1];
embed = new Discord.MessageEmbed()
.setColor("#00FE0C")
.setTitle(`${selected.title}`)
.setURL(`${selected.link}`)
.setDescription(`${selected.description}`)
.setThumbnail(`${selected.thumbnails.default.url}`);
message.channel.send(embed)
if (message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
await message.channel.send(`.p ${selected.link}`).then(d_msg => { d_msg.delete({ timeout: 1500 })})
}
};
};
});
async function execute(message, serverQueue) {
const args = message.content.split(" ");
const voiceChannel = message.member.voice.channel;
if (!voiceChannel)
return message.channel.send(
"No wbij Mordunio na kanał najpierw!"
);
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has("CONNECT") || !permissions.has("SPEAK")) {
return message.channel.send(
"Dawaj klucze do kantorka to wbije!"
);
}
const songInfo = await ytdl.getInfo(args[1]);
const song = {
title: songInfo.title,
url: songInfo.video_url
};
if (!serverQueue) {
const queueContruct = {
textChannel: message.channel,
voiceChannel: voiceChannel,
connection: null,
songs: [],
volume: 5,
playing: true
};
queue.set(message.guild.id, queueContruct);
queueContruct.songs.push(song);
try {
var connection = await voiceChannel.join();
queueContruct.connection = connection;
play(message.guild, queueContruct.songs[0]);
} catch (err) {
console.log(err);
queue.delete(message.guild.id);
return message.channel.send(err);
}
} else {
serverQueue.songs.push(song);
return message.channel.send(`**${song.title}** został do kolejeczki dodany Byku!`);
}
}
function skip(message, serverQueue) {
if (!message.member.voice.channel)
return message.channel.send(
"Nie zatrzymasz mnie! Ciebie tu nie ma!"
);
if (!serverQueue)
return message.channel.send("A co miałabym pominąć");
serverQueue.connection.dispatcher.end();
}
function stop(message, serverQueue) {
if (!message.member.voice.channel)
return message.channel.send(
"Musisz tu byyyyć byyyyyku!!"
);
serverQueue.songs = [];
serverQueue.connection.dispatcher.end();
}
function play(guild, song, message) {
const serverQueue = queue.get(guild.id);
if (!song) {
serverQueue.voiceChannel.leave();
queue.delete(guild.id)
return;
}
const dispatcher = serverQueue.connection
.play(ytdl(song.url))
.on("finish", () => {
serverQueue.songs.shift();
play(guild, serverQueue.songs[0]);
})
.on("error", error => console.error(error));
dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
serverQueue.textChannel.send(`Gram: **${song.title}**`);
};
client.login(config.TOKEN);