Discord Bot not going online [duplicate] - javascript

This question already has answers here:
Why am I getting a ReferenceError: AbortController is not defined in Discord.js v13?
(3 answers)
Closed 1 year ago.
require("dotenv").config();
const { Client, Intents } = require("discord.js");
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
});
client.on("ready", () => {
console.log("bot is ready");
});
client.login(process.env.DISCORD_BOT_TOKEN).catch((e) => {
console.log(e);
});
OUTPUT
HTTPError [ReferenceError]: AbortController is not defined
at RequestHandler.execute (g:\goofy-translator\node_modules\discord.js\src\rest\RequestHandler.js:172:15)
at RequestHandler.execute (g:\goofy-translator\node_modules\discord.js\src\rest\RequestHandler.js:176:19)
at RequestHandler.push (g:\goofy-translator\node_modules\discord.js\src\rest\RequestHandler.js:50:25)
at async WebSocketManager.connect (g:\goofy-translator\node_modules\discord.js\src\client\websocket\WebSocketManager.js:128:9)
at async Client.login (g:\goofy-translator\node_modules\discord.js\src\client\Client.js:245:7) {
code: 500,
method: 'get',
path: '/gateway/bot',
requestData: { json: undefined, files: [] }
}
The error is caused by client.login() method.Already triple checked the bot token and all seems fine. The problem isn't in the enviroment varible either, because also doesn't work when I pass the token directly.
[Resolved]
The problem was the node version, discord.js requires v16 min

Since version 13 of Discord.js, the library requires that you use a more recent Node.js version. According to the docs, you need to use Node.js version v16.6.0 or higher.
For more information about how to change your node version, or use multiple node versions, see NVM for Windows or NVM for Linux depending on your OS.

Related

Problem with Intents updating discord.js version 14 [duplicate]

This question already has answers here:
Discord.js v13 code breaks when upgrading to v14
(1 answer)
Discord.Js: TypeError: Cannot read properties of undefined (reading 'FLAGS')
(1 answer)
Discord.js reads Intents as undefined
(2 answers)
Closed 14 days ago.
i am having a problem when i want to update to discord.js version 14 this is my discord.js client code
const { Client, GatewayIntentBits } = require('discord.js')
const client = new Client({
intents: [
GatewayIntentBits.FLAGS.GUILDS,
GatewayIntentBits.FLAGS.GUILD_MEMBERS,
GatewayIntentBits.FLAGS.GUILD_BANS,
GatewayIntentBits.FLAGS.GUILD_INTEGRATIONS,
GatewayIntentBits.FLAGS.GUILD_WEBHOOKS,
GatewayIntentBits.FLAGS.GUILD_INVITES,
GatewayIntentBits.FLAGS.GUILD_VOICE_STATES,
GatewayIntentBits.FLAGS.GUILD_PRESENCES,
GatewayIntentBits.FLAGS.GUILD_MESSAGES,
GatewayIntentBits.FLAGS.GUILD_MESSAGE_REACTIONS,
GatewayIntentBits.FLAGS.GUILD_MESSAGE_TYPING,
GatewayIntentBits.FLAGS.DIRECT_MESSAGES,
GatewayIntentBits.FLAGS.DIRECT_MESSAGE_REACTIONS,
GatewayIntentBits.FLAGS.DIRECT_MESSAGE_TYPING,
],
partials: ["CHANNEL", "GUILD_MEMBER", "MESSAGE", "REACTION", "USER"],
allowedMentions: {
parse: ['users', 'roles'],
repliedUser: false
}
});
client.setMaxListeners(0)
module.exports = client;
the error i get on console
GatewayIntentBits.FLAGS.GUILDS,
^
TypeError: Cannot read properties of undefined (reading 'GUILDS')
i had discord version 13 and i updated the client but i still get a error on flags.guilds.
As your error already states, FLAGS is not a property of GatewayIntentBits
You can find the official documentation of braking changes here
So according to the official docs, GatewayIntentBits.FLAGS.GUILDS should be GatewayIntentBits.Guilds

Why am I getting a timeout error when exporting a mariadb connection pool in Node.js?

EDIT
I found the error. The mistake was very obvious: I did not include the
require("dotenv").config(); in the connection.js file. Without this, the database connection simply fails after a timeout because it does not have any connection details.
I found an update log from the Mariadb Node.js connector team stating they have a few errors where Mariadb does not provide sufficient error messages (it sometimes only offers a "timeout" without further information), so I changed what I was looking for, and found the mistake.
For anyone getting a similar error message, this can mean anything, so check all parts of your code!
Original Post
I am trying to get familiar with Nodejs and express, but ran into an issue that I can't seem to solve:
When creating a Mariadb database pool in a seperate file, and exporting the pool using module.exports, I am having trouble using the same pool in another file. I get a timeout error when trying to use the pool to query a database.
If I use the exact same code in the same file instead of two separate files, the query works perfectly, so I think there is something going wrong during module.exports = pool.
Am I missing something? Thanks in advance!
I have two files:
index.js:
// import express web framework
const express = require("express");
//create an express application
const app = express();
const pool = require('./database/connection')
const cors = require('cors');
//middleware
app.use(cors())
app.use(express.json())
getData = async () => {
data = await pool.query("call stored_procedure")
console.log (data)
}
getData()
app.listen(3001, () => {
console.log('Serving running on port 3001')
})
and connection.js:
//import mariadb library
const mariadb = require("mariadb")
//function that create mariadb connection pool for database
const createPool = () => {
try {
return (
mariadb.createPool({
connectionLimit: 10,
host: process.env.MARIADB_HOST,
user: process.env.MARIADB_USER,
password: process.env.MARIADB_PASSWORD,
database: process.env.MARIADB_DB,
port: 3306
})
)
}
catch (err) {
console.error('Failed to connect to database: ')
console.error(err)
}
}
const pool = createPool()
//export database connection pool
module.exports = pool
Running this app results in the following error (after some time):
path_to_dir/node_modules/mariadb/lib/misc/errors.js:57
return new SqlError(msg, sql, fatal, info, sqlState, errno, additionalStack, addHeader);
^
SqlError: (conn=-1, no: 45028, SQLState: HY000) retrieve connection from pool timeout after 10001ms
(pool connections: active=0 idle=0 limit=10)
at Object.module.exports.createError (path_to_dir/node_modules/mariadb/lib/misc/errors.js:57:10)
at Pool._requestTimeoutHandler (path_to_dir/node_modules/mariadb/lib/pool.js:345:26)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7) {
text: 'retrieve connection from pool timeout after 10001ms\n' +
' (pool connections: active=0 idle=0 limit=10)',
sql: null,
fatal: false,
errno: 45028,
sqlState: 'HY000',
code: 'ER_GET_CONNECTION_TIMEOUT'
}
I found the error. The mistake was very obvious: I did not include the require("dotenv").config(); in the connection.js file. Without this, the database connection simply fails after a timeout because it does not have any connection details. I found an update log from the Mariadb Node.js connector team stating they have a few errors where Mariadb does not provide sufficient error messages (it sometimes only offers a "timeout" without further information), so I changed what I was looking for, and found the mistake.
For anyone getting a similar error message, this can mean anything, so check all parts of your code!

Discord Bot - Cannot access FLAGS from Intents

I started coding personal bot. I'm getting an error
TypeError: Cannot read properties of undefined (reading 'FLAGS')
I'm assuming it can't access FLAGS. I don't understand why because I have installed the latest node and discord.js. I allowed all premission for 'Privileged Gateway Intents' for my Bot on my personal account on Discord Developer Portal. I followed this tutorial: https://www.youtube.com/watch?v=Qc9uPgGmQ7I
This is my code so far:
require("dotenv").config();
const { Client, Intents } = require("discord.js")
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES
]
});
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("interactionCreate", async interaction => {
if (!interaction.isCommand()) return;
if (interaction.commandName === "ping") {
await interaction.reply("Pong!");
}
});
client.login(process.env.SPELL_BOT_TOKEN)
It means you are using Discord.js v11 or older, where intents weren't there so to update it to v12 or newer you can:
Reinstall the module with npm uninstall discord.js and npm install discord.js.
Update it to the latest version with npm install discord.js#dev or a specific one with npm install discord.js#13.3.1.
Edit the version of the module in your package.json file.
the first mistake I see is that you have to pass object to Client class, you did new Client(intents: [...]}). should be like new Client({ intents: [...] })

Discord Bug Error Invalid Token in discord.js

So I want to create a bot discord for fun in JavaScript using discord.js.
I wrote this code:
const Discord = require("discord.js")
const client = new Discord.client()
client.once('ready',() => {
console.log("Ready !");
});
client.login('token');
But when I'm trying to run it, I get this error:
/home/runner/MelodicPlainApplicationprogrammer/node_modules/discord.js/src/rest/RESTManager.js:32
const token = this.client.token ?? this.client.accessToken;
^
SyntaxError: Unexpected token '?'
This is on repl.it, and when I'm in VSCode, it works.
Why?
You are using Discord.js v13 and Discord.js13 requires node.js v16 to work.
Replit.com uses node.js v12 by default so you will need to set up node16 manually.
First, create a node.js repl
Next, run npm install node#16 in shell
After that you need to create a file called .replit
Inside the .replit file, add run = "npx node index.js". If your main file has a different name change index.js to your main file's name.
Now when you click run, replit uses node.js v16 instead of v12
Now for the problems with your code:
const Discord = require("discord.js")
const client = new Discord.client()
client.once('ready',() => {
console.log("Ready !");
});
client.login('token');
In the second line, const client = new Discord.client(), the c in Discord.client has to be capital, so write const client = new Discord.Client()
Now you need to add gateway intents so that your bot receives events. This is required in discord.js13 (Here's a list of gateway intents)
So change const client = new Discord.Client()
to const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] }) (You can add more intents if you want, these are just the basic ones)
You will also need to get your bot token and replace "token" in client.login('token'); with your bot token. Check this to see how to get your token.
Final code:
const Discord = require("discord.js")
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] })
client.once('ready',() => {
console.log("Ready !");
});
client.login(enter your token here);
Most likely repl.it is running Node 12 or earlier. The error is saying that the operator ?? is a syntax error, meaning that it does not recognize the nullish coalescing operator. It is supported from Node 14.0.0 and later.
Try upgrading your node.js version (go to shell, next to console):
$ npm install node#16
Or you can downgrade your discord.js version to v12.5.3 in your json file, because v12 has way more tutorials than v13 at the moment.
The choice is upto you, you can upgrade your node.js version or downgrade your discord.js version

my discord.js bot doesn't reply to a user message even if there isn't any error [duplicate]

This question already has answers here:
message event listener not working properly
(2 answers)
Closed 1 year ago.
my discord.js bot has version 13.1.0, and my node's version is 16.7.0. I entered these commands in the terminal : npm init to create package.json and npm install discord.js to install discord package.
I writed the code in index.js, and I created config.json to put the token there.
When I run then the code it shows me 'Ready!' in the console and being online in Discord. I also can change the status and the activity of the bot without a problem. The problem here is the bot doesn't send or reply to a message.
Here's the code bellow
const { Client, Intents } = require('discord.js');
const { token } = require('./config.json');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
client.once('ready', () => {
console.log('Ready!');
});
client.on ('messageCreate', (message) => {
if (message.content === 'hello') {
message.reply('Hello')
};
});
client.login(token);
this's config.json's code just in case.
{
"token": "my_bot_token!"
}
The issue is caused by missing intents. To listen to messages, you need to specify the GUILD_MESSAGES flag:
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });

Categories

Resources