How To Make Queue System - Discord.js - 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 = []
}
})

Related

Discord.js music bot playlist dont loop

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.

discord.js v12 | TypeError: Cannot read property 'send' of undefined

Here is my entire code for my ban command. Good to note I am using Discord.JS Commando as well I have been struggling with this error but literally cannot figure out why I am getting it everything looks fine unless I have used a deprecated function. Would really appreciate someone to help me on this one I've been getting along quite well creating a rich featured bot before this happened.
const { Command } = require('discord.js-commando');
const { MessageEmbed } = require('discord.js');
const db = require('quick.db');
module.exports = class banCommand extends Command {
constructor(client) {
super(client, {
name: 'ban',
memberName: "ban",
group: 'moderation',
guildOnly: true,
userPermissions: ['BAN_MEMBERS'],
description: 'Bans the mentioned user from the server with additional modlog info.'
});
}
async run(message, args) {
if (!args[0]) return message.channel.send('**Please Provide A User To Ban!**')
let banMember = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find(r => r.user.username.toLowerCase() === args[0].toLocaleLowerCase()) || message.guild.members.cache.find(ro => ro.displayName.toLowerCase() === args[0].toLocaleLowerCase());
if (!banMember) return message.channel.send('**User Is Not In The Guild**');
if (banMember === message.member) return message.channel.send('**You Cannot Ban Yourself**')
var reason = args.slice(1).join(' ');
if (!banMember.bannable) return message.channel.send('**Cant Kick That User**')
banMember.send(`**Hello, You Have Been Banned From ${message.guild.name} for - ${reason || 'No Reason'}**`).then(() =>
message.guild.members.ban(banMember, { days: 7, reason: reason })).catch(() => null)
message.guild.members.ban(banMember, { days: 7, reason: reason })
if (reason) {
var sembed = new MessageEmbed()
.setColor('GREEN')
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription(`**${banMember.user.username}** has been banned for ${reason}`)
message.channel.send(sembed)
} else {
var sembed2 = new MessageEmbed()
.setColor('GREEN')
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription(`**${banMember.user.username}** has been banned`)
message.channel.send(sembed2)
}
let channel = db.fetch(`modlog_${message.guild.id}`)
if (channel == null) return;
if (!channel) return;
const embed = new MessageEmbed()
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL())
.setColor('#ff0000')
.setThumbnail(banMember.user.displayAvatarURL({ dynamic: true }))
.setFooter(message.guild.name, message.guild.iconURL())
.addField('**Moderation**', 'ban')
.addField('**Banned**', banMember.user.username)
.addField('**ID**', `${banMember.id}`)
.addField('**Banned By**', message.author.username)
.addField('**Reason**', `${reason || '**No Reason**'}`)
.addField('**Date**', message.createdAt.toLocaleString())
.setTimestamp();
var sChannel = message.guild.channels.cache.get(channel)
if (!sChannel) return;
sChannel.send(embed)
}
};
The reason you are getting the TypeError: args.slice(...).join is not a function error is because the slice method creates a new array of the sliced data, and so can not join(' ') since there is no space to join with. (i.e. it is not a string)
What you are looking for is args.slice(1).toString().replace(",", " ")
This removes the 2nd part of the args array object, then converts it to a string, then removes the commas in the string and replaces them with spaces.

Call Exports.run async from a member phrase

Please help me understand how can i call that ping.js from user input, like if a user type ping it will Trigger cuz of the aliases but if a user types a full phrase it won't trigger.
Or in a non headic question how can i implent this to work -> if (message.content.includes('ping'))
Sorry in advance and thanks a lot
ping.js
const Discord = require('discord.js')
const colors = require('../lib/colors.json')
exports.run = async (client, message, args, level) => {
try {
const pingEmbed = new Discord.RichEmbed()
.setColor(colors.default)
.setFooter('ping)
.addField(`${message.author.id}`, 'hey')
const msg = await message.channel.send(pingEmbed)
const embed = new Discord.RichEmbed()
.setColor(colors.default)
.addField('...',
`${msg.createdTimestamp - message.createdTimestamp}ms`)
msg.edit(embed)
} catch (err) {
message.channel.send('There was an error!\n' + err).catch()
}
}
exports.conf = {
enabled: true,
aliases: ['ping'],
guildOnly: false,
permLevel: 'User'
}
exports.help = {
name: 'ping,
category: 'tools,
description: 'ping pong',
usage: 'ping'
}
If you want to check whether a message contains any of the aliases you can just use Array.some() like this:
let aliases = ['your', 'command', 'aliases']
client.on('message', message => {
if (aliases.some(trigger => message.content.includes(trigger))) {
// The message includes at least one of your keywords
}
})
In this example is just declared aliases, but you can use the array from your command and integrate this method in your normal command handler.

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.

mongoose update array and add new element

I pretty sure this question was asked many items, however I cannot find an answer to my particular problem, which seems very but I just can't seem to get it working. I have a user model with cart schema array embedded in it. I am trying to add an object to an array and if it exists only update quantity and price, if it is doesn't add to an array. what happens with my code is that it adds a new item when array is empty, it updates the item's quantity and price but it doesn't want to add a new item. I read a bit a bout and as far as I understood I cannot use two different db methods in one request. I would appreciate any help on this, this is the first time I am actually using mongooose.
const CartItem = require('../models/cartModel');
const User = require('../models/userModel');
exports.addToCart = (req, res) => {
const cartItem = new CartItem.model(req.body);
const user = new User.model();
User.model
.findById(req.params.id)
.exec((err, docs) => {
if (err) res.sendStatus(404);
let cart = docs.cart;
if (cart.length == 0) {
docs.cart.push(cartItem);
}
let cart = docs.cart;
let isInCart = cart.filter((item) => {
console.log(item._id, req.body._id);
if (item._id == req.body._id) {
item.quantity += req.body.quantity;
item.price += req.body.price;
return true;
}
});
if (isInCart) {
console.log(cart.length)
} else {
cart.push(cartItem);
console.log(false);
}
docs.save(function (err, docs) {
if (err) return (err);
res.json(docs);
});
});
};
I actually managed to get it working like this
exports.addToCart = (req, res) => {
const cartItem = new Cart.model(req.body);
const user = new User.model();
User.model
.findById(req.params.id)
.exec((err, docs) => {
if (err) res.sendStatus(404);
let cart = docs.cart;
let isInCart = cart.some((item) => {
console.log(item._id, req.body._id);
if (item._id == req.body._id) {
item.quantity += req.body.quantity;
item.price += req.body.price;
return true;
}
});
if (!isInCart) {
console.log(cart.length)
cart.push(cartItem);
}
if (cart.length == 0) {
cart.push(cartItem);
}
docs.save(function (err, docs) {
if (err) return (err);
res.json(docs);
});
});
};
don't know if this is the right way to do it, but I can both add a new product into my array and update values of existing ones
Maybe your problem hava a simpler solution: check this page at the mongoose documentation: there is a compatibility issue with some versions of mongoDB and mongoose, maybe you need to edit your model code to look like this:
const mongoose = require("mongoose");
const CartSchema = new mongoose.Schema({
//your code here
}, { usePushEach: true });
module.exports = mongoose.model("Cart", CartSchema);
You can find more information here: https://github.com/Automattic/mongoose/issues/5924
Hope it helps.

Resources