"ready" event is never called - javascript

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")

Related

Issues with dming a user if they send a command

I am trying to create a discord bot that can serve a multitude of purposes. Right now, I need some help with dming the user if they use the !help prefix. I tried multiple ways of dming the user & they lead to nowhere.
Here is my code:
const Discord = require("discord.js");
const config = require("./config.json");
const client = new Discord.Client({intents: ["GUILDS", "GUILD_MESSAGES"]});
const prefix = "!";
client.on("messageCreate", function(message) {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const commandBody = message.content.slice(prefix.length);
const args = commandBody.split(' ');
const command = args.shift().toLowerCase();
if (command === "") {
const timeTaken = Date.now() - message.createdTimestamp;
message.reply("e")
}
});
client.on('message', message => {
if (message.content === 'help') {
messageCreate.author.send('Help')
}
});
client.login(config.BOT_TOKEN);
Note your code here:
if (message.content === 'help') {
messageCreate.author.send('Help')
}
What is messageCreate defined as? Try replacing messageCreate with just message in the above excerpt.

How do i make my discord bot respond to a message with prefix?

What I'm trying to do is set up a discord autoresponse bot that responds if someone says match prefix + respondobject like "!ping". I don't know why it doesn't come up with any response in the dispute. I've attached a picture of what it does. I can't figure out why it's not showing up with any responses in discord.
const Discord = require('discord.js');
const client = new Discord.Client({intents: ["GUILDS", "GUILD_MESSAGES"]});
const prefix = '!'
client.on('ready', () => {
let botStatus = [
'up!h or up!help',
`${client.users.cache.size} citizens!`,
`${client.guilds.cache.size} servers!`
]
setInterval(function(){
let status = botStatus[Math.floor(Math.random() * botStatus.length)]
client.user.setActivity(status, {type: 'WATCHING'})
}, 15000);
console.log(client.user.username);
});
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()
const responseObject = {
"ping": `🏓 Latency is ${msg.createdTimestamp - message.createdTimestamp}ms. API Latency is ${Math.round(client.ws.ping)}ms`
};
if (responseObject[message.content]) {
message.channel.send('Loading data...').then (async (msg) =>{
msg.delete()
message.channel.send(responseObject[message.content]);
}).catch(err => console.log(err.message))
}
});
client.login(process.env.token);
Your main issue is that you're trying to check message.content against 'ping', but require a prefix. Your message.content will always have a prefix, so you could try if (responseObject[message.content.slice(prefix.length)]).
Other alternatives would be to add the prefix to the object ("!ping": "Latency is...")
Or, create a variable that tracks the command used.
let cmd = message.content.toLowerCase().slice(prefix.length).split(/\s+/gm)[0]
// then use it to check the object
if (responseObject[cmd]) {}

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.

Discord Bot Logging in Over 1000 Times

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.

Only assign role to users with 1+ roles in discord.js?

So I created a bot that will add a role to all users in a 6K+ user Discord server, so we can manage trolling easier with only allowing members with a certain role to type in specific channels. Problem is, I want to only give the role to users with 1+ roles already on the server.
Using Discord.js, I have come up with the following code that works perfect to give the role to all users (I have tested on another server), but I want to make it specifically only add to users with 1+ roles already.
Thanks for any help in advance!
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.on("message", async 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();
if(command === "addalltorole") {
process.setMaxListeners(0);
let role = message.guild.roles.find(r => r.name == 'Community')
if (!role) return message.channel.send(`**${message.author.username}**, role not found`)
message.guild.members.filter(m => !m.user.bot).forEach(member => member.addRole(role))
message.channel.send(`**${message.author.username}**, role **${role.name}** was added to all members`)
}
});
client.login(config.token);
As the documentation says:
https://discord.js.org/#/docs/main/stable/class/Guild?scrollTo=members
You can use this parameter to get all the members in a guild once you have a reference to a Guild. You can then filter it down to just those with more than one role:
guild.members.filter(member => member.roles.array().length > 0).forEach(member => member.addRole(role));
Something like this is the general premise and should work.
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.on("message", async 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();
if(command === "addalltorole") {
process.setMaxListeners(0);
let role = message.guild.roles.find(r => r.name == 'BIGROLE')
if (!role) return message.channel.send(`**${message.author.username}**, role not found`)
message.guild.members.filter(member => member.roles.array().length > 1).forEach(member => member.addRole(role));
/* message.guild.members.filter(m => !m.user.bot).forEach(member => member.addRole(role))
*/
message.channel.send(`**${message.author.username}**, role **${role.name}** was added to all members`)
}
});
client.login(config.token);

Categories

Resources