Unexpected token '?' using, Discord.js Slash Command handler [duplicate] - javascript

I'm not sure what's wrong. I deleted my code and downloaded it then uploaded it again and now I get this error.
Code: https://replit.com/#hi12167pies/webcord#index.js (Click code for code and output for output)
Error:
/home/runner/C8AU9ceLyjc/node_modules/discord.js/src/rest/RESTManager.js:32
const token = this.client.token ?? this.client.accessToken;
^
SyntaxError: Unexpected token '?'
I have no idea whats wrong since it's in the node_modules folder.
If you have problems viewing it here is the code:
const http = require("http")
const discord = require("discord.js")
const client = new discord.Client()
const config = require("./config.json")
const fs = require("fs")
// const readLine = require("readline")
// const rl = readLine.createInterface({
// input: process.stdin,
// output: process.stdout
// })
let msgs = {
"873195510251532348": [],
"873195522633105429": []
}
client.on("ready", () => {
console.log("ready discord")
})
client.on("message", (message) => {
if (message.author.bot) return
if (!config.chats.includes(message.channel.id.toString())) return
msgs[message.channel.id].push({
"username": message.author.tag,
"content": message.content,
"type": "0"
})
})
http.createServer((req,res) => {
const url = req.url.split("?")[0]
let query = {}
req.url.slice(req.url.split("").indexOf("?")).slice(1).split("&").forEach((e) => {
const splited = e.split("=")
query[splited[0]] = splited[1]
})
if (query.q == "messages") {
let msg = []
let i = 0
while (msgs[query.code].length > i) {
const e = msgs[query.code][msgs[query.code].length - (i+1)]
msg.push(e)
i++
}
res.write(JSON.stringify(msg))
res.end()
} else if (query.q == "post") {
let name = query.name.split("%20").join(" ")
let content = query.content.split("%20").join(" ")
client.channels.cache.get(query.code).send(`**${name}**: ${content}`)
msgs[query.code].push({
"username": name,
"content": content,
"type": "1"
})
res.end()
} else if (url == "/robot" && query.istrue == "true") {
res.write("Robot!")
res.end()
} else {
let path
if (!query.code) {
path = "./code.html"
} else {
if (!config.chats.includes(query.code)) {
path = "./invaildcode.html"
} else {
path = "./chat.html"
}
}
fs.readFile(path, (er, da) => {
if (er) res.write("Could not get index.html")
res.write(da)
res.end()
})
}
}).listen(80, (err) => {
if (err) throw err
console.log("listening webserver")
})
client.login(process.env.TOKEN)
I am aware my code is not good right now, I am rewriting it but I still want to know what the error is.

repl.it uses node v12.22.1 but the nullish coalescing operator (??), is relatively new and was added in node v14.
So to use the ?? operator you need to update node in repl.it.
Which you can do by following this repl.it forum post by lukenzy.
Create a file and name it .replit
Inside it, copy and paste the following code:
run = """
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
export NVM_DIR=\"$HOME/.nvm\"
[ -s \"$NVM_DIR/nvm.sh\" ] && \\. \"$NVM_DIR/nvm.sh\"
[ -s \"$NVM_DIR/bash_completion\" ] && \\.\"$NVM_DIR/bash_completion\"
nvm install 14
node index.js
"""
This will install and use the latest Node.js v14 (14.17.4).
If u want to use a different version, change nvm install 14 to any other
number.
Also, change node index.js to the file u want to run.

You are getting this error because you are using an older version of node that didn't support nullable for some packages.
Simply change node version of yours.
You can simply change node versions using 'nvm'. follow this git repo https://github.com/nvm-sh/nvm

Related

using forEach inside a string

Im trying to use fs to make a Command-Handler for ESM(ECMAScript) because you can't use fs in ESM i have 2 js enviornments, one with ESM and one with Node.js the Node env is only there so it reads all file names of a folder and uses the names to import and export them inside a file that the other env uses. I allready have it so the names get stored inside a const in the node env but when i try to write them with fs it gives me an error, and when i try to log the string it says undefined
const fs = require("fs")
const commands = []
try {
fs.unlinkSync("./scripts/modules/commands.js")
console.log('\x1b[32m File Deleted Succesfully \x1b[0m')
} catch (e) {
console.error(e)
}
try {
fs.openSync("./scripts/modules/commands.js", 'w')
console.log('\x1b[32m Created File Successfully')
} catch (e) {
console.error(e)
}
try {
const cCommands = fs.readdirSync("./scripts/modules/commands/").filter(file => file.endsWith('.js'));
for (const file of cCommands) {
const name = file.replace(".js", "")
commands.push(name)
}
console.log('\x1b[32m Pushed all Files Successfully \x1b[0m\n')
} catch (e) {
console.error(e)
}
// This outputs => 'ping' as a string
console.log(`${commands}`)
// This outputs => undefinedexport const commands = {undefined}; but should output => import {ping} from './commands/ping'; export const commands = {ping:ping};
console.log(`${commands.forEach(command => `import {${command}} from './commands/${command}';`)}export const commands = {${commands.forEach(command => `${command}:${command},`)}};`)
try {
const cmdString = `${commands.forEach(command => `import {${command}} from './commands/${command}';`)}export const commands = {${commands.forEach(command => `${command}:${command},`)}};`
const jsonString = JSON.stringify(cmdString);
fs.writeFile("./scripts/modules/commands.js", jsonString)
console.log(jsonString)
console.log('\x1b[32m Send all Commands Successfully \x1b[0m')
} catch (e) {
console.error(e)
}
Edit: Changed all .forEach() functions to .map() now this error accures => TypeError [ERR_INVALID_ARG_TYPE]: The "cb" argument must be of type function. Received undefined
To fix this error just use fs.writeFileSync instead of fs.writeFile

slashCommands.push(slashCommand.data.toJSON()); | TypeError: Cannot read properties of undefined (reading 'toJSON')

I started the bot as usual, in the handler or other file from the slash command I didn't change anything.
anyone know how to group? I need it now, and I can't find anything on the internet.
I started doing the bot at 1 p.m., now when I am writing this it is 10:13 p.m. and the problem appeared only around 9:30 p.m.
I don't know what to write next but they keep telling me so have a nice day / night: D
const fs = require('fs')
const { REST } = require('#discordjs/rest')
const { Routes } = require('discord-api-types/v9')
const token = process.env['token']; //get the token in .env
const guild = process.env['guild']; //get the guild ID in .env
const application_id = process.env['application_id']; //get the application ID in .env
module.exports = (client) => {
const slashCommands = []; //make a variable
fs.readdirSync('./slashCommands/').forEach(dir => {
const slashCommandFiles = fs.readdirSync(`./slashCommands/${dir}/`).filter(file => file.endsWith('.js'));
for (const file of slashCommandFiles) {
const slashCommand =require(`../slashCommands/${dir}/${file}`);
slashCommands.push(slashCommand.data.toJSON());
if(slashCommand.data.name) { //if the slash command file has a name
client.slashCommands.set(slashCommand.data.name, slashCommand)
console.log(file, '- Success') //check if the file load and log in console
} else {
console.log(file, '- Error') //if the file doesn't have command name, log it error in console
}
}
});
const rest = new REST({ version: '9' }).setToken(token);
(async () => {
try{
console.log('Start registering application slash commands...')
await rest.put(
guild
? Routes.applicationGuildCommands(application_id, guild) //registered the slash command in guild
: Routes.applicationCommands(application_id), //registered the slash command globally
{
body: slashCommands,
}
);
console.log('Successfully registered application slash commands.')
} catch (err) {
console.log(err);
}
})();
};
One of the files located in this directory is missing the data object: require(../slashCommands/${dir}/${file});
A fix that will stop the error, but will also render the file useless would be skipping over the file that is missing data or data.toJSON()
for (const file of slashCommandFiles) {
const slashCommand = require(`../slashCommands/${dir}/${file}`)
if (!slashCommand.data || !slashCommand.data.toJSON()) continue
// Carry on with code after here
}

Discord.js Error: EISDIR: illegal operation on a directory, read

When i try executing this code i get an error. "Error: EISDIR: illegal operation on a directory, read".
Line 18 : Column 19
const { Client, Intents, Collection } = require('discord.js')
const config = require('./config.json')
const fs = require('fs')
const bot = new Client({ intents: [ Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES ] })
bot.commands = new Collection()
var cmdFiles = fs.readFileSync('./cmd').filter(f => f.endsWith(".js"))
for(const f in cmdFiles) {
const cmd = require(`./commands/${f}`)
bot.commands.set(cmd.help.name, cmd)
}
bot.once("ready", () => {
console.log('Bot is ready!')
})
bot.on("messageCreate", async message => {
if(message.author.bot) return;
var prefix = config.prefix
if(!message.content.startsWith(prefix)) return;
var array = message.content.split(" ");
var command = array[0];
const data = bot.commands.get(command.slice(prefix.length))
if(!data) return;
var args = array.slice(1)
try {
await data.run(bot, message, args)
} catch(e) {
await message.channel.send(e)
await console.log(e)
}
})
bot.login(config.token)
Yes all config things are defined.
I've tried searching for this error but got nothing that i need.
What i want to do is load every file from the directory 'cmd' in a array list and run a command if it is called.
Change this:
var cmdFiles = fs.readFileSync('./cmd').filter(f => f.endsWith(".js"));
to this:
var cmdFiles = fs.readdirSync('./cmd').filter(f => f.endsWith(".js"));
As your question states, ./cmd is a directory and you can't list the files in a directory with fs.readFileSync(). You would use fs.readdirSync() to do that.
fs.readFileSync() tries to open the directory as a file and read its contents. Since it's not a file, you get the EISDIR error.

MongoServerSelectionError: getaddrinfo ENOTFOUND at Timeout._onTimeout

So you may have seen this question type somewhere else. but the thing here is I tried all of the things we need to do according to docs and saw other posts with similar errors but still my error is not fixed. So I use keyv and use MongoDB atlas as storage adapter in this code, but the error is from MongoDB. Also, there is no error in the "keyv" because it works for other people, there is error in the MongoDB
So now I will list whatever I tried:
1. Made sure there is IP access
2. The userid and passcode are correct
3. The MongoDB atlas is running
4. Read the docs and code multiple times
5. If u think adding the +srv with the code will fix the error, it won't, it doesn't work with keyql idk why also it is not present in many codes, I already tried it
So this is the code
const { Client, Intents, MessageEmbed, Collection } = require('discord.js');
let client = new Client({ intents: [Intents.FLAGS.GUILDS,Intents.FLAGS.GUILD_MESSAGES] });
const dotenv = require('dotenv');
const Keyv = require('keyv');
const keyv = new Keyv('mongodb://Discord:password#cluster0.auifa.mongodb.net/Cluster0');
dotenv.config();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('messageCreate', async (msg) => {
if (msg.author.bot) return;
let number = msg.content.split(' ')[1];
if (msg.content === '!ping') {
msg.channel.send('ping!')
}
// Use like const prefix = await getGuildPrefix(); `
const getGuildPrefix = async () => {
const prefixMap = await keyv.get('prefix');
return prefixMap ?. [msg.guild.id] || "!"
}
// Sets the prefix to the current guild.
const setGuildPrefix = async (prefix) => {
let prefixMap = await keyv.get('prefix');
if (!prefixMap)
{
prefixMap = "!";
}
prefixMap[msg.guild.id] = prefix;
await keyv.set('prefix', `${prefixMap}`);
}
let prefix = await getGuildPrefix();
// Get prefix command.
if ((msg.content === `${process.env.prefix}prefix`) || (msg.content === `${prefix}prefix`)) {
msg.channel.send(`Your server prefix is ${prefix}`)
}
// Change prefix command
const commandPrefix = await getGuildPrefix();
if ((msg.content.startsWith(`${process.env.prefix}setprefix`)) || (msg.content.startsWith(`${commandPrefix}setprefix`))) {
const newPrefix = number;
if (newPrefix.length === 0) {
msg.channel.send(`Please enter a valid prefix`);
}
await setGuildPrefix(newPrefix)
msg.channel.send(`Your server prefix is now '${newPrefix}'`);
}
})
client.login(process.env.token);
And this is the error message
Keyv connection error: MongoServerSelectionError: getaddrinfo ENOTFOUND cluster0.auifa.mongodb.net
at Timeout._onTimeout (D:\javascript\node_modules\mongojs\node_modules\mongodb\lib\core\sdam\topology.js:438:30)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7) {
reason: TopologyDescription
Connection string does not look like an Atlas one.
It has to be something like: mongodb+srv://<username>:<password>#cluster0.auifa.mongodb.net/YOUR-DB
Login to your Atlas account then:
Go to Databases page
Click on Connect button
Choose "Connect your application"
Copy your connection string
Docs about Mongo Atlas connection: https://docs.atlas.mongodb.com/connect-to-cluster/#connect-to-a-cluster

Paho MQTT: Possible importing error?

I recently downloaded paho-mqttvia yarn. The problem is I am not sure if I am importing it correctly, because I am getting an error:
Cannot read property 'Client' of undefined
The way I am importing and using it is like this:
import Paho from 'paho-mqtt';
var client = new Paho.MQTT.Client(location.host, location.port, location.clientID)
const MQTTConnectAndMessage = (message) => {
client.connect({onSuccess: sendMQTTMessage})
}
const sendMQTTMessage = (msg) => {
let message = new Paho.MQTT.Message(msg);
message.destinationName = location.messageDestination;
client.send(message);
}
location.host = a string for the IP
location.port = a number for the port
location.clientID = a string for the clientID
If it is relevant, I am attempting to use it within a React Native app.
Maybe this module is not meant to be downloaded via NPM or Yarn? Or maybe I am not supposed to be importing "Paho"?
EDIT: when using react-native-paho-mqtt--this is the code I am using:
const client = new Client({ uri: 'ws://myiphere/ws', port: 1883, clientId: 'clientId', storage: myStorage});
const sendMQTTMessage = (msg) => {
client.on('connectionLost', (responseObject) => {
if (responseObject.errorCode !== 0) {
console.log("connection lost!");
}
});
client.on('messageReceived', (message) => {
console.log(message.payloadString);
});
client.connect()
.then(() => {
const message = new Message(msg);
message.destinationName = 'F2/BOX2/LED3';
client.send(message);
})
.catch((responseObject) => {
if (responseObject.errorCode !== 0) {
console.log('onConnectionLost:' + responseObject.errorMessage);
}
});
}
export {
sendMQTTMessage
}
I notice that whenever I enter anything that isn't prefaced with ws:// (web sockets) I would get a URI error.
The paho-mqtt library has changed, and the example code is incorrect
var client = new Paho.MQTT.Client(location.host, location.port, location.clientID)
Should be changed to (remove MQTT from Object path):
var client = new Paho.Client(location.host, location.port, location.clientID)
See the "breaking changes" in the GitHub README page:
paho.mqtt.javascript
Try this react-native compatible library: https://www.npmjs.com/package/react-native-paho-mqtt
yarn add react-native-paho-mqtt

Categories