Cannot read properties of undefined 'on' - discord.js

It gives me this error with the following code
TypeError: Cannot read properties of undefined (reading 'on')
at C:\Users\mihai\Desktop\Eli_4.0.0\handlers\loadSlashCommands.js:21:34
at Array.forEach ()
at module.exports (C:\Users\mihai\Desktop\Eli_4.0.0\handlers\loadSlashCommands.js:11:37)
at Array.forEach ()
at new MainClient (C:\Users\mihai\Desktop\Eli_4.0.0\nanospace.js:68:88)
at Object. (C:\Users\mihai\Desktop\Eli_4.0.0\index.js:2:16)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
const { readdirSync } = require('fs');
const { PermissionsBitField, Routes } = require('discord.js');
const { REST } = require('#discordjs/rest');
const delay = require('delay');
const chalk = require("chalk");
module.exports = async (client, message) => {
const data = [];
let count = 0;
readdirSync("./slashCommands/").forEach((dir) => {
const slashCommandFile = readdirSync(`./slashCommands/${dir}/`).filter((files) => files.endsWith(".js"));
for (const file of slashCommandFile) {
const slashCommand = require(`../slashCommands/${dir}/${file}`);
if (!slashCommand.name) return console.error(`slashCommandNameError: ${slashCommand.split(".")[0]} application command name is required.`);
if (!slashCommand.description) return console.error(`slashCommandDescriptionError: ${slashCommand.split(".")[0]} application command description is required.`);
client.slashCommands.set(slashCommand.name, slashCommand);
data.push({
name: slashCommand.name,
description: slashCommand.description,
type: slashCommand.type,
options: slashCommand.options ? slashCommand.options : null,
default_member_permissions: slashCommand.default_member_permissions ? PermissionsBitField.resolve(slashCommand.default_member_permissions).toString() : null
});
count++;
}
});
client.logger.log(`Client SlashCommands Command (/) Loaded: ${count}`, "cmd");
const rest = new REST({ version: '10' }).setToken(client ? client.config.token : process.env.TOKEN);
(async () => {
try {
client.logger.log('Started refreshing application (/) commands.', 'cmd');
await rest.put(Routes.applicationCommands(client ? client.config.clientID : process.env. CLIENT_ID), { body: data });
client.logger.log('Successfully reloaded application (/) commands.', 'cmd');
} catch (error) {
console.error(error);
}
})();
await delay(4000);
console.log(chalk.white('[') + chalk.green('INFORMATION') + chalk.white('] ') + chalk.green('Command Slash ') + chalk.white('Events') + chalk.green(' Loaded!'));
};

Related

Discord.js push slash commands

I recently started writing Discordbots and just can't seem to get anywhere pushing the slash commands. I already have a handler file (pushSlash.js) but for some reason the commands are never loaded or I get an error in the console (mostly simply this: chalk.blue is not a function). My bot also doesn't get the badge that it supports slash commands.
Can anyone help me further?
Here is my code (pushSlash.js):
module.exports = (client) => {
const fs = require('fs');
const { PermissionsBitField } = require('discord.js');
const { Routes } = require('discord-api-types/v9');
const { REST } = require('#discordjs/rest');
const AsciiTable = require('ascii-table');
const table = new AsciiTable().setHeading('Slash Commands', 'Stats').setBorder('|', '=', "0", "0");
const TOKEN = process.env.BOT_TOKEN;
const CLIENT_ID = process.env.CLIENT_ID;
const rest = new REST({ version: '9' }).setToken(TOKEN);
import( 'chalk').then(chalk => {
const slashCommands = [];
fs.readdirSync('/home/container/src/slashCommands/').forEach(async dir => {
const files = fs.readdirSync(`/home/container/src/slashCommands/${dir}/`).filter(file => file.endsWith('.js'));
for(const file of files) {
const slashCommand = require(`/home/container/src/slashCommands/${dir}/${file}`);
slashCommands.push({
name: slashCommand.name,
description: slashCommand.description,
options: slashCommand.options ? slashCommand.options : null,
default_permission: slashCommand.default_permission ? slashCommand.default_permission : null,
default_member_permissions: slashCommand.default_member_permissions ? PermissionsBitField.resolve(slashCommand.default_member_permissions).toString() : null
});
if(slashCommand.name) {
client.slashCommands.set(slashCommand.name, slashCommand);
table.addRow(file.split('.js')[0], '✅');
} else {
table.addRow(file.split('.js')[0], '⛔');
}
}
});
console.log(chalk.blue(table.toString()));
(async () => {
try {
await rest.put(
process.env.GUILD_ID ?
Routes.applicationGuildCommands(CLIENT_ID, process.env.GUILD_ID) :
Routes.applicationCommands(CLIENT_ID),
{ body: slashCommands }
);
console.log(chalk.green('Successfully registered application commands.'));
} catch (error) {
console.log(error);
}
})();
});
};
I've already tried everything possible, but since I'm relatively new to discord.js, I don't know that much yet either.
Actually everything should work and exactly 2 different commands should be loaded, but I only get error messages or the handler was loaded on console but nothing is displayed on Discord.
first download chalk#4.1.2 with
npm install chalk#4.1.2
and import chalk normally.
const chalk = require('chalk')
There your code modified version:
module.exports = (client) => {
const fs = require('fs');
const { PermissionsBitField } = require('discord.js');
const { Routes } = require('discord-api-types/v9');
const { REST } = require('#discordjs/rest');
const AsciiTable = require('ascii-table');
const table = new AsciiTable().setHeading('Slash Commands', 'Stats').setBorder('|', '=', "0", "0");
const TOKEN = process.env.BOT_TOKEN;
const CLIENT_ID = process.env.CLIENT_ID;
const rest = new REST({ version: '9' }).setToken(TOKEN);
// Imported chalk normally
const chalk = require('chalk')
// removed `import( 'chalk').then(chalk => {})`
const slashCommands = [];
fs.readdirSync('/home/container/src/slashCommands/').forEach(async dir => {
const files = fs.readdirSync(`/home/container/src/slashCommands/${dir}/`).filter(file => file.endsWith('.js'));
for(const file of files) {
const slashCommand = require(`/home/container/src/slashCommands/${dir}/${file}`);
slashCommands.push({
name: slashCommand.name,
description: slashCommand.description,
options: slashCommand.options ? slashCommand.options : null,
default_permission: slashCommand.default_permission ? slashCommand.default_permission : null,
default_member_permissions: slashCommand.default_member_permissions ? PermissionsBitField.resolve(slashCommand.default_member_permissions).toString() : null
});
if(slashCommand.name) {
client.slashCommands.set(slashCommand.name, slashCommand);
table.addRow(file.split('.js')[0], '✅');
} else {
table.addRow(file.split('.js')[0], '⛔');
}
}
});
console.log(chalk.blue(table.toString()));
(async () => {
try {
await rest.put(
process.env.GUILD_ID ?
Routes.applicationGuildCommands(CLIENT_ID, process.env.GUILD_ID) :
Routes.applicationCommands(CLIENT_ID),
{ body: slashCommands }
);
console.log(chalk.green('Successfully registered application commands.'));
} catch (error) {
console.log(error);
}
})();
};

Web worker causes a gradual increase of memory usage! how to use transferable objects?

I am trying to create a web-worker logic into a react custom hook, but unfortunately i noticed
that memory usage is gradual increasing. After a research, i found out that in order to transfer large data between web-workers and main thread,a good practice is to use transferable objects. I tried to add transferable objects, but every time i get following errors:
// postMessage(arrayBuffer , '/', [arrayBuffer]) error:
Uncaught TypeError: Failed to execute 'postMessage' on 'DedicatedWorkerGlobalScope': Overload resolution failed.
// postMessage(arrayBuffer, [arrayBuffer]) error:
Uncaught DOMException: Failed to execute 'postMessage' on 'DedicatedWorkerGlobalScope': Value at index 0 does not have a transferable type.
Any ideas how I can solve that problem (any alternative solutions or any possible web worker improvements) and where the problem is?
.
web-worker main job:
connect to a mqtt client
subscribe to topics
listen to changes for every topic, store all values into a object and every 1 second
send stored topics data object to main thread (notice that data is large)
custom hook main job:
create a web-worker,
in every onmessage event, update redux store
// react custom hook code
import React, { useEffect, useRef } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { setMqttData } from 'store-actions';
const useMqttService = () => {
const dispatch = useDispatch();
const topics = useSelector(state => state.topics);
const workerRef = useRef<Worker>();
useEffect(() => {
workerRef.current = new Worker(new URL('../mqttWorker.worker.js', import.meta.url));
workerRef.current.postMessage({ type: 'CONNECT', host: 'ws://path ...' });
workerRef.current.onmessage = (event: MessageEvent): void => {
dispatch(setMqttData(JSON.parse(event.data)));
// dispatch(setMqttData(bufferToObj(event.data)));
};
return () => {
if (workerRef.current) workerRef.current.terminate();
};
}, [dispatch]);
useEffect(() => {
if (workerRef.current) {
workerRef.current.postMessage({ type: 'TOPICS_CHANGED', topics });
}
}, [topics ]);
return null;
};
// web-worker, mqttWorker.worker.js file code
import mqtt from 'mqtt';
export default class WorkerState {
constructor() {
this.client = null;
this.topics = [];
this.data = {};
this.shareDataTimeoutId = null;
}
tryConnect(host) {
if (host && !this.client) {
this.client = mqtt.connect(host, {});
}
this.client?.on('connect', () => {
this.data.mqttStatus = 'connected';
trySubscribe();
});
this.client?.on('message', (topic, message) => {
const value = JSON.parse(message.toString());
this.data = { ...this.data, [topic]: value };
});
}
trySubscribe() {
if (this.topics.length > 0) {
this.client?.subscribe(this.topics, { qos: 0 }, err => {
if (!err) {
this.tryShareData();
}
});
}
}
tryShareData() {
clearTimeout(this.shareDataTimeoutId);
if (this.client && this.topics.length > 0) {
postMessage(JSON.stringify(this.data));
// Attemp 1, error:
// Uncaught TypeError: Failed to execute 'postMessage' on
// 'DedicatedWorkerGlobalScope': Overload resolution failed.
// const arrayBuffer = objToBuffer(this.data);
// postMessage(arrayBuffer , '/', [arrayBuffer]);
// Attemp 2, error:
// Uncaught DOMException: Failed to execute 'postMessage' on
// 'DedicatedWorkerGlobalScope': Value at index 0 does not have a transferable type.
// const arrayBuffer = objToBuffer(this.data);
// postMessage(arrayBuffer, [arrayBuffer]);
this.shareDataTimeoutId = setTimeout(() => {
this.tryShareData();
}, 1000);
}
}
onmessage = (data) => {
const { type, host = '', topics = [] } = data;
if (type === 'CONNECT_MQTT') {
this.tryConnect(host);
} else if (type === 'TOPICS_CHANGED') {
this.topics = topics;
this.trySubscribe();
}
};
}
const workerState = new WorkerState();
self.onmessage = (event) => {
workerState.onmessage(event.data);
};
// tranform functions
function objToBuffer(obj) {
const jsonString = JSON.stringify(obj);
return Buffer.from(jsonString);
}
function bufferToObj(buffer) {
const jsonString = Buffer.from(buffer).toString();
return JSON.parse(jsonString);
}
i update tranform functions
function objToBuffer(obj){
// const jsonString = JSON.stringify(obj);
// return Buffer.from(jsonString);
const jsonString = JSON.stringify(obj);
const uint8_array = new TextEncoder().encode(jsonString);
const array_buffer = uint8_array.buffer;
return array_buffer;
}
function bufferToObj(array_buffer) {
// const jsonString = Buffer.from(array_buffer).toString();
// return JSON.parse(jsonString);
const decoder = new TextDecoder('utf-8');
const view = new DataView(array_buffer, 0, array_buffer.byteLength);
const string = decoder.decode(view);
const object = JSON.parse(string);
return object;
}
in web-worker file add
const arrayBuffer = objToBuffer(this.data);
postMessage(arrayBuffer, [arrayBuffer]);
finally in custom hook add in onmessage
dispatch(setMqttData(bufferToObj(event.data)));

How to read file with async/await?

const Discord = require('discord.js');
const { MessageEmbed } = require('discord.js');
const fs = require('fs');
module.exports = {
name: 'prefix',
aliases: ['setprefix'],
description: 'Установить новый префикс на вашем сервере',
execute(message, args) {
if (!message.member.hasPermission('MANAGE_SERVER'))
return message.reply(' Не не не.');
if (!args[0] || args[0 == 'help'])
return message.reply(`Использование: prefix <Тут ваш префикс> `);
let prefixes = JSON.parse(fs.readFileSync('./prefixes.json', 'utf8'));
prefixes[message.guild.id] = {
prefix: args[0]
};
fs.writeFile('./prefixes.json', JSON.stringify(prefixes), (err) => {
if (err) console.log(err)
})
let pEmbed = new MessageEmbed()
.setColor('#000001')
.setTitle('Префикс изменён!')
.setDescription(`Новый префикс на сервере **${args[0]}**`)
message.channel.send(pEmbed)
message.delete({ timeout: 10000 })
}}
let prefixes = JSON.parse(fs.readFileSync('./prefixes.json', 'utf8'));
if (!prefixes[message.guild.id]) {
prefixes[message.guild.id] = {
prefix: config.prefix
};
}
let prefix = prefixes[message.guild.id].prefix;
if i'm change prefix, bot stopping music.
Tried to do it via ' ReadFile`, it returns me a callback error
I know I could use readFileSync, but if I do, I know I'll never understand async/await and I'll just bury the issue.
UPD:
client.on('message', async (message) => {
if (message.author.bot) return;
if (!message.guild) return;
let prefixes = JSON.parse(fs.readFileSync('./prefixes.json', 'utf8'));
if (!prefixes[message.guild.id]) {
prefixes[message.guild.id] = {
prefix: config.prefix
};
}
let prefix = prefixes[message.guild.id].prefix;
// let msgArray = message.content.split(" ");
// let cmd = msgArray[0];
// if(cmd.slice(0, prefix.length) !== prefix) return;
// let args = msgArray.slice(1);
// let cmdFile = client.commands.get(cmd.slice(prefix.length))
// if(cmdFile) cmdFile.run(client, message, args);
const prefixRegex = new RegExp(`^(<#!?${client.user.id}>|${escapeRegex(prefix)})\\s*`);
if (!prefixRegex.test(message.content)) return;
const [matchedPrefix] = message.content.match(prefixRegex);
const args = message.content.slice(matchedPrefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command =
client.commands.get(commandName) ||
client.commands.find((cmd) => cmd.aliases && cmd.aliases.includes(commandName));
if (message.content.startsWith(prefix) && commandFiles) {
if (message.deletable) {
try {
await message.delete();
} catch(e) {
console.error(e);
}
}
}
if (!command) return;
if (!cooldowns.has(command.name)) {
cooldowns.set(command.name, new Collection());
}
const now = Date.now();
const timestamps = cooldowns.set(command.name);
const cooldownAmount = (command.cooldown || 1) * 1000;
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return message.reply(
`Пожалуйста подождите ${timeLeft.toFixed(1)} секунд перед повторным использованием \`${command.name}\` команд.`
);
}
}
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('Произошла ошибка при выполнении этой команды.')
.then(message => message.delete({ timeout: 5000 }))
.catch(console.error);
}
});
fs doesn't offer the possibility to give the Promise of a file, but it can read a file asynchronously with a callback instead of a promise. But in the fs module, you can use fs/promises (aka fs.promises). Here's the same code. I corrected 1 problem, added the fsp var (fs promises), and used it to read your prefixes.json file. fs.readFileSync is totally fine though.
const Discord = require("discord.js");
const { MessageEmbed } = require("discord.js");
const fs = require("fs");
const fsp = fs.promises; // ++
module.exports = {
name: "prefix",
aliases: ["setprefix"],
description: "Установить новый префикс на вашем сервере",
async execute(message, args) {
if (!message.member.hasPermission("MANAGE_SERVER"))
return message.reply(" Не не не.");
if (!args[0] || args[0] == "help") /** Correction */
return message.reply(`Использование: prefix <Тут ваш префикс> `);
let prefixes = JSON.parse(await fsp.readFile("prefixes.json", "utf8")); // Using fsp
prefixes[message.guild.id] = {
prefix: args[0],
};
fs.writeFile("./prefixes.json", JSON.stringify(prefixes), (err) =>
err ? console.error(err) : null
);
let pEmbed = new MessageEmbed()
.setColor("#000001")
.setTitle("Префикс изменён!")
.setDescription(`Новый префикс на сервере **${args[0]}**`);
message.channel.send(pEmbed);
message.delete({ timeout: 10000 });
},
};

a problem with bot.login(token). what to do?

I am new to coding in Discord.js and I have a problem. writes to me the error is the line that contains bot.login(token)
Could you tell me my mistake and explain how to fix it? thank you in advance.
writes to me: bot.login(token);
^
ReferenceError: bot is not defined
at Object. (C:\Users\пользователь\Desktop\FNaFRP-bot3.0\index.js:7:1)
[90m at Module._compile (internal/modules/cjs/loader.js:1138:30)[39m
[90m at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)[39m
[90m at Module.load (internal/modules/cjs/loader.js:986:32)[39m
[90m at Function.Module._load (internal/modules/cjs/loader.js:879:14)[39m
[90m at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)[39m
[90m at internal/main/run_main_module.js:17:47[39m
here is the code itself
const client = new Discord.Client();
const { token } = require ("./config.json")
const prefix = '?'
const noperms = 'I dont think you have premission to do that!'
const norole = 'I dont think you have the right role to do that!'
bot.login(token);
bot.on('reddy', messgae => {
console.log(`${bot.user.username} is succefully on! in ${bot.guilds.size} Servers and in ${bot.channels.size} channels.`)
})
bot.on('message', function(message){
if (message.mentions.users.first() --- bot.user) {
message.channel.send('My prefix is \'?\'')
}
})
bot.on('message', message => {
let args = message.content.substring(prefix.length).split(" ");
switch(args[0]){
case 'help' :
if(!message.member.roles.find(r => r.name === 'Test Role')) return message.channel.send(norole)
message.channels.send('My prefux is \'?\' ').then(msg => {
msg.react('✅')
})
}
})
bot.on('message', message=>{
let args = message.content.substring(prefix.length).split(" ");
switch(args[0]){
case 'clear' :
message.delete();
if(!message.nomber.hasPermission("ADMINISTRATOR")) return message.channel.send(noperms)
if(!args[1]) return message.channel.send('Please provide a number.')
message.channel.bulkDelete(args[1]).then ;{
message.channel.send('- Succefully Deleted').then(msg => {
msg.react("✅")
})
console.log(`${message.author.username} deleted ${args[1]} messages in ${message.channel.name}`)
}
}
})```
your client is client and not bot you could either change the
const client = new Discord.Client(); to const bot = new Discord.Client(); or replace all the bot. with client.
EDIT: Fixed other Errors in the Code
const Discord = require("discord.js");
const bot = new Discord.Client();
const { token } = require ("./config.json")
const prefix = '?'
const noperms = 'I dont think you have premission to do that!'
const norole = 'I dont think you have the right role to do that!'
bot.login(token);
bot.on('ready', () => {
console.log(`${bot.user.username} is succefully on! in ${bot.guilds.cache.size} Servers and in ${bot.channels.cache.size} channels.`)
})
bot.on('message', message => {
if (message.mentions.users.first() == bot.user) {
message.channel.send('My prefix is \'?\'');
}
let args = message.content.substring(prefix.length).split(" ");
switch(args[0]){
case 'help' :
tr = message.member.roles.cache.find(role => role.name === 'Test Role').id;
if(!message.member.roles.cache.has(tr)) return message.channel.send(norole);
return message.channel.send('My prefix is \'?\' ').then(msg => {
msg.react('✅')});
case 'clear' :
message.delete();
if(!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send(noperms)
if(!args[1]) return message.channel.send('Please provide a number.')
message.channel.bulkDelete(args[1]).then ;{
message.channel.send('- Succefully Deleted').then(msg => {
msg.react("✅")
})
console.log(`${message.author.username} deleted ${args[1]} messages in ${message.channel.name}`)
}
}
})
move bot.login(token); to the bottom of your code
you can't login untill your code is all down
const Discord = require("discord.js");
const bot = new Discord.Client();
const { token } = require ("./config.json")
const prefix = '?'
// other code
bot.login(token);

TypeError: Cannot read property 'forEach' of undefined discord.js

I'm having this issue: TypeError: Cannot read property 'forEach' of undefined on my discord bot after adding aliases. It worked before I added aliases to it so I'm assuming the problem is somewhere around there. I can't seem to find where the problem is originating from so any help would be appreciated!
code:
const botconfig = require("./botconfig.json");
const Discord = require("discord.js");
const fs = require("fs");
const bot = new Discord.Client({disableEveryone: true});
bot.commands = new Discord.Collection();
bot.aliases = new Discord.Collection();
let profile = require("./profiles.json");
fs.readdir("./commands/", (err, files) => {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if(jsfile.length <= 0){
console.log("Couldn't find commands");
return;
};
jsfile.forEach((f, i) => {
let props = require(`./commands/${f}`);
console.log(`${f} loaded!`);
bot.commands.set(props.help.name, props);
props.help.aliases.forEach(alias => {
bot.aliases.set(alias, props.help.name);
});
});
});
bot.on("ready", async () => {
console.log(`${bot.user.username} is online`);
bot.user.setActivity("$ Made by xkillerx15");
});
bot.on("message", async message => {
if(message.author.bot) return;
if(message.channel.type === "dm") return;
let prefix = botconfig.prefix;
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = messageArray.slice(1);
let commandfile = bot.commands.get(cmd.slice(prefix.length)) || bot.commands.get(cmd.slice(prefix.length));
if(commandfile) commandfile.run(bot,message,args);
if(!profile[message.author.id]){
profile[message.author.id] = {
coins: 0
};
}
let coinAmt = Math.floor(Math.random() * 15) + 1;
let baseAmt = Math.floor(Math.random() * 15) + 1;
if(coinAmt === baseAmt){
profile[message.author.id] = {
coins: profile[message.author.id].coins + coinAmt
};
fs.writeFile("./profiles.json", JSON.stringify(profile), (err) => {
if(err) console.log(err)
});
}
});
bot.login(botconfig.token);
exact error:
TypeError: Cannot read property 'forEach' of undefined
at jsfile.forEach (C:\Users\Jordy\Desktop\jbot\index.js:23:28)
at Array.forEach (<anonymous>)
at fs.readdir (C:\Users\Jordy\Desktop\jbot\index.js:19:12)
at FSReqWrap.args [as oncomplete] (fs.js:140:20)
your problem is that aliases is undefined which means is not an object so you can't use forEach
there is one possibility:
commands file should contains aliases inside help object.
so it should something like this
exports.help = {
aliases:[...props]
}

Resources