Sharding Ready Timeout - javascript

I keep getting this error when I try to run the bot. (I'm a beginner at coding, please explain in a way I can understand.)
My index.js:
const Discord = require('discord.js');
const chalk = require('chalk');
require('dotenv').config();
const express = require('express')
const app = express()
app.get('/', function (req, res) {
res.send('Hello World')
})
app.listen(3000)
const webhook = require("./config/webhooks.json");
const config = require("./config/bot.js");
const startLogs = new Discord.WebhookClient({
id: webhook.startLogs.id,
token: webhook.startLogs.token,
});
const shardLogs = new Discord.WebhookClient({
id: webhook.shardLogs.id,
token: webhook.shardLogs.token,
});
const manager = new Discord.ShardingManager('./src/bot.js', {
totalShards: 2,
token: process.env.DISCORD_TOKEN,
respawn: true
});
// const { AutoPoster } = require('topgg-autoposter');
// const poster = AutoPoster(process.env.TOPGG_TOKEN, manager);
console.clear();
console.log(chalk.blue(chalk.bold(`Sistem`)), (chalk.white(`>>`)), (chalk.green(`Başlıyor`)), (chalk.white(`...`)))
console.log(`\u001b[0m`)
console.log(chalk.red(`© Dessky | 2021 - ${new Date().getFullYear()}`))
console.log(chalk.red(`Her hakkı saklıdır`))
console.log(`\u001b[0m`)
console.log(`\u001b[0m`)
console.log(chalk.blue(chalk.bold(`Sistem`)), (chalk.white(`>>`)), chalk.red(`Versiyon ${require(`${process.cwd()}/package.json`).version}`), (chalk.green(`yüklendi`)))
console.log(`\u001b[0m`);
manager.on('shardCreate', shard => {
let embed = new Discord.MessageEmbed()
.setTitle(`🆙・Bot başlatılıyor`)
.setDescription(`Bir parça az önce başlatıldı`)
.addField("🆔┆Kimlik", `${shard.id + 1}/${manager.totalShards}`, true)
.addField(`📃┆Bilgi`, `Başlatılıyor...`, true)
.setColor(config.colors.normal)
startLogs.send({
username: 'Başlıyor',
embeds: [embed],
});
console.log(chalk.blue(chalk.bold(`Sistem`)), (chalk.white(`>>`)), (chalk.green(`Başlatılıyor`)), chalk.red(`Shard #${shard.id + 1}`), (chalk.white(`...`)))
console.log(`\u001b[0m`);
shard.on("death", (process) => {
const embed = new Discord.MessageEmbed()
.setTitle(`🚨・Beklenmedik bir şekilde ${shard.id + 1}/${manager.totalShards} parça kapatılıyor`)
.addField("PID", `\`${process.pid}\``)
.addField("Çıkış Kodu", `\`${process.exitCode}\``)
.setColor(config.colors.normal)
shardLogs.send({
username: 'Uyarı!',
embeds: [embed]
});
if (process.exitCode === null) {
const embed = new Discord.MessageEmbed()
.setTitle(`🚨・Shard ${shard.id + 1}/${manager.totalShards} NULL hata koduyla çıkıldı!`)
.addField("PID", `\`${process.pid}\``)
.addField("Çıkış Kodu", `\`${process.exitCode}\``)
.setColor(config.colors.normal)
shardLogs.send({
username: 'Bot Logs',
embeds: [embed]
});
}
});
shard.on("shardDisconnect", (event) => {
const embed = new Discord.MessageEmbed()
.setTitle(`🚨・Shard ${shard.id + 1}/${manager.totalShards} bağlantıyı kesti`)
.setDescription("Boşaltma soketi kapatma olayı...")
.setColor(config.colors.normal)
shardLogs.send({
username: 'Bot Logs',
embeds: [embed],
});
});
shard.on("shardReconnecting", () => {
const embed = new Discord.MessageEmbed()
.setTitle(`🚨・Sharda yeniden bağlanılıyor ${shard.id + 1}/${manager.totalShards}`)
.setColor(config.colors.normal)
shardLogs.send({
username: 'Bot Logs',
embeds: [embed],
});
});
});
manager.spawn();
And the error I got:
node --trace-deprec/home/runner/Sekizz/node_modules/discord.js/src/sharding/Shard.js:166
reject(new Error('SHARDING_READY_TIMEOUT', this.id));
^
Sometimes I get this error and sometimes I don't. I'm very confused.
Error
The code I am using is the template.
The program I'm using is replit.
And I don't even know what the shard is, as I'm new to these things, I want to get information about it.

Related

TypeError [INVALID_TYPE]: Supplied data.type is not a valid MessageComponentType - Discord.js

hey im trying to make a slashCommand that generate random pics with button..
so when a user use the command it will sent an embed with button and then the button when a user clicked that, the embed will edited and load another picture
but It seems i was doing it wrong..
Node: v17.7.2
Discord.js: 13.2.0
here is my code
const { MessageEmbed, MessageActionRow, MessageButton } = require('discord.js');
const superagent = require('superagent');
const ee = require("../../config.json");
module.exports = {
name: 'waifu',
description: 'Give you a random anime waifus pics',
run: async (client, interaction, args) => {
let { body } = await superagent.get(`https://api.waifu.pics/sfw/waifu`);
const msg = await interaction.followUp({
embeds: [
new MessageEmbed()
.setColor(ee.color)
.setTitle("Waifu 😳")
.setImage(body.url)
.setTimestamp()
],
components: [
new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId('nextWaifu')
.setLabel('More Waifu')
.setStyle('SUCCESS')
)
],
fetchReply: true
});
let embed = msg.embeds
embed.color = ee.color;
embed.image = body.url;
let components = msg.components
return msg.edit({ embeds: [embed], components: [components], fetchReply: true });
}
}

timeout.js discord.js v13 command not working

I got this problem, when i wanna use a message embed in my timeout command, that i get a error message! I sended all of the command / files down there! i appreciate the help!
Here the Error Message:
TypeError: command.run is not a function
at module.exports (/home/runner/Bolt-Utilities/events/guild/command.js:132:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Here the Timeout.js command:
const MessageEmbed = require("discord.js");
module.exports = {
name: 'timeout',
aliases: ["tmute", "tm"],
utilisation: '{prefix}timeout',
async execute(client, message, args) {
const fetch = require('node-fetch');
const ms = require('ms');
if (!message.member.permissions.has('TIMEOUT_MEMBERS')) {
message.delete()
} else {
const user = message.mentions.users.first();
const embed1 = new MessageEmbed()
.setDescription("Please provide the user.")
.setColor("RED");
const embed2 = new MessageEmbed()
.setDescription("Please specify the time.")
.setColor("RED");
const embed3 = new MessageEmbed()
.setDescription("Please specify the time between **10 seconds** (10s) and **28 days** (28d).")
.setColor("RED");
if(!user) return message.reply({ embeds: [embed1] });
const time = args.slice(1).join(' ');
if(!time) return message.reply({ embeds: [embed2] });
const milliseconds = ms(time);
if(!milliseconds || milliseconds < 10000 || milliseconds > 2419200000) return message.reply({ embeds: [embed3] });
const iosTime = new Date(Date.now() + milliseconds).toISOString();
await fetch(`https://discord.com/api/guilds/${message.guild.id}/members/${user.id}`, {
method: 'PATCH',
body: JSON.stringify({ communication_disabled_until: iosTime }),
headers: {
'Content-Type': 'application/json',
'Authorization': `Bot ${client.token}`,
},
});
const embed4 = new MessageEmbed()
.setDescription(`${user} has been **Timeout.** | \`${user.id}\``)
.setColor("YELLOW");
message.channel.send({ embeds: [embed4] })
}
},
};
and here the command.js file:
if (!cooldowns.has(command.name)) {
cooldowns.set(command.name, new Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(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(
`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.run(client, message, args, p, cooldowns);
} catch (error) {
console.error(error);
let embed2000 = new MessageEmbed()
.setDescription("There was an error executing that command.")
.setColor("BLUE");
message.channel.send({ embeds: [embed2000] }).catch(console.error);
}
};
That are all files! i hope someone can help me i dont know what is wrong there!
Typo: you don't actually have a command.run function in your command file, instead you have execute. Change either one to be the same as the other will solve the problem.
Note: if you change the async execute to async run, change like the following:
async run(client, message, args) => {

Allow users to send suggestion for the bot to create and send an embed with two emojis to vote

I'm trying to create a discord bot that will where someone can enter the slash command /suggestion and the bot will take that suggestion and turn it into an embed and send it into a specific suggestions channel with two emojis, an X and Checkmark.
After getting it all written and doing node deploy-commands.js and getting no errors, I inputted node . with also no errors in the terminal.
But when I went into the discord and enter the /suggestions command, I get an error in the terminal which is:
TypeError: Cannot read properties of undefined (reading 'join')
and I have no idea how to follow the error to see where it's originating from.
Does anyone have any thoughts on this?
I'll leave my index.js, suggestions.js, and deploy-commands.js below.
index.js
// Require the necessary discord.js classes
const fs = require('fs');
const { Client, Collection, Intents, } = require('discord.js');
const { token } = require('./config.json');
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
],
});
client.commands = new Collection();
client.events = new 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);
}
// When the client is ready, run this code (only once)
client.once('ready', () => {
console.log("You are now connected to Boombap Suggestions!");
});
client.on('interactionCreate', async (interaction) => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
return interaction.reply({
content: 'There was an error while executing this command!',
ephemeral: true,
});
}
});
// Login to Discord with your client's token
client.login(token);
suggestions.js
module.exports = {
name: 'suggestions',
aliases: ['suggest', 'suggestion'],
permissions: [],
description: 'creates a suggestion!',
execute(message, args, cmd, client, discord) {
const channel = message.guild.channels.cache.find(c => c.name === 'suggestions');
if (!channel) return message.channel.send('suggestions channel does not exist!');
let messageArgs = args.join(' ');
const embed = new discord.MessageEmbed()
.setColor('5104DB')
.setAuthor(message.author.tag, message.author.displayAvatarURL({ dynamic: true }))
.setDescription(messageArgs);
channel.send(embed).then((msg) => {
msg.react('❌');
msg.react('✅');
message.delete();
}).catch((err) => {
throw err;
});
}
}
deploy-commands.js
const { SlashCommandBuilder } = require('#discordjs/builders');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { clientId, guildId, token } = require('./config.json');
const commands = [
new SlashCommandBuilder().setName('suggestions').setDescription('Submit A Suggestion!'),
]
.map(command => command.toJSON());
const rest = new REST({ version: '9' }).setToken(token);
rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
.then(() => console.log('Successfully registered application commands.'))
.catch(console.error);
You're only passing the interaction at command.execute(interaction) yet you're expecting message, args, etc at execute(message, args, cmd, client, discord). As args is undefined you receive "TypeError: Cannot read properties of undefined (reading 'join')" .
Another problem is that you're using v13 of discord.js and still having some v12 syntax, just like in your previous post.
As you are using slash commands, you will have no args, you could add a string option in your deploy-commands.js file using the addStringOption() method. You should also mark this command option as required by using the setRequired() method.
Update commands in deploy-commands.js:
const commands = [
new SlashCommandBuilder()
.setName('suggest')
.setDescription('Submit a suggestion!')
.addStringOption((option) =>
option
.setName('suggestion')
.setDescription('Enter your suggestion')
.setRequired(true),
),
].map((command) => command.toJSON());
In your suggestions.js file, you can get this option from the CommandInteractionOptionResolver using interaction.options.getString('suggestion').
There are some changes to how setAuthor() works in v13. It now accepts an EmbedAuthorData object that has a name and an iconURL property.
Replace your suggestions.js with the following:
const { MessageEmbed } = require('discord.js');
module.exports = {
name: 'suggest',
aliases: ['suggest', 'suggestion'],
permissions: [],
description: 'creates a suggestion!',
async execute(interaction) {
let channel = interaction.guild.channels.cache.find((c) => c.name === 'suggestions');
if (!channel) {
await interaction.reply('`suggestions` channel does not exist!');
return;
}
let suggestion = interaction.options.getString('suggestion');
let embed = new MessageEmbed()
.setColor('5104DB')
.setAuthor({
name: interaction.member.user.tag,
iconURL: interaction.member.displayAvatarURL({ dynamic: true }),
})
.setDescription(suggestion);
let sentEmbed = await channel.send({ embeds: [embed] });
await interaction.reply({
content: '🎉 Thanks, we have received your suggestion',
ephemeral: true,
});
sentEmbed.react('❌');
sentEmbed.react('✅');
},
};

TypeError: Cannot read properties of undefined (reading 'createdTimestamp')

I'm trying to create a ping command for my discord bot. My code seems pretty straightforward:
index.js:
require("dotenv").config();
const { Client, Intents, Collection } = require("discord.js");
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
});
const fs = require("fs");
client.commands = new 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.data.name, command);
}
const eventFiles = fs
.readdirSync("./events")
.filter((file) => file.endsWith(".js"));
for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args, client));
} else {
client.on(event.name, (...args) => event.execute(...args, client));
}
}
client.on("interactionCreate", (interaction) => {
console.log(interaction);
});
client.login(process.env.TOKEN);
messageCreate.js:
require("dotenv").config();
module.exports = {
name: "messageCreate",
on: true,
async execute(msg, client) {
// If message author is a bot, or the message doesn't start with the prefix, return.
if (msg.author.bot || !msg.content.startsWith(process.env.PREFIX)) return;
var command = msg.content.substring(1).split(" ")[0].toLowerCase();
// Remove the command from the args
var args = msg.content.substring().split(/(?<=^\S+)\s/)[1];
if (!client.commands.has(command)) return;
try {
await client.commands.get(command).execute(msg, args, client);
} catch (error) {
console.error(error);
await msg.reply({
content: "Error: Please check console for error(s)",
ephemeral: true,
});
}
},
};
ping.js:
const { SlashCommandBuilder } = require("#discordjs/builders");
const { MessageEmbed } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("ping")
.setDescription("Replies to ping with pong"),
async execute(msg, args, client, interaction) {
const embed = new MessageEmbed()
.setColor("#0099ff")
.setTitle("🏓 Pong!")
.setDescription(
`Latency is ${
Date.now() - msg.createdTimestamp
}ms. API Latency is ${Math.round(client.ws.ping)}ms`
)
.setTimestamp();
await interaction.reply({
embeds: [embed],
ephemeral: true,
});
},
};
I'm passing my msg parameter, so why is it that it doesn't recognize the msg.createdTimestamp within ping.js? EDIT: I've updated some of my code, updating the way the parameters are passed. Now I'm getting a TypeError: Cannot read properties of undefined (reading 'reply') error in my ping.js file.
So I figured it out. The msg portion of what I'm passing actually gets passed down to the interaction argument. Just had to change msg to interaction to get everything to work:
ping.js
const { SlashCommandBuilder } = require("#discordjs/builders");
const { MessageEmbed } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("ping")
.setDescription("Replies to ping with pong"),
async execute(interaction, args, client) {
const embed = new MessageEmbed()
.setColor("#0099ff")
.setTitle("🏓 Pong!")
.setDescription(
`Latency is ${
Date.now() - interaction.createdTimestamp
}ms. API Latency is ${Math.round(client.ws.ping)}ms`
)
.setTimestamp();
await interaction.reply({
embeds: [embed],
ephemeral: true,
});
},
};

How do I log new bans?

I'm working on something and I need to add ban logging, I tried something but it doesn't send anything.
Any help would be appreciated!
client.on('guildBanAdd', async (guild, user) => {
let Banch = await client.channels.cache.get('ID')
const fetchedLogs = await guild.fetchAuditLogs({
limit: 1,
type: 'MEMBER_BAN_ADD',
});
const banLog = fetchedLogs.entries.first();
if (!banLog) return console.log(`${user.tag} was banned from ${guild.name} but no audit log could be found.`);
const embed = new Discord.MessageEmbed()
.setTitle(`Member Banned`)
.setDescription(`${guild.name}`)
.setColor("RED")
.addField(`Member`, `\n${username}`)
Banch.send(embed)
}
);
This should work
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('guildBanAdd', async (guild, user) => {
const banned = await guild.fetchAuditLogs({
type: 'MEMBER_BAN_ADD',
limit: 1
});
const channel = client.channels.cache.get('ID');
if(!channel) return console.log(`Channel was not found!`);
const userbanned = banned.entries.first();
const { executor, target } = userbanned; // get the user who banned the user and the user that got banned
if(target.id !== user.id) return console.log(`Invalid data in the audit logs!`); // check if the user that got banned in the Audit Logs is the user that is banned
const embed = new Discord.MessageEmbed()
.setTitle(`Member Banned`)
.setDescription(`${guild.name}`)
.setColor("RED")
.addField(`Member`, `${target.username}`);
channel.send(embed).catch(err => {
console.log(err);
});
});

Categories

Resources