Discord.js music bot playlist dont loop - discord.js

I made a bot for Discord and came out with a pre-built playlist in the code itself, I tried to loop it so that whoever executes the command can get for example 20 songs and not just 1.
This is what I tried:
for (let i = 0; i < 10; i++) {
const msg = message
let channel = msg.member.voice.channel;
if (!channel) return msg.reply("\`I'm sorry but you need to be in a voice channel to play music\`");
const presong = ["Etham - 12:45 (acoustic ver.)(cover by Monkljae)","another love cover","James Arthur – Train Wreck (Acoustic) #AtHome #WithMe","Gracie Abrams - I miss you, I’m sorry","Olivia Rodrigo - drivers license","slow shy","Miguel - Sure Thing (Lyrics)","Nightcore - I Lied, I'm Dying Inside (Lyrics)","Nightcore - Sorry","Nightcore → Don't Watch Me Cry (Lyrics)","Khalid - Talk (Official Video)","Khalid - Better","Demons by Imagine Dragons | cover by Jada Facer","The One That Got Away by Katy Perry | cover by Jada Facer","Let Her Go - Passenger (Official Video Cover by Jasmine Thompson)","IT'S YOU - ALI GATIE[slowed + reverb]starmilk","All Kids Are Depressed (Slowed to Perfection)","billie eilish khalid - lovely","Duncan Laurence - Arcade","yellow","Heartbreak Anniversary","dancing with your ghout","heater tate macrae","hold on","watch billie eilish","martin and gina slowed reverb","Kali Uchis - telepatía (Cover by Lesha)","leaving on a jet plane macarone project","fly me to the moon yungrythm","close to you renee dominnique","blue moon jaritenph remix","run away","let me down slowely","little do you know","gnash feat. Olivia o'brien - I hate u, I love u (Consoul Trainin Remix)","ocaen eyes","hostage","listen before i go billie","Billie Eilish - Six Feet Under ","Chelsea Cutler - Crazier Things","All Kids Are Depressed (Slowed to Perfection)","Close To You- The Carpenters (ukulele cover) | Reneé Dominique","the hills || slowed","Powfu - Death Bed (Slowed To Perfection)","maroon 5 - memories (slowed + reverb)","Ashe - Moral Of The Story (Slowed + Lyrics)","Olivia Rodrigo - traitor (Lyrics)","kina - can we kiss forever [slowed + reverb]","Claire Rosinkranz - Backyard Boy (Lyrics)","comethru - jeremy zucker cover by kimswizzled","Be Alright by Dean Lewis | acoustic cover by Jada Facer","remendy of broken heart","jocelyn floers","CKay - Love Nwantiti (Acoustic Version)","Tate McRae - friends don’t look at friends that way","juice wrld - forever ( lyrics )"]
const preLofi = presong[Math.floor(Math.random() * presong.length)];
var searched = await yts.search(preLofi);
const url = "";
var serverQueue = message.client.queue.get(message.guild.id);
let songInfo = null;
let song = null;
if (url.match(/^(https?:\/\/)?(www\.)?(m\.)?(youtube\.com|youtu\.?be)\/.+$/gi)) {
try {
songInfo = await ytdl.getInfo(url);
if (!songInfo) return msg.reply("\`Looks like i was unable to find the song on YouTube\`");
song = {
id: songInfo.videoDetails.videoId,
title: songInfo.videoDetails.title,
url: songInfo.videoDetails.video_url,
img: songInfo.player_response.videoDetails.thumbnail.thumbnails[0].url,
duration: songInfo.videoDetails.lengthSeconds,
ago: songInfo.videoDetails.publishDate,
views: String(songInfo.videoDetails.viewCount).padStart(10, " "),
req: msg.author,
};
} catch(error) {
}
} else {
try {
songInfo = searched.videos[0];
song = {
id: songInfo.videoId,
title: Util.escapeMarkdown(songInfo.title),
views: String(songInfo.views).padStart(10, " "),
url: songInfo.url,
ago: songInfo.ago,
img: songInfo.image,
req: msg.author,
};
} catch (error) {
return msg.reply("\`Something Wrong, Text Or\`")
}
}
if (serverQueue) {
serverQueue.songs.push(song);
let thing = new MessageEmbed()
.setAuthor("Song has been added to queue")
.setThumbnail(song.img)
.setColor("#fffdd0")
.addField("Name", song.title, true)
.addField("Playlist", "Lofi")
.setFooter(`Views: ${song.views} | ${song.ago}`);
return msg.channel.send(thing);
}
const queueConstruct = {
textChannel: msg.channel,
voiceChannel: channel,
connection: null,
songs: [],
volume: 80,
playing: true,
loop: false,
};
msg.client.queue.set(msg.guild.id, queueConstruct);
queueConstruct.songs.push(song);
const play = async (song) => {
const queue = msg.client.queue.get(msg.guild.id);
if (!song) {
message.client.queue.delete(message.guild.id);
return;
}
let stream = null;
if (song.url.includes("youtube.com")) {
stream = await ytdl(song.url);
stream.on("error", function (er) {
if (er) {
if (queue) {
queue.songs.shift();
play(queue.songs[0]);
}
}
});
}
queue.connection.on("disconnect", () => msg.client.queue.delete(msg.guild.id));
const dispatcher =
queue.connection.play(ytdl(song.url, { quality: "highestaudio", highWaterMark: 1 << 25, type: "opus" })).on("finish", () => {
const shiffed = queue.songs.shift();
if (queue.loop === true) {
queue.songs.push(shiffed);
}
play(queue.songs[0]);
});
dispatcher.setVolumeLogarithmic(queue.volume / 100);
let thing = new MessageEmbed()
.setAuthor("PussyMusic Has Started Playing Music")
.setImage(song.img)
.setColor("#fffdd0")
.addField("Name", song.title, true)
.addField("Views", song.views, true)
.addField("Requested by", song.req.tag, true)
.setFooter(`PussyMusic`);
queue.textChannel.send(thing).then((question) => {
question.react('⏸');
question.react('▶️');
question.react('⬅️');
question.react('⏹️');
const filter = (reaction, user) => {
return ['⏹️', '⬅️','⏸','▶️'].includes(reaction.emoji.name) && !user.bot;
};
const collector = question.createReactionCollector(filter, { time: 400000 });
collector.on('collect', (reaction, reactionCollector) => {
const emoji = reaction.emoji.name;
if (emoji === '⬅️') {
const channel = msg.member.voice.channel
if (!channel)return msg.channel.send("\`I'm sorry but you need to be in a voice channel to skip music\`");
const serverQueue = msg.client.queue.get(msg.guild.id);
if (!msg.member.voice.channel)
return msg.channel.send(
"You have to be in a voice channel to skip the music!"
);
if (!serverQueue)
return msg.reply("\`There is no song that I could skip\`");
if (serverQueue.connection.dispatcher.paused)try{
serverQueue.connection.dispatcher.resume();
}
catch (error) {
}
serverQueue.connection.dispatcher.end();
} else if (emoji === '⏹️') {
const channel = msg.member.voice.channel
if (!channel)return msg.channel.send("\`I'm sorry but you need to be in a voice channel to stop music\`");
const serverQueue = msg.client.queue.get(msg.guild.id);
if (!serverQueue)return msg.channel.send("\`There is nothing playing that I could stop for you\`");
if(!serverQueue.connection)return
if(!serverQueue.connection.dispatcher)return
try{
serverQueue.connection.dispatcher.end()
msg.channel.send(":ballot_box_with_check: \`The Music Has Stopped\`:ballot_box_with_check:")
} catch (error) {
}
msg.client.queue.delete(msg.guild.id);
serverQueue.songs = [];
}
else if (emoji === '⏸') {
const channel = msg.member.voice.channel
if (!channel)return sendError("I'm sorry but you need to be in a voice channel to pause music!", msg.channel);
const serverQueue = msg.client.queue.get(msg.guild.id);
if (!serverQueue)return msg.channel.send("\`There is nothing playing that I could pause for you\`");
if (serverQueue.connection.dispatcher.paused)return msg.reply("\` The Music Already Been Paused \`");
if(!serverQueue.connection)return
if(!serverQueue.connection.dispatcher)return
try{
serverQueue.connection.dispatcher.pause()
msg.channel.send(":ballot_box_with_check:\`Pussy Has Paused The Music\`:ballot_box_with_check:")
}
catch (error) {
}
}
else if (emoji === '▶️') {
const channel = msg.member.voice.channel
if (!channel)return msg.channel.send("\`I'm sorry but you need to be in a voice channel to resume music\`");
const serverQueue = msg.client.queue.get(msg.guild.id);
if (!serverQueue)return msg.channel.send("\`There is nothing playing that I could resume for you\`");
if (!serverQueue.connection.dispatcher.paused)return msg.reply("\` The Music Already Been Resumed \`");
if(!serverQueue.connection)return
if(!serverQueue.connection.dispatcher)return
try{
serverQueue.connection.dispatcher.resume()
msg.channel.send(":ballot_box_with_check:\`Pussy Has resumed The Music\`:ballot_box_with_check:");
}
catch (error) {
msg.reply(`Whoops, Something wrong`);
}
}
});
});
};
try {
const connection = await channel.join()
queueConstruct.connection = connection;
play(queueConstruct.songs[0]);
} catch (error) {
msg.client.queue.delete(msg.guild.id);
await channel.leave();
return msg.reply(`I could not join the voice channel`);
}
}
}
};
In this situation, the bot gives only 2 songs, and not 10 (as i write in for loop)
how can i fix it? thank's for helping.

Related

Discord.js - How to send YouTube url after searching for a video

So basically, my idea for a new command for my discord bot is a "link searcher", which will be a searching command that sends the url of the video that is chosen by the user. Something like in the image attached.
What I already have made is a searching command with embed, but im not quite sure how to send the video url that gets chosen via reaction. Any ideas/solutions?
I have found a solution after some tries, so here's the final code.
//////CONFIG LOAD///////////
////////////////////////////
const ytsr = require("youtube-sr")
const { Client, Collection, MessageEmbed } = require("discord.js");
const { attentionembed } = require("../util/attentionembed"); //attentionembed is an embed i pre-made for errors/attention cases for when the user gets one
const { approveemoji, denyemoji, PREFIX, } = require(`../config.json`); //my config contains the definitions for "yes" and "no" emojis, together with the bot token
////////////////////////////
//////COMMAND BEGIN/////////
////////////////////////////
module.exports = {
name: "linkfor",
aliases: ["searchlink","findlink","link","lf"], //optional
cooldown: 3, //optional
async execute(message, args, client) {
//if its not in a guild return
if (!message.guild) return;
//react with approve emoji
message.react(approveemoji).catch(console.error);
//if the argslength is null return error
if (!args.length)
return attentionembed(message, `Usage: ${message.client.prefix}${module.exports.name} <Video Name>`)
//if there is already a search return error
if (message.channel.activeCollector)
return attentionembed(message, "There is a search active!");
//define search
const search = args.join(" ");
//define a temporary Loading Embed
let temEmbed = new MessageEmbed()
.setAuthor("Searching...", "put a gif link here if you want")
.setColor("#F0EAD6")
//define the Result Embed
let resultsEmbed = new MessageEmbed()
.setTitle("Results for ")
.setDescription(`\`${search}\``)
.setColor("#F0EAD6")
.setAuthor("Search results:", "put a gif link here if you want")
.setFooter("Respond with the right number", "put a gif link here if you want")
//try to find top 9 results
try {
//find them
const results = await ytsr.search(search, { limit: 9 });
//map them and sort them and add a Field to the ResultEmbed
results.map((video, index) => resultsEmbed.addField(video.url, `${index + 1}. ${video.title}`));
//send the temporary embed aka Loading... embed
const resultsMessage = await message.channel.send(temEmbed)
//react with 9 Numbers
await resultsMessage.react("1️⃣");
await resultsMessage.react("2️⃣");
await resultsMessage.react("3️⃣");
await resultsMessage.react("4️⃣");
await resultsMessage.react("5️⃣");
await resultsMessage.react("6️⃣");
await resultsMessage.react("7️⃣");
await resultsMessage.react("8️⃣");
await resultsMessage.react("9️⃣");
//edit the resultmessage to the resultembed (you can also try deleting and sending the new one, if you need to)
await resultsMessage.edit(resultsEmbed)
//set the collector to true
message.channel.activeCollector = true;
//wait for a response
let response;
await resultsMessage.awaitReactions((reaction, user) => user.id == message.author.id,
{ max: 1, time: 60000, errors: ['time'], }).then(collected => {
//if its one of the emoji set them to 1 / 2 / 3 / 4 / ...
if (collected.first().emoji.name == "1️⃣") { return response = 1; }
if (collected.first().emoji.name == "2️⃣") { return response = 2; }
if (collected.first().emoji.name == "3️⃣") { return response = 3; }
if (collected.first().emoji.name == "4️⃣") { return response = 4; }
if (collected.first().emoji.name == "5️⃣") { return response = 5; }
if (collected.first().emoji.name == "6️⃣") { return response = 6; }
if (collected.first().emoji.name == "7️⃣") { return response = 7; }
if (collected.first().emoji.name == "8️⃣") { return response = 8; }
if (collected.first().emoji.name == "9️⃣") { return response = 9; }
//otherwise set it to error
else {
response = "error";
}
});
//if response is error return error
if (response === "error") {
//send error message
attentionembed(message, "Please use the right emoji symbol.");
//try to delete the message
return resultsMessage.delete().catch(console.error);
}
//get the response link
const URL = resultsEmbed.fields[parseInt(response) - 1].name;
//set collector to false aka off
message.channel.activeCollector = false;
//send the collected url
message.channel.send(URL);
//delete the search embed (optional, for better displaying)
resultsMessage.delete().catch(console.error);
//catch any errors while searching
} catch (error) {
//log them
console.error(error);
//set collector false, just incase its still true
message.channel.activeCollector = false;
}
}
};

discordjs Embed won't show up

Ok, so i'm trying to make a push notification for my discord.
i found this script online.
but it will not post the embed....
This is my monitor code:
TwitchMonitor.onChannelLiveUpdate((streamData) => {
const isLive = streamData.type === "live";
// Refresh channel list
try {
syncServerList(false);
} catch (e) { }
// Update activity
StreamActivity.setChannelOnline(streamData);
// Generate message
const msgFormatted = `${streamData.user_name} is nu live op twitch <:bday:967848861613826108> kom je ook?`;
const msgEmbed = LiveEmbed.createForStream(streamData);
// Broadcast to all target channels
let anySent = false;
for (let i = 0; i < targetChannels.length; i++) {
const discordChannel = targetChannels[i];
const liveMsgDiscrim = `${discordChannel.guild.id}_${discordChannel.name}_${streamData.id}`;
if (discordChannel) {
try {
// Either send a new message, or update an old one
let existingMsgId = messageHistory[liveMsgDiscrim] || null;
if (existingMsgId) {
// Fetch existing message
discordChannel.messages.fetch(existingMsgId)
.then((existingMsg) => {
existingMsg.edit(msgFormatted, {
embed: msgEmbed
}).then((message) => {
// Clean up entry if no longer live
if (!isLive) {
delete messageHistory[liveMsgDiscrim];
liveMessageDb.put('history', messageHistory);
}
});
})
.catch((e) => {
// Unable to retrieve message object for editing
if (e.message === "Unknown Message") {
// Specific error: the message does not exist, most likely deleted.
delete messageHistory[liveMsgDiscrim];
liveMessageDb.put('history', messageHistory);
// This will cause the message to be posted as new in the next update if needed.
}
});
} else {
// Sending a new message
if (!isLive) {
// We do not post "new" notifications for channels going/being offline
continue;
}
// Expand the message with a #mention for "here" or "everyone"
// We don't do this in updates because it causes some people to get spammed
let mentionMode = (config.discord_mentions && config.discord_mentions[streamData.user_name.toLowerCase()]) || null;
if (mentionMode) {
mentionMode = mentionMode.toLowerCase();
if (mentionMode === "Nu-Live") {
// Reserved # keywords for discord that can be mentioned directly as text
mentionMode = `#${mentionMode}`;
} else {
// Most likely a role that needs to be translated to <#&id> format
let roleData = discordChannel.guild.roles.cache.find((role) => {
return (role.name.toLowerCase() === mentionMode);
});
if (roleData) {
mentionMode = `<#&${roleData.id}>`;
} else {
console.log('[Discord]', `Cannot mention role: ${mentionMode}`,
`(does not exist on server ${discordChannel.guild.name})`);
mentionMode = null;
}
}
}
let msgToSend = msgFormatted;
if (mentionMode) {
msgToSend = msgFormatted + ` ${mentionMode}`
}
let msgOptions = {
embed: msgEmbed
};
discordChannel.send(msgToSend, msgOptions)
.then((message) => {
console.log('[Discord]', `Sent announce msg to #${discordChannel.name} on ${discordChannel.guild.name}`)
messageHistory[liveMsgDiscrim] = message.id;
liveMessageDb.put('history', messageHistory);
})
.catch((err) => {
console.log('[Discord]', `Could not send announce msg to #${discordChannel.name} on ${discordChannel.guild.name}:`, err.message);
});
}
anySent = true;
} catch (e) {
console.warn('[Discord]', 'Message send problem:', e);
}
}
}
liveMessageDb.put('history', messageHistory);
return anySent;
});
This is the embed code:
const Discord = require('discord.js');
const moment = require('moment');
const humanizeDuration = require("humanize-duration");
const config = require('../data/config.json');
class LiveEmbed {
static createForStream(streamData) {
const isLive = streamData.type === "live";
const allowBoxArt = config.twitch_use_boxart;
let msgEmbed = new Discord.MessageEmbed();
msgEmbed.setColor(isLive ? "RED" : "BLACK");
msgEmbed.setURL(`https://twitch.tv/${(streamData.login || streamData.user_name).toLowerCase()}`);
// Thumbnail
let thumbUrl = streamData.profile_image_url;
if (allowBoxArt && streamData.game && streamData.game.box_art_url) {
thumbUrl = streamData.game.box_art_url;
thumbUrl = thumbUrl.replace("{width}", "288");
thumbUrl = thumbUrl.replace("{height}", "384");
}
msgEmbed.setThumbnail(thumbUrl);
if (isLive) {
// Title
msgEmbed.setTitle(`:red_circle: **${streamData.user_name} is live op Twitch!**`);
msgEmbed.addField("Title", streamData.title, false);
} else {
msgEmbed.setTitle(`:white_circle: ${streamData.user_name} was live op Twitch.`);
msgEmbed.setDescription('The stream has now ended.');
msgEmbed.addField("Title", streamData.title, true);
}
// Add game
if (streamData.game) {
msgEmbed.addField("Game", streamData.game.name, false);
}
if (isLive) {
// Add status
msgEmbed.addField("Status", isLive ? `Live with ${streamData.viewer_count} viewers` : 'Stream has ended', true);
// Set main image (stream preview)
let imageUrl = streamData.thumbnail_url;
imageUrl = imageUrl.replace("{width}", "1280");
imageUrl = imageUrl.replace("{height}", "720");
let thumbnailBuster = (Date.now() / 1000).toFixed(0);
imageUrl += `?t=${thumbnailBuster}`;
msgEmbed.setImage(imageUrl);
// Add uptime
let now = moment();
let startedAt = moment(streamData.started_at);
msgEmbed.addField("Uptime", humanizeDuration(now - startedAt, {
delimiter: ", ",
largest: 2,
round: true,
units: ["y", "mo", "w", "d", "h", "m"]
}), true);
}
return msgEmbed;
}
}
module.exports = LiveEmbed;
But it won't post the embed, only the msg. as you can see it updates teh msg aswell.
enter image description here
i'm stuck on this for four days now, can someone help?

How can i run this command X times (!command [X times])? discord bot, discord.js

So I have a command for my discord music bot, here's the command:
run: async function (client, message, args) {
let channel = message.member.voice.channel;
if (!channel) return sendError("I'm sorry but you need to be in a voice channel to play music!", message.channel);
const lofiSongs = ["listen before i go billie","Billie Eilish ~ No Time To Die Slowed to Perfection","Billie Eilish - Six Feet Under ","Chelsea Cutler - Crazier Things","All Kids Are Depressed (Slowed to Perfection)","Close To You- The Carpenters (ukulele cover) | Reneé Dominique","the hills || slowed","Powfu - Death Bed (Slowed To Perfection)","maroon 5 - memories (slowed + reverb)","Ashe - Moral Of The Story (Slowed + Lyrics)","Olivia Rodrigo - traitor (Lyrics)","kina - can we kiss forever [slowed + reverb]","Claire Rosinkranz - Backyard Boy (Lyrics)","comethru - jeremy zucker cover by kimswizzled","[DOXTAPE] Maddox(마독스) - At My Worst (Pink Sweat$ Cover)","Be Alright by Dean Lewis | acoustic cover by Jada Facer","The One That Got Away by Katy Perry | cover by Jada Facer","Let Her Go - Passenger (Official Video Cover by Jasmine Thompson)","Can't Help Falling In Love | Elvis Presley (cover)","IT'S YOU - ALI GATIE[slowed + reverb]starmilk","All Kids Are Depressed (Slowed to Perfection)","billie eilish khalid - lovely","Duncan Laurence - Arcade","yellow","Heartbreak Anniversary","dancing with your ghout","heater tate macrae","hold on","watch billie eilish","martin and gina slowed reverb","Kali Uchis - telepatía (Cover by Lesha)","leaving on a jet plane macarone project","fly me to the moon yungrythm","close to you renee dominnique","blue moon jaritenph remix","run away","let me down slowely","little do you know","gnash feat. Olivia o'brien - I hate u, I love u (Consoul Trainin Remix)","ocaen eyes","hostage","remendy of broken heart","jocelyn floers","CKay - Love Nwantiti (Acoustic Version)","Tate McRae - friends don’t look at friends that way"]
const randomLofi = lofiSongs[Math.floor(Math.random() * lofiSongs.length)];
var searched = await yts.search(randomLofi)
const msg = message
const url = "";
var serverQueue = message.client.queue.get(message.guild.id);
let songInfo = null;
let song = null;
if (url.match(/^(https?:\/\/)?(www\.)?(m\.)?(youtube\.com|youtu\.?be)\/.+$/gi)) {
try {
songInfo = await ytdl.getInfo(url);
if (!songInfo) return sendError("Looks like i was unable to find the song on YouTube", message.channel);
song = {
id: songInfo.videoDetails.videoId,
title: songInfo.videoDetails.title,
url: songInfo.videoDetails.video_url,
img: songInfo.player_response.videoDetails.thumbnail.thumbnails[0].url,
duration: songInfo.videoDetails.lengthSeconds,
ago: songInfo.videoDetails.publishDate,
views: String(songInfo.videoDetails.viewCount).padStart(10, " "),
req: message.author,
};
} catch (error) {
console.error(error);
return message.reply(error.message).catch(console.error);
}
} else {
try {
songInfo = searched.videos[0];
song = {
id: songInfo.videoId,
title: Util.escapeMarkdown(songInfo.title),
views: String(songInfo.views).padStart(10, " "),
url: songInfo.url,
ago: songInfo.ago,
img: songInfo.image,
req: message.author,
};
} catch (error) {
console.error(error);
return message.reply(error.message).catch(console.error);
}
}
if (serverQueue) {
serverQueue.songs.push(song);
let thing = new MessageEmbed()
.setAuthor("Song has been added to queue")
.setThumbnail(song.img)
.setColor("#fffdd0")
.addField("Name", song.title, true)
.addField("Duration", song.duration, true)
.addField("Playlist", "Lofi")
.setFooter(`Views: ${song.views} | ${song.ago}`);
return message.channel.send(thing);
}
const queueConstruct = {
textChannel: message.channel,
voiceChannel: channel,
connection: null,
songs: [],
volume: 80,
playing: true,
loop: true,
};
message.client.queue.set(message.guild.id, queueConstruct);
queueConstruct.songs.push(song);
const play = async (song) => {
const queue = message.client.queue.get(message.guild.id);
if (!song) {
message.client.queue.delete(message.guild.id);
return;
}
let stream = null;
if (song.url.includes("youtube.com")) {
stream = await ytdl(song.url);
stream.on("error", function (er) {
if (er) {
if (queue) {
queue.songs.shift();
play(queue.songs[0]);
return sendError(`An unexpected error has occurred.\nPossible type \`${er}\``, message.channel);
}
}
});
}
queue.connection.on("disconnect", () => message.client.queue.delete(message.guild.id));
const dispatcher = queue.connection.play(ytdl(song.url, { quality: "highestaudio", highWaterMark: 1 << 25, type: "opus" })).on("finish", () => {
const shiffed = queue.songs.shift();
if (queue.loop === false) {
queue.songs.push(shiffed);
}
play(queue.songs[0]);
});
dispatcher.setVolumeLogarithmic(queue.volume / 100);
let thing = new MessageEmbed()
.setAuthor("PussyMusic Has Started Playing Music")
.setImage(song.img)
.setColor("#fffdd0")
.addField("Name", song.title, true)
.addField("Views", song.views, true)
.addField("Requested by", song.req.tag, true)
.setFooter(`PussyMusic`);
queue.textChannel.send(thing);
};
try {
const connection = await channel.join();
queueConstruct.connection = connection;
play(queueConstruct.songs[0]);
} catch (error) {
console.error(`I could not join the voice channel: ${error}`);
message.client.queue.delete(message.guild.id);
await channel.leave();
return sendError(`I could not join the voice channel: ${error}`, message.channel);
const executeTimes = 5;
for (let i = 0; i < executeTimes; i++) {
<Command>.execute(...);
}
}
}
};
Im pretty new to coding, sorry for my bad knowledge.
As I said I want the command to run X times, Example:
!Command 4 (will run the command 4 times, It means the bot should play 4 songs)
I realy struggle with this code, so thanks if you're helping :)
Simplest way (and maybe buggy way) is to just create for loop for it.
Personal note: I would add cap to the times people can use the command, to avoid spam and possible rate limit issues.
For loop basically can be as simple as:
if(!isNaN(args[0]){
for (let i = 0; i < args[0]; i++){
//Run rest of your code here
}
}
There is not much to go on with your current questions code, so this is the simplest way I can imagine explaining this. Create for loop for it and cap it to prevent spam

How To Make Queue System - Discord.js

I am working on a music and I would like to know how to add a queue system to the command; I have been looking around for hours and not been able to find anything on it,
If anyone can help that would be great and I don't need a queue command but I do need to add a queue system so it would really help I will be checking back in an hour to see if anyone has given me or an idea or the answer to my problem
This is my code so far:
const Discord = require('discord.js');
const ytdl = require('ytdl-core');
const YoutubeSearcher = new QuickYtSearch({
YtApiKey: '',
});
module.exports={
name: 'play',
category: 'music',
description: 'Joins and plays the song',
aliases: ['p'],
usage: '.play <song name or URL>',
run: async(client, message, args)=>{
try{
if (message.member.voice.channel) {
let args = message.content.split(' ').slice(1).join(' ');
if (!args) {
const error = new Discord.MessageEmbed()
.setTitle(`🔴 Looks like there is an Issue!`)
.setColor(0x2f3136)
.setDescription(`You have to provide me at least, the name or the url.\n\nExample :
\`\`\`fix
.play <url>
OR
.play <name>\`\`\``)
return message.channel.send(error);
};
message.member.voice.channel.join()
.then(connection => {
if (YoutubeSearcher.isVideoUrl(args) === false) {
YoutubeSearcher.getVideo(args).then(video => {
const volume = { volume: 10 };
const dispatcher = connection.play(ytdl(video.url, { filter: 'audioonly' }, volume));
const play1 = new Discord.MessageEmbed()
.setTitle('Song info')
.setURL(video.url)
.setDescription(`Name: ${video.title}, By: ${video.channelTitle}`)
.setThumbnail(video.highThumbnail)
message.channel.send(play1);
dispatcher.on("finish", () => {
dispatcher.end();
message.reply('End of the song.');
message.member.guild.me.voice.channel.leave();
});
});
} else {
const volume = { volume: 10 };
const dispatcher = connection.play(ytdl(args, { filter: 'audioonly' }, volume));
message.reply('Now playing ' + args);
dispatcher.on("finish", () => {
dispatcher.end();
message.reply('End of the song.')
message.member.guild.me.voice.channel.leave();
});
};
});
} else {
message.reply('You need to join a voice channel.');
};
}catch(err) {
console.log(err)
return message.channel.send(`Error: ${err.message}`)
}
}
}
In theory you could use the queue data structure (the last element is taken out and when a new one is added it is added to the start) and in the queue hold the music that is requested to be played. This is how it might roughly look like:
client.on("message", (msg) => {
var arrOfMusic = [];
if(msg.content.startsWith("!queue")){
msg.channel.send(arrOfMusic.join(" , ")
}
if(msg.content.startsWith("!play")){
arrOfMusic.push(msg.content.slice(6))
// you don't need to play the music
}
// your code to play the end of the array all you do is play the last element you also //need to check once it is over and use pop to remove last element
if(msg.content.startsWith("clear")){
arrOfMusic = []
}
})

How do i resolve Alexa stop, cancel intents not working

i am using a mish mash of scripts as i do not know coding to be honest, and its working for the most part, but i am struggling with stop, help and cancel during the welcome speech, stop/cancel works ok once you get to the next part, but during the welcome speech, exanmples
User: "Alexa open breckland weather"
Skill: "Welcome to Breckland Weather. Please ask me for the weather, heres a hint, whats the weather like or whats the current conditions."
User: "stop" / User: "cancel" / User: "help"
Skill: "There was a problem with the requested skill's response"
The intents are there and i added utterances in case but still the same so i feel theres sommat in the code thats not right, probably most of it lol, please can one of you kind soles peruse at your leisure and see if you can shed a little light?
exports.handler = (event, context, callback) => {
try {
//console.log(`event.session.application.applicationId=${event.session.application.applicationId}`);
//if (event.session.application.applicationId !== APP_ID) {
// callback('Invalid Application ID');
//}
if (event.session.new) {
onSessionStarted({ requestId: event.request.requestId }, event.session);
}
if (event.request.type === 'LaunchRequest') {
onLaunch(event.request,
event.session, (sessionAttributes, speechletResponse) => {
callback(null, buildResponse(sessionAttributes, speechletResponse));
});
} else if (event.request.type === 'IntentRequest') {
onIntent(event.request,
event.session,
(sessionAttributes, speechletResponse) => {
callback(null, buildResponse(sessionAttributes, speechletResponse));
});
} else if (event.request.type === 'SessionEndedRequest') {
onSessionEnded(event.request, event.session);
callback();
}
} catch (err) {
callback(err);
}
};
const isDebug = false;
const APP_ID = 'amzn1.ask.skill.d31840b5-27f2-4f07-9e19-ec0c73d78b39';
const url_weather = 'http://www.brecklandweather.com/currentout.txt';
const APP_NAME = 'Breckland Weather';
const STR_REPROMPT = '\nPlease ask me for the weather, heres a hint, whats the weather like or whats the current conditions.';
const HELP_MESSAGE = 'You can say whats the weather like, or, you can say exit... What can I help you with?';
const HELP_REPROMPT = 'What can I help you with?';
const STOP_MESSAGE = 'Goodbye!';
function getWeather(intent, session, callback, numLetters) {
let speechOutput = '';
let cardTitle = 'Weather output';
getWebRequest(url_weather, function webResonseCallback(err, data) {
if (err) {
speechOutput = `DOH! somethings done gone bad, self destuct in 3 2 ah, false alarm, still broken though, carry on.`;
callback({}, buildSpeechletResponse(cardTitle, speechOutput, STR_REPROMPT));
} else {
//if (isDebug) {"SolveAnagram::data = " + console.log(data)};
speechOutput = data;
callback({}, buildSpeechletResponse(cardTitle, speechOutput, STR_REPROMPT));
}
});
}
//Simple welcome intent handler
function getWelcomeResponse(callback) {
console.log("START session");
if (isDebug) {console.log("getWelcomeResponse()")}
const cardTitle = APP_NAME;
const speechOutput = 'Welcome to '+APP_NAME+'. '+ STR_REPROMPT;
// If the user either does not reply to the welcome message or says something that is not
// understood, they will be prompted again with this text.
const repromptText = STR_REPROMPT;
const shouldEndSession = false;
callback({}, buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}
//My effort of code
const handlers = {
'LaunchRequest': function () {
// this.emit('myIntent');
this.emit(':tell', '2 Hello, what would you like to do?');
},
'AMAZON.HelpIntent': function () {
const speechOutput = HELP_MESSAGE;
const reprompt = HELP_REPROMPT;
this.response.speak(speechOutput).listen(reprompt);
this.emit(':responseReady');
},
'AMAZON.CancelIntent': function () {
this.response.speak(STOP_MESSAGE);
this.emit(':responseReady');
},
'AMAZON.StopIntent': function () {
this.response.speak(STOP_MESSAGE);
this.emit(':responseReady');
},
};
//Simple end session intent handler
function handleSessionEndRequest(callback) {
console.log("END session");
const cardTitle = 'Goodbye';
const speechOutput = 'Thanks for using '+APP_NAME+'.';
const shouldEndSession = false;
callback({}, buildSpeechletResponse(cardTitle, speechOutput, null, shouldEndSession));
}
function buildSpeechletResponse(title, output, repromptText, shouldEndSession) {
if (isDebug) {console.log(`buildSpeechletResponse(title:${title}, shouldEndSession:${shouldEndSession}, reprompt:${repromptText})`)}
return {
outputSpeech: {
type: 'PlainText',
text: output,
},
card: {
type: 'Simple',
title: `${title}`,
content: `${output}`,
},
reprompt: {
outputSpeech: {
type: 'PlainText',
text: repromptText,
},
},
shouldEndSession,
};
}
function buildResponse(sessionAttributes, speechletResponse) {
return {
version: '2.0',
response: speechletResponse,
sessionAttributes: sessionAttributes,
};
}
//----------------- Web service helper ----------------------//
var http = require('http');
function getWebRequest(url,doWebRequestCallBack) {
try
{
http.get(url, function (res) {
var webResponseString = '';
if (isDebug) {console.log('Status Code: ' + res.statusCode)}
if (res.statusCode != 200) {
doWebRequestCallBack(new Error("Non 200 Response"));
return;
}
res.on('data', function (data) {
webResponseString += data;
});
res.on('end', function () {
//if (isDebug) {console.log('getWebRequest::Got some data: '+ webResponseString)};
//the weather isn't JSON so just return the string
//var webResponseObject = JSON.parse(webResponseString);
doWebRequestCallBack(null, webResponseString);
});
}).on('error', function (e) {
if (isDebug) {console.log("Communications error: " + e.message)}
doWebRequestCallBack(new Error(e.message));
});
}
catch(err)
{
doWebRequestCallBack(new Error(err.message));
}
}
// --------------- Events -----------------------
/**
* Called when the session starts.
*/
function onSessionStarted(sessionStartedRequest, session) {
//console.log(`onSessionStarted requestId=${sessionStartedRequest.requestId}, sessionId=${session.sessionId}`);
}
/**
* Called when the user launches the skill without specifying what they want.
*/
function onLaunch(launchRequest, session, callback) {
//console.log(`onLaunch requestId=${launchRequest.requestId}, sessionId=${session.sessionId}`);
// Dispatch to your skill's launch.
getWelcomeResponse(callback);
}
/**
* Called when the user specifies an intent for this skill.
*/
function onIntent(intentRequest, session, callback) {
const intent = intentRequest.intent;
const intentName = intentRequest.intent.name;
console.log(" ");
console.log("== New Intent ==");
console.log(`onIntent(${intentName})`);
if (intentName === 'GetWeather') {
getWeather(intent, session, callback,1);
}
}
/**
* Called when the user ends the session.
* Is not called when the skill returns shouldEndSession=true.
*/
function onSessionEnded(sessionEndedRequest, session) {
//console.log(`onSessionEnded requestId=${sessionEndedRequest.requestId}, sessionId=${session.sessionId}`);
// Add cleanup logic here
}
Your design pattern is quite confusing. But I see where your problem is. You are not using your handlers object for handling intent requests at all. According to your design pattern you can make changes as follows:
/**
* Called when the user specifies an intent for this skill.
*/
function onIntent(intentRequest, session, callback) {
const intent = intentRequest.intent;
const intentName = intentRequest.intent.name;
console.log(" ");
console.log("== New Intent ==");
console.log(`onIntent(${intentName})`);
if (intentName === 'GetWeather') {
getWeather(intent, session, callback,1);
}else if(intentName === 'AMAZON.StopIntent'){
getStopResponse(intent, session, callback,1)
}else if(intentName === 'AMAZON.HelpIntent'){
getHelpResponse(intent, session, callback,1)
}
}
And response builder function as follows:
//Simple welcome intent handler
function getStopResponse(callback) {
console.log("START session");
if (isDebug) {console.log("getStopResponse()")}
const cardTitle = APP_NAME;
const speechOutput = STOP_MESSAGE
const repromptText = STOP_MESSAGE;
const shouldEndSession = true;
callback({}, buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}
Similar one would go for getHelpResponse(). I will leave that up to you.
Tell me if this helps you.

Resources