I've been trying to get my bot to come online for hours but I keep getting the same error.
Here's the error:
Error: Cannot find module './commands/${f}1'
Require stack:
- C:\Users\Apskaita\Desktop\Viper bot\main.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:965:15)
at Function.Module._load (internal/modules/cjs/loader.js:841:27)
at Module.require (internal/modules/cjs/loader.js:1025:19)
at require (internal/modules/cjs/helpers.js:72:18)
at C:\Users\Apskaita\Desktop\Viper bot\main.js:20:22
at Array.forEach (<anonymous>)
at C:\Users\Apskaita\Desktop\Viper bot\main.js:19:12
at FSReqCallback.oncomplete (fs.js:156:23) {
code: 'MODULE_NOT_FOUND',
requireStack: [ 'C:\\Users\\Apskaita\\Desktop\\Viper bot\\main.js' ]
}
Here's my code for my main.js:
const Discord = require('discord.js');
const client = new Discord.Client();
const botconfig = require('./botconfig.json');
const fs = require("fs");
client.commands = new Discord.Collection();
client.alieses = new Discord.Collection();
// READ COMMANDS FOLDER
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("couldin't file any commands!");
return;
}
jsfile.forEach((f) => {
let preops = require("./commands/${f}1")
console.log('${f} loaded!');
bot.commands.set(props.help.name, props);
props.help.aliases.forEach(alias => {
bot.aliases.set(alias, props.help.name);
})
})
})
// BOT ONLINE MESSAGE AND ACTIVITY MESSAGE
client.on('ready', async () => {
console.log('${bot.user.username} is online on ${bot.guilds.size} servers!')
bot.user.setActivity('with ${bot.guilds.size} servers!');
})
client.on('message', async message => {
// CHECK CHANNEL TYPE
if(message.channel.type === "dm") return;
if(message.author.bot) return;
// SET PREFIX
let prefix = botconfig.prefix;
// CHECK PREFIX, DEFINE ARGS & COMMAND
if(message.content.startsWith(prefix)) return;
let args = message.content.slice(prefix.length).trim().split(/ +/g);
let cmd;
cmd = args.shift().toLowerCase();
let command;
let commandfile = bot.commands.get(cmd.slice(prefix.length));
if(commandfile) commandfile.run(bot, message, args);
//RUN COMMANDS
if(bot.commands.has(cmd)) {
command = bot.commands.get(cmd);
} else if (bot.aliases.has(cmd)) {
command = bot.commands.get(bot.aliases.get(cmd));
}
try {
command.run(bot, message, args);
} catch (e) {
return;
}
client.login(botconfig.token)})
My ping.js:
module.exports.run = async (bot, message, args) => {
const m = await message.channel.send("ping!");
m.edit("Pong! ${m.createTimestamp - message.createdTimestamp}ms");
}
module.exports.help = {
name: "",
aliases: ["p"]
}
These errors are very confusing and I don't really know how to fix them so please can someone fix them?
I am very new to JavaScript so I don't have a clue what I'm typing... I copied the code from a tutorial so I don't what's going on.
You're not using the correct quotes, you're using " instead of `
Replace
jsfile.forEach((f) => {
let preops = require("./commands/${f}1")
console.log('${f} loaded!');
bot.commands.set(props.help.name, props);
props.help.aliases.forEach(alias => {
bot.aliases.set(alias, props.help.name);
})
})
By
jsfile.forEach((f) => {
let preops = require(`./commands/${f}1`)
console.log(`${f} loaded!`);
bot.commands.set(props.help.name, props);
props.help.aliases.forEach(alias => {
bot.aliases.set(alias, props.help.name);
})
})
It means that the path is incorrect. First of all, be sure to use good quotes as someone said before. Then, are you sure that there is a 1 at the end of your files' names ? It is what you ask ${f}1.
Related
hello all, is my script of discord bot
It's is my script JavaScrypt
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();
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 on ${bot.guilds.size} servers!`);
bot.user.setActivity(`In Development`);
bot.user.setStatus('online');
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 args = message.content.slice(prefix.length).trim().split(/ +/g);
let cmd = args.shift().toLowerCase();
let commandfile;
if (bot.commands.has(cmd)) {
commandfile = bot.commands.get(cmd);
} else if (bot.aliases.has(cmd)) {
commandfile = bot.commands.get(bot.aliases.get(cmd));
}
if (!message.content.startsWith(prefix)) return;
try {
commandfile.run(bot, message, args);
} catch (e) {
}}
)})
bot.login("MTAwNzkyMDIyMDIyNjIwNzc2NQ.GldCmn.1jWZEr1ALjADcZvbAnDHkrhpy6OBlzpjcFMw8w");
my error:
throw new TypeError(ErrorCodes.ClientMissingIntents);
^
TypeError [ClientMissingIntents]: Valid intents must be provided for the Client.
at Client._validateOptions (C:\Users\4bino\node_modules\discord.js\src\client\Client.js:480:13)
at new Client (C:\Users\4bino\node_modules\discord.js\src\client\Client.js:78:10)
at Object.<anonymous> (C:\Users\4bino\OneDrive\Рабочий стол\economybot-master\index.js:4:13)
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)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47 {
code: 'ClientMissingIntents'
}
I do not understand what to do, please help with this problem
I'm trying to run this script for the discord bot
I tried to look for a solution to this problem in other resources, but I didn't find anything
I have already installed the discord package.js but it looks like he can't find some module
My Node version.js is v16.16.0
I tried to make a button in Discord.js. However, when I wrote the code, I found that there was an error during startup.
I don't know why this error is happening. I checked many related questions online, but none of my problems were solved, and I even became even more confused.
This is my code:
const config = require("./config.json");
const Discord = require('discord.js');
const bot = new Discord.Client();
require('discord-buttons')(client);
const fs = require("fs");
const client = new Discord.Client({disableEveryone: false});
const moment = require("moment");
const { MessageButton, MessageActionRow } = require('discord-buttons')
client.commands = new Discord.Collection();
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("XX");
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/${f}`);
client.commands.set(props.help.name, props);
});
});
client.on('message', async message => {
if(message.content === "buttonstest"){
const button = new MessageButton()
.setLabel("test")
.setStyle("green")
.setID("btn1")
var embed = new Discord.RichEmbed()
.setColor("#FFFFFF")
.setTitle("test")
message.channel.send(embed, button);
}
})
client.on("message", async message => {
if(message.author.bot) return;
if(message.channel.type === "dm") return;
let prefix = config.prefix;
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = messageArray.slice(1);
let commandfile = client.commands.get(cmd.slice(prefix.length));
if(commandfile) commandfile.run(client,message,args);
});
client.login(config.token)
This is the error message:
I have no name!#f7808405-1373-45ee-bac7-0059f94bd574:~$ /home/container/node_modules/discord.js-buttons/src/Classes/APIMessage.js:5
class sendAPICallback extends APIMessage {
^
TypeError: Class extends value undefined is not a constructor or null
at Object.<anonymous> (/home/container/node_modules/discord.js-buttons/src/Classes/APIMessage.js:5:31)
at Module._compile (internal/modules/cjs/loader.js:1068:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
at Module.load (internal/modules/cjs/loader.js:933:32)
at Function.Module._load (internal/modules/cjs/loader.js:774:14)
at Module.require (internal/modules/cjs/loader.js:957:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (/home/container/node_modules/discord.js-buttons/src/Classes/Message.js:3:20)
at Module._compile (internal/modules/cjs/loader.js:1068:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
In Discord.js v13, the API message class has been renamed to MessagePayload. APIMessage would therefore be undefined.
This error is occurring in the discord-buttons module. Discord.js v13 supports buttons so you do not need this module. See the Discord.js guide on buttons for more details.
To send a button, you could use this code:
client.on('message', async message => {
if(message.content === "buttonstest"){
const button = new Discord.MessageButton()
.setLabel("test")
.setStyle("SUCCESS")
.setCustomId("btn1");
// Note that RichEmbed was renamed to MessageEmbed in v12
const embed = new Discord.MessageEmbed()
.setColor("#FFFFFF")
.setTitle("test");
message.channel.send({
embeds: [embed],
components: [{components: [button]}]
// alternatively
// components: [new Discord.MessageActionRow([button])]
});
}
});
You should also take a look at the Discord.js v13 upgrade guide.
Whenever I try to use a function like client.users.cache.size or client.guilds.size, they keep giving me an error like "TypeError: Cannot read property 'guilds' of undefined" or "TypeError: Cannot read property 'cache' of undefined".
I was also trying to use let guilds = client.guilds.cache.array().join('\n') but it also throws the same error.
Command's code:
const Discord = require('discord.js');
module.exports = {
name: 'stats',
description: 'Views the bot\'s stats',
execute(client, message) {
const embed = new Discord.MessageEmbed
.setDescription(`In ${client.guilds.size} servers`)
.setTimestamp()
.setFooter(message.member.user.tag, message.author.avatarURL());
message.channel.send(embed)
}
}
Bot's main file:
const path = require('path');
const fs = require("fs");
const { token, prefix } = require('./config.json');
const Discord = require('discord.js');
const db = require ('quick.db');
const client = new Discord.Client
client.commands = new Discord.Collection();
const isDirectory = source => fs.lstatSync(source).isDirectory();
const getDirectories = source => fs.readdirSync(source).map(name => path.join(source, name)).filter(isDirectory);
getDirectories(__dirname + '/commands').forEach(category => {
const commandFiles = fs.readdirSync(category).filter(file => file.endsWith('.js'));
for(const file of commandFiles) {
const command = require(`${category}/${file}`);
client.commands.set(command.name, command);
}
});
client.on("ready", () => {
console.log(`ready!.`);
console.log(token);
// Activities
const activities_list = [
`Serving Tacos | .help`,
`Preparing Orders | .help`
];
setInterval(() => {
const index = Math.floor(Math.random() * (activities_list.length - 1) + 1);
client.user.setActivity(activities_list[index]);
}, 10000);
});
//Joined Guild
client.on("guildCreate", (guild) => {
const EmbedJoin = new Discord.MessageEmbed()
.setColor('#FFFF33')
.setTitle(`Joined Guild: ${guild.name}!`)
.setTimestamp()
console.log(`Joined New Guild: ${guild.name}`);
client.channels.cache.get(`746423099871985755`).send(EmbedJoin)
});
//Left Guild
client.on("guildDelete", (guild) => {
const EmbedLeave = new Discord.MessageEmbed()
.setColor('#FFFF33')
.setTitle(`Left Guild: ${guild.name}.`)
.setTimestamp()
console.log(`Left Guild: ${guild.name}`);
client.channels.cache.get(`746423099871985755`).send(EmbedLeave)
});
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.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 (!command) return;
if (command.guildOnly && message.channel.type === 'dm') {
return message.reply('I can\'t execute that command inside DMs!');
}
if (command.args && !args.length) {
let reply = `${message.author}, wrong usage`;
if (command.usage) {
reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
}
return message.channel.send(reply);
}
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
process.on("error", () => {
console.log("Oops something happened!");
});
client.login(token);
In your code, client.guilds returns a manager, so you have to use client.guilds.cache.size. The rest of the code works fine.
const Discord = require('discord.js');
module.exports = {
name: 'stats',
description: 'Views the bot\'s stats',
execute(message, args, client) {
const embed = new Discord.MessageEmbed
.setDescription(`In ${client.guilds.cache.size} servers`)
.setTimestamp()
.setFooter(message.member.user.tag, message.author.avatarURL());
message.channel.send(embed)
}
}
In your main bot file you're only passing the message and the args (in this order) to command.execute(). You can add the client too, and update the parameters in your command's code to match this order.
try {
command.execute(message, args, client);
} catch (error) {
...
}
I'm currently trying to get the bot to send a filler message to the channel I eventually want the suggestions to go to and have tried multiple methods to do so, but keep getting errors. I'm sure the solution is very simple, and any help is much appreciated.
suggest.js
module.exports = {
name: 'suggest',
aliases: ['suggestion'],
description: 'Sends a suggestion to the <#700591796119535657> channel.',
usage: '<your suggestion>',
cooldown: 1,
execute(message, args) {
const Discord = require('discord.js');
const client = new Discord.Client();
const channel = client.channels.cache.get('701087240729657457');
channel.send('test');
},
};
error message in console upon running .suggest
TypeError: Cannot read property 'send' of undefined
at Object.execute (/home/shares/public/RetroCraft/commands/suggest.js:11:11)
at Client.<anonymous> (/home/shares/public/RetroCraft/index.js:69:11)
at Client.emit (events.js:310:20)
at MessageCreateAction.handle (/home/shares/public/RetroCraft/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/home/shares/public/RetroCraft/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/home/shares/public/RetroCraft/node_modules/discord.js/src/client/websocket/WebSocketManager.js:386:31)
at WebSocketShard.onPacket (/home/shares/public/RetroCraft/node_modules/discord.js/src/client/websocket/WebSocketShard.js:436:22)
at WebSocketShard.onMessage (/home/shares/public/RetroCraft/node_modules/discord.js/src/client/websocket/WebSocketShard.js:293:10)
at WebSocket.onMessage (/home/shares/public/RetroCraft/node_modules/ws/lib/event-target.js:120:16)
at WebSocket.emit (events.js:310:20)
index.js
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const cooldowns = new Discord.Collection();
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}`);
// set a new item in the Collection
// with the key as the command name and the value as the exported module
client.commands.set(command.name, command);
}
client.once('ready', () => {
console.log('Ready!');
client.user.setActivity('RetroCraft', { type: 'WATCHING' });
});
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName)
|| client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return;
if (command.guildOnly && message.channel.type !== 'text') {
return message.reply('I can\'t execute that command inside DMs!');
}
if (command.args && !args.length) {
let reply = `You didn't provide any arguments, ${message.author}!`;
if (command.usage) {
reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
}
return message.channel.send(reply);
}
if (!cooldowns.has(command.name)) {
cooldowns.set(command.name, new Discord.Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command.name);
const cooldownAmount = (command.cooldown || 3) * 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(`please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${command.name}\` command.`);
}
}
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('there was an error trying to execute that command!');
}
});
client.login(token);
This is a really easy fix. Just change the channel.send to message.channel.send and that should work. Tell me if you get any errors and I'll try to help :)
Here is what it currently looks like:
const Discord = require("discord.js")
const client = new Discord.Client()
const fs = require("fs")
const ytdl = require("ytdl-core")
const config = require("./config.json")
fs.readdir("./events/", (err, files) => {
if (err) return console.error(err)
files.forEach(file => {
let eventFunction = require(`./events/${file}`)
let eventName = file.split(".")[0]
client.on(eventName, (...args) => eventFunction.run(client, ...args))
})
})
client.on("message", message => {
if (message.author.bot) return
if(message.content.indexOf(config.prefix) !== 0) return
const args = message.content.slice(config.prefix.length).trim().split(/ +/g)
const command = args.shift().toLowerCase()
try {
let commandFile = require(`./commands/${command}.js`)
commandFile.run(client, message, args)
} catch (err) {
console.error(err)
}
if(command === "test"){
let url = args[0]
ytdl(url, {filter:'audioonly', format:'mp3'}).pipe(fs.createWriteStream("audio.mp3"))
message.channel.sendFile("./audio.mp3")
}
});
client.login(config.token)
commands are stored in seperate files, but I write in the
if(command === "test")
for testing commands
Any help is appreciated, thanks
You're using Stream and it's asynchronous. To make it work you need to check is the file's writing process completed or not!
ytdl(url, {filter: 'audioonly', format: 'mp3'})
.pipe(fs.createWriteStream('audio.mp3'))
// End of writing
.on('end', () => {
message.sendFile('./audio.mp3');
});