How to add server stats channels on discord.js - discord.js

I have a basic code for a discord bot that is only used for 1 server. The end result that I want is so that the bot displays the amount of total members, human users, bots, channels, roles, categories and emojis as a list of voice channels at the top of the server. I have made the channels and used their IDs in the following code.
//All Members
module.exports = client => {
const channelId = '871913848020545546'
const updateMembers = guild => {
const channel = guild.channels.cache.get(channelId)
channel.setName(`All Members: ${guild.memberCount.toLocaleString()}`)
}
client.on('guildMemberAdd', (member) => updateMembers(member.guild))
client.on('guildMemberRemove', (member) => updateMembers(member.guild))
const guild = client.guilds.cache.get('868192571766239262')
updateMembers(guild)
}
//Members
module.exports = client => {
const channelId = '871916605569892373'
const updateMembers = guild => {
const channel = guild.channels.cache.get(channelId)
channel.setName(`Members: ${guild.members.cache.filter(member => !member.user.bot).size}`)
}
client.on('guildMemberAdd', (member) => updateMembers(member.guild))
client.on('guildMemberRemove', (member) => updateMembers(member.guild))
const guild = client.guilds.cache.get('868192571766239262')
updateMembers(guild)
}
//Bots
module.exports = client => {
const channelId = '871917535589728297'
const updateMembers = guild => {
const channel = guild.channels.cache.get(channelId)
channel.setName(`Bots: ${guild.members.cache.filter(member => member.user.bot).size}`)
}
client.on('guildMemberAdd', (member) => updateMembers(member.guild))
client.on('guildMemberRemove', (member) => updateMembers(member.guild))
const guild = client.guilds.cache.get('868192571766239262')
updateMembers(guild)
}
//Channels
module.exports = client => {
const channelId = '871928838412705846'
const updateChannels = guild => {
const channel = guild.channels.cache.get(channelId)
channel.setName(`Channels: ${guild.channels.cache.size}`)
}
client.on('guildChannelAdd', (channel) => updateChannels(channel.guild))
client.on('guildChannelRemove', (channel) => updateChannels(channel.guild))
const guild = client.guilds.cache.get('868192571766239262')
updateChannels(guild)
}
//Roles
module.exports = client => {
const channelId = '871928838412705846'
const updateRoles = guild => {
const channel = guild.channels.cache.get(channelId)
channel.setName(`Roles: ${guild.roles.cache.size}`)
}
client.on('guildRoleAdd', (role) => updateRoles(role.guild))
client.on('guildRoleRemove', (role) => updateRoles(role.guild))
const guild = client.guilds.cache.get('868192571766239262')
updateRoles(guild)
}
//Categories
module.exports = client => {
const channelId = '871928838412705846'
const updateCategories = guild => {
const channel = guild.channels.cache.get(channelId)
channel.setName(`Categories: ${guild.categories.cache.size}`)
}
client.on('guildCategoryAdd', (category) => updateCategories(category.guild))
client.on('guildCategoryRemove', (category) => updateCategories(category.guild))
const guild = client.guilds.cache.get('868192571766239262')
updateCategories(guild)
}
//Emojis
module.exports = client => {
const channelId = '871928838412705846'
const updateEmojis = guild => {
const channel = guild.channels.cache.get(channelId)
channel.setName(`Channels: ${guild.emojis.cache.size}`)
}
client.on('guildEmojiAdd', (emoji) => updateEmojis(emoji.guild))
client.on('guildEmojiRemove', (emoji) => updateEmojis(emoji.guild))
const guild = client.guilds.cache.get('868192571766239262')
updateEmojis(guild)
}
The All Members section doesn't update automatically, the Members and Bots sections work, the Channels section returns the wrong amount of channels, and the Roles, Categories and Emojis sections return nothing.
Please advise

Related

Discord bot not coming online despite no error messages?

I have recently spent a long time making a discord ticket bot, and all of a sudden now, it isnt turning on. There are no error messages when I turn the bot on, and the webview says the bot is online. I am hosting on repl.it
Sorry for the long code, but any genius who could work this out would be greatly appreciated. Thanks in advance.
const fs = require('fs');
const client = new Discord.Client();
const prefix = '-'
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);
}
require('./server.js')
client.on("ready", () => {
console.log('Bot ready!');
client.user.setActivity('-help', { type: "LISTENING"} ).catch(console.error)
})
client.on("message", async (message) => {
if (message.author.bot) return;
const filter = (m) => m.author.id === message.author.id;
if (message.content === "-ticket") {
let channel = message.author.dmChannel;
if (!channel) channel = await message.author.createDM();
let embed = new Discord.MessageEmbed();
embed.setTitle('Open a Ticket')
embed.setDescription('Thank you for reaching out to us. If you have a question, please state it below so I can connect you to a member of our support team. If you a reporting a user, please describe your report in detail below.')
embed.setColor('AQUA')
message.author.send(embed);
channel
.awaitMessages(filter, {max: 1, time: 1000 * 300, errors: ['time'] })
.then ( async (collected) => {
const msg = collected.first();
message.author.send(`
>>> ✅ Thank you for reaching out to us! I have created a case for your inquiry with out support team. Expect a reply soon!
❓ Your question: ${msg}
`);
let claimEmbed = new Discord.MessageEmbed();
claimEmbed.setTitle('New Ticket')
claimEmbed.setDescription(`
New ticket created by ${message.author.tag}: ${msg}
React with ✅ to claim!
`)
claimEmbed.setColor('AQUA')
claimEmbed.setTimestamp()
try {
let claimChannel = client.channels.cache.find(
(channel) => channel.name === 'general',
);
let claimMessage = await claimChannel.send(claimEmbed);
claimMessage.react('✅');
const handleReaction = (reaction, user) => {
if (user.id === '923956860682399806') {
return;
}
const name = `ticket-${user.tag}`
claimMessage.guild.channels
.create(name, {
type: 'text',
}).then(channel => {
console.log(channel)
})
claimMessage.delete();
}
client.on('messageReactionAdd', (reaction, user) => {
const channelID = '858428421683675169'
if (reaction.message.channel.id === channelID) {
handleReaction(reaction, user)
}
})
} catch (err) {
throw err;
}
})
.catch((err) => console.log(err));
}
})
client.login(process.env['TOKEN'])
Your problem could possibly be that you have not put any intents. Intents look like this:
const { Client } = require('discord.js');
const client = new Client({
intents: 46687,
});
You can always calculate your intents with this intents calculator: https://ziad87.net/intents/
Side note:
If you are using discord.js v14 you change client.on from message to messageCreate.

discord.js v13 SlashCommandBuilder Reaction Roles

So i need help with the assign roles part - so if someone click on the reaction(emojiID) it should give the user who clicked on it the role(roleID)..
My code below sends the embed in the channel with my title & description and the emoji, but nothing happend if someone clicked on the emoji!
I use SlashCommandBuilder :
const { SlashCommandBuilder } = require('#discordjs/builders');
const fs = require('fs');
const { Client, Intents, MessageEmbed, MessageReaction } = require('discord.js');
const client = new Client({ intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MEMBERS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
Intents.FLAGS.DIRECT_MESSAGE_REACTIONS,
],
partials: ["MESSAGE", "CHANNEL", "REACTION"]
});
module.exports = {
data: new SlashCommandBuilder()
.setName('reaction')
.setDescription('Create reaction messages')
.addChannelOption((option) => {
return option
.setName('channel')
.setDescription('Choose a channel')
.setRequired(true)
})
...
async execute(interaction, client) {
const channelID = interaction.options.getChannel('channel');
const titleID = interaction.options.getString('title');
const descID = interaction.options.getString('desc');
const emojiID = interaction.options.getString('emoji');
const roleID = interaction.options.getRole('role');
let embed = new MessageEmbed()
.setTitle(titleID)
.setDescription(descID)
channelID.send({ embeds: [embed] }).then((sentMessage) => {
sentMessage.react(emojiID);
The code above is the working part - for the roles - I tried something like
async (reaction, user) => {
if(reaction.interaction.partial) await reaction.interaction.fetch();
if(reaction.partial) await reaction.fetch();
if(user.bot) return;
if(!reaction.interaction.guild) return;
if(reaction.interaction.channel.id === channelID) {
if(reaction.emoji.id === emojiID) {
reaction.interaction.guild.members.cache.get(user.id).roles.add(roleID)
}
}
};
but this is not working, please help :)

discord.js sharding issue in fetching guild

how do i check in discord.js sharding speciic guild id include in my client or not?
const getServer = async (guildID) => {
// try to get guild from all the shards
const req = await client.shard.broadcastEval((c, id) => c.guilds.cache.get(id), {
context: guildID
});
// return Guild or null if not found
return req.find(res => !!res) || false;
}
app.get('/test', checkAuth, async (req, res) => {
let Data =[];
req.user.guilds.forEach(async guild => {
const permsOnGuild = new Permissions(guild.permissions_new);
if(!permsOnGuild.has(Permissions.FLAGS.MANAGE_GUILD))return
if(await getServer(guild.id)){
Data.push(guild)
}
})
return res.render('test.ejs', { perms: Permissions,data:Data,client:client, user: req.user});
});

Discord.js code isn't working. I should give a the member a role but it says add is undefined

Here is my code:
let userlist = [];
let reactedlist = [];
client.on('message', msg=> {
const filter = () => {
return true
};
const collector = msg.createReactionCollector(filter, { time: 86400000 });
collector.on('collect', (a,reaction) => {
console.log(reaction.id);
if(!userlist.includes(reaction.id) && !reactedlist.includes(reaction.id)){
userlist.push(reaction.id)
}
console.log(userlist);
userlist.forEach(id => {
const userReactions = msg.reactions.cache.filter(reaction => reaction.users.cache.has(id));
try {
let duo = '';
for (const reaction of userReactions.values()) {
duo+=reaction.emoji.id;
}
if(duo.includes('854754738956664901') && duo.includes('854754766609055764')){
userlist.shift();
const member = client.users.fetch(id);
let role = msg.guild.roles.cache.find(i => i.id === '854756696965644319')
member.roles.add(role);
if(!reactedlist.includes(id)){
reactedlist += id;
}
}
} catch (error) {
console.error(error);
}
});
});
collector.on('end', collected => {
console.log(`Collected ${collected.size} items`);
});
});
client.login('');
Users cannot have roles added to them.
To get the GuildMember, you should be going into the guild and fetching from the GuildMemberManager.
const member = await msg.guild.members.fetch(id);
member.roles.add(role);

Trying to display JSON data from API as an array

So I've been trying to make a Discord Bot in Node.js, Im fetching data from an external api and using the BOT to display the data, problem is that when I call the function, its showing one by one instead of everything in one message.
I want to display everything in one message.
const token = 'my discord token is here';
const Discord = require('discord.js');
const axios = require('axios');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.on('message', async msg => {
if (msg.content === '!inventario') {
let getInv = async () => {
let response = await axios.get('my api link where im getting the info is here')
let inventario = response.data
return inventario
}
let inventarioValue = await getInv ()
var inv = inventarioValue.total_inventory_count
msg.channel.send(`Total de Itens no inventário: ${inventarioValue.total_inventory_count} \nSkins:\n`);
for (var i=0;i<inv;i++)
{
var itens = inventarioValue.descriptions[i].market_name
msg.channel.send(itens);
}
}
});
client.login(token);
I want to execute this inventarioValue.descriptions[i].market_name, then after executing showing the full result instead of showing one by one.
Thanks
You can map object array element and add to message. For a better visual reflection, you can add them to embed.
const token = 'my discord token is here';
const Discord = require('discord.js');
const axios = require('axios');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.on('message', async msg => {
if (msg.content === '!inventario') {
let getInv = async () => {
let response = await axios.get('my api link where im getting the info is here')
let inventario = response.data
return inventario
}
let inventarioValue = await getInv()
var inv = inventarioValue.total_inventory_count
let embed = new Discord.MessageEmbed()
embed.setDescription(`${inventarioValue.descriptions.map(val => val.market_name).join('\n')}`)
msg.channel.send(`Total de Itens no inventário: ${inventarioValue.total_inventory_count} \nSkins:\n`, embed);
}
});
client.login(token);

Resources