How to fix this issue in my code (Node.js&Discord.js): "node:8036"? - node.js

I'm started programming yesterday and i wanted to make a bot. I have a small issue and I can't fix him. Error = "(node:8188) UnhandledPromiseRejectionWarning: ReferenceError: bread is not defined". Line of code = "return message.channel.send({files: [bread.png]});". Thank you in advance.
bot.on('message', async message => {
let prefix = '!';
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = messageArray.slice(1);
if(cmd === `${prefix}bulka`) {
return message.channel.send({files: [bread.png]});
}
})

There is a syntax error in this line:
return message.channel.send({files: [bread.png]});
Use:
return message.channel.send({files: ["bread.png"]});
If you want to use a string inside an array, you need to wrap the text in single quotes ('), double quotes ("), or grave accents (`) to let JS know that it's a literal string. If you use bread.png, Node.js looks for the global object or variable bread and its property png.

Related

How to scape special characters for linux, nodejs exec function

I'm running this ffmpeg command on my linux server and while I paste it into the terminal, it works just fine but as soon as I use execPromise to run the EXACT same command, it returns an error.
const { exec } = require('child_process');
const { promisify } = require('util');
const execPromise = promisify(exec);
const encode = async ffmpegCode => {
try {
console.log(ffmpegCode) //Here I can see that the code is the
//exact same one than the one that works
//when pasted into the terminal
await execPromise(ffmpegCode);
return 200
} catch (err) {
console.log(err)
}
}
I need \: to be interpreted as such. When I type it as is, \:, the error message shows me that it interpreted it as : which is expected.
If I pass in \\:, I expect it to interpret it as I need it which would be \: but the error shows me that it interprets it as \\:.
\\\: is interpreted as \\: and \\\\: is interpreted as \\\\:.
Part of the command passed:
...drawtext=text='timestamp \\: %{pts \\: localtime \\: 1665679092.241...
Expected command:
...drawtext=text='timestamp \: %{pts \: localtime \: 1665679092.241...
Error message:
...drawtext=text='timestamp \\: %{pts \\: localtime \\: 1665679092.241...
How do I get /: through to the exec function?
It looks like the issue might be related to escaping special characters in the ffmpegCode string. The execPromise function is interpreting the backslash character () as an escape character, which is modifying the string passed to ffmpeg in unexpected ways.
To properly escape special characters in the ffmpegCode string, you can use the built-in JSON.stringify() function. This function properly escapes special characters in a string and produces a valid JSON string that can be passed as an argument to execPromise.
Here's an updated encode function that uses JSON.stringify() to properly escape the ffmpegCode string:
const encode = async ffmpegCode => {
try {
console.log(ffmpegCode);
const command = `ffmpeg ${JSON.stringify(ffmpegCode)}`;
await execPromise(command);
return 200;
} catch (err) {
console.log(err);
}
};
By wrapping the ffmpegCode string with JSON.stringify(), the backslashes and other special characters will be properly escaped, allowing the execPromise function to properly execute the ffmpeg command.
Note that the resulting command string will be wrapped in double quotes, so you may need to modify your ffmpeg command to properly handle quoted arguments.

How can I take multiple words as one argument in Discord.Js

I want to make a command like !ban <mentioned_user> <reason>.
But I tried many ways to do but nothing suits for my code, I want to get the reason string as args[1].
I used this code to fetch all arguments and to store all argument in args variable...
let messageArray = message.content.split(" ");
let command = messageArray[0].toLowerCase();
let args = messageArray.slice(1);
Try something like that
const argument = msg.content.trim().split(/ +/g);
const comand = argument.shift().toLowerCase();
if(comand === `${prefix}ban`) {
const user = argument[0];
const reason = argument.slice(1).join(' ');
// ban user
}
If I understand well, message.content contains "<mentioned_user> <reason>"
If I'm correct, you can get each in a variable and then do what you want with it
const [mentionedUser, ...arrRreason] = message.content.split(" ");
const reason = arrReason.join(' ');
// or
const reason = message.content.substring(message.content.indexOf(' ') + 1);

How to check if JSON includes something NODEJS

I want to check if my JSON includes "hello". All of the JSON.
Normally if it was a string I'd do this:
var string = "hello there this is a test"
if(string.includes("hello")) return console.log("Hello found")
is there a JSON version for that?
You can convert the JSON into javascript object using JSON.parse() and then search on it.
For example:
let jsonOb = {"msg": "hello there this is a test"}
let ob = JSON.parse(jsonOb)
let string = ob.msg
if(string.includes("hello")) return console.log("Hello found")
Hope it solves your problem.

Require() from string into object

Assuming I have the content of a js file in a string. Furthermore, assume it has an exports['default'] = function() {...} and/or other exported properties or functions. Is there any way to "require" it (compile it) from that string into an object, such that I can use it? (Also, I don't want to cache it like require() does.)
Here's a very simple example using vm.runInThisContext():
const vm = require('vm');
let code = `
exports['default'] = function() {
console.log('hello world');
}
`
global.exports = {}; // this is what `exports` in the code will refer to
vm.runInThisContext(code);
global.exports.default(); // "hello world"
Or, if you don't want to use globals, you can achieve something similar using eval:
let sandbox = {};
let wrappedCode = `void function(exports) { ${ code } }(sandbox)`;
eval(wrappedCode);
sandbox.default(); // "hello world"
Both methods assume that the code you're feeding to it is "safe", because they will both allow running arbitrary code.

Invalid character entity parsing xml

I am trying to parse a string of xml and I getting an error
[Error: Invalid character entity
Line: 0
Column: 837
Char: ]
Does xml not like brackets? Do I need to replace all the brackets with something like \\]. Thanks
Ok, the invalid character was the dash and an &. I fixed it by doing the following:
xml = data.testSteps.replace(/[\n\r]/g, '\\n')
.replace(/&/g,"&")
.replace(/-/g,"-");
Thanks
Using a node domparser will get around having to do a string replace on every character that is not easily parsed as a string. This is especially useful if you have a large amount of XML to parse that may have different characters.
I would recommend xmldom as I have used it successfully with xml2js
The combined usage looks like the following:
var parseString = require('xml2js').parseString;
var DOMParser = require('xmldom').DOMParser;
var xmlString = "<test>some stuff </test>";
var xmlStringSerialized = new DOMParser().parseFromString(xmlString, "text/xml");
parseString(xmlStringSerialized, function (err, result) {
if (err) {
//did not work
} else {
//worked! use JSON.stringify()
var allDone = JSON.stringify(result);
}
});

Resources