I‘m trying my first member counter bot on Discord. Somehow the numbers of the online, idle and dnd members aren‘t updating correct anymore. It seems that the bot is outputting old numbers.
My code:
module.exports = async (client) => {
const guild = client.guilds.cache.get('889774617349218304');
const guildMembers = await guild.members.fetch({ withPresences: true });
const onlineCount = await guildMembers.filter(member =>!member.user.bot && member.presence?.status === "online").size
setInterval(() =>{
const channel = guild.channels.cache.get('906111710706954251');
channel.setName(`🟢 ${onlineCount.toLocaleString()}`);
console.log('Updating User-Online Count');
}, 360000);
}
Looking at your code, you are repeating the process where it changes the channel name, but using the whole variable. You are not updating the guildmember variable, hence it's always the same.
You could either move everything into the setInterval function, or redefine it.
For example:
module.exports = async (client) => {
setInterval( async () =>{
const guild = client.guilds.cache.get('889774617349218304');
const guildMembers = await guild.members.fetch({ withPresences: true });
const onlineCount = await guildMembers.filter(member =>!member.user.bot && member.presence?.status === "online").size
const channel = guild.channels.cache.get('906111710706954251');
channel.setName(`🟢 ${onlineCount.toLocaleString()}`);
console.log('Updating User-Online Count');
}, 360000);
}
This way, every hour, the bot will fetch the members of the guilds again, making it accurate.
Related
I have been trying to create a member count on my discord server. My code isn't working, I keep getting "Cannot read property 'channels' of undefined".
module.exports = (client) => {
const channelId = '810343814517489664'
const updateMembers = (guild) => {
const channel = guild.channels.cache.get(channelId)
channel.setName(`Members: ${guild.memberCount.toLocaleString()}`)
}
client.on('guildMemberAdd', (member) => updateMembers(member.guild))
client.on('guildMemberRemove', (member) => updateMembers(member.guild))
const guild = client.guilds.cache.get('464316540490088448')
updateMembers(guild)
}
You channel is undefined because you are not asking for it the right way.
You can ask for it :
const channelId = guild.channels.cache.get('CHANNEL ID');
Next below I will explain and show you what I am using for member counter!
module.exports = async (client) =>{
const guild = client.guilds.cache.get('GUILD ID');
setInterval(() =>{
const memberCount = guild.memberCount;
const channel = guild.channels.cache.get('CHANNEL ID');
channel.setName(`🏠Members🏠:${memberCount.toLocaleString()}`);
console.log('Updating Member Count');
}, 3600000);//I set the update time every 1 hour!
}
You need to create a voice channel for start and then the bot will rename it every time you will set the update!
In your main file (like index.js) you need to require for counter.So you need to create a folder in your main folder with name counters. Inside this folder ('counters') you need to create a file named 'member-counter.js' and you paste the code above. In your main file (like index.js) you require it with :
const memberCounter = require('./counters/member-counter');
You go next in line that having the client.on(ready) function and set in last line :
memberCounter(client);
What i mean is :
client.on('ready', () => {
console.log('I am ready')
memberCounter(client);
});
I've made a code for verify command, it's reacting to certain embed. But when I reboot the bot won't recognize it, so users can still react but won't get role at all. I've heard I can use Partial Event but I don't want to make it inside index.js.
Code:
let wembed = new Discord.MessageEmbed()
.setAuthor("Test")
.setColor("PURPLE")
.setDescription(arg1)
const reactmessage = await client.channels.cache.get(chx).send(wembed)
await reactmessage.react('✅');
const filter = (reaction, user) => reaction.emoji.name === '✅' && !user.bot;
const collector = reactmessage.createReactionCollector(filter);
collector.on('collect', async reaction => {
const user = reaction.users.cache.last();
const guild = reaction.message.guild;
const member = guild.member(user) || await guild.fetchMember(user);
member.roles.add("725747028323205170");
});
If there is a way of doing this help would be appreciated!
https://discordjs.guide/popular-topics/partials.html#enabling-partials
index.js:
const client = new Client({ partials: ['MESSAGE', 'CHANNEL', 'REACTION'] });
your messageReactionAdd file:
module.exports = async (reaction, user) => {
if(reaction.partial) await reaction.fetch();
}
Now all reactions are sent to messageReactionAdd, now you just have to validate the reaction and add the role if it corresponds to the right emoji and the right message
Normally I wouldn't ask for help, but I've tried almost everything and I'm stumped. Here is my code,
const Discord = require('discord.js');
const client = new Discord.Client();
const timedResponses = ["Test"]
const token = '';
client.on('ready', () =>{
console.log('the doctor is ready');
client.user.setActivity('medical documentaries', { type: 'WATCHING'}).catch(console.error);
const channel = client.channels.fetch('691070971251130520')
setInterval(() => {
const response = timedResponses [Math.floor(Math.random()*timedResponses .length)];
channel.send(response).then().catch(console.error);
}, 5000);
});
client.login(token);
The code seems to be working fine on my other bots, but for some reason it refuses to work on this one.
Edit: I tried to add console.log(channel) but I got an error. "Channel" is not defined.
ChannelManager#fetch returns a Promise Check the return type in the documentation
You could fix your issue by using async / await
client.once("ready", async () => {
// Fetch the channel
const channel = await client.channels.fetch("691070971251130520")
// Note that it's possible the channel couldn't be found
if (!channel) {
return console.log("could not find channel")
}
channel.send("Your message")
})
I am assuming you copied the ID manually from a text based channel, if this ID is dynamic you should check if the channel is a text channel
const { TextChannel } = require("discord.js")
if (channel instanceof TextChannel) {
// Safe to send in here
}
So, I'm trying to create a simple bot that when the user writes:
!howmanypoints {user}
It should just go to a specific channel, and search how many times it was mentioned in the specific channel.
As of now, I encountered the function fetchMentions() but it seems deprecated and the API doesn't like it when a bot tries to do this..
Any input or at least a better approach for this. Maybe I'm fixated with making it work.
const Discord = require('discord.js')
const client = new Discord.Client()
client.on('message', msg => {
if (msg.content.includes('!howmanypoints') || msg.content.includes('!cuantospuntos')) {
const canal_de_share = client.channels.find('name', 'dev')
const id_user = client.user.id
client.user.fetchMentions({guild: id_user })
.then(console.log)
.catch(console.error);
}
})
ClientUser.fetchMentions() is deprecated, and only available for user accounts.
As an alternative, you could fetch all the messages of the channel and iterate over each, checking for mentions.
Example:
let mentions = 0;
const channel = client.channels.find(c => c.name === 'dev');
const userID = client.user.id;
channel.fetchMessages()
.then(messages => {
for (let message of messages) {
if (message.mentions.users.get(userID)) mentions++;
}
console.log(mentions);
})
.catch(console.error);
So I am trying to make a SQLite database for my Discord.js bot, but I keep getting this error (Cannot read property of 'run' of null) when I try to use SQLite. Non of my friends seem to have this problem, so I thought to come here. Sorry if this is like a noobish question.. I'm still a little new to this
Here is my code:
const Discord = require("discord.js");
const client = new Discord.Client();
const bot = new Discord.Client();
const sql = require("sqlite")
const fs = require("fs");
const staff = ["97122523086340096", "450241616331145217", "283438590875402240", "288755621787074560"]
const config = require("./config.json");
client.on("ready", async () => {
console.log(`${client.user.username} is ready to help servers!`)
console.log ("Warning: I am being locally hosted. During high usage times, the bot may crash.")
console.log(`I am available in 1 shard! I am in ${client.guilds.size} guilds and serving ${bot.users.size}`)
client.user.setActivity("For sat!help", {type: "WATCHING"}, {status:"dnd"});
client.user.setPresence( {status:"idle"} )
sql.run("CREATE TABLE IF NOT EXISTS guild (guildId TEXT, language INTEGER, links INTEGER)")
});
fs.readdir("./events/", (err, files) => {
if (err) return console.error(err);
files.forEach(file => {
let eventFunction = require(`./events/${file}`);
let eventName = file.split(".")[0];
client.on(eventName, (...args) => eventFunction.run(client, ...args));
});
});
client.on("message", 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();
try {
let commandFile = require(`./commands/${command}.js`);
commandFile.run(bot, message, args);
} catch (err) {
return
}
});
client.on("guildCreate", guild => {
let guildp = guild.owner
guildp.send("Thanks for adding me to your server! \n To save you some time I would suggest you run the command 'sat!setup' to create the nessecary roles and channels for the bot. \n Please note that the channel is not made with perms.\n ***[PLEASE NOTE!] - I am still in beta so any issues with any part of the bot please tell us with sat!bug! \n Thanks!")
})
client.login(config.token);
You need to open connection with the database and then run the SQL query.
const sql = require("sqlite")
const db = sql.open('./database.sqlite', { Promise });
db.run("CREATE TABLE IF NOT EXISTS guild (guildId TEXT, language INTEGER, links INTEGER)");