The file path is correct but not when using fs.readFileSync? - discord.js

So i have a system that only saves to files when the bot is shutdown to prevent file corruption.
When the bot starts it reads these files and put the data into a library.
The issue im having is that when trying to read the file the path is invalid.
// How my files are stored:
Databases: {
Default: {
Errors.json
}
Exchangeable: {
Errors.js
}
}
bot startup code:
if (command === "startup") { // line 14 > 18
await require(`../Default/Errors.json`); // this is a valid path / gives no error
let rawdata = await fs.readFileSync('../Default/Errors.json'); // invalid path / gives the error
Data = await JSON.parse(rawdata);
}
Error:
node:events:368
throw er; // Unhandled 'error' event
^
Error: ENOENT: no such file or directory, open '../Default/Errors.json'
at Object.openSync (node:fs:585:3)
at Object.readFileSync (node:fs:453:35)
at Object.execute (C:\Users\NAME\Desktop\Botters\C.U.A.L - Bot V2\Databases\Exchangeable\Errors.js:16:36)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Client.<anonymous> (C:\Users\NAME\Desktop\Botters\C.U.A.L - Bot V2\main.js:69:9)
Emitted 'error' event on Client instance
at:
at emitUnhandledRejectionOrErr (node:events:251:10)
at processTicksAndRejections (node:internal/process/task_queues:85:21) {
errno: -4058,
syscall: 'open',
code: 'ENOENT',
path: '../Default/Errors.json'
}

Related

i get this error when i try to start my discord bot

Error: ENOENT: no such file or directory, scandir './events/client/' at readdirSync (node:fs:1392:3) at loadcommand (/home/runner/test-5/handlers/loadEvent.js:7:24) at /home/runner/test-5/handlers/loadEvent.js:14:40 at Array.forEach () at module.exports (/home/runner/test-5/handlers/loadEvent.js:14:25) at /home/runner/test-5/nanospace.js:49:107 at Array.forEach () at new MainClient (/home/runner/test-5/nanospace.js:49:68) at Object. (/home/runner/test-5/index.js:2:16) at Module._compile (node:internal/modules/cjs/loader:1097:14) { errno: -2, syscall: 'scandir', code: 'ENOENT', path: './events/client/'

Send a IMAGE on Discord was Bot

whatsup?!
I'm starting a new research on java and i'm cracking my head about how to send image when i set the command in client side.
if(result == 1 ) {
message.channel.send('4 ★ Great Staff', {
files: [
"./test.jpeg"
]
}); }
What give me on server side
ReferenceError: message is not defined
at Object.pull (C:\Bot\neobot\gacha.js:12:15)
at Client. (C:\Bot\neobot\index.js:17:39)
at Client.emit (events.js:315:20)
at MessageCreateHandler.handle (C:\Bot\neobot\node_modules\discord.js\src\client\websocket\packets\handlers\MessageCreate.js:9:34)
at WebSocketPacketManager.handle (C:\Bot\neobot\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:100:65)
at WebSocketManager.eventMessage (C:\Bot\neobot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:225:31)
at WebSocket.ws.onmessage (C:\Bot\neobot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:83:37)
at WebSocket.onMessage (C:\Bot\neobot\node_modules\ws\lib\WebSocket.js:442:14)
at WebSocket.emit (events.js:315:20)
at Receiver.ontext (C:\Bot\neobot\node_modules\ws\lib\WebSocket.js:841:10)
You can use the MessageAttachment which comes with discord.js
const { MessageAttachment } = require("discord.js")
const image = new MessageAttachment(LINK HERE)
And you can do more customizations
For more info:
https://github.com/discordjs/discord.js/blob/master/docs/examples/attachments.md

FS Events Message.js not working in Discord.js v12

I'm trying to redo my events into an fs event system to have separate files for each event, and I'm having some issues with converting the code to Discord.JS v12.
Can someone please help me figure out what's going wrong with my message.js file?
Here is my code:
index.js
const { Client } = require('discord.js-commando');
const path = require('path');
const fs = require('fs');
const server_invite = (process.env.INVITE_URL);
const owner_id = (process.env.BOT_OWNER);
const prefix = (process.env.BOT_PREFIX);
const stripIndents = require('common-tags').stripIndents;
require('dotenv').config();
const client = new Client({
commandPrefix: prefix,
unknownCommandResponse: false,
disableMentions: 'everyone',
owner: owner_id,
invite: server_invite
})
client.registry
.registerDefaultTypes()
.registerGroups([
['admin', 'Administration'],
['mod', 'Moderation'],
['fun', 'Fun'],
['misc', 'Miscellanious'],
['util', 'Utility']
])
.registerDefaultGroups()
.registerDefaultCommands()
.registerCommandsIn(path.join(__dirname, 'commands'))
fs.readdir('./events/', (err, files) => {
if (err) return console.error;
files.forEach(file => {
if (!file.endsWith('.js')) return;
const evt = require(`./events/${file}`);
let evtName = file.split('.')[0];
console.log(`Loaded event '${evtName}'`);
client.on(evtName, evt.bind(null, client));
});
});
client.on('error', console.error)
client.login(process.env.BOT_TOKEN);
message.js
const discord = require("discord.js");
const dotenv = require('dotenv').config;
const prefix = (process.env.BOT_PREFIX);
const fs = require('fs');
module.exports = (client, message) => {
if (message.author.bot) return;
if (message.content.indexOf(prefix) !== 0) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
const cmd = client.commands.cache.get(command);
if (!cmd) return;
cmd.run(client, message, args);
};
Basically every time I run a command it crashes the bot. Other than that my ready.js event seems to work flawlessly.
Here is the error my message.js file throws:
/app/events/message.js:13
const cmd = client.commands.cache.get(command);
^
TypeError: Cannot read property 'cache' of undefined
at module.exports (/app/events/message.js:13:33)
at CommandoClient.emit (events.js:326:22)
at MessageCreateAction.handle (/app/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/app/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/app/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
at WebSocketShard.onPacket (/app/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
at WebSocketShard.onMessage (/app/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
at WebSocket.onMessage (/app/node_modules/ws/lib/event-target.js:125:16)
at WebSocket.emit (events.js:314:20)
at Receiver.receiverOnMessage (/app/node_modules/ws/lib/websocket.js:797:20)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! yuzuki#1.0.0 start: `node --harmony index.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the yuzuki#1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /app/.npm/_logs/2020-10-07T08_08_09_863Z-debug.log
Process exited with status 1
State changed from up to crashed
I'm running Discord.JS ^12.0.0 with discord.js-commando discord.js/Commando and node ^12.16.4 if it helps.
Thanks for the help from all who responded. Was able to fix my message.js file with the response provided.
Here is my working message.js file if anyone wants to use it:
const client = require('discord.js-commando');
const prefix = (process.env.BOT_PREFIX);
require('dotenv').config;
module.exports = (message) => {
if (message.author.client) return;
if (message.content.indexOf(prefix) !== 0) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
const cmd = client.commands.cache.get(command);
if (!cmd) return;
cmd.run(client, message, args);
};
Because you're using Commando, you don't need another listener for the message event. The library already does that for you. Deleting message.js should remove the error.
The error is occurring because client.commands is undefined. You seem to be using code from the main guide, which is intended for bots that are not using Commando and assumes you have already set client.commands to a Collection of your commands. You may want to take a look at the Commando guide.
Please don't ask multiple questions in one post. If you have a different issue with your other event handlers, please ask a new question.

Route crashes heroku-app but works on localhost

I have a working backend which is running on Heroku. The client is a react-app.
Everything works fine until a specific router request is made.
I've read many posts about apps working locally but not on Heroku. The difference is that I can get my app to start and function normally until a specific post-request is made to the server.
This is the route. The console.logs are for debugging. I first want to check that a user hasn't voted on that specific answer before, then the user can vote.
router.post('/:qID/answers/:aID/vote-:dir',function(req, res, next) {
console.log(req.body, "THIS IS THE REQ.BODY");
console.log(req.params.aID);
if(req.params.dir.search(/^(up|down)$/) === -1) {
var err = new Error("Not found");
err.status = 404;
next(err);
} else {
req.vote = req.params.dir;
req.userId = req.body.userId;
next();
}
},
function(req, res, next){
console.log(req.body, "IS THIS THE SAME VALUE?");
try{
User.findById(req.userId, (err, user) => {
if(err){
console.log(err, "IS THIS AN ERROR?");
next(err);
}
if(user.answersVoted.length > 0) {
for(let i = 0; i < user.answersVoted.length; i++){
if (user.answersVoted[i] == req.answer._id){
req.answered = true;
} else {
req.answered = false;
}
} return next();
} else {
updateAnswerArrayandVote(req, res);
}
});
}catch(err){
console.log(err, "IS THIS AN ERROR TOO?");
return next(err);
}
}, function(req, res, next){
if(req.answered){
res.status(422).json({message: "Only vote once!"});
} else {
updateAnswerArrayandVote(req, res);
}
});
This is the client side
handleVote = (id, dir) => {
if (dir === "up") {
axios.post(`https://sleepy-falls-59530.herokuapp.com/questions/${this.state.id}/answers/${id}/vote-up`, {
userId: this.props.userId
})
.then(res => {console.log(res)})
.catch(err => {
console.log(err);
this.setState({
show: true
})
})
} else {
axios.post(`https://sleepy-falls-59530.herokuapp.com/questions/${this.state.id}/answers/${id}/vote-down`, {
userId: this.props.userId
}).then(res => {console.log(res)})
.catch(err => {
console.log(err);
this.setState({
show: true
})
})
}
}
This is the error message from the heroku logs:
]: throw er; // Unhandled 'error' event
2019-07-09T16:04:09.523006+00:00 app[web.1]: ^
2019-07-09T16:04:09.523009+00:00 app[web.1]:
2019-07-09T16:04:09.523012+00:00 app[web.1]: TypeError: Cannot read property 'length' of undefined
2019-07-09T16:04:09.523015+00:00 app[web.1]: at User.findById (/app/routes.js:329:34)
2019-07-09T16:04:09.523017+00:00 app[web.1]: at /app/node_modules/mongoose/lib/model.js:4645:16
2019-07-09T16:04:09.523019+00:00 app[web.1]: at /app/node_modules/mongoose/lib/query.js:4004:12
2019-07-09T16:04:09.523023+00:00 app[web.1]: at process.nextTick (/app/node_modules/mongoose/lib/query.js:2622:28)
2019-07-09T16:04:09.523025+00:00 app[web.1]: at _combinedTickCallback (internal/process/next_tick.js:132:7)
2019-07-09T16:04:09.523027+00:00 app[web.1]: at process._tickCallback (internal/process/next_tick.js:181:9)
2019-07-09T16:04:09.569320+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2019-07-09T16:04:09.570120+00:00 app[web.1]: npm ERR! errno 1
2019-07-09T16:04:09.573462+00:00 app[web.1]: npm ERR! restAPI#1.0.0 start: `node app.js`
2019-07-09T16:04:09.573822+00:00 app[web.1]: npm ERR! Exit status 1
2019-07-09T16:04:09.574525+00:00 app[web.1]: npm ERR!
It seems like the User.findById() isn't working in heroku, since the answersVoted-array on the user object is undefined. How come this is working locally and more importantly, how can I fix it? I know I am sending a correct value since the console.logs are shown in the logs (not included in this post though). Thanks in advance!
EDIT
So the heroku logs gives me this:
MuPuLM8q9i6A1a3uFvUzD8K2EbsGkaRt.QlHmBlMi3ry5ZK',
2019-07-10T18:52:49.981062+00:00 app[web.1]: __v: 1,
2019-07-10T18:52:49.981064+00:00 app[web.1]: answersVoted:
2019-07-10T18:52:49.981066+00:00 app[web.1]: [ '5d0bed720498750dbcc31b3e',
2019-07-10T18:52:49.981067+00:00 app[web.1]: '5ceac5948761ba2b4c2f7a7e',
2019-07-10T18:52:49.981069+00:00 app[web.1]: '5d0bed720498750dbcc31b3e',
2019-07-10T18:52:49.981072+00:00 app[web.1]: '5d17524e4dfec60016a07609',
2019-07-10T18:52:49.981074+00:00 app[web.1]: '5d0bed720498750dbcc31b3e',
2019-07-10T18:52:49.981076+00:00 app[web.1]: '5d17524e4dfec60016a07609',
2019-07-10T18:52:49.981078+00:00 app[web.1]: '5cf90359990b3233a0fbb1ce',
2019-07-10T18:52:49.981080+00:00 app[web.1]: '5d17524e4dfec60016a07609' ] } 'THE USER'
2019-07-10T18:52:49.981088+00:00 app[web.1]: THE USER IS A object
2019-07-10T18:52:49.981159+00:00 app[web.1]: undefined 'THE USERS ANSWERSARRAY'
2019-07-10T18:52:49.983370+00:00 app[web.1]: TypeError: Cannot read property 'length' of undefined
And the code for that is:
User.findById(req.userId, async (err, user) => {
console.log(user, "THE USER");
console.log("THE USER IS A", typeof user);
console.log(user.answersVoted, "THE USERS ANSWERSARRAY");
As you can see I am able to access the user object with the answersVoted-array shown.
console.log(user)Shows me the user and all the nested objects, including the answersVoted-array
console.log(user.answersVoted) undefined.
Asynchronous error or something with heroku (since it works with postman)? Please help.
Always remember to actually add the property to your Mongoose Model's Schema if you later want to use it, say in a express router...

Nodejs - FindOneAndUpdate method works but makes my website crash (using mongo) on events.js

I want to delete an array index with an ID that I get from front-end. My code works fine and the elements are deleted, however the website crashes and I have to restart npm or check mongo's atlas to check the results. I'm really in the dark here.
Here's the error:
events.js:167
throw er; // Unhandled 'error' event
^
ReferenceError: errors is not defined
at User.findOneAndUpdate (C:\repos\InventoryApp\routes\index.js:52:17)
at C:\repos\InventoryApp\node_modules\mongoose\lib\model.js:4851:16
at process.nextTick (C:\repos\InventoryApp\node_modules\mongoose\lib\query.js:2776:28)
at process._tickCallback (internal/process/next_tick.js:61:11)
Emitted 'error' event at:
at C:\repos\InventoryApp\node_modules\mongoose\lib\model.js:4853:13
at process.nextTick (C:\repos\InventoryApp\node_modules\mongoose\lib\query.js:2776:28)
at process._tickCallback (internal/process/next_tick.js:61:11)
[nodemon] app crashed - waiting for file changes before starting...
//all variables are set and I have done a push method with the same variables
User.findOneAndUpdate(
{ email : useremail },
{ $pull: { products: {
_id : mongoose.Types.ObjectId(id)
} } },
(err) => {
if (err) console.log('found errors');
req.flash('success_msg', 'New record');
})
I found out that mongoose.Types.ObjectId(id) was causing this issue.
By doing _id : id I mananged to make it work.

Resources