Discord error unexpected token

So it's my first ever time coding and i'm creating a discord bot. It's all been going fine until I try to run the bot.js file on commmand line (using "node bot.js") But It just comes up with a bunc...

Question: Will you re-post you error picture? When you click on it it says the page doesn’t exist.

PLEASE READ ALL BEFORE MAKING CHANGES!

First (Bad) Guess: But without the picture, I would guess (and this is not a good guess) that it’s because «client.login(auth.token)» isn’t at the bottom. Another guess is that «.content ===» does nothing. You should try and remove «.content» to see if it then works.

Here is your code with just that change:

const Discord = require('discord.js');
const client = new Discord.Client();
const auth = require('./auth.json');

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}`)
});

client.on('message', msg => {
    if (msg.content === 'ping') {
        msg.reply('pong')

    }
});



client.login(auth.token);

Logging bot is ready: The is also some other things I think you should change, this changing «client.user.tag» to «client.user.username» to instead show the bot’s username. Another thing is «msg.content» I’m pretty sure this does nothing, and should be changed to just «===», there are some other ones, but that’s my favorite one because it’s the least amount of characters and easiest to type.

Here is your code with all of these changes:

const Discord = require('discord.js');
const client = new Discord.Client();
const auth = require('./auth.json');

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}`)
});

client.on('message', msg => {
    if (msg === "ping") {
        msg.reply('pong')

    }
});



client.login(auth.token);

Token (& patrik's answer): (No hate to patrik) What patrik says that putting your token in the actual script will help (It won’t, and makes it easier to hack), now while I do this, I really don’t care if my bot gets hacked, it’s in one server. He/She also says that the token error means that discord.js can’t get the token, this is a node.js error, not a discord.js error. You probably messed up on writing a piece of code, that is likely in «auth.json». You should probably re-run through your files before doing any of these changes.

A auth/config/token (token file) .json file should look like this:

{
    "token":"TOKEN-HERE"
}

And then it should be used by doing

const auth|config|token = require(./auth|config|token.json);

client.login(auth.token);

I hope this helps with coding your bot!

Here’s the code I put in

 const Discord = require('discord.js');
const bot = new Discord.Client();
const TOKEN = 'insert token here'

bot.on('message', function(message) {
    if(message.content == "hello") {
        message.reply('Hey what up?');
    }
    ;

    bot.login(TOKEN);
    }
)

And here’s the error I got

SyntaxError: Unexpected token )
    at new Script (vm.js:83:7)
    at createScript (vm.js:267:10)
    at Object.runInThisContext (vm.js:319:10)
    at Module._compile (internal/modules/cjs/loader.js:685:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:733:10)
    at Module.load (internal/modules/cjs/loader.js:620:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
    at Function.Module._load (internal/modules/cjs/loader.js:552:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:775:12)
    at startup (internal/bootstrap/node.js:300:19)

I’m sorry if this is a really dumb question, I’m basically a newbie when it comes to coding this sort of stuff and coding in general for that matter.

(Just to note I’m using visual studio code and node.js)

asked Nov 28, 2018 at 4:44

Monsieur Oeuf's user avatar

10

The bot.login(TOKEN); needs to be outside of your message event handler. Additionally, your code formatting is incorrect. Here is corrected code that should work for you:

const Discord = require('discord.js');
const bot = new Discord.Client();
const TOKEN = 'your_token'

bot.on('message', function(message) {
    if(message.content == "hello") {
        message.reply('Hey what up?');
    }
});

bot.login(TOKEN);

answered Nov 28, 2018 at 17:59

Gridonyx's user avatar

0

Please describe the problem you are having in as much detail as possible:
when the script is ran, the following error produced:

/home/pi/node_modules/discord.js/src/structures/interfaces/Collector.js:203
  async *[Symbol.asyncIterator]() {
        ^

SyntaxError: Unexpected token *
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:617:28)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/home/pi/node_modules/discord.js/src/structures/MessageCollector.js:3:19)

Include a reproducible code sample here, if possible:

const Discord = require('discord.js');
const client = new Discord.Client();
var mysql = require('mysql');
var Raven = require('raven');

//Raven.config('SomeId').install();
client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on('message', msg => {
//  Raven.context(function () {

  if(msg.channel.type != "dm" && msg.content.startsWith('!')) {
    msg.channel.send('The bot will only function if it called in DM');
  } else if(msg.channel.type == "dm" && msg.content != "!something") {
    msg.channel.send('The bot will only handle The Something, no other command can be used. To verify, type !verify');
  }
  if (msg.content === '!something') {
    // Do the stuff
//    var dbconn = mysql.createConnection({
//      host: "localhost",
//      user: "yourusername",
//      password: "yourpassword",
//      database: "mydb"
//   });
  }
//});
});

client.login('code');

Further details:

  • discord.js version: 11.5.1
  • Node.js version: 8.16.1
  • Operating system: Raspbian Debian 9
  • Priority this issue should have – please be realistic and elaborate if possible:
    High
  • I have also tested the issue on latest master, commit hash:

Когда встречается. Допустим, вы пишете цикл for на JavaScript и вспоминаете, что там нужна переменная цикла, условие и шаг цикла:

for var i = 1; i < 10; i++ {
<span style="font-weight: 400;">  // какой-то код</span>
<span style="font-weight: 400;">}</span>

После запуска в браузере цикл падает с ошибкой:

❌ Uncaught SyntaxError: Unexpected token ‘var’

Что значит. Unexpected token означает, что интерпретатор вашего языка встретил в коде что-то неожиданное. В нашем случае это интерпретатор JavaScript, который не ожидал увидеть в этом месте слово var, поэтому остановил работу.

Причина — скорее всего, вы пропустили что-то из синтаксиса: скобку, кавычку, точку с запятой, запятую, что-то подобное. Может быть, у вас была опечатка в служебном слове и язык его не распознал.

Что делать с ошибкой Uncaught SyntaxError: Unexpected token

Когда интерпретатор не может обработать скрипт и выдаёт ошибку, он обязательно показывает номер строки, где эта ошибка произошла (в нашем случае — в первой же строке):

Интерпретатор обязательно показывает номер строки, где произошла ошибка Uncaught SyntaxError: Unexpected token

Если мы нажмём на надпись VM21412:1, то браузер нам сразу покажет строку с ошибкой и подчеркнёт непонятное для себя место:

Строка с ошибкой Uncaught SyntaxError: Unexpected token

По этому фрагменту сразу видно, что браузеру не нравится слово var. Что делать теперь:

  • Проверьте, так ли пишется эта конструкция на вашем языке. В случае JavaScript тут не хватает скобок. Должно быть for (var i=1; i<10; i++) {}
  • Посмотрите на предыдущие команды. Если там не закрыта скобка или кавычка, интерпретатор может ругаться на код немного позднее.

Попробуйте сами

Каждый из этих фрагментов кода даст ошибку Uncaught SyntaxError: Unexpected token. Попробуйте это исправить.

if (a==b) then  {}
function nearby(number, today, oneday, threeday) {
  if (user_today == today + 1 || user_today == today - 1)
    (user_oneday == oneday + 1 || user_oneday == oneday - 1)
      && (user_threeday == threeday + 1 || user_threeday == threeday - 1)
  return true
  
  else
     return false
}
var a = prompt('Зимой и летом одним цветом');
if (a == 'ель'); {
  alert("верно");
} else {
  alert("неверно");
}
alert(end);

Errors

There is no doubt that you have encountered errors while making bots. While errors are instrumental at warning you of what is going wrong, many people are stumped by them and how to track them down and fix them, but don’t worry, we have you covered. This section will be all about diagnosing errors, identifying where they are coming from, and fixing them.

Types of Errors

API Errors

API Errors or DiscordAPIErrors are thrown by the Discord API when an invalid request carries out. API Errors can be mostly diagnosed using the message that is given. You can further examine errors by inspecting the HTTP method and path used. We will explore tracking these errors down in the next section.

Example: DiscordAPIError: Cannot send an empty message

discord.js errors

discord.js errors are thrown by the library itself. They can usually be easily tracked down using the stack trace and error message.

Example: The messages must be an Array, Collection, or number.

JavaScript errors

JavaScript errors are thrown by node itself or by discord.js. These errors can easily be fixed by looking at the type of error and the stack trace. You can find a full list of types hereopen in new window And a list of common js errors hereopen in new window.

Example: ReferenceError: "x" is not defined, Cannot read properties of null(reading 'something')

WebSocket and Network errors

WebSocket and Network errors are common system errors thrown by Node in response to something wrong with the WebSocket connection. Unfortunately, these errors do not have a concrete solution and can be (usually) fixed by getting a better, more stable, and more robust connection. discord.js will automatically try to reconnect to the WebSocket if an error occurs.

In version 12, WebSocket errors are handled internally, meaning your process should never crash from them. If you want to log these errors, should they happen, you can listen to the shardError event as shown below.

client.on(Events.ShardError, error => {
	console.error('A websocket connection encountered an error:', error);
});

1
2
3

The commonly thrown codes for these errors are:

  • ECONNRESET — The connection was forcibly closed by a peer, thrown by the loss of connection to a WebSocket due to timeout or reboot.
  • ETIMEDOUT — A connect or send request failed because the receiving party did not respond after some time.
  • EPIPE — The remote side of the stream being written to has been closed.
  • ENOTFOUND — The domain being accessed is unavailable, usually caused by a lack of internet, can be thrown by the WebSocket and HTTP API.
  • ECONNREFUSED — The target machine refused the connection; check your ports and firewall.

How to diagnose API errors

API Errors can be tracked down by adding an event listener for unhandled rejections and looking at the extra info. This can be done by adding this to your main file.

process.on('unhandledRejection', error => {
	console.error('Unhandled promise rejection:', error);
});

1
2
3

The next time you get the error it will show info along the bottom of the error which will look something like this for example:

  name: 'DiscordAPIError',
  message: 'Invalid Form Bodynmessage_id: Value "[object Object]" is not snowflake.',
  path: '/api/v10/channels/638200642359525387/messages/[object%20Object]',
  code: 50035,
  method: 'GET'

1
2
3
4
5

All of this information can help you track down what caused the error and how to fix it. In this section, we will run through what each property means.

Message

The most important part of the error is the message. It tells you what went wrong, which can help you track down where it originates. You can find a full list of messages hereopen in new window in the Discord API documentation.

Path

Another helpful piece of information is the path, which tells you what API endpoint the error occurred on. We cannot possibly cover all endpoints, but they are usually very descriptive.

In the above example, the path tells you that the action was executed in the /channels/ scope. The number you see next is the channel’s id. Next, you can spot the message/ scope. The number is again the object’s id. Combined with the method GET you can conclude, that the bot tried to fetch the message with the id [object Object] from the channel with the id 638200642359525387.

As the error message tells you [object Object] is not a valid id, so you now know where to look for an error! Find out where you pass an object as an id when trying to fetch a message and fix your code in that location.

Code

The code is another partial representation of the message, in this case, Invalid Form Body. You can find a full list of codes hereopen in new window

The code is also handy if you want only to handle a specific error. Say you’re trying to delete a message which may or may not be there, and wanted to ignore unknown message errors. This can be done by checking the code, either manually or using discord.js constants.

message.delete().catch(error => {
	// Only log the error if it is not an Unknown Message error
	if (error.code !== 10008) {
		console.error('Failed to delete the message:', error);
	}
});

1
2
3
4
5
6

Or using Constants:

const { RESTJSONErrorCodes } = require('discord.js');

message.delete().catch(error => {
	if (error.code !== RESTJSONErrorCodes.UnknownMessage) {
		console.error('Failed to delete the message:', error);
	}
});

1
2
3
4
5
6
7

You can find a list of constants hereopen in new window.

Method

The final piece of information can tell you a lot about what you tried to do to the path. There are a set of predefined keywords that describe our actions on the path.

GET    - Used to retrieve a piece of data
POST   - Used to send a piece of data
PATCH  - Used to modify a piece of data
PUT    - Used to replace a piece of data completely
DELETE - Used to delete a piece of data completely

1
2
3
4
5

In this particular example, you can see you are trying to access a piece of data, specifically, a message.

Common discord.js and API errors

An invalid token was provided.

This is a prevalent error; it originates from a wrong token being passed into client.login(). The most common causes of this error are:

  • Not importing the config or env file correctly
  • Copying the client secret instead of the bot token (the token is alphanumerical and three parts delimited by a period while the client secret is significantly smaller and one part only)
  • Not updating the token after resetting it

WARNING

Before the release of version 12, there used to be an issue where the token was not prefixed correctly, which resulted in valid tokens being marked as invalid. If you have verified that all of the above is not the case, make sure you have updated discord.js to the current stable version.

Request to use token, but token was unavailable to the client.

This error originates from the client attempting to execute an action that requires the token but the token not being available. This is most commonly caused by destroying the client and then trying to perform an action.

This error is also caused by attempting to use a client that has not logged in. Both of the examples below will throw errors.

const { Client, GatewayIntentBits } = require('discord.js');

// Should not be here!
const client = new Client({ intents: [GatewayIntentBits.Guilds] });

module.exports = interaction => {
	const id = interaction.options.getString('id');
	// Should be `interaction.client` instead!
	client.users.fetch(id).then(user => {
		interaction.reply(`Your requested user: ${user.tag}`);
	});
};

1
2
3
4
5
6
7
8
9
10
11
12

const { Client, Events, GatewayIntentBits } = require('discord.js');

const client = new Client({ intents: [GatewayIntentBits.Guilds] });

client.on(Events.InteractionCreate, someHandlerFunction);

client.login('your-token-goes-here');
// client will not be logged in yet!
client.users.fetch('myId').then(someInitFunction);

1
2
3
4
5
6
7
8
9

EmbedBuilder field values may not be empty.

This error originates from calling EmbedBuilder#addFields() with a field object’s name property as an empty string. If you would like the title to be empty for a reason, you should use a zero width space, which can be input as u200b.

In conjunction with the previous error, this error results from calling EmbedBuilder#addFields() with a field object’s value property as an empty string. You can use a zero-width space if you would like this blank.

The messages must be an Array, Collection, or number.

This error originates from an invalid call to bulkDelete(). Make sure you are inputting a valid Array or Collection of messages or a valid number.

Members didn’t arrive in time.

This error happens when fetching multiple members via GuildMemberManager#fetch() and:

  • The GuildMembers intent is not specified or enabled in the dev dashboard
  • The internet connection is somewhat bad
  • The amount of members fetched is large (about 50 thousand and upwards)

You can specify the time to wait for with the time option in the .fetch() call. Another solution could be to move your bot to a faster infrastructure, if available.

MaxListenersExceededWarning: Possible EventEmitter memory leak detected…

This error is caused by spawning a large number of event listeners, usually for the client. The most common cause of this is nesting your event listeners instead of separating them. The way to fix this error is to make sure you do not nest your listeners; it is not to use emitter.setMaxListeners() as the error suggests.

You can debug these messages in different ways:

  • Through the CLIopen in new window: node --trace-warnings index.js
  • Through the process#warning eventopen in new window: process.on('warning', console.warn);

Cannot send messages to this user.

This error throws when the bot attempts to send a DM message to a user but cannot do so. A variety of reasons causes this:

  • The bot and the user do not share a guild (often, people attempt to DM the user after kicking or banning them).
  • The bot tries to DM another bot.
  • The user has blocked the bot.
  • The user has disabled DMs in the privacy settings.

In the case of the last two reasons, the error is not preventable, as the Discord API does not provide a way to check if you can send a user a DM until you attempt to send one. The best way to handle this error is to add a .catch() where you try to DM the user and either ignore the rejected Promise or do what you want because of it.

Common miscellaneous errors

code ENOENT… syscall spawn git.

This error is commonly thrown by your system due to it not finding git. You need to install git or update your path if git is already installed. Here are the download links for it:

  • Ubuntu/Debian: sudo apt-get install git
  • Windows: git-scmopen in new window

code ELIFECYCLE

This error is commonly thrown by your system in response to the process unexpectedly closing. Cleaning the npm cache and deleting node_modules can usually fix it. The instructions for doing that are as such:

  • Clean npm cache with npm cache clean --force
  • delete node_modules
  • delete package-lock.json (make sure you have a package.json!)
  • run npm install to reinstall packages from package.json

Сообщение

SyntaxError: expected expression, got "x"
SyntaxError: expected property name, got "x"
SyntaxError: expected target, got "x"
SyntaxError: expected rest argument name, got "x"
SyntaxError: expected closing parenthesis, got "x"
SyntaxError: expected '=>' after argument list, got "x"

Тип ошибки

Что пошло не так?

Вместо определённой конструкции языка было использовано что-то другое. Возможно, просто опечатка.

Примеры

Ожидаемое выражение

Недопустимыми являются, к примеру, запятые после элементов цепочки выражений.

for (let i = 0; i < 5,; ++i) {
  console.log(i);
}
// SyntaxError: expected expression, got ';'

Правильным вариантом будет убрать запятую или добавить ещё одно выражение:

for (let i = 0; i < 5; ++i) {
  console.log(i);
}

Недостаточно скобок

Иногда можно потерять скобки при использовании if:

function round(n, upperBound, lowerBound){
  if(n > upperBound) || (n < lowerBound){
    throw 'Число ' + String(n) + ' больше, чем ' + String(upperBound) + ', или меньше, чем ' + String(lowerBound);
  }else if(n < ((upperBound + lowerBound)/2)){
    return lowerBound;
  }else{
    return upperBound;
  }
} // SyntaxError: expected expression, got '||'

На первый взгляд кажется, что скобки расставлены правильно, но обратите внимание, что || находится не в скобках. Необходимо заключить || в скобки:

function round(n, upperBound, lowerBound){
  if((n > upperBound) || (n < lowerBound)){
    throw 'Число ' + String(n) + ' больше, чем ' + String(upperBound) + ', или меньше, чем ' + String(lowerBound);
  }else if(n < ((upperBound + lowerBound)/2)){
    return lowerBound;
  }else{
    return upperBound;
  }
}

Понравилась статья? Поделить с друзьями:
  • Disable error powershell
  • Discord error failed to initialize discord
  • Disable error c4996
  • Discord error codes
  • Disable display error php