#development
1 messages · Page 670 of 1
Then how do I vote lock the commands that is what I'm trying to do
well, you have to listen on the vote event, then store every new vote anywhere, and then when someone is running the command you check if he is in your db
^
don't vote
I can just setup the vote server for you xD
Then delete it

I'm seeing that
If it makes you feel better I'm trash at webhooks and API's, I usually try to avoid them 
neither have i, but they are not hard to understand lul
I haven't read up on em tbh
i dont like vote locking
It's basically just a post request
I should but eh
JSON API's are a good learning point though. If you're a weeb, try setting up the nekos.life API or even random.bird if you're a bird lover like me
yeah i have my own api as well
vote locking is nasty
ok
Thank you
no one is telling them to change it
I'm also vote locking a feature to prevent spamming lol
lol
Vote locking is also a good way to low-key promote voting, so I mean, why not haha
anyway, is level a file based db? Never used it
Idk
level?
yeah leveldb is file based, but its very efficient
votelocking is bad in my opinion; it's turning away users from using your bot because people don't wanna bother, and it's equivalent of having to watch ads in mobile games in order to get something, except here the bot owner isn't even getting any money despite DBL putting ads on your bot page 🙃
Can I get help
Can I get help
Oops lag
but level doesnt support multiple clients last time i checked, which is a no-no for sharded bots
Just ask what you want holy shit
sqlite is a good solution for most discord bots
Yes for tickets
nah I'm just seeing that Haruna switched to level db
Tickety
I agree with Tim, SQlite, MySQL, mongoDB are all really good
I don't think this is the right channel
I prefer SQLite and MySQL
Not here
Where did
I don't give a fuck what that bot has as prefix
kun go to general if you wanna figure out a bot prefix, or just go into the testing channels and ask around there
Nothing related to developing
Chill
I'm chill
Try the support server @earnest phoenix
@tight heath why mmmm? PostgreSQL good 
jesus christ we have a troll
@onyx summit that's the point
I GOT TO HERE
Yas
No
this isn't a support server for any bot, this is simply a bot listing service
postgres good
STILL WRONG CHANNEL
cry stop crying
THIS HAS NOTHING TO DO WITH DEVELOPMENT

@earnest phoenix no it isn't pls stop caps or i will eat all your pancakes
okay at least we all agree that psql is good
postgres is genuinely nice for big scale projects
No not the pancakes 
@earnest phoenix Go to the bot's support server --> https://discordbots.org/bot/352854019934257156 (Click the white Join Support Server button, not the Join Discord one at the top of the page)
And ask for help there
I fucked up
ye we know
definitely
we've been trying to tell u
I said !help and now I got 100 DMs
thats ur problem

is that enough proof that we're a bot listing service and not tickety support?
But this is the support server 
@opaque eagle how is Excuse defined?
it says right there "Discord Bot List" 
you forgot to throw an exception
class Excuse { constructor() { throw null; } }
interface Excuse {
reason: string;
howLongItWillLastBeforeHavingToFindANewOne: Date;
}```
thanks for the hint
class Me
{
constructor()
{this.sad = true;}
}
kthx
async unSad() { await this.getHappy(); this.sad = false; }
Why did this turn into talking about vote locking to this
because why not
this is serious dev talk right here
weed lol
@tight heath ReferenceError: getHappy() is not a function
oh huh
TypeError: Cannot read property getHappy of undefined```
LOL
they say console is slow
That's identical to js while (true) { console.warn('reeee kill meee') }
Console is indeed slow
afaik console logging in an endless loop will fill ram very fast
Also Unexpected token } @onyx summit
Maybe that's fixed
You've got an extra one
k
To lazy to turn my computer on lol
const { promisify } = require('util');
const sleep = promisify(setTimeout);
async getHappy(time) {
await sleep(time);
await this.city.stores.find(s => s.has('chocolate')).buy('chocolate')
.then(c => c.eat);
return true;
}
u forgot the function keyword
no it's in a class
it's just async getHappy(time) rn
i just cba to write that
oh
otherwise the this would be pretty pointless too lol
:)
Error .buy()
^
No vendor will sell you chocolate```
what
@onyx summit I'ma figure this voting thing out
but
But what?
I wanted to clone it rn
Clone what
Clone what
Sure to ahead
Hm?
Really noob question: how do you handle storage in node.js?
I don't need to persist data, I already use a DB for that. I want some runtime memory to introduce a cooldown on certain commands.
Okay added in the token and auth into my bot.json @onyx summit
just use a variable and pass it to other functions if needed @lucid iris
I think a Map is what you would need for cooldown
dude I said in vote-server/config.js
depends
but I will just get it out of there lol
Oh sorry
Map seems to be the best option
@onyx summit do you want me to change it
I already did
i use Sets and timeouts now. its a horribly inefficient method but i dont care enuogh to rewrite those 7 lines
yes, remove that stuff from your bot, bec port 30 001 is blocked xD
fixed it for you, but just saying: ' is not allowed in json
so basically you should be able to do
// your command stuff
if (! await client.voted.hasVoted(some user id)) console.log('that person didnt vote');
Okay thanks!
more info?
It just keeps sending the message that if they haven't voted
Won't send the embed if they already have
And I voted myself to test this
What?
change it to https://webhooks.chilo.space/clap/vote/
When i upgraded to node 10, i am now getting
Error: Cannot find module '/root/node_modules/.registry.npmjs.org/sqlite3/4.0.2/node_modules/sqlite3/lib/binding/node-v64-linux-x64/node_sqlite3.node'
Hello
did you reinstall everything?
Nope, i upgraded npm using the n package
then reinstall node modules
should i just run npm install
you can press on "test" @lusty dew to vote again
on the edit page
I would first delete node_modules and then npm i
if you change node versions you normally have to recompile everything
alright i'll try that
player.brawlers.forEach(e => {
var resultados;
if(e.trophies > 500){
let resta = e.trophies - 500
let division = resta / 2
let final = parseInt(division)
resultados += final
// message.channel.send(resta)
}
})
message.channel.send(resultados)
}
Don't work
resultados isn't definied
why
@onyx summit it's still asking me to vote
bec you didnt define it @real helm
is define in the forEach
but its not defined xD
@real helm you're using it out of scope
But if put the message.channel.send the bots sends the results a lot of times
and I like that it only send the results 1 time
if you do var resultados; resultados will still be undefined
yes, i know
scoping issue
he is not using it out of the scope
i put now a let
at least in normal browsers
> function callIt(f) { f() }
undefined
> callIt(() => { var x = 1; })
undefined
> x
Thrown:
ReferenceError: x is not defined```
even in normal browsers that'd error
var isn't global
and never was
it's always been function scoped
im getting npm ERR! path /root/node_modules/.staging/better-sqlite-pool-1347399d/node_modules/lodash npm ERR! code ENOENT npm ERR! errno -2 npm ERR! syscall rename npm ERR! enoent ENOENT: no such file or directory, rename '/root/node_modules/.staging/better-sqlite-pool-1347399d/node_modules/lodash' -> '/root/node_modules/.staging/lodash-74c86b5c' npm ERR! enoent This is related to npm not being able to find a file. npm ERR! enoent
@onyx summit I even had one of my beta testers try the vote locked commands and have em vote then try it again it's not working for them as well
you did set the url in dbl?
but yeah
- wrong scope
- would still error, you didnt gave it a value
@onyx summit Have you checked the vote-server logs lol
yes
Ye same
https://webhooks.chilo.space/clap/vote
the slash at the end was too much
Ok
now every module i try install i get errors
block scoped !== function scoped
Socket hang up please help me :/
(glitch) i didn't fix
solution: don't use free hosting
^
but every free hosting is bad 🙃
well a public free service is bad
I get free Azure for a limited time cuz of GitHub Student
but free doesnt mean bad 
so is Azure bad
azure isn't free though
they provide you a service without fees because you're a student and they can offer you education through that
🙃
aws (free trial) is limited
can you click on test again?
Now will it work for everyone else?
got everything working by deleting package.json aswell and instlaling every module one by one
i heard on discord.js master reactions are now seperate to the message object, how do i fetch the reactions object?
a bot dev?
hehe
just made me laugh that we read syntax errors in here all the time
to get one from a website cracked me up
what syntax error?
İ fixed...
Hello. I'm trying to set up my bot to be configurable (with SQLite) but let's just say, the documentation isn't that helpful. I already have the connection set up
const connection = mysql.createConnection({
host : '#',
port : '3306',
user : '#',
password : '#',
database : '#',
charset : 'utf8mb4'
});
how do I check to see if a server's value is marked as, let's say 1 then run code? Also, how do I set that value in a command? Thank you! (By the way, please ping me if you respond!)
@wooden lance iirc you’ll generally be interacting with the DB via a “cursor” object in your language of choice
Fetching a value from the DB will generally be done w a “SELECT” query and assigning will generally be done with an “UPDATE” query
if you haven’t used SQL before the queries aren’t too bad but the general pattern is using the cursor to make a query, then fetching the results as needed and acting on them
I haven't used databases before. And, I don't know what a select or update query is.
ah np
I've tried using a db before, it didn't work.
SQLite as well?
I haven't successfully got SQLite to work before either.
ah
do you have a way to interact with the server in the command line?
or otherwise*
yes
cool
With python at least
@wooden lance and you haven't been able to get a response from it yet?
wait, the server (as in vps) or sql db?
lol don't worry about it
being insecure about asking for help won't serve any benefits, you've gotta do it once or so
yeah
i guess like
what resource have you been using to start up the sql DB so far
and where are you hosting it from as well (local or online or)
start the my sql server?
yeah
it's up 24/7
ah cool
it's managed by a company with my domain name
hosting it online
is it mysql or sqlite?
mysql
ah ok
do you have an interface like phpmyadmin that you can interact with it through or is it purely command line
wait, give me a sec, i do think i can get SSH access to it
oh oh cool
additionally are there any errors that appear when you try to connect or is it just not responding at all
i haven't actually tried starting the bot up with that connection
oh
you could try something like mysql workbench to access the DB
might be a good way to start fiddling around
should be able to log into your database through that
and start creating tables and things
Okay
if that works then would definitely suggest getting familiar with some common queries, select, insert, and update are the most common ones so knowing those is key
After I have done that, what code would I need to check to the db for a server's ID and a value? And if the value = 1 run code?
that would most likely be a select query
you could build a table which tracks server ids along with a one bit flag
okay
@stone dust, this is gonna seem like a very stupid question, but what is the code for the select query? I have not used them before.
And the discord.js docs make no sense to me
how do i make the ShardingManager of the master process available to my sharded clients
to connect to the server? dont think so
assuming the credentials and port num are correct it’s that or the server is unresponsive
or something else
hmm
can i have mysql on my bot's vps @stone dust?
as in a local server? so just on the same vps?
or quickdb
yeah any of those should be fine to host locally assuming the port isn’t occupied
No problem, sorry I couldn’t get to the bottom of it but best of luck!
thanks!
I am having some problems with quick.db on javascript. Anyone know what I can do to fix this?
/root/DiscordBotApp/node_modules/better-sqlite3/lib/backup.js:9
return async function backup(filename, options) {
^^^^^^^^
SyntaxError: Unexpected token function
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/root/DiscordBotApp/node_modules/better-sqlite3/lib/database.js:51:34)
Does your Node.js version support async?
One message removed from a suspended account.
nothing is returned by the function so gold isn’t set to anything
or there’s no error so console.log just logs something falsy
I noticed
let e = array[i]```
makes it loop over a non existant element aswell, so if have 3 elements, it will loop over a 4th one that doesnt exist
do i just add -1 to array.length?
or just
remove the operator that says to continue if i is equal to length
length starts with base 1
arrays with base 0
ergo length is always going to be +1
@commands.has_permissions(manage_server=True)
```why it does not recognize the `manage_server`?
server -> guild
@wooden lance Did you fix that error: https://discordapp.com/channels/264445053596991498/272764566411149314/609490456287510528 ?
@warm marsh no, i didnt notice the response. do you know how to update node?
Depends, Are you on windows on Linux?
Linux
What version is currently running? node --version
I doubt node is the main issue behind that error but, If the distro of linux is Ubuntu try:
sudo apt-get purge node* then curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash - change 12 to a version you want, 12 being the latest once chosen run sudo apt-get install -y nodejs
Although, I don't think you need to purge the old one.
What is the best way of limiting memory usage of my bot and sweeping useless things from memory? My memory climbs to about 1.1gb (from 600mb per shard) when it was online for around a day. im using discord.js
master
I restart mine daily if that helps
auto reboot every day
Is there a quick way of implementing that?
And as already mentioned earlier, you should limit the caching of messages if you don't really need them
You can define some cache options in the client constructor
Will probably have to look at those in the docs then haha
And i really dont need to cache messages as i fetch them from api anyway
i also have a packet event that fires messagereactionadd, delete and remove if the message is uncached
messageCacheLifetime
messageSweepInterval
messageCacheMaxSize
I played a bit with those and my ram doesnt really rise anymore
May i ask for your recommendation for the setting of those?
I have ```js
messageCacheLifetime: 60,
messageSweepInterval: 61,
messageCacheMaxSize: 20,
(master)
but I think you will have to try your owns
tbh I just mixed some numbers I thought that might work
lmao
Are there also sweep options for users?
because i dont get users from cache anyway, i do it through the API
not that I know of, but you can sweep every collection. you would probably sweep them if their last message was like really old
I should probably add user sweeping on an interval
you can define that sweeping in the client options
but you can sweep users yourself
so, theoretically you could sweep users if your ram gets too high (but prevent spamming it when your ram goes higher without the users fault)
i just keep everything cached
cool
you can have it run with less than 100mb ram at 2k guilds if you know what you're doing
also, "high" memory usage can be just the gc being lazy
Should i sweep users every couple hours?
and not running all the time to avoid pausing frequently
for example, delete everything except guilds, then use the raw event for messages, and if message matches a command, you can optionally fetch the channel, the user, the member, and everything else you need
and how much its cleaning
yeah i use the raw event for messagereactionadd, remove and delete
in garbage collected languages it's normal to have memory look like this https://i-was-scammed-by.dabbot.org/72dSsrz.png
(that's over a week, so it might look like memory is always rising but it isn't)
depends on how much memory that is
I would recommend https://developer.ibm.com/node/monitoring-post-mortem/application-metrics-node-js/ do have stats (including gc stats)
for the last 6 hours, it looks like memory is only increasing
if its 1gb ram at 1k guilds for example, then its not normal
but zooming out shows that's not the case
it goes from ~1.1GB to ~1.4 then drops back to 1.1
the thing is that d.js caches a lot of things by default, most of them you might not actually need
out of 1.5gb allocated for the process
so there is a lot of room for ram improvements
agreed, d.js is not bad, but without some tweaks it eats a lot of ram
that you can do as the end user, even if they are techincally not suppoerted methods
with my method i could keep my bot stable at 80-90mb ram at 1.5k guilds
my vps only has 1gb ram so.. xD
yeah I actually rented some overpowered shit
thought I would host some gameservers but 
still can't run a minecraft 1.14 server 🙃
you need a server farm to run a mc 1.14 server at this point to be honest, they made it so heavy
I think it will
(i was joking)
but my old vps wasnt able to run 1.13 becs of some fcking fish path calculations
maxed the cpu out
yeah 1.13 has a fuckton of performance issues
actually do i need users cached for anything? I only fetch users through API
yeah I'm unsure too xD
ask in d.js support
but I don't think so
only reduces api calls (afaik)
actually do i need users cached for anything? I only fetch users through API
if your commands require a user to be provided as an argument, it would be preferred to have the user cached
that way you don't have to nag the command executor to use their id, rather you allow them to use their username etc
though caching users is irrelevant in guilds which have less than 100 members
Wouldn't i just get everything through the member object?
if you need to do any operation on a user, like kick/ban/dm/roles/etc, then you should cache them
yeah i need for roles and dm so i should probs keep them 
Wouldn't i just get everything through the member object?
but how will you get the member object if you don't have the id
yes, but what you can do is also cache them as needed
or simply sweep them regularly
I would make it like this:
sweep allows a method to decide if they should be sweeped or not. you could check the last message, if its not set, delete the user, if its set and already a few hours old (check timestamp) delete him
the issue comes where the caches between your bot and a user's client are mismatched. a user can have another user in their client cache, but your bot maybe doesn't have that specific user in cache, so the bot wouldn't recognize the user if it was provided as an argument through a form of a username lets say
you mean like using mentions?
mentions are doable
you can extract the id
however, it will cost you an api call to verify if the user actually exists or not
because someone can provide a dummy mention
discord.js seems to be really heavy on caching and honestly i don't know why, i used to keep every single member in 2.2k guilds cached (even in here) and the bot wouldnt peak over 500 mbs on discord.net
yes, but you can fetch it once and then keep it in the cache, it costs a few calls, but its still better than running with hundreds of cached users that are never used
slowly your bot will get populated with users that are actually relevant and used, instead of trash
lul
but i think djs's goal is to minimize hitting the api as much as possible
even if it costs half of your machine's resources
or more
well im still using the sweeping version in production, using around 200-300mb
but im gonna switch to the raw methods eventually
I'm getting these when starting bot
0|shards | [Error ../js/decoder.h:28] Bad version number.
0|shards | [Error ../js/decoder.h:151] Reading sequence past the end of the buffer.
0|shards | [Error ../js/decoder.h:117] List doesn't end with a tail marker, but it must!
0|shards | [Error ../js/decoder.h:28] Bad version number.
0|shards | [Error ../js/decoder.h:50] Reading a byte passes the end of the buffer.
0|shards | [Error ../js/decoder.h:50] Reading a byte passes the end of the buffer.```
looks like discord sent a bad payload
or something in the middle sent garbage
removing erlpack might help
i'll try that
erlpack has issues with node v12
there is a pr to fix them, but its been pending there for 25 days and nobody seems to care so idk
im using the forked version from the guy who made the pr
Now i'm getting
0|shards | at Timeout.setTimeout [as _onTimeout] (/root/node_modules/discord.js/src/sharding/Shard.js:137:31)
0|shards | at ontimeout (timers.js:436:11)
0|shards | at tryOnTimeout (timers.js:300:5)
0|shards | at listOnTimeout (timers.js:263:5)
0|shards | at Timer.processTimers (timers.js:223:10) [Symbol(code)]: 'SHARDING_READY_TIMEOUT' }```
but on a test version of bot that has same code (thats on glitch) works fine
maybe the shard process is throwing an exception
actually yes i got a rejection
(node:6603) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'emoji' of undefined
will fix that myself
seems to be coming from
if(reaction.emoji.name !== "🎁") return;
does master not include emoji object in reactions?
they do
That's weird, it's in the messageReactionAdd event
module.exports = async (client, reaction, user) => {
reaction only passes two things https://discord.js.org/#/docs/main/master/class/Client?scrollTo=e-messageReactionAdd
following that, you're getting the .emoji.name prop from a User object
no event in d.js passes client
he means a event handler
stop being so specific, everyone uses event handlers and everyone passes a client
are you using the raw event?
i am
I think I had a similar issue a year ago lol
can you show the part in the raw event where you define the things for the event and then emit it
if (!['MESSAGE_REACTION_ADD', 'MESSAGE_REACTION_REMOVE'].includes(packet.t)) return;
const channel = client.channels.get(packet.d.channel_id);
if (channel.messages.has(packet.d.message_id)) return;
channel.messages.fetch(packet.d.message_id).then(message => {
const emoji = packet.d.emoji.id ? `${packet.d.emoji.name}:${packet.d.emoji.id}` : packet.d.emoji.name;
const reaction = message.reactions.get(emoji);
if (reaction) reaction.users.set(packet.d.user_id, client.users.get(packet.d.user_id));
if (packet.t === 'MESSAGE_REACTION_ADD') {
client.emit('messageReactionAdd', reaction, client.users.get(packet.d.user_id));
}
if (packet.t === 'MESSAGE_REACTION_REMOVE') {
client.emit('messageReactionRemove', reaction, client.users.get(packet.d.user_id));
}
});
}```
can you try this:
module.exports = (client, packet) => {
if (!['MESSAGE_REACTION_ADD', 'MESSAGE_REACTION_REMOVE'].includes(packet.t)) return;
const channel = client.channels.get(packet.d.channel_id);
if (channel.messages.has(packet.d.message_id)) return;
channel.messages.fetch(packet.d.message_id).then(message => {
const emoji = packet.d.emoji.id ? `${packet.d.emoji.name}:${packet.d.emoji.id}` : packet.d.emoji.name;
const reaction = message.reactions.get(emoji);
if (reaction) {
reaction.users.set(packet.d.user_id, client.users.get(packet.d.user_id));
} else {
const emoji = new Discord.Emoji(client.guilds.get(data.guild_id), data.emoji);
reaction = new Discord.MessageReaction(message, emoji, 1, data.user_id === client.user.id);
}
if (packet.t === 'MESSAGE_REACTION_ADD') {
client.emit('messageReactionAdd', reaction, client.users.get(packet.d.user_id));
}
if (packet.t === 'MESSAGE_REACTION_REMOVE') {
client.emit('messageReactionRemove', reaction, client.users.get(packet.d.user_id));
}
});
}
i'll give it a shot
by the way that user thingy will rely on cached users
so if you really need that user it you would need to fetch that user
i get the same error
its also preventing my bot from booting
i just noticed one shard booted but some of the others refuse to do so
hold on the error went away
now im getting discord is not defined
need to find that
now i'm getting
0|shards | at channel.messages.fetch.then.message (/root/events/raw.js63)``` @onyx summit
uff okay that happens if you copy and paste code from another context
my bad
maybe this
https://txtupload.cf/9DP#lf2qk

now im getting "animated is not defined" and "data is not defined"
what i dont get is the exact same code works on glitch where i test the bot before i put it onto the vps
hm, I dunno why, but this worked good for me, sorry, then I can't help you
glitch good 
are the cache settings different?
their the same
i guess i'll revert to my stable code until i figure out how to get it working
When you add your bot on Discord Bot List, it automatically adds it to the Discord. How would I do the same?
well first your bot needs to pass the submission process
it then appears publicly on the website and gets invited here
if not your submission gets deleted and bot doesnt get invited
hi guys
im trying to make a custom prefix command, everything is ok
but i need to define the db.Fetch to functions.js
how can i do it ?
When would you use zlib-sync? When sharding or can you use it at any time?
Why is it saying my token is invalid when its not
no
Have you tried regenerating the token and using the new token?
i didnt make it
so idk how it works
but ive never had an invalid token error ever
Wait what language are you using
i think its js
You think?
like i just said
i didnt make it so idk how it works but ive never had an invalid token error ever
You shouldn't copy and paste code without understanding it first
Okay?
I'm confused as to how that has anything to do with this? You're still making the bot and don't even know if it's js
and this is why i dont come to this server for hlep
no one understands that everyone just forks modmail and starts it
thanks for trying
var ttt = new Discord.RichEmbed()
.setTitle("TIC TAC TOE")
.addField ("⬜⬜⬜ ", )
.addField ("⬜⬜⬜ ", )
.addField ("⬜⬜⬜ ", );
message.channel.send(ttt).then(function (msg) {
msg.react("↖️")
msg.react("⬆️")
msg.react("↗️")
msg.react("⬅️")
msg.react("↕️")
msg.react("➡️")
msg.react("↙️")
msg.react("⬇️")
msg.react("↘️")
}).catch(function() {
})
break;```
It's not reacting msg
No console err
try logging it at .catch
Ok
Someone know how if the user click on emoji reacted by a bot he get the user mentions or username?
Or something like this???
What language and what library @earnest phoenix
Well considering he's in the Discord.js Official discord
I would assume d.js
Well the basic pseudo-code would be
listen/wait for reaction > if reacted mention user
@opaque eagle discord.js
A guide made by the community of discord.js for its users.
ah fuck
Discord.js official site
XD
@opaque eagle you arent
just saying that he is
I didnt mean to be passive aggressive, I guess.
Ok
Hi, i have a question.
I want my bot to run on multiple vps, but i have a big statistics database i cannot query remotely all the time from all shards. Each vps/shard should hence load and have only the information it neeeds for answering stats requests from the respective servers the shard is on. Each shard will also write new statistics into its local storage, andshoueld update the changes to the remote database perodically.
I was wondering, is there some known and beautiful solution to this? I am about to "manually" program this cache: An api for my remote database (mysql) to load and update saved records. Then some local storage solution (maybe some in-memory sql solution?) to load and run the actual queries on the vps machines.
is it a violation of tos to send people a dm once they've voted 3 times
no
epic
just dont spam down someones dm
anyone have know why my bot keeps changing its presence when the only time it changes it is when its ready. But it doesn't restart
i can send the code that does it
Send it.
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`)
client.user.setActivity("people poke each other", { type: 'WATCHING' })
});
Nothing wrong there
the whole thing?
yeah
this is my first time coding in js
that is so messy and unreadable
i can understand it. but yh i see what you mean
is it on glitch/heroku?
glitch
i can already see a few issues; you should only have one event handler, switch case your commands in one handler instead, and don't use json as a database as it's more prone to data loss and corruption
im gonna move over to sqlite
you should try catch sending a dm to a user as it oftens fails due to the user not having dms enabled
i thought i did
yeah there is room for improvement, but i dont see why it would be resetting its presence every 10 seconds aside from crashing/disconnecting
maybe after a code cleanup it will also fix itself
ok
join all your on("message") together into a single on("message") event
ok
i g2g out now
Hey Tim please help me out on this, noone seems to know.
So i have a statistics bot and my bot/3shards(discordjs) an data(mysql) lie on the same server. I am at 3500 servers and i think my current build will not make more than 20k, as a loot of complex database queries are done every second already and the response time is also not great.
At some point i need to be able to horizontally scale on multiple vps. I intend to have a remote backup database and a local "cache", that is populated at startup (with records of the servers the respiective shard has), and periodically saved. This local cache should be an in memory database to increase response time (for calculating statistics).
Do you know of any tools/dbms to automatically achieve this "persitant-remote-inmemory-chache-backup behavior? Or do i have to implemnt it "manually", meaning write an api for my remote mysql database to pull and update the records, and write controller in my bot for populating and updating the in-memory database from/to my remote api?
ty for the help
@viral spade you will probably have to set it up manually to fit your needs, but try using sqlite for a local process-specific database, and then flush it do the remote db once in a while
Or use a time-series database like InfluxDB for the statistics data. That can easily handle statistics for 20k servers
Classic SQL databases are the worst for storing statistics of stuff 🤷
ok thank you.
but i really wonder, is there no in-memory database system that 1 . is able to load from a remote disk in its own memory only the reocrds it needs and 2. has a persistance mode that is able to save the stuff back remotely automatically?
like many people must need something like this, no?
only thing i can think of would be redis replication
Time-series databases are good for your use case. I suggest you look at those
They're optimized for that
and yes, many people need something like that, but that is something that is very implementation-specific, and should mostly be done manually
i see.
that redis replication looks interesting and sounds like what i was looking for.
I will still do it manually,, thank you
so you would suggest sqlite for this?
will i be able to use all my mysql sql statements with sqlite just the same?
Whenever I boot the bot & shards, i always get cannot read property emoji of undefined and then the shards crash, and pm2 reboots them and the cycle continues, from my message reaction add event file, it seems that my raw event isn't working on master, can someone take a look? https://hasteb.in/nacayito.js
are you sure the error is coming from there? not sure why would you be receiving an empty packet
if you're sure the problem is there, you could just add if(!packet.d) { console.log(packet); return; }
that will stop the errors and give you some info about the packet to maybe find out why its empty
I'll try that
cpu yes, mem no
Oh
Okay well someone told me to just install it and it should work is that the?
True*
After the emoji error I got
{ t: null, s: null, op: 11, d: null }������
after logging packet
if packet.d is missing
Do I just install zlib-sync and it will work?
Or do I have to do some stuff coding wise
you just need to restart your bot in most cases
unless you use a process manager like pm2
Okay
oh i think it logged the heartbeat because i put the logging before the if packet contains messagereactionadd stuff
5% sounds normal
Ye
mine is also at 5% with zlib, and 10-20% without zlib lul
lmao
with zlib-sync its 20%
Before it was at like 20 then when I installed zlib it jumped up to 60% now it’s down to 5%
A lot of jumping around eh
@sinful lotus single shard 
internal sharding
How does that work
yes single process multiple ws shard
Ah okay
Doesn’t sharing have an auto feature?
1gb at 15k guilds is nice
I’ve seen stuff like shardCount: 'auto'
my ws shards is auto
yes, the auto option will fetch recommended shards
I only specify my process
Someone told me actually 2-3 people told me auto wasn’t an option 
Is there a way to cut down on mem usage?
Actually is 100+mb normal for a bot in 19 servers?
just d.js stuff
yes
Okay
specially if your bot is in here
I don’t think it is
the node process itself will use 50-60mb
I have to use a separate website for hosting my mongodb
then thats should be fine
Cause my friend doesn’t use mongodb so he doesn’t have a mongodb server running on his service
But that website only allows me to have 500mb and that’s it
500mb is more than enough in most cases
unless you store files or images
my bot uses about 4mb for user/guild configuration and 600mb for images lol
The user collections if I ever get it working may become a problem in the future
Rn userData isn’t being written which is fine for now cause I’m not doing anything userwise Rn
Also my next question is how do I control caches?
nothing gets logged @quartz kindle
this is the full error
0|shards | at module.exports (/root/events/messageReactionAdd.js16)
0|shards | at Client.emit (events.js:198:13)
0|shards | at channel.messages.fetch.then.message (/root/events/raw.js20)
0|shards | at process._tickCallback (internal/process/next_tick.js7)
0|shards | (node:8879) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 9)0|shards | (node:8879) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'emoji' of undefined
0|shards | at module.exports (/root/events/messageReactionAdd.js16)
0|shards | at Client.emit (events.js:198:13)
0|shards | at channel.messages.fetch.then.message (/root/events/raw.js20)
0|shards | at process._tickCallback (internal/process/next_tick.js7)
0|shards | (node:8879) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 9)```
either sweep them regularly or prevent unneeded caching. the former is easy to do, the latter not so easy
I don’t know how to do that lol
are you using master or stable?
master
@split hazel is messageReadtionAdd.js the file you posted earlier?
Nope, that was the raw.js file
or event shall i say
what confuses me is the same exact code works correctly on a test bot thats on glitch
@lusty dew master has several different caches, such as client.users, client.channels, client.guilds, but most importantly, each guild has several caches itself such as guild.members, guild.presences, guild.roles, guild.emojis, etc...
all of those can be cleaned regularly to free up memory, specially if you dont use them in the first place
line 16 in messsageReactionAdd is
if(reaction.emoji.name !== "🎁") return;
and using module.exports = async (client. reaction, user) => {
how would that possibly happen
it works correctly on glitch, which has the same code
on a test bot thats in like 2 servers
@quartz kindle I don’t know how to do that, that’s my problem
I’ve never worked with caches didn’t know that you could reduce mem usage by cleaning caches until a few minutes ago lol
@lusty dew all collections have a sweep function
<collection>.sweep(function)
so you can do client.users.sweep(function to decide what to sweep and what not to sweep)
the function works the same way as any other iterator, like you would use in a .map or something
or a .find
Would I have to do that for every cache?
yes
yes
for example, this is something i tested before
guild.channels.clear();
guild.members.clear();
guild.roles.clear();
guild.voiceStates.clear();
guild.presences.clear();
guild.emojis.clear();```
assuming you dont need to use any of that content
is it ok to send a user a dm once they've voted?
Even if they haven't interacted with the bot in the past
Lava link uses voice states at some point or I think I do I can’t remember what I used in all my music commands
you have to make a lot of tests
because sometimes you might need something that you're not aware you do
for example if you use members, or set roles
and in most cases you will also need channels
presences is usually what most people complain uses a lot of memory and not a lot of people need it
I use members and set roles
And I mess with channels a lot but idk if it counts as like message.channel.send?
yes it does
Okay so I shouldn’t sweep channels members or roles?
if you need something you deleted, you need to re-fetch it when you need it
for example, if you delete channels, then you need to send a message to a channel
you can do this
let channel = client.channels.get(id) || client.channels.fetch(id)```
another good idea is to not clear stuff that has been used recently
for example .clear() clears everything, but .sweep() only clears what you specify in the function
you can for example clear users that havent sent a message in a while
by comparing lastmessage timestamps
O.o okay
i had a more complete example somewhere, let me find it
let OLD_SNOWFLAKE = Discord.SnowflakeUtil.generate(Date.now() - 3600000);
for(let guild of client.guilds.values()) {
guild.channels.sweep(t => t.type !== "text" && t.type !== "dm");
guild.members.sweep(t => t.id !== guild.me.id && (!t.lastMessageID || t.lastMessageID < OLD_SNOWFLAKE));
guild.roles.sweep(t => t !== guild.id);
guild.voiceStates.clear();
guild.presences.clear();
guild.emojis.clear();
}
client.channels.sweep(t => t.type !== "text" && t.type !== "dm");
client.users.sweep(t => t.id !== client.user.id && (!t.lastMessageID || t.lastMessageID < OLD_SNOWFLAKE));
for(let channel of client.channels.values()) {
if(channel.permissionOverwrites) {
channel.permissionOverwrites.clear();
}
}```
clear channels that are not text or dm channels
clear members and users that havent sent a message in the last hour
and some other stuff
but for each of those, you need to test how it impacts your bot, and make corrections if needed
so implement those carefully, one by one
How would I test?
@carmine echo should be ok i think
@lusty dew use your bot normally and see if and where it crashes lul
That's good thanks
Oof Okay xD
I’ll look into that later rn I think everything is fine how it is thanks for teaching me how to do this though!
when trying to login to my main bot through the working test bot on glitch i get
(node:1185) UnhandledPromiseRejectionWarning: Error [SHARDING_READY_TIMEOUT]: Shard 0's Client took too long to become ready.
at Timeout.setTimeout [as _onTimeout] (/rbd/pnpm-volume/e0893195-5421-40b1-bc2f-fb899ad367c3/node_modules/.github.com/discordjs/discord.js/d14db521585f2b6b1a6c50d3a9acecc73bea25a3/node_modules/discord.js/src/sharding/Shard.js:137:31)
at ontimeout (timers.js:436:11)
at tryOnTimeout (timers.js:300:5)
at listOnTimeout (timers.js:263:5)
at Timer.processTimers (timers.js:223:10)
(node:1185) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:1185) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
The app exceeded the memory limit. Stopping and pausing for 15 seconds.
yeah i knew that would happen i just tried to see if at least 1 shard managed to go online before the memory limit
how many guilds are you running on again?
3.2k
hmm
What’s the guild limit before you need to start sharding?
2.5
k
Okay
its strange how the test bot works fine
Anyway I can automate sharding for when it reaches that limit to start sharding?
yeah d.js will spawn the recommended shards
Yes
Might as well get the code over with instead of having to worry about it later
You can also post to the discord API to see what they recommend
im still trying to realise why my reaction objects are coming back empty
Wait couldn’t I just do this:
client = new Discord.Client({shardCount: 'auto'})
Or smth
no
Hm
@split hazel
You woukd have to use https://discord.js.org/#/docs/main/stable/class/ShardingManager @lusty dew
Mk
put the packet type comparison inside the reaction check
I think he is on master
Ye then that works
if(reaction){
reaction.users.set();
if(packet.t === ...) {}
else if(packet.t === ...) {}
}```
Also nice pfp
yes, the way it is right now, you're still sending the reaction event even if there is no reaction
so you get an empty reaction on the event listener
ahh that would make sense
since the bot is constantly receiving reaction packets all the time from the 3.2k guilds
or other packets
welp ig2gnow
Can’t you sweep messages with the sweepMessage method?
Jkjk
But does it sweep old messages or new messages?
You have to pass a lifetime
Ah mk
In seconds, and messages that are older than this get removed
Trying to find ways of reducing mem usage seems like clearing caches is the only good way?
like client.sweepMessages(100) will sweep all messages that are older than 100 sec
You can pass some stuff in the client constructor
so your bot caches less messages
Wym
Gimme 10 sec to turn on my pc
Kk
Optimize your code a bit and make sure you don't have memory leaks as well
I haven’t noticed any memory leaks
your bigggest memory leak is lavalink anyway
Really?
not really a memory leak but it eats the most ram
const client = new BClient({
shardCount: await Discord.Util.fetchRecommendedShards(process.env.BTOKEN, 500),
presence: {
status: 'idle',
activity: {
name: 'Shard Starting',
},
},
messageCacheLifetime: 60,
messageSweepInterval: 61,
messageCacheMaxSize: 20,
});
the part to cache less messages:
messageCacheLifetime: 60,
messageSweepInterval: 61,
messageCacheMaxSize: 20,
Ah so I can add that type of stuff in my client constructor to help reduce cached messages?

and e.g. my bot has 38 731 channels, meaning it could cache up to ~ 8 Million Messages
Woah
if my maths isnt shit (it is)
but I think thats right, 38731 channels * maximal 200 messages = 7.746.200 Messages
My bot only reads 433 channels lol
Okay well brb while I add in the message cache string
Thing*
How would I know if it’s working?
uhhh, you can eval in any channel (preferable #commands ) how many messages it has cached message.channel.messages.size
Okay
My bot isn’t even in here I don’t think
Okay nvm
Why did it not work earlier when I tried using I
It*
Hmph
change the prefix tho xD
Wym?
your bots prefix is -, and by running it in here a lot of bots will respond
so if you can, change its prefix in here

None of its active rip
Except for when me and the other dev talk I’m it
In*
Hm
@onyx summit should I just change the prefix globally?
👀
nah
I mean, you don't really have to care bout ram yet
I know but I wanna be prepared lol
my server is not really busy yet 
Lol I just don’t want to cause problems for you
I don’t know how to add that btw
its on my github readme


