Discord Command Prompt Error with Constants - javascript

When I would enter
"node index.js"
Into Command Prompt & the folder with all of the Discord bot information, it'd give me this error:
const client = Discord.Client();
^^^^^
SyntaxError: Unexpected token const
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
Anyway to fix?
Edit:
config.json
{
"BOT_TOKEN": "bot's token"
}
index.js
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
client.login('bot's token');

From what i can see, you have probably put one of these somewhere in the code: (maybe by accident in another .js file?)
const client = Discord.client();
SyntaxError: Unexpected token const, usually means the app waited for some kind of const, but did not receive it.
Also, try to move the 'Token' constant in your index.js file.

It's suggesting somewhere in your code you have const client = Discord.Client();. Once found just remove it.
Advice
I'd suggest you refer to your config.json .
The following:
const settings = require('./config.json')
Then extract bot token by making a variable:
const token = settings.BOT_TOKEN;
Result:
client.login(token);
Optimises your code ;)

Related

Discord Bot initialization Failure

I have a problem in creating the main file for my discord bot. currently, i encountered a problem in trying to get my bot to work but sadly, this error message has been outputted from the console.
PS C:\Users\Kelvin Wang\Documents\Projects\DiscordBot> node index.js
node:internal/modules/cjs/loader:1170
throw err;
^
SyntaxError: C:\Users\Kelvin Wang\Documents\Projects\DiscordBot\config.json: Unexpected end of JSON input
at parse (<anonymous>)
at Object.Module._extensions..json (node:internal/modules/cjs/loader:1167:22)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (C:\Users\Kelvin Wang\Documents\Projects\DiscordBot\index.js:4:19)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
My code in index.js is this:
//initial discord initialization of client and library
// Require the necessary discord.js classes
const { Client, Intents } = require('discord.js');
const { token } = require('./config.json');
const dotenv = require('dotenv');
// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
// When the client is ready, run this code (only once)
client.once('ready', () => {
console.log('Ferraribot is online!');
});
// Login to Discord with your client's token
client.login(token);
While my config.json looks like this:
{
"token": "token"
}
Any help would be much appreciated! This is my first time using stack overflow so I'm sorry for any wrong formatting that I've done. Thanks in advance!
Your code looks just fine.
The error said, your code has some problems reading the JSON config. (is it in the same directory?)
First try your code using your token in the index.js. client.login(*****) // just don't upload e.g. github ;)
Second, I believe better practice using .env for sensitive information. https://www.npmjs.com/package/dotenv

discord bot -- node index.js problem -- "client is not defined"

I've been working on a discord bot, but when I run node main.js it replies with this response:
(I have changed index.js with main.js, as that is what the file is called)
/Users/Liam/Desktop/Discordbot/main.js:7
client.once('ready', () => {
^
ReferenceError: client is not defined
at Object.<anonymous> (/Users/Liam/Desktop/Discordbot/main.js:7:1)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at internal/main/run_main_module.js:17:47
This is my full code:
const Discord = require("discord.js");
const client = new Discord.Client();
client.once("ready", () => {
console.log("Online!");
});
client.login("TOKEN");
I think you copied the wrong error, because when I tried to recreate this error it gave me different error, which has a simple solution.
client.login takes in a private discord token, I'm guessing you probably pasted the "TOKEN" string directly from a guide.
To create a bot token, follow the official docs at https://discordjs.guide/
After you created the token, you can do this:
const Discord = require("discord.js");
const client = new Discord.Client();
const token = 'ThePrivateTokenYouGenerated'
client.once("ready", () => {
console.log("Online!");
});
client.login(token);

Discord.js module error before first line of code

I just started writing a Discord bot in Visual Studio Code in Javascript, it's literally the most basic it can be, loading discord.js, on ready event and then login.
Before it even runs the first line of code, I get this error:
Debugger listening on ws://127.0.0.1:5489/3cf4a3d1-ef26-4c1c-a274-030564d40731
For help see https://nodejs.org/en/docs/inspector
i:\Coding\Bots\PURGE\node_modules\discord.js\src\util\Util.js:584
str = str.replace(/#([^<># ]*)/gmsu, (match, target) => {
^
SyntaxError: Invalid regular expression flags
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:607:28)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Module.require (module.js:587:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (i:\Coding\Bots\PURGE\node_modules\discord.js\src\index.js:3:14)
Process exited with code 1
The error occurs in the Discord.js module which I didn't write, and have no idea how it works and therefore cannot fix.
Re-installling Discord.js didn't help, reinstalling Visual Studio Code didn't either.
I sent a friend the exact same files (even the same node_modules folder) and when he runs it, it works with no problems. Any ideas what the problem is or how I can fix it?
This is my code:
console.log("test") //DOESNT LOG
const Discord = require("discord.js");
const fs = require("fs");
const config = require("./config.json");
let christian = {}
//This will define our bot
var bot = new Discord.Client()
bot.on('message', async msg => {
console.log(msg)
})
bot.on('ready', () => {
console.log(`-----Purge#2420 Online-----\nWatching over ${bot.guilds.cache.size} servers |`)
});
bot.login(config.token)
From the comments:
I am on [Node] v8.9.4, [...] on Discord.js V12
From Discord JS' upgrade guide::
v12 requires Node 12.x or higher to use, so make sure you're up-to-date.
That is -- you'll have to upgrade your Node.js.
In the ready event you have an invalid string which maybe causing the error '-----Purge#2420 Online-----\nWatching over ${bot.guilds.cache.size} servers | it maybe crashing due to the invalid single quote ' at string's start, try replacing it with a backtick (`).
Read more about template strings here

How can you read commands from another file using Discord.js?

So. I've been searching for a while, and couldn't seem to find anything that particularly applies. So far, I've got this:
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
Then, in my second file, located in commands, which is named ping.js
module.exports = {
name: 'ping',
description: 'Ping!',
cooldown: 5,
execute(message) {
message.channel.send('Pong.');
},
};
The error that I've been getting is the following,
internal/modules/cjs/loader.js:979
throw err;
^
Error: Cannot find module './commands/hello.js'
Require stack:
- /Users/SurajAnand/Desktop/Discord/discordBot/index.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:976:15)
at Function.Module._load (internal/modules/cjs/loader.js:859:27)
at Module.require (internal/modules/cjs/loader.js:1036:19)
at require (internal/modules/cjs/helpers.js:72:18)
at Object.<anonymous> (/Users/SurajAnand/Desktop/Discord/discordBot/index.js:11:18)
at Module._compile (internal/modules/cjs/loader.js:1147:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1167:10)
at Module.load (internal/modules/cjs/loader.js:996:32)
at Function.Module._load (internal/modules/cjs/loader.js:896:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [ '/Users/SurajAnand/Desktop/Discord/discordBot/index.js' ]
}
I've just started to get into JS for the sake of making a fun little bot to mess with some friends. I tried to run this piece of code off of the discord.js guide, and it seems incredibly cool... Just that I can't seem to get it to work, so any help would be very appreciated.
For me it looks like just the relative path is wrong.
If you call ./commands/hello.js in index.js, it will look in discordBot/commands/hello.js, which obviously doesn't exist. Change it from ./commands/hello.js to ../commands/hello.js, this should work.
Another option would be moving the commands folder into discordBot,which may be a bit cleaner but that is up to you to decide

Node.js async await in express

I'm building an endpoint /users which will return the contents in the Users.json file. I'm using aysnc/await feature.
var express = require('express');
var app = express();
var fs = require('fs');
var readFile = Promise.promisify(fs.readFile);
const util = require('util');
app.get('/users', async (req, res, next) => {
try {
const user = await readFile('./users.json');
return eval(user);
//res.send(JSON.parse(data));
// res.json(user);
} catch (e) {
//this will eventually be handled by your error handling middleware
next(e)
}
});
app.listen(3000,function(){
console.log("listening on port 3000");
});
This throws the below error
SyntaxError: Unexpected token (
at createScript (vm.js:56:10) at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:542:28) at Object.Module._extensions..js
(module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad
(module.js:446:12) at Function.Module._load (module.js:438:3) at
Module.runMain (module.js:604:10) at run (bootstrap_node.js:389:7) at
startup (bootstrap_node.js:149:9)
I'm using the npm 3.10.10 with node v6.11.3.
Can someone please guide where I have gone wrong?
Async/await is only available in Node versions 8 an up. Try using a newer Node version if possible.
Instead of calling:
return eval(user);
You should call:
res.send(JSON.parse(user));
or
res.send(JSON.stringify(JSON.parse(user)));
and use bodyParser.json() middleware if returning an object.
Likewise in the catch block,
res.status(500).send(‘there was an error’);
and log the error to your console.
——-
Also, fs.readFile takes another param, the encoding. Use ‘utf-8’. It returns a buffer, not a string, if you leave it out.

Categories

Resources