DiscordAPIError[50035]: Invalid Form Body | 5[APPLICATION_COMMANDS_DUPLICATE_NAME]: Application command names must be unique - discord.js

This Is My index.js
const LOAD_SLASH = process.argv[2] == "load"
const CLIENT_ID = "981858607362629663"
const GUILD_ID = "970702726348546078"
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildVoiceStates
]
})
client.slashcommands = new Discord.Collection()
client.player = new Player(client, {
ytdlOptions: {
quality: "highestaudio",
highWaterMark: 1 << 25
}
})
let commands = []
const slashFiles = fs.readdirSync("./slash").filter(file => file.endsWith(".js"))
for (const file of slashFiles){
const slashcmd = require(`./slash/${file}`)
client.slashcommands.set(slashcmd.data.name, slashcmd)
if (LOAD_SLASH) commands.push(slashcmd.data.toJSON())
}
I Recieve The Following Error After I Run node index.js load :-
DiscordAPIError[50035]: Invalid Form Body 5[APPLICATION_COMMANDS_DUPLICATE_NAME]: Application command names must be unique at SequentialHandler.runRequest
I have tried uninstalling and re-installing discord.js, still I am experiencing this error, I would really like some help!

You have a duplicate command name somewhere in your files. Try finding it with the following snippet:
const slashFiles = fs.readdirSync("./slash").filter(file => file.endsWith(".js"))
for (const file of slashFiles){
const slashcmd = require(`./slash/${file}`)
console.log(slashcmd.data.name)
}
Find the command name which is logged twice and edit the command file accordingly.

In one of the files you duplicated name with another file

Related

NOT NULL constraint failed: accounts_personalcolor.user_id

I am new to Django and have trouble making django-rest-framework API for post, inheriting APIView. I'm using a serializer, that inherits djangos ModelSerializer. I face NOT NULL constraint failed: accounts_personalcolor.user_id error whenever I try saving the serializer or model object.
color.js posts image using Django rest framework as follows.
function PersonalColorScreen({navigation,route}) {
const {image} = route.params;
console.log('uri is', image.uri);
const [userToken, setUserToken] = React.useState(route.params?.userToken);
const requestHeaders = {
headers: {
"Content-Type": "multipart/form-data"
}
}
// helper function: generate a new file from base64 String
//convert base64 image data to file object to pass it onto imagefield of serializer.
//otherwise, serializer outputs 500 Internal server error code
const dataURLtoFile = (dataurl, filename) => {
const arr = dataurl.split(',')
const mime = arr[0].match(/:(.*?);/)[1]
const bstr = atob(arr[1])
let n = bstr.length
const u8arr = new Uint8Array(n)
while (n) {
u8arr[n - 1] = bstr.charCodeAt(n - 1)
n -= 1 // to make eslint happy
}
return new File([u8arr], filename, { type: mime })
}
//random number between 0-9
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
// generate file from base64 string
const file = dataURLtoFile(image.uri, `${getRandomInt(10)}.png`)
const formData= new FormData();
formData.append('img',file,file.name);
console.log(file.name);
//axios post request to send data
// axios.post('http://localhost:8000/accounts/personalcolor/', formData,requestHeaders)
//multipartparser
axios.post('http://localhost:8000/accounts/personalcolor/', formData, requestHeaders)
.then(res => {
console.log(res);
if (res.data === 'upload another image') {
setimageError('upload another image');
} else {
// signUp(userToken);
let color;
switch (res.data){
case ('spring'):
color = 'spring';
break;
case ('summer'):
color = 'summer';
break;
case ('fall'):
color = 'fall';
break;
case ('winter'):
color = 'winter';
break;
}
}
})
.catch(err => {
console.error(err.response.data)
})
view.py handles the image posted. I tried #1 but it did not work. So I tried #2, or #3 instead and they return the same error saying NOT NULL constraint failed: accounts_personalcolor.user_id. I thought saving the serializer or model object creates id(Autofield)automatically and I don't understand why I face this error.
views.py
#api_view(['POST'])
def personalcolor(request):
# 1
image=request.FILES['img']
personal_color=Personalcolor()
personal_color.img=image
personal_color.save()
# 2
image=request.FILES['img']
personal_color=Personalcolor.objects.create(img=image)
personal_color.save()
# 3
serializer = ColorSerializer(data=request.data)
# validation of input data
if serializer.is_valid():
serializer.save()
else:
return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST)
model.py
class Personalcolor(models.Model):
objects = models.Manager()
img = models.ImageField('personal_img',upload_to="personalcolor/", blank=True)
serializer.py
class ColorSerializer(serializers.ModelSerializer):
class Meta:
model = Personalcolor
fields = ['img']
As mentioned above, executing the code returns django.db.utils.IntegrityError: NOT NULL constraint failed: accounts_personalcolor.user_id. Any help would be greatly appreciated.
Set null to true in your img field like:
img = models.ImageField('personal_img',upload_to="personalcolor/", blank=True, null=True)
Then in your migrations folder within the app where the Personalcolor model is located, delete all of the files that look like 000*_initial.py
Then run makemigrations and migrate

How to do the correct way to encrypt to AES256 using CryptoJs

Hi i'm new to React Native,
i can encrypt the data in the PHP but not with React Native using Crypto JS. (result in JS always different, the correct one is from the PHP)
This is the example in PHP :
<?php
$data = 'my1234567';
$iv = 'yourivare1234567';
$key = '356d9abc7532ceb0945b615a622c3370';
$abc = openssl_encrypt($data, 'aes-256-cbc', $key, 0, $iv);
var_dump($abc);
// result is : string(24) "9EF/QLpR+o/KrVueiI4L0g=="
Now i try to replicate it in my React Native apps using Crypto JS.
But the result always different, where i'm expecting the result using hardcoded data and iv like above is : "9EF/QLpR+o/KrVueiI4L0g=="
Below is the source code in JS :
const data = 'my1234567';
const iv = 'yourivare1234567';
const key = '356d9abc7532ceb0945b615a622c3370';
const fkey = CryptoJS.enc.Hex.parse(key);
const fiv = CryptoJS.enc.Hex.parse(iv);
const enc = CryptoJS.AES.encrypt(data, md5key, {
iv: fiv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
const final = enc.ciphertext.toString(CryptoJS.enc.Base64);
console.log('encrypted password: ' , final) // result is kYLFiwI1IDZcFfsKsbrbzg==
Can somebody help on this?
Thanks before
fkey and fiv must be parsed using the UTF8 encoder. md5key is not defined and must be replaced by fkey:
const data = 'my1234567';
const iv = 'yourivare1234567';
const key = '356d9abc7532ceb0945b615a622c3370';
const fkey = CryptoJS.enc.Utf8.parse(key);
const fiv = CryptoJS.enc.Utf8.parse(iv);
const enc = CryptoJS.AES.encrypt(data, fkey, {
iv: fiv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
const final = enc.ciphertext.toString(CryptoJS.enc.Base64);
console.log('encrypted password: ' , final) // result is 9EF/QLpR+o/KrVueiI4L0g==
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
Note that (except for testing purposes) no static IV may be used for security reasons.

getting the folder of a given file from a different file (JAVASCRIPT)

I have subfolders for each of my commands and I'm wondering how I would check the name of the command's folder without having to add code into the command file itself. I've tried folders.filter(folder => folder.includes(command) and I'm hoping there's a similar way that could help me.
const folders = fs.readdirSync(`./categories`);
for (const folder of folders) {
const files = fs.readdirSync(`./categories/${folder}`);
for (const file of files) {
const command = require(`./categories/${folder}/${file}`);
client.commands.set(command.name, command);
};
};
client.on("message", async message => {
if (command.args && !args.length) {
const commandArgs = new Discord.MessageEmbed()
.setAuthor(command.category) // HERE - how would i check what subfolder the given command is in?
.setTitle(command.name)
.setDescription(command.description);
}
//code...
});
You can simply add a property when retrieving it:
const command = require(`./categories/${folder}/${file}`);
command.folder = folder;
client.commands.set(command.name, command);
Now you can use it when referencing the object:
const commandArgs = new Discord.MessageEmbed()
.setTitle("From folder: " + command.folder);

client.commands.has() not working with normal input

To get the files with commands (such as ping.js)
module.exports = {
name: 'ping',
description: 'Play some ping pong.',
execute(message, args) {
const bot = require('../bot.js');
message.channel.send('pong!');
bot.log(message, '$ping', message.guild.name);
},
};
I use this in bot.js
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command_file = require(`./commands/${file}`);
client.commands.set(command_file.name, command_file);
}
I'm trying to set the variable for the command with this:
let command = '';
if(message.content.includes(' ')){
command = message.content.substr(1, message.content.indexOf(' ')).toLowerCase();
} else {
command = message.content.substr(1).toLowerCase();
}
which returns the name of the command as a string, like 'info' or 'ping'.
But, when I put that variable into client.commands.has() it doesnt find the command and returns back with this:
if(!client.commands.has(command)) return;
I cant find any answers to this online so I figured I'd ask, sorry if this doesnt fit
Try this instead:
const cmd =
message.client.commands.get(command) ||
message.client.commands.find(
(cmd) => cmd.aliases && cmd.aliases.includes(command) // if you're also using aliases
);
if (!command) return;

How to make this bot listen to argument after prefix and answer?

so i'm trying this 8ball bot, and everything is working fine, but i can't get how can i leave in the condition that only when the bot get "!verda arg1 arg2" it answers one of the replies in the array.
meanwhile my condition is if the user type the prefix "!verda" only, it replies , i want to include the argument too in the condition
const Discord = require("discord.js");
const client = new Discord.Client();
const cfg = require("./config.json");
const prefix = cfg.prefix;
client.on("message", msg => {
if (!msg.content.startsWith(prefix) || msg.author.bot) return;
const args = msg.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase;
if (msg.content === prefix){
let replies = [
"Yes.",
"No.",
"I don't know.",
"Maybe."
];
let result = Math.floor((Math.random() * replies.length));
msg.channel.send(replies[result]);
}
else if (msg.content === "!help"){
msg.channel.send("I have only 1 command [!verda]");
}
})
client.login(cfg.token);
const command = args.shift().toLowerCase;
toLowerCase is a function and therefore should be
const command = args.shift().toLowerCase();
By doing msg.content === prefix, you are checking if the whole content of the message is equal to that of cfg.prefix
if(msg.content.startsWith(`${prefix}8ball`) {
}
The answer was simple as i figured it out, i simply had to join the spaces
if (msg.content === `${prefix} ${args.join(" ")}`)

Resources