#development

1 messages · Page 154 of 1

deft wolf
#

Good job

neon leaf
#

same

brave geode
#

I'm new in web development. I wanted to create a dashboard for my bot. My bot have like 60+ shards. when user auth I want to show all mutual guilds with bot. Should I use ws to get all guilds from bot to website or should I create a api endpoint?

quartz kindle
#

mutual guilds is not a good idea, its very spammy, api-wise, unless you have all members cached

frosty gale
#

isnt it literally a case of getting all the guilds the user is in through the oauth scope and then seeing if the bot is in those guilds, whether by querying a database with said IDs or broadcasteval?

#

then that can be cached

real rose
#

yea use the oauth schope then you can check if the bot is in those servers, and if the user has admin/manage guilds

#

or however you wanna work that

frosty gale
#

for communication with my bot and dashboard i used an api setup on the bot side but you could opt in for something more complex like redis message brokers if youre fancy or websockets indeed

#

depends on your scale

quartz kindle
#

oh yeah i fogot about oauth, since you already have the user's oauth you can just add the guilds scope

sterile brook
#

is there smth like awaitModalCancel()? when person just closes it without submitting

lament rock
#

For Discord? No. No events are sent if the user doesn't submit a modal

radiant kraken
#

can anyone help me with puppeteer here?

client side:```js
console.log('- [client] launching browser...')
const browser = await puppeteer.launch({
headless: 'new'
})

  console.log('- [client] launching browser page...')
  const page = await browser.newPage()
  
  console.log('- [client] requesting to localhost:8080...')
  await page.goto('http://localhost:8080', {
    waitUntil: 'domcontentloaded'
  })

  console.log('- [client] running tests...')
  const a = await page.evaluate(async () => {
    return window.a.toString()
  })
index.html: ```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
  </head>
  <body>
    <script type="module">
      window.a = 69
    </script>
  </body>
</html>

page.evaluate doesn't work because it says that window.a is undefined, despite me using waitUntil: 'domcontentloaded'

sharp geyser
#

I don't think domcontentloaded pertains to script bodies do they?

#

I might be wrong

radiant kraken
#

how do you even make puppeteer wait until all scripts are executed

sharp geyser
#

hm

#

@radiant kraken have you tried looking into the waitForFunction?

#

or any of the other wait methods

#

something there might be able to help you

#

what happens if you do waitForNetworkIdle or put networkidle0 in the waitUntil

#

presumably that will wait until all javascript has executed at least according to stack overflow

crude totem
#
Error handling request
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/aiohttp/web_protocol.py", line 433, in _handle_request
    resp = await request_handler(request)
  File "/home/container/.local/lib/python3.10/site-packages/aiohttp/web_app.py", line 504, in _handle
    resp = await handler(request)
  File "/home/container/.local/lib/python3.10/site-packages/topgg/webhook.py", line 163, in _handler
    (BotVoteData if type_ is WebhookType.BOT else GuildVoteData)(**data),
  File "/home/container/.local/lib/python3.10/site-packages/topgg/types.py", line 366, in __init__
    super().__init__(**parse_vote_dict(kwargs))
  File "/home/container/.local/lib/python3.10/site-packages/topgg/types.py", line 46, in parse_vote_dict
    query_dict = {k: v for k, v in [pair.split("=") for pair in query.split("&")]}
  File "/home/container/.local/lib/python3.10/site-packages/topgg/types.py", line 46, in <dictcomp>
    query_dict = {k: v for k, v in [pair.split("=") for pair in query.split("&")]}
ValueError: not enough values to unpack (expected 2, got 1)```

what does this error mean and why am i getting it?
#

and py Error handling request Traceback (most recent call last): File "/home/container/.local/lib/python3.10/site-packages/aiohttp/web_protocol.py", line 332, in data_received messages, upgraded, tail = self._request_parser.feed_data(data) File "aiohttp/_http_parser.pyx", line 551, in aiohttp._http_parser.HttpParser.feed_data aiohttp.http_exceptions.BadStatusLine: 400, message="Bad status line 'Invalid method encountered'"

lyric mountain
#

but someArray only has 1 value

#

show where ur creating topgg client

craggy pine
#

if that giant string is your secret or any type of token I'd suggest not putting it in this channel like that.

crude totem
#

smfh im a little high

#

why wont iet let me regenerate the token for the bot

lyric mountain
#

if u did put, reset it ASAP

crude totem
#
dblclient = topgg.DBLClient("token").set_data(CLIENT)
autoposter: topgg.AutoPoster = (
    dblclient.autopost()
    .on_success(on_autopost_success)
    .on_error(on_autopost_error)
    .stats(stats)
)```
lyric mountain
#

there are selfbots here to grab tokens

crude totem
#

but anyways this is where i set up the client

frosty gale
eternal osprey
#

hey guys sorry for these dumb questions all the time, but would working with vh and vw be a good practice for a responsive website?

#

i mean, by doing this the site changes, scales up or down relative to the viewport of the user.

sharp geyser
#

I usually use vh and vw anyway

#

I hardly ever use pixels unless I have to

eternal osprey
#

i see thankss!

eternal osprey
#

damn i am samrt

peak drum
#

nice

spark pebble
#

How do you link app commands like this? ❤️

rustic nova
spark pebble
#

</NAME:COMMAND_ID> right?

rustic nova
#

yes

spark pebble
#

I know i'm being 100% stupid but how do you get a command id?

#

dw found it!

rustic nova
warm surge
rustic nova
#

There's another way to get the id?

spark pebble
#

ahh ty ty, I just grabbed it from Intergrations, but you're way is much easier 😄

#

my idiot brain took me to intergrations before trying anything else 🤣

rustic nova
#

Oh

deft wolf
rose warren
#

You can fetch it from the API. You can get the commands endpoint to dynamically fetch all command names and IDs.

#

That's the best way instead of hard-coding it

hidden moth
#

Guys, has finally been verified my bot

rose warren
#

GGs

hidden moth
#

Do you know how it is possible to get the developer badge?

rose warren
#

-nobadge

gilded plankBOT
hidden moth
deft wolf
#

Yea

#

This is one of those og badges you'll never get

#

Like early supporter or something like that

hidden moth
#

How can I do this now that my bot is verified?

deft wolf
#

You can't add it, it will appear by itself some time after your bot is verified

hidden moth
#

oh ok

quartz kindle
# eternal osprey damn i am samrt

what platform is that? last time i saw a platform that did that, the results were so wrong you had people with slow ass code with a higher score than actual fast codes lmao

eternal osprey
#

I could make the function even faster

#

By returning if the initial condition wasn’t met before the loop.

quartz kindle
#

is there a way to see other people's solutions and their performance results?

eternal osprey
#

Yeah

#

You can see all solutions that were handed in

quartz kindle
#

then check if their performance results make sense, for example a solution using for loops will always be faster than a solution using array methods like .forEach or.map

#

because i remember one website where their results were completely non-sensical

eternal osprey
#

yeah I did. I was surprised i created this code and didn’t believe it so I did my research by looking at other solutions written in js. I used for loops and others usually forEach, while etc.

quartz kindle
#

i dont remember what was the name of the other website

#

but i remember they had like rankings for problems, and the top rank solution was slow af

#

lmao

eternal osprey
#

Also what i did was creating an arrow function to check whether a condition was met, others usually didn’t create a seperate function but copy pasted the checks each time

eternal osprey
#

leetcode is pretty fun and cool to learn. So far i think I know a lot about the dom and nodejs so i thought let’s do some challenge problems

quartz kindle
#

like, their benchmarking system was really bad and pretty much random, every time you ran the function you would get completely different results

#

so the guy got top rank by luck

eternal osprey
#

Oowhh no leetcode is pretty known for accurate results. It’s also linked to lots of companies who provide tests, reviews and challenges

quartz kindle
#

thats what im interested in, how accurate their results are

#

because js is not easy to benchmark

#

there is a lot of variance

eternal osprey
#

Lets do a quick research 🙂 I think they have a field on their website talking about the benchmarks

#

One sec I’ll try to find it

quartz kindle
#

yeah pretty much same shit

#
  • check top ranked solutions
  • copy paste them and run them
  • watch the result being slower than what you initially did
  • yet somehow they got top rank
eternal osprey
#

this was back in 2020 tho

#

idk over the years it got way more popular due to people talking about it etc

#

they might have fixed it but I’ll take the runtime with a grain of salt..

#

as long as my code passes the test cases I’m good ig

quartz kindle
#

the thing is, its almost impossible to accurately benchmark js

#

especially online like that

#

i would rather trust a loop with 1 million iterations and run my function in there

tulip ledge
#

Leetcode is known to be inaccurate tho

quartz kindle
#

because what these companies do, is they put your code in a file, and call node thatfile, and measure the time to complete that

#

which includes the whole nodejs spin up time, which is wildly variant

tulip ledge
#

Best u can do is benchmark it yourself with console.time() or create a big-O notation if your function isn’t too complicated

quartz kindle
#

also who knows how many machines they have to run thousands of things per day, which introduces even more variance

tulip ledge
#

But if you benchmark it yourself you’ll need other function to compare to, ran in the exact same environment

quartz kindle
#

an accurate comparison has to be always done in the same machine in the same configuration

#

yeah

#

so basically, online benchmarking competitions are a lottery, you win by luck, not by fast code

#

xD

eternal osprey
#

I see. Damn I am stupid then hahahaha

#

Still the code I wrote was mint tho 😭

quartz kindle
#

:^)

eternal osprey
#

sure I will send it once I am home

soft laurel
#

How do people have fancy descriptions for their bot?

gilded plankBOT
civic scroll
#

wow

#

luca ai

deft wolf
#

-htmldesc -d MegaThonk

soft laurel
#

does it support javascript?

#

Mine won't save for whatever reason D;

lyric mountain
#

it doesn't

#

and for a good reason

soft laurel
#

how do people get the interactivity in their stuff?

#

I've seen pages where you can select buttons with animation and stuff

lyric mountain
#

you can do animations with css alone

#

regarding buttons, you probably saw an iframe

#

which is a site embedded into the long description

soft laurel
#

ahhhh, the iframe. makes sense, ty

lyric mountain
#

worth to note, iframes cannot access the parent, so whatever scripts u got into it will only work on the site itself

neon leaf
#

so I want to delete many rows using prisma, the thing is I also need some data of the deleted rows back, not just count (the only thing included by default). how can I do that without losing performance? Im mostly deleting around 200 items, maximum 500 at a time

lyric mountain
#

the best you can get is doing 2 queries

#

one to get data, the other to delete

neon leaf
#

hm

#

would a prisma transaction make that in any way faster? no, right?

lyric mountain
#

not really

#

transactions only mean u can rollback should anything happen

neon leaf
#

currently I have

    .http('POST', '/', (http) => http
        .document((docs) => docs
            .description('Cancel multiple Invoices')
        )
        .ratelimit((limit) => limit
            .hits(3)
            .window(time(1).s())
            .penalty(time(2).s())
        )
        .onRequest(async(ctr) => {
            const infos = ctr.validateZod((z) => ({
                items: z.number().array().max(500)
            }))

            if (!infos) return

            const { count } = await ctr["@"].database.invoice.updateMany({
                data: {
                    status: 'CANCELLED'
                }, where: {
                    status: 'PENDING',
                    userId: ctr["@"].user.id,
                    id: {
                        in: infos.items
                    }
                }
            })

            FIX SIR

            return ctr.print({ success: true, count })
        })
    )```

so the way you proposed would be
```ts
    .http('POST', '/', (http) => http
        .document((docs) => docs
            .description('Cancel multiple Invoices')
        )
        .ratelimit((limit) => limit
            .hits(3)
            .window(time(1).s())
            .penalty(time(2).s())
        )
        .onRequest(async(ctr) => {
            const infos = ctr.validateZod((z) => ({
                items: z.number().array().max(500)
            }))

            if (!infos) return

            const invoices = await ctr["@"].database.invoice.findMany({
                where: {
                    status: 'PENDING',
                    userId: ctr["@"].user.id,
                    id: {
                        in: infos.items
                    }
                }, select: {
                    id: true,
                    // any other data I want to process with
                }
            })

            for (const invoice of invoices) {
                // do some stuff
            }

            await ctr["@"].database.invoice.deleteMany({
                where: {
                    id: {
                        in: invoices.map((invoice) => invoice.id)
                    }
                }
            })

            return ctr.print({ success: true, count: invoices.length })
        })
    )```
?
lyric mountain
#

I think so

#

Not that I've used prisma anyway

solemn latch
neon leaf
#

I definitely have some regrets too, but migrating to somethig like drizzle would take too long

quartz kindle
#

i have a question about Angular, so basically there is a group of students who are doing an Angular course but they are having trouble with some basic JS concepts like classes, oop, inheritance, polimorphism, typescript and shit. So i was tasked with giving them a reinforcement class on those concepts, which is fine, but also they want a few examples of how they are used in an Angular context.
i've never used Angular before, so if anyone here is experienced with Angular, can you explain a little bit and provide a few examples of how Angular works and how to particularly show a bunch of people how OOP is used in Angular?

#

i'll be looking at some Angular docs and tutorials tomorrow, but any input, tip or example would be nice

#

but the basic premise is "teach students about OOP and how its used in Angular"

neon leaf
#

an orm that aims to only send 1 query with every invocation (and use native join unlike prisma for some reason)

sharp geyser
neon leaf
#

yes

sharp geyser
#

Actually doesn't look all too bad

#

i'd likely use it over typeorm or prisma

#

prisma is still one of my go to choices tho

dry imp
latent ravine
compact pier
#

what is the best way to display a big size image?

#

I have 20 images that weight about 10mb each

#

I think <Image> component from nextjs can compress it right?

lament rock
#

Compress the images manually

#

Having to compress an image each time you serve it would suck up cpu power very quickly

#

Also serve them as webp if available

quartz kindle
#

doesnt the framework cache the compressed images or something?

civic scroll
#

so by being a class it can do one of the stuffs like

  • encapsulates data and its own logic (each property in the angular component class is a state)
    which is also inheritance, due to the class implementing interfaces like OnInit
  • or, it can also extend other classes / components to inherit structure / logic
    similar cases to polymorphism: a class that implements an interface / another abstract class
    i did this but tbh the code looks ugly
#

in short,
any angular-extended class property is a state
all of its dependency will be updated whenever those states change
for inheritance, you can have other component classes inherit base + implementing interfaces, like OnInit, OnChange functionality of a base component class
for polymorphism, same case of overriding abstract class methods

#

and don't forget depency injection

export class ExampleComponent {
    constructor(private / public exampleService: ExampleService)
    {
        // After this component is constructed, you can access the service's methods and look at its states (this component update callback via `OnChange.ngOnChange` method would also get triggered when any of its dependencies (services)' state updates)
    }
}
quartz kindle
#

hmmm i think i understand, well most of it

#

thanks!

civic scroll
quartz kindle
#

i dont think i'll need to go in depth into angular and explain what is a decorator and how does it work, since they have a different teacher for that (i hope)

civic scroll
#

as long as the dependy is Injectable

quartz kindle
#

or explaining state changes

civic scroll
quartz kindle
#

isnt it still experimental in ts?

civic scroll
civic scroll
quartz kindle
#

are angular decorators exactly the same as in ts?

#

can you use them in a version of ts that doesnt support decorators?

civic scroll
#

yes

quartz kindle
#

or has them disabled?

civic scroll
quartz kindle
#

so ts with decorators enabled is a requirement for using angulrar

#

alright

civic scroll
#

yeah

quartz kindle
#

so i guess i'll have to go into that subject too

#

i dont really like decorators as a concept, i think they are confusing and hard to understand lol

civic scroll
#

the flag is experimentalDecorators

civic scroll
#

unless you want them to also make their own decorators

#

which is definitely helpful

quartz kindle
#

nah, just so they know dafuq angular is doing when you type atComponent

#

from what i understood, they started an angular course, and the teacher started using components an classes and all that, and the students were like, uh... dafuq is a class?

civic scroll
#

i just explain that "angular would add this class to the component tree, adding necessary identifiers and some other metadata for rendering later"

civic scroll
#

damn...

#

they will need to learn typescript and oop first before working with angular

quartz kindle
#

yeah thats what i was tasked with

#

its just that they wanted me to also give some examples of how it looks like when applied to angular

#

so they get more familiarized

#

but for the most part i will not be going into angular, just sticking with oop and ts

#

i wonder how much can be done in mere 3 hours (thats how long the class is gnna be)

civic scroll
#

ah also what ide they use

#

anything with intellisense is suffice

quartz kindle
#

i sure hope they use vsc

civic scroll
#

encourage them to explore via hints
in vsc that is Ctrl + Space

quartz kindle
#

ye

civic scroll
#

you can also show additional notes / docs of a suggestion as well

quartz kindle
#

is it the same in jetbrains and shit?

#

ctrl space i mean

civic scroll
#

with vsc keymap yes

quartz kindle
#

ah

civic scroll
#

not sure about others

quartz kindle
#

well i'll just tell them if they use a different code editor to look into how to do that there

#

inb4 someone uses notepad

civic scroll
#

yeah that works

quartz kindle
#

:^)

civic scroll
#

or for some without editor

#

tell em to use stackblitz

quartz kindle
#

code js with physical transistors

civic scroll
#

with crafted cpus omegalul

quartz kindle
#

from sticks and stones

civic scroll
#

also another thing, since it's typescript
tell them to be aware of the kind of data they are working with at all times

quartz kindle
#

like paying attention to typings and stuff?

civic scroll
#

esp. one created by their code, tell them to pay attention to types, function / method signatures

#

yeah, and maybe also teach them how to read errors as well

quartz kindle
#

i'll try

#

yeah type errors can be confusing

civic scroll
#

there are 2 types: compile error and runtime error
in this case we will do type error

civic scroll
#

so at least they will know what to ask for help for when they are in trouble

quartz kindle
#

i'll hire you as an assistant teacher

#

but you need to speak portuguese xd

civic scroll
#

typescript also have error code associated with an error, and you can google the error code up for examples, which is neat

civic scroll
quartz kindle
#

go to brazil

#

:^)

#

you can bring voltrex too

civic scroll
#

i wish PensiveWobble

#

i will go to brazil when i can

#

ah tim

#

one more thing

#

just make it simple

#

only includes part of the code that relates to the topic

#

to reduce noise

quartz kindle
#

yeah

#

im planning to go very basic on it

#

but i'll need to ask first how they feel about it and what exactly they have trouble with

civic scroll
#

with other part of the code (i suppose to show integrations later), just fade it to make the part you are talking about stands out more

civic scroll
#

so that you can see what are the main struggles and tackle one by one

quartz kindle
#

ye

#

because supposedly they already had a basic JS course

#

so they should already know a few things

civic scroll
#

ts is like js with types

#

i believe they will be fine after showing similarities

quartz kindle
#

ts is js pretending to be c#

#

or java

civic scroll
#

at least js has top-level statements gx_tro

quartz kindle
#

xD

civic scroll
#

oh yeah

#

also encourage them to type the same thing in their editor

#

to show that it works like demonstrated

#

(only for simple examples)

quartz kindle
#

something fun that i saw another teacher do, is have the students suggest what to type on his screen

#

so he just types what the students say

#

withtou correcting them

#

and then go over the mistakes

civic scroll
#

that works too

#

low key i would do that in my next english class

quartz kindle
#

xD

civic scroll
#

make it as interactive as possible

#

for some reasons people likes hands-on learning

quartz kindle
#

ye

eternal osprey
rustic nova
#

localhost != 127.0.0.1 according to chrome/firefox

quartz kindle
#

lmao

rustic nova
#

which is logical though

#

per URI, localhost is not 127.0.0.1

eternal osprey
#

so i should have the app.js run on 127.0.0.1 instead

rustic nova
#

that wont make a different, just visit localhost:3001 within your code

#

aka within your fetch

eternal osprey
#

oowh

#

if i host this with ngrok or something

#

would i be able to set a proper domain name

#

for my api

rustic nova
#

yes, or you just use localhost to visit your site

#

way easier

#

you're currently on 127.0.0.1 and not localhost, thats why cors says no

eternal osprey
rustic nova
#

if someone accesses your website outside of localhost then yes that wont work

eternal osprey
rustic nova
#

oh where's your server

#

I dont understand your setup tbf

civic scroll
#

@eternal osprey okay so

#

if that is your server endpoint

#

you better add an OPTION handler for all the paths

rustic nova
#

or just go fuck all and cors allow everything during development

eternal osprey
#

wait should i rpovide some code lmao

civic scroll
#

browsers often do preflight checking, which is sending an OPTION request to the endpoint beforehand to check for what is allowed to include

#

so in this case

#

you will need to add the corresponding header field on the OPTION handle

#

@eternal osprey

#

just you know, read the error carefully

eternal osprey
#

i have no fucking clue what preflight is

civic scroll
#

also i just explained above

#
app.option('*', (_, response) => {
    response.header({
        // required header here
    }).send()
})
#

something like that idk express

#

it's kinda funny how you don't search something up when you know it

#

but yeah general tip is read the error carefully

#

read it twice

rustic nova
#

make it 3

civic scroll
#

fr

#

webdev is funky

eternal osprey
#

just watched a tutorial about this subject

#

finally undestand how it works

#
app.use(
  cors({
    origin: "http://127.0.0.1:3001",
  })
);
app.use("/tax", routes);
app.listen(3000);``` i got one last issue tho
#

why is this page not defined?

quartz kindle
#

go you have a routes.get("/") ?

eternal osprey
#

yup

#

let me send the actual code in the route

#
const express = require("express");
const routes = express.Router();

routes.get("/", (req, res) => {
  console.log(req);
  res.status(200).send("good");
});

module.exports = routes;
deft wolf
#

Hi guys, I don't ask questions here very often, but maybe you know a way to limit the size of a Set in javascript, let's say to 100? I've already looked online for some methods, but it wouldn't hurt to ask here as well

quartz kindle
eternal osprey
#

maybe my fetch is wrong

quartz kindle
#

try /tax/

eternal osprey
#
 fetch("http://localhost:3000/tax", {
        method: "POST",
        headers: {
          "content-type": "application/json",
        },
        body: JSON.stringify({
          country: this.getCountry(),
          grossIncome: this.getGrossIncome(),
          taxPercentage: this.getTaxPercentage(),
        }),
      })
        .then((res) => {
          if (res.ok) {
            console.log("POST request successful");
            return res.json();
          } else {
            console.log("Error sending POST request");
            return new Error("Error sending POST request");
          }
        })
        .then((data) => console.log(data));
    });```
eternal osprey
quartz kindle
#

ah

#

you're doing a POST

#

not a GET

eternal osprey
#

omg that was from practicing before, i forgot tot change iut

slender wagon
#

So which way would be the best way to store invoices of certain users?
Is it inserting in their table better than making a new one called Invoices and store all the invoices there and each one has a user id to whom it belongs to

lyric mountain
#

yes

#

oh wait, no no

#

dont store in their table, fat columns are bad

quartz kindle
#

as a general rule, if you have multiple copies of something, it should be in its own table

frosty gale
#

i did learn something useful from computer science after all

digital swan
#

anyone have tips for looking for a memory leak? i tried using the chrome debugger thing but it just crashes the bot with 100% cpu usage

lyric mountain
#

memory leaks ain't very easy to find

#

some tools have a built-in profiler, which u could use to get a flame graph

#

ik webstorm does have it

digital swan
#

it takes a few days for it to become noticeable though

#

im rly tempted to move to digitalocean for their droplet memory graph so i can see if its caused by a certain event or something

lyric mountain
#

when it becomes noticeable, use kill -USR2 <pid>

#

this will generate a heap dump in the folder you were at the moment

digital swan
#

would it not make a difference if im using discord hybrid sharding

lyric mountain
#

memory leaks dont happen like that

digital swan
#

its always on the clusters though

lyric mountain
#

is your code public?

digital swan
#

yeah

#

you want the repo?

lyric mountain
#

would help to see the code yeah

digital swan
lyric mountain
#

why are u starting intervals and jobs inside timeouts?

#

or actually, doing everything inside timeouts

digital swan
#

there was a job that relied on data that would only be available after the bot had started up so the timeout for that is to preven the job running without the data it needs

lyric mountain
#

u can use .then for tasks that must run after the bot is online

#

using timeouts wont guarantee the bot is ready at execution time, as connection time isn't constant

digital swan
#

it doesnt but ive never had a problem with using timeouts

lyric mountain
#

that's still relying on luck, but up to u

#

well, I'll need a heap dump to be able to find anything wrong, too many files to check

digital swan
#

yeah ik its a nightmare

crystal wigeon
#

hey can anyone help with postgres? Im using knex and currently due to high traffic on my discord bot, it suddenly disconnects Database and i get the error "connection timeout"

#

what can i do here, how do i debug and fix this

#

my pg max connections is 100

#
dotenv.config({ path: "../../.env" });

export default {
    development: {
        client: "pg",
        connection: {
            host: process.env.DB_HOST,
            user: process.env.DB_USER,
            password: process.env.DB_PASSWORD,
            database: process.env.DB_NAME,
        },
        pool: {
            min: 1,
            max: 5
        },
        migrations: {
            tableName: "knex_migrations_ts",
            directory: "migrations" 
        }
    },
    onUpdateTrigger: (table: string) => `
  CREATE TRIGGER ${table}_updated_at
  BEFORE UPDATE ON ${table}
  FOR EACH ROW
  EXECUTE PROCEDURE on_update_timestamp();`,
};

This my knex config

lyric mountain
#

you need to ping the database ever so often

crystal wigeon
#

maybe i need to increase the max pool?

lyric mountain
#

else the conn will get dropped

crystal wigeon
#

it is always connected to db

#

peoplel are active using it

#

it suddenly disconnects

#

it suddenly just throws the connection timeout error

marsh lark
#

I assume whichever lib (like pg) that knex uses handles the database connection

lyric mountain
#

anything in postgres log?

#

also, reduce the pool size, 100 is way too much

crystal wigeon
#

max_connections is pg config is 100

#

which is normal ig?

crystal wigeon
lyric mountain
#

ah yes, then ur max connections is 5 (in code)

#

as the pool will never go above that

crystal wigeon
#

yea

marsh lark
#

If you only have 1 shard then it definitely should be enough

crystal wigeon
#

there are 12 shards

#

for my discord bot

lyric mountain
#

5 is enough, that wont be the issue

crystal wigeon
#

so that probably connects 12 times?

marsh lark
#

Yes but pool size doesn't need to be the max connections you might get

crystal wigeon
#

yeah so my config should be fine

#

also where can i see postgres logs

lyric mountain
#

in etc I think

crystal wigeon
#

nop

lyric mountain
#

run SELECT pg_current_logfile()

#

it'll tell u where it is

crystal wigeon
#

it says null lol xd so its not set in pg config

marsh lark
#

See /var/log/postgresql?

crystal wigeon
#

i found it

#

yeah

crystal wigeon
#
could not receive data from client: Connection reset by peer```
#

this is the error i got

#

i see in the log

#

hmm

lyric mountain
#

well, then the error is in ur code

#

as it's crashing the connection

crystal wigeon
#

unexpected EOF on client connection with an open transaction

#

mmm

lyric mountain
#

it's happening during some transaction, perhaps ur getting OOM

#

how's your ram usage?

crystal wigeon
#

normal

#

i dont see any high usage so i was investigating why it keeps crashing

lyric mountain
#

and i get the error "connection timeout"
do u have a stacktrace?

crystal wigeon
#

ah nop, well the stack trace is from the current commands being trying to access DB then failing

lyric mountain
#

but where is that error being logged?

crystal wigeon
#

so could be someone tried sql injection, and closed connection?

lyric mountain
#

like, the line where u print to the console

crystal wigeon
#

its being logged into my log file

#

ye it gets logged into an out file

lyric mountain
#

Not what i mean

#

U have to be printing it somewhere

#

Or is it an uncaught exception?

crystal wigeon
#

yeah, in the catch block

#

nahj

#

its caught

#

it is not crashing the app

lyric mountain
#

In that block, make it print the stacktrace

crystal wigeon
#

just the db

#

yeah, the stack trace shows which command was invoked

lyric mountain
#

Which one is it?

#

Brb, gonna lose internet for a while

crystal wigeon
#

but its not the command that broke the connection. any new commands after the connection breaks, it sits in connection timeout until i restart the app

#

kk

#

it might be because im not wrapping the db transaction in a try catch block

#

hmmm but weird nothing should break there

#

is there a way i can reconnect if the connection drops in knex? instead of me restarting the whole app

lyric mountain
#

Poolers are supposed to reconnect automatically

crystal wigeon
crystal wigeon
lyric mountain
#

Hm

crystal wigeon
#

well i bascially make a db call to fetch some data whenever any command is called

#

so it fails initially without the connection

lyric mountain
#

What data are u fetching?

crystal wigeon
#

im trying to figure out what caused the issue in the first place

#

user data

lyric mountain
#

How much data are we talking?

crystal wigeon
#

the crash happened way before

#

some 5 columns thats all

#

probably some data in where clause might've caused it

lyric mountain
#

U could try finding another pool manager, to see if the issue is with it

crystal wigeon
#
2023-08-03 14:57:01.419 UTC [2517794] postgres@izzi STATEMENT:  select * from commands where alias::jsonb @> '"didn't"' and is_deleted```
#

becuase i see this error

#

in pg log

lyric mountain
#

Ur not using params?

crystal wigeon
#

this is a special case yeah so had to do raw

#

probably need to normalize this

lyric mountain
#

Use params in 100% of the cases

#

If it doesn't allow params, find another way to make it allow

crystal wigeon
#
            `select * from ${tableName} where alias::jsonb @> '"${key}"' and is_deleted = false`
        )```

This the query
#

mm

lyric mountain
#

Replace raw with the proper function

#

Raw doesn't sanitize params

#

Also why is tablename variable?

quartz kindle
#

prepared statements dont support table name variables, so sometimes if you want to programmatically query different tables, you have to use raw

crystal wigeon
#

its jsut a global constant

quartz kindle
#

at least in sqlite

lyric mountain
crystal wigeon
lyric mountain
#

Hardcode it then

crystal wigeon
#

its from a local constants file

#

ye its all hardcoded

quartz kindle
#

i guess he wants it to be configurable from a json file

crystal wigeon
#

yeah, im thinking thats probably why it happened

#

using raw

lyric mountain
#

Hm, then use the regular query function but append the table name with + tableName +

#

It won't be caught as a param, so it'll still work on regular query

quartz kindle
#

'"${key}"' this will never support the ' character

#

so you have to either remove it from all queries, or specifically find it and escape it

#

or use prepared statements for that part

crystal wigeon
#

yeah, im trying to serialize it pretty much

lyric mountain
#

It'll be caught as a param

#

So the quote will be escaped

crystal wigeon
#

apparently it didnt

lyric mountain
#

Because u used raw

#

Raw treats the query as literal

crystal wigeon
#

i just have to convert the query using knex query builder and should be fine

#

knex will take care of serialisation

#

@lyric mountain okay so i got this error this time

#
2023-08-03 15:30:20.784 UTC [2519253] [unknown]@[unknown] HINT:  This may indicate that the client does not support any SSL protocol version between TLSv1.2 and TLSv1.3.```
#

pg is in same machine

lyric mountain
#

Something related to your database connection string probably

crystal wigeon
#

weird

#

it happens after some time tho like wtf

#

when the app is up and running

#

it breaks suddenly in the middle after 30mins

thorn spruce
#

Hey guys, I'm looking for a list of "bad words" in all the world's languages there's an public api or file idk ? because i found nothing

deft wolf
#

You are not alone

thorn spruce
#

ahh don't relate to the automods, just working on a guild system but i need to allow player to give a name

deft wolf
#

I found something more youtube related

thorn spruce
#

i just found that

deft wolf
#

500+ words in google document

digital swan
lyric mountain
digital swan
#

yeah the memory usage had increased by about a gb before i did the snapshot

lyric mountain
#

do u know how to read a heap dump?

digital swan
#

nah idk what im looking for or what would be considered normal

lyric mountain
#

send it

digital swan
#

yeah idk about that its got the token in it

lyric mountain
#

replace it, it's a text file

#

also whatever else u consider sensitive

digital swan
#

oh shit alr awesome 1 min

violet latch
#

If I change the name of the bot,how long does it take to update it on top.gg?

#

or do I have to do this manually

lyric mountain
#

u need to click refresh data

#

and then go into Edit and save

violet latch
lyric mountain
#

in the bot edit page, in topgg

violet latch
#

ah thank you

knotty quartz
#

hi

frosty gale
#

bye

quartz kindle
#

you say goodbye

#

and i say hello

knotty quartz
frosty gale
#

are there any good clustering libs in js

#

by that i mean something which can spawn and manage clusters and distribute load amongst them evenly

#

not confined to the same machine either

solemn latch
#

Maybe I'm misunderstanding, but I dont think you would want to use JS for something like that

frosty gale
#

well maybe i do

#

nevertheless what would you suggest on a basis of language?

solemn latch
#

For cluster management?
kubernetes

frosty gale
#

sounds interesting

#

how does it even integrate into applications

solemn latch
#

For kubernetes it just starts runs containers

frosty gale
#

like docker containers?

#

what about distributing messages/tasks/commands to those instances on the api level?

#

google is more focused on telling you why they should sell you it on GCP rather than explaining what it can do in detail

earnest phoenix
wheat mesa
#

the first damn time someone has used markdown appropriately in #development

earnest phoenix
rustic nova
#

Shit you're right

#

anyways time to ruin this moment

#

though I think Voltrex has used it before

#

haven't you?

lament rock
#

Task distribution is a broad term. There are many different ways to manage tasks such as round robin, random, etc.
How exactly you would determine which one is doing the least amount of work as well can be code base dependent which would require you to make your own scheduler

#

A chain of tasks inter-dependent on each other should also go to the same node if necessary

#

For example, I encode cluster IDs in button custom_ids

earnest phoenix
crystal wigeon
#

how do i send an embed in broadcast eval?

#
        await client.shard?.broadcastEval(async (cl) => {
            const channel = await cl.channels.fetch(id);
            if (!channel || channel.type !== "GUILD_TEXT") {
                return;
            }
            const embed = createEmbed(author, client)
                .setTitle(title)
                .setThumbnail(//image
                )
            channel.send({ embed });
        });```

This is my current implimentation
#

i keep getting the error "embed" is not defined

marsh lark
#

Also in your code you're not passing in any context at all, remember that inside the function you cannot access any local variables

crystal wigeon
#

gotcha, thanks lemme try this

marsh lark
#

So something like ```js
const json = generateEmbed(...).toJSON();
await client.shard?.broadcastEval(async (cl, { json }) => {}, { context: { json } });

crystal wigeon
#

to get back the object

marsh lark
#

yes

#

but djs already handles that for you

#

you dont have to pass in a string, you can pass in json as an object

#

so you can new EmbedBuilder().toJSON()

crystal wigeon
#

oo ic, thanks

frosty gale
#

i had a flick through it and im not sure if its advanced enough

#

@earnest phoenix why is nodejs doing a github

#

if its because someone got offended i want to live on mars

rustic nova
#

Please tell me there also was a rename for something like setupSlave

quartz kindle
#

peer pressure offense

#

there are some weirdos who made it their life mission to go on every single repo and open source project ever, and yell at them "please change it, everyone else is also changing it, if you dont then you're evil"

radiant kraken
#

@earnest phoenix rough rust implementation of the unicode bidirectional algorithm mimu_thisisfine

#

this does not include rendering each paragraph btw

#

should decancer implement bidi support is that too overkill

quartz kindle
quartz kindle
#

3complex5me

radiant kraken
#

i copied it from some library's code and try to stitch them together so i can see the rough approximation of how the algorithm works, but it just confuses me instead 😭

#

i want my library to have right-to-left text rendering support

#

the fact that the chromium browser secretly have this algorithm implemented whenever it renders text is crazy

quartz kindle
#

its probably from ICU

#

both chromium and node have it as a dependency

radiant kraken
#

ICU?

quartz kindle
#
earnest phoenix
radiant kraken
#

i just hate the fact that the way unicode text laid out in memory is not the same as how unicode text is read left-to-right

earnest phoenix
quartz kindle
#

can decancer cure cancer?

radiant kraken
#

the pseudocode is over 600 lines long 😭

radiant kraken
quartz kindle
#

nice

#

wait, why did my nickname change

#

dafuq

radiant kraken
#

its funny because your real name isnt even timothy

quartz kindle
#

yeah lmao

rustic nova
neon leaf
#

so I have a poll system, each poll has options and answers, whats the best way with this schema (even if you dont know prisma you should probably understand it enough) to get the percentage of answers that each option of poll X has?

#
  id Int @id @default(autoincrement())
  pollId Int
  poll Poll @relation(fields: [pollId], references: [id], onDelete: Cascade)

  title String @db.VarChar(255)

  answers PollAnswer[]

  @@map("pollOptions")
}

model PollAnswer {
  id Int @id @default(autoincrement())
  pollId Int
  poll Poll @relation(fields: [pollId], references: [id], onDelete: Cascade)
  userId Int
  user User @relation(fields: [userId], references: [id], onDelete: Cascade)
  optionId Int
  option PollOption @relation(fields: [optionId], references: [id], onDelete: Cascade)

  chosen DateTime @default(now())

  @@map("pollAnswers")
}

model Poll {
  id Int @id @default(autoincrement())

  title String @db.VarChar(30)
  multiSelect Boolean

  options PollOption[]
  answers PollAnswer[]

  created DateTime @default(now())
  expires DateTime?

  @@map("polls")
}```
plain talon
#

🥄

neon leaf
#

im not asking for code, im asking for the best approach

frosty gale
#

this is giving me graphql vibes

#

why cant graphql just die

#

anyways

frosty gale
neon leaf
#

yes so like "30% chose option Y"

lyric mountain
#

Poll and User are the primary keys

#

it's an M-N relationship

neon leaf
#

like all fields with @relation dont actually exist, they are just abstractions

lyric mountain
#

the middle table (PollAnswer) must have a reverence to both Poll and PollOption

#

as it's just making the connection between them

#

I sent an UML not so long ago here, lemme see if I find it

#

but with the FK on nutrition facts, not product

#

kinda messed this

#

basically you Poll will have and id, and so will PollOption

#

then PollAnswer will reference both Poll and PollOption, having 2 FKs as primary keys

neon leaf
#

ah

#

how would I be able to get all possible options for a poll then?

#

nvm

lyric mountain
neon leaf
#

alr, yeah that turns out to save me some trouble

#

I have this now

frosty gale
#

oo btree

#

im surprised it doesnt use b+ trees

#

its better suited for database indexing

lyric mountain
frosty gale
#

makes sense

#

pretty cool

quartz kindle
#

hash table best

frosty gale
#

hash tables are actually used in some databases still

#

but theyre inefficient

#

use too much space

#

and the rehashing/resizing procedure is extremely slow

quartz kindle
#

stil

#

o(1) retrieval

#

:^)

frosty gale
#

not sure how that factors into the performance modelling

#

i think its not significant enough

quartz kindle
#

with robin hood you can go up to ike 95% instead of the typial 75% load factor

frosty gale
#

chance is still there though

#

but yeah if there was no need for resizing hash maps would be op

#

i wonder how c++/js hash maps resize/decide when to resize+rehash

#

its quite a significant operation especially in large hashmaps

quartz kindle
#

its usually based on load factors

#

when it reaches a certain % of filled hashmap

#

i think by default its 70%

frosty gale
#

i think thats what i did with mine

#

ill check what i set it to

#

think its 90%

quartz kindle
#

90% may not be very efficient if you use linear probing

#

but tis fine if you use robin hood

frosty gale
#

actually 92% 💀

quartz kindle
#

xD

#

also, table resizing doesnt need to be sync

#

its can be done asynchronously and/or multithreaded

frosty gale
#

yeahh but adds complexity

#

you probably also have to make the thread wait during resizing too if it wants to set a new item

quartz kindle
#

nop

#

it can write immediatelly

frosty gale
#

although for fetching i dont see a big problem considering you can keep the old container active while you copy/rehash everything

#

but then when do you decide when to no longer allow writes

#

because it might conflict with the rehash/resize

quartz kindle
#

like you said, you keep two containers

#

you create a new one with new size, and you can immediately start reading/writing to it

#

and you asynchronously fill it up from the old one

#

reads might need to check both tables for a little while, so they will be o(2) instead of o(1), mostly

#

but writes will be done to the new one immediatelly

frosty gale
#

true that makes sense

quartz kindle
#

i implemented this in one of my shelved/abandoned projects

#

xD

frosty gale
#

iterate over each old key and re-add it to the new one with some set function

#

and then add a mutex

quartz kindle
#

yeah i implemented a separate mutex per table entry

frosty gale
#

although what if a case exists where you do so many sets so quickly that the new size of the container gets exhausted while its still copying over the old keys

wheat mesa
#

Multithreaded data structures will always be an interesting thing to implement

quartz kindle
#

i think what i did was forcing a wait

frosty gale
#

i think at some point you need to keep track of the capacity and make it wait if adding a new key would no longer make the old keys fit

#

yeah

#

it gets quite messy but if you really wanted to you could implement it

quartz kindle
#

it was fun working on it, using js buffers

#

but i shelved it because i didnt have a good serialization solution

#

for the actual data

#

also, memory fragmentation is a huge issue

#

if you also implement the memory alloc for the data

#

instead of using pointers/heap

frosty gale
#

serializing what?

quartz kindle
#

i was building something like a js Map() with it

#

key value store

frosty gale
#

honestly for a hash map i think what you could do is allocate an entire 4kb page from the operating system hence completely avoiding malloc therefore no memory fragmentation

quartz kindle
#

yeah the key part is fine

frosty gale
#

the size is reasonable regardless

quartz kindle
#

the problem was i wanted to also do the allocation for the values in js buffers

#

since js doesnt have pointers/heap

#

i scratched my head quite a lot regarding fragmentation

#

thats why i shelved the project

#

in the end i figured i had to implement something like what jemalloc does, arenas and buffers with diffrent sizes

#

too complicated

tribal crow
#

How do i update a single value in an object in an array? I'm using MongoDB, and i just can figure out how i (through code) can do so. For example, if someone buys Tesla stocks, i want it to update the quantity.

quartz kindle
#

for example stocks.find(value => value.code === "TSLA").quantity = 6

frosty gale
#

... for the unintended reasons

quartz kindle
#

lmao

#

recently i stopped using node buffers

#

and started using only uint8array

#

:^)

frosty gale
#

basically the same thing

quartz kindle
#

although for utf8 encoding/decoding, node buffers are still faster

frosty gale
#

except uint8arrays are less flexible i think

quartz kindle
#

and faster

frosty gale
#

whats the difference between uint8arrays and buffers anyways

#

i imagine the underlying storage is the same

quartz kindle
#

Buffer extends uint8array and adds things to it

frosty gale
#

makes sense

quartz kindle
#

but for some reason, some things are slower

#

because they are implemented in the nodejs cpp side

frosty gale
#

as with javascript

#

are for ofs still slower than for i's

quartz kindle
#

yes afaik

frosty gale
#

i think its because for ofs handle cases where the array gets mutated during interation

frosty gale
#

for i does not

quartz kindle
#

if you want to make a performant thing with buffers, you need 4 things, an ArrayBuffer, a uint8array, a Buffer and a DataView

tribal crow
#

The update part is what confuses me

quartz kindle
#

if you use stull like Models and Schemas

tribal crow
#

yeah

quartz kindle
#

or if you use mongo queries directly

tribal crow
#

models

#

and schemas

quartz kindle
#

then the Model should have a .save() method, no?

frosty gale
quartz kindle
#

then try that

quartz kindle
#

all others are views over that raw memory

tribal crow
frosty gale
quartz kindle
quartz kindle
#

views as in, interpretations of that memory

#

both read and write

#

unit8 interprets it as bytes

#

Buffer also as bytes, but with additional stuff

#

DataView as numerical formats, ie int32, unit64, etc

frosty gale
#

ah okay so how to interpret the underlying bytes?

quartz kindle
#

ye

frosty gale
#

never knew i could do type punning in js

#

im starting to like it more

quartz kindle
#

DataView is the fastest way to read/write multi-bytes number formats, basically

#

including bigint

#

and doubles

frosty gale
#

i see

#

how would bigints be written

quartz kindle
#

node Buffer is the fastest when reading/writing string formats, like utf8 and ascii

frosty gale
#

arent they stored as strings underneath or is it that npm library that does that

quartz kindle
#

nah, bigint is stored as a list of "words" in cpp

tribal crow
quartz kindle
#

word is either 4 byte of 8 byte idk

quartz kindle
#

but you can do it like this:

tribal crow
#

Never seen that before

quartz kindle
#

assuming each object in that array is a mongodb Model/Schema ```js
const TSLA = stocks.find(value => value.code === "TSLA");
TSLA.quantity = 6;
TSLA.save();

tribal crow
#

Hmmm

radiant kraken
quartz kindle
#

so for example read/write bigint64 in DataView will always read/write 64 bits at a time

tribal crow
quartz kindle
neon leaf
#

Stock.quantity += 2 should work too

quartz kindle
#

ye

neon leaf
#

:^)

#

Alright Who Changed Your Nickname

radiant kraken
#

i just dont find the purpose behind Uint16Array, Int16Array, Uint32Array, and Int32Array

#

when node.js is dynamically typed

quartz kindle
#

its for working with binary data

radiant kraken
#

.readUint16LE(), .readUint32LE(), etc ???

quartz kindle
#

for example if you wanna make an audio/video transcoder or whatever, where the format specifies data blocks being 2-4 bytes long, etc

neon leaf
#

so im currently adding my poll endpoints to my sdk, how should I name the method used for voting and for revoking a vote (really not an important question)
I currently thought of voteForOption(optionId: number) for voting

quartz kindle
#

i think the erlang/ETF specification uses both LE and BE for example

quartz kindle
neon leaf
#

what about revoking a vote

quartz kindle
#

just revoke, or revokeID

#

idk

frosty gale
#

performance is huge

quartz kindle
#

revokeVote

quartz kindle
#

is that its extremely slow to instantiate

neon leaf
#

idk how I just came up with this horrible name

quartz kindle
#

its literally faster to copy a 14kb buffer than to create a new DataView

quartz kindle
#

voteVote(vote: Vote): Vote

neon leaf
#

fr

#

okay now the most important question in the universe, where do I put my getPolls(page?: number, search?: string) method, following options:

import { API } from "asdgadsgasgfsigjwiasjgha"

const api = new API(...)

api.getPolls() // option 1
api.account.getPolls() // option 2
api.poll.getPolls() // option 3

// maybe something else?
quartz kindle
#

well idk what the entire structure looks like, so wherever makes more sense to you

#

are polls account specific? then put them in account

#

are there other poll related things in .poll? then put it there

neon leaf
#

polls are the same for every user, you can only vote if logged in

quartz kindle
#

if there is nothing else worth grouping it with, then put it in the root

neon leaf
#

alr, time to do frontend now

quartz kindle
#

good luck (i hate frontend)

neon leaf
#

||same||

#

not like I always love backend either though

quartz kindle
#

i'll have to teach 21 people about Angular on monday

#

i've never used Angular before

#

lma

#

o

neon leaf
#

sounds like fun

quartz kindle
#

i have no idea why, because they are already doing an angular course, but they said there are somethings they didnt get, and want someone else to explain it like they're 5

neon leaf
#

well youre good at that

#

so take that as a compliment

#

lmao

quartz kindle
#

i hope i'll manage

#

Angular is weird af

#

but i think i got the hang of the basics at least

tribal crow
#

It apparently isnt

#

Or

#

Could it be because Stock isnt the name of the document?

neon leaf
quartz kindle
tribal crow
#

Used another method

quartz kindle
#

👍

frosty gale
#

how much current and coils around an iron core would i need to make a decent strength electromagnet

#

i have a feeling the current coming from my arduino is no where near the amount i need

#

may need to order a mini power supply

#

capable of at least 2 amps ig but i dont know how much i need or if it even matters

#

i dont think i asked :(

deft wolf
#

Yea, discord mobile app is shit

#

I'm going to download some apk from the net because what happens in this application after these updates is just ridiculous

frosty gale
#

i havent updated the discord app in like 6 months and im happy

peak drum
deft wolf
#

I guess I should do that too

eternal osprey
#

look how cool this is

#

i connected the products to a js code, and you can then using fetch requests add and delete products.

vast condor
#

cool @eternal osprey

proud star
#

Hi

wheat mesa
#

This is the equation for a magnetic field strength of a solenoid, multiplied by N turns

#

u0 being the vacuum permeability constant (you can look it up), r being the radius of the loop (in meters), and I being the current (in amps)

sage bobcat
#

One message removed from a suspended account.

eternal osprey
#

It was mainly to learn js and idk I think I fully know the key concepts by know

brisk light
#
      throw err;
      ^

Error: Cannot find module '/home/user/Downloads/tetris-bot-main/index.js'. Please verify that the package.json has a valid "main" entry
  code: 'MODULE_NOT_FOUND',
  path: '/home/user/Downloads/tetris-bot-main/package.json',
  requestPath: '/home/user/Downloads/tetris-bot-main'
}

https://github.com/Richienb/tetris-bot

not my repo

#

help

quartz kindle
#

how are you running it?

brisk light
#

Should i change it to index.ts?

brisk light
quartz kindle
#

like did you download the entire repo and ran node .?

brisk light
#

Npm install
Npm run start

quartz kindle
#

add a new script to the package.json

#

"build": "tsc"

#

and try running node run build

civic scroll
#

node can't run typescript files

#

so you will need to compile them first to js

quartz kindle
#

then change the start script to "start": "node ./dist/index.js"

#

then should be able to use node run start

brisk light
#

Ok

civic scroll
#

wait

#

tim

#

tsc won't introduce dist

#

it will compile in place

quartz kindle
#

it wont use tsconfig?

#

tsconfig has /dist as the outdir

civic scroll
#

ah i forgot

quartz kindle
#

ye they have a tsconfig in the repo already with a /dist outdir

civic scroll
quartz kindle
#

so basically the scripts in package.json should look like this:

    "scripts": {
        "start": "node ./dist/index.js",
        "build": "tsc",
        "dev": "nodemon --watch source --ext ts,json --exec \"node --loader ts-node/esm ./source/index.ts\""
    },
#

then you can run ```shell
npm install
npm run build
npm run start

#

or you can run it with the dev script they already have in there, but it will auto-restart on every change

earnest phoenix
#

They really be using discord.js v13, ts-node/esm loader, and TypeScript v4

brisk light
#

And the repo has 5 errors

#

Wonderful

earnest phoenix
#

They should've also outlined those instructions troll

quartz kindle
#

its old code

#

so yeah

#

the repo is 2 years old with no updates

brisk light
# quartz kindle its old code

                                                Type 'NewsChannel' is missing the following properties from type 'VoiceChannel': editable, speakable, full, joinable, and 8 more.

1571     } & MessageComponentCollectorOptions<MappedInteractionTypes<Cached>[T]>;
#

what is mapped interaction

#

the code ancient

deft wolf
#

This is how it is with github code from a few years ago angeryBOYE

frosty gale
#

except i dont think i have a good enough iron core and i do need to buy insulated copper wire

#

so need to do that first

#

kinda wanna make a transformer now

#

ill add that to my future project list

quartz kindle
#

dafuq are you trying to do

#

a stargate?

sage bobcat
quartz kindle
night mantle
sage bobcat
#

One message removed from a suspended account.

#

One message removed from a suspended account.

dense flame
#

yikes

dense flame
#

please stop mentioning the channel yikes

frosty gale
#

please change it into a capital

tulip ledge
#

How is multi language usually done in bots? Are the strings moved to json files or something and then you use .replace on it?

dense flame
#

there ya go

frosty gale
#

and for each string you assign some kind of token like WELCOME_MESSAGE_DMS

#

so instead of something like message.send("welcome user!"); you would have some system which fetches the string for the desired language, something like message.send(strings["WELCOME_MESSAGE_DMS"].us);

#

a very rough idea amongst the millions of possible implementations

tulip ledge
#

yeah that's how I thought

#

but what if you have variables in the string that need to change?

#

like a username for example

#

do you use a token like {user} and then replace it?

frosty gale
#

yeah something like that, maybe a function which automatically does that and you provide an object to that function which replaces {var} with the actual values

#

it is messy and annoying though so many bots choose not to

tulip ledge
#

yeah thats why I was looking for a cleaner solution

frosty gale
#

would be cool if discord added automatic translations or something like that

tulip ledge
#

but I guess it's hard

queen needle
#

templating system, it does replace but in a nicer fashion per se

tulip ledge
frosty gale
#

actually

#

you could still use ${something} if you evaluated the string with eval

#

that would make the js engine actually compute and replace the variable with the actual variable

queen needle
#

but that presents security risks if it has user entered input

frosty gale
#

language files usually only contain strings from the developer themselves

#

if you want to be extra safe you could use sandbox ig

queen needle
earnest phoenix
tulip ledge
#

no

earnest phoenix
#
rustic nova
#

Imagine ads on npm pages

#

Cring

#

Gold sponsor

deft wolf
#

Sponsored by json

pale vessel
#

sponsored by jason

earnest phoenix
rustic nova
radiant kraken
#

make npm display an ad while its installing

#

ez stonks

lyric mountain
radiant kraken
civic scroll
#

@quartz kindle zig is js cousin

bronze owl
#

@bronze owl

plucky hearth
#

Hi

deft wolf
#

Yo

radiant kraken
quartz kindle
wicked pivot
#

I see that we can configure the shards. For you how many guilds max per shards would be optimal? (I have a bot that only uses command and button interactions)

deft wolf
#

Sharding is required at 2,5k guilds if I remember correctly

#

I guess 1k per shard should be good and it's default value

wicked pivot
#

ohh so I still have time I'm around 500

wicked pivot
deft wolf
#

You can read about it until then and think about which way you would like to go and which will suit your bot better

#

In discord.js, there are 3 ways to make sharding

wicked pivot
#

I already made the system thinking that it was around the 1k guilds that it happened and in case it happens I'm not lost

#
const { ShardingManager } = require('discord.js');

const manager = new ShardingManager('./index.js', { token: '...token...'});

manager.on('shardCreate', shard => console.log(`Launched shard ${shard.id}`));

manager.spawn();```

I did like this
deft wolf
#
The above code utilizes the discord.js sharding manager to spawn the recommended amount of shards for your bot. The recommended amount should be approximately 1,000 guilds per shard
#

You have answer on discord.js guide

wicked pivot
#

So everything is good ShrugAnimated