#development
1 messages · Page 196 of 1
so something may just not work on node
actually I think I already see an issue
ffs
DEBUG Running Router Promises ...
ERROR Failed to load route file /home/robert/projects/rjweb/server-new/test/routes/random/bytes.ts
ERROR Failed to load route file /home/robert/projects/rjweb/server-new/test/routes/test.ts
DEBUG Running Router Promises ... Done
DEBUG Running Middleware Promises ...
http2 is the same except with binary frames
it has its uses and mitigates certain vulnerabilities caused by misconfigured servers which is cool
think browsers use it by default
but fall back to 1.1 no problem
http3 is completely different it uses udp for faster transmission
so it avoids the tcp handshake and error checking by using its own http optimized error checking
ye but for instance, if you were to make http2 from scratch using only tcp
since http2 can work with multiple data streames in the same socket
its probably not gonna be that simple
to make it compliant with the spec at least
i would be very interested in making a quic ipc lib tho, whenever node decides to add quic sockets to its net lib
Make your own impl 
yes, my own quic on top of node's net udp
http 1 is annoying as well since theres a lot of stuff
theres also chunked encoding via transfer-encoding: chunked which allows you to send a body in chunks
as well as connection keepalive and shit
upgrades
and all other weird headers
i wonder why discord never implemented stuff like messagepack and protobuff for its ws encoding
as additional options to json and etf
protobuff would honestly be amazing for discord
yeah but probably for simplicity or they just werent aware of it when they started writing the api
json is extremely annoying to parse
i think javascript somewhere partially uses simdjson which is very good
simdjson is the fastest json parsing library since it doesnt parse the entire object right away
you iterate through the object and consume values once
so you can store parts of the json until you need them later and parse them
I made a parser for my cursed json-like library that saves character space that just walks over the string once and adds properties to the current object as it traverses. Could add circular support at a later time but nah
It's actually easy to do
i like binary formats so much more
sure they are not human readable
but they are so nice to make and parse
very fluid and very efficient
can save more space at the byte level yeah but I needed utf 8 and less characters
i never finished my binary format, is abandoned in a drawer somewhere
but it even had string compression
and context sharing
and fast object key decoding
and object key deduplication
lmao
is it kind of like json but binary?
kind of like messagepack but better
it even had a variable bit length float format lol
instead of only float32 and double64
it was a very shitty idea i had but it actually worked pretty well
so you can store stuff like 1.5 in 1 byte instead of 4 bytes
I hate debugging
Error [ERR_HTTP_HEADERS_SENT]: Cannot write headers after they are sent to the client
that error is quite self-explanatory
xDD
skill issue
Worry about getting shit to work first
compression is easy, just zlib everything
Hey Tim, speaking of encodings, is wetf better than the etf enc/dec you had in tiny-discord that's also in cloudstorm?
slightly better yes
Time to add it as an optional dep
decoding is mostly the same, only marginal improvement
encoding is a big difference
but encoding is rarely used in a discord lib
so i didnt focus much on it before
Wouldn't be surprised if Discord uses your lib instead of erlpack
lmao
They would probably like more cpu time
discord doesnt use js anyway
their own erlpack is a c++ wrapper for js and python
just to help people decode their shit
ye ik
is that the only place where you have res.writeHead()?
yes
I get one log from it per request when I add one
it doesnt die on every request though
OH
I may have found the issue
if (eTag) {
if (context.headers.get('if-none-match') === eTag) return rawContext.status(Status.NOT_MODIFIED, STATUS_CODES[context.response.status] || 'Unknown').write(new ArrayBuffer(0))
context.response.headers.set('etag', eTag)
}
so it is calling it twice
idk why it didnt log but alr
the code senses im tired i think
hue
nice
sir
if someone provides a full response body, do I stream it for compression or just do it all at once too after compressing
depends on how big the body is i gues
if its like bigger than like, idk, 100kb?
stream it, else compress at once, but idk
are there many uses for that level of precision though
reducing bits like that has its own overhead and adds complexity
so theres probably not that many uses for it if not many things have it
i dont remember what kind of precision you can achive in 1 byte
its been a while since i had a computer science class lol
but for that id imagine a 6 bit mantissa 2 bit exponent?
unless you want more decimals so a bigger exponent in that case
best programmer in the world right here
obviously not it doesnt even work 🙄🙄🙄
localhost is bound to internal connections only, silly!
something tells me this isnt ascii
i actually dont use the same format as floats, my exponent and mantissa are base 10 because i dont fucking understand dafuq they do
but yeah, its 1 bit exponent, 7 bit mantissa
then 2 bits exponent, 14 bits mantissa
and increase as needed
is there something wrong with this? like it corrupts but on the streams the response is delayed by exactly 5 seconds?
in school they taught us how to work them out on paper lol
its worth learning it honestly
especially with the things youre doing
theres a thing with compression streams where it waits for more data before outputing anything
you need to explicitly drain it i think
ä
but like, why overcomplicate it when base 10 is so simple and works just as good
its also faster than calling buffer.writeFloat32BE or whatever
how are you even storing it as base 10
i think you can but you will lose negatives and positives
or youll have to spend an extra bit to add them
yeah the point of twos complement is to avoid wasting a bit to figure out positives or negatives
what youre doing is called sign magnitude
yeah
but i already use 1 byte to get the content type anyway
so i dont lose anything
give me a number example
what do you want specifically
any float lel
2.35
that will take 2 bytes
expo = 01
mantissa = whatever the binary for 235 is
so 10 bits
i know its dumb and dead simple, but it works quite well in practice, can save a lot of bytes if you're encoding a lot of small floats
like coordinates or something
its essentially how floats work actually but without the mantissa and exponent being represented in twos complement
the positioning of your decimal is probably different too
but same concepts
yeah
but IEEE floats do some weird math shit
whats IEE if you dont mind me asking?
Double-precision floating-point format (sometimes called FP64 or float64) is a floating-point number format, usually occupying 64 bits in computer memory; it represents a wide dynamic range of numeric values by using a floating radix point.
Double precision may be chosen when the range or precision of single precision would be insufficient.
In t...
IEEE = Institute of Electrical and Electronics Engineers
all of them
institute of efficient electrical electronics engineering extra economics entrepreneurship enthusiastic excelent excelled exceeded extra ergonomic entropic energetic energy erlang earth
probably yes, but idk
Is it better to self host or use vercel for a nextjs app?
Depending, likely Vercel as it's built for nextjs
haven't used it myself but seems really raelly good
That's exactly what i told you zerls!
vercel does have limits for stuff like middleware to be aware of
Only downside of free tier imo is maximum function execution time. Something like 10s. Which isn't GREAT
how long do you need said function to execute
depends. something like ai image generation without using app router for streaming, can take upwards of 1-2 mins
it's actually not too hard
Here's an example for 11.125
take the first part before the decimal point, convert to binary
11 = 1011
take the second part after the decimal point, convert to binary
0.125 * 2 = 0 + 0.25
0.25 * 2 = 0 + 0.5
0.5 * 2 = 1 + 0.0
(Stop here because you got + 0.0)
0.125 = 001
Combine them
1011.001
Convert this to scientific notation by moving the decimal point to the right of the leftmost 1
1.011001 * 2^3
The bits after the decimal point are now your mantissa
Mantissa = 011001 (Plus trailing zeroes and such)
If you're doing single precision floats (4 bytes), your "bias" will be 127 (for double it'll be 1023, follow the same process)
Add the exponent to the bias (the 3 in 2^3)
127 + 3 = 130
Convert that to binary
130 = 10000010
Then you have your final answer after you set the sign bit (1 for negative 0 for positive)
0 10000010 011001 (Trailing zeroes here for however many bits you need)
^ Sign ^ Exponent ^ Mantissa
This was an easy one since 11.125 can be perfectly represented by it but the only difference if it can't be perfectly represented is that your mantissa bits will be more detailed (Just repeat the process for getting the bits after the decimal point until you're out of bits)
Hope this was a decent explanation, that's what I found works best for me
so the fraction part is multiplied by 2 N times until its a whole number?
sounds convoluted af lol
Basically it's binary but past the decimal point
You know how binary goes 2^0, 2^1, 2^2, and so on?
and for example, you needed to multiply 3 times, why is it 001 and not 10?
It's basically the process for converting to 2^-1, 2^-2, etc
You see the (0) + 0.25, (0) + 0.5, (1) + 0.0
It's the number in the front that determines the bits
Here's an example for something that's a bit more complex
also why is the leading bit removed from 1011
0.11 for this process would be
0.11 * 2 = 0 + 0.22
0.22 * 2 = 0 + 0.44
0.44 * 2 = 0 + 0.88
0.88 * 2 = 1 + 0.76
0.76 * 2 = 1 + 0.52
0.52 * 2 = 1 + 0.02
0.02 * 2 = 0 + 0.04
Repeat for however many bits your mantissa is for maximum precision
So you would get 0.11 is approx .0001110
For the IEEE format there will always be a 1 there in all cases
So it just removes it since it's not significant and doesn't tell us anything about the number
so thats where the precision is cut off
Yes
when you run out of bits
but basically
But some numbers just aren't possible to represent perfectly in a finite amount of bits
the whole concept of this format is to make it easy for the cpu to do math with it right
in some way the cpu can do fast math by moving bits around
Yes the FPU is designed specifically around this format
because from a number>binary>number conversion stand point, the whole format is super convoluted and makes no logical sense
which is where i look at it from
so its confusing to me
It's for math and so that we can also represent very big numbers while doing big calculations with them
After all, we designed computers with the intention of using them for highly complex calculations
yeah
i understand a bit better now thanks, but its still weird, because i can only see the conversion difficulty side of it
I feel that it's partly due to the implications in astrophysics, where numbers are so huge but also need a lot of precision to work with
Since we basically worked on a ton of computer shit solely to go to the moon lol
hard wired to do these calculations its pretty cool
but most of the bulk is done by a C library lol
But yeah, I can't speak much to the actual hardware components, but I do know that there are circuits specifically designed to take advantage of this format and reduce CPU cycles needed for floating point arithmetic
yeah thats basically what it is
Yeah SIMD is designed for that sort of thing too
i know cpus have specific instructions dedicated to do fast float math
a lot of calculations it cant even do in a single clock cycle so it needs its own clock too
Yup
but faster than the cpu can for sure
fpu's never used to be integrated in cpus
it used to be a motherboard addon
3 complex 5 me
wired to the cpu
bruh
cpu engineering is so amazing, i really cant grasp my mind around it
It's interesting stuff but I really have no intention of studying more of the hardware, since I'm not a computer engineering major
compression didnt work because this.getCompression() returns brotli, not br
ah lmao
same, I just took a screenshot of my slides lol
im planning to design my own CPU with its own ram and everything with an FPGA
cool project for the future
yourecrazy
This is the stuff you're talking about with the SIMD instructions @quartz kindle
ye
AVX-512 for example has 512 bit space of calculations
which can be divided into a ton of smaller ones
and be done all in a single cycle
looking at all of this crap makes you feel really small and humble lol
like idk why people look up to me, i dont know shit
To be fair, a lot of people spent their entire careers studying these sorts of things in order to invent them
Man some more nerd shit going on that I dont understand
What may take us a few minutes to understand likely took a lot of very intelligent people a long time to come up with
i think for simd you need to copy over the data to some special cpu registers so whatever calculations youre doing has to be worth the transfers and copies
same with the gpu really
Yeah it's in separate registers
mathematicians literally spend years/decades on a single problem
its the optimizations clearly
if i need my js code to run the speed of c i know who im going to
If you want the slides I have @quartz kindle I can send you a pdf
They're not super detailed but can definitely help with looking up more specific questions about it
Z_SYNC_FLUSH is only for gzip and deflate
for brotli its zlib.constants.BROTLI_OPERATION_FLUSH
yeah, sadly doesnt fix the issue either though
nope
ohhhh
sir
I should not code while half asleep
im assigning content-length
yeah
works fine now
ok Im gonna go to sleep
cool
@rocky turret ah just checked modlogs to see what was the issue, how did you list that command on ?help?
like, how does it appear there?
[i for i in cog.walk_commands()]
you can't say role hahahaha command exists lol
didn't mean that
how are you showing the command list to the user?
the help embed, not the code
I'm making a list of all commands from that cog and sending it
sigh
I dont mean how you're doing it through code, I want to see how ?role appears on the command list
ok wait
this is very likely why they thought there was a command named role list
did you, at some point, have ?role list there?
that's auto, never
do you have a help (or command list) command?
yes ofc
Btw your date field is messed up
dont care
Just thought I’d point that out :)
Okay grumpy
(lazy)
btw I HIGHLY recommend structuring your command list another way, there's no background color for inline code on mobile
ok so, my bet is that temprole list got wrapped, making it appear as role list
You mean this?
no connection between those two commands...
what? no, I mean this appears without the darker background
not what I said
But it helps user to understand it and make it highlight?
I said that command might've been wrapped due to screen size, so instead of temprole list it appeared as temp
role list
...you're not understanding what I mean
nope no way
yeah
on mobile all you get is the different font, no black background
discord changed that a while ago, don't rely on the darker bg
it can happen
which is why I use column format on my bot's help command
at least there's no risk of mobile breaking it when there's only 1 cmd per line
What’s the +2 for
doesn't happen with zalgo text
zalgo combine with the original text, but what does this even have to do with what I said?
I'm giving u the probable reason as to why they thought ?role list to be a command
if you think this isn't the case, ask them
asked her she is off..
So I have this help command, it looks somewhat fine on pc, but inline not supported on phone, its super long and looks messy, any of you hvae any idea or tips for a good help command?
coalesce subcommands into a single help entry, when possible
Could split each category of commands as a paginated help menu.
Another suggestion not relevant to the question but should make the aliases consistant between the commands. Like chose a side you like them on since I'm noticing some are on the left side and some are on the right side.
plot twist: list is actually an alias of l 
siri: list all my L's
will try
ah yes, thank you
sorry, didnt got to reply earlier, was busy with works
is it possible to have text input parameter on a slash command AND a select menu?
Well select menus can’t be user input text
Also iirc select menus values can be any primitive type
i ended up finding the document to do what i was trying to do lol
the question i asked wasn’t really clear sorry
Does anyone know that Restorecord leaks ip
Does Top.gg have restorecord bot on their site, if they do, it's a real bad situation
No, there is no such bot on the top.gg website because it is probably not even a bot, but rather a website/service that does not have a physical bot
Not every application is a bot
Hey guys, getting 413 payload too large using nextjs on vercel. I've set the config in my api route to an extremely large size just to prove to myself that this was not working regardless of the size i'm posting.
export const config = {
api: {
bodyParser: {
sizeLimit: '1gb' // Set desired value here
}
}
}
but i'm still getting the error. Does anyone have any idea why this might be? (using cloudflare too in case that's relevant)
Cloudflare limits the request size by default if you're on the free tier
Iirc, it's like 100 or 250 mb - but you'd have to double check
ah okay cool thank you, found a reasonable solution.
convert b64 to blob url --> send that to backend --> convert back to b64
Just wondering is there any reason why it wont return my data in the Site?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dashboard</title>
<style>
</style>
</head>
<body>
<div id="info">Hoi!</div>
<a id="login" style="display: none;" href="https://discord.com/oauth2/authorize?client_id=1182682121094049923&response_type=code&redirect_uri=https%3A%2F%2Frosearcher.xyz%2Fdeveloper&scope=identify+email+guilds+guilds.join">Login</a>
<script>
window.onload = () => {
const fragment = new URLSearchParams(window.location.hash.slice(1));
const accessToken = fragment.get("access_token");
const tokenType = fragment.get('token_type');
if (!accessToken) {
document.getElementById('login').style.display = 'block';
return;
}
fetch('https://discord.com/api/users/@me', {
headers: {
authorization: `${tokenType} ${accessToken}`,
},
})
.then(result => result.json())
.then(response => {
const { username, discriminator } = response;
document.getElementById('info').innerText += ` ${username}#${discriminator}`;
})
.catch(error => {
console.error('Error fetching user data:', error);
});
}
</script>
</body>
</html>
This is EJS btw
check console
you should really be doing that all server side
also discord returns a different type of token which you need to turn into an access token first
Hi,
I've stopped getting vote webhook calls from 8th April, nothing has changed my my webhook and I've verified the password, tried resetting the password as well. But still not receiving any new vote webhook events.
Any ongoing issue? or something that I'm missing?
did you try a webhook tester?
there should be a delete button in your bot's edit page
just add /delete to the url
Yes, it says "Your test webhook request was sent!" but I'm not receiving any event
thanks i deleted it
i mean, a webhook tester like https://webhook-test.com/
Experience instant, free access to a unique URL and email address at webhook-test.com. Test, inspect, and automate incoming HTTP requests effortlessly with our powerful tools, including a visual workflow editor and customizable scripts. Streamline your testing process and enhance your automation
put the test url in your top.gg and send the test there, see if it shows up
+1 for that site, works without hassle
Received the event there :/
then the problem is on your end
where is your bot hosted?
on a vps
it used to work fine tho, nothing changed on my end.. I'll try to check what's wrong
double check your vps's ip, ports, firewall, code
use a request tester like https://reqbin.com/ and try to send a manual vote yourself to see if your vps receives it
Thanks
Oh cool an api testing tool that runs in the browser!
Found the issue, thanks a lot for help @quartz kindle ❤️
cool
theres not that many because it has to go through their server first
cors and browser restrictions and everything would otherwise fuck it up
@lyric mountain , in java if we have a try-catch, if it's a regular exception that occurs in the code within the try clausule it will always execute the code in the catch right. Then i am a bit confused as for why we have throw?
Is it to define new custom exception labels? Like: throw new RandomFuckinName("some reason here")?
Exceptions aren't always thrown by the runtime itself
Exceptions sometimes need to be thrown by the programmer
Like if you have a function called "parseInt()", you'd want it to return an int. But what if a string is passed that isn't parse-able? You'd need to throw an exception, something like IllegalArgumentException or something
ye, its pretty heavily rate limited
if you need power testing, you'll need something stronger, like postman
there are 3 types of (base) exceptions:
- RuntimeException: might happen due to input validation or other conditional errors, meaning that with proper handling it shouldn't happen (optional)
- Exception: might happen due to errors outside programmer's control, like IO issues
- Error: catastrophic errors that should never be handled, else it might cause serious runtime issues
all exceptions will inherit one of those, usually with a predictable naming pattern
as waffle said, most exceptions will be thrown by the developers themselves, to prevent the runtime continuing execution of that scope
let's take runtimeexception for example, a very common example is IndexOutOfBoundsException, meaning you tried to access an invalid list index
if it weren't for the exception, whoever is using lists wouldn't know about the illegal access, and the issue would be fairly hard to find out where it happened as you dont have a stacktrace for it
for exceptions, a common example is IOException, which happens when you try to read or access a file that either you cant or doesn't exist
Personally I've always hated the exception system ever since I started using rust, but I can see how it was a major step up from C/C++ where an error was usually completely silent
this type forces you to write a try-catch block, as it's an error that's required to be expected since it's outside your control
for errors, a common one is StackOverflowError, you know how it happens
once an error happens, the runtime is supposed to exit, as the side effects are usually catastrophic
you can still catch it, but shouldn't
js is a good example of this, when shit happens you better call sherlock to find where the hell the issue is
good thing people adopted exceptions there
ahhh i see
so it's basically to create specific custom runtime exceptions given your program and whatever you don't want to happend
arigato guys
you can create any of those 3 types
but runtimeexception is the one mostly used, unless you want to force the dev to write a try-catch block
Yeah the IndexOutOfBounds check is pretty much ```java
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index " + index + " out of bounds for size " + size);
}
I for example use a ConfirmationException to force myself to put try-catches whenever I use my command-lock feature on my bot
since it prevents using certain commands till the user confirms it
had way too many cases where I forgot about it and people could transfer stuff while in a trade
so forcing me to write the catch kinda helps remembering it
i see that's pretty cool!!!
Idk i am trying to pick up some far-lost java principles that i once learned but didn't use for a year or two...
This breaks my current understanding of js arrays. In that sense, are they more like Maps where each entry is keyed by something but by default when pushed it's the next seq number?
and an out of bounds check is as simple as checking if a key exists or not
If you pushed more data into this array, how would slice(0, -1) work?
it doesnt
oh it throws an Error?
the array part of it only works on normal indexes
anything other than that is treated as an object
so its an array and an object at the same time
Makes sense. Everything inherits from Object anyways
ye
any key that is not in the 0-32bit range is not affected by array methods
can only be accessed directly like an object key
or using object functions like Object.keys
the -1 from indexOf is the "not found" index, not the actual -1 index (for clarity)
mfw keys are converted into strings
yup
I dont like Objects for that
Or rather, Records
it's just js not being strict on being an array
Had a bug in my lib where trying to get a shard by ID or finding it by ID would always fail since even though I assign a number, it's converted to a string
keys are always converted into strings
so it's advised that you do the conversion
or use a Map
Yup
is it safe to say djsv14 is easier to use than 13?
I don't think it comes down to how easy it is to use. It comes down to which one is still maintained for the latest Discord API versions. If you're putting off updates because the lib becomes too difficult to use, then it's time to switch libraries
the older the lib, the easier to use :^)
how would my slash command get a user that isn't a member? the slash command can only be used in channel
https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-object-resolved-data-structure
fetch the user
so they could still be a member even if they dont show up in the members object? this is the first time i've seen this happen
i have an interaction URL and my data.resolved looks like this
"members":{
"1":{},
"2":{},
"3":{}
},
"users":{
"1":{},
"2":{},
"3":{},
"4":{},
}
}```
so they referenced a user that isn't a member of the server perhaps?
or discord just forget to send the member info for that user
what type of interaction is that?
slash command sent from a channel in their server, not a DM
and the command has an option to chose members?
it's a string input. they can reference multiple people per input
string type? not mentionable type?
i didnt even know discord would resolve strings lol
you can, just only those who are friends with them or share servers with them will be able to click on the mention
really?
nope
what kind of buttons are these?
most likely buttons with a zero width space as the labels
Does anyone know why if I press a button on my bot a message appears that can only be viewed for me? I use the bdfd bot and I didn't put $ephemeral anywhere
If you're using the app as a personal app, then all responses are ephemeral in guilds > 25 members
You could also double check the events. Or use the search function to search for ephemeral.
Or yeah, could be a personal application as well. In that case, refer to PapiOphidian message.
Oke thanks
It doesn't work
personal app in what sense?
Apps that you can use anywhere even in guilds that dont have the app added
Let me explain better, I have that problem with any command and this thing has been going on for a week but I haven't added any new commands and I haven't changed anything
BFDD don't have their own Discord server? I don't think anyone here is familiar with this program and how it works, so it would be better to seek help from a community that knows it better
It is but nobody is online
I was hoping someone could help me...
nobody here uses bdfd, thats the problem
They are certainly not active on this channel
yup
that's what tim meant lul, that nobody here (active) uses bdfd
Broken indeed
funnily enough burp suite the tool we use for pentesting is one of the best http clients
because its for pentesting it supports basically everything you can do with http
other http clients i find to be massive bloatware
and they dont even do what their entire purpose is well
it lets you also manually modify the http 1/2 request so its great for testing custom http server implementations
portswigger the company behind it is very cool
they also have penetration testing labs on basically every attack there is completely for free
ok so i have this giveaway command
how would i go about creating a new command that will end the giveaway, or reroll it? is that something i need a database for?
most likely yes
if you really dont want a database you could just extract the data from a giveaway message if its there
fetch reactions to reroll etc
So, I has a question for your very experienced developers
Does anyone here know of a service that allows me to verify people's age/documents?
stripe
Stripe is for payment stuff
Stripe also does age/document verification
Its what discord uses to verify your ID when you verify a bot too.
well I def want to learn databases, but I was working on a giveaway command and it just made me wonder about making a reroll or cancel command for giveaways
and I assumed it would involve database with the logic i had in mind, but wasn't sure
rocket
its not 1:1 to express
but its one of the best ones and has a lot of support
instead of middleware it has route guards
rocket requires nightly rust, no?
no
its just recommended
it will still compile and run fine
although null brings a good point, I highly recommend using nightly with rocket.rs (even if its not 100% required)
most likely
yes
definitely not the second one

the entire point of writing an api is to group the endpoints together
so for example, /guilds /users /whatever
Btw I’d recommend learning rust before going into async rust. Very different languages
I think he's been using rust for a while now
Not for long enough I don’t think lol
I on the other hand threw a hail mary and said fuck it
So now I am learning rust while learning async rust

Just look at me, I didn't know a lick of rust
I went right for async rust

Do you know C++ or much about memory
I’m not saying that it’s impossible but you’re going to make your life hard without knowing about memory
Idk much about memory and im doing just fine 
I only know the basics
like how it works
Not understanding why the borrow checker is good is going to lead to a lot of clones and copies that aren’t necessary
yea
me and the borrow checker have a love hate relationship
I try my hardest not to use any methods that create a clone
but sometimes I say fuck it
and sometimes its needed
Borrow checker is literally just references and pointers (from my perspective)
my rule of thumb is, always have a method accept a reference of something rather than letting it consume the value
this might be bad practice
but I find 9 times out of 10 I'd rather it accept a reference then the actual value, since i need the value later on
Hm?
If you give it the value the function consumes that value until the end of the function
so if you are using the value after calling that function rust doesn't know whether or not it is free, because now that function has consumed the value
so you can either
A. Clone the value if it is clonable
B. Pass it in as a reference
C. Something else I have yet to figure out :)
nope
if you want for whoever use the function reuse input value later after calling said function use a reference
otherwise, consume it
but misty was right, try to use less of .clone() or .to_string() as possible
you want to work with more of &T, &str, or &[T]
any type that is a reference yes
I love lifetimes
I love them
took me around a month or two to get used to the concept of lifetimes lmao
I don't even want to touch them
I've yet to run into a case where I actually need them
struct Wrapper<'a> {
reference: &'a String,
}
fn thing<'a>(input: &'a String) -> Wrapper<'a> {
Wrapper { reference: input }
}
``` here, the returned `Wrapper` will have the same lifetime of `input`, as it holds a reference to `input`, basically Rust knows that `Wrapper` will never outlive `input`
the lifetime `a` here basically means that it will die when the `input` String is freed
(:
I will forever avoid lifetimes until I actually need them
I know how they work
but no ty
also at that point why not use a string slice rather than String
I know
I was just curious why you chose String over str
sorry
thats how you specify a lifetime
it's a lifetime generic
rust doesn't let you use ' except for lifetimes iirc
here, the lifetime is a, you can name it anything u want tho
and chars
normal convention for lifetimes is to go through the alphabet tho
a, b ,c ,d, e ,etc
some libs opt for a word
yea
but the standard is a single lowercase word yes
pretty much
Basically what null said is the compiler/runtime knows that Wrapper will exist as long as input does because it has the same lifetime
if what null said was confusing
thank you for rephrasing it ❤️
tbf most tutorials/guides on the web about rust lifetimes suck
made me quit learning rust once
if you think about it, every rust reference implicitly has their own lifetime
Right guys
Here me out, if I only want to verify someone is 18+, then could I not make a bot that reads an image of an ID, look for the DOB (Date of Birth) and then compare the date to todays date
Why pay a company an enourmous amount of money if all I care about is whether or not they are 18+
well people could fake that ID
who cares I am doing my due diligence
Discord can't blame me 😎
I also don't want to pay $1.50 to stripe just to verify someone's identity nor the other resources out there charging much much more
Pain in my ass ong
yes
stripe charges $1.50 per check if you use images
or $0.50 if you have them put hte information in themselves
💀
I am using python with easyocr
tesseract?
this only works for US ids tho who literally display DOB on their ids
foreign ids don't
tesseract is terrible ngl
It got a lot of stuff wrong
Foregin Ids don't have DOB 00-00-000
oh in that format?
they index it based off numbers
like 1. 00-00-0000
US makes it stupid simple, because americans are stupid
they'd probably get the issued date mixed with their date of birth 💀
icic
yummy!! data ❤️
Lowkey fixing to say fuck ML and just do manual verifications cause like
fuck
too hard
no wanna do it

Honestly might
Also have to stress to people that all we want to see is their DOB and picture all the other stuff can be blurred
cant wait to become ID reviewer of the month
Hi
How would you auth requests from a person (idk if I asked you this already). What I currently do is create a token for a user and then query the db based off the user id in the cookie to verify if the token sent through the auth header matches the token attached to the user id
Do you use JWT etc
no
Because that ensures it can only be a token signed by you and then verified by you
Otherwise I could just edit the user id in the cookie or token and impersonate another user
lol
Actually wait
this wont work 😭
FUCK
JWT are so weird though
You can't revoke a JWT so it just exists until it expires
but what if the user logs out
Majority of companies that do ID verification of any sort have a manual review. GitHub literally does a manual review for your student ID to see if you qualify for the education package
Yea I just don't know the legalities of this, as this isn't for a company per sey but for a server
@quartz kindle @lyric mountain do you know how to retrieve the redirect URL by fetch()ing it? say https://github.com/actions/setup-node/releases/latest and i want to retrieve the https://github.com/actions/setup-node/releases/tag/v4.0.2
it's just res.url
thanks
they do indeed
i literally just show them i have education microsoft 365 and they go yep youre in
bc we dont do student ids here
yeah which is why i avoid JWTs
JWTs are good but you can mess them up easily as well
because youre literally entrusting the user to send a valid JWT that wasnt modified by anyone else
only thing between that is a cryptographic signature
and implementing a mechanism to invalidate them is annoying enough to the point where its just easier if you do a traditional session token
Do any of you know how to make js async functions run as sync like if I can block the thread until the task executes, but for stuff like while, idk if it all runs on the same tick or what
If you ask why: exit handlers cannot have any async code or calls
theres actually a lib for that
but not sure if its needed anymore meanwhile nodejs might have added a way to do async stuff on exit
@quartz kindle is probably more qualified to answer that
not possible
its possible to run async before exit on certain cases
what cases are that
there is the beforeExit event, but it only works when its a natural exit, not a forced exit/crash
then some termination signals allow for the process to continue
others dont
depending on the OS, the signal received from ctrl+C may be different
its probably gonna be easier to use a lib for that, theres too many different cases to handle
unless you know exactly the type of exit you wanna handle
i mean, you could always use writeFileSync
and store them in a txt/json lul
but try one of those libs
That's what I'm doing, but I have some queues I have to destroy cleanly which is an async task
you can do the clean destroy on restart no?
mm. I guess?
or you can have a separate scroipt for that and run it using exec/spawn
stripe doesnt either. Discord support had to adjust something so it would accept mine again
in brazil there is an official government app that requires you to face id with your phone to login
they compare your face with the face they have in their records, which is the image from when you had your id card or driver license done
so yeah, it never works
and then after it fails a few times they lock you out for 24h
and theres no support and nobody you can talk to to get it fixed, besides going personally to some office in bigger cities
governments should have no interest in tech
they always deploy the modern way of doing things but they never make sure it works properly
it might work in development but in production theres a million other factors that come in play
to view my tax account i had to submit a few documents one of them being a passport from said country
but i wasnt from that country so i didnt have the passport they wanted so i was locked out from my taxes
until now a few years later where they actually fixed it and let you verify with other documents instead

lel
you were right there was an $ephemeral in the command for calculator and it was outside the customID
sure but its primary use is for your server to know and identify an oauth request
ideally it should be a completely random ID that your server can then lookup in some cache to get info about the oauth request
if it doesnt exist then it should reject it
you mean global variables?
but yes in the native programming world theyre called global variables
and they live with the program
i dont use rust really but id assume it would be just like defining any other variable except outside of a function
ill checkl
ah compiler even told me
rust has some of the best error messages of any language
but yeah something like this
youd use static if you need to share that variable and change it, and use const if you just need a value there and it will never change
kinda like an enum/constant
That’d only be usable in that file btw, if you want to define something usable anywhere throughout the project check out once_cell or lazy_static
yep
show some of the code around it
but looks like you cant make it mutable for whatever reason
He’s borrowing something that’s not mutable
STATE_MANAGER is immutable and you’re passing it to a function that expects it to be mutable
youre probably doing something wrong then
i assume its this call that wants statemanager to be mutable?
but that wouldnt be borrowing it?
Yea, he said generate_state takes in a mutable self
ah
can you not make a mutable static variable?
you shouldnt have to do that
defeats the point of rust
yeah dont think you can make a mutable static
classed as unsafe
why does that statemanager needs to modify a reference of itself
probably so the state can be shared across multiple routes/functions
use dotenvy::dotenv;
use google_cloud_storage::client::{Client as StorageClient, ClientConfig};
use sqlx::{postgres::PgPoolOptions, Pool, Postgres};
use std::env;
pub struct App {
pub stripe: stripe::Client,
pub db: Pool<Postgres>,
pub s3: StorageClient,
}
impl App {
pub async fn new() -> Self {
dotenv().expect(".env file not found");
let connection = PgPoolOptions::new()
.connect(env::var("DATABASE_URL").unwrap().as_str())
.await
.unwrap();
let config = ClientConfig::default().with_auth().await.unwrap();
Self {
stripe: stripe::Client::new(env::var("STRIPE_KEY").unwrap()),
db: connection,
s3: StorageClient::new(config),
}
}
}
.manage(App::new().await)
boom
i need to learn rust
looks good actually
looks like it will also verify that input is the expected datatype since you can define a struct as a template
If you use rocket its even easier to handle json input from endpoints
use rocket::{
http::{Cookie, CookieJar},
response::Redirect,
serde::{json::Json, Deserialize},
State,
};
#[derive(Deserialize)]
pub struct Login {
email: String,
password: String,
}
#[post("/login", data = "<login>")]
pub async fn login(
cookie: &CookieJar<'_>,
login: Json<Login>,
state: &State<App>,
) -> Result<Redirect> {...}
then its just login.email
though you can use the serde_json package if you are wanting to do it in any project
Yep! It will also error if its parsed incorrectly
e.g a key is missing
ok question.. might be a dumb question.
as far as the giveaway command that i was talking about
does it make sense to add a “reroll” button on the embed that announces the winner? like is it possible to have the bot retrieve the data from the collector of the lobby message and reroll it? idk if my question makes sense logic-wise
The way I handle a re-roll type of system in my giveaways is by storing the entiries in my database. The winner by default has a flag set when they've won so if they need to be rerolled I just grab the entries without the flag and chose a new one and flip flop the flag.
ok i’ll have to study databases more, tim walked me through the concept and set up on the charts on better-sqlite3 but i’d have to read and practice it a few more times
I use Maria but I'm sure they're similar
Not like that
yep
if you wanted just normal params you can also do /redirect/<code> for future reference
it depends what you do for giveaway entries
if you make people click a reaction to enter and that reaction is kept then you can fetch all reactions and select a random person
but if its a button or you remove the reaction then you have to have a database
id say its quite smart to make it a reaction since youre basically forcing discord to be the database
but then reactions can be unreliable and annoying
i gotcha, ok i’ll just figure out how to set it up with sql
should be quite simple
first make a table for storing giveaways, in that table you should have giveaway name, giveaway id, giveaway contents, etc
then make a table for entries in the giveaway which will have the id of the user and the giveaway id it belongs to
You can return pretty much anything
will i have to have a logic coded within the giveaway.js for generating a giveaway id?
how you wanna make the giveaway id is up to you
you could make the database make one automatically by having an autoincrement field
or you could make your own by generating a random string or number and using it as id
or even use the message ID of the giveaway message as ID
shouldnt be too much logic though
if i have a slash command, e.g /enter <username> and then it responds with two buttons, am i still able to access the value of <username>
when i log the data, its just the customId that prints
but i cant store it in the customId because it exceeds 100 characters
actually i can probably just store it in the msg ig
Of course
username is a option
likely a user option
so you will always have access to it in the scope of the command
actually, when you click on the button you dont get that information
when the interaction is ran you do though 🤔
You'd logically handle all this in the command handler for that command
im using cf workers so its not like i can use an interaction collector
its like a confirmation prompt
wtf
they run the command, the bot reiterates that info and they click yes or no
but i just parsed the info from the msg and it worked fine
started doing it for fun and it actually isnt bad at all
dont need to use any hosting services either 🤷♂️
I mean fair enough get your bag
its a pretty good free tier so y not take advantage of it xdd
yeah its p limited, but works for simple stuff
I made a bot with a cf worker. It lets my mods run a /down command in my server when my bot / host is down which triggers a Pagerduty alert on my phone. Because it's a cf worker it basically has 100% uptime and will always work even if my host is offline.
I also host my status page on a cf worker
Oh Im not saying its not a useful thing
I just have yet to see someone do much with em
I know 2 people at this point who use cf workers for their bot.
the thing is
cf workers are good because of their edge network / global availability
which a discord bot cant take advantage of
since requests are always coming from discord's servers, which means its pretty much always the same worker being hit
all other workers accross the world will never be activated lul
lmao
linklava server hosted somewhere
cf workers control everything else
You can’t join a vc and receive gateway events
You’d need to be able to control voice state and listen to the updates
Unless lavalink has changed
hello is there everybody can help me with discord api?
probably many people
I am trying to change the about me bot through api, the request is sent correctly, even I used toJSON
And I also sent the JSON data manually, but I get this error again
response : {"message": "Invalid Form Body", "code": 50035, "errors": {"_errors": [{"code": "DICT_TYPE_CONVERT", "message": "Only dictionaries may be used in a DictType"}]}}
One message removed from a suspended account.
One message removed from a suspended account.
can you explain more?
I realized that I should send the request in json format. What do you mean by dictionaries ?
are you talking about json collection ?
yes it is
i've seen lots of lua devs here from roblox
tho i rarely see people use lua for discord bots yea
why
what
cause I am a developer who likes helping others
you used lua?
ofc

I have a mysql completion framework in lua that you can easily use if you replace it with the functions for sending Roblox queries.
It has the ability to backup at a specified time and upload it to pastebin or as a file or email and also multi db connection
Oh, I don't code in roblox anymore

It was something I was doing cause I was bored anyway
I never had fun with Roblox
Roblox was always a hobby project for me
I never pursued it seriously
If it worked out, great, if not who cares

our

im still problem ;(
right
so discord expects the response to be form url encoded iirc
so you can't send it just like that
what is the right syntax to sending request?
Actually they might not require it to be form url encoded, that might only be on the oauth2 stuff
try and send it as a stringified json
I wonder if that will work
[ { "bio": "bruh" } ]
wait
What you are doing is not even possible
There is only 2 possible things you can update
the username and the avatar
ops
Goodnight! I'm using typescript together with ts-node, and I wanted to know if there is a setting in tsconfig so that I can use ESNext (import and export) in typescript and have it compiled with .js files
I use ts-node in a testing environment (dev environment) and use import with the .ts extension, but when I try to run the code using ts-node, it returns an error, saying that it was impossible to find the file with the . ts in the directory
Good night!
good night misty
In your imports, dont include the file extension
Of course at runtime it wouldnt be able to find ts files since it compiles to js first when you run ts-node, not just running raw ts files.
unless you wanna name it .ts.ts then yes
not even a terrible idea
makes it more clear its a typescript file
hey guys
for fibonacci of 4 i got the result of 1.25
but i have no clue whether it's correct. i don't seem to understand the computation that they are coming up with
almost thought my ubuntu server got taken over
before i realized i was tryna ssh at root
but it gives me an error that the file was not found. If I put the .ts in the tsconfig extensions, wouldn't it work?
what are some factors to consider when coding in raid protection
You're doing something wrong then because you cannot import ts files at runtime
Don’t
Discord’s auto mod basically handles this already
It’s not perfect of course but if you really wanted to you can make your bot work alongside it
work alongside how?
how come this isnt updating the msg with the button:
i click the yes button and want it to just disable the two buttons given
and then i follow up afterward
but its not editing the msg
no errors either, and i print the response and it looks fine
it just sends the follow up without editing the msg
msg isnt editing tho
is the original message ephemeral
try removing that flag for update, you don't need it anyway
it wouldn't make sense for an edit to be ephemeral anyway
still nothing
the components are disabled buttons
but neither msg nor buttons are updating
its still the same msg
you should still be able to update ephemeral messages so i don't think it's that
you can always try without ephemeral if you want to make sure though
i tried without ephemeral
i tried just content as well
neither is working
and for some reason it still returns 200 so idk why it isnt actually editing the msg
it isnt a webhook, its just the bot
The bot status ain't updating
No errors
where's this from?
cf worker logs
its the json of the response
{\"type\":7,\"body\":\"{\\\"content\\\":\\\"work pls??\\\",\\\"components\\\":[{\\\"type\\\":1,\\\"components\\\":[{\\\"type\\\":2,\\\"emoji\\\":{\\\"name\\\":\\\"✅\\\"},\\\"label\\\":\\\"Yes\\\",\\\"style\\\":3,\\\"disabled\\\":true,\\\"custom_id\\\":\\\"disabled_yes\\\"},{\\\"type\\\":2,\\\"emoji\\\":{\\\"name\\\":\\\"✖\\\"},\\\"label\\\":\\\"No\\\",\\\"style\\\":4,\\\"disabled\\\":true,\\\"custom_id\\\":\\\"disabled_no\\\"}]}]}\"}```


