50035 Invalid Form Body - Application command names are unique - discord

I am trying to make a quick bot (with my limited knowledge of discord.js) that has a command to "mine bobux" which determines a random variable and tells the user how much bobux they "mined." After doing node deploy-commands.js (following discordjs.guide) powershell responds with
S[50035]: Invalid Form Body
1[APPLICATION_COMMANDS_DUPLICATE_NAME]: Application command names are unique
at Q.runRequest (C:\Users\myname\Downloads\bobuxminer\node_modules\#discordjs\rest\dist\index.js:7:581)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Q.queueRequest (C:\Users\myname\Downloads\bobuxminer\node_modules\#discordjs\rest\dist\index.js:5:2942) {
rawError: {
code: 50035,
errors: { '1': [Object] },
message: 'Invalid Form Body'
},
code: 50035,
status: 400,
method: 'put',
url: 'https://discord.com/api/v9/applications/936299610002038784/guilds/399355403567366146/commands',
requestBody: { files: undefined, json: [ [ae], [Object], [Object], [Object] ] }
}
This is the command itself that I am trying to make.
const { SlashCommandBuilder } = require('#discordjs/builders');
module.exports = {
data: new SlashCommandBuilder().setName('mine')
.setDescription('Mines bobux'),
async execute(interaction) {
var bobuc = Math.floor(Math.random() * 100) + 1;
await interaction.reply(`You mined ${bobuc} bobux`);
},
};
I've checked all my files and found no duplicate commands and do not know how to resolve this issue. If you need anything else, I will provide my other files.

Remove all other instances of the command and only keep the command in the mine.js file.

Related

Discord.JS getting "Expected a string primitive Received: | undefined" when registering command

i was trying to create a new slash command, i use a folder called commands and i require every file in that folder to register it
this is the command file:
const { SlashCommandBuilder, EmbedBuilder, Client, CommandInteraction, CommandInteractionOptionResolver } = require("discord.js");
module.exports = {
name: "ping",
data: new SlashCommandBuilder()
.setName("ping")
async do(client, interaction, options) {
const check = await interaction.reply({content: "Pinging...", fetchReply: true});
const latency = check.createdTimestamp - interaction.createdTimestamp;
const pingEmbed = new EmbedBuilder()
.setTitle(":ping_pong: Pong!")
.setColor([40,40,38,255])
.setTimestamp()
.addFields(
{name: "Bot Latency", value: `${latency}ms`, inline: true},
{name: "API Latency", value: `${client.ws.ping}ms`, inline: true});
await interaction.editReply({content: "", embeds: [pingEmbed]});
}
};
when i try to load it i keep getting an Expected a string primitive error
i was expecting it to register the command successfully, but instead it keeps giving me an error, i tried everything on the guide what it said
The issue is very simple and straightforward and if you would have reviewed the discord.js documentation, you would have known that slash commands need to have a description to register.
Therefore, add a .setDescription() below your .setName method and give it a description before trying again.

Axios Adds Brackets [] To Request Param

I'm trying to add a list of items as a request parameter. When I manually write the URL like that: http://localhost:8080/api/user/book/?keyword=&page=1&pageSize=5&field=id&order=ascend&author=aziz&author=nazim, I get what I want.
However, Axios insists on adding square brackets pointlessly.
const _fetchBooks = async (params) => {
const url = `${UrlUtil.userURL()}/book/`;
const response = await axios.get(url, {
params: {
keyword: params.search,
page: params.pagination.current,
pageSize: params.pagination.pageSize,
field: params.sorter?.field,
order: params.sorter?.order,
author: params.filter?.author,
},
...
};
Here's the result URL React trying to reach when I do filtering:
http://localhost:8080/api/user/book/?keyword=&page=1&pageSize=5&field=id&order=ascend&author[]=aziz&author[]=nazim
With the brackets, I cannot go on because I get an exception:
java.lang.IllegalArgumentException: Invalid character found in the request target [/api/user/book/keyword=&page=1&pageSize=5&field=id&order=ascend&author[]=aziz&author[]=nazim ]. The valid characters are defined in RFC 7230 and RFC 3986
So, Java doesn't like the brackets.
As #AndyRay said in the comment, it's not React doing this, its Axios. This is standard behaviour as documented by their API. You can change the way that arrays get serialized using paramsSerializer option:
const response = await axios.get(url, {
params: {
keyword: params.search,
page: params.pagination.current,
pageSize: params.pagination.pageSize,
field: params.sorter?.field,
order: params.sorter?.order,
author: params.filter?.author,
},
paramsSerializer: { indexes: null }
});
as I can understand your issue of Invalid character found
I suggest you to read this first:
What's valid and what's not in a URI query?
To solve this issue of using invalid characters such as "[" you need to encode the url params and to do so check this fuction:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
Example:
const _fetchBooks = async (params) => {
const url = `${UrlUtil.userURL()}/book/`;
const response = await axios.get(url, {
params: {
keyword: params.search,
page: params.pagination.current,
pageSize: params.pagination.pageSize,
field: params.sorter?.field,
order: params.sorter?.order,
author: encodeURIComponent(JSON.stringify(params.filter?.author)),
},
...
};
Best of luck ...

.setname is not a function in discord.js

I have finished completing the code for my bot from a tutorial on YouTube: https://www.youtube.com/watch?v=fN29HIaoHLU
Here is the entire code on replt.it: https://replit.com/#TylerLanier/Comusity-Bot#slash/info.js:6:4
And I am getting this error: TypeError: (intermediate value).setname is not a function at "..."
Here is the code at slash/info.js:
module.exports = {
data: new SlashCommandBuilder()
.setname("info")
.setDescription("Displays info about the currently playing song"),
run: async ({client, interaction}) => {
const queue = client.player.getQueue(interaction.guildId)
if(!queue)
return await interaction.editReply("There are no songs in the queue")
let bar = queue.createProgressBar({
queue: false,
length: 19
})
const song = queue.current
await interaction.editReply({
embeds: [
new MessageEmbed()
.setThumbnail(song.thumbnail)
.setDescription(`Currently Playing [${song.title}](${song.url})\n\n` + bar)
],
})
},
}
The reason behind the error is a capitalisation mistake when you use .setname(). It needs to be .setName() with a capital N. This is why you need to go through your code just to check the spelling of each function and variable you call. You will also have to change this incorrect spelling in every command except the play command as in each file, you are using .setname()

Sending JSON via Postman causes an error in my Node.js service

I created schema in node.js. It worked before I included arrays.
This is my schema code:
const Item = new item_Schema({
info:{
title:{type:String, required:true},
bad_point:{type:Number, 'default':0},
Tag:{type:String, required:true}
},
review:{
Review_text:{type:Array, required:true},
Phone_list:{type:Array, required:true},
LatLng_list:{type:Array, required:true}
}
});
Item.statics.create = function(info, review){
const list = new this({
info:{
title,
bad_point,
Tag
},
review:{
Review_text,
Phone_list,
LatLng_list
}
});
return list.save();
};
This is my register code:
exports.register = (req, res) => {
const { info, review } = req.body
const create = (list) => {
return Item.create(info, review)
}
const respond = () => {
res.json({
message: 'place route registered successfully'
})
}
const onError = (error) => {
res.status(409).json({
message: error.message
})
}
RouteReviewItem.findOneBytitle(title)
.then(create)
.then(respond)
.catch(onError)
}
And this is the Postman JSON raw code:
{
"info":"{
"title":"test title",
"badPoint":"0"
"Tag":"tag1"
}",
"review":"{
"Review_text":["1번리뷰", "2번리뷰", "3번리뷰"],
"Phone_list":"["010-0000-0000", "010-1111-1111", "010-2222-2222"],
"LatLng_list":["111.1111,111.1111", "222.222,222.222","333.3333,333.3333"]
}"
}
This is the error I get in Postman:
SyntaxError: Unexpected token in JSON at position 17
at JSON.parse (<anonymous>)
at parse (C:\MainServer\node_modules\body-parser\lib\types\json.js:89:19)
at C:\MainServer\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (C:\MainServer\node_modules\raw-body\index.js:224:16)
at done (C:\MainServer\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (C:\MainServer\node_modules\raw-body\index.js:273:7)
at emitNone (events.js:105:13)
at IncomingMessage.emit (events.js:207:7)
at endReadableNT (_stream_readable.js:1045:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
Is this a problem with postman? Or the node.js side?
I looked at the node.js book I was studying, but could not find any relevant information.
The code is fine, you have an issue with JSON you used for testing. For further testing and debugging, I suggest that you verify that the requests you send you the endpoint are correct by using a service like JSONLint (or any offlne tool that does the same). For the request you posted in the question, this service complains:
Error: Parse error on line 2:
{ "info": "{ "title": "test t
----------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'
Next time, before sending a request, make sure it is correct syntactically. That way you'll know that there is a problem with your code, and won't spend time debugging a non-existent issue.

Uploading files to meteor server using Method call

I am trying to implement file uploads for meteor using Method call.
I am using this meteor package: https://atmospherejs.com/ostrio/files.
I have no problem on client side (I can send file in a base64 encoded format). on server side I am trying to implement this function : https://github.com/VeliovGroup/Meteor-Files/blob/master/docs/write.md
but I am getting this error.
Error during upload: TypeError: Images.write is not a function
Here is the code of my Method on server:
export const insertImage = new ValidatedMethod({
name: 'images.insert',
validate: new SimpleSchema({
file: { type: String },
}).validator(),
run({ file }) {
Images.write(file, {
fileName: 'sample.png',
type: 'image/png',
}, function (error, fileRef) {
if (error) {
throw error;
} else {
console.log(`${fileRef.name} is successfully saved to FS. _id: ${fileRef._id}`);
}
});
},
});
According to the lib documentation you will need to first instantiate Images with an instance of FilesCollection, similar to as following:
https://github.com/VeliovGroup/Meteor-Files#api-overview-full-api
import { FilesCollection } from 'meteor/ostrio:files';
const Images = new FilesCollection({
collectionName: 'Images',
allowClientCode: false, // Disallow remove files from Client
onBeforeUpload(file) {
// Allow upload files under 10MB, and only in png/jpg/jpeg formats
if (file.size <= 10485760 && /png|jpg|jpeg/i.test(file.extension)) {
return true;
} else {
return 'Please upload image, with size equal or less than 10MB';
}
}
});
For more details on the constructor parameters please refer to https://github.com/VeliovGroup/Meteor-Files/wiki/Constructor
I have used this syntax:
Meteor.call('images.insert', {
file: image
}, (err, res) => {
if (err) {
console.log(`Error during upload: ${err}`);
} else {
console.log(`Upload successfully!`);
}
});

Resources