Discord Bot Logging in Over 1000 Times - javascript

I suspect this is happening due to the code below. It's the only bot of 3 with this code. The code itself hasn't been working 100% of the time when the bot is logged in. It's supposed to give anyone that is live streaming a "streaming" role. Some people it adds the role onto and for others it doesn't.
I'd like help for both issues if possible. Mostly the logging issue since I can't even keep the bot online anymore
The code below shows the entire index.js file. The code talked about above is the "presenceUpdate" section of code.
const fs = require('fs');
const Discord = require('discord.js');
const {prefix, token} = require('./config.json');
const welcomeGif = require('./welcomeGifs.json');
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}`);
client.commands.set(command.name, command);
}
client.once('ready', () => {
console.log(`${client.user.username} is online!`);
});
client.on('guildMemberAdd', gif => {
gif = new Discord.Attachment(welcomeGif[Math.floor(Math.random() * welcomeGif.length)]);
client.channels.get('614134721533968494').send(gif);
});
client.on('presenceUpdate', (oldPresence, newPresence) => {
const guild = newPresence.guild;
const streamingRole = guild.roles.cache.find(role => role.id === '720050658149138444');
if (newPresence.user.bot || newPresence.presence.clientStatus === 'mobile' || oldPresence.presence.status !== newPresence.presence.status) return;
const oldGame = oldPresence.presence.activities ? oldPresence.presence.activities.streaming: false;
const newGame = newPresence.presence.activities ? newPresence.presence.activities.streaming: false;
if (!oldGame && newGame) { // Started playing.
newPresence.roles.add(streamingRole)
.then(() => console.log(`${streamingRole.name} added to ${newPresence.user.tag}.`))
.catch(console.error);
} else if (oldGame && !newGame) { // Stopped playing.
newPresence.roles.remove(streamingRole)
.then(() => console.log(`${streamingRole.name} removed from ${newPresence.user.tag}.`))
.catch(console.error);
}
});
// This is the start of the main function when the bot is turned on
client.on('message', message => {
// The bot will not respond if there is no prefix,
// the user that typed it was a bot,
// or if it was not sent from in the server
if (!message.content.startsWith(prefix) || message.author.bot || !message.guild) return;
// Creates the arguments variable and separates it with a space
// and creates the command variable
const args = message.content.slice(prefix.length).split(' ');
const commandName = args.shift().toLowerCase();
if (!client.commands.has(commandName)) return;
const command = client.commands.get(commandName);
if (command.guildOnly && message.channel.type !== 'text') {
return message.reply('I can\'t execute that command inside DMs!');
}
try {
command.execute(message, args);
}
catch (error) {
console.error(error);
message.channel.send('There was an error trying to execute that command!\nCheck the console for details.');
}
});
// This logs in the bot with the specified token found in config
client.login(token);

Ok I'm getting closer and closer I think. I think the issue is that upon the bot logging in, it crashes from an error I found. When it crashes it is set to automatically restart so when it restarts it crashes again and repeats the cycle. The error I found is "clientStatus" is undefined which is in the presenceUpdate section.

Related

Discord.js Replit, cannot get my bot to respond to commands

I am currently developing a Discord bot for replit, and I am able to get it to post and even get it to send an intro message when joining a server, however whenever I try to get it to respond to a command I type it won't respond. The message for the first one client.on guild create works. However the client.on for async message will not work.
This is what I have so far.
const { Client } = require('discord.js');
const client = new Client({ intents: 32767 });
//const Discord = require('discord.js');
const keepAlive = require('./server');
require("dotenv").config();
//const client = new Discord.Client();
//const fetch = require('node-fetch');
const config = require('./package.json');
const prefix = '!';
const guild = "";
client.once('ready', () => {
console.log('Jp Learn Online');
});
// let defaultChannel = "";
// guild.channels.cache.forEach((channel) => {
// if(channel.type == "text" && defaultChannel == "") {
// if(channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
// defaultChannel = channel;
// }
// }
// })
//defaultChannel.send("This is a test message I should say this message when I join");
//if(guild.systemChannelId != null) return guild.systemChannel.send("This is a test message I should say this message when I join"), console.log('Bot entered new Server.')
// client.on('guildCreate', (g) => {
// const channel = g.channels.cache.find(channel => channel.type === 'GUILD_TEXT' && channel.permissionsFor(g.me).has('SEND_MESSAGES'))
// channel.send("This is a test message I should say this message when I join");
// });
client.on('guildCreate', guild => {
guild.systemChannel.send('this message wil print')
});
client.on('message', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/); // This splits our code into to allow multiple commands.
const command = args.shift().toLowerCase();
if (command === 'jhelp') {
message.channel.send('こんにちは、私はDiscordロボットです。始めたいなら、!jhelp タイプしてください。 \n\n Hello I am a discord bot built to help learn the Japanese language! \n\n If you want to access a japanese dictionary type !dictionary \n\n If you would like to learn a random Japanese Phrase type !teachme \n\n If you would like to answer a challenge question type !challenge1 through 5 each different numbered challnege will ask a different question \n (ie. !challenge1) this will ask the first question.')
}
please note. the lower parts of the code are simply commands. That expand further from jhelp I want to know mainly why my second client.on with messages wont work specifically in the context of working with replit.
Thanks for the help in advance.
I expected that maybe changing intents might work, I even went into the discord developer portal, and enabled options, and am still not able to get it working.
After Discord separated out the message intent as a privileged one, the bit field you need to use for all intents has changed. You need to use 131071.
I.e.
const { Client } = require('discord.js');
const client = new Client({ intents: 131071 });
//const Discord = require('discord.js');
const keepAlive = require('./server');
require("dotenv").config();
//const client = new Discord.Client();
//const fetch = require('node-fetch');
const config = require('./package.json');
const prefix = '!';
const guild = "";
client.once('ready', () => {
console.log('Jp Learn Online');
});
// let defaultChannel = "";
// guild.channels.cache.forEach((channel) => {
// if(channel.type == "text" && defaultChannel == "") {
// if(channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
// defaultChannel = channel;
// }
// }
// })
//defaultChannel.send("This is a test message I should say this message when I join");
//if(guild.systemChannelId != null) return guild.systemChannel.send("This is a test message I should say this message when I join"), console.log('Bot entered new Server.')
// client.on('guildCreate', (g) => {
// const channel = g.channels.cache.find(channel => channel.type === 'GUILD_TEXT' && channel.permissionsFor(g.me).has('SEND_MESSAGES'))
// channel.send("This is a test message I should say this message when I join");
// });
client.on('guildCreate', guild => {
guild.systemChannel.send('this message wil print')
});
client.on('messageCreate', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/); // This splits our code into to allow multiple commands.
const command = args.shift().toLowerCase();
if (command === 'jhelp') {
message.channel.send('こんにちは、私はDiscordロボットです。始めたいなら、!jhelp タイプしてください。 \n\n Hello I am a discord bot built to help learn the Japanese language! \n\n If you want to access a japanese dictionary type !dictionary \n\n If you would like to learn a random Japanese Phrase type !teachme \n\n If you would like to answer a challenge question type !challenge1 through 5 each different numbered challnege will ask a different question \n (ie. !challenge1) this will ask the first question.')
}
Yes! its the problem with your intents, for guildMemberAdd/Remove you require GuildMembers intents

discord.js "TypeError: Cannot read property 'execute' of undefined" with async function in command file

I'm trying to add a command code under the command file, but i'm unable to get it to work. The problem arises at this line => if (command == 'checkin' || command == 'ch') {
client.commands.get('chk').execute(message).
Without that line, the code works fine with the other 2 commands. I think it has to do with the async function but I'm not sure how to solve this problem. I don't want to include the whole chunk of code in the main file either, as it gets very long and cluttered. I'm new to coding, so it might be something I can't understand yet - please help me!
bot.js (the main .js file)
const { token, prefix } = require('./config.json');
const fs = require('fs');
const db = require('quick.db');
const ms = require('parse-ms-2')
const { Client, Intents, Message, Collection } = require("discord.js");
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES
]
});
client.commands = new Discord.Collection();
// filter commands
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
// fetch commands
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.once("ready", () => {
console.log("online.");
client.user.setPresence({ activties: [{ name: 'with commands' }] });
})
client.on('messageCreate', async message => {
// definite command components
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase()
if (command == 'help' || command == 'h') {
client.commands.get('help').execute(message)
}
if (command == 'bal') {
client.commands.get('bal').execute(message)
}
if (command == 'checkin' || command == 'ch') {
client.commands.get('chk').execute(message)
}
})
client.login(token)
chk.js (where the command is)
const db = require('quick.db')
const nm = require('parse-ms-2')
module.exports = {
name: "check in",
descrption: "daily check in rewards.",
async execute(message) {
let user = message.mentions.users.first() || message.author;
let daily = await db.fetch(`daily_${message.author.id}`);
let money = db.fetch(`money_${user.id}`);
let cooldown = 1000*60*60*20
let amount = Math.floor(Math.random() * 500) + 250
if (daily != null && cooldown - (Date.now() - daily) > 0) {
let time = ms(cooldown - (Date.now() - daily));
message.channel.send(`You have already collected the daily check in reward, please check in again in **${time.hours}h ${time.minutes}m ${time.seconds}s**`)
} else {
let embed = new Discord.MessageEmbed()
.setTitle('Daily Check In')
.setDescription(`Here is the amount collected today: ${amount}`)
.setColor('#ffc300')
message.channel.send({embeds: [embed]})
db.add(`money_${message.author.id}`, amount)
db.add(`daily_${message.author.id}`, Date.now())
}
}}
Cannot read property 'execute' of undefined"
Means client.commands.get('chk') is returning undefined.
Presumably, this means the chk command can't be found.
So, let's look at where you're setting the commands:
// fetch commands
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
And let's check your chk.js file which is being imported.
module.exports = {
name: "check in",
// ...
What I can see is, you're exporting the module and setting the command with the name "check in" but later in the script, you're asking for a command called "chk". The command can't be found, returns undefined, and kills your code as it isn't handled.
The solution in this case is to just change your name property to "chk", or request client.commands.get("check in") instead.

How to fix TypeError: Cannot read property 'execute' of undefined in discord.js

I am new to command handler I am trying to execute commands for different js file
but I get this error
TypeError: Cannot read property 'execute' of undefined
this is my main.js
// Import the discord.js module
const Discord = require('discord.js');
const fs = require('fs');
// Create an instance of a Discord client
const client = new Discord.Client();
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
const prefix = "$"
/**
* The ready event is vital, it means that only _after_ this will your bot start reacting to information
* received from Discord
*/
client.on('ready', () => {
console.log('I am ready!');
});
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'pingg'){
client.commands.get('pingg').execute(message, args);
}
if (!client.commands.has(command)) return;
try {
client.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
client.login('censored');
fs.readdir("./commands/", (err, files) => {
if(err) console.error(error)
let jsfiles = files.filter(f => f.split(".").pop() === "js")
if (jsfiles.length <= 0) {
return console.log("No commands to log in FOLDER NAME")
}
console.log(`Loading ${jsfiles.length} commands from FOLDER NAME...`)
jsfiles.forEach((f,i) => {
let props = require(`./commands/${f}`)
console.log(`${i + 1}: ${f} loaded!`)
client.commands.set(f, props)
})
})
my ping.js
module.exports = {
name : 'pingg',
description : 'Test',
execute(message, args){
message.channel.send('pongg')
}
}
The commands are registered in client.commands collection in the bot application lifecycle after the client is ready.
This is because client.login is invoked before it.
You can use commandFiles to load the commands from their modules. This was already performed sychronously so you have some guarantee on the order.
Also do that before the client.login statement.
Another issue is that the command module is named ping.js and as such your current implementation registers ping command to client.command collection.
However, you are resolving pingg command from the collection which returns an undefined
commandFiles.forEach(file => {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
});
client.login('censored');
//...

Discord JS command not being proccesed

I've been working on a moderation bot in Discord.JS recently, and I've completed many commands such as Purge, Mute, etc. As I was working on the 'ban' command, I noticed that I was getting no response from the bot. I started debugging, even restarted development on the command a couple times, and then, I thought to change the command to something basic to check if the bot was even receiving the command. So the command now just had message.channel.send('hello world'), and I ran the command, still no output, just when I use no arguments, a Please provide arguments to execute this command message. I then tried deleting the command file and restarting the bot, and I ran the command, same output. Ill include my bot.js below:
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
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}`);
client.commands.set(command.name, command);
}
const cooldowns = new Discord.Collection();
client.once('ready', () => {
console.log('Ready!');
});
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.permissions) {
const authorPerms = message.channel.permissionsFor(message.author);
if (!authorPerms || !authorPerms.has(command.permissions)) {
return message.reply('You can not do this!');
}
}
if (command.args && !args.length) {
let reply = `\`Please provide arguments to execute this command\``;
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 could be an issue with discord rate limiting which can happen often if you attempt to login a bot many times over a short period of time. If the issue is just with that one ban command its either an issue with the ban command itself or your command handler. if its an issue with all commands, the ready event might not be being emitted which would indicate what I mentioned above. try using a different bot token or regenerating your current one and running the program again.

"ready" event is never called

I'm programming my first Discord bot and I programmed it to output something to the console whenever it starts up, or in other words whenever client.on("ready") is called. However, I can't get it to actually fire and I don't know why. I have all Node dependencies installed, the bot is in the server and is able to send messages, and the first few lines of the program run fine.
What is the problem?
Here is the source:
console.log("Launching bot...\n");
const Discord = require("discord.js");
const client = new Discord.Client();
const config = require("./config.json");
client.on("ready", () => {
console.log(`Bot has started, with
${client.users.size} users, in
${client.channels.size} channels of
${client.guilds.size} guilds.`);
client.user.setActivity(`Serving
${client.guilds.size} servers`);
});
client.on("message", async message => {
if(message.authot.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();
if(command === "ping") {
let m = await message.channel.send("Ping?");
m.edit(`Pong! Latency is ${m.createdTimestamp -
message.createdTimestamp}ms. API Latency is
${Math.round(client.ping)}ms`);
}
});
You forgot to use the .login method for your client, that's the reason why your ready event doesn't get triggered!
Here is the updated code, you just have to insert your top secret key from https://discordapp.com/developers/applications/
console.log("Launching bot...\n");
const Discord = require("discord.js");
const client = new Discord.Client();
const config = require("./config.json");
client.on("ready", () => {
console.log(`Bot has started, with
${client.users.size} users, in
${client.channels.size} channels of
${client.guilds.size} guilds.`);
client.user.setActivity(`Serving
${client.guilds.size} servers`);
});
client.on("message", async message => {
if(message.authot.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();
if(command === "ping") {
let m = await message.channel.send("Ping?");
m.edit(`Pong! Latency is ${m.createdTimestamp -
message.createdTimestamp}ms. API Latency is
${Math.round(client.ping)}ms`);
}
});
client.login("YOUR TOP SECRET KEY")

Categories

Resources