Discord.js Slash commands name invalid - javascript

I have an issue with discord.js slash commands.
As you can see in my code I am setting the name to "Name" and "Age" so I don't understand what the issues are.
This is my error:
error: (node:16004) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body
options[0].name: Command name is invalid
And this is my code:
const Discord = require('discord.js');
require("dotenv").config();
const client = new Discord.Client();
client.on('ready', async () => {
console.log(`Logged in as ${client.user.tag}!`);
const getApp = (guildid) => {
const app = client.api.applications(client.user.id);
if(guildid){
app.guilds(guildid);
}
return app;
}
await getApp("842486032842358784").commands.post({
data: {
name: 'embed',
description: 'Displays embed',
options: [
{
name: 'Name',
description: 'Your Name',
required: true,
type: 3
},
{
name: 'Age',
description: 'Your Age',
required: false,
type: 4
}
]
},
})
client.ws.on('INTERACTION_CREATE', async(interaction) => {
const command = interaction.data.name.toLowerCase();
const { name, options } = interaction.data;
console.log(options);
if(command === "embed"){
reply(interaction, 'hi');
}
})
const reply = (interaction, response) => {
client.api.interactions(interaction.id, interaction.token).callback.post({
data: {
type: 4,
data: {
content: response,
}
}
})
}
});
client.login(process.env.TOKEN);

The option names should be all lowercased, in your case, substitute "Name" with "name" and "Age" with "age". That should work. The code is below:
const Discord = require('discord.js');
require("dotenv").config();
const client = new Discord.Client();
client.on('ready', async() => {
console.log(`Logged in as ${client.user.tag}!`);
const getApp = (guildid) => {
const app = client.api.applications(client.user.id);
if (guildid) {
app.guilds(guildid);
}
return app;
}
await getApp("842486032842358784").commands.post({
data: {
name: 'embed',
description: 'Displays embed',
options: [{
name: 'name',
description: 'Your Name',
required: true,
type: 3
},
{
name: 'age',
description: 'Your Age',
required: false,
type: 4
}
]
},
})
client.ws.on('INTERACTION_CREATE', async(interaction) => {
const command = interaction.data.name.toLowerCase();
const {
name,
options
} = interaction.data;
console.log(options);
if (command === "embed") {
reply(interaction, 'hi');
}
})
const reply = (interaction, response) => {
client.api.interactions(interaction.id, interaction.token).callback.post({
data: {
type: 4,
data: {
content: response,
}
}
})
}
});
client.login(process.env.TOKEN);

Related

Undefined value

i have a problem
i entered Unturned or any other game but in output it says about other game
const { ApplicationCommandType } = require('discord.js');
const fetch = require("node-fetch");
const pop = require('popcat-wrapper')
module.exports = {
name: 'steam',
description: "get info about games",
type: ApplicationCommandType.ChatInput,
cooldown: 3000,
options: [
{
name: 'gameinfo',
description: 'get info about a game',
type: 1,
options: [
{
name: 'game',
description: 'Game name',
type: 3,
required: true
}
]
}
],
run: async (client, interaction) => {
const game = interaction.options.get('game')
const gameinfo = await pop.steam(game)
console.log(gameinfo)
}
}
what i got (this is not that game that i entered)
{
type: 'game',
name: 'Touhou Seirensen ~ Undefined Fantastic Object.',
thumbnail: 'https://cdn.akamai.steamstatic.com/steam/apps/1100160/capsule_231x87.jpg?t=1591411698',
description: 'アレは何だ? 鳥か? 妖精か? 謎に満ちた未確認幻想物体が、君を未知の世界に誘う! ファンタスティックでレトロな弾幕シューティング幻想',
website: 'http://www16.big.or.jp/~zun/',
banner: 'https://cdn.akamai.steamstatic.com/steam/apps/1100160/header.jpg?t=1591411698',
developers: [ '上海アリス幻樂団' ],
publishers: [ 'Mediascape Co., Ltd.' ],
price: '12,49€'
}
I'm new to Javascript. And English its not my main language sorry for errors if there's any
i fix it
i added .value:
const game = interaction.options.get("game").value;

This interaction failed - Buttons - Discord.js

"This interaction failed"
I'm trying to make buttons with discord.js, everything is good and the buttons work well, but even though it gives the error message "This interaction failed".
(This is the code)
Everyone talk about the "defer", and I don't understand.
I hope for some help :)
interactionCreate.js:
let hastebin = require('hastebin');
module.exports = {
name: 'interactionCreate',
async execute(interaction, client) {
if (!interaction.isButton()) return;
if (interaction.customId == "open-ticket") {
if (client.guilds.cache.get(interaction.guildId).channels.cache.find(c => c.topic == interaction.user.id)) {
return interaction.reply({
content: 'you have already a Ticket created!',
ephemeral: true
});
};
interaction.guild.channels.create(`ticket-${interaction.user.username}`, {
parent: client.config.parentOpened,
topic: interaction.user.id,
permissionOverwrites: [{
id: interaction.user.id,
allow: ['SEND_MESSAGES', 'VIEW_CHANNEL', 'READ_MESSAGE_HISTORY'],
},
{
id: client.config.roleSupport,
allow: ['SEND_MESSAGES', 'VIEW_CHANNEL', 'READ_MESSAGE_HISTORY'],
},
{
id: interaction.guild.roles.everyone,
deny: ['VIEW_CHANNEL'],
},
],
type: 'text',
}).then(async c => {
interaction.reply({
content: `Ticket has ben created! <#${c.id}>`,
ephemeral: true
});
const embed = new client.discord.MessageEmbed()
.setColor('ff9600')
.setAuthor('Reason', ' ')
.setDescription('choose a reason why you open a ticket')
.setFooter('Ticket System', ' ')
.setTimestamp();
const row = new client.discord.MessageActionRow()
.addComponents(
new client.discord.MessageSelectMenu()
.setCustomId('category')
.setPlaceholder('choose a reason why you open a ticket')
.addOptions([{
label: 'Apply',
value: 'Apply',
emoji: { name: '📑' }
},
{
label: 'Support',
value: 'Support',
emoji: { name: '❓' }
},
{
label: 'Complaint',
value: 'Complaint',
emoji: { name: '😡' }
},
{
label: 'Hosting',
value: 'Hosting',
emoji: { name: '📌' }
},
{
label: 'Partnership',
value: 'Partnership',
emoji: { name: '🥇' }
},
]),
);
msg = await c.send({
content: `<#!${interaction.user.id}>`,
embeds: [embed],
components: [row]
});
const collector = msg.createMessageComponentCollector({
componentType: 'SELECT_MENU',
time: 20000
});
collector.on('collect', i => {
if (i.user.id === interaction.user.id) {
if (msg.deletable) {
msg.delete().then(async () => {
const embed = new client.discord.MessageEmbed()
.setColor('ff9600')
.setAuthor('Ticket', ' ')
.setDescription(`<#!${interaction.user.id}> has create a **Ticket** with the reason・ ${i.values[0]}`)
.setFooter('Ticket System', ' ')
.setTimestamp();
const row = new client.discord.MessageActionRow()
.addComponents(
new client.discord.MessageButton()
.setCustomId('close-ticket')
.setLabel('close ticket')
.setEmoji('899745362137477181')
.setStyle('DANGER'),
);
const opened = await c.send({
content: `<#&${client.config.roleSupport}>`,
embeds: [embed],
components: [row]
});
opened.pin().then(() => {
opened.channel.bulkDelete(1);
});
});
};
if (i.values[0] == 'Apply') {
c.edit({
parent: client.config.parentApply
});
};
if (i.values[0] == 'Support') {
c.edit({
parent: client.config.parentSupport
});
};
if (i.values[0] == 'Complaint') {
c.edit({
parent: client.config.parentComplaint
});
};
if (i.values[0] == 'Hosting') {
c.edit({
parent: client.config.parentHosting
});
};
if (i.values[0] == 'Partnership') {
c.edit({
parent: client.config.parentPartnership
});
};
};
});
collector.on('end', collected => {
if (collected.size < 1) {
c.send(`There was no reason, the ticket will be closed.`).then(() => {
setTimeout(() => {
if (c.deletable) {
c.delete();
};
}, 5000);
});
};
});
});
};
if (interaction.customId == "close-ticket") {
const guild = client.guilds.cache.get(interaction.guildId);
const chan = guild.channels.cache.get(interaction.channelId);
const row = new client.discord.MessageActionRow()
.addComponents(
new client.discord.MessageButton()
.setCustomId('confirm-close')
.setLabel('Ticket close')
.setStyle('DANGER'),
new client.discord.MessageButton()
.setCustomId('no')
.setLabel('close cancel')
.setStyle('SECONDARY'),
);
const verif = await interaction.reply({
content: 'Are you sure you want to close the ticket?',
components: [row]
});
const collector = interaction.channel.createMessageComponentCollector({
componentType: 'BUTTON',
time: 10000
});
collector.on('collect', i => {
if (i.customId == 'confirm-close') {
interaction.editReply({
content: `The ticket has been closed by <#!${interaction.user.id}>`,
components: []
});
chan.edit({
name: `closed-${chan.name}`,
permissionOverwrites: [
{
id: client.users.cache.get(chan.topic),
deny: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
},
{
id: client.config.roleSupport,
allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
},
{
id: interaction.guild.roles.everyone,
deny: ['VIEW_CHANNEL'],
},
],
})
.then(async () => {
const embed = new client.discord.MessageEmbed()
.setColor('ff9600')
.setAuthor('Ticket', ' ')
.setDescription('```Ticket saving```')
.setFooter('Ticket System', ' ')
.setTimestamp();
const row = new client.discord.MessageActionRow()
.addComponents(
new client.discord.MessageButton()
.setCustomId('delete-ticket')
.setLabel('Ticket delete')
.setEmoji('🗑️')
.setStyle('DANGER'),
);
chan.send({
embeds: [embed],
components: [row]
});
});
collector.stop();
};
if (i.customId == 'no') {
interaction.editReply({
content: 'Close ticket cancelled!',
components: []
});
collector.stop();
};
});
collector.on('end', (i) => {
if (i.size < 1) {
interaction.editReply({
content: 'Ticket closure cancelled!',
components: []
});
};
});
};
if (interaction.customId == "delete-ticket") {
const guild = client.guilds.cache.get(interaction.guildId);
const chan = guild.channels.cache.get(interaction.channelId);
interaction.reply({
content: 'ticket saving...'
});
chan.messages.fetch().then(async (messages) => {
let a = messages.filter(m => m.author.bot !== true).map(m =>
`${new Date(m.createdTimestamp).toLocaleString('de-DE')} - ${m.author.username}#${m.author.discriminator}: ${m.attachments.size > 0 ? m.attachments.first().proxyURL : m.content}`
).reverse().join('\n');
if (a.length < 1) a = "It was not written in the ticket"
hastebin.createPaste(a, {
contentType: 'text/plain',
server: 'https://www.toptal.com/developers/hastebin/documents'
}, {})
.then(function (urlToPaste) {
const embed = new client.discord.MessageEmbed()
.setAuthor('Logs Ticket', ' ')
.setDescription(`📰 Ticket-Logs \`${chan.id}\` created by <#!${chan.topic}> and deleted by <#!${interaction.user.id}>\n\nLogs: [**Click here to see the logs**](${urlToPaste})`)
.setColor('2f3136')
.setTimestamp();
const embed2 = new client.discord.MessageEmbed()
.setAuthor('Logs Ticket', ' ')
.setDescription(`📰 Logs of your ticket \`${chan.id}\`: [**Click here to see the logsn**](${urlToPaste})`)
.setColor('2f3136')
.setTimestamp();
client.channels.cache.get(client.config.logsTicket).send({
embeds: [embed]
});
client.users.cache.get(chan.topic).send({
embeds: [embed2]
}).catch(() => {console.log('I cant send it DM')});
chan.send('Delete channel.');
setTimeout(() => {
chan.delete();
}, 5000);
});
});
};
},
}; ```
Try adding i.deferUpdate(); in your collector.
collector.on('collect', i => {
i.deferUpdate();
// code here
})

I have this embed for leaderboards in my bot, but i would like it to create more than 1 embed, to show more than the first 10 in the list?

exports.run = async (client, message, args) => {
let data = await cs.leaderboard(message.guild.id);
if (data.length < 1) return message.reply("Nobody's in leaderboard yet.");
const msg = new Discord.MessageEmbed();
let pos = 0;
// This is to get First 10 Users )
data.slice(0, 10).map(e => {
if (!client.users.cache.get(e.userID)) return;
pos++
msg.setColor('#0099ff')
msg.setTitle('Leaderboard')
msg.setAuthor({ name: 'Arkbuddies UK', iconURL: 'https://i.imgur.com/yHgaVv2.png', url: 'https://discord.js.org' })
msg.setThumbnail('https://i.imgur.com/yHgaVv2.png')
msg.addFields(
{ name: `${pos}\u200B\n`, value: `**${client.users.cache.get(e.userID).username}**`, inline: true },
{ name: `Wallet:`, value: `**${e.wallet}** <:Wishbone:939942552809902150>'s`, inline: true },
{ name: `Bank:`, value: `**${e.bank}** <:Wishbone:939942552809902150>'s`, inline: true},
)
msg.setTimestamp()
msg.setFooter({ text: 'Arkbuddies UK', iconURL: 'https://i.imgur.com/yHgaVv2.png' });
});
message.reply({
embeds: [msg]
}).catch();
}
exports.help = {
name: "leaderboard",
data: {
name: 'leaderboard',
description: "show's guild leaderboard.",
options: []
}
}
exports.conf = {
aliases: ["lb"],
cooldown: 5
}

expressjs - mongoDb return nested subArray

im trying to create a seprate route in my api for a subArray from a nested array. using expressJs.
categories array:
const Categories = [
{
_id: 's654fs54s6d4f'
title: 'category 1',
SubCats: [
{
_id: 'jhgfsf68746'
name: 'subcat 1',
image: '/assets/images/vr-box-6203301_1920.jpg',
},
{
_id: 'vb40n5b4vn'
name: 'subcat 2',
image: '/assets/images/galaxy-s20_highlights_kv_00.jpg',
},
]
},
]
categoryModel:
import mongoose from 'mongoose'
const Catschema = mongoose.Schema({
name: {
type: String,
required: true,
},
image: {
type: String,
required: true,
},
})
const CategorySchema = mongoose.Schema(
{
title: {
type: String,
required: true,
},
SubCats: [Catschema]
},
{
timestamps: true,
}
)
const Category = mongoose.model('Category', CategorySchema)
export default Category
categoryController:
this would return the whole array
const getCategories = asyncHandler(async (req, res) => {
const categories = await Category.find({})
res.json(categories)
})
i want to return 'SubCats' array.
tried this but getting "SubCats is not defined".
const getSubCategories = asyncHandler(async (req, res) => {
const subcategories = await Category.find({SubCats})
res.json(subcategories)
})
find() returns an array and it takes in an object to query the db. In your question you used Category.find({SubCats}) which is Category.find({SubCats: SubCats}), which SubCats is not defined.
I think what you are looking for is Category.find().select('SubCats'), this will return an array of Categories with SubCats only.

Can't POST to nested array with express js

It's my first post here so please let me know if there's anything incomplete about my question, or if there's anything else that is missing :)
I'm trying to make a POST request to an array in my data structure called features:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CategorySchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'users'
},
categoryname: {
type: String,
required: true
},
items: [
{
user: {
type: Schema.Types.ObjectId,
ref: 'users'
},
itemname: {
type: String,
required: true
},
features: [
{
user: {
type: Schema.Types.ObjectId,
ref: 'users'
},
firstfeature: {
type: String
},
date: {
type: Date,
default: Date.now
}
},
{
user: {
type: Schema.Types.ObjectId,
ref: 'users'
},
secondfeature: {
type: String
},
date: {
type: Date,
default: Date.now
}
}
],
date: {
type: Date,
default: Date.now
}
}
],
date: {
type: Date,
default: Date.now
}
});
module.exports = Category = mongoose.model('category', CategorySchema);
I don't have any issues with posting to the items array with the following code:
router.post(
'/item/:id',
passport.authenticate('jwt', { session: false }),
(req, res) => {
const { errors, isValid } = validateItemInput(req.body);
// Check Validation
if (!isValid) {
// if any errors, send 400 with erros object
return res.status(400).json(errors);
}
Category.findById(req.params.id)
.then(category => {
const newItem = {
itemname: req.body.itemname,
user: req.user.id
};
// Add to item array
category.items.unshift(newItem);
// Save
category.save().then(category => res.json(category));
})
.catch(err =>
res.status(404).json({ categorynotfound: 'No category found' })
);
}
);
But I can't figure out what I need to change here in order to add data to the features array:
router.post(
'/feature/:id/:item_id',
passport.authenticate('jwt', { session: false }),
(req, res) => {
Category.findById(req.params.id)
.then(category => {
const newFeature = {
firstfeature: req.body.firstfeature,
secondfeature: req.body.secondfeature,
user: req.user.id
};
// Add to item array
category.items.features.unshift(newFeature);
// Save
category.save().then(category => res.json(category));
})
.catch(err => res.status(404).json({ itemnotfound: 'Item not found'
}));
}
);
Issue solved with the following data structure:
features: [
{
user: {
type: Schema.Types.ObjectId,
ref: 'users'
},
price: {
type: String
},
size: {
type: String
},
date: {
type: Date,
default: Date.now
}
}
]
And then simply make a post request for one feature at a time.

Categories

Resources