Guild Members TImeout: Members didn't arrive in time - discord

So I have this command that shows the riches users in a server this command worked yesterday however recently it has stopped working.
const { MessageEmbed } = require("discord.js");
const { stripIndents } = require("common-tags");
const { prefix } = require("../../botconfig.json");
const db = require('quick.db')
let bal = require('../../database/balance');
let rep = require('../../database/rep');
let work = require('../../database/works');
module.exports = {
config:{
name: "rich",
aliases: ["r"],
category: "currency",
description: "Tells who is rich",
usage: ""
},
run: async (client, message, args) => {
// Get all members of the server before doing anything
message.guild.members.fetch().then(guildMembers => {
let board = [];
for (let key of Object.keys(bal)) {
// Checks if the collection of GuildMembers contains the key.
if (guildMembers.has(key)) {
let value = Object.assign({user: guildMembers.get(key).user}, bal[key]);
board.push(value);
}
}
const emojis = [':first_place:', ':second_place:', ':third_place:', ':small_blue_diamond:', ':small_blue_diamond:']
board = board.sort((a,b) => b.balance-a.balance).splice(0, 5);
let top = board.map((x, i) => `${emojis[i]} **${x.balance.toLocaleString()}** - ${x.user.tag}`).join('\n');
let embed = new MessageEmbed()
.setColor("RANDOM")
.addField(`Richest users in **${message.guild.name}**`, `${top}`)
.setFooter('Switch Version 1.1');
return message.channel.send(embed);
}).catch(console.error)
}
}
The error code when the !rich command is used is as follows:
Guild_Members_Timeout: Members didn't arrive in time
I don't know if this is an issue within the bot or if it is an issue with discord.

Okay I have found the answer to my own problem it seems I needed to add intents to my discord bot to fetch the members.
All I did was add this line of code and it worked.
const intents = new Intents([
Intents.NON_PRIVILEGED, // include all non-privileged intents, would be better to specify which ones you actually need
"GUILD_MEMBERS", // lets you request guild members (i.e. fixes the issue)
]);
const client = new Client({ ws: { intents } });

None of my discord.js guildmember events are emitting, my user caches are basically empty, and my functions are timing out? . In this post it is explained in great detail and that helped me out a lot.TLDR:go to discord developer portal on your particular application ,go to bot , on bot permissions tick whatever is needed and copy the number.Then use this number as a constructor parameter for new Discord.Intents('insert the number here').This worked for me.

Related

Discord.js Filter Discord Events From Only 1 Server

I am working on trying to filter events for only 1 server rather than all servers the bot is in, but I'm trying to figure out how to exactly save each guild the bot is in as an collection so I can just filter events based on a guild ID I desire. Is this even possible? This is a snippet of the code I have to date, it's able to display the server names and ID's the bot is currently in, the events are working properly but triggering for all servers rather than the one I desire, how would I go about filtering for one guild collection?
const Discord = require('discord.js')
const bot = new Discord.Client()
const config = require('./config.json')
bot.on('ready', () => {
console.log(`Logged in as ${bot.user.tag}!`);
//Sets Activity
//client.user.setStatus('invisible')
bot.user.setActivity("Discord Cooks", { type: "WATCHING"})
console.log("Set User Activity!");
//Online Webhook
const webhookClient = new Discord.WebhookClient('','');
const embed = new Discord.MessageEmbed()
.setTitle(`${bot.user.tag} is online`)
.setColor('#FFFF00')
.setTimestamp()
webhookClient.send(embed);
bot.guilds.cache.forEach((guild) => {
console.log(guild.name, guild.id);
});
});
bot.on("channelCreate", (channel) => {
console.log(`channelCreate: ID: ${channel.id} Name: ${channel.name}`);
});
bot.on("channelUpdate", (oldChannel, newChannel) => {
console.log(`channelUpdate -> ${oldChannel.name} to ${newChannel.name}`);
});
bot.on("channelDelete", (channel) => {
console.log(`channelDelete: ID: ${channel.id} Name: ${channel.name}`);
});
bot.login(config.bottoken)
You can only execute code if event happened on exact server in much easier way:
if(guild.id == "GUILD_ID") {
// code
}
Also as #MrMythical said, you can just use if (message.guild.id !== "GUILD_ID") return; if you only need to run your code for 1 guild!

How do I display local image with discord.js message embed?

I'm working on semi-gacha bot command where you can pull characters and so on. I want to display the characters image after the user pulls and here is where I get stuck, it just doesn't display anything and I found what looked like the answer on here, but it didn't help, as I would get the same result and I don't get any errors, so I don't know what exactly is wrong. I have tried printing out the result of MessageAttachment first:
const attachment = new Discord.MessageAttachment('./chars/1.Jakku.png', '1.Jakku.png');
console.log(attachment);
and I get: undefined, anybody has any ideas of what am I doing wrong? And yes, I have discord.js library imported.
Relevant part of the code:
collector.on('collect', reaction => {
//new embd
const newEmbd = new Discord.MessageEmbed();
// gacha logic
if (reaction.emoji.name === '✅') {
const values = Object.values(chars);
const randomChar = values[parseInt(Math.floor(Math.random()*values.length))];
const attachment = new Discord.MessageAttachment('./chars/1.Jakku.png', '1.Jakku.png');
const charData = randomChar.split('.');
newEmbd
.setTitle(`You pulled: ${charData[1]}!`)
.setColor('YELLOW')
.attachFiles(attachment)
.setImage(`attachment://1.Jakku.png`);
embdReact.edit(newEmbd);
pulled = true;
} else if (reaction.emoji.name === '❌') {
newEmbd
.setTitle('Time for gacha!')
.setColor('YELLOW')
.addFields(
{ name: 'Result:', value: 'You decided against pulling' }
);
embdReact.edit(newEmbd);
};
});
You need to use the correct syntax for attaching files as per this guide
const exampleEmbed = new Discord.MessageEmbed()
.setTitle('Some title')
.attachFiles(['./chars/1.Jakku.png'])
message.channel.send(exampleEmbed);

Why does my discord bot not add roles properly?

I am trying to make a bot that would add a role that is in the server when a person types !join choiceOutOfVariousRoles. I am currently using discord version 12. My error message is:
fn = fn.bind(thisArg);
Although trying various techniques I could not get the code to work.
const Discord = require('discord.js');
const client= new Discord.Client();
const token = process.env.DISCORD_BOT_SECRET
client.on('ready', () => {
console.log("I'm in");
console.log(client.user.username);
});
client.on('message', msg => {
if (msg.content.toLowerCase().startsWith("!join"))
{
var args = msg.content.toLowerCase().split(" ")
console.log(args)
if (args[1] === 'sullen')
{
msg.channel.send('You have successfully joined Sullen!')
const sullenRole = msg.guild.roles.cache.find('name','Sullen')
msg.member.addRole(role.id)
}
}
});
client.login(token)
**EDIT: Fixed what everyone was saying and all I need to do now Is update the permissions, (my friend has to do that because its not my bot) and I should be all good. Thanks everyone! :D
discord.js introduces breaking changes very frequently, and v12 is no exception. You need to make sure you find up-to-date code otherwise it won't work. GuildMember#addRole was moved to GuildMemberRoleManager#add, which means you must use msg.member.roles.add(sullenRole).

Grabbing the permissions from a TextChannel - Discord.js

Basically, I need to grab the permissions from the current text channel the user is in. I have already got the channel name, if I need to get the ID that should be pretty easy to do.
const Discord = require("discord.js");
module.exports.run = async (client, message, args) => {
let currentChannel = message.channel.name;
let category = message.channel.parent;;
message.guild.createChannel(currentChannel).then(mchannel => {
mchannel.setParent(category).then(() => {
message.channel.delete();
});
});
}
module.exports.help = {
name: "a.cleanchannel"
}
// Need the channel permissions to overwrite the new channel's permissions with the old ones
The expected results are that the channel should have the same permissions as the old one.
To answer your question directly, you can use GuildChannel#permissionOverwrites to create the new channel with the same permissions as the old one. For example...
message.guild.createChannel(message.channel.name, {
type: 'text',
permissionOverwrites: message.channel.permissionOverwrites
});
However, it looks like you're trying to clone a channel. To help make that easier, there's a method built into Discord.js for it - GuildChannel#clone(). You can use it like so...
message.channel.clone(undefined, true, true) // Same name, same permissions, same topic
.then(async clone => {
await clone.setParent(message.channel.parent);
await clone.setPosition(message.channel.position);
await message.channel.delete();
console.log(`Cloned #${message.channel.name}`);
})
.catch(console.error);

Discord.js some GuildMemeber functions don't work or?

Anyone knows what could be the issue that .kick() .setMute(true/false) or even setDeaf(true/false) in discord.js libary don't seem to work. Here is also a part of the code that doesn't do anything when it should but also doesn't throw any errors. Bot was invited with maximum privileges and also code block executes the command to steMute / setDeaf / kick. Any ideas of what might cause this or what should i try logging to find the issue? THANKS!
ar msgUserId = msg.author.id
var allUsers = []
var reset = true
bot.channels.forEach((channel, id) => {
if (reset){
channel.members.forEach((user, id) => {
allUsers.push(user)
if (id == msgUserId){
reset = false
}
})
if (reset){
allUsers = []
}
}
})
if (allUsers){
var number = Math.floor((Math.random() * allUsers.length))
allUsers[number].setDeaf(true)
allUsers[number].setMute(true)
} else {
var channel = msg.channel
channel.send("You must be in a voice channel with others for this to work!")
}
Channels in bot.channels are cached for the sole purpose of metadata which are instances of Channel, you need a guild context (aka. server ID) in order to acquire a TextChannel with which the operations you say can be done.

Resources