So I’m doing a discord bot and decided to group my commands in separate files like help.js is one command and ping.js is another for example. Though now the problem is that the command cant find the module and so the code gives me an error like:
UnhandledPromiseRejectionWarning: ReferenceError: ms is not defined
Even though I have it defined in the top of the index file. (ms is a module that I need in my mute command to convert time)
const ms = require(“ms”);
I use this to get the commands:
try {
if (fs.existsSync(`./commands/${command}.js`)) {
let commandFile = require(`./commands/${command}.js`);
commandFile.run(client, message, args);
} else {
message.reply(`+${command} does not exist`)
}
And here is the ping command for example:
exports.run = async (client, message, args, level) => {
const m = await message.channel.send("Ping?");
m.edit(`Pong! Latency is ${m.createdTimestamp -message.createdTimestamp}ms. API Latency is ${Math.round(client.ping)}ms`);
}
I have checked that I have the node modules installed.
My question is, what am I doing wrong, why is it doing this & what do I do to fix this?
You need to require it in every file you have, unless it won't be available for you. You can also export it but you still need to import the main file and use it from there.
Related
I am getting this problem every time I import a lib or when I use puppeteer and I don't know how to fix it. I am trying to get some data from LinkedIn using https://www.npmjs.com/package/linkedin-client
the code is easy:
import LinkedinClient from 'linkedin-client';
async function getIt() {
const session = supabase.auth.session();
const tok = session?.provider_token;
const token = JSON.stringify(tok);
console.log(token);
const client = new LinkedinClient(token);
const data = await client.fetch('https://www.linkedin.com/in/some-profile/');
console.log(data);
}
at first it gives me this error:Module "util" has been externalized for browser compatibility. Cannot access "util.promisify" in client code
after I install npm i util then it displays the following error:
500 process is not defined ReferenceError: process is not defined
Can you please let me know how to fix it?(I'm using sveltekit)
The library requires to be run on the server. It has be in a server endpoint, it cannot be in a component or a load function.
If this is already the case, this might be an issue with Vite trying to remove server dependencies. There is e.g. a plugin #esbuild-plugins/node-globals-polyfill which polyfills the process variable. It may also be necessary to list packages in resolve.alias in the Vite config, to point to the Node modules.
I am trying to use #metaplex/js to do some NFT minting. Usually my .js files work properly but when I run the file this error comes up.
bigint: Failed to load bindings, pure JS will be used (try npm run rebuild?)
I don't really get what that means. So, I tried to run npm run rebuild but rebuild is said to be a missing script and I couldn't find a way to install it.
Here is my code:
import { Connection, programs} from "#metaplex/js";
import { Loader } from "#solana/web3.js";
const { metadata: {Metadata}} = programs;
const connection = new Connection("devnet");
const tokenPublicKey = 'my_adress';
const run = async() => {
try{
const ownedMetadata = await Metadata.Loader(connection,tokenPublicKey)
console.log(ownedMetadata)
}
catch{
console.log('Failed to fetch')
}
};
run();
If you have any idea, or simply an explanation of what my error means, I'd be grateful.
You are getting this error because a nested dependency has a compilation step that might not succeed in your platform. This issue provides a good explanation.
[...] This happens because one of our dependencies (bigint-buffer) runs a compilation step on installation and this can step may fail for a couple of reasons. One of the reasons is that your system might not have the build-tools the library is looking for. You can install these build tools on Windows (see https://www.npmjs.com/package/windows-build-tools), but you don't actually need to as it automatically falls back to a pure JS solution instead. Though I agree... that warning is very annoying.
However, this should give you a warning and still allow you to compile your code.
It is worth noting that the current JS SDK from Metaplex is going to be deprecated in favour of the new one: https://github.com/metaplex-foundation/js-next
With the new JS SDK, you can fetch an NFT using the following piece of code.
import { Metaplex } from "#metaplex-foundation/js";
import { Connection, clusterApiUrl } from "#solana/web3.js";
const connection = new Connection(clusterApiUrl("mainnet-beta"));
const metaplex = new Metaplex(connection);
const mintAddress = new PublicKey("ATe3DymKZadrUoqAMn7HSpraxE4gB88uo1L9zLGmzJeL");
const nft = await metaplex.nfts().findByMint({ mintAddress });
I'm working with a temp file that's downloaded from a server. but when I ran it on macOS, it ran fine. and did what it was supposed to do. but when I ran it on windows, it keeps giving me an EBUSY error when trying to spawn the child.
I tried delaying the start of the file. tried to remove the chmod so it just runs on Linux and macOS. But still getting the Ebusy error. Am I doing something wrong?
Note:
I can launch the binary from another node instance outside. Like from a cmd. but launching it from the node instances that created it leads to a Ebusy error.
temp.open('', (err, info) => {
if (err) throw err;
console.log('File: ', info.path);
console.log('Filedescriptor: ', info.fd);
var data = fs.createWriteStream(info.path);
res.data.pipe(data);
data.on('close', async () => {
fs.chmodSync(info.path, 0o755);
await delay(1000);
var child = cp.spawn(info.path, [key, jwt], { stdio: ['inherit', 'inherit', 'inherit', 'ipc'] });
Error:
Error: spawn EBUSY
at ChildProcess.spawn (node:internal/child_process:415:11)
at Object.spawn (node:child_process:707:9)
at WriteStream.<anonymous>
at WriteStream.emit (node:events:394:28)
at emitCloseNT (node:internal/streams/destroy:138:10)
at processTicksAndRejections (node:internal/process/task_queues:82:21) {
errno: -4082,
code: 'EBUSY',
syscall:
Edit:
I created a new module to try to spawn the child that way. it will be forked in the main process. but I'm still getting the same error in the fork. still the same error.
const cp = require('child_process')
const childpath = process.argv[2]
var argv = [];
for (let index = 3; index < process.argv.length; index++) {
const element = process.argv[index];
argv.push(element)
}
console.log(argv)
var child = cp.spawn(childpath, argv, {
stdio: ['inherit', 'inherit', 'inherit', 'ipc']
})
child.on('message', (msg) => {
if (process.send) process.send(msg)
else process.emit('message', msg)
})
child.on('error', (msg) => {
console.log(msg)
process.emit('error', msg)
})
child.on('close', (msg) => {
process.exit(msg)
})
Update:
I've noticed that I cannot run the file until the process the created it is ended. meaning that the process that needs to use it is using it. but I cannot do the thing I want to do with it.EI spawn it
Update 2:
The next thing I tried was to create a symbolic link with the node. And still nothing but I noticed that the file doesn't become runnable until the main process is ended. which means that the process that I'm running has something to do with it. So I need to be able to unlike it from the process that's running. it seems like windows need to do some initialization after the file is made. and because it's still connected to the main process in some way it's not able to. Im guess this is why when I ended the process, the node icon showed up on the symlink and that's why I'm able to run it manually.
Final Update:
I'm gonna work on a file system module that acts like temp files but is just regular files. that the process is tracking. giving the function of temp files but not really. this will allow me to use the function of temp files but without the file being unable to be executed. It seems like making it a temp file made it so it could not be executed by the same process that created it. it seems like a windows file system thing and how they handle temp file permissions.
The way Temp files are handled in windows is different than macOS. to my best estimate, it seems like Temp files in windows are linked to the process that created them and aren't able to be changed or accessed by that process. The problem lies in trying to execute these temp files which windows has assigned to a process already making it unassignable. NodeJs needs to be able to access the file to be able to launch it and windows permission will not allow it until the main process is killed or ended. this unlinks the file from that process making it accessible to the rest of the system.
I am currently trying to make a simple discord bot following the discord.js documentation.(https://discordjs.guide/creating-your-bot/creating-commands.html#command-deployment-script)
My issue is regarding the deploy-command.js file:
const {SlashCommandBuilder} = require('#discordjs/builders')
const {Routes} = require('discord-api-types/v9')
const dotenv = require('dotenv')
const {REST} = require("#discordjs/rest");
dotenv.config()
const token = process.env.DISCORD_JS_TOKEN
const clientId = process.env.clientId
const guildId = process.env.guildId
const commands = [
new SlashCommandBuilder().setName('ping').setDescription('Replies with pong!'),
new SlashCommandBuilder().setName('server').setDescription('Replies with server info!'),
new SlashCommandBuilder().setName('user').setDescription('Replies with user info!')
].map(command => command.toJSON())
const rest = new REST({version:'9'}).setToken(token)
rest.put(Routes.applicationGuildCommands(clientId,guildId),{body:commands})
.then(() => console.log("Successfully registered application commands from file"))
.catch(() => console.log('error happened'))
I'm getting an error at the following line:
const rest = new REST({version:'9'}).setToken(token) ---> Interface cannot be instantiated
I've tried removing package-lock.json and node_modules and then reinstalling them via "npm install", that didn't have any effect.
There is a REST interface and a REST class in the discordjs/rest module. While hovering over the
{version:'9'}, I'm getting the following message: "Invalid number of arguments, expected 0" and the suggestion to "create constructor in class rest"(which there already is one, for the REST class)
This issue has been extremly frustrating as I can't seem to find anyone else that had a similar issue and all the videos I've watched on youtube execute the exact same code with no issues(only difference being that they use visual studio code in the videos).
Any help would be appreciated.
software used:
nodejs(tried version 16.6.0 and 17.0.0)
webstorm 2021.2.2
I had the exact same issue and then tried it on VS Code and it perfectly worked. I have no idea so far as to why it does not work in Webstorm though...
Ive came across the same issue. For anyone whos coming across this thread and has the same issue, i found out that i was using the wrong Client ID. i was using my personal Client ID instead of the ClientID of the Bot found in the discord developer portal.
The documentation doesn't clearly state this annoyingly
What I want to do is if I have a file called test.js I want to be able to run a Discord command, for example !deletefile, and it will delete the test.js file. Is this possible? If not, is it possible to do something similar but be able to edit the file instead of deleting it?
It seems you want to delete a file using a Discord bot.
You can use the built-in Node.js module, fs for this. Its .unlink method will remove a file. I don't think it's a good idea to remove files through a Discord bot, but the following should work:
const fs = require('fs').promises;
const path = require('path');
const { Client } = require('discord.js');
const client = new Client();
client.on('message', async (message) => {
if (message.author.bot || !message.content.startsWith('!deletefile')) return;
try {
// change the path to your file
await fs.unlink(path.join(__dirname, '../logs/1.test'));
message.channel.send('File is deleted. 🎉');
} catch (error) {
console.log(error);
message.channel.send('⚠️ Oops, there was an error. File is not deleted.');
}
});
And yes, you can also edit files in Node.js.
If you want to use your keyboard, you could focus on the file using your arrow keys and then press CMD + Delete (or CTRL, respectively). Doing this, you can also press Enter to start renaming a file.
I suggest looking at keyboard shortcuts in VS Code:
macOS: https://code.visualstudio.com/shortcuts/keyboard-shortcuts-macos.pdf
windows: https://code.visualstudio.com/shortcuts/keyboard-shortcuts-windows.pdf
linux: https://code.visualstudio.com/shortcuts/keyboard-shortcuts-linux.pdf
Vscode is just a text editor, if you press ctr` you can open the terminal and check what shell do you have, if you installed git then you probably have bash which is a linux shell. you can invest a tiny amount of time and learn bash and you can do much more than deleting a file. the command to delete a file is:
rm filename