#development
1 messages · Page 901 of 1
looking at some big open source bots, a lot of them seem to use postgres + redis
which ones did you look at
also tony im just gonna make some assumptions for now
so i see that if you provide an intents field in the options, only stuff that you input in the intents field will be sent to you as packets
only thing im really confused on is the presence and guild member relationship
YAGPDB
ok so
if i put something in the intents, i WILL recieve packets for it or i WONT recieve packets for it
you will
isnt that the point of intents
so you can like, only request stuff that you need
i thought it was that you put stuff that you dont need, so they dont send it
eh im also stupud so
its the other way around
anyone know why postgres seems to be so favoured among popular bots
if (message.author.bot) return;
},```
I use that to stop my bot from listening to itself and it doesn't seem to work? any suggestions
What doesn't seem to work. Are bots still able to trigger commands?
That }, at the end may be your issue.
Do you have more than one bot.on("message", (...)) statement in your code.
yes
Is it within your execute block.
nvm, where do you have your multiple bot.ons? You should only have one, and I believe I told you this last time.
@earnest phoenix why dont you just put if (message.author.bot) return; in the function below
you should only be using one
@earnest phoenix an event is fired for whenever the event is emitted by its name. Loading multiple events fire each of the functions its set as. When you make a new event with a different function, they're not the same. I can't really tell if you have the second event within that message event, but you should only be using 1 message event. No more.
@misty river and @sudden geyser ty the bot stopped spamming
Okay just make sure you're only using one messge event unless you know for a fact you need more than one.
np
i dont see much of a downside to using redis as the primary datastore for my bot, as long as i dont run out of ram or something
which i wont
@hazy jewel like, the websocket latency?
what lib
Discord.JS
client.ws.ping
Discord Bot maker
discord what maker
okey
don`t work
kkkk
var ping = Date.now() - msg.createdTimestamp; Actions.storeValue(ping, 1, "latencia", cache);
i use this code
the problem is that when I set a custom prefix, I can't use the prefix to execute any commands, Here's the code: https://gist.github.com/IF64/4f7ba6691d58512d3fa8d2aa42164aa1
yes
why are you creating a new client lol
also, it might be better to store your global/default prefix in a config file
I have a db tho
oh you're talking about the default config
yes
makes sense
so it works with the default prefix but not when you set anything
Does ytdl download the video and then stream it?
and use the db for custom commands
@earnest phoenix i think it plays while it downloads the file
why?
because sometimes the songs will have random moments when it jumps/cuts/ends
I finally know why my bot crashed
out of mem?
bc I played an 10 hour video
Yes
lol
i fixed that by bumping up HighWaterMark as high as possible
that looks shiny
pretty clean
he like ur config
😳
If I get Object object, how do I turn it to a thing again? Object.keys(map)?
im using akairo for this rewrite
its cool but i dont understand how some of it works
NVM, stringify
how would I state my globalprefix in my main file
const globalPrefix = {config}?
is the config file stored in the same directory as this command
no stored in folder above it
const globalPrefix = require("../config").prefix
replace .prefix with whatever you called the prefix in config
so like
.globalPrefix or whatever
so the globalPrefix works, but I still need to have the custom prefix execute the commands in the commands folder
now logs give back execute of undefined
well this is the first time I got a 2-liner error TypeError: Cannot read property 'execute' of undefined at Client.<anonymous> (C:\Users\IF6\Documents\GitHub\disc-bot-rep\bot.js:45:21) at processTicksAndRejections (internal/process/task_queues.js:97:5)
what is line 45
can you send the code for what command you're trying to run
I will but one thing to state is that the two commands are in the same folder which probably prevents interaction
oh the command im trying to run?
name: 'help',
description: 'help message embed',
execute(message) {
const Discord = require("discord.js")
const helpEmbed = new Discord.MessageEmbed()
.setColor('#9534eb')
.setTitle('Available Commands')
.setDescription('A list of commands the bot will recognize')
.setThumbnail('https://i.imgur.com/wdrNBe6.jpg')
.addFields({
name: 'Music Commands',
value: '`play`, `skip`, `stop`',
inline: true
}, {
name: 'Misc. Commands',
value: '`brownbricks`, `respond`',
inline: true
}, {
name: 'Moderation Commands',
value: '`kick`, `ban`',
inline: true
}, {
name: 'Bot Settings',
value: '`prefix`',
inline: true
}
)
.setTimestamp()
.setFooter('The Saddest Cat On The entire Discord platform', 'https://i.imgur.com/wdrNBe6.jpg');
message.channel.send(helpEmbed);
}
}```
am i the only one who thinks you should probably clean that up?
absolutely
never thought about it
imma just throw some beautify on that
that's much better
so basically It gives me an error everytime I try to execute a command with my custom prefix
how do i let a bot ban random memebrs if they brekaing the rules
Hey, how can i get the total number of members of all servers discord js v11 ?
no
all
guilds
and sorry i don't understand verry good the english because im french
this can help https://stackoverflow.com/a/51573064
no because client.guilds.size not showing the corret number because i get more 100k users total
ohhh you want to count the users?
in all the guilds?
yes
users or members
client.users.zize 
just members
@copper cradle no because not showing the correct numbers
i get mort 100k user / members

remember that this server has 80K members
because my bot is in a server with 90k users, 1 with 4k and 1 with 6k
no 90k members not 80k
no
you're actually getting the number of users that share servers with your bot
so you just have to skip this server
You can use reduce
@copper cradle if i skip it i get ~ 12k
well
Loop through every guild and add their membercount to each other
then that means that without this server your bot has 12K usets
But that's not a valid way as you could have Mee6 more than 10 times in there
and how do you know the number you're getting from client.users.size is not correct
zSnails, it's probably not correct, I doubt every user would be cached
I mean they would have to fetch every server for that to be 100% correct
Some do
¯\_(ツ)_/¯
How do a check if an image from discord's cdn is still available (js)?
i have a reactionrole code and every time i react to any message it will add the role / remove
client.on("messageReactionAdd",(reaction,user)=>{
if(reaction.emoji === emoji && reaction.message.id === message.id);
reaction.message.guild.member(user).addRole(role)
///.catch(err => message.channel.send(errembed1));
client.on("messageReactionRemove",(reaction,user)=>{
if(reaction.emoji === emoji && reaction.message.id === message.id);
reaction.message.guild.member(user).removeRole(role)
///.catch(err => message.channel.send(errembed1));```
this is the adding and removing role part
You need to filter the reactions to only include the messaes that you want
i tried with reaction.message.id
That was what I was going to suggest
oh
so if its not the message return ?
You could simply do if(listOfMessages.includes(reaction.message.id))
And then put all the messages you want to watch in the listOfMessages array
I can't see where you're defining message
if(reaction.emoji === emoji && reaction.message.id === message.id);
message.id is the message the bot sent
but i think im wrong there
its supposed to be msg
oops
Oh lol
Personally I would be sending a message and then awaiting reactions on it directly after, rather than using a separate event
id rather use an event
but i dont get why its not working
i mean it is, but every time i react to a message it will add the role
(any message)
I would do this:
const mes = await somechannel.send("React here!")
mes.awaitReactions(...)
That kind of thing
but i want it to last forever
Yeah that's possible
You could even store the id of mes and then fetch it again when the bot restarts
let msg = await message.channel.send(reactionroleembed)
with discordjs, how can I know who banned someone?
this is the "msg"
with discordjs, how can I know who banned someone?
I think you have to do something with audit logs because BanInfo only stores the banned user and the reason
oh ok
@true ravine
so im deleting the events
and can you help me with the awaitreactions?
let msg = await message.channel.send(reactionroleembed)
Yeah so then you do
mes.awaitReactions((reaction,user)=>[YOUR FILTER GOES HERE],{OPTIONS HERE}).then(collected=>{
//do stuff here
})```
collected returns all the reactions to mes
just copypaste 👀
?
the text
who even uses screenshots 
but iguess
at least its not a photo
let msg = await message.channel.send(reactionroleembed)
msg.awaitReactions((reaction,user)=>[reaction.emoji.name === emoji],{}).then(collected=>{
//do stuff here
})```
so somthing like this
mes.awaitReactions((reaction,user)=>(reaction.emoji.name==="✅" || reaction.emoji.name==="🗑") && user.id===msg.author.id,{max: 1}).then(collected=>{
Readable version for your enjoyment
let msg = await message.channel.send(reactionroleembed)
msg.awaitReactions((reaction,user)=>[reaction.emoji.name === emoji],{}).then(collected=>{
//do stuff here
})```
Not in the square brackets, that was a placeholder
uhm
One sec
like this hihi x)
let totalUsers = bot.guilds.reduce((a,b) => a + b.memberCount, 0);
@copper cradle & @earnest phoenix
@true ravine
how do i make it so if he removed reaction it will remove and if he added it will add
on awaitreactions
i dont know shit about javascript, i just read the docs and understand it in the meantime 
(collected)
twixty https://tryitands.ee
-wrongserver
Hey! We think you have our server mistaken. We do not provide support, help, or advice for any bot. You need to click on the "Support Server" button on the bot's page, not the "Join Discord" button at the top of our website. If there isn't a button that says Join Support Server, then we can't help you. Sorry :(
How long does discord keep images on their cdn before they're deleted?
idk
never had any issues of them getting deleted
or until the message is deleted i think
Oh right thank you
with discordjs, how can I intentionally emit a client event? I have to test what happens if someone joins a server, but I'l too lazy to add a bot to the server to test
I tried doing this https://i.imgur.com/GcdPEre.png
sharex wtf happens
thats unfortunately the only way to do that
I remember one time in v11 doing that, but I dont remember how to do it
@true ravine up to 10 days, usually deletes after about a hour.
Is that for deleted messages or all messages? Because some images I uploaded and sent ages ago still work
it requires the user token after it's "deleted" and sometimes discord misses the image
like user token as in you need to be in the same server
at least that's how it is for me 
Oh right thank you
I want to add a value to Json. But I don't want to read the whole json for that. If there is, change the value. If there isn't, add the value. Is it possible to do this? discordjs
no
ok thx
well i mean, you can read through it only until you reach it
that'd be the fastest way
so I'm currently testing welcome messages with my bot, and I have this code in my guildMemberAdd event https://link-is-qt.lumap.me/r6u2hwri.png . The message is sent, the db works, but the .replace dont work https://link-is-qt.lumap.me/r4kq3ham.png . What I did wrong
he should be sending the new message variable rather than the predefined one
I fixed it
still doesnt work
if I console.log message after the .replace, it seems that the .replace didnt work
try to hardcode it for testing
const {GuildsBeta} = require('../../mongoose')
const Discord = require('discord.js')
module.exports = async (member) => {
let guild = member.guild
GuildsBeta.findOne({id: guild.id}, async (err,res) => {
if (err) console.log(err)
if (!res || !res.memberLogChannel || !res.memberAddMessage) return console.log(res);
let message = res.memberAddMessage
message.replace('{memberTag}', member.user.tag)
message.replace('{member}', `<@!${member.user.id}>`)
message.replace('{serverName}', member.guild.name)
message.replace('{serverMemberCount}', member.guild.memberCount)
let channel = guild.channels.cache.get(res.memberLogChannel)
if (!channel) return console.log('channel not found');
channel.send(message)
})
}```
everything else works, emitting the event, storing informations in the db...
const {GuildsBeta} = require('../../mongoose')
const Discord = require('discord.js')
module.exports = async (member) => {
let guild = member.guild
GuildsBeta.findOne({id: guild.id}, async (err,res) => {
if (err) console.log(err)
if (!res || !res.memberLogChannel || !res.memberAddMessage) return console.log(res);
let message = res.memberAddMessage
.replace('{memberTag}', member.user.tag)
.replace('{member}', `<@!${member.user.id}>`)
.replace('{serverName}', member.guild.name)
.replace('{serverMemberCount}', member.guild.memberCount)
//replace it when creating the new variable
// These return the message with replaced meaning you would need a new variable every time.
// message.replace('{memberTag}', member.user.tag)
// message.replace('{member}', `<@!${member.user.id}>`)
// message.replace('{serverName}', member.guild.name)
// message.replace('{serverMemberCount}', member.guild.memberCount)
let channel = guild.channels.cache.get(res.memberLogChannel)
if (!channel) return console.log('channel not found');
channel.send(message)
})
}
🙂
thanks! ^^
JS is whack
how do you make it so the status is basically a loop that refreshes every 30 seconds
using setInterval
like this?
setInterval(client.user.setPresence({
status: "online",
activity: {
name: `${client.guilds.cache.size} servers battle it out`,
type: "WATCHING"
}
}), 3000)
but the 3000 being 30000
yes
is there a way i can make like a command for my bot and allow users to vote on my bot with this api?
like using a >vote and that would make the user that used the command vote for my bot
nope
oki thanks
(node:4) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received Promise { <pending> }
script:
client.on("ready", () => {
console.log(`${client.user.username} is online!`);
setInterval(client.user.setPresence({
status: "online",
activity: {
name: `${client.guilds.cache.size} servers battle it out`,
type: "WATCHING"
}
}), 30000)
});```
what does 'The user aborted a request' mean
literally what it says
yeah
but if I have a .catch after sending the message its ok?
because it shows error but bot is ok
yeah should work
you gotta ask someone who knows js though, because i only refer to the docs
and it says that, does it mean that they have dms off?
@royal portal I thought that's giving another error. I read something aboutuser aborted a requestand I guess it was when sending a message takes too long for some reason
but you can always try sending a DM to yourself if you blocked your bot
alr thanks
wait I'll check it
sending a dm when it's not possible gives this error: Cannot send messages to this user, but you can catch this too of course
Hello, I'm still just starting out with the development of discord.js; it is a private bot, I try to make a help command with rotating pages but I can't manage to react with emojis, delete is not definited, I don't understand the error, someone could one help me?
if (msg.content === settings.prefix + 'help') {
if (msg.author.bot) return;
const embedhelp = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('Tableau de bord de Louveteaubot')
.setAuthor('Louveteaubot', 'https://www.dropbox.com/s/oc14jg53esuhdid/wolf-head-hand-drawing-vector.jpg?dl=1')
.setDescription('Bienvenue dans ma matrice ! Découvrez toutes mes options !')
.setThumbnail('https://www.dropbox.com/s/cccpms8t8fhsqhp/c44f5e4c21e5a8e5af536ca2b8a7bf1b.gif?dl=1')
.addField('Choissisez les menus :', "test en cours", true)
.setTimestamp()
.setFooter('Bot développé par Valmi');
const embedhelpadmin = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('Tableau de bord de Louveteaubot')
.setAuthor('Louveteaubot', 'https://www.dropbox.com/s/oc14jg53esuhdid/wolf-head-hand-drawing-vector.jpg?dl=1')
.setDescription('Bienvenue dans ma matrice ! Découvrez toutes mes options !')
.setThumbnail('https://www.dropbox.com/s/cccpms8t8fhsqhp/c44f5e4c21e5a8e5af536ca2b8a7bf1b.gif?dl=1')
.addField('pban (mention.user)', "Permet de ban un membre",
true)
.addField('pkick (mention.user)', "Permet de kick un membre",
true)
.addField('ppurge (nb)', "Permet de faire un giga suppr",
true)
.setTimestamp()
.setFooter('Bot développé par Valmi');
msg.channel.send(embedhelp).then(sentEmbed => {
sentEmbed.react('🗑️').then(sentEmbed.react('➡️'))
client.on('messageReactionAdd', (reaction, user) => {
if (msg.author.bot) return;
if (reaction.emoji.name === "🗑️")
msg.reaction.delete()
})
})
}
});```
Version NodeJS : V12.X
client.shard.fetchClientValues(`users.size`)
this work but I need
client.shard.fetchClientValues(`users.filter(member => !member.bot ).size`)
but this not working bot undefined error
my bot twice, why?
kill the clone

...
kill the second instance
:u
Kill your program
or where are you hosting?
@quartz hill try client.shard.fetchClientValues(`users`)
and then filter them afterwards
Guys, how do you debug your code on vscode whilst using discord.js shards manager?
ok trying now
whats the error?
what version of d.js are you using
then you need to use MessageEmbed instead of RichEmbed
and im pretty sure thats not how you send an embed anyways
wait did you say you want to remove it?
then just... remove it???
yeah thats what i was scratching my head to
then just.. dont create and send and embed..
@pale vessel not working
then send a normal message without the embed tag
Wait i dont know how js works xD
just remove the code that creates and sends the embed
How can I make a forEach work synchronically? Is there anything else than doing something like this?
array.forEach(async (element) => {
await new Promise((resolve) => {
// do something
// finally:
resolve();
});
});```
Or does that even not work?
are those always executed after each other?
yes
okay thank you!
well it's not working @mossy vine, guess it's because I have a .then() in the for loop
and according to the result, the then is just too late
const cd = require("./cooldown.json");
const Discord = require("discord.js");
const client = new Discord.Client();
const prefix = "p!";
//LOGIN
client.login("Token");
client.on("message", message => {
//RETURN IF USER IS A BOT
if (message.author.bot) return;
//GETTING CURRENT MILLISECONDS
let date = new Date().getMilliseconds();
//CHECKING IF USER CAN USER THIS COMMAND
let canUse;
if (cd[String(message.author.id)] !== undefined) canUse = (cd[String(message.author.id)] >= 21600000);
else canUse = true;
if (message.content.toLowerCase() === `${prefix}credits` && canUse && String(message.author.id) !== "460690666964385803" /*YOU*/) {
if (!canUse) {
message.channel.send("You can only use this command one time in 6 Hours");
return;
};
var numbers = [
"You have recieved 5 credits for Pokecord Bot\n\nYour reddem code is ||NwEf||\n\nDM ULTRON#4070 to recieve your gift with reddem code",
"You have recieved 10 credits for Pokecord Bot\n\nYour reddem code is ||FtwK||\n\nDM ULTRON#4070 to recieve your gift with reddem code",
"Better Luck Next time try again in 6 hours",
"Better Luck Next time try again in 6 hours",
"Better Luck Next time try again in 6 hours",
"You have recieved 20 credits for Pokecord Bot\n\nYour reddem code is ||TraW||\n\nDM ULTRON#4070 to recieve your gift with reddem code"
];
var answer = numbers[Math.floor(Math.random() * numbers.length)];
var embed = new Discord.MessageEmbed()
.setColor("#FF4500")
.setTitle("Pokécord Credits")
.setDescription(answer);
message.channel.send(embed);
//ADDING THE USER TO THE FILE
cd[String(message.author.id)] = date;
//WRITING THE DATA TO THE FILE
fs.writeFile("cooldown.json", cd, "utf8", () => {});
}
});
client.on("ready", () => {
console.log("Bot was logged in"); // Output a message to the logs.
});```
My bot isn't responding to me
After trying cooldown cmd
what
Bot is not responding to me
So #502193464054644737 says all bots are tested with permissions=0 - Does that mean they won't give embed permissions either? 👀
show your cooldown.js
@tight plinththere it is
@vivid crescent permisisons=0 is send & read messages + embed links
so dont worry about that one
Alright, thought embed links was separate my bad
he is hardcoding the cooldown
I think that's the issue
^
21600000
{}
Should do date - cooldown or something
empty {} ~= empty file
use something else
What should be there
@tight plinth think they're just using it as an entry set or something
Hi all! I'm pretty new to working with API's, can someone give me a hand understanding some of the documentation? In the list of properties for a channel object, what do the question marks mean? I'm trying to get a list of recipients from a channel object but it's saying there's no property called "recipients"... Does the question mark mean I need to access it through a .get() or something?
idk
But it doesn't need to be a sepatate file tbh
@rare coral it means "can not exist"
or null yea
Ah so like it'll only sometimes be a property?
most of the time yea
But is that supposed to just be for channels with no members? Because I'm querying a channel which does have members in
Maybe a better word instead of null is undefined - The properties without ? will always be defined in a valid request
so for example dms channels dont have a guild id property
@surreal notch change how you handle cooldowns
use something else than a cooldown.js
@surreal notch Just actually decrement the cooldown
That makes sense, thanks 🙂 In that case, can I then ask a follow up: Why might a non-DM channel not have any recipients property?
I'd say because it can be an empty voice channel
So !nips check is the message, you can see on the right that the channel has members
IT LOOKS PRETTY OKAY don't judge 😉
Can any one give me the server link of Trivia Alex Or utility Trivia??
white
i came here to have a good time and i'm honestly feeling so attacked right now
Can any one give me the server link of Trivia Alex Or utility Trivia??
This server are in the hit list now😂😂
there is one api for all the types of channels which is why there are so many nullable fields
@rare coral it says so in the Docs. The recipients are "the recipients of the DM"
no dm => no recipients
Oh right, so how do I get a list of users in a channel then?
TextChannel has members, not recipients if that's what's you're looking for
recipients is a private channel only endpoint afaik
so message.channel.members?
Yeah
I'm not using the API directly, so this might be wrong, but since there is no user field or anything, you'd wanna get the whole guild members MINUS the ones that can't see it through the permission_overwrites
I'm not using the API directly, so this might be wrong, but since there is no user field or anything, you'd wanna get the whole guild members MINUS the ones that can't see it through the permission_overwrites
@blazing portal If I could get the whole guild members that would do in and of itself! Would it be message.channel.guild.members?
Yes
Wait, are you using Discord.js? Or is it just this similar
No it's discord.py, but .member seems to work, thanks!
Ok
message.guild.members should also work
*.members I mean
How come .members isn't listed as a fied in the API docs? Are they out of date?
It's a discord.py thing I believe
Ahhhh, I see
If you are using Discord.py, I would recommend using the Discord.py docs though, not the official Discord docs, as .py might add things to make it easier. like this one 😉
aight can someone ban this guy for... liking white or smth
No theme wars here please 
(node:10196) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'get' of undefined
which line
whats ops.active
what you want it to be
One guy creates a tutorial on how to make a music bot on YouTube, literally everyone else copies his code
This code is from TheBelguimGames on YouTube
@twilit rapids mine is not from a youtuber 😛
if from my friend 😛
Fun thing is, nobody watches the tutorial but straight goes to the hastebins in the desc
from friend from a youtube video
ur friend copied it from yt
@tight plinth idk, i just know that it works for him
Yes
its better
what if i copy python code into js?
it will never work
Then you will have nightmares the next 3 weeks
hi
hi
how can i get a guilds prefix?
like, i just want to get the prefix and nothing else
idk do you use json or a db?
what u use as db
let a = require('../../models/Guild'); let p = a.findOne({ id: message.channel.guild.id }); p;
// returns the guilds config stuff (everything)
let a = require('../../models/Guild'); let p = a.findOne({ id: message.channel.guild.id }); p.prefix;
// returns undefined
My bot say two times the event messageUpdate!
with mongoose
nope
a.findOne({id: message.channel.guild.id},async (err,res) => {
if (err) console.log(err)
let prefix = res.prefix
//your code
})
My bot say two times the event messageUpdate!
what i can do?
@earnest phoenix u sent this message two times!
i have lag
idk
nothing
have u got any code?
let me send
oki, thank u lumap
does it works?
im checking now
after defining your prefix put the rest of your codee
client.on("messageUpdate", async (oldMessage, newMessage) => {
let count = await logs.obtener(oldMessage.guild.id);
//Obtenemos el nombre del canal donde se edito el mensaje
let nameChannel = newMessage.channel.name;
// Obtenemos el nombre del usuario que edito el mensaje
if (oldMessage.author.bot) return;
await snipedit.establecer(newMessage.channel.id, {
"author": newMessage.author.username,
"antes": oldMessage.content,
"despues": newMessage.content
})
let member = newMessage.member.displayName;
const embed = new Discord.RichEmbed()
.setTitle("**MENSAJE EDITADO**")
.setColor(0xff0000)
.setThumbnail(newMessage.author.displayAvatarURL)
.addField('Antes', oldMessage.content)
.addField('Despues', newMessage.content)
.addField('ID del mensaje', newMessage.id)
.addField('Link del mensaje',`[Link](${`https://discordapp.com/channels/${newMessage.guild.id}/${newMessage.channel.id}/${newMessage.id}`})`)
.addField('Nombre del autor', newMessage.author.username)
.addField('ID del autor', newMessage.author.id)
.addField('Mencion del autor', newMessage.author)
.addField('Nombre del canal', oldMessage.channel.name)
.addField('ID del canal', oldMessage.channel.id)
.addField('Mencion del canal', oldMessage.channel)
.setTimestamp()
.setFooter(newMessage.guild.name, newMessage.guild.iconURL);
// enviamos un mensaje de información de la actualización de un emoji en un canal X
client.channels.get(count).send(embed);
});
This is the code
make sure your bot is not running twice
@warm heart youre in dbl you have dbl pfp coongrats
i++
and #topgg-api for this question
lump, it retuns the same thing as what i sent
it returns what
hey i'm trying to make a top of user sorted by xp that is contained in a json file. My code looks like this :
var lb = []
for (const user in xp[msg.guild.id]) {
lb.push({
xp:user.xp,
level:user.level,
ID:user
})
}
var lb = sortByKey(lb, "xp")
if (lb.length > 10) {
lb.length = 10
}```(xp is requireing the json file)
And this code gives me this error :
(node:23114) UnhandledPromiseRejectionWarning: ReferenceError: sortByKey is not defined```
Would anyone know why ?
rhw whole guild config
like the guild id, the logs channel prefix etc
@hasty lotus define the function lol
i just want the prefix
res.prefix returns the whole config?
yes
res is the whole config
try res.prefix.prefix
ye, but .prefix is meant to get the prefix or?
yes it is
returns the whole config
i tried it
client.on("messageUpdate", async (oldMessage, newMessage) => {
let count = await logs.obtener(oldMessage.guild.id);
//Obtenemos el nombre del canal donde se edito el mensaje
let nameChannel = newMessage.channel.name;
// Obtenemos el nombre del usuario que edito el mensaje
if (oldMessage.author.bot) return;
await snipedit.establecer(newMessage.channel.id, {
"author": newMessage.author.username,
"antes": oldMessage.content,
"despues": newMessage.content
})
let member = newMessage.member.displayName;
const embed = new Discord.RichEmbed()
.setTitle("**MENSAJE EDITADO**")
.setColor(0xff0000)
.setThumbnail(newMessage.author.displayAvatarURL)
.addField('Antes', oldMessage.content)
.addField('Despues', newMessage.content)
.addField('ID del mensaje', newMessage.id)
.addField('Link del mensaje',`[Link](${`https://discordapp.com/channels/${newMessage.guild.id}/${newMessage.channel.id}/${newMessage.id}`})`)
.addField('Nombre del autor', newMessage.author.username)
.addField('ID del autor', newMessage.author.id)
.addField('Mencion del autor', newMessage.author)
.addField('Nombre del canal', oldMessage.channel.name)
.addField('ID del canal', oldMessage.channel.id)
.addField('Mencion del canal', oldMessage.channel)
.setTimestamp()
.setFooter(newMessage.guild.name, newMessage.guild.iconURL);
// enviamos un mensaje de información de la actualización de un emoji en un canal X
client.channels.get(count).send(embed);
});
<channel>.mention
<#someid> inside the field works too
plz dont repost
You fooled me, thought I was looking at java for a sec
idk why it triggers multiple times
<#channelID>
<#id>
You have to iterate through the channels and find the one with that name
then that will only mention one of the channels right
client.channels.find((e) => e.name === 'general').mention
ok thx
that?
now i've got a new error
(node:23114) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body
user_id: Value "[object Object]" is not snowflake.
Yeah what Officially said ^^
for (const u of lb) {
i++
const username = await bot.fetchUser(u).username
text += `${i}. ${username} - ${u.level} (${u.xp})\n`
}``` this code
not all channels are named general though
event message{
event messageUpdate
}
or
event message{
//code
}
event messageUpdate{
//code
}
second one
@hasty lotus you are parsing a random object as a message or something
u is likely not a user instance
Which is causing your type issue
he said he wants the every channel named general
so i dont know the problem
how can i fix it ?
@earnest phoenix which event are you using
messageUpdate
@earnest phoenix you might find this helpful https://www.reddit.com/r/discordapp/comments/7dnnfl/using_the_on_messagemessage_function_in_discordpy/
its a bit dated but eh
oh you using js
yes
try client.on("message" function... I think
messageUpdate
messageUpdate is called when the message is edited I think 👀
Haven't used discord.js though so maybe I'll just shutup then
whats the problem again?
He was saying the event was being called twice or something
My bot say two times the event messageUpdate!
the issue isn't coming from there
show a few lines above that code and a few lines below that code @earnest phoenix
(node:4) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_CALLBACK]: Callback mustbe a function. Received Promise { <pending> }
script:
client.on("ready", () => {
console.log(`${client.user.username} is online!`);
setInterval(client.user.setPresence({
status: "online",
activity: {
name: `${client.guilds.cache.size} servers battle it out`,
type: "WATCHING"
}
}), 30000)
});```
@digital ibex ok wait
});
client.on("warn", info => {
// enviamos un mensaje de información de las advertencias en un canal X
client.channels.get("704028719987163177").send(`Se ha generado una advertencia\nInformación: **${info}**`);
// por consola
console.log(`Se ha generado una advertencia\nInformación: ${info}`);
});
client.on("messageDelete", async message => {
let count = await logs.obtener(message.guild.id);
// Validamos si el mensaje es de un bot y que sea por mensaje directo
if (message.author.bot) return; //Acá está
if (message.channel.type === "dm") return;
await snipe.establecer(message.channel.id, {
"author": message.author.username, //establemeos el author del mensaje
"say": message.content //Y establecemos el contenido del mensaje borrado
})
......
@earnest phoenix setInterval takes a function, setPresence returns a promise
@earnest phoenix you need to set a function like () => {}
() => {
Code
}```
@digital ibex already
()=>{code}
wat
Hi, I have a question, how can I do that with a command my music bot reproduces a yt link? xD
setInteval(() => {
//code here
), ms('12s')}```
setInverval(() => {
updateprecense
}, ms)```
ms is a npm
setInverval(() => {
client.user.setPresence({
status: "online",
activity: {
name: `${client.guilds.cache.size} servers battle it out`,
type: "WATCHING"
}
})
}, 30000)```
yes.
ok, thanks
client.shard.fetchClientValues(`users.size`)
this work but I need
client.shard.fetchClientValues(`users.filter(member => !member.bot ).size`)
but this not working bot undefined error
what type is member?
how does that work, u r filtering users to a member
idk djs but if thats a thing wtf r they thinking
wait, nvm
Remove bots from all users. Returns the number of the rest.
});
client.on("warn", info => {
// enviamos un mensaje de información de las advertencias en un canal X
client.channels.get("704028719987163177").send(`Se ha generado una advertencia\nInformación: **${info}**`);
// por consola
console.log(`Se ha generado una advertencia\nInformación: ${info}`);
});
client.on("messageDelete", async message => {
let count = await logs.obtener(message.guild.id);
// Validamos si el mensaje es de un bot y que sea por mensaje directo
if (message.author.bot) return; //Acá está
if (message.channel.type === "dm") return;
await snipe.establecer(message.channel.id, {
"author": message.author.username, //establemeos el author del mensaje
"say": message.content //Y establecemos el contenido del mensaje borrado
})
......
@digital ibex
can you stop pinging me
pings him
i ping u just 2 time
yes
@quartz hill try member.user.bot.
users.filter(member => !member.bot ).size this work
and this client.shard.fetchClientValues(users.size) work but need
client.shard.fetchClientValues(users.filter(member => !member.bot ).size)
I am trying to send the number of members to all shards. But except bots. So I'm trying to filter. But it doesn't work that way.
ok trying
why doesnt it work? what happens when you try?
its probably cause its a guildmember not a user
bot is undefined error
guildmember does not a bot variable
^
ok I trying now this
whats the differ?
Cannot read property 'user' of undefined
member.user.bot not working
ok. what type is it even
Hey, i've got a json file looking like this :
"GUILDID":{
"userid1":{"xp":"...","level":"..."},
"userid2":{"xp":"...","level":"..."}
},
"GUILDID2":...```
And i'm trying to sort it with a top command like this :
```js
function sortByKey(array, key) {
return array.sort(function(a, b) {
let x = a[key]; let y = b[key];
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
});
}
var lb = []
if(!xp[msg.guild.id]) {
xp[msg.guild.id] = {}
}
for (const id in xp[msg.guild.id]) {
console.log(id.level)
lb.push({
xp:id.xp,
level:id.level,
ID:id
})
}
var lb = sortByKey(lb, "xp")```
But the problem is that if the for (const id in xp) pushes an "undefined" xp. Does anyone know why ?
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
/top command executed```
in the console :/
is there need to post 100 undefines?
not really
jut to shox
show
i haven't puted them all xD
but do you see any reason for it to be undefined ?
of course i did a require to the json
const xp = require("../xp.json")
yes i can print the id
for (const u of lb) {
i++
const username = await bot.users.get(u.ID).username
const tag = await bot.users.get(u.ID).discriminator
text += `#${i} **${username}#${tag}** - niveau ${u.level} (${u.xp}xp)\n`
}```
what does id say?
setInterval(() => {
let ping = Math.floor(message.client.ping);
client.channels.get('705741696322895983').setName(`Ping: ${ping} ms`)
}, ms('12s'));
let ping = Math.floor(message.client.ping);
^
TypeError: Cannot read property 'client' of undefined
@dull plume move here
ok
@dull plume e.g. to set the count with discord.js and got, you can do ```js
got("https://top.gg/api/bots/" + client.user.id + "/stats", {
method: "POST",
body: JSON.stringify({ server_count: client.guilds.cache.length })
});
yeah but what does the id object in your for loop print out as?
aah this
just client.ping
@hasty lotus work, ty
JSON.stringify
np
hmm
lb.ID is also undefined
lb.push({
xp:id.xp,
level:id.level,
ID:id
})
console.log(lb.ID)```
tried this
undefined
::
:/
yeah cause lb is an array
ok so what do you want me to print out ?
id
yes
yeah this works
what does it return?
the id
just the id?
console.log ?
@dull plume e.g. to set the count with discord.js and got, you can do
got("https://top.gg/api/bots/" + client.user.id + "/stats", {
method: "POST",
body: JSON.stringify({ server_count: client.guilds.cache.size })
});
wont that only count guilds in cache?
should be client.guilds.cache.size
with djs 12 client.guilds.size isn't working
and yes Thaun, but guilds are always cached by default
ok
I'm friggin new to HTML and I don't know why this code doesn't work
<script>
$("#darkm").on("change", function() {
var valuee = document.getElementById("darkm").checked;
alert(valuee)
if (valuee == "true"){
alert("Dark mode on!")
}
});
</script>
is it checked? I thought it's value
not sure now
also, it probably isn't string true
it's literal true
The alert box shows true when it's checked and false when not checked
if (valuee == true){
alert("Dark mode on!")
}
Alright I'll try it
or even simpler, just ```js
if(valuee) {
alert("dark");
}
you meanjs if(valuee) alert("dark");
idk when people mean "code does not work" does it mean the function does not get exectued?
that's javascript
@copper fog logging is an essential part of any kind of development. you can find the browser logs by hitting F12 and going to the "console" tab
all logs are written there, including those you generate yourself when using "console.log()"
imagine not logging anything @amber fractal
no matter which application, html or css, logging is important
Can suggest another method? I will show the number of users in all shards. But except bots. (nodejs)
fetchClientValues
I can't use the filter outside.
whats your current code?
await client.shard.fetchClientValues(`users.filter(member => !member.bot).size`).then(results =>{
totalsize = results.reduce((prev, memberCount) => prev + memberCount);
}).catch(console.error);
v11 or v12?
11
use broadcastEval instead
I never got the right result with Broadcast.But I will try again.
you will never get the right result anyway because not all users are cached
it will not count offline users for example
client.users.size
Doesn't that count all?
with eris, how can u get the size of the offline members in a certain role?
QQQWWW, only the cached ones
Thanks everyone.
@quartz hill the only thing that counts ALL users is guild.memberCount
but you cannot filter that
@digital ibex filter by role then filter by status
will also only work on cached members
oh
you filter the members
client.guild.memberCount
this?
no
ok
each guild has its own memberCount
there is no global memberCount
you need to join all guilds' memberCounts
you gotta combine all those yeah
you can use a reduce function, just like you did with your previous code
i hate how they return the fetchClientValues data
role.members.filter((e) => e.status === 'offline') ?
thx so much
I will try it now.
discord have problems with the bots?
not as far as i know?
there is no global memberCount
@quartz kindle umm, client.users.size
@digital ibex does eris have role.members?
xd
@wind solstice thats not the same thing
thats a "global memberCount"
from the bot
role.guild.members
yeah?
guild.memberCount = total members in a guild
guild.members.size / guild.members.cache.size = number of cached members in the guild
client.users.size / client.users.cache.size = number of cached users in the current client instance
@wind solstice
cached members is not the same as total members
huh
idk why i thought thta would work

because b r a i n
but then how would i get the members in that role?
you already got it
role.guild.members.filter((e) => <include role id> already returns all members that have the role
?
members.filter(member => member.roles.includes(role.id) && member.status === "offline")
oh
has is for guild#roles
guildmember#roles is an array of ids
see how eris is memory efficient
i love it
lemme see if it works
haha
so
role.guild.members.filter(
(e) => e.roles.includes(role.id) && role.guild.members.status === 'offline'
);
``` doesn't respond with anything
fp
think of e as a member
i use x for every function
i use t for every function
nice
because it stands for this
didn't want to get confused with m, message
lmao
sometimes i for items or indexes
and x/y/z when there are loops inside loops
j for row, i for column
ez
and my reduce functions use "atir"
a for accumulator, t for this, i for index, r for array
i also use function funcName(f1, f2) { } for whatever reason
instead of funcName(foo, bar)
lul
a,b for sort functions
yeah, i use (a, b) for reduce
none of these matter but i still like having my own principals
just makes the code cleaner
this is why i never use it
its fast af tho
i like it because of it
and makes my code look more intense
lmao
for angle in angles:
cosines.append(math.cos(angle))``` :^))
ye but later down i need to know which angle is which
this looked easier to understand at the time
Eh, I mean true
hi another issue kinda
double quote
yes nice
lmao
`am i cool yet`
i have ```js
let permissions = [];
if(role.permissions.has('administrator')) {
permissions.push('admin');
}
if(permissions.length < 0) {
embed.field[7] = { name: 'Permissions', value: permissions.join(', '); }
}
that's my secondary option
why doesn't it add a field?
permisssions
an array length cant ever be smaller than 0
are you think what i'm thinking
oh, pretend its spelt correctly
lmao
imagine you could have inverted arrays with negative indexes and negative length
Technically possible to do with your own class
doesn't that makes it add a field if the role has perms then it'd add a field or
did i get it the wrong way around
?
i knew you could have negative indexes
but the length stays 0 all the same instead of increasing lmao
That's interesting
@digital ibex your code has a lot of problems
what is embed.field
why is the length less than 0
i thought it was only thta oen
also, adding a a[0] only adds one to length
i'm using the object embed
it's fields
it's fields and you can use fields.push({ name: "...
thats not really a problem tho
instead of fields[7] =
it is
field is not a thing
unless the embed worked for you
i assume not
check the documentations?
still a collection
How long do I need to wait for rate limit?
ok
lemme giv u the actual code
yeah, better that way
Coffin doe
maybe you should stick with discord.js

@earnest phoenix there is no ETA for those i think
@turbid bough oh no
how did you ended up getting rate limited anyway
let permissions = [];
if (role.permissions.has('administrator')) {
permissions.push('Administrator');
}
if (role.permissions.has('manageChannels')) {
permissions.push('Manage Channels');
}
if (permissions.length > 0) {
embed.fields[7] = { name: 'Permissions', value: permissions.join(', ') };
}```
thats kinda what it is with a few things moved
how did you ended up getting rate limited anyway
@pale vessel I created 7 apps and try to create the 8 and then got rate limit, and then I try to make the bot on all the apps and got rate limit again on the 6 apps
why lol
no wonder
how much more?
For the coffin meme
coffin meme?
yes
uh
what exactly are you trying to accomplish with the meme?
raid
it's supposed to be embed.fields.push({ name: 'Permissions', value: permissions.join(', ') });
fields is an array
you just push an element
that simple
wha
you can do it!
how much more?
@pale vessel 1 more app and then 3 more bots
i'm using the same way i do for every command which is like that
and ye
fields r an array
so
i add the fields[7] = { object }
oh
you're better off using push

