#development
1 messages · Page 70 of 1
At best it creates needless load, at worst it creates lag
How intensive is your help command bro
Doesn't matter given enough spam
so for calling an api could i just use fetch that was implemented lately on nodejs
or should i use axios (i don't like axios)
Just add a ratelimiter
Kills their fun instantly
Why would spamming a command "Cause a lag tho"?
Unless it's a thread-freezing task, which means it's programmed incorrectly
Or you're creating a lot of objects each execution and i mean a lot, without clearing them after
yes
You shouldn't use either of them, Axios is just straight up bloat to the maximum extent, and about the built-in Fetch API, we haven't marked it as stable yet so you should stay away from it for now, use either Undici (it's request() method or others), or use Node-Fetch
use http/https
The good* ol' HTTP(S) implementations, aren't they fun to use
const filter1 = i => i.member.id === gamedatabase[key].team2[3]
const collector11 =
r.createMessageComponentCollector({filter1,
componentType: "BUTTON",
time: 10000,
max: 1,
});
collector11.on(
"collect",
async (i) => {
if(i.member.id !== gamedatabase[key].team2[3]){
return;
}```why can everyone react to this collector?
You're passing an option called filter1 not filter
The solution would be filter: filter1 in this case
what's the best way to collect reactions over a period of time in py-cord?
i tried sleeping for a set time and then collecting reactions but the count only included the bot's counts so im not sure what the problem is
I guess starting a timeout listening to the associated event and collect your data
No matter what ur language is
Before that, I want to ask why you're using pycord over discord.py since it's being maintained again
is discord.py generally better?
Pycord is a fork of discord.py that was created when discord.py's sole maintainer abandoned it, but they're back to continue maintaining it so it's better as it'll get much better and faster support
Until he drops it again cause of his "busy" life and mimimi about discord being as stupid as they are
I still don't get how the sole maintainer haven't gathered a group of maintainers for discord.py instead of being the only maintainer, just like how discord.js grouped a couple of them
I mean one man projects are a thing but since he knows the time and effort he had to invest into it and was aware about all the people relaxing on his stuff it has been the worst decision to just throw anything away
While i fully agree real life comes at first without exception then coming back, flaming about discord and their shitty behavior and maintaining the project again literally because, I assume, too many people flamed him and ask him to continue it was also a weird move
Either I have thr time, know how and will to run a project or not
And without knowing him personally the stuff he wrote and I read anything and the context to all that makes me seriously say he's just an idiot not much else
While I still respect the decision to prioritize real life interests
The way he dropped his project and literally the community with the reason discord had a big impact because of their shitty development is nothing else than an excuse
I might not find the exact right words here what i want to say but it literally give you a direction what I think about just by reading his statements and getting some infos about the context
Yeah I agree, although none of it is an excuse to not promote some people they trust to be maintainers, especially the people with the most contributions and stuff; it would've make things much easier and better for not only them but also the project in it's entirety, and for the users as well as it would be maintained better
It's also a shame to make people move to the maintained project again after others have put time and effort into forks of his project to at least make it possible for the dpy community to go on
And have something they can rely on instead of fearing their code and projects will be completely outdated in the future
Yeah absolute shame, I've kinda always hate it when a big project is solely maintained by one person, if something happens to that person then oh well
Either you stand behind your projects (and community) or not
And yes life can always can change unexpectedly forcing you to do things you don't want to but then have the balls to make a decision
And not to drop anyone relying on your stuff, pointing the middle finger to them
For absolutely no reason
not really, i would even say myself that i think pycord is still better than the original d.py
i dont trust danny enough to use his projects again
but i dont even wanna do discord bot dev again so ill probably never gonna use both again lmao
just make your own lib
ezpz
guildMember.timeout(5 * 60 * 1000, 'They deserved it')
Can someone explain the 5 * 60 * 1000 so I can figure out how to make it from 5 minutes to an hour
60 * 60 * 1000
yes but how does it work exactly
I don't want the answer I just don't know how to customize it
1000 milliseconds is 1 second. Multiply that by 60 is 60 seconds or 1 minutes and multiply it again by 60 would make 60 minutes or 1 hour
Np
discord.py doesnt seem to detect my reactions (here is the code)
msg = await interaction.followup.send(stri + "\npick the number of your desired permutation (react with :x: to stop voting): ")
for x in range(math.factorial(len(units))):
try:
await msg.add_reaction(emoji[x])
except:
pass
await asyncio.sleep(math.factorial(len(units))*1.5)
await msg.edit(content = f"round over!\n{lrs}")
cache_msg = discord.utils.get(bot.cached_messages, id=msg.id)
votes = [e.emoji for e in cache_msg.reactions]
print(votes) # this line is purely to check in the console
for e in Counter(votes):
print(e, emoji.index(e), Counter(votes)[e]) # this line is purely to check in the console
lrs += f"{e}: {Counter(votes)[e]-1}\n```
i made the bot edit the original message to display the results but it doesnt seem to be able to count votes (reactions) from my end
i had the same issue in py-cord (i switched over today)
does anyone know how to solve this?
woah
i know
string format stuff
i dont like using it tho
Interesting
import math
skills = [
"Farming",
"Mining",
"Crafting",
"Healing",
"Melee",
"Archery",
"Alcehmy",
"Stealth",
"Persuasion",
"Mobility"
]
num_skills = len(skills)
variations = math.comb(num_skills, 3)
print(variations) # -> 120
I haven't messed with math stuff in many languages idk if any other lang has a similar comb method
factorial
is it from that youtube short
cannot find -lSDL2_image
set(SDL2_IMAGE_INCLUDE_DIR C:/Dev/SDL2-image)
include_directories(${SDL2_INCLUDE_DIR} ${SDL2_IMAGE_INCLUDE_DIR})
link_directories(${SDL2_LIB_DIR})
target_link_libraries(${PROJECT_NAME} SDL2main SDL2 SDL2_image)
Precisely I follow a lot of coding people on youtube
their shorts pop up all the time
it just doesn't exist
chief that ain't what it means lol
the file type is JetBrains CLion
that looks like a shortcut to clion
never knew CMake supported CLion files
Its not CLion specific my guy
what's the file extension
its a header file apparently
SDL_image isn't a header file either way so that doesn't make much sense
either way you don't link with header files
it should look more like that
imagine making file extensions hidden
You need to link the .lib file and set the include folder to that include folder in there
Looks nothing like that
make it show file extensions
When I downloaded it I just got a folder full of files
all you need are just the header files and .lib files
Got it
Non-const lvalue reference to type 'unsigned int' cannot bind to a temporary of type 'unsigned int'
void Math::fact(unsigned int& n)
{
if(n == 0 || n == 1)
n = 1;
n * fact(n - 1);
}
I guess I can't use references here can I 
the statement in the end doesn't do anything lmao
also void Math::fact() {} is not valid C++
unless Math is a class and fact is a static method already declared
namespace Math {
void fact() {}
}
it is indeed
//
// Created by dyeaa on 11/22/2022.
//
#ifndef BLAZE_MATH_H
#define BLAZE_MATH_H
class Math {
public:
static unsigned int comb(unsigned int n, unsigned int k);
static void fact(unsigned int& n);
// static unsigned int fact(unsigned int n);
};
#endif //BLAZE_MATH_H
bad practice
im kidding
Huh
would the header file just look like
namespace Math {
void fact(unsigned int n)
}
I believe so
Also there's no way I can calculate the factorial using references can I? Its not needed but it'd be cool not having to save the result to a variable and just modify the existing ones
Bad idea
Oh?
Shouldn’t do it like that
Why so?
It’s a bad practice to modify variables like that, you should be returning a new value for math stuff like that
I’m not saying you can’t, you just shouldn’t
It’s convoluted
Ofc
The only way I'd know how to calculate a factorial would have conflicting types
namespace Math {
unsigned int fact(unsigned int n)
{
if (n == 0 || n == 1)
return 1;
return n * fact(n - 1);
}
}
for example if n was a reference instead and I removed the returns and such fact(n - 1) would result in a type confliction like I showed above
Don’t use recursion for that
should I just a for loop ?
You can dereference the n if you want to do it like that though
Alright
Should only be used when an iterative solution is difficult/impossible to write
I keep getting an exit code cause I am dividing by 0
tf
Okay so
3628794! = Infinity
then I am taking that result and multiplying it by my second factorial (in this instance 6)
std::cout << factorialN << std::endl;
std::cout << factorialK << std::endl;
std::cout << factorialN - factorialK << std::endl;
std::cout << combinedFact << std::endl;
3628800
6
3628794
0
🤔 I think I am fucking up somewhere
okay so in python math.comb(10,3) -> 120
factorial of 10 is 3628800
factorial of 3 is 6
(3628800 / (6 * (3628800-6)) -> somehow equals 120 even tho google says 0
unsigned int comb(unsigned int n, unsigned int k)
{
int factorialN = fact(n);
int factorialK = fact(k);
int combinedFact = fact(factorialN-factorialK);
std::cout << factorialN << std::endl;
std::cout << factorialK << std::endl;
std::cout << factorialN - factorialK << std::endl;
std::cout << combinedFact << std::endl;
return factorialN / (factorialK * fact(factorialN-factorialK));
}
You’re not doing the math right
Oh wait hold on
Are you sure it’s not a massive number?
I am doing it based on the formula though?
How can I check?
cause console just outputs 0
Are you sure you’re doing this right
Plug it into wolframalpha or something with the same numbers
Plug it in with the actual formula
With the factorials
What’s your numbers you’re doing
3628800 and 6
No
I meant what are you using for the factorials
Ok hold on
So that means you should be getting 10! / (3! * 7!)
Which is 120
10-3
I am fucking dumb

Fixed
I was doing the factorial of n and k minusing each other and getting the factorial of that
Yeah
Yeah that explains it
Well now i have my own factorial and comb methods

I already forgor what comb was supposed to be used for
I guess get the number of possible combinations
so out of 10 and choice of 3 there is a 120 unique combinations possible ig that is what it means
.
anyone has any idea why my reactions might not be working properly
(code here)
you really shouldn't use endl
do you have the partials/intents enabled?
alr so I have two numbers that cant be under 0 and can scale infinitely, lets say 5 & 7, Whats the best way to find out the percentage each take up? (with 3 & 7 it would be 30% and 70%)
percentage math
scale infinitely
you cant have percentage without a maximum value
scale infinitely probably meaning that they can be anything up to high numbers
he probably wants something like 9374987% damage
no, its for voting so the total wont be over 100%
yeah, so that's normal maths
ok so, you technically will need a maximum value, which in this case will be the number of votes
100 * value / total
total = 100
X = ?
X * 100 / total = ?
yes
I wasnt sleeping for 20 hours man, I cant think rn
its honestly the single most useful thing in math ever invented
rule of three actually
yep
it's the only thing i still use
it's among the most useful formulas out there
everything else went poof gone
thankfully i don't
can I somehow get the text of other buttons in d.js?
sure
if they are in the same message, access the message then access its components
something like interaction.message.components
what should I round to? two decimals or one?
i set intents.messages and intents.reactions to true
it actually does detect reactions but only those from the bot
so im trying to figure out why
zero decimals
additionally, I'd suggest using upvote/downvote icons instead of + and -
like this?
how do I check if a user has already decided on an option?
aka how do I store that
just put it in an array or a set if its not meant to last long
it should probably stay forever since its a poll though
would just saving it in my db be a good option?
well if you want it to last forever it looks like thats the only option
yep, much better (and intuitive)
Hey im getting high cpu usage on nodejs ubuntu
im using htop to check whats causing it and it shows my nodejs program
any suggestions i could do to figure out whats causing this?
could it be that there are too many calls that would cause high cpu usage?
well, "too many calls" but calls to what?
do you have anything you'd consider "intensive" tasks in ur bot?
how exactly would I go about storing the userids in the db? Id assume I need some kind of map to know the id and what they voted, how do I do that in postgres? I heard of jsonb but how would I query that?
you could give each poll and id, store that in a db table. create another db table for votes, with columns for user id and the poll id, then store users in that table when they vote on a poll
then you can query based on poll id to figure out if a user has already voted on that poll
wouldnt that be pretty inefficient compared to jsonb for example?
ive never heard of jsonb before, but thats how i would do it
probably better ways to do it yeah but it would most likely work well enough
pretty much the opposite
jsonb would be less efficient than a OTM table relationship
"yes"?
is that a varchar field or...?
it is varchar
varchar
primary key, did u make those 2 fields primary keys?
you need to assign a PK for each table, else u get NATURAL search queries
which are a fuckton slower than INDEX queries
I have been making a bot named ishu-bot it will be published soon!
just run this ALTER TABLE <thetable> ADD CONSTRAINT <name> PRIMARY KEY (messageId, userId)
idk the name of ur table, so fill that in
well, not necessarily with two columns, in this case u have to since both messageId and userId might repeat, but never the same combination
but yes, always define a PK for all tables
if this table has relationship to other tables you'll also want to define a foreign key
for example, Human (PK Name, Sex, Age) --< Pet (FK Owner, PK Name, Race, Age)
a human can have multiple pets (--<), while a pet can only have 1 owner
a pet is linked to Human through the FK Owner, which will be the same as Human's PK
I think im not gonna go through that rn
Looks very complicated, especially with my 15 ish tables
liar
if u were to select it, you'd do
SELECT *
FROM Human h
INNER JOIN Pet p ON p.owner = h.name
that's basics for sql structuring
it's not like advanced min-maxing stuff, it's literally a thing you need to account when creating tables
actually inner join doesnt make sense
when no pet exists, no match exists means an empty rresult will be returned
LEFT JOIN makes sense here
it all depends on the intent of the query tbh, whether you want only pet owners or all
so, back to that, the difference between properly structuring your tables can be as high as 80% increased performance
that's true, but like I said I expect humans without pets and your query would not return humans without pets
and it aint really that hard, just think how tables would interact with eachother
just to show him and tell him the case matters and different types of JOINS exist
does pg actually require the INNER keyword?
I think so
oh ... ok weird tho, usually JOIN should be INNER JOIN by default
so the engines really have noticable differences
never looked it up tbh, I got the habit of declaring it everytime
yep, inner is the default join
say i had 3 documents:
userId: ...
userBumps: [
{timestamp: 1, count: 1 },
{timestamp: 2, count: 1 },
{timestamp: 3, count: 1 }
]
and
userId: abc
userBumps: [
{timestamp: 0, count: 1 },
{timestamp: 2, count: 1 },
{timestamp: 3, count: 1 }
and
userId: 1234
i need to push some of the data to an array to look like this
[
{userId: ..., count: 3},
{userId: 1234, count: 0},
{userId: abc, count: 2}
if timestamp is greater than 0 (in this instance, this will change depending on the argument)
i have been trying to figure out a solution for a good few hours now and i know it seems so easy but oh my. Can anyone help me please?
what you need is a combo of map + reduce
since u said "document" I imagine ur using some nosql database like mongo, but I cant really help with it
but if u were to do that with general objects, you'd use map + reduce
Mmm not really ig, I do have some canvas drawings but it completes in 1 - 2s
and my calls I mean all the network traffic
All the invokes from discord
const test = [
{ a: 1, b: 5 },
{ a: 2, b: 3 },
{ a: 3, b: 6 },
{ a: 4, b: 0 },
{ a: 5, b: 1 },
];
const reduced = test.reduce((obj, out) => {
if (obj.a < 3) {
return out;
}
return out + obj.b;
});
console.log(reduced); // Will print 7
chose to use full-sized ifs for readability
but could be a one-liner with ternaries
are those drawings inside promises?
it's accumulator first, and then current object so (out, obj). you also need to specify the first number so that it could accumulate off of that
const reduced = test.reduce((out, obj) => {
if (obj.a < 3) {
return out;
}
return out + obj.b;
}, 0);```
I never really remember reduce syntax
how can i short the link give by reader.readAsDataURL
@earnest phoenix is there a place where i can put this for people who wanna know?
https://github.com/pendragons-code/nsfw-reddit/
the thing seems obscure and there are many people in this server likely to use such features. So i'm sorry for ping, but maybe you can put this at a 'useful resources' section or something like that.
if it is not possible than oh, im pretty new to this thing, thank you
We do not have such a thing, no
RIP ok 🫡
If you find someone else having such an issue, don't hesitate to give your input 
zamn you really need to clean your code up
so many things wrong in one function
no space between postcheck and (a)
no space between => and {
no camelcase function name
importing a moduke inside a function
awaiting a function but still using promises
postcheck => checkPost
using let unnecessarily
@drowsy vault next time please don't ghost ping
turks ☕
if (thing == true)
You said that the king commands don't work, I'm trying it myself, it works perfectly?
@earnest phoenixAre you sure you spelled it right?
I'm not Enigma.
DM Enigma, not me.
Krypton != Enigma
That's why I'm tagging and writing privately now.
Then don't ask me
inb4, make sure you're testing your commands without admin permission
You said that the king commands don't work, I'm trying it myself, it works perfectly?
No I didn't
and im out
quick.db + multiple dbs = wtf are you even doing
quick.db = wtf are you even doing*

quick.db could be so good if they (the devs) actually took their time to setup a proper ORM instead of saving everything in key-json tables
i did this from my phone without my usual prettier config, which i also did say don't use it in your own code directly, but yeah i'll make it nice some time soon. nvim on mobile isn't easy to use. ask why my friends forced me to sit at a fastfood restaurant with nothing i can eat (i am vegetarian at macdonalds so lmao)
atVoltrex
PFFFT LMAO, never noticed if(thing), but it seems to be a string actually
PFFT AHHAHA
i did that because on my actuall prod thing i hosted the db on a seperate device and i was too lazy so i did that for github
think of it as a microservice onn a seperate server kinda thing
but it is meant to be quick and easy,plus most of the users are like me amatuer 15 yo kids
age isn't a justification for bad practices
im sorry what
but really, seriously speaking, I don't see the purpose of that whole file
true,im just too lazy, and i may not even want to become a dev anyway, think of this as a stupid side project so really
which?
yeah, documentation is scarce, you can modify however you like right?
that's...not how github works
🤷♂️
what I mean is that the whole file has no meaning since u can just make a request to reddit using any http lib
tell me, how should i have done it
true, and yes taht is really pointless, but that thing is mostly for people who are like me, constantly using bad practices
that somehow work
that said, yes i rather improve
quick qtn, how old are you? im kinda conflicted about becoming a developer in the future
const nsfw = await fetch(`https://reddit.com/r/${sub}/about.json`)
.then(res => res.data.data.over18)
.catch(console.log);
// Done
wait if i am not wrong "true", is returned as a string
i could be wrong
but yeah i get that i should have written it bettetr
im 14 🗿
you usually dont need to make wrappers for wrappers because...well...they're already wrappers
yes yes
why use promises if youre gonna use async
can't think 🤣 it is midnight and my head hurts
that really looks painful to me
await and then doesnt look good
I mean, that's mostly a preference thing, I like to mine whatever data I need inside the same async block
turn 0 and 1 into boolean:
!!+0 // false
!!+1 // true
turn strings into boolean
('true' === 'true') // true
('false' === 'true') // false
why
=== doesn't do any kind of conversion
yes
It's one of the recommend ways to use it, chaining them to only get the data you need instead of initializing multiple variables for it
it's a strict-type comparison
thats the point
it'll compare string content
that what its supposed to do
still
it compares and retuns a false
or true
without await could look better for me
but thats just my opinion
without await you'd need to use the value inside .then block
depending if 'false' is 'true', it returns boolean false
since you would not be able to extract the value to the outer scope
obv == also works but it doesnt matter in this case if you follow the comment
That wouldn't even work without await because it would be an unresolved promise, you would only be able to use the resolved value inside the %Promise.prototype.then% callback
ah
nerdtrex
I also use winforms, they're fine if u don't need its xml cousin
still?
let me try to show what im trying to do
im 13.9 👀
💀
💀
i wanna do something like this, in a list
anyone an actually working as a dev for a living? if yes, please hear my story out,
i want to become dev, but im dyslexic and i cannot get my acads together
someone i know, a dev, took a similar path to me because they did bad at school and totally regrets becoming one
he takes the same paths as me in acads and basically is very likely me in the future, what should i do?
not even a dev, multiple actually, btw the devs in qtn are my school it guys.
and sysadmins (only 4 of them are sysadmins, the rest are actual devs)
but i dont know c# properly (or winforms), so 💀
being a developer is a "you" thing really, everyone can code but not everyone can think abstractally enough to become a dev
im already bad at web dev 🤣 and bad acad scores, who would wanna hire me?
like, "typing" or "knowing all the keywords" is the least of the problems, you need to think as if you were building something greater
This reminds me of
https://youtu.be/T7aSI-E1fCE
Avoid these mistakes at all costs if you are learning to code! -- PS Watch this to Learn the FASTEST way to get into coding https://youtu.be/4MkPTWZGkm0
These traps can be devastating, but now that you know about them you can conquer them. Maybe if you gave up this will inspire you to start again too.
I'm not sponsored or affiliated with any...
PFFFT AHHAHAAHAHHAHA
im ugly enough to look like that guy, so that meme is literally me
no but seriously, the industry itself is also looking bad
How so?
mass retrenchment and lay offs in FAANG
i mean FAANG isn't everything, but they are major players
nah, they're just the popular guys
after the pandemic, less people are as reliant on the computers
excuse-me????
yeah>
i will suffer in IT
i actually used more electronics before and during the pandemic than after
the lockdowns *
well you still use some dont you?
Well there's logic behind those lay offs and stuff, only the people who are active and working as expected get to stay, not the Daniel sitting on his ass all day doing nothing and slacking off at work, and not reaching the required quotas, so it doesn't make them look bad really
that's just confinement sickness, IT jobs are even higher than ever
Please mind your language @earnest phoenix
not the remote guys too XD
can u help me
anyways.i was gonna ask something code related and got distracted
wot
what was i gonna ask
deez
The message that got blocked
iam trying it for alot of time now i cant wait
:troll:
i meant be patient asking for help
huh?
You know what you typed
Tell me some server lists in dms O:
damn i forgot what to say
me?
no because i only use top.gg lol
i feel like trying to bypass the filter is not a good idea lol
Yes mind your language thanks
👀
oh no so many team members
why it doesnt show :pain:
😭
life-development
what am I looking at?
turkish
yet they keep trying sigh
@rose warren bypassing with an image this time
lol this is funny
automod
that word caused the message to be deleted and notify the mods of your infraction
how is it still there, but blocked?
only for u
no
oh bruh
you dont get notified, only the mods
ok what
it's like a silent alert
so how was i supposed to know XD
i did some code work saved on a college PC, i tried to get it from another one and now I can't find it 😭
oh, it's still there
but yeah, i;ll still not say it tho
you don't, simply be light on curses
L
i can't delete it
what the that thing just teleported
Segoe UI has only icons no?
discord is bugging on me
I never used the ui builder, I always made my forms though code
wait you guys are talking about the font no?
they're talking abt the winforms component not appearing, from what I understood
I don't think you should chain off an add call
whatever
tbh, I dont even know what ur attempting to do
this
and what is that?
html
I refer to the "thing" you're trying to show
yes, i load image and draw on it
its something that i made
which is the only popular thing i made
see my most popular repo on gh :teef:
Learning discord.js, what does type mean?
client.user.setActivity(
`Tutorial bot`,
{
type: 3,
}
);
That's the type of the activity
https://discord-api-types.dev/api/discord-api-types-v10/enum/ActivityType
These are the different types
I see.
So 3 represents a watching activity
Thanks!

How to speedup bot verify ?
You can't, as simple as that
Ok, thanks
Now I see that you are checking servers from 5 days ago, it's not that bad yet
How long does it take to review one request
They get to you when they do, no point in wondering how long it'll take. Queue times vary, there's a pin in #support for estimated times right now
I am interested in how long it takes to check one bot, 2min ?
Oh
I'm sure it depends on how many features that bot has. The reviewers are looking for things that break the rules of top.gg
Depends on how advanced the bot is, if there are any language barriers that needs to be translated during testing, ect
I understand, thanks for the reply
u sure?
yep
well its drawing on canvas, let me send code
export const createBattleCanvas = async (
cards: (
| Pick<
CollectionCardInfoProps,
"filepath" | "type" | "rank" | "id" | "metadata"
>
| undefined
)[],
extras?: {
isSingleRow: boolean;
version?: "small" | "medium" | "default";
}
): Promise<Canvas | undefined> => {
if (!Array.isArray(cards)) return;
const canvas = createCanvas(
CANVAS_DEFAULTS.width,
extras?.isSingleRow ? CANVAS_DEFAULTS.height / 2 : CANVAS_DEFAULTS.height
);
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
if (!extras?.isSingleRow) {
const bgPath = await loadImage("./assets/images/background.jpg");
ctx.drawImage(bgPath, 0, 0, canvas.width, canvas.height);
}
try {
const dh = extras?.isSingleRow ? canvas.height : canvas.height / 2;
const images = await Promise.all(
cards.map(async (card) => {
if (card) {
// const startImageTimer = loggers.startTimer("[Image] Path: ");
// load precomputed images with border and stars
let filepath = card?.filepath;
const version = extras?.version || (extras?.isSingleRow ? "medium" : "small");
if (card.metadata?.assets && card.metadata.assets[version]) {
filepath = card.metadata.assets[version].filepath;
}
// startImageTimer.message = startImageTimer.message + " -> " + filepath;
const image = await loadImage(filepath).catch((err) => {
loggers.error("canvas.createBattleCanvas: ERROR Unable to load filepath -> " + filepath, err);
throw err;
});
// loggers.endTimer(startImageTimer);
return {
id: card.id,
image,
};
}
})
).then((res) =>
res.reduce((acc, r) => {
if (r) {
acc[r.id] = r;
}
return acc;
}, {} as { [key: string]: { id: number; image: Image } })
);
return await new Promise((resolve) => {
for (let i = 0; i < cards.length; i++) {
const card = cards[i];
if (!card) continue;
const dy = extras?.isSingleRow
? 0
: (canvas.height / 2) * Math.floor(i / 3);
ctx.drawImage(
images[card.id].image,
(canvas.width / 3) * (i % 3),
dy,
canvas.width / 3,
dh
);
resolve(canvas);
});
} catch (err) {
loggers.error(
"helpers.adventure.createBattleCanvas: ERROR",
err
);
return;
}
};```
do you see any blocking code here? this function executes in less than 1sec max
yep
await
if ur going for async u need to go async all the way
but well, not to shoot the wrong target, do this:
const before = new Date().getTime();
try {
const cmd = ...;
// whatever u use to call commands
} finally {
console.log(`${cmd.name} took ${before - new Date().getTime()}ms`);
}
mhm alr
well i'am returning a promise
so that should be good no?
well, js has a little issue where tasks inside the promise constructor can halt the entire program (since js is mono-thread)
returning a promise doesnt change anything
hmm, so how do you recommend i go about this, cause using for loop directly is straight up blocking code no
hmm
canvas itself is sync, you cannot make it async
for example
console.log("Before")
new Promise((res) => {
while (true) {}
})
console.log("After")
ctx.drawImage is sync
although the infiniloop is inside a promise, "After" will never be printed
I cant really say THAT'S what's causing the freeze, put the measurer as I said before
then run the commands
the one that shows the biggest number is the one that's halting the prog
the only way to make it "async" is to break the loop into diffeent parts and manually introduce delays
which is not really recommended, you wont make it faster like that, just slower
adding delays? but if canvas itself is sync, will it still not halt?
hmm, i've added these logs and found no matter what image the canvas is ready in less than a 500ms - 1sec
actually
its even less i think
well, 1 sec is a fucklong time
just let the bot run for a while
when u notice the halt, look at the logs
hmm alr i'll give that a shot
but the question is, if i do find an image taking longer to be drawn, how do i go about it, if its an already down sized image,
all of my images are less than 100kb
filesize doesn't usually reflect the actual image size due to compression
no im manually downsizing them
in java I simply split the image in sections and render each part individually, merging into a final result
it might not be as fast as a single task, but it allows me to balance the job across some threads
idk how to accomplish that with canvas tho
i believe we talked about this before
i suggested pre-rendering the common stuff, like background
yep, im doing that
im precreating the image with required cosmetics like stars etc, then putting 3 images together
on the canvas
ig can do that, but will that still not become blocking?
cause takes cpu
youre still loading the images from disk
you can keep them in memory in separate canvas objects
any example i can use?
im actually loading each image from a url dynamically, and combining 3 images into 1 canvas
JavaScript function/method or library to make number strings?
e.g 1 > 'one'
oh btw, if possible, dont resize images during render
ah ok
jsut combining 3 images into 1 canvas
parseInt("string")
ah that, yeah i forgot to remove that from snippet but that isnt being used
No as in
Number 15 > String "fifteen"
and this?
const image = await loadImage(filepath).catch((err) => {
this is in the for loop right?
yes
search google for "npm number to long name"
this is where the image is loaded from a external url
how many different cards are there?
maybe i can store the image buffer once i get from url?
you can do something like ```js
let image = card.cache;
if(!image) {
image = await loadImage(filepath);
card.cache = image;
}
it will use more memory yes
memory is often used to make things faster
you have to monitor it
and if it gets too much you start balancing it out
for example deleting un-used caches
is there logic i can determine which ones are un-used
set timers, add timestamps for when a cache was used last time
mm
TTL collections
time-to-live
if its most used why would i use a ttl
ik i meant, if its frequently used
why ttl after some time and load again
nono, if it's recently used
let image = card.cache;
if(!image) {
image = await loadImage(filepath);
card.cache = image;
}
card.lastUsed = Date.now();
i see
anyway i g2g
cya, thanks for the help
LRU will remove the least recently used entries after some time
LFU will remove the least frequently used ones
the difference is that LRU simply moves the tail to the head on access
while LFU will store a counter to track access count
i see
I believe redis does
hmm
it all depends on your usage, try both and see what fits the most
alright, thanks a bunch
I for example use 3 levels of cache for my bot
a small, ultrafast heap cache, a larger but not as fast off-heap cache and a big slow file cache
the lib I use automatically manages that for me, the cache will go to the next level if it hits the size limit
cache is tricky to get it right, but it's a fun thing to implement
ehcache
yeah
it's a java lib btw
java, not "script"
probably, I believe all langs have cache-specialized libs
redis is good, but it's a single-level cache
well it says redis is an alternative wlep
perhaps there's a way to configure it for multi level
but u dont really need to go into multi level unless ur using a ton of assets constantly
my bot is a tcg bot, so I quite literally have to render an entire game (2d) for each frame
so I rely a lot on cached assets
i see
demm
well its been an interesting topic for me as well, effecient caching
i had problems before where the cache was not updating user info or the info in DB and cache were completely out of sync wew
because the updates were so frequent
u dont really need a cache for most dbs
unless ur dealing with clusters
or a big amount of clients
hey so, i got this object from the loadImage
{ image: [Image:236x315 complete] }
how do i store this in redis,
you need to serialize the image
i see, how?
idk what kinds of formats redis allows
if it allows bytes, simply store the image buffer directly
else convert the buffer to base64 and store as text
do note that base64 is 33% bigger than storing as bytes
i see, i mean how do i do that for the image
since it uses 3 bytes per 2 bytes (iirc)
in js? no idea
mm
gotcha
mmm
dem it only has onload, on error
height, width
there no data buffer at all in the image object
google time
ye not able to find anything lel
in java it'd be just image.toByteArray() lmao
canvas has some nice features like filters and named colors, but also a fuckin ton of missing features
well, all the solutions say i need to load image to canvas and convert to dataurl
makes no sense
I mean, converting to dataurl is probably converting to base64
since base64 is a valid url
yeah
try image.data
it does in their code
its private
hmm, alr let me try
js doesn't care abt privacy does it? 

lemme try it real quick
That’s C
I know
also, it doesnt really matter how you get the data from the image, because if you're gonna store it in redis then you need to use loadImage again to recreate it
so you might as well download the image using http and saving the buffer directly
then use loadImage with the buffer
but redis is not gonna improve your performance
hmm i see
i was gonna say image.data was undefined
so whats the optimal solution for this in that case
mmm
well the main goal is to reduce any blocking code
the problematic part of node-canvas is that all images have to be unpacked into the canvas format, which is what loadImage does
hmm
so no matter where you store the image data, you will always have to use loadImage before you can use it with canvas
i see, and drawImage is always sync
the only way to improve performance, is to store the loadImage result in memory
drawImage uses loadImage if you give it a url
the loadimage result is what i showed earlier
so the only solution is to store the result of loadImage in a variable
and reuse it
and not in cache?
the variable is the cache
for all the different cards?
so you can put it in the object as well
thats what you mean
but then i will have to loadimage at the start of the command
in that case
its the same principle as used by video games, all images are loaded into memory, before the game can run
it uses a lot of memory, but gives the game the performance it needs to run smoothly
you can check if that specific card is already cached, if it is, use it, if its not, use loadImage and save it so that the next time it will be already cached
so here's the thing
the card is not a global object
when a user invokes a command the card is fetch from db
then you need a place to store it, for example a Map
alr, so 600 * 9 is the number of images i have
more than 600 actually
will that not cause memory leaks
or should i wrong
ttl logic
so put a timer in the cache items
and delete those that are not used
its not a bad thing, but you dont need to use it either, there are other ways
for example
just trying to avoid memory leaks
hmm
while fetching from cache
i can delete?
but then it would only be deleted if it is accessed
const cache = new Map();
setInterval(() => {
for(const [key, val] of cache.entries()) {
if(val.time < Date.now() - 3600000) { // last used more than 1 hour ago
cache.delete(key);
}
}
}, 600000); // run every 10 minutes
// inside the command
... {
const cached = cache.get(card.id);
let image;
if(cached) {
image = cached.image;
cached.time = Date.now(); // image is used again, so reset time
} else {
image = await loadImage(card.url);
cache.set(card.id, {
image,
time: Date.now();
});
}
}
mmm
i was thinking the same logic, ig i have to give this a try
thanks a bunch btw, i appreciate it 
then you have to monitor your memory usage
and find something you're ok with
it will use a lot more memory, but it will be much faster when repeatedly loading the same cards
you can tweak how often to run the interval and how long to keep the cards in memory
hmmm
makes sense
i hope it wont cause any memory leaks. lets see, i'll give this a shot
i usually set my caches to 24 hours
will the for loop not cause any event blocks no?
same
looping over the Map shouldnt be a big deal
cant some images be generated procedurally?
no because they least used ones will always be deleted before that happens
gotch haha, dem boss, the load speed went from 1sec to loading all 3 images to 1ms
sikeee
haha cool
Does anyone know the cause for this bug? The bot will occasionally send improper emojis despite having the correct permissions and them being coded as proper emojis.
show code for both
the issue was a bug where if the message is a reply and everyone has the external emojis permission denied then they wont send
ah ok
If you did !eval process.exit() as a joke, and now your MongoDB isn't connecting anymore what should you do 
restart the process entirely
perhaps you shouldn't evaluate code like that in the future, just a tip
Yeah
Now MongoDB is eating me, getting errors I've never seen before.
node:events:491
throw er; // Unhandled 'error' event
^
MongooseError: Operation `bots.count()` buffering timed out after 10000ms
at Timeout.<anonymous> (/home/container/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:153:23)
that means mongo is not connected
The code is working locally, but not when I host it. Not sure why this error is only happening when I try to host it on the server.
have you setup mongo on the server?
atlas
Hm?
did you whitelist your host's ip address in your atlas configuration?
Don't think I need to
show your mongodb connection code
@quartz kindle is this correct code to make the bot reply if someone mention it.
const { MessageEmbed } = require ('discord.js');
module.exports = (client) => {
client.on('messageCreate', (message) => {
const mentionEmbed = new MessageEmbed()
.setTitle(`Hello ${message.author.username}!`)
.setDescription("To view my commands, use </help:0>")
.setColor('#4169E1');
if (message.content === `<@${client.user.id}>` || message.content === `<@!${client.user.id}>`) return message.reply({ embeds: [mentionEmbed]})
});
}
I can't try it on my pc since it's been gone for servicing.
Can u plz try and tell? If u dont mind
How do I get the amount of users in a server without bots included? I haven’t found anything online that helped I’m using discord.js V14
I love waiting for typedoc to finish compiling for 5 minutes straight
Not possible with fetching to exclude bots. You filter over the result and exclude bots
I read your question wrong. Just filter over the members and exclude bots
members.cache.filter
Thank you
Your editor should help you if you use vscode
I do
or any other editor with intellisense
great then learn how to use filter
Collection<K, V>.filter is the same essentially as Array<T>.filter
Or I could just have it pull the bots and the members then subtract bots from members
~~I've ran the webhook manager and pressing send test but im not getting anything on my end?
I'm listening to the on_dbl_vote event with discord.py in a cog.~~
I fixed it, was running on a test bot so nothing was firing.
Does anyone use vultr hosting ?
How often do they do “maintenance” this usually means all my vms are pretty much gonna be shut down no? How would I get high availability in that case
If I’m running things in production I can’t just shut down these Vms and wait for them to finish maintenance
do thye have a discord server
ty
hey is there a way for me cache the images loaded from path in nginx ?
async getImage(req, res) {
try {
const filename = req.params.filename;
const finalPath = `${STORAGE_BUCKET_V3}/${filename}`;
const { mime } = await FileType.fromFile(finalPath);
res.type(mime);
return res.compress(fs.createReadStream(finalPath));
} catch (err) {
if (err.code === "ENOENT") {
return res.notFound();
}
return res.serverError();
}
},
};```
So i have this code, and everytime the image url is called it serves from disk. which is not ideal right? because the images dont change unless its replaced
What you'd do is tell the client to cache the image and then the client sends an If-Modified-Since header
If it's been modified, you 200 send the image, else, 304
This can be done by sending a Last-Modified header to the client
Please read the mdn docs for these headers
Gotcha, thanks
for keeping a ws connection alive is sending an empty string once in a while enough?
If the server sends a ping, the client will answer with a pong
Should also work the other way around
The ws server you use most likely has them already implemented
In that case you need to implement yep, not super hard as you said
funny enough, I already had implemented a ping pong before, but the rate was the same as the conn timeout
made it half the timeout, should work correctly now
ping and pong are frames defined by the spec (op code 9 and 10)
whatever websocket implementation youre using should already have them
if youre making your own websocket with raw tcp then just implement them according to the spec
you can also have application level pings, like discord does, which uses regular data frames
those are mostly used for situations where the connection can break without breaking the actual websocket connection, ie a zombie connection
it does have the operation, but not the routine to keep sending ping frames
I was sending once every minute, but the timeout is also 1 minute
I just made it always be half the timeout time
@sleek marsh post your problem here. there is like 4k bot devs on this server 😄
ok sure
more like 12 on this server and 3988 on the list
have you guys heard about the new friend request link
yep
yeah, something like that 😄
nope
anyway to modify it on creation (make it unlimited)
so the problem in my code is that my core was missing in the code and to add it i did something terrific i deleted the venv file and now i cant restore it
uh oh

i dlted cuz it missed google trans package
if you used pycharm there is some sort of version control hidden inside somewhere?
so...a venv file represents a virtual environment, something akin to a partition
if u deleted it I don't think any source control would be able to store a venv file (nor they should)
i did it on repl ig u can check it if i give invite link of repl
https://replit.com/join/xmgzkgkzjd-pokemaster123
maybe u can check here ? i am not too much of coder
PokeMaster123 is inviting you to collaborate live on their Repl "deleted"
would it be much trouble to set a new environment up and copy your code files over?
that said, I believe u don't really need to restore it
i have it downloaded it but it wont load for any reason
if I'm not mistaken, venv is exclusively used for python packages
just reinstall those
it is a python code
like, venv doesn't contain your code, it's only a "place" where your code will be ran
together with its dependencies
That's exactly what i meant. KuuHaKu phrased it better though
Traceback (most recent call last):
File "main.py", line 1, in <module>
from core.apolex import apolex
File "/home/runner/radion-fixing/core/apolex.py", line 1, in <module>
import discord
ModuleNotFoundError: No module named 'discord'
this came when i tried to run
you'll need to pip all modules again
yep
