#development
1 messages ยท Page 671 of 1
yes you can
you can add that:

\


into the dbl page
In the long description?
ye
Okay also it works
I spammed messages
And checked the message size it only chanced 20
Cached*
the error is gone but my bot now wont start
I'm getting client took too long to get ready on shard 0
so i added timeout and disabled waiting for client ready
and its sitting there, adding debug event spams console with channel, user. member, guild objects
I see you are having fun
not really
Does my sharding file for master look ok?
const token = require('./config.json').token
const manager = new ShardingManager('./index.js', { token: token });
manager.spawn(4, 15000, false);```
im starting to suspect theres something incorrect with it
On master, the last arg should be a number
@split hazel false could lead to some serious issue here, not sure tho
that would explain why the shard gets flagged because it took too long to get ready
because you are passing weird stuff as timeout
last time i had it just on 4
thats when the timeout errors come
when it tried launching bot with internal sharding it shows as online but doesnt set status or respond to commands
i think the memory leaked
FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
that error basically means you don't have enough memory to start the bot
right 30gb memory isnt enough you say 
you oofed up somewhere
When havin a bot run on multiple vps, and if i only want to run one instance of the bot per vps. do i need sharding at all? Will the servers get assigned to the bots evenly, no server assigned twice?
@viral spade How big is your bot?
because clustering is not really an easy thing to do
and no, you would need to assign each instance to specific shards
the bot is not big, but i need to distribute the database load. i do a lot of statistics on the database and i want to brake the database up into the shards
what db u use
mysql at the moment
I don't know what you are doing but I'm sure mysql is able to handle most
i do like multiple joins and calculation per message sent n any server
my MySQL instance used to have 8 read/writes per second
And that was when I had leveling
i really do calculate a lot per second
For a github bot that I am making publicly, should I add the docs to the readme or link the docs in the readme to my website docs?
I may have already asked this idk
link the docs
ye, but is it actually at its limit?
and maybe, you could cache that stuff and then write it every x seconds in one run
thats my plan, but flush it remotely
have a remote persistent, and a local in memory db
as long as the item you're caching isn't constantly changing
its a statistics bot, every message leads to a write, every message leads to recalculating, rewriting statistics in my database
I don't see a point for a cache then
isnt that a lot to handle?
For the db? no
If you look around on the internet there are people who can push it to 22k operations per second
but if you have 20k servsers and do 100 operations per message, dont you get close?
I dont know, i have the calculations of a users rank and level, everytime he sends a message, before and after. this calculation involves 4+ joins
async run(message) {
let main = new Discord.RichEmbed()
.setTitle('... Help')
.setDescription('')
.addField('Add ... to your Discord Server :handshake:', '...')
.addField('Join the Support Server', '...')
.setFooter('...')
.setColor(0xFF8A46)
message.author.send(main)
}```
that doesnt respond?
try put the main in curly brackets message.author.send({main})
@viral spade do you use d.js?
y
master?
i hid it, its not blank
.send({main}) won't work
^^^
use .send({ embed: main })
that's .send({main: main})
you could do .send({embed}) if you name it embed
@onyx summit what do you mean with master? d.js master branch?
yes
npm ls discord.js
you have to get master from git
still nothing @topaz fjord
why?
because
because its not out yet
why do I have to swim to not drown?
its beta
why would i need it?
since its a breaking change
he is probably asking why I asked for it
how so?
sec
@viral spade (all on master)
you can specify what shards should spawn in the Client constructor:
Meaning server A can log into shard 0-5 and server B can log into shard 6-10
You would probably have a master telling the children (so the servers) on what shard they should log on
Ok but i only have to assign those number to the shards? then the servers will be distrubuted eually without me doing anything more?
you have to pass the shard ids
https://discord.js.org/#/docs/main/master/typedef/ClientOptions
by the way how tf do you get that many upvotes
so i could theoretically hardcode 2 servers, so server1 logs to 0-5 and server 2 to 6-10., without any master?
you could
how i get that mayn upbotes?
on dbl
well users can get xp by upvoting each other and an upvote counts more if they upvote my bot
and apparently my bot is really liked
which is why i want to be able to scale over 20k servers. before i intrudce new features
if you want to talk about shard assignment you should probably ask in the d.js server
and hope one of the devs is online xD
because you rarely have to cluster over multiple server
well how many servers does a very database heavy bot have usually, before they decide to cluster it over multiple vps?
i show u something
I don't know much about databases, but I would probably rather go for PostgreSQL
so every minute, i count for every user in every voicechannel of any server my bot is in that minute, and add it to the stats
where its starts to be up constantly is 17:26:00, where the voice munites start adding
this 85% disc usage is 30/60 seconds every minute
so its critical already, i can stretch this by only doing this run every 5 or 10 minutes and add 5 or 10 minutes every run
but i have to think of something different^^
i had it on a vps running too, but i have a spare pc in my flat that it runs on nicely^^
for the moment
but it has an ssd and those disc spikes are the same on vps
Get the message object, and use the react method
wdym?
ok ive done that
and then use .react on the message object
no
oh just message.react under it?
const message = await message.channel.send('the docs are great');
message.react('find some emoji');
there's an example at the bottom of it
const filter = (reaction, user) => reaction.emoji.name === '๐' && user.id === 'someID';
const collector = message.createReactionCollector(filter, { time: 15000 });
collector.on('collect', r => console.log(`Collected ${r.emoji.name}`));
collector.on('end', collected => console.log(`Collected ${collected.size} items`));```
yes
message is the message object you get from doing await message.channel.send
then change reaction.emoji.name === '๐' && user.id === 'someID'; to your desired emoj and userID
ok thanks
@topaz fjord
let emb = new Discord.RichEmbed()
.setTitle('... Help')
.setDescription('React to load a category, react to ๐ to return to this message.')
.addField('Categories:', '๐ป - General\n๐ฑ - Generators\n๐ก๏ธ - ... Guard\n๏ธ๐ ๏ธ - Utilities\n๐ - Fun commands\n๐ฏ๐ต - Anime\n๐ - NSFW Anime\n๐ - Logs (coming soon)')
.setColor(0xFF8A46)
const main = await message.author.send(emb)
>>main.react('๐ป')<<
main.react('๐ฑ')
main.react('๐ก')
main.react('๐ ')
main.react('๐')
main.react('๐ฏ๐ต')
main.react('๐')
main.react('๐')```
its saying main isnt defined
did the embed send
yeah
and doesnt react
ok so i did an await before the reacts @topaz fjord
it reacts now
but...
the bot sends this:
An error occurred while running the command: ReferenceError: main is not defined
You shouldn't ever receive an error like this.
nvm i fixed it
it was like something to do together
Just wondering @fossil oxide How much do you charge?
He doesn't charge. You contact him to put a job offer in #434058442764714002
Go in dm with him
its for jobs, not collaborations
That's... not how #434058442764714002 works smh
but actually, why isnt there a channel for collabs
yea i know that
what they mean is "i'll do the login, you do the rest, i don't know how to do it so i want someone else to do it for me"
-help
This channel is not for running bot commands @tall perch
Okey
@onyx summit if you have suggestions you can make them on our github repo
lol faq 1
Click the link to get more information on the question:
thanks !
can you link it
Wdym?
Feedback and bug reports go here: https://github.com/DiscordBotList/issues
thx, posted it
How do you get the node version again?
in the console or in code
Code
node -v in shell
or
process.version in code
How can I use emojis in a server on my bot?
normal: <:name:id>
animated: <a:name:id>
discord.js:
im getting this error
(node:78416) UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Message
at item.request.gen.end (C:\Users\\node_modules\discord.js\src\client\rest\RequestHandlers\Sequential.js:85:15)
at then (C:\Users\\node_modules\discord.js\node_modules\snekfetch\src\index.js:215:21)
at process._tickCallback (internal/process/next_tick.js:68:7```
what is it saying?
unknown message?
the message was probably deleted or you requested a message that doesn't exist
so its in the messagedelete bit?
deleting/reacting/fetching/any kind of interaction with a deleted message or invalid id
How did you delete a text channel in discord.py
and how can i delete a specified channel again
it's not quite a dev issue but, my bot isn't appearing as "online" on it's DBL webpage, though it is online on discord and operational. I've tried doing a DBL Webhook test which was successful.
Does anyone have any ideas as to what wrong?
@wild thorn is your bot on this server?
Yes
apparently not ๐ฆ
What ya mean
I can't @ mention it
it's webpage is still available though https://discordbots.org/bot/580530774692986892
My account???
no I meant Nazrin
I don't think your account is relevant to development
rip, gotta fix that, or post stats (I think that will make it show as online too)
that's not good?
it should only dm when there's incorrect permission to inform a user it has incorrect permissions
Might wanna dm mods and fix it
Question how can I replace the status of the bot/user to an emoji?
Cause it just comes back as online, offline, idle, dnd
ok
@winged thorn i need the await channel.delete() to delete a specified channel
because an other command is creating a channel named after the ctx.message.author.name
so i need the channel to delete the channel ctx.message.author.name if you understand
cant
Why not
cant get it by id
why not
An other command creates a channel named after that member
So get it by name instead
THAT is what i dont remember how
Use discord.utils.get
maybe this will make you see what i mean
if ctx.message.channel.name == ctx.message.author.name: the code is wrong btw
If you have duplicate channels obviously discord.utils.get won't work if you try to get it by name but
Use discord.utils.get
or you can loop through every channel in the guild and try to find one with the same name
bot.on('messageDeleteBulk', async(messages) => {
const emb7 = new Discord.RichEmbed()
.setTitle(':wastebasket: Bulk Message Delete')
.setDescription('A user has deleted a mass of messages.')
.addField('Guild:', `${messages.guild.name}`)
.addField('User:', `${messages.author.tag}`)
.addField('Channel', `<#${messages.channel.id}>`)
.addField('Time:', `${messages.createdAt}`)
.setColor(0xF44336)
.setFooter('... | Logs', 'https://file.coffee/WdTuqTwGF.PNG')
bot.channels.get(`609829032644706352`).send(emb7)
});
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'name' of undefined
how is this meant to be done?
error is on the Guild: line
I havent looked at it, but I'm guessing messages is a collection
you need to get a message
yeah it is
the others will also error
will it work with messages[0] then?
@winged thorn channel = discord.utils.get(ctx.guild.text_channels, name=ctx.author)
how do you suggest i get it into await channel.delete()
you can use .first()
Can you make a bot leave a server with the guild ID?
Like client.guilds.get(guildID).leave()
client.guilds.get('id').leave()
i did that
works
thanks @amber fractal
Well ye but I'm using args wouldn't that be a string @onyx summit
ids are always strings
strings? yes
what u trying to do
I'm trying to make a bot leave a guild by the guild ID but wait 4 seconds so it can send an embed
just send the embed and then leave?
You're not understanding
yes
I want it to wait 4 seconds
client.guilds.get(input).leave()
}, 4000)```
ye that works too
async def close(self, ctx):
channel = discord.utils.get(ctx.guild.text_channels, name=ctx.author)
await ctx.channel.delete()```
This doesnt work 100%, it can delete but it just deleted the channel you typed that in and not the channel named ctx.author
I tried `await ctx.channel.delete(channel)` but only got an error
How do I check if my ID matches an array of IDs?
Would I have to loop through the array?
[array of ids].includes(the id you wanna check)
Mk
So I could do something like
if(!client.settings.bot_dev.includes(message.author.id))
Or something like that
if bot_dev is an array yes
Okay thanks
(node:22868) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 message listeners added to [Client]. Use emitter.setMaxListeners() to increase limit
what would this error mean?
you have 11 listeners to the message event
this is not very good
<client>.on('message'......
is one, and you have 11 from that
oh okay,, yeah not good lol. thanks
@onyx summit setTimeout(guild.leave, 4000) won't work
> class Guild {
... constructor(id) { this.id = id; }
... leave() { console.log("Leaving guild", this.id); }
... }
undefined
> const g = new Guild("123");
undefined
> g.leave()
Leaving guild 123
undefined
> setTimeout(g.leave, 4000)
Timeout {
_idleTimeout: 4000,
_idlePrev: [TimersList],
_idleNext: [TimersList],
_idleStart: 54613,
_onTimeout: [Function: leave],
_timerArgs: undefined,
_repeat: null,
_destroyed: false,
[Symbol(refed)]: true,
[Symbol(asyncId)]: 677,
[Symbol(triggerId)]: 4 }
> Leaving guild undefined```
you need setTimeout(() => guild.leave(), 4000) or setTimeout(guild.leave.bind(guild), 4000)
may want to explain why
guild.leave isn't bound to any instance
guild.leave() passes the instance
but just getting the leave function doesn't
so you need to bind or create a closure that calls guild.leave()
yes, I get that now
I had similar issues with that in ts, by doing
event.on('stuff', this.somefunc)
ts is a superset of js
bec it was out of context 
it's js with static types
Ik
Anyone looking for python bots help?
No

I also offer my assistance services to those using discord.py
For the low low price of 1 cookie
btw can you advice me some cloud services?
bcuz Im lookin for a free way to save some user data into a cloud
Somebody know how make a bot make a channel?
what language and what library
discord.js javascript
Here is the relevant documentation
Ok, thanks!!
@earnest phoenix it's discord.ext
very bad way to hide your token
do you have the module installed?
if you don't have discord.py installed you can't use it
which version?
so u don't need to use this
python3.7 -m pip install discord.py
import discord
client = discord.Client()
@client.event
async def on_ready():
print("a")
client.run(token)
then it should be working
@upper salmon im trying
now
btw keep it client or change it to bot ?
@upper salmon
if you want
@upper salmon theres a difference between discord.Client and commands.Bot
this is for discord == 1.2.2
yeahh
Every time i do something i need to get errors
discord.Client only allows you to use events
what to change to
@earnest phoenix are you sure you got the right module?
bruh
py -m pip install discord.py --upgrade
Also first question: Do you have any solid knowledge with Python @earnest phoenix
and try again
@earnest phoenix stop revealing your token
@broken shale small
put it in a .env or something
its bot token
I think you should learn a bit more py before making a bot
And bot token can be very powerful
you don't realize how bad leaking your bot token is
So keep it SAFE
if people get hold of your bot they can make it do literally anything, they can make it leave all of its servers or nuke all of its servers, I'd suggest you reset it and properly remove it when you upload a screenshot
and if you don't want your server raided and all channels deleted you better not fcking share it
- bots, if their token is stolen, you can be banned because of it
A small thing I've had with my ping command. When I run channel.send(...).then((msg) => {...}) and minus msg.timestamp - message.timestamp, I sometimes get a negative number. Anyone know how to fix this, I could use Math.abs but I don't know why it would be negative in the first place
show code
// eris lib
return message.channel.createMessage("Pinging...").then((msg) => {
return msg.edit(`${Constants.EMOJIS.PING_PONG} Pong! Response time: \`${msg.timestamp - message.timestamp}ms\``);
});```
This is mine js msg.channel.send(something).then(x => { m.createdTimeStamp - msg.createdTimeStamp })
different lib
oh you're eris
your on d.js
noticed
ye
I believe it does the same on both libraries, it might be something not even library-related
I'd have to check
fun fact, that kind of a ping command is not accurate
well subtraction obviously isnt lib related
lol
try message - msg
you'd have some sort of a stopwatch and you'd time how much time it takes to send the request
cause subtracting the timestamps includes internal api latency
ahh, okay. I'll try it out
True but me: Lazy asf
yeah, it's not like it's a big difference
plus or take 5% marginal error
pretty much
As my message has been lost, I will post again.
Discord.js
Will someone please recommend a (good) NPM package to auto detect a language and translate it?
Ping with response please!
just use the google translate api
How do I find out what role was removed? In Discord.JS
changes: [ { key: '$remove', old: undefined, new: [Array] } ],
there is an event for it
lol
another way you could do it is that you store the roles before the delete and after the delete and compare their values
just check for difference in roles before and roles after
Should I run my bot and website together as one instance?
Because if my web dashboard contains code that needs to be sent to the bot, how do I do that?
ipc
ipc?
Is an option
i just share the same database on both
Right but lets say the dashboard I can send messages through
and send a message over pubsub to notify the bot that data was changed
Intern process communication = IPC
How can I coordinate that with the bot saying to do x
send a message to the bot which says "do x"
then eval it
you send a message to the bot
You could either have predefined scenarios that are ran when the dashboard sends something specific to the bot
The message or the code?
a message can be whatever, eg {"action": "send", "content": "hello world"}
How do I set that up tho @onyx summit
Right
that's a massive security hole
Would you guys happen to know how I can make those functions and then send that?
eg you send to the bot "eval bot.guilds.get('id').channels.get('other id').send('${message}')"
then users get a full RCE on your bot
if they set the message as ' + bot.token + ', they have your token now
Loving the docs. Why does nothing tell me what I need to do to get started lol https://vinniehat.is-inside.me/HHdXlpQy.png
There is an example folder in the GitHub
sending data can be just an http server on the bot
then the website does a request to that
or eg a pubsub thing such as nats or rabbitmq or even redis
What would you use?
i use nats to communicate between bot and website
How do you connect your bot with the dashboard?
and just write directly to the database from the website
@lusty dew We already said Oauth2
I thought you guys meant with users
My bad
I'm still trying to figure out this emoji ID thing
user presses save on the dashboard -> settings get sent -> website cleans input, writes to db -> website notifies bot about which guild was updated and by who
so the bot can write that to the log channel
Ok so let me get this straight. To tell the bot to run a certain function with x parameters what thing do I use?
Gotcha
i just send json payloads
Confoosed
Ok is there a way that I can make a HTTP request with the bot? Like change the data of the url from the website, and then the bot just waits for it automatically
that's what handles messages on the bot's end
This is way to confusing for me lol
https://gist.github.com/natanbc/6cceabd402ff3a6cdda911046fc95567 and this is on the website's end
Can't I just run a second instance of the bot and then run the specific function?
Blank 2nd instance
1st instance has the main code
2nd instance has the predefined scenarios and functions that connect with the website
Ok, but would a 2nd instance be bad/allowed?
ยฏ_(ใ)_/ยฏ
sounds like overengineering to me
also you'd need to login two instances
It would be allowed, but it makes even harder to manage ratelimits
which would double startup time
aka your library won't be able to handle them good
Ik its just then I don't get the separate github repos and organization
Hey
Unless they are in the same folder
Hey
Just found out the bots have a server and now Iโm here
Nothing much
i just have a bunch of things like this on my bot that handle messages from the website
Woah
when i used to run my old public bot, i had my bot and website separated each to their own server
the website had small websocket support so the information between the bot and the website could be exchanged
if that helps
How would I do that?
in node? no idea, i did everything in .net c#
I still don't get why you would choose IPC but ok
just google "node websocket client" and "node websocket server"
because you need to move data around
IPC is just a generic name
Is that safe tho?
inter process communication
And actually like good?
it's as safe as you make it
if you run it without ssl and without authentication then no
no, normal websockets are not encrypted
Ok so the website is the server
use wss with an auth key and you're all g
just let something like nginx terminate the ssl connection
And the bot is the client?
Uhhh
so complicated talk here
and get a certificate from let's encrypt
I can actually learn something 
I have HTTPS
then you can just use that
i would say the bot is the server, so the website can make request to it
or regular unencrypted websockets if both processes are on the same machine
making the website be the server is easier imo
it already needs to handle http requests
How would I make it encrypted with HTTPS?
And can the server recognize the clients request and do something?
if not, the same way you'd do https for your domain
Like if the client says ok do x function with y variables
websockets are a full duplex channel
Can the server interperate that as console.log(y)
both sides can send and receive at the same time
Ok so I don't even need WSS?
if both are on the same server and connect via localhost, no
you should still have authentication
Right
When you forget what you were trying to do oof
A dashboard
No decided not to do that yet
I want help with that tbh i don't wanna do it all on my own
Wanna have a partner
Unless my other bot Dev knows html and CSS i don't think he does though
Oh yee
User info command
And info cmd
Does d.js master have a thing for nitro?
yes
wym by nitro
what thing for nitro
I'm talking about if they have an active nitro subscription
Ye that's for boosting iirc
I don't know how to do the OAuth thing to use it
I prob would cuz Im bored as fk and I would like to use mutualguilds
mutual guilds aren't sent over oauth
How would I setup OAuth to use this?
you need to loop all your guilds and check if the user is in there
How do I implement a vote-to-use-this-feature system?
you don't
Wait what
oauth2 is explained here
Integrate your service with Discord โ whether it's a bot or a game or whatever your wildest imagination can come up with.
Then how do I access UserProfile
there's no way to get an user's profile at all
unless you make an userbot
you can get parts of that with oauth
but not in a single request
Then why have it in the docs?
because that's for client accounts
which can be used with d.js
but will get you banned from discord
Hn
So they are promoting things that can get you banned
Oof
Okay thanks for the help!
lmao
Called laziness
Ah mk
if you try getting help with that you'll probably get nothing

Mk
Kinda sad you can't get if they have active nitro oof
Don't people who boost get a booster role automatically or do the server owners have to make the role?
@broken shale its actually not laziniess its actually just the fact that d.js follows semver
so v12 already has all user bot stuff removen
but stable ( eg v11.5 ) cant just throw it out
Show code and error someone will be able to help you faster and easier @alpine lark
How can I compare if the users account was created to today's date
javascripts date object
Discord.py > Discord.js
Hm?

1. it's not js

if(client.user.createdAt > Date.now()){
message.channel.send('Im old!')
}else{
message.channel.send('Im young')
}
I evaled that and it returned the I'm young thing
import time
because a user will never be newer than now
True
a user can't have been created in the future
Didn't think about that
All I'm trying to do is check if they are older then 1 year and if not then format the time in a different way
get the difference between current time and user account creation
I am trying to figure out how to delete a message after certain time If anyone knows
and check if it's greater than 1 year
How would I check if it's greater then 1 year
you'll get a difference in milliseconds
Okay
compare that to how many milliseconds you have in a year
m!eat @fast tendon
Date.now() - createdTimestamp >= 31536000000ย ? true : false;
Use whatever you want. It's your code.
Yes.
Also, createdAt returns a date, you might wanna use createdTimestamp instead.
Date objects are converted to numbers when needed
both work
Okay
why does no one know how that works
it says it cannot read the property that is query of undefined
so the object you are attempting to get query from isnt defined
How is it not defined tho
That question is very vague
wdym
What language are u using, wdym by open โforโ a folder
Ohhhhhh
You can open a folder by using open <PATH> I think
Itโll open in file explorer
Where is that
I suggest you go through some sort of terminal for beginners guide online
Anidiots.guide is a Discord bot guide
Iโm talking about one that teaches you how to use the terminal
Iโm on andiots
Also donโt use anidiots.guide to make a bot, itโs a really bad option
Then why is it open in the background
So donโt follow its tutorial?
Iโd suggest this for discord.js โ> https://discordjs.guide
A guide made by the community of discord.js for its users.
Anidiots.guide is made for those with imposter syndrome
Oh
The one I showed you is the official guide and itโs audited constantly by lots of active devs in the community
This?
Yeah, use that site
But to answer your question you need to do:
open <PATH-TO-FOLDER> to open a folder within file explorer, and cd PATH-TO-FOLDER> to go to a folder in the command line itself
If you donโt know js, you should ideally do one of those short guides, although Iโd recommend options 2 or 3
Option 1 doesnโt teach you shit, Option 4 is made for people who already know JS, and Option 5 is well Google
So Options 2 and 3 r the best
K
when i try sending an embed with some links such as this:
{embed: {description: `[Promise](https://google.com)<[Array](https://google.com)<*>>`}}
the result ends up being: https://ss.vysion.cc/19r2gftojz6ltd4n.png, can anyone explain why?
because discord's parser is garbage
i assume it's a bug
bc it's parsing <> lmao
i would have assumed \< and \> are workarounds
Help Iโm big dumb
the package doesnt exist on npm
?
take time to read the errors npm gives you
You know what Iโm gonna do this tomorrow Iโm so tired
Too late 
Idk
Then why respond?
Show me the code
Ok
But I, doing:
message.guild.members.get('479603748382179329').highestRole
It works with .roles
Let me test it
Thatโs why Iโm confused as to whatโs undefined
that's not how you access it
message.guild.members.get('479603748382179329').roles.highest
Oh?
No
yes. look at the docs
You use member.highestRole
are you using dev version?
Dev version and google feud is correct
or master
Its member.highestRole
that is stable, not master
dw I'm guilty of that as well lol
np!
Also when did stable get clientStatus
I thought master only had that
Last time I checked master did only have that
11.5? 
Dang okay
Honestly I switched to master cause of clientStatus and the other cool features lol
Okay ima go have fun with moment 
Would I be able to assign a variable a new value inside an if statement and use it out of the scope of the if statement?
yes
Iโm trying to check if the users account age is over a year and if so then itโd format it a certain way
And if it is younger then a year itโd format it a different way
let variable;
if (something) {
variable = 4;
}```
Okay
My question is could I do something like:
let time;
if(Date.now() - member.createdAt > yearinms){
time = moment(member.createdAt).format('YY')
//Format: Example. Account age: 3 years
}else{
time = moment(member.createdAt).format('MM/D/YY HH:mm:ss')
//Format: Example. Account age: 05/09/18
}
God that took forever to write lmao
Then do
.addField('Account age: ', time)
yeah that works
you can also do it with the ternary operator
Oh?
.addField('Account age: ', (Date.now() - member.createdAt > yearinms) ? moment(member.createdAt).format('YY'):moment(member.createdAt).format('MM/D/YY HH:mm:ss'));
kinda ugly
Smh why did I not think of that
I was thinking of using that for something else lol
Honest though
The if statement looks better to me
A lot more clean and easy to read imo
Will js support 3.154e+10
That time format
I think it will
Really?
No way
Ok
2|clap | at Object.run (/home/panda/Clap Bot/commands/uInfo.js:34:48)
2|clap | at Client.client.on (/home/panda/Clap Bot/clap.js:50:88)
2|clap | at Client.emit (events.js:198:13)
2|clap | at MessageCreateAction.handle (/home/panda/Clap Bot/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
2|clap | at Object.module.exports [as MESSAGE_CREATE] (/home/panda/Clap Bot/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
2|clap | at WebSocketManager.handlePacket (/home/panda/Clap Bot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:391:31)
2|clap | at WebSocketShard.onPacket (/home/panda/Clap Bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:418:22)
2|clap | at WebSocketShard.onMessage (/home/panda/Clap Bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:274:10)
2|clap | at WebSocket.onMessage (/home/panda/Clap Bot/node_modules/ws/lib/event-target.js:120:16)
2|clap | at WebSocket.emit (events.js:198:13)
2|clap | at Receiver.receiverOnMessage (/home/panda/Clap Bot/node_modules/ws/lib/websocket.js:789:20)
I keep getting this error I logged member to make sure it isnโt member
Hereโs the code:
Ok
let member = message.mentions.members.first() || message.author;
member can be a GuildMember OR a User. message.author is an instance of the User object. Either do
let member = message.mentions.members.first() || message.member or let member = message.mentions.users.first() || message.author; so member is always the same type
Okay thanks
You are trying to access member.user.bot, Users do not have a user property, only GuildMembers do
GuildMember
Okay thanks
np 
Forgot the mixture between the two donโt work well yikes
How can I get the bots cpu usage?
D.js master
what operating system
My friends hosting service is Ubuntu iirc
That only gets the cpu time doesnโt it?
var os = require('os');
console.log(os.cpus());
console.log(os.totalmem());
console.log(os.freemem())```
Or whatever
thats with os
with os-utils
var os = require('os-utils');
os.cpuUsage(function(v){
console.log( 'CPU Usage (%): ' + v );
});```
yep
Ah mk
the os-utils package looks very poorly made though.
ยฏ_(ใ)_/ยฏ
How do you convert bytes in to MB and GB
/ 1024
Ah mk so like
let bytes = 1024;
let mb = bytes / 1024
let gb = mb / 1024
*i suck at math btw so Iโm probably wrong
let gb = mb / 1024
but to get to gb you need to divide mb by 1024
that works too
whats the easiest way to store levels in js?
Cause it can spike from mb to gb one day
@wide ruin levels as in experience?
yeah
@lusty dew if (mb > 1024) display gb
else mb
ยฏ_(ใ)_/ยฏ
use a database like mongodb
is a json easy?
json is prone to corruption and super slow
so how do i set up a db?
atomic json is not easy lmao
this seems quite good
but tbh
sql gang
This doesn't look right
The mem usage and cpu usage I mean
I know why nodejs isn't working I fixed it already
let memUsage
if(process.memoryUsage()['heapUsed'] > 1024){
memUsage = process.memoryUsage()['heapUsed'] / (1024 * 1024) + ' gb'
}else{
memUsage = process.memoryUsage()['heapUsed'] / 1024 + ' mb'
}
Oh wait
I see what I did wrong
Cpu usage though idk what I did wrong
@winged thorn
Os-utils is being weird
No that isn't correct
Idk whats going on there either
I thought I fixed it but Ig not
I'm using process.memoryUsage for the mem usgae
The cpu usage I guess is plausible if you're only running a bot
But in the pm2 console it says 4.6%
hm
Not all that wonky shit
Well idrk how that package works, maybe some googling would solve your problem
Oof
So I got a conundrum here. I wanna differentiate between kicks and normal leaves, so I was using the audit logs and checking the last kick entry. Works well so far
The thing is, if a user got kicked, joined, and then left again it would still think it got kicked, since in a short time no new kick entries would've been added to the audit logs
But then I decided to check the time the entry was created and compare it with the time at which the leave event got triggered and that always varies, and my bot sometimes lags
I have no idea how to do this properly
The fact that the kick and leave events are the same is a pain
I usually see if the difference between last audit log entry and the time of event being fired is >= 500 milliseconds
Is half a second enough?
Works well so far for me, at least 
That's more than 500ms for me RIP
It always varies
Imma give it like 1 sec difference lol
2 ftw
Yeah sounds about right lol
Its a bit janky but oh well
I have no idea what else to do instead honestly
I just bit the bullet and decided to only log kicks made through my bot
Lmao sounds easier. Can't do that unfortunately
rip
Okay I got CPU usage working
But mem usage isn't working
Still
@tight heath 1024Bytes = 1MB?
yes



