#development
1 messages · Page 2034 of 1
Is this a valid sql statement?
DELETE FROM guilds WHERE EXISTS (SELECT * FROM guilds WHERE id = $1)
$1 is obviously replaced with a real value
Ok
:o
quite complicated but i can give it a try
give some use for my https://remmacs.org domain
other than scamming
anyways i want to actually fix my databases TCP
so theres no set message length
im thinking make a buffer, check the message length and if it doesnt match the actual length, store it in some variable and wait
of course setting the limit to something generous to not run out of memory
like 100mb maybe
mysql's packet limit is 1gb
but for incoming packets from the database there wont be a limit
but by default there will be a limit of rows returned
if someone decides to request every record and theres a million of them, i hope you have enough time and memory
well same applies to the database tbh
add rickroll 🏃♂️
that is just cringe
fr
topgg mfs dying because someone made a rickroll joke
i mean this is also an option https://www.youtube.com/watch?v=4ebas1ZvyVI
I was going to make another meme with this for some friends. I couldn't find the original video so I opted to do my best to replicate it.
node uses a rope structure
how do actually change the prefered guild locale (for testing reasons)?
imagine you're waiting for a 200 byte message, but you get in 3 tcp frames:
on first frame:
start = rope = {
size: a
ptr: aaa
next: null
}
on second frame:
rope = rope.next = {
size: b,
ptr: bbb,
next: null
}
on third frame:
rope = rope.next = {
size: c,
ptr: ccc,
next: null
}
final structure for the start variable would be ```js
{
size: a
ptr: aaa
next: {
size: b,
ptr: bbb,
next: {
size: c,
ptr: ccc,
next: null
}
}
}
on each frame you follow the next chain and count the sizes, until the combined size surpasses the expected message size (provided in a header in the first frame)
if the size surpasses, then you follow the chain again to assemble the buffer pointers
and then emit the final combined buffer, and reassing the excess bytes back to the first element
this is basically what node.js does in its tcp stream
this way you dont need to preallocate a massive buffer to account for all possible message sizes
ima just malloc a base buffer size(e.g. 1mb) then check if all data has arrived (check for null character at the end of the buffer size) if not maybe make a linked array and store the buffer pointers in it then at the end assemble them, or just concat them immediately (maybe using realloc)
the obvious problem is how big of a contiguous block can i allocate with malloc
apparently its compiler and OS dependent
1mb should be more than fine
yeah
how many bytes are you using for the length header?
for now its only 2 but i can extend that to 4
no biggie
or even 8
but i dont need that much
idk if its possible in c++, but in node its possible to receive tcp frames of 0 size, or 1 size, or anything weird like that
it gets a bit complicated
the receive function takes in a max size, if a packet exceeds that size the next receive call will give you the other part of the packet
but thats per packet, it doesnt take into account split packets
Just make incredibly unsafe macros to outsmart the compiler 😉
i would do something like this (pseudocode)
buffer = <1mb buffer here>
bytesWritten = 0
tcp.on("message", data => {
if(bytesWritten + data.length > buffer size) { realloc/extend buffer }
buffer.write(bytesWritten, data)
bytesWritten += data.length
if(bytesWritten < 4) { return } // return if buffer not big enough to get our header
header = buffer.readUint32(0)
if(bytesWritten < header) { return } // return if buffer not big enough to contain our data
ourdata = buffer.slice(0, header); // copy data from buffer
buffer.write(0, buffer.slice(header)) // write excess bytes to the beginning for next messages
bytesWritten = bytesWritten - header; // write excess bytes to the beginning for next messages
emit(ourdata)
})
this is not the most efficient solution, because it involves copying buffers
but its the easiest solution
if you want max performance, you need to implement a zero-copy solution
which is a bit more complicated
i think i know how i can kind of achieve that
i can always extend the buffer with realloc
how it does that does not concern me but the important thing is it works
it can be done with the rope method i mentioned before
why cant tcp just be normal and let you decide if you want to split packets or not:(
honestly it'd be easier to just use a library that does this for you
they would probably do a better job anyways
involves a lot of copying right
at the end
the json parser i use has to have the entire string at hand
cant have it in parts sadly
otherwise that would make it so much easier
i might ask some c++ experts to see what they think
the rope method doesnt require copying to a temporary buffer
it stores the pointers to the original buffers provided by the tcp
can you create a buffer composed by multiple pointers in cpp?
well here you have to make your own buffer and point to it
nope
unless they have some std function for it
but then again you cant make a buffer composed of the size of a packet
you have to set a strict size for it
so if you want a buffer to fit that packet size you either have to shrink it (with realloc) or copy
but then what realloc does to achieve that is implementation details
it may or may not copy
though that doesnt really matter considering you can place a null terminator at the end
so you can assemble the entire string at the end
im reading some stuff on zero copy, it seems they use mmap for that
huh?
the rope method does not require copying the tcp packets, but it does do a copy at the end when the final message is assembled
basically when the entire message is available, a new buffer is created for that message, and the parts are written to it
yeah i can do that with a linked list no biggie
allocate size of message, write message, push pointer to linked list then assemble the string at the end
and continue until everything has been read
when it reaches the size of the string, it saves the position in the buffer and the pointer currently being read, processes the current string and continues with the next
it is a lot of copying though
because we have the size of the entire packet in the header, you can allocate the exact amount of memory needed for it
mapping separate buffers to appear contiguous would be very good though
oh wait
i thought of a million dollar idea
lets split that real quick
- make the receive function take in 4 bytes (the header size) at first
- allocate a buffer of that exact size and store the pointer in a variable
- make the receive function take in the "remaining" size of the data with the pointer pointing to the next position in the buffer we allocated previously
- subtract the remaining size by the amount of bytes written, if it is zero, send off the buffer for processing, if not repeat previous step
- at last the last step, free!
@quartz kindle thoughts?
I AM A GENIUS
not a single copy in sight
no need
we have the max size parameter
we only take in what we need
i will focus on detecting incorrectly or maliciously crafted packets later
tried to install better-sqlite3 by adding it to package.json, deleting the node_modules and it still gave me an error, any clue how to fix this ?
the regular way have the same error.
what node version are you running
v18.1.0
is node-gyp installed?
yes
This is a bit vague, but how can I prevent an user from sending too many requests? I have a few situations I need to fix for a website I’m making using ExpressJS. One is creating accounts/logging in where the user data is stored in a SQLite database. However, the user can slow down the server if they create too many accounts at once, but I’m not sure how I can prevent this. Another is through the search bar, where I send HTTP requests to an API and to another website. I’m planning on only having the user be able to search 5 times per minute (as a start), but I don’t know how to track that if they don’t have an account (staying logged in is also a problem I’m having since I don’t know how to track that).
limit request per user ?
honestly its quite a tricky topic
the easiest way is to do it via a users ip
but if an attacker was motivated enough they can perform a DDOS where IPs dont really matter
you're really going to want to have logging in & sessions sorted out before moving forward with ratelimits(for ratelimiting per user)
express also has a few middleware options for rate limits per ip.
For account creation you'd ideally have a captcha used along with ratelimits per ip..
yeah a captcha
forgot about that
a captcha is a must for ratelimiting registrations
logins too
after that you can rate limit per account
@quartz kindle to make you feel better
for tracking the buffer position im using a pointer to the position rather than an index
because indexes use multiplication on the buffer to get to the destination
and multiplications are slow:)
Well... we're going to have fun.
what, so fast?

mfs probably changed the language to java as a breaking change
Does anybody have a "smart" idea how to parse the JSON and replace the double quotes of the value direct_message (of the key errors) by ` to turn it into a template string
{
"errors":
{
"direct_message": "**Sorry** ${somevar}",
}
}
they'll call it a 'minor' change though
lmao
My Approach would be:
- JSON.parse(obj)
- Recursive function ,which loops through keys and creates a string of key value
What's the goal here though?
nvm need to do it differently anyways
so ${somevar} gets replaced with the variable's value?
you'll need to use eval
or Function
gonna take my php language parser as example
yeah, that's what I want to avoid
You can make up your own templating engine which is simpler to parse
and parse the strings
yeah I do
that's your safest option
im gonna replace {{somevar}} by the arguments I pass
yeah that works
I'd go with something like @somevar cause it's simpler
Easier to escape as well
errr nope, that could get in conflict which strings containing @
double brackets are actually good to go in JS and PHP
yeah ik, I just prefer {{..}}
to be consistent in my projects, you know
damn can't test things atm
Is that the correct syntax for optional chaining for dynamic keys?
object[key]?.[val]
yes
alr
wdym by is cursed?
well works like a charm
language(localization, group, key, placeholder = false)
{
if(!localization || !group || !key) return;
if(localization.includes("en-")) localization = "en";
const language = (this.client.localizations.has(localization)) ? this.client.localizations.get(localization) : ((this.client.localizations.has(locale)) ? this.client.localizations.get(locale) : null);
if(language)
{
if(language[group]?.[key])
{
let string = language[group][key];
if(Array.isArray(placeholder))
{
const match = string.match(/{{.+?}}/g);
if(match)
{
for(let i = 0; i < match.length; i++)
{
if(placeholder[i]) string = (placeholder[i].length > 0) ? string.replace(match[i], placeholder[i].trim()) : string.replace(match[i], match[i].slice(2, -2));
}
}
}
if(string) return string.replaceAll("{{", "").replaceAll("}}", "");
}
}
return this.utils.log("warn", `Missing language record for '${group}->${key}'`);
}
could probably be compressed a little bit more but who cares
which allows me to call the method and pass my args where ever my vars are in the right scope
True, the code looks a bit weird to me since it is scrunched up :p
also I'm replacing placeholders in my language files by vars where I need 'em
Ah yes, reinventing the wheel. Classic js
that indentation is cursed
For example:
// lang json file
{
"errors":
{
"direct_message": "test {{123}} {{afas}} df"
}
}
const wow = 345;
app.language("en", "errors", "direct_message", [wow])
// test 345 afas df
how is that weird?
I'm just using TAB not spaces
I guess not the indentation, just the style... Opening curly brackets on new line 🤮
I assume whatever is in the {{}} will be replaced?
yes
what about that [wow] thing?
the array does only replace the first placeholder of {{ }} as it has only 1 item
Oh right, so that is what actually gets placed in there and the other 3 are to tell it where to look
gotcha
When I pass more items like [wow, 456] the result would be test 345 456 df
I can even pass more items than placeholders exist
that wouldn't do anything
What happens if you nest inside direct_message with another object?
This is just a general example of what happens if you ever do need to nest
I don't need that over here, but my PHP equivalent build can lookup one structure deeper
I see
For this example I don't need nesting as I already have the key errors and the value direct_message aka. 2nd key
In PHP a much deeper nesting wouldn't make sense, too
because I'm using an INI structure as language file
for example:
[static]
time_years = "year{{s}}"
time_months = "month{{s}}"
time_weeks = "week{{s}}"
time_days = "day{{s}}"
time_hours = "hour{{s}}"
time_minutes = "minute{{s}}"
time_seconds = "second{{s}}"
time_few_seconds = "a few seconds"
[footer]
link_tos = "Terms of Service"
link_privacy = "Privacy Policy"
while in that case when passing an empty item in my replacement array time_years would just be year and not years
that's very simply but effient
and when not passing any item in my array, then year{{s}} would get years
if(string) return string.replaceAll("{{", "").replaceAll("}}", "");
which allows me to replace any part of the final language string by a different string or for example by a var I pass
So I'm just loading my (JSON) language files into a map and access it whenever I need and replace my placeholder if I have to
can't actually think of any easier way to do it

well it's all about preferences
He needs language again after that
language?.[group]?.[key]
zamn
why width 8 tabs tho
i use the i18next lib, but only have American english
then what's the point
pluralization stuff
you could make a simple template for that
i also plan to support more languages
then that's ok
maybe european english. i'll add random u's to words
legacy english should be supported
simish too
latin is next
also old himalayan
i just looked this up. i want 3 sims
sim cards! not the sims 3. oof
why would I need the first chain? as language already exists (and is an object) it doesn't matter if group exists or not in JavaScript
if not it will still be undefined
and the statement would fail
you could remove that first if statement with the optional chaining
ah, that's what u mean
i mean things and stuff
actually not a bad idea
it's a miracle
huh?
it's a miracle that i didnt have a bad idea
eval random strings. what could go wrong?
eval("`${alert('hello')}`")
edge doesn't want to protect me, but chrome does
the javascript version of a buffer overflow
you can use this if you want to make life easier ```js
const i18next = require('i18next');
const fallbackLng = "en-US"
const resources = {
[fallbackLng]: {
translation: require('./en-US/translation.json')
}
}
const initializeLocalization = async (locale) => {
await i18next.init({fallbackLng, resources});
return i18next.getFixedT(locale);
}
module.exports = initializeLocalization;
nah... don't wanna use libs
How does supporting multiple translations even work in i18next
my selfmade thing actually works perfect and is damn effient
when initializing i pass the locale. i can add more keys to the resources object to support more languages
Mmm
you live dangerously. if you returned that object on a new line it would fail
return
{
color: ...
description: ...
};```
nothing
i'm returning nothing with my code
well I wouldn't open that bracket in a new line
it's a bad habit in js
that's the issue when you don't need to put a ; to end your line
yeah, ; should be required
but I still don't get why I'm living dangerously
just because I generally open the brackets in a new line?
I'm only doing it, when ever it doesn't fuck up the syntax, don't worry
Making anonymous functions in js is a good reason why semi should be required
also I would never end an clause without a ;
even in JavaScript I add ; to any line
fixed
to prevent that sort of bullshit to happen
i put my ; on a new line too
I do it as much as possible but I just sometimes forget and let prettier do it for me
even if it isn't required
well npp doesn't do shit for me
once it belongs to your routines, shit can't happen anymore
notepad++. i just figured out what npp is
also I would define that inline
let x = { live: "dangerously" };
very nice
The reason #development message is multi line, is the readability
everything should be a oneliner
well it can be multiline, but only one assignment is allowed
I could get rid of hundrets of lines if I optimize one liners but I don't like to
as I said earlier
well it's all about preferences
so... just because I'm not as lazy as you to add ; I can live my "weird" style
scala has similar problems because of the lookahead + auto inserted ;
tbh I think js should require semicolons like every standard c-like lang does
it saves a lot of headaches
to have strictly defined behavior
yep, i'd change the way i write js if they did that
actually i probably wouldn't
this looks betterjs return { hello: "world" }
awww speedicus saves the day
honestly
You're trying to make a request with the client such as fetching a user before the client is even logged in
for discord.js unfortunately yes
you might have some luck trying to login then logout
i had the same issue but forgot how i solved it
hmm
you can try https://npmjs.com/package/discordtools
Discord Tools is a powerful, productive, efficient, and easy-to-use set of tools that allows you to interact with Discord API.. Latest version: 2.0.54, last published: 4 years ago. Start using discordtools in your project by running npm i discordtools. There is 1 other project in the npm registry using discordtools.
oh last update 4 years ago
nevermind
and deprecated
According to the source, seems like you haven't even provided a token to begin with
https://github.com/discordjs/discord.js/blob/df64d3ea382c07e66bc7cc8877ee430206c31d63/packages/discord.js/src/util/Util.js#L230
i think i know how you can do that
eris allows you to perform api calls without logging in
I mean if you dont wanna use simple IPC for example to pass the vote data to your logged in client then why don't you init a new client without any intents and cache?
even if a second connection doesn't really make sense tho
I don't think you need to be logged in, seems like they're just missing the token completely
ahh nvm then
@earnest phoenix do you happen to know if node has a TCP interface similar to C? i need to receive a max amount of bytes, each time being variable and the event API nodejs has just fires the most bytes it can at you
I had to make an ugly solution with a main buffer being allocated with a set size and when bytes arrive, slice the buffer and copy over the contents to a certain position in the buffer
would have been strange if a login would be required just to send an request to the api
but djs is strange as we know

funnily enough in this case its easier to work with TCP in C than nodejs
if you didnt know the C way of receiving TCP bytes is by
recv(socket_id, destination_buffer_pointer, max_bytes)
I don't think my lib requires to be logged in to send rest api requests either Tho if someone would like to fully test that go for it :^)
blocking if that isnt obvious
The built-in node:net module provides such an interface, but may not be as low-level as a C TCP API to work with
https://nodejs.org/api/net.html
yeah receiving data still requires you to use events
hm
i guess I can implement this myself
but eh
i feel that'll impact performance even more
@earnest phoenix this is what i wrote to work around the limitation https://hatebin.com/vghkkfpmpc
because tcp is a stream API when you send a packet, at the receiving end it can be grouped with another packet or split into two
which makes the stream approach of it terrible to work with
Should I make a Base Channel class and then have classes like TextChannel, DMChannel, etc extend it ? It seems like that would be the most logical as a dm channel will have different properties than a text channel or even a category channel
ctrl+shift+l added semicolons for me. 3 key strokes is easier than pressing ;
you're the type of guy to write a program to rename 5 files
i use ken rename
Looks good to me, that's a pretty good implementation unless you've got some issues with it (?)
yeah not really just wondering
mainly not happy about the part that you have to copy from another buffer to another when you can directly write to the empty portion of the buffer
but I get thats not really easily implementable because js is a memory safe language
What would be the most logical way to attach the guild the channel belongs to right onto the channel glass? I was thinking of getting it from the cache using the guildid the channel receives but that doesn't make sense as the guild could also not be cached
I was also thinking that to make a channel you must pass the guild with the channel class constructor but that would be rather hard to do as well for events where you either create a channel or update it and then you'd have no access to the guild there either
i think its a poor idea not to cache every guild
its not much overhead and saves you a lot of headaches
I am already caching every guild
I am trying to figure out how to get the guild the channel belongs to
and attach it to the channel class
just attach the guild class to the channel?
if every guild is cached that shouldnt be an issue
Mmm, should I even bother caching a channel on channel create?
If I don't have to bother I very well could easily do that
i would let the user decide
maybe let the user set a channel cache limit
if it reaches that limit it will start overwriting older channels
on every action that involves a channel you should cache the channel discord sends you
Hmmm that seems like a good idea but how should I tell if the channel is an older channel? If it is later in the cache or should I attach a timestamp of when it was added?
Also, how should I update the channel in the cache if it already exists, as the properties of the channel could change
you should remove the first element of the map (assuming you'll use that for storage) since they're ordered and just set the new channel
be warned anything that holds the channel that isnt the map and is long-lived will result in a memory leak when you try remove them
Wdym by this?
I understand what a memory leak is but not what you mean
lets say you have a map of channels which holds a class to cached channels
then you decide to cache messages which also hold the channel class
if you remove the channel from the map the channel wont be released from memory since the message you cached still exists and holds it
you'd also have to remove the message to release it from memory
just a warning
So should I also delete message as well?
Mmm, I see
just make sure your message cache is low
ye
a few excess channels wont hurt
I plan on setting the limit for a lot of things by default
and then let them decide if they wanna cache more or less
But then I still have the question of how I should retrieve the guild the channel belongs to to attach it to the channel class I tried retrieving the guild from cache with the guild id you get from the channel object but it just returns undefined even tho the guild does exist in the cache
You say just attach the guild to it, I can surely do that when I cache the channels of the guild in the guild create event but not in say channel create or update
i believe the guild object comes with the event
ah probably to limit bandwidth
{
type: 0,
topic: null,
rate_limit_per_user: 0,
position: 2,
permission_overwrites: [],
parent_id: '957867801119449110',
nsfw: false,
name: 'aha funny word',
last_message_id: null,
id: '972974453367652362',
hashes: {
version: 1,
roles: { hash: 'kyCmkswUy88' },
metadata: { hash: '7KBK+FxBI+w' },
channels: { hash: 'oVyKHFAhsMU' }
},
guild_id: '957867801119449109',
guild_hashes: {
version: 1,
roles: { hash: 'kyCmkswUy88' },
metadata: { hash: '7KBK+FxBI+w' },
channels: { hash: 'oVyKHFAhsMU' }
},
flags: 0
}
all you get back
import { ChannelData, MessageCreateData, PermissionOverwrites } from '../../../util';
import { BaseClient } from '../../BaseClient';
import { ChannelType, RESTPostAPIGuildChannelJSONBody, RESTPostAPIGuildChannelResult } from 'discord-api-types/v9';
import { Message } from './Message';
import { Guild } from './Guild';
export class Channel {
public client: BaseClient;
public id: string;
public type: ChannelType;
public guildId: string;
public position?: number | null;
public permissionOverwrites?: Array<PermissionOverwrites> = [];
public name: string;
public topic: string;
public parentId: string;
public guild: Guild;
public nsfw: boolean;
constructor(client: BaseClient, data: ChannelData) {
this.client = client;
this.id = data.id;
this.type = data.type;
this.guildId = data.guild_id;
this.position = data.position;
this.permissionOverwrites = data.permission_overwrites;
this.name = data.name;
this.topic = data.topic;
this.parentId = data.parent;
this.nsfw = data.nsfw;
this.guild = this.client.guilds.get(this.guildId)
}
public async send(data: MessageCreateData): Promise<Message> {
return await this.client.rest.post(`/channels/${this.id}/messages`, data);
}
public async create(
guildId: string,
data: RESTPostAPIGuildChannelJSONBody,
): Promise<RESTPostAPIGuildChannelResult> {
return await this.client.rest.post(`/guilds/${guildId}/channels`, data);
}
}
have you tried logging the guild id?
yes I get back the guild id as expected
but this.client.guilds.get(this.guildId) is undefined
have you tried fetching the guild with the ID hard coded?
are you sure its even cached? can you print your whole guild cache
Printing the entire guild cache returns the base store with the guild in it, and fetching it with a hard coded id works fine and returns the guild
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
response
im stumped then you have to be doing something wrong though
hard to debug when you arent in front of the code haha
Same
pushed
where are you instantiating the channel?
In the webhook shard, on guild create and channel create
I make a new channel to convert the data returned to my class's data so I can keep the methods with the data
cant see it at first glance so i'll just clone and run it
Alrighty ty in advance <3
lol
typescript is one of the deps for it so it should have it locally installed in the project
it is just a config file with an export of TOKEN
always a good start
Yea no idea what happened there
windows: git is not a recognized cmdlet, go fuckin google how to solve this
linux: git is not recognized as a command, perhaps you could try installing with apt install git
That's not a windows thing eiter
That's a shell thing
I'm seriously considering installing wsl
windows mocks itself
lmao thank you :)
@sharp geyser https://github.com/MistyyBoi/strife/pull/1 :D
Also question would it not be better to just
this.guild = guild ?? this.client.guilds.get(data.guild_id);
Either way works tbh
I do like the look of ?? tho
https://www.toptal.com/developers/hastebin/muvamufave.yaml Mmm, is it just me or does this look bloated?
more useful connection errors
a few times my connections timed out and i got a basic "request failed"
Mmmm
So i was looking at discord.js lib and they do something rather confusing
They have a Channel class right which is just a basic channel not really a text, dm or category, etc. Then they have GuildChannel which extends that, then BaseGuildTextChannel which extends GuildChannel then TextChannel which extends BaseGuildTextChannel. What is the point of all this extension?
inheritance
Well yes but could they not have done it simpler?
let's say all channels have id, name, permissions, category, etc
instead of repeating that same code in all channels, u just make a superclass with common properties
ur not really supposed to use the superclasses themselves
Yea i know this much, but why the whole long winded extension
Why not just have a Super class then extend that super class for the things you need
Like
Channel (Super Class) -> GuildChannel -> TextChannel
because not all guildchannels are textchannels
and not all channels are guild channels
Yes, which is why GuildChannel is a class in its own where all guild related channels extend it
ah, u mean there's a class between those two?
Yes Channel is the super class, GuildChannel is the class that extends it and has basic properties a guild channel should have and TextChannel has the properties of what a guild channel should have + text channel properties
Yes, but they add a fuck ton of what seems to be useless stuff
I am sure it has its uses but it seems to be overly done when it could be much simpler
maybe the Base classes aren't classes but interfaces
Looking at the difference between BaseGuildTextChannel and TextChannel seem to be nothing different despite a few things you could probably add to TextChannel in itself
well then idk, base doesn't really make sense tbh
They seem to apply a interface properties to it using applyToClass or smth
So it extends GuildChannel and implements TextBasedChannel
in jda it's like ```
┌ PrivateChannel
Channel ┤
└ GuildChannel ┐
├ TextChannel
├ VoiceChannel
├ ...
I don't really see the point in having a BaseGuildTextChannel class tho it seems like they took an unneeded extra step
is that what u mean it should be?
Yea, that is what I was planning to do
But I wondered why djs did it so weirdly
Wait what djs uses something from sapphire
:^)
sapphire?
the djs command framework
used to be klasa but the devs had falling out so the ones left made sapphire
because ThreadChannel exists
so they needed a common class for text channels that are not text channels
Mmm, I guess that makes sense yea
I still feel there is a better way to do it tho but 🤷♀️
they are the pros
In jda it just extends textchannel 
also soon there will voice text channels
I mean tbh isn't a thread channel just a special text channel?
yea dope
its better than to comment about the stream on a irrelevant channel
It already started?
v10 I think is a part of that
And they still didn't finish the join agreement part
The screen that appears when u join a server, it has many "To be added" features
yes its been a few months now
i had to upate djsl a few times to fix it
Quick question: is server count setting via the API broken right now? Just noticed my bot hasn't updated in a while but as far as I can tell the API calls are going through
takes a while to update in your browser since the page is cached
It's like 50 servers behind though, so I'm guessing something else is wrong then. I'll look into it thanks
well which duration since the last update are we speaking about?
Estimate would be about a month
Mine is working fine, did u see if ur not getting any http error?
I'm gonna try to set it manually and see if it updates, and if it does then I guess the library I'm using might have an issue
What lib is it?
I remember a few reports recently about the java lib iirc
I use the java lib
might be an issue with it
I tried updating to 2.1.1 but for some reason I can't seem to get it off maven
doesn't exist
But tbh, I'm quite sure I'll not be using it anymore on my reworked bot
Doing direct http requests is easy enough to remove the dependency
yeah it updated via manual API call, so something broke in the bot seems like
Also iirc, the java lib has some vulnerabilities (uses org.json) reported on maven central
nice
alright guess I'll implement it myself as you suggested then, thanks for the help
Btw, before you go, I recommend using apache http for doing the requests
And moshi to parse data into json
Noted, although I literally just update server count and nothing else. So... not too much work being done
org.json is a terrible lib (it was created as a proof-of-concept) to use anywhere
Mostly because it lacks any optimization
I usually use OkHttp, not a fan of that either?
That's for requests, not parsing data
oh yeah sorry I misread
It's fine too, I like apache's bcuz it's very flexible
And since it uses factory pattern, u can set default settings for every request
Yeah true, I've used Apache before for other things but for whatever reason I started with OkH with this and never changed. Does enough for what I need
Oh, btw, do u use log4j?
I gained something but I lost another as well
I don't use log4j no
I managed to split the channels up according to their type so now the data is properly typed with the methods that are meant for that channel but the channels cache on the client is only storing one channel
yeah don't worry I'm aware of that lol
I'd maintain the go package but tbh I haven't seen anyone using go here
So I find that I am once again going down the hole of writing a minecraft mod, does anyone know a good way to avoid global state? A lot of the features I need to support rely on settings provided by the user, and in previous mods I've done this with using a bundle of static variables, but I know it's a bad practice
pretty sure the mod loader provides a way of r/w of a config file
would have to read your mod loader's docs
docs??!! on forge??! impossible
I'm using 1.8.9 forge, there's basically no resources for it
Because they refuse to support anything older than like 1.12
surprisingly, they actually made some docs for later versions
yeah then you might be shit out of luck unless you find a mod's source that does what you want to do
then don't write mods for 1.12
/j
Unironically, forge needs more love in the performance departments like fabric gets
or one of the mod loaders just gives up on trying to update and have it be obsolete
or both
Is there actually some sort of process environment vars in node which can be an array?
env vars are all strings
Ok let's say I'm exporting this:
module.exports =
{
name: "evil",
description: "very evil shit",
do(param1, param2, lang)
{
// do some evil shit
lang.something...
}
};
Let's pretend u didn't use "do"
I'm getting my params in the do() method right from where I require the module and execute do()
let's say lang is another class or object I wanna use on the module's name
I don't actually wanna define lang as global var
And I can't import/require it from anywhere else
Can't u just require it inside the scope?
hmm... I feel like the only option is to export lang as module itself
and import it over here
in my case lang is a method in class
The entire concept concept of having to export stuff in js so it's discoverable in other files is weird to me
In java u just write the class and that's it
yeah I don't have that trouble in PHP, too
If u don't want to import u just write the full path to the class
Js is the only lang I see this behavior
Maybe that's due to its browser origins
Importing something that is I'm already passing as argument is weird
well the example was stupid
lang actually is a class, let's call it app and lang is it's method
That should've work, if it's passed as a param u shouldn't need to import the class
// some other file
class app
{
language() ...
}
// some very other file
module.exports =
{
name: "evil",
description: "very evil shit",
exec(param1, param2, app)
{
// do some evil shit
app.language(...);
}
};
wait
the class app get's exported
module.exports = app;
can't I actually export language as well?
with a second export like module.exports = app.language;
which I can then import in my very, very, very other module
I mean, that's what I mean
U shouldn't need to import every single method in a class if ur passing an instance of it as an argument
YES I'M PASSING THE ENTIRE INSTANCE
BUT
I'm passing it to exec(param1, param2, app)
Yes?
I wanna use it ouside that scope already
U mean outside of exec?
module.exports =
{
name: app.language(...),
description: "very evil shit",
exec(param1, param2, app)
{
// do some evil shit
app.language(...);
}
};
Ah, that
yeah that's the issue
Well, that's something I don't think any lang can achieve
Forward reference in this case
that's what I mean, I need to export that method separately
which I can then import in this module
to NOT import the entire class (again)
U could, tho, make it a class instead of a (whatever that structure is called in js)
Then instantiate the class with an instance of app
And use it in constructor to build ur command
(assuming that's a command)
importing the class isn't the issue tho
I mean, in ur example it'd not work since you'll be getting a static method instead of a reference's
but I don't want to initiate it another time in my module (since the entire class is already available as argument)
2 different contexts
yeah
You either use a class so u can store the reference in a broader scope or don't forward-reference it
U can also set a placeholder in name
Like, idk if those fields are all final, but can't u do something like this.name = app.language(...)?
If anything, replace that value where u import it
i could check if the module name is a string or an object, when it's an object I could pass my language key and value
Ye
module.exports =
{
name: { group: "something", key: "something else" },
description: "very evil shit",
exec(param1, param2, app)
{
// do some evil shit
app.language(...);
}
};
For my commands I set their names like cmd/some_command, then when printing the name I grab that entry from the locale files
damn I haven't thought about that actually
actually a good idea tho
never thought I would appreciate tips from a Java user, but nice one


How are u doing it?
i gave up on localizing timezones in my api
the user can localize them themselves if they want, fuck it
lmao
theres zero consistency
just do an autocomplete list of timezones he can pick one of
/localize inmyhouse please supply a valid timezone
/localize im_my_house please supply a valid timezone
/localize here please supply a valid timezone
Ah fuck it this bot is brokenz
lmao
well... by having a default locale (en) and return the user/guild locale where ever I have access to that property
pretty simple
No, i mean, are u using files + cache?
i'm importing the lang file, yeah
Oh, no cache then
Like, in my schema I get from the cache, if it's missing it loads the entry from the target locale file
So the cache auto-loads itseld basically, and keeps the entries cached for 30 mins before discarding it
I'm not letting the user pick a language etc.
This way I don't have the whole file loaded, only the requested lines
I only wanna support the description_locales
technically not, no but why should I care?
the import process happens once when the client being initiated
Wasted memory
we're just speaking about a few bytes of ram
or megabytes
wtf who cares about RAM in 2022
Definitely megabytes
I can fucking assign up to 198GB to the VM if I want to
but yeah I know what u mean
not going for microptimizing here
a few mb of ram as base load doesn't matter for me, tbh
Remember fixing i18n-related issues gets exponentially harder the longer a project is
that's why I'm using my own simple system I used to show earlier this day
which is also capable of replacing placeholder in my language string if I wanna replace something with a var for example
I faced the i18n demon eye-to-eye, which is part of the reason I'm rewriting my entire bot
Every single visible string is going to be localized
Ngl it's easier when starting again, but my file already surpassed a hundred lines
im never gonna localize my help command, fuck that
yeah I'm currently rewriting my bot, too, making anything more dynamicly to be able to reload basically the entire app while keeping alive the gateway conection
it would be like writing a book
Yeah I made the accident to translate the entire API docs
starting at line 170 to 271

doesn't sound much, but is 2s scroll time on 4K
My current locale file
And I didn't even start the most verbose commands
I really dislike JS hasn't a native INI parser like php does
I prefer the INI format
over JSON
so much
I like properties
No nesting, each line is a key-value
And u can stream the file to load the entry instead of loading the entire file
Ye, we use that format at my work
while categories (as key) are sexy to work with
since you have to write same key, for example rarity/ in any line
I can just use the category
I also use properties bcuz intellij has a i18n manager that shows the data side by side (edit all locales at the same time)
the ini file which will be parsed as array/object and I can easily access them by the key (category) and val (names)
if JS would only have a native INI parser

The editor
Now you know how to say thank u in german
panzerfaust
now you know how to say good bye

ok enough of that
we were talking for an hour and I didn't make any progress
I feel like Tim
Ok fuck localization
The API isn’t ready for it yet
Once a command is registered/edited with a description localization for example, it does loose when I restart the app
Fetching the command from the API and boom localization is null again
This whole localization gives me a wonderful idea
But the command registration promise does return the new and correct application command object
With the localization
But it’s not accepted by the API for some reason also doesn’t throw an error
My gosh
Fuck Discord
Ok I can now understand Tim
Wait what are you talking bout at this point
Let’s say you register an application command at the API
You can now add a localization for the command name and description
While I don’t care about the command name, the description might be worth to translate
As well as any command option descriptions
Yea
So when registering that command or editing it, a guild command in my test, I can add the description_localization property to the command object which is an object to
{ locale: string }
{ "en-US": "us description" }
The API will respond successfully with new application command object I’m logging
But nothings happens
When I restart the app and fetch the guild commands the description localization is null again
Mmmm, maybe localization isn't fully out yet?
And even without a restart and clearing the cache no translation is happening
Idk I thought it is
Nvm
It isn’t
Yea, the api for it is, but client wise I don't think it is
Looks like it requires a special discord app built
Well if so the API wouldn’t respond with success but doesn’t save my localization
Looks like it’s not ready yet
Yea, well hopefully soon it will be :p
Regarding the time they posted it and I can’t even register the localization strings I highly doubt
Enough bot rehauling for me right now
Back to web development
The api isn’t ready for anything they introduced lately
As well as the missing features
Meh makes me sad
I still don't know how to solve this, already do all the troubleshooting on the github page, and I also have node-gyp either.
danke schon
why does node gyp always have issues
it is singlehandedly the most unreliable thing in node
async function cercaCanale(id, client) {
let canale;
let contatoreRicerca = 1;
do {
canale = await client.channels.cache.get(id);
console.log(`Canale cercato ${contatoreRicerca} volt*`);
contatoreRicerca = contatoreRicerca + 1;
} while (!canale);
return canale;
}
Is this good or not?
no
First off, you're only getting the value from the cache
you're not fetching it
the second problem is if the bot doesnt have the permession to see that channel
and it will loop forever
Second, fetching a channel multiple times makes no sense - you'll always get the same result, unless like you said suddenly a person gives you permission to the channel.
But that should be detected in an event
I did this bcs I get a lot of errors bcs the bot doesnt find a channel
I want to say that this is only a test, In my hosted bot I have
let canale = await client.channels.cache.get(id)
return canale
}```
lol, still in cache
but without cicles
I had also fetch
but still errors
async function cercaCanale(client, id) {
let canale = await client.channels.fetch(id)
return canale
}
This should be better, right?
yes
after this I have a question about bot verification, I have only the guild intent for a welcomer.
Is it enough to get the verification or It will be denied?
if you don't have permissions to see it you could fetch all channels of that specific guild and find it by id
@pale vessel your status is great haha
How can I fetch for a guild?
for(const key in roledatabase){
m = newMember.guild.roles.cache.find(r => r.id === key);
newMember.roles.add(m)
console.log(m)
}```always returns missing permissions
While i am pretty sure the role hierarchy is set, alongside admin perms of the bot.
You're bots role is above the key role correct?
@harsh nova scam
...do-while
💀
I'm trying to add a role in another server for an user that uses a command, but I'm doing somethin' wrong and I don't get what lol
const NPW = await client.guilds.fetch("972430091927818280");
const utente = await NPW.members.fetch(interaction.user.id);
const aggiuntaRuolo = await NPW.utente.roles.add(ruolo);
users cant have roles
ah nvm, ur fetching it
why dont u just get interaction.member?
works for different server?
The command is being used in server X, and I want to add a role in the server Y
ik that is something strange, but is what I need 😮💨
const aggiuntaRuolo = await NPW.utente.roles.add(ruolo);
Cannot read properties of undefined (reading 'roles')```
either the member isn't cached or they arent in the server
It's very strange, bcs the console.log of utente and the role are correct
I have the data of the Y server, and not X
nvm, I've solved it 'NPW.' was not needed
they are better for different purposes
Best py purpose is to make a bot to make fun of js
worst js purpose is installing it
True
worst php purpose i suppose 
lol compared to shit like JS or py php is far ahead
cope with it fake 
Quiet py user 
Make a discord bot in Holy C
I just made a bot with CSS
guys remember rules, no lang war 
Ofc that’s the only reason we’re here
Why?
CSS very powerful…
Aye
bro
html is not lang
havent you heard of ✨brainfuck✨
it is a lang
bro really? Why
lol
my fav lag
👍
Make a brainfuck discord bot and i will be give you all my money xD
I mean, u could just write a bot as normal and use the js > brainfuck converter to make the sourcecode become brainfuck
well that doesnt change the fact that it has a maximum amount of characters you can use which is 30000
for what?
i mean you could easily reach it by a few lines of code in js
?
like, code doesn't have size limit, it's just that after a certain amount of lines most text editors will refuse to open the file
Windows notepad, best editor 
30k characters is easily reachable in normal code
actually the only editor that'll open such big file is nano
I will try to reach it in my bot
what is this then?
I wonder how many people will be able to run my 1TB javascript project 

no idea, but no code enforces a max limit
wat
heck I constantly see people who surpass 30k chars all the time here
by putting everything inside index
Well if it's about disk space, i can handle that, i have 13,75TB disk space
who uses multiple files in 2022 anyways
True
50k line in one file is what the kids like to see nowadays
Especially on mobile 
and with no indent
lol yes
remember that line counter utility thing
that also says how much your code is worth
(kinda stupidly exaggerated tho)
my code was worth some tens of millions
lmao
wait, loops and functions are a thing?
?
Bruuuh... I use sticky notes
Answer (1 of 5): Sure, you can use any text/word processor to create the code, just don’t forget to save your work as plain text and update the .txt suffix to the language relevant one using the command line.
However, standard word processors (Word included) miss some features which make coder’s...
nah, code in powerpoint
nah, code with powerpoint
how to get bot developer role
develop a bot ||and have it accepted on top.gg||
can bitfields store negative values?
ah nvm, I can just use 255 and offset by 127
thats cursed dont say that ever again
Hello hello! I need some help! For a long time I've tried to sort and rank different objects in my database, but i cannot figure out a way to do so. I've managed to sort it from highest to lowest, but how to i get the rank of each item? Any help is appreciated :)
any kind of ranking requires some sort of criteria, so you want to rank them according to what?
ok so
lets say i have 5 of these:
{
user: string
money: number
}
then i want to rank them based on the ammount of money they have
Use sort
I have
assuming the objects are in an array
Yeah
Well then show your code
var times = UserProfiles.length;
var Sorted = UserProfiles.sort((a, b) => b - a);
const rank = UserProfiles.map(v => Sorted.indexOf(v) + 1);
let UserProfiles = await UserSave.find({ guildID: interaction.guild.id });
And what do you want do to? You're already sorting them
yeah,
but lets say i have an array with the numbers
[10, 5, 100, 29, 52]
I want to sort then from high to low
and then give the highest number the rank #1
the second highest #2 etc
So you want to sort them in an descending order
Yes
Then you do a - b instead of b - a in your sort function
alr
Also this could be simplified, by a lot:
UserProfiles.sort((a, b) => a - b).map(v => v + 1);
so by logging rank, i get [ 1, 2 ]
Pretty sure UserProfiles.map(v => Sorted.indexOf(v) + 1); is wrong because v is the value, not the index
the rank is literally the index of the item in the array after sorting
and i get that how?
who is the first rank? sorted[0]
who is the second rank? sorted[1]
what rank is user ID? sorted.findIndex(x => x.id === ID) + 1
and indexOf takes a value?
yeah, i understand this, but the point is that i dont know how many items there will be
depends on how many users there are
yeah, but im using a forEach() to add a field to an embed for every user
still doesnt matter
-.-
i know the ranks don't change, but when adding fields i do it like this
embed.addField(`#${rank} <@${element.userID}>`, `\`❂ ${element.bank + element.wallet}\``)
right?
so i dont know what rank is added
Also, camelCase please 
const sorted = UserProfiles.sort((a, b) => a.money - b.money);
for (let i=0; i < sorted.length; i++) {
const user = sorted[i];
embed.addField(`#${i + 1} <@${user.userID}>`, `\`❂ ${user.bank + user.wallet}\``)
}
Simple as that, sort the profiles, then loop through each one. The index of the profile is the rank, so you just add + 1 to it so it starts from 1
Also don't put await in front every function call
may i ask why? never understood what it does, just been told to use it
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise It's used to await async code - you don't need to put it in front of calls to sync code
alr
ok this works, but is it possible to limit how many times it loops?
ideally 10 times
for (let i=0; i < 10; i++) {
alr
but since the amount of users is lower than than 10 rn, i get an error because user.userID is undefined 8 times
for (let i=0; i < (sorted.length > 10 ? 10 : sorted.length); i++) {
sorted.find(u => u.userID === id)
that gives me the object of that user
findIndex
how do i use it? Tried multiple things, none work
sorted.findIndex(u => u.userID === id)
