UNHANDLED_EXCEPTION: DiscordAPIError[50035]: Invalid Form Body 3.type[ENUM_TYPE_COERCE]: Value "6" is not a valid enum value - discord.js

I'm developping a Discord BOT on repplit and when i launch it with CTR+Enter (or with the run button), i'm getting the following error :
UNHANDLED_EXCEPTION: DiscordAPIError[50035]: Invalid Form Body
3.type[ENUM_TYPE_COERCE]: Value "6" is not a valid enum value.
Promise {
<rejected> DiscordAPIError[50035]: Invalid Form Body
3.type[ENUM_TYPE_COERCE]: Value "6" is not a valid enum value.
at SequentialHandler.runRequest (/home/runner/AIUC/node_modules/discord.js/node_modules/#discordjs/rest/dist/index.js:667:15)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async SequentialHandler.queueRequest (/home/runner/AIUC/node_modules/discord.js/node_modules/#discordjs/rest/dist/index.js:464:14)
at async REST.request (/home/runner/AIUC/node_modules/discord.js/node_modules/#discordjs/rest/dist/index.js:910:22) {
requestBody: { files: undefined, json: [Array] },
rawError: { code: 50035, errors: [Object], message: 'Invalid Form Body' },
code: 50035,
status: 400,
method: 'PUT',
url: 'https://discord.com/api/v10/applications/1069961347166646272/guilds/1069355488258560122/commands'
}
}
I don't know where my error could come from. You can see bellow my package.json
{
"name": "nodejs",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#discordjs/opus": "^0.8.0",
"#discordjs/rest": "^1.5.1-dev.1676247033-0e4224b.0",
"#discordjs/voice": "^0.14.0",
"#distube/soundcloud": "^1.3.0",
"#distube/spotify": "^1.5.1",
"#distube/yt-dlp": "^1.1.3",
"chalk": "4.1.2",
"dayjs": "1.10.7",
"discord.js": "^14.7.1",
"distube": "^4.0.4",
"express": "^4.18.2",
"ffmpeg-static": "4.4.0",
"glob": "7.2.0",
"libsodium-wrappers": "^0.7.10",
"lyrics-finder": "^21.7.0",
"moment": "^2.29.4",
"moment-duration-format": "^2.3.2",
"mongoose": "^6.9.1",
"ms": "2.1.3",
"node-fetch": "^3.2.6",
"opusscript": "^0.0.8",
"pm2": "^5.2.2",
"systeminformation": "^5.17.9",
"ytdl-core": "^4.11.2"
},
"description": ""
}
This error appear when i'm update my Discord BOT from DiscordJS v13 to DiscordJS v14. I've tried to add a register.js file to initialize my REST API but the problem still...
EDIT
index.js
const { Client, Collection, GatewayIntentBits } = require('discord.js');
const { DisTube } = require('distube');
const { SpotifyPlugin } = require('#distube/spotify');
const { SoundCloudPlugin } = require('#distube/soundcloud');
const { YtDlpPlugin } = require('#distube/yt-dlp');
const client = new Client(
{
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.MessageContent
]
}
);
const mongoose = require('mongoose');
const Logger = require('./utils/Logger');
['commands', 'buttons', 'selects'].forEach(x => client[x] = new Collection());
['CommandUtil', 'EventUtil', 'ButtonUtil', 'SelectUtil'].forEach(handler => { require(`./utils/handlers/${handler}`)(client) });
require('./utils/Functions')(client);
mongoose.set('strictQuery', true);
process.on('exit', code => { Logger.client(`Process shutdown with the following code: ${code}`) });
process.on('uncaughtException', (err, origin) => {
Logger.error(`UNCAUGHT_EXCEPTION: ${err}`);
console.error(`Origin: ${origin}`);
});
process.on('unhandledRejection', (reason, promise) => {
Logger.warn(`UNHANDLED_EXCEPTION: ${reason}`);
console.log(promise);
});
process.on('warning', (...args) => Logger.warn(...args));
mongoose.connect(process.env.DATABASE_URI, {
autoIndex: false,
maxPoolSize: 10,
serverSelectionTimeoutMS: 5000,
socketTimeoutMS: 45000,
family: 4
}).then(() => { Logger.client('Connected to the database!') })
.catch(err => { Logger.error(err) });
client.distube = new DisTube(client, {
leaveOnStop: false,
emitNewSongOnly: true,
emitAddSongWhenCreatingQueue: false,
emitAddListWhenCreatingQueue: false,
plugins: [
new SpotifyPlugin({
emitEventsAfterFetching: true
}),
new SoundCloudPlugin(),
new YtDlpPlugin()
]
});
client.login(process.env.DISCORD_TOKEN);
resident-evil.js
const { EmbedBuilder, ApplicationCommandOptionType } = require('discord.js');
const { ResidentEvilRPGCharacter } = require('../../models');
module.exports = {
name: 'resident-evil',
category: 'context',
permissions: ['SEND_MESSAGES'],
ownerOnly: false,
usage: 'Use context menu!',
examples: ['Use context menu!'],
type: ApplicationCommandOptionType.User,
async runInteraction(client, interaction) {
const member = await interaction.guild.members.fetch(interaction.targetId);
const residentEvilData = await ResidentEvilRPGCharacter.findOne({ id: interaction.guild.id, member: member.id });
if (!residentEvilData) return interaction.reply({ content: 'You have no character in Resident Evil RPG' })
const embed = new EmbedBuilder()
.setAuthor({ name: `${member.user.tag} (${member.id})` })
.setColor('#0047AB')
.setImage(`${residentEvilData['picture']}`)
.setThumbnail(member.user.displayAvatarURL())
.setDescription(`**+ Lastname**\n${residentEvilData['lastname']}\n\n**+ Firstname**\n${residentEvilData['firstname']}\n\n**+ Surname**\n${residentEvilData['surname']}\n\n**+ Age**\n${residentEvilData['age']}\n\n**+ Sexe**\n${residentEvilData['sexe']}\n\n**+ Family**\n${residentEvilData['family']}\n\n**+ Nationality**\n${residentEvilData['nationality']}\n\n**+ Sexual Orientation**\n${residentEvilData['sexualorientation']}\n\n**+ Political Party**\n${residentEvilData['politicalparty']}\n\n**+ Religion**\n${residentEvilData['religion']}\n\n**+ History**\n${residentEvilData['history']}\n\n${residentEvilData['other']}`);
interaction.reply({ embeds: [embed] });
}
}
I finally find where this error come from, and the error come from my context command resident-evil.js

Instead of type: ApplicationCommandOptionType.User, we need to replace this value by 2! Why ??? I don't know, because the DiscordJS Documentation tell us to use ApplicationCommandOptionType.User! My only conclusion of that is with Discord JS v14 context menu are split into 2 different type :
UserContextMenu
MessageContextMenu
So maybe DiscordJS considered these context menu command as SubCommandGroup. So the correct file is the following files:
resident-evil.js
const { EmbedBuilder, ApplicationCommandOptionType } = require('discord.js');
const { ResidentEvilRPGCharacter } = require('../../models');
module.exports = {
name: 'resident-evil',
category: 'context',
permissions: ['SEND_MESSAGES'],
ownerOnly: false,
usage: 'Use context menu!',
examples: ['Use context menu!'],
type: 2,
async runInteraction(client, interaction) {
const member = await interaction.guild.members.fetch(interaction.targetId);
const residentEvilData = await ResidentEvilRPGCharacter.findOne({ id: interaction.guild.id, member: member.id });
if (!residentEvilData) return interaction.reply({ content: 'You have no character in Resident Evil RPG' })
const embed = new EmbedBuilder()
.setAuthor({ name: `${member.user.tag} (${member.id})` })
.setColor('#0047AB')
.setImage(`${residentEvilData['picture']}`)
.setThumbnail(member.user.displayAvatarURL())
.setDescription(`**+ Lastname**\n${residentEvilData['lastname']}\n\n**+ Firstname**\n${residentEvilData['firstname']}\n\n**+ Surname**\n${residentEvilData['surname']}\n\n**+ Age**\n${residentEvilData['age']}\n\n**+ Sexe**\n${residentEvilData['sexe']}\n\n**+ Family**\n${residentEvilData['family']}\n\n**+ Nationality**\n${residentEvilData['nationality']}\n\n**+ Sexual Orientation**\n${residentEvilData['sexualorientation']}\n\n**+ Political Party**\n${residentEvilData['politicalparty']}\n\n**+ Religion**\n${residentEvilData['religion']}\n\n**+ History**\n${residentEvilData['history']}\n\n${residentEvilData['other']}`);
interaction.reply({ embeds: [embed] });
}
}

There were some changes to enums in Discord.js. It looks like the number 6 was a string and not a number, you should remove the quotations around it. (of course, this is just an assumption since you didn't share any of your code.)
For more info, you can check the Discord JS Guide!

Related

next-auth custom auth window not defined

I am trying to use next-auth with my backend but it doesn't work. I use version 4 with typescript. The error is
{error: 'window is not defined', status: 200, ok: true, url: null}
Why?????. Thanks a lot.
My custom API /login result is
{
"data": {
"username": "test",
"users": {
"id": 2,
"username": "test",
"email": "test#test.com",
"createdAt": "2021-05-24",
"updatedAt": "2021-05-24",
"name": "John Smith",
"id_groups": 99,
"groups": "guest",
"avatar": null
},
"timestamp": 1646808511,
"jwt": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiG9.eyJpc3MiOiJodHRwOlwvXC90d2luYXBwLml0IiwiYXVkIjoiaHR0cDpcL1wvdHdpbmFwcC5pdCIsImlhdCI6MTM1Njk5OTUyNCwibmJmIjoxMzU3MDAwMDAwLCJleHAiOjE2NDY4MTIxMTEsImRhdGEiOiJtYXJjb2JvbmNpIn0.R1aAX99GHmoSPRKv4Vnzso8iRjUhrDWhPEdq4oql_r0"
},
"status": "",
"code": 200
}
Now, I'm try to configure next auth
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import gApi from "../../../api/gApi";
export default NextAuth({
session: {
strategy: "jwt",
},
providers: [
CredentialsProvider({
name: "credentials",
credentials: {
username: {label: "Username",type: "text", placeholder: "username"},
password: { label: "Passwort", type: "password" },
},
async authorize(credentials) {
const resp = await gApi.post("/login", JSON.stringify(credentials));
const user = resp.data;
console.log('CALL MY API');
console.log(resp);
if ( resp.status && user) {
return user;
}
return null;
},
}),
],
callbacks: {
async jwt({ token, user, account, isNewUser }) {
if (user) {
if (user.jwt) {
token = { accessToken: user.jwt };
}
}
return token;
},
async session({ session, token }) { // this token return above jwt()
session.accessToken = token.accessToken;
return session;
},
},
pages: {
signIn: "/auth/Login",
},
});
In my login page I have e simple form and i call with:
const onSubmit: SubmitHandler<FormData> = async data => {
const resp: any = await signIn("credentials", {
username: data.username,
password: data.password,
redirect: false,
});
console.log('RESPO signin');
console.log(resp);
if (resp && !resp.error) {
router.replace('/')
} else return;
}

Jest test throws "Cannot read property 'prototype' of undefined" when tested action returns a call to fetch

I'm trying to debug a Jest test in a React/Redux app; I'm running the following test (I haven't implemented faker yet).
it("Should create a SUBMIT_CONTACT_ME_FORM_SUCCESS action when contact me form submission completes successfully.", () => {
const contactMe = {
id: 1,
name: "John Shepard",
email: "shepard#n7.gov",
comments: "I am not the very model of a scientist salarian."
};
fetchMock.postOnce(contactMeURL, {
headers: { "content-type": "application/json" },
body: contactMe
});
const expectedActions = [
{
type: navbarActions.SUBMIT_CONTACT_ME_FORM_REQUEST,
contactMeForm
},
{
type: navbarActions.SUBMIT_CONTACT_ME_FORM_SUCCESS,
contactMe,
receivedAt: 1
}
;
const store = mockStore({ contactMe: null });
return store.dispatch(navbarActions.submitContactMeForm(contactMeForm, 1))
.then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
});
However, my logs point to the beginning of the fetch in the following statement within the tested action.
return fetch(`${apiRoot}/contact`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(contactMeForm)
})
.then(response => response.json())
.then(json => {
if (json.err) {
dispatch(submitContactMeFormFailure(json.err, forcedTime))
} else {
dispatch(submitContactMeFormSuccess(json, forcedTime))
}
});
It seems to be a timing/lifecycle issue, but I can't isolate or correct it. I'm using the following dev dependencies.
"devDependencies": {
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.6",
"fetch-mock": "^9.11.0",
"jasmine": "^3.9.0",
"jasmine-enzyme": "^7.1.2",
"node-fetch": "^3.0.0",
"redux-mock-store": "^1.5.4"
}
This might not be the answer but try running your test with async
it("Should ... successfully.", async() => {
const contactMe = {
id: 1,
name: "John Shepard",
email: "shepard#n7.gov",
comments: "I am not the very model of a scientist salarian."
};
fetchMock.postOnce(contactMeURL, {
headers: { "content-type": "application/json" },
body: contactMe
});
const expectedActions = [
{
type: navbarActions.SUBMIT_CONTACT_ME_FORM_REQUEST,
contactMeForm
},
{
type: navbarActions.SUBMIT_CONTACT_ME_FORM_SUCCESS,
contactMe,
receivedAt: 1
};
const store = mockStore({ contactMe: null });
await store.dispatch(navbarActions.submitContactMeForm(contactMeForm, 1));
expect(store.getActions()).toEqual(expectedActions);
});

Axios send strange array to React

I geting the data back from my API in React from a post request and I get just the first object of the entire Array.prototype
My API for the upload:
router.post("/uploads", upload.any(), async (req, res) => {
try {
if (!req.files) {
res.send({
status: false,
message: "No file uploaded",
});
} else {
let data = req.files;
res.send({
status: true,
message: "Files are uploaded",
data: data,
});
}
} catch (error) {
res.status(500).send(err);
}
});
POSTMAN gives me back:
{
"status": true,
"message": "Files are uploaded",
"data": [
{
"fieldname": "uploads\n",
"originalname": "46335256.jpg",
"encoding": "7bit",
"mimetype": "image/jpeg",
"destination": "client/uploads/",
"filename": "46335256-2020-08-04.jpg",
"path": "client/uploads/46335256-2020-08-04.jpg",
"size": 19379
},
{
"fieldname": "uploads\n",
"originalname": "120360358.jpg",
"encoding": "7bit",
"mimetype": "image/jpeg",
"destination": "client/uploads/",
"filename": "120360358-2020-08-04.jpg",
"path": "client/uploads/120360358-2020-08-04.jpg",
"size": 78075
}
]
}
perfect!
this is my function in React to upload
const uploadFiles = () => {
uploadModalRef.current.style.display = "block"
uploadRef.current.innerHTML = "File(s) Uploading..."
for (let i = 0; i < validFiles.length; i++) {
const formData = new FormData()
formData.append("images", validFiles[i])
axios
.post("http://localhost:5000/api/db/uploads", formData, {
onUploadProgress: progressEvent => {
const uploadPercentage = Math.floor(
(progressEvent.loaded / progressEvent.total) * 100
)
...// code for graphic upload
},
})
.then(resp => {
console.log(resp.data.data)
resp.data.data.map(item => {
console.log(item)
})
})
.catch(() => {
... // code
}
}
and with this I get (from the console):
[{…}]
0:
destination: "client/uploads/"
encoding: "7bit"
fieldname: "images"
filename: "46335256-2020-08-04.jpg"
mimetype: "image/jpeg"
originalname: "46335256.jpg"
path: "client/uploads/46335256-2020-08-04.jpg"
size: 19379
__proto__: Object
length: 1
__proto__: Array(0)
is an array(if I map it works) but with just the first object.
How is it possible ??
I tried even with async/await but nothing changes
Where I'm mistaking?
Thanks!

I need to do a React.js app that logs in into an API to get the session key from the current session using Axios

I apologize if it doesnt make much sense, I am new to stackoverflow and React
I already made the React app, my problem is that I dont understand how to login into an API and making a GET request to get the current session key.
I have tried following axios docs and fetch but the only thing I get is or Network error or a CORS error.
this is with axios
// class LoginForm extends React.Component {
// state = {
// users: []
// }
// componentDidMount() {
// const url = API_URL;
// axios.get(url)
// .then(res=> {
// const users = res.data;
// this.setState({users});
// })
// }
// render() {
// return (
// <div>{Object.keys(this.state.users).map(user => <h3>{user.skey}</h3> )}</div>
// )
// };
// }
this is with fetch
componentDidMount() {
fetch(API_URL)
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result.items
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
this is the JSON from the API (I had altered content for security)
{
"skey": "lep8k7jcbtba2Hwlcf4ZGVtgbmwo8s56721",
"authenticated": false,
"silo": "demo",
"user": {
"uuid": "f205daa8-b838-41c7-984be",
"username": "guest",
"full_name": "Guest",
"email": "guest",
"groups": [
{
"uuid": "27e2e4f9-ebee-4ecca10151",
"name": "guest_user"
},
{
"uuid": "c354f1b5-ca702fe3",
"name": "public"
}
],
"roles": [
{
"uuid": "027a210b657f52b10dd4",
"name": "limited"
}
],
"permits": [
{
"uuid": "e1e896-c5bd-35494211374e",
"name": "collection.create.ccpUser"
},
{
"uuid": "0e4a0a9c-8cca9-4803da46d23d",
"name": "contribution.create.ccpArticle"
},
{
"uuid": "83f93b4dab-116dd29b19e3",
"name": "contribution.view.ccpComment"
},
{
"uuid": "b7401658-4509-98e28868748b",
"name": "view_pub_public"
},
{
"uuid": "0016447d-af2b-3c4dd0bcf55d",
"name": "ws.config.list"
},
{
"uuid": "0c776bcb-7656-6e15-9ecb2389ea6f",
"name": "ws.pubs"
},
{
"uuid": "4839a09b-5be-b119-3ee8281780e3",
"name": "ws.user.login"
}
]
},
"httpSession": "devtvowc4gmo8s5672",
"cmsVersion": "6.3p"
}
Wrap your res around parenthesis. Try this:
axios.get(url)
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
})

Expo Android stand alone Google sign in error

When I try to sign in with google inside an android stand alone app, it gives the following error:
{"framesToPop":1,"code":"GOOGLE_ERROR"}
This is the app.json(changed the last four digits of hash and apikey, just for stack-overflow )
{
"expo": {
"name": "flux-scrollable",
"description": "An empty new project",
"slug": "flux-scrollable",
"privacy": "public",
"sdkVersion": "19.0.0",
"android": {
"package": "com.anonsment.chat",
"config": {
"googleSignIn": {
"apiKey": "AIzaSyD5d-Y6MKS3wmxUOHvBTGhIMPOmZC9mvdc",
"certificateHash": "F6B135645BC1D38C2FF5CE2C7BC3E7C573CCA943"
}
}
},
"version": "1.0.0",
"orientation": "portrait",
"primaryColor": "#cccccc",
"icon": "./assets/icons/app-icon.png",
"loading": {
"icon": "./assets/icons/loading-icon.png",
"hideExponentText": false
},
"packagerOpts": {
"assetExts": [
"ttf",
"mp4"
]
},
"ios": {
"supportsTablet": true
}
}
}
Code for login
const { type, user } = await Google.logInAsync({
androidStandaloneAppClientId:'173851312683-pittv77ag7tn3tpq26bvu6d5nirbs5dr.apps.googleusercontent.com',
iosStandaloneAppClientId: '<IOS_CLIENT_ID>',
androidClientId: '603386649315-9rbv8vmv2vvftetfbvlrbufcps1fajqf.apps.googleusercontent.com',
iosClientId: '603386649315-vp4revvrcgrcjme51ebuhbkbspl048l9.apps.googleusercontent.com',
scopes: ['profile', 'email']
});
Maybe you need to add behavior: 'web' in your code
const { type, user } = await Google.logInAsync({
androidStandaloneAppClientId:'173851312683-pittv77ag7tn3tpq26bvu6d5nirbs5dr.apps.googleusercontent.com',
iosStandaloneAppClientId: '<IOS_CLIENT_ID>',
androidClientId: '603386649315-9rbv8vmv2vvftetfbvlrbufcps1fajqf.apps.googleusercontent.com',
iosClientId: '603386649315-vp4revvrcgrcjme51ebuhbkbspl048l9.apps.googleusercontent.com',
behavior: 'web',
scopes: ['profile', 'email'] });

Resources