here's my code:
//All of the constants
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./myconfig10.json');
const client = new Discord.Client();
const cheerio = require('cheerio');
const request = require('request');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
//Telling the bot where to look for the commands
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
let activities = [
'with ur dad',
'with ur mom',
]
const pickedActivity = Math.floor(Math.random() * (activities.length - 1) + 1)
//Once the bot is up and running, display 'Ready' in the console
client.once('ready', () => {
client.user.setPresence({
status: 'online',
activity: {
name: (pickedActivity),
type: 'STREAMING',
url: 'https://www.twitch.tv/monstercat'
}
})
console.log('Ready!');
//Seeing if the message starts with the prefix
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
//Telling the bot what arguments are
const args = message.content.slice(prefix.length).trim().split(/ +/)
const commandName = args.shift().toLowerCase();
//Checking to see if the command you sent is one of the commands in the commands folder
if (!client.commands.has(commandName)) return;
console.log(`Collected 1 Item, ${message}`)
const command = client.commands.get(commandName);
//Try to execute the command.
try {
command.execute(message, args);
//If there's an error, don't crash the bot.
} catch (error) {
console.error(error);
//Sends a message on discord telling you there was an error
message.reply('there was an error trying to execute that command!');
}})})
client.login(token);
but when i try this, i get the error:
UnhandledPromiseRejectionWarning: TypeError [INVALID_TYPE]: Supplied name is not a string.
I know this means that the name of the status needs to be a string, so how would I be able to make it a variable?
I'm pretty new to this so it would be appreciated if your answer was in simple enough terms.
Thanks!
I think this should do the trick. Replace:
const pickedActivity = Math.floor(Math.random() * (activities.length - 1) + 1)
with:
const pickedActivity = activities[Math.floor(Math.random() * activities.length)]
Related
So I recently started developing a discord bot using discord.js, and when I'm trying to run this command, it is raising an error when I update the bot at the line where I execute the command (client.commands.get('kick').execute(message, args);).
The error is:
TypeError: Cannot read properties of undefined (reading 'get'
at Client.<anonymous> (C:\Users\Shushan\Desktop\discordbot\main.js:18:25)
at Client.emit (node:events:527:28) )
And here are my code files:
main.js
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '?';
client.once('ready', () => {
console.log("Shushbot is online!");
})
client.on('message', message => {
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'kick') {
client.commands.get('kick').execute(message, args);
}
})
client.login('SECURITY TOKEN');
kick.js
module.exports = {
name: 'kick',
description: 'This Command Kicks People!',
execute(message, args) {
const member = message.mentions.users.first();
if(member) {
const memberTarget = message.guild.members.cache.get(member.id);
memberTarget.kick();
message.channel.send("This User Has Been Kicked From The Server.");
} else {
message.channel.send("This User Couldn't Be Kicked.");
}
}
}
I think you should check that : https://discordjs.guide/creating-your-bot/command-handling.html#reading-command-files
So far, your bot (client) don't know the commands method, and even if he knows, get dosent exists at all.
You have to write some code to create and set these commands, exemple from doc :
client.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
// 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.data.name, command);
}
You can do it that way or an other, but at this time your object is empty.
Even your client.commands is undefined !
const Discord = require('discord.js');
// fs
const fs = require('fs');
// path
const path = require('path');
// config
const config = require('./config.json');
// config.json
const token = config.token;
// config config.json
const PREFIX = config.prefix;
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: \[Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES\] })
client.commands = new Discord.Collection();
// message
client.on('message', message =\> {
// message not sent by bot
if (!message.author.bot) {
// if the message starts with the prefix
if (message.content.startsWith(PREFIX)) {
// split the message into an array
const args = message.content.slice(PREFIX.length).split(/ +/);
// command is the first element of the array
const command = args.shift().toLowerCase();
// ping command
if (command === 'ping') {
// send a message to the channel
message.channel.send('pong');
}
// success message after login
client.on('ready', () =\> {
console.log(`Logged in as ${client.user.tag}!`);
})
// token config file
client.login(config.token);
so I run node index.js it's supposed to shown Logged in as "my bot name here" on the VSC terminal and should be online on the discord, but it doesn't and I can't figure it out, mind anyone help
Formatting will save your life, Bro:
Also, I'd recommend less comments. It's a lot of noise. I refactored this stuff out. Look how much nicer your code looks:
const { token, prefix: PREFIX } = require('./config.json');
const { Collection, Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] })
client.commands = new Collection();
client.on('message', message => {
if (message.author.bot) return
if (!message.content.startsWith(PREFIX)) return
const args = message.content.slice(PREFIX.length).split(' ');
const command = args.shift().toLowerCase();
if (command === 'ping') {
message.channel.send('pong');
}
})
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
})
client.login(token);
My problem is the following: when compiling, I get the error that the property 'execute' is not defined. What I'm trying to do is open a file that is in another folder and dock it in the if, I was guided by the command handling documentation, I don't know if the error is in the other file which is called 'pong.js'. I recently started, so I don't fully understand it. The main code is as follows:
The Error error message
index.js file
const Discord = require('discord.js');
const client = new Discord.Client();
const keepAlive = require("./server")
const prefix = "!";
const fs = require('fs');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./src').filter(file => file.endsWith('.js'));
for (const file of commandFiles){
const command = require(`./src/${file}`);
client.commands.set(command.name, command);
}
// ======== Ready Log ========
client.on ("ready", () => {
console.log('The Bot Is Ready!');
client.user.setPresence({
status: 'ONLINE', // Can Be ONLINE, DND, IDLE, INVISBLE
activity: {
name: '!tsc help',
type: 'PLAYING', // Can Be WHATCHING, LISTENING
}
})
});
client.on('message', async message => {
if(!message.content.startsWith(prefix)) return;
let args = message.content.slice(prefix.length).split(" ");
let command = args.shift().toLowerCase()
if (command === "ping"){
client.commands.get('ping').execute(message, args)
}
})
const token = process.env.TOKEN;
keepAlive()
client.login(token);
pong.js file
module.exports.run = {
name: 'pong',
description: "pong cmd",
execute(message, args){
message.reply("pong!")
}
}
I am currently making a discord joke bot with discord.js. Upon startup, the bot works jut fine. One of the only two commands works just fine, but my joke command does not go so well. For my testing, I have it set up like this:
My main "bot.js" file:
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '*';
const fs = require('fs');
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);
}
client.once('ready', () => {
console.log('JokeBot is Online!');
console.log(`Logged in as ${client.user.tag}!`);
client.user.setPresence({
status: "online", //You can show online, idle....
});
});
client.on('message', message =>{
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command == 'pun'){
client.commands.get('pun').execute(message, args);
} else if (command == 'joke'){
client.commands.get('joke').execute(message, args);
}
});
client.login('NzY4MjcyOTE5NDQ0NDU1NDg3.X4-D6Q.UTLMv192yOfpACfQ6Vm2882OLc0');
My "joke.js" command file:
var messages1 = ["What’s the best thing about Switzerland?", "I invented a new word!"];
var messages2 = ["I don’t know, but the flag is a big plus.", "Plagiarism!"]
module.exports = {
name: 'joke',
description: "this is a joke command!",
execute(message, args){
var messagenumber = [Math.floor(Math.random() * 50)];
var message1 = messages1[messagenumber];
var message2 = messages2[messagenumber];
message.channel.send(message1).then().catch(console.error);
setTimeout(function(){
message.channel.send(message2).then().catch(console.error);
}, 3000);
}
}
When I do my joke command, or *joke, I get this, twice:
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (C:\Users\shery\Desktop\Stuff\JokeBot\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async RequestHandler.push (C:\Users\shery\Desktop\Stuff\JokeBot\node_modules\discord.js\src\rest\RequestHandler.js:39:14) {
method: 'post',
path: '/channels/773228754003558430/messages',
code: 50006,
httpStatus: 400
}
There is no output on discord, and I have tried taking off the console error catch blocks, but this just gave me a different error message. I do not know what to do. If anyone could help me, that would be wonderful.
Thanks!
var messagenumber = [Math.floor(Math.random() * 50)];
You are trying to get a random number from 0 to 49 from this. The length of your jokes is too small to account for the random max.
Try
function getRandomValue(arr) {
return arr[(Math.floor(Math.random() * arr.length))];
}
console.log(getRandomValue([2,3]))
So you account for every joke and no more.
I just made a command handler, but for some reason it starts two bots (I used the same commands I used before, I just put them inro a different file). I tried generating new token but that did not help. I rebooted my pc but nothing. This is my code:
const Discord = require("discord.js");
const { prefix, token } = require("./config.json");
const client = new Discord.Client();
const fs = require("fs");
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);
client.once("ready", () => {
console.log("Ready!");
});
client.on("message", (message) => {
let args = message.content.substring(prefix.length).split(" ");
switch (args[0]) {
case "kick":
client.commands.get("kick").execute(message, args);
break;
case "serverinfo":
client.commands.get("serverinfo").execute(message, args);
break;
}
});
client.login(token);
}
The commands were in the for loop.