Collection#find: pass a function instead ERROR - javascript

So I am very new to node.js and I am making a Discord bot. I am trying to make a ticket system using djs-ticketsystem and it is giving me this error: (node:15168) DeprecationWarning: Collection#find: pass a function instead
const ticketsystem = require("djs-ticketsystem");
bot.on("message", async message => {
if (message.content == '-new') {
ticketsystem.createTicket({
name: 'new-ticket',
category: 'TICKETS',
owner: message.author,
roles: [
'Owner',
'Support'
],
openmessage: 'Creating your ticket...',
ticketmessage: 'Thank-you for creating a ticket!',
messagelinker: message
}).catch(err => {
message.reply('Failed to create a new ticket.')
});
};
});

Related

DiscordAPIError[50001]: Missing Access discord.js bot

So been following a guide to get started on a discord bot, but keep getting this error message when running node deploy-commands.js
DiscordAPIError[50001]: Missing Access
at SequentialHandler.runRequest (C:\Users\voidy\.vscode\python\test-codes\DiscordBot\node_modules\#discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:293:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest (C:\Users\voidy\.vscode\python\test-codes\DiscordBot\node_modules\#discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:99:14)
at async REST.request (C:\Users\voidy\.vscode\python\test-codes\DiscordBot\node_modules\#discordjs\rest\dist\lib\REST.cjs:52:22) {
rawError: { message: 'Missing Access', code: 50001 },
code: 50001,
status: 403,
method: 'PUT',
url: 'https://discord.com/api/v10/applications/1018530446092554290/guilds/1018530446092554290/commands',
requestBody: { files: undefined, json: [ [Object], [Object], [Object] ] }
}
I have already added both the bot and applications.commands scope for my bot, and kicked it and re-added it quite a few times with no luck.
The guildId, clientId and Token are all correct, even reset and used the new token instead.
Here's the code if needed
const { SlashCommandBuilder, Routes } = require('discord.js');
const { REST } = require('#discordjs/rest');
const { clientId, guildId, token } = require('./config.json');
const commands = [
new SlashCommandBuilder().setName('ping').setDescription('Replies with pong!'),
new SlashCommandBuilder().setName('server').setDescription('Replies with server info!'),
new SlashCommandBuilder().setName('user').setDescription('Replies with user info!'),
]
.map(command => command.toJSON());
const rest = new REST({ version: '10' }).setToken(token);
rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
.then(() => console.log('Successfully registered application commands.'))
.catch(console.error);

DiscordAPIError: Cannot send an empty message at RequestHandler.execute

As one of the first bigger js/node projects I decided to make a discord bot using discord.js. Every user is able to add new messages to the repl.it (the website I host the bot on) database and read random ones. The bot is working fine so I wanted to make it reply with embeds because it looks better and that is where the problem is.
I don't get any errors when making the embed but when I try to send it to the chat it says that it can't send an empty message at the RequestHandler.execute. Here is the full error message:
/home/runner/anonymous-message/node_modules/discord.js/src/rest/RequestHandler.js:350
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (/home/runner/anonymous-message/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/runner/anonymous-message/node_modules/discord.js/src/rest/RequestHandler.js:51:14) {
method: 'post',
path: '/channels/880447741283692609/messages',
code: 50006,
httpStatus: 400,
requestData: {
json: {
content: undefined,
tts: false,
nonce: undefined,
embeds: undefined,
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: 0,
message_reference: { message_id: '970404904537567322', fail_if_not_exists: true },
attachments: undefined,
sticker_ids: undefined
},
files: []
}
}
And here is the full code:
const Discord = require("discord.js")
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] })
const keepAlive = require("./server.js") //just a webserver that I combine with uptimerobot.com so the bot doesn't go offline
const Database = require("#replit/database")
const db = new Database()
client.login(process.env.TOKEN) //since all replits are public (unless you buy the premium) you can use the environment variables to keep somestuff private
let prefix = "msg "
let channel
let starterMessages = ["a random test message!", "Hello World!", "why is this not working"]
db.get("msgs", messages => {
if (!messages || messages.length < 1) {
db.set("msgs", starterMessages)
}
})
client.on("ready", () => {
console.log("bot is working")
})
client.on("messageCreate", (msg) => {
channel = msg.channel.guild.channels.cache.get(msg.channel.id)
switch (true) {
case msg.content.toLowerCase().startsWith(prefix + "ping"):
channel.send("the bot is working")
break
case msg.content.toLowerCase().startsWith(prefix + "send"):
let exists = false
let tempMsg = msg.content.slice(prefix.length + 5, msg.length)
if (tempMsg.length > 0) {
db.get("msgs").then(messages => {
for (i = 0; i < messages.length; i++) {
if (tempMsg.toLowerCase() === messages[i].toLowerCase()) { exists = true }
}
if (exists === false) {
console.log(tempMsg)
messages.push(tempMsg)
db.set("msgs", messages)
msg.delete() //deletes the message so no one knows who added it
} else {
console.log("message already exists") //all console logs are for debugging purposes
}
});
}
break
case msg.content.toLowerCase().startsWith(prefix + "read"):
db.get("msgs").then(messages => {
let rndMsg = messages[Math.floor(Math.random() * messages.length)] //gets the random message from the database
//Here I make the embed, it doesn't give any errors
let newEmbed = new Discord.MessageEmbed()
.setColor("#" + Math.floor(Math.random() * 16777215).toString(16))
.setTitle("a message from a random stranger:")
.setURL("https://www.youtube.com/watch?v=dQw4w9WgXcQ&ab_channel=RickAstley")
.addFields({ name: rndMsg, value: `if you want to send one of these for other people to read? Type "${prefix}send [MESSAGE]"` })
.setFooter({ text: `type "${prefix}help" in the chat for more info!` })
msg.channel.send(newEmbed) //and here is the problem. Without this line it runs with no errors
});
break
}
})
keepAlive() //function from the webserver
I couldn't find any answers to this problem on the internet so I'm hoping you can answer it. Thanks in advance!
Since you're using (I assume) discord.js v13, the way to send embeds is this:
msg.channel.send({embeds: [newEmbed]});
That should solve your problem.

Discord.js Embed error Cannot send an empty message

so I'm trying to make a help command with list of commands showed in embed. My code kinda works but it throws an error "DiscordAPIError: Cannot send an empty message" and I've tried already everything I know and what I've found but I can't fix it.
Here's the code
const Discord = require('discord.js');
const { prefix } = require('../config.json');
module.exports = {
name: 'help',
description: 'List all of my commands or info about a specific command.',
aliases: ['commands', 'cmds'],
usage: '[command name]',
cooldown: 5,
execute(msg, args) {
const data = [];
const { commands } = msg.client;
if (!args.length) {
const helpEmbed = new Discord.MessageEmbed()
.setColor('YELLOW')
.setTitle('Here\'s a list of all my commands:')
.setDescription(commands.map(cmd => cmd.name).join('\n'))
.setTimestamp()
.setFooter(`You can send \`${prefix}help [command name]\` to get info on a specific command!`);
msg.author.send(helpEmbed);
return msg.author.send(data, { split: true })
.then(() => {
if (msg.channel.type === 'dm') return;
msg.reply('I\'ve sent you a DM with all my commands!');
})
.catch(error => {
console.error(`Could not send help DM to ${msg.author.tag}.\n`, error);
msg.reply('it seems like I can\'t DM you! Do you have DMs disabled?');
});
}
const name = args[0].toLowerCase();
const command = commands.get(name) || commands.find(c => c.aliases && c.aliases.includes(name));
if (!command) {
return msg.reply('that\'s not a valid command!');
}
data.push(`**Name:** ${command.name}`);
if (command.aliases) data.push(`**Aliases:** ${command.aliases.join(', ')}`);
if (command.description) data.push(`**Description:** ${command.description}`);
if (command.usage) data.push(`**Usage:** ${prefix}${command.name} ${command.usage}`);
data.push(`**Cooldown:** ${command.cooldown || 3} second(s)`);
msg.channel.send(data, { split: true });
},
};
You should try replace this line :
msg.channel.send(data, { split: true });
with
msg.channel.send(data.join(' '), { split: true }); since your data variable is an array and not a string
The problem is as the error states. You are trying to send an empty message somewhere.
You can try replacing msg.channel.send(data) with msg.channel.send(data.join('\n')), since the data variable is an array.
I don't see why sending an array doesn't work though.

I need help accessing info inside an object

Working on a Discord bot and I need the user ID, which in this case is 'xxx'. Not sure how to get it.
I've tried
n.mentions.users.User. -- n.mentions.users.User()
What I have on my app:
bot.on('message', msg => {
if (msg.content === 'myId'){
msg.reply().then(n => {
console.log(n.mentions.users);
});
}
})
What I get back:
Collection [Map] {
'1803209281398201380913' => User {
id: 'xxx',
username: 'zzz',
discriminator: '0000'
}
I expect 'xxx' but get undefined.
Use this:
message.mentions.users.first().id

Node.js RESTful API validation error on array schema

I am creating a RESTful API using Node.js and mongoose by following the tutorial by Acedemind. I have got it working just fine and am now expanding it to allow the client to post several products in the same order. Basically I am modifying a simple "POST" request to be an array instead of some variables. My problem is that I run into a long validation error that hinders the array from being created. Here is the code for the post request:
router.post("/", async (req, res, next) => {
const productsMaybeFalses = await Promise.all(req.body.products.map(async ({ productId })=> {
const product = await Product.findById(productId);
if (!product) {
return false;
}
return {
...product,
productId,
}
}));
const errors = productsMaybeFalses
.map((productMaybeFalse, index) => {
return {
productMaybeFalse, index
}
})
.filter(({ productMaybeFalse }) => !productMaybeFalse)
if (errors.length) {
console.log(error);
return;
}
console.log(productsMaybeFalses);
const products = productsMaybeFalses
.filter((productMaybeFalse) => productMaybeFalse);
const order = new Order({
_id: mongoose.Types.ObjectId(),
products: products
});
return order.save().then(results => {
console.log(results);
res.status(201).json(results.map((result) => ({
message: "order stored",
createdOrder: {
_id: result._id
},
request: {
type: "GET",
url: "http://localhost:3000/orders/" + result._id
}
})));
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
})
})
})
And here is the Schema for the Order:
const mongoose = require("mongoose");
const pSchema = mongoose.Schema({
productId: { type: mongoose.Schema.Types.ObjectId, ref: "Product", required: true},
quantity: { type: Number, default: 1}
});
const orderSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
products: [pSchema]
});
module.exports = mongoose.model("Order", orderSchema)
To keep this question from being too long I will only post the end part of the error. The part that I feel tells the most information abut the problem. If anyone wants the whole error message to better understand the problem and maybe come up with a solution for me I will be very willing to post it as well. Here it is:
kind: 'Array',
value: [Array],
path: 'products',
reason: TypeError: value[i].toObject is not a function
at DocumentArray.cast (/Users/axelhagman/Documents/Jacobs/node_modules/mongoose/lib/schema/documentarray.js:309:27)
at DocumentArray.SchemaType.applySetters (/Users/axelhagman/Documents/Jacobs/node_modules/mongoose/lib/schematype.js:755:12)
at model.$set (/Users/axelhagman/Documents/Jacobs/node_modules/mongoose/lib/document.js:922:18)
at model._handleIndex (/Users/axelhagman/Documents/Jacobs/node_modules/mongoose/lib/document.js:740:14)
at model.$set (/Users/axelhagman/Documents/Jacobs/node_modules/mongoose/lib/document.js:697:22)
at model.Document (/Users/axelhagman/Documents/Jacobs/node_modules/mongoose/lib/document.js:114:12)
at model.Model (/Users/axelhagman/Documents/Jacobs/node_modules/mongoose/lib/model.js:73:12)
at new model (/Users/axelhagman/Documents/Jacobs/node_modules/mongoose/lib/model.js:4324:13)
at router.post (/Users/axelhagman/Documents/Jacobs/api/routes/orders.js:70:17)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:189:7) } },
_message: 'Order validation failed',
name: 'ValidationError' }
POST /orders/ 500 440.085 ms - 7622
I am very new to using node.js and creating API overall so any help would be very much appreciated. Thanks!

Categories