#development

1 messages · Page 2057 of 1

quartz kindle
#

what are you using for the server?

spark flint
#

NGINX

quartz kindle
#

only nginx or nginx -> node/whatever?

spark flint
#

nginx proxying Express.js

#

ah shit yeah

#

body-parser

quartz kindle
#

so yeah you need to raise the limit in both

spark flint
#

yeah my bad

#

forgot about that KEK

wheat mesa
#

so uh

#

I have GameObjects stored in the components field as such in my main struct: ```rs
pub struct Simulator<'a> {
fps: u32,
components: Vec<Box<dyn GameObject>>,
ctx: &'a Sdl,
canvas: Canvas<Window>,
}

#

And then I add them kinda like this: ```rs
let mut hollow_box = HollowBox::new(
0,
0,
20,
20,
Some(50)
);
self.components.push(Box::new(hollow_box));

#

Which works fine, but the problem arises because the vector is taking ownership of the gameobject

#

when I want to be able to use hollow_box below that

#

For example when I want to add a force on a keypress: ```rs
Event::KeyDown {
keycode: Some(Keycode::Space),
..
} => {
hollow_box.add_force_angle(150.0, 45.0);
}

#

(Formatting got weird)

#

But I can't use it because the vec already took ownership

#

Would this be the right time to use an Rc or something like that

#

Instead of a box?

#

Oh maybe I need to store them as a HashMap or something similar so I can borrow them from the struct when I need to do things to them

cinder patio
wheat mesa
#

problem is that they're listed as dyn GameObject but I need to access specific methods on the component

cinder patio
#

hmmm well

cinder patio
wheat mesa
#

Not everything is going to need that though

#

I might be able to add a default implementation

#

I feel like that's going to clutter GameObject with a lot of useless methods eventually

cinder patio
#

You could use an enum instead of dyn GameObject

enum GameObjectTypes {
    Box(...),
    ...
}
#

And keep them generalised

wheat mesa
#

I think I'm walking closer and closer towards falling into the ECS rabbit hole

feral aspen
#

Most of the servers are returning undefined?

cinder patio
wheat mesa
#

rendering and updating

cinder patio
#

shouldn't your framework be doing this

wheat mesa
#
    fn update(&mut self, dt: f32) -> Result<(), String> {
        for component in &mut self.components.values_mut() {
            component.render(&mut self.canvas)?;
            component.update(dt)?;
        }
        Ok(())
    }
#

I'm just using SDL2

cinder patio
#

so you're making your own game engine

wheat mesa
#

Attempting to make my own physics engine yes

cinder patio
#

is the Simulator struct a singleton?

wheat mesa
#

yes

cinder patio
#

if so you could just use a global vector to store everything. That actually doesn't solve any of ur issues actually why I am suggesting that

wheat mesa
#

Yeah the vector would still own it lol

cinder patio
#

Well use reference counting

#

easy way out

wheat mesa
#

But I need mutation :C

cinder patio
#

Then use RefCell

quartz kindle
cinder patio
#

Rc + RefCell

feral aspen
#
module.exports = async bot => {
    let activities = [`${(await bot.shard.fetchClientValues('guilds.cache.size').then(total => total.reduce((a, b) => a + b, 0))).toLocaleString()} servers!`, `${(await bot.shard.fetchClientValues('users.cache.size').then(total => total.reduce((a, b) => a + b, 0))).toLocaleString()} members!`, `attitudebot.com`], i = 0;
    setInterval(() => bot.user.setActivity(`${activities[i++ % activities.length]} || /help`, { type: 'PLAYING' }), 60000);
    
    bot.shard.broadcastEval(client => console.log('Shard ID', client.shard.ids[0], client.guilds.cache.map(guild => guild.name)));
    console.log(`Attitude is now online serving ${(await bot.shard.fetchClientValues('guilds.cache.size').then(total => total.reduce((a, b) => a + b, 0))).toLocaleString()} servers, ${(await bot.shard.fetchClientValues('users.cache.size').then(total => total.reduce((a, b) => a + b, 0))).toLocaleString()} members (${(await bot.shard.broadcastEval(client => client.guilds.cache.reduce((a, b) => a + b.memberCount, 0)).then(results => results.reduce((a, b) => a + b, 0))).toLocaleString()} members uncached) & ${(await bot.shard.fetchClientValues('channels.cache.size').then(total => total.reduce((a, b) => a + b, 0))).toLocaleString()} channels.`);
};
wheat mesa
cinder patio
#

yup

#

hmm

#

actually

#

RefCell needs the type to be sized I believe, try it

#

actually it doesn't

wheat mesa
#

Yeah I'm just updating my loop to work with those types rn, hold up

#

Yeah no still not gonna work unfortunately

#

I probably need to just come up with a different solution than the gameobject garbage, it's going to be too difficult to fight the borrow checker over it

#

Or, I could make a mess and just add a ton of methods to gameobject with default implementation lmao

#

And use a hashmap

#

I think I'm going to redesign into an ECS

cinder patio
#

I don't know how using a hashmap will solve your issue

#

the hashmap has ownership of the game object

cinder patio
#

Or even better, just make it so a component can check if a key is down in their update function

quartz kindle
sharp geyser
#
    let mut output = Vec::new();

    let mut streak = 0;
    for &item in arr {
        if item == 1 {
            streak += 1;
        } else if item == 0 && streak > 0 {
            output.push(streak);
            streak = 0;
        }
    }

    if streak > 0 {
        output.push(streak);
    }

    output

So what is this guy doing with the whole &item thing?

cinder patio
sharp geyser
#

I am still new to the idea of borrowing and ownership

cinder patio
#

so it'll be freed after the loop is over

#

so you won't be able to use it afterwards

sharp geyser
#

I see

sharp geyser
cinder patio
#

yes

sharp geyser
#

I also notice if you do for num in &numbers num is now &i32 which you can't compare against a normal int anymore can you?

#

so you can't do if num == 1

cinder patio
#

you can compare rust automatically dereferences them

sharp geyser
#

let me try one sec

#
error[E0277]: can't compare `&i32` with `{integer}`
 --> src\main.rs:9:16
  |
9 |         if num == 1 {
  |                ^^ no implementation for `&i32 == {integer}`
  |
  = help: the trait `PartialEq<{integer}>` is not implemented for `&i32`
#

Unless I am doing something wrong?

wheat mesa
#

why do for num in &numbers

cinder patio
#

interesting why it doesn't dereference it here

#

you can do num == &1

#

or you can do num.clone() == 1

wheat mesa
#

or *num == 1

cinder patio
#

that too, same as clone

sharp geyser
#

what does * do in rust?

cinder patio
#

(well actually copy but in this case clone == copy)

wheat mesa
#

gets the value of a reference

cinder patio
wheat mesa
sharp geyser
#

I see

wheat mesa
#

This was an absolutely fantastic video on state and such, currently I'm going down the OOP road of it which is very bad

sharp geyser
#

I keep learning more and more about rust every time I do these small code challenges

cinder patio
#

if the data type can be copied it copies it, it doesn't dereference it

wheat mesa
#

So I need to refactor to represent state better and closer to an ECS

wheat mesa
#

The more mistakes you make, the better you'll become at rust

sharp geyser
#

Yeeee

wheat mesa
#

I've rewritten my engine 3 times from the ground up already, but I've learned a shit ton along the way

sharp geyser
#

kek

#

you kind of just went straight into rust by making a math parser

#

so like

wheat mesa
#

rust has amazing pattern matching and I've done the parser thing 3 times before

#

(In other languages)

sharp geyser
#

Yea

#

You have the knowhow to implement something like that rather easily

wheat mesa
#

enums + match statements made my interpreter like 5 times shorter than it was in C#

sharp geyser
#

I do wanna kinda challenge myself a bit more tho with these rust challenges

wheat mesa
#

you can try rustlings

#

That's a good start for an overall introduction into a lot of features in rust

royal portal
#

give me ideas on how to stop memory leaks angeryBOYE

wheat mesa
#

use rust

royal portal
#

no

royal portal
#

is 2 gb good enough

#

i currently have 1 gb

#

and i only get memory leaks when someone ddos

sharp geyser
#

You could also not write code thatcauses memory leaks

spark flint
#

lol

royal portal
#

its in the package

sharp geyser
#

wait no my english today sucks I was right the first time

royal portal
#

no you are wrong

sharp geyser
royal portal
#

well i will

#

i need it for https

sharp geyser
#

what package are you using for https

royal portal
#
sharp geyser
#

👀

royal portal
#

so getting more ram is the solution

feral aspen
royal portal
#

misty say yes

sharp geyser
#

sure ig but i'd ask someone else

royal portal
#

@feral aspen what are your thoughts on this

sharp geyser
#

1gb should be fine for a small website

royal portal
#

as the founder and developer of the bot named attitude

#

its a proxy server

sharp geyser
#

oh

#

either way

royal portal
#

yes but if you are getting ddosed

#

you get more requests

#

more traffic

sharp geyser
#

yea

royal portal
wheat mesa
#

gotta love when websites don't know what a memory leak actually is

cinder patio
royal portal
#

then how else would i do it

cinder patio
#

you can use reverse proxy with nginx

split hazel
#

an automatic letsencrypt express handler

#

thats pretty awesome

cinder patio
#

using a reverse proxy allows you to handle DOSing a lot better than an express middleware can

royal portal
#

but am not sure if its that package causing that error

#

i cant find whats causing it

cinder patio
#

Is your server storing a lot of stuff in memory

royal portal
#

in the system?!?!1

#

or just that process

#

it does use a lot of memory in the process when there is a ddos

#

more than half the ram

#

and now its out of memory

split hazel
royal portal
#

could i just change the max listeners to infinity?!?!1

split hazel
#

not easy to fix them or even tell if its because of a module but generally you should make sure you remove every single reference to objects

#

node out of memory crashes arent very helpful would be nice if they provided an overview of whats using most memory

#

@earnest phoenix take notes

royal portal
#

it does say it happened in server.js

#

or maybe thats just the current process

earnest phoenix
royal portal
#

volty would increasing ram help stop the event listener error?!?!1

earnest phoenix
#

No, that warning is given out because something is constantly adding more event listeners to an event emitter in your program, that reaches the maximum set event listeners

split hazel
#

i hate snapshots and the chrome remove debugger

cinder patio
#

not necessarily event listeners

royal portal
#

maybe my memory went to like 500 mb because i logged every request during the ddos

split hazel
#

the chrome node debugger actually crashes node for me often

royal portal
#

its now at 100 mb without logging

earnest phoenix
# cinder patio not necessarily event listeners

Well yes, event listeners aren't always the cause of the program running out of memory, but I suppose it's the event listeners in this case because apparently burber didn't show the initial warning

royal portal
#

the full warning?!?!1

earnest phoenix
#

Yes

royal portal
split hazel
#

burbur pov:

app.get("/", () => {
  something.on("event", () => {});
});
quartz kindle
royal portal
#

not bad code

#

smh

quartz kindle
#

you literally add event listeners inside an event

#

meaning infinte event listeners

split hazel
#

💀 💀 💀 💀

quartz kindle
#

thats bad code

split hazel
royal portal
#

thats inside my routes

quartz kindle
#

you are adding .on("error") somewhere inside an existing event

#

show full code smh

royal portal
#

you mean that?!?!1

quartz kindle
#

well where did you put that???????

split hazel
#

bro just show the whole thing lmao

earnest phoenix
#

Nothing in that sparks something that is adding event listeners to an event emitter, not directly at least

quartz kindle
#

are you importing app in another file? show that other file

split hazel
#

that library is looking hella sus rn

earnest phoenix
#

It's either the proxy.web() call doing something suspicious there, or it's the greenlock-express library being the impostor

royal portal
quartz kindle
#

try running with node --trace-warnings

royal portal
#

node --trace-warnings server.js

#

thats what i will run

quartz kindle
#

yes

royal portal
#

now just stress testing the server

#

so i get the warning

split hazel
#

that library has a ton of nested event listeners so i can see its easy to fuck up

earnest phoenix
#

Goody ahh library

split hazel
#

that code is so spaghetti its not even funny

earnest phoenix
#

a

royal portal
split hazel
#

the library

royal portal
#

thought you were talking about mine

quartz kindle
#

no event listener warnings?

sharp geyser
#

God borrowing is still rather confusing to me in rust 😔

royal portal
#

thats all there is

#

all in the screenshot i sent

sharp geyser
#

nice email

#

time to email them

royal portal
#

no cryangeryBOYE

earnest phoenix
#

I think you've stress-tested it a bit too much before it was able to show the warnings

#

My guy runs on almost Nintendo 3DS RAM

royal portal
#

do i upgrade the ram?!?!1

#

lmao

earnest phoenix
#

1GB RAM is most likely enough for your program, but becomes a lot confusing with less RAM in case of debugging

royal portal
#

so do i upgrade to 2 gb?!?!1

earnest phoenix
#

I would say stress-test it again but stop at a early stage so it doesn't ran out of memory

#

Where I can ask question about launching bot on top.gg

royal portal
#

and how can i do that

split hazel
#

yeah its defo the library

royal portal
#

do i stop it at like X mb or just change the amount of seconds the attack runs

split hazel
#

the library assigns error listeners like theres no tomorrow

earnest phoenix
#

Yeah it's definitely the library

#

Use something else or implement your own I suppose

royal portal
#

someone rewrite it cryangeryBOYE

#

well the ram does go up

#

so does volty recommend upgrade

earnest phoenix
#

It wouldn't really ramp up if you use something else

royal portal
#

but if i still use that

earnest phoenix
#

Because your program seems simple enough

quartz kindle
#

ram it down its throat

earnest phoenix
#

Don't use that, because it's not written properly

royal portal
#

i dont know what to move to cryangeryBOYE

quartz kindle
#

nginx

royal portal
#

does that auto renew certs

quartz kindle
#

you can literally do the entire proxy thing in pure nginx, you dont even need node

#

you can autorenew with cerbot or acme.sh

split hazel
#

use certbot to generate a letsencrypt certificate then use this answer to start a https express server with it https://stackoverflow.com/a/70443344/11138133

#

tho i think you can also make nginx handle the https for you

#

if you proxy

royal portal
#

what if i use nginx and express

#

if thats possible

split hazel
#

your choice really

#

but it might be better to setup https on nginxs side

sturdy stratus
#

is there any way when someone votes for the bot my bot can know?

spark flint
#

i really wanna make a websocket module which can listen to topgg votes

earnest phoenix
spark flint
#

nope

#

thats for servers

spark flint
earnest phoenix
#

dam

sturdy stratus
spark flint
#

yeah

sturdy stratus
#

this is to show who voted?

split hazel
#

nodejs mfs if events didnt exist:

while (true) {
  if (event) {};
}
quartz kindle
boreal iron
#

What’s the definition of "not working"?

#

You just defined a function

#

Do you even call your "crazy" function?

sturdy stratus
#

What does it do?

boreal iron
#

Because you just defined some_crazy_function for whatever reason and you don’t call/execute the function

#

Why do you even define that?

earnest phoenix
sturdy stratus
#

and where do you publish?

earnest phoenix
#

What do you mean?

sturdy stratus
#

and where do you publish?

earnest phoenix
#

?

#

It posts your Discord bot's stats to Top.gg's API if that's what you're asking

boreal iron
#

I feel like he means where to put it in his code

royal portal
#

@earnest phoenix wait volty about that error, could i just leave it how it is and just let pm2 restart?!?!1

boreal iron
#

I told you way

split hazel
boreal iron
#

Don’t randomly ping people for no reason

royal portal
#

@boreal iron

earnest phoenix
royal portal
boreal iron
earnest phoenix
royal portal
#

inspect element!!1

#

omg

spark flint
boreal iron
#

If you don’t know what you did, you need to learn the basics of python before working with it

earnest phoenix
boreal iron
#

Because you defined a function for no reason and you don’t call/execute it

#

Copy and pasting usually doesn’t work

#

_They all must have won the green role in a lottery _

earnest phoenix
#

What the hell do you expect to achieve here?

# CREATES A NEW BOT OBJECT WITH A SPECIFIED PREFIX. IT CAN BE WHATEVER YOU WANT IT TO BE.
bot = commands.Bot(command_prefix="$")

# EXECUTES THE BOT WITH THE SPECIFIED TOKEN. TOKEN HAS BEEN REMOVED AND USED JUST AS AN EXAMPLE.
bot.run("the token")

bot = commands.Bot(command_prefix="$")



@bot.command(name="ping")
async def some_crazy_function_name(ctx):
    await ctx.channel.send("pong")
#

I'm not telling you to try that, that's your code

boreal iron
#

Execute you’re some_crazy_function_name

#

My gosh

#

lmao

earnest phoenix
#

You're logging in with the bot, but then reassigning the bot variable to a new bot instance

boreal iron
#

Executing doesn’t mean deleting

wheat mesa
#

KEKW he thought execute meant kill in this context

#

That’s actually pretty funny

boreal iron
#

I feel like you’re using the google translator or worse, bing translator

earnest phoenix
#

They're not telling you to delete that, you're declaring a function to be executed when that command is run, but that part is never even reached because the the bot instance you logged in with is destroyed, and you're creating a new one after logging it

#

And I would recommend setting up your commands before logging in

wheat mesa
#

(Also fake he doesn’t need to execute it, python is a little bit different because of annotations)

boreal iron
#

pepowot 🔫

earnest phoenix
#

Try removing the second

bot = commands.Bot(command_prefix="$")
#

My God, you should follow up on what I said

#

Also you shouldn't just outright copy code that you don't understand what it does

royal portal
#

gonna try that

#

even though its published 8 years ago

earnest phoenix
#

last published: 8 years ago

royal portal
#

as long as it works

#

then burbur happy

earnest phoenix
#

I wouldn't recommend trying it at all, it will definitely not work, probably has security issues or haven't adapted to newer versions of Express

royal portal
#

so i try nginx instead?!?!1

earnest phoenix
#

Yeah

royal portal
#

but could i have nginx and express

#

so nginx used for the https

earnest phoenix
#

You absolutely can, just read up on the documentation

boreal iron
#

Dude you need some basic knowledge before working with any programming language

#

Things don’t work by copy and pasting stuff

royal portal
#

that was easier than i thought

split hazel
#

8 years ago 💀

royal portal
#

but anyways

boreal iron
#

Nope, I don’t need to, thanks

royal portal
#

D:

boreal iron
#

:D

#

That’s part of getting into any programming language

#

Once again, once you know the basics of your program language you’re using, things will get a lot easier

#

Why would it be an event when you say you wanna make it a command?

#

You should probably read some not-outdated guides on how to start with python and a discord bot in python

royal portal
sage bobcat
#

One message removed from a suspended account.

wheat mesa
#

Postgres is really nice

#

You don’t need experience with SQL, you can use an ORM which would make your life easy

sharp geyser
#

What language do you use if I might ask?

#

an orm I recommend then is sequelize if you want something basic and if you are using typescript at all I highly suggest typeorm

wheat mesa
#

It’s essentially an abstraction of methods for you to interact with an SQL database in a way that doesn’t require you to manually write SQL (most of the time)

sharp geyser
#

sometimes you can write your own sql though if you wanted to

#

a lot of orms provide what is known as a query builder which allows you to use sql keywords and such

boreal iron
#

Even if it’s nice to build and use dynamic functions you can pass non, one or multiple parameters to, to insert or update data dynamically

#

But i somehow felt more comfortable writing the sql queries down where I need them and adjust them if needed

#

Instead of editing my functions which sometimes caused a rewrite and a different structure which also caused a rewrite of any line of code where I was calling the function

#

But you should somehow still build a wrapper which takes all sort of queries also prepared statements for example and which handles errors etc

#

Without the need to use multiple functions for queries, either it’s insert, update … etc or prepared statements

#

many words but a short meaning

lament rock
#

I wrote my own query builder mainly for typings

earnest phoenix
#

I always get this Error when trying to get a json file to a variable:

SyntaxError: Unexpected end of JSON input

My code is:

const filePath = statistics.json
function updatedata() {

    var data = JSON.parse(fs.readFileSync(filePath))

    windows = data.win;
    mac = data.mac;
    linux = data.lin;
    discord = data.discord;
    total = windows + mac + linux + discord;

    datad = new MessageEmbed()
        .setColor('#0099ff')
        .setTitle('Statistics')
        .setDescription('Total: ' + total + '\nWindows: ' + windows + '\nMac: ' + mac + '\nLinux: ' + linux + '\nDiscord: ' + discord)
        .setTimestamp()

    client.channels.cache.get('XXX').send(datad);
}

can anyone help?

bright hornet
#

I was trying to create a mini rpg game but it loops forever and ignore the collection, I was using recursive function, What should i change to not ignore the collection?
https://sourceb.in/00dYJGkujC

lyric mountain
#

Second, your entire setDescription can be replaced with an interpolated string

#

Third, did you check what is being read?

quartz kindle
#

you want to wait for the collector before the fights() function?

bright hornet
bright hornet
quartz kindle
#

the only way is to wrap the collector in a promise and resolve the promise when the collector "end" event fires

#

but from looking at your code you shouldnt even be using collectors in the first place, since you're only collecting 1 message

#

just use channel.awaitMessages()

lyric mountain
#

I would make the entire game run inside a single collector, that way you don't need to re-run the command again and again for each action

bright hornet
quartz kindle
#

if you want to go the callback hell route, yes, put all the code that is supposed to be run after the collector inside a collector.on("end", () => {....}) event

bright hornet
#

i see isee, gonna try it thanks for the tips

hidden gorge
wheat mesa
#

I think the error is really obvious...

#

Your code you posted has literally nothing to do with the error

#

You need to actually read the error

hidden gorge
#

my friend sent me the code

wheat mesa
#

You cannot keep copy pasting code without understanding it

hidden gorge
#

it’s his bot

wheat mesa
#

Read the error and tell me what you think it means

hidden gorge
#

i’m helping him

wheat mesa
earnest phoenix
#

Does anyone know a text to image api that just takes text and returns an image url?

wheat mesa
#

Depends on what you're looking for

#

Like just the text as an image..?

earnest phoenix
#

Yeah

#

not like with ai

#

just the text

wheat mesa
#

Not sure, thought I found one for a second but turned out to be an ai thing

pale vessel
wheat mesa
#

It's probably difficult to search for something like that given the hype surrounding ai art rn

earnest phoenix
#

thank you

earnest phoenix
#

Yeah xD

wheat mesa
#

checks out

#

lol

earnest phoenix
#

thanks

pale vessel
desert sable
#

Hello. I made a bot that handles NS*W categories like NS*W channels. Basically it works like if they are already official. It does not contain any NS*W content. It just toggles some channel properties. (it is an utility bot)

I already submitted the bot and it didn't get accepted. Is there any way to censor some text or anything to make it get accepted?

wheat mesa
#

it's because of your bot page

desert sable
#

i know

wheat mesa
#

You need to not mention anything about NSFW in your bot page

desert sable
#

does it get accepted if i put* everywhere?

wheat mesa
#

You cannot mention NSFW in your page

desert sable
#

ok thanks
i am unfortunately forced to use another bot list website

wheat mesa
#

Why's that?

ancient nova
#

so if he can't mention any nsfw then it's kinda missing the point of advertising the bots features

wheat mesa
#

I guess so

ancient nova
#

happy bday btw

wheat mesa
#

ty

desert sable
#

quick question: can i recover the bot's description after it has been declined?

ancient nova
#

at least that was the case for me

desert sable
ancient nova
#

just copy the description and close the site

desert sable
#

where is the reapply button
sorry for all of these questions

ancient nova
#

just try adding the bot again, there is no button for that

desert sable
#

ok thanks

#

for all

desert sable
bright hornet
#

So I was trying to figure it out on how to bring back on the first callback when the content does not the proper answer? Like yes and no

https://sourceb.in/U8UANcf4Nv

fathom sonnet
#

guys, how can I create role with djs?

#

and also, how can i check if role with same name exist on server

#

ok i realized...

earnest phoenix
#

hey. how do i make my bot see and reply to commands in voice channel chats

fathom sonnet
#

i think it should work same as in the normal chat, im not sure?

#

ok new Question: Can I use if() statement to get choices in slash commands?

like: ```js
if(interaction.choice === "30") {
// Do Something
}

fervent moss
#

How to resize thumbnail?

sharp geyser
#

I don't think you can

#

Unless you were to use a bigger sized image but iirc that even has limits

fathom sonnet
#

so I get this error when i try to execute my timeout command:
and here is part of the code where error happen

#

so "remove" is undefined, so that mean that .roles dosent exist?

#

why that happens?

earnest phoenix
#

user isnt wnat you want most likely

#

@fathom sonnet

fathom sonnet
#

ahh so i think i know how to fix it

earnest phoenix
#

if its User Structure, that itself doesnt have .roles

#

only Member Structure does.

astral halo
#

hello, is there anyone who used azure sql vm?

#

and is it a product that i can use if i want to have an sql database and also do things with it on a virtual machine?

fathom sonnet
#

ok so I resolved that problem, but...how can I assign role that I created to the memebr?

earnest phoenix
#

roles.create should return the Role Object.

#

so you can reassignment MutedRole to roles.create

#

and then your code should work

#

or do its intended purpsoe

fathom sonnet
#

bcz that wil lthrow err

earnest phoenix
#

variable reassignment

#

MutedRole = interactions.guild.roles.create({

fathom sonnet
#

ahhh

#

tnx

#

lemme try

#

yep...still same err

earnest phoenix
#

do

fathom sonnet
#

ok lemme try

#

same...but... on roles.remove()

earnest phoenix
#

are you deleting the role each time you test?

fathom sonnet
#

nope, it dosent even look like it is created

#

also, It need to check everytime of role exist on server, if not then it will create new one, if yes, it will just add it to member

earnest phoenix
#

can you repost the current code you have

fathom sonnet
#

second

#
const { SlashCommandBuilder } = require('@discordjs/builders')
const { MessageEmbed } = require('discord.js')
const Schema = require('../../models/timeout-schema')

module.exports = {
    data: new SlashCommandBuilder()
    .setName('timeout')
    .setDescription('Timeout a user for a set amount of time')
    .addUserOption(option =>
        option.setName('user')
            .setDescription('The user to timeout')
            .setRequired(true)
    )
    .addStringOption(option =>
        option
            .setName('duration')
            .setDescription('The amount of time to timeout the user for')
            .setRequired(true)
            .addChoices(
                { name: '30 minutes', value: "30minutes" },
                { name: '1 hour', value: "1hour" },
                { name: '24 hours', value: "24hours" },
                { name: '1 week', value: "7week" },
                { name: '1 month', value: "1month" },
            )
    )
    .addStringOption(option =>
        option
            .setName('reason')
            .setDescription('The reason for the timeout')
            .setRequired(true)

    ),
    async execute(interaction, client) {
        try {

            if(!interaction.member.permissions.has('DEAFEN_MEMBERS')) {
                interaction.reply('You are not allowed to use this command!!')
                return 
            }

            const user = interaction.options.getUser('user')
            const member = interaction.guild.members.cache.get(user.id) || await interaction.guild.members.fetch(user.id).cache                
            const time = interaction.options.getNumber('time')
            const reason = interaction.options.getString('reason')
            let MutedRole = interaction.guild.roles.cache.find(role => role.name === 'Timeouted');
            
            
            
            let embed = new MessageEmbed() // embed for the timeout
                .setTitle('Timeout')
                .setDescription('You have been timed out for **' + time + '\n**Reason: ** ' + reason + '**')
                .setColor('#F66969')
                .setTimestamp()
                user.send({embeds: [embed]})


            if(!MutedRole) {
                MutedRole = interaction.guild.roles.create({
                    data: {
                        name: 'Timeouted',
                        color: '#000000',
                        permissions: [
                            'VIEW_CHANNEL'
                        ]

                    }
                })
            }
            else {
                member.roles.add(MutedRole.id)
            }
            
           /*
            setTimeout(() => {
                member.roles.remove(MutedRole.id)
            }, time)
           */

            Schema.findOne({ Guild: interaction.guild.id }, (err, data) => {
                
                if(data) {
                    data.User = user.id,
                    data.Time = time
                    data.Reason = reason
                    data.save()
                }
                else {
                    new Schema({
                        Guild:  interaction.guild.id,
                        User: user.id,
                        Time: time,
                        Reason: reason,
                    }).save()
                }

                let embed = new MessageEmbed()
                .setTitle('User Timeouted')
                .setDescription(`${user.username} has been timeouted for **${time}**.
**Reason**: ${reason}`)
                .setColor('#A7FFBE')
                .setTimestamp()
                .setFooter({ text: `${interaction.member}` })
                interaction.channel.send({embeds: [embed]})


            }) // end of Schema

        }
        catch(err) {
            console.log(err)
        }
    }

}
#

this is basicly whole file

#

and here is part for role... ```js
const user = interaction.options.getUser('user')
const member = interaction.guild.members.cache.get(user.id) || await interaction.guild.members.fetch(user.id).cache
const time = interaction.options.getNumber('time')
const reason = interaction.options.getString('reason')
let MutedRole = interaction.guild.roles.cache.find(role => role.name === 'Timeouted');

        let embed = new MessageEmbed() // embed for the timeout
            .setTitle('Timeout')
            .setDescription('You have been timed out for **' + time + '\n**Reason: ** ' + reason + '**')
            .setColor('#F66969')
            .setTimestamp()
            user.send({embeds: [embed]})


        if(!MutedRole) {
            MutedRole = interaction.guild.roles.create({
                data: {
                    name: 'Timeouted',
                    color: '#000000',
                    permissions: [
                        'VIEW_CHANNEL'
                    ]

                }
            })
        }
        else {
            member.roles.add(MutedRole.id)
        }
        
       /*
        setTimeout(() => {
            member.roles.remove(MutedRole.id)
        }, time)
       */
#

after i removed timeout

#

i think it should work...THEN

earnest phoenix
#

thats so weird.

fathom sonnet
#

ok...new role is created, BUT, it have default name new role

#

and it didnt even assigned it

earnest phoenix
#

oooh that makes more sense.

#

roles.create is following a different format

#

than what you do

#

peretty sure you dont need the: data: { on roles.create

fathom sonnet
#

ok ok, progress

#

role created, now...hmmm

#

it dosent assign...

#

...I think i know what i can try

#

ok, it didnt created new role, it assigned role to memebr, and i still have this

#

xd

earnest phoenix
#

you dont do

#

interaction.reply

#

anywhere

fathom sonnet
#

yep

#

i added it

#

now only thing left to be done is: to get choices from option

fathom sonnet
#

ah nvm fixed it

fathom sonnet
#

sooo i changed code a little bit and i got this...
Here is my whole code: ```js
const { SlashCommandBuilder } = require('@discordjs/builders')
const { MessageEmbed } = require('discord.js')
const Schema = require('../../models/timeout-schema')

module.exports = {
data: new SlashCommandBuilder()
.setName('timeout')
.setDescription('Timeout a user for a set amount of time')
.addUserOption(option =>
option.setName('user')
.setDescription('The user to timeout')
.setRequired(true)
)
.addStringOption(option =>
option
.setName('duration')
.setDescription('Duration of the timeout (In Minutes) ')
.setRequired(true)
)
.addStringOption(option =>
option
.setName('reason')
.setDescription('The reason for the timeout')
.setRequired(false)

),
async execute(interaction, client) {
    try {

        if(!interaction.member.permissions.has('DEAFEN_MEMBERS')) {
            interaction.reply('You are not allowed to use this command!!')
            return 
        }

        let user = interaction.options.getUser('user')
        let member = interaction.guild.members.cache.get(user.id) || await interaction.guild.members.fetch(user.id).cache                
        let duration = Number(interaction.options.getString('duration'))
        let reason = interaction.options.getString('reason')
        if(!reason) reason = "No reason given"
        let MutedRole = interaction.guild.roles.cache.find(role => role.name === 'Timeouted');
        
        // need to get choices from option
        
        
            let embed = new MessageEmbed()
            .setTitle('Timeout')
            .setDescription('You have been timed out for **' + duration + ' minutes.' + '\n**Reason: ** ' + reason + '**')
            .setColor('#F66969')
            .setTimestamp()
            user.send({embeds: [embed]})


            if(!MutedRole) {
                MutedRole = interaction.guild.roles.create({
                    
                        name: 'Timeouted',
                        color: '#000000',
                        permissions: [
                            'VIEW_CHANNEL'
                        ]

                    
                })
            }


            if(member.roles.cache.has(MutedRole.id)) {
                return interaction.reply('This member is already timed out')
            }
            else {

            member.roles.add(MutedRole)
            member.timeout(duration, reason)

            embed = new MessageEmbed()
            .setTitle('User Timeouted')
            .setDescription(`${user.username} has been timeouted for **${duration}** minutes.

Reason: ${reason}`)
.setColor('#A7FFBE')
.setTimestamp()
interaction.channel.send({embeds: [embed]})

            setTimeout(() => {
                member.roles.remove(MutedRole)
            }, duration)
        }





    
        



        Schema.findOne({ Guild: interaction.guild.id }, (err, data) => {
            
            if(data) {
                data.User = member,
                data.Duration = duration
                data.Reason = reason
                data.save()

            }
            else {
                new Schema({
                    Guild:  interaction.guild.id,
                    User: member,
                    Duration: duration,
                    Reason: reason,
                }).save()

            }
        })
    } catch(err) {
            console.log(err)}
}

}

#

so i saw that i can use member.timeout() to timeout members so I used that

#

in brackets i passed duration and reason

#
 setTimeout(() => {
                    member.roles.remove(MutedRole)
                }, duration)
``` should remove muted role after time that has been passed inside duration
#
if(member.roles.cache.has(MutedRole.id)) {
                    return interaction.reply('This member is already timed out')
                }
``` this should check if user alredy have this role (if it is alredy muted)
#
 member.roles.add(MutedRole)
                member.timeout(duration, reason)
``` bot give role to the user and then time out him
dry imp
#

{ name: '1 week', value: "7week" },
interesting...

fathom sonnet
#

i deleted that...cuz there is easier reason

spark flint
#
const EventEmitter = require('events');
class VoteWatcher extends EventEmitter {
    constructor(apiKey) {
        // code
        VoteWatcher.emit("vote", data)
        //code
    }
    
}```
pale vessel
#

why emit an event inside the constructor?

#

if you want to emit, use super() and this.emit()

spark flint
#

ah ok

#

awesome it worked

fathom sonnet
#

is there a way to check if member on the server is muted, if I dont use roles for mutes?

spark flint
#

you can check for timeout

boreal iron
#

You will most likely need to fetch the audit logs

spark flint
#

<guildMember>.communicationDisabledUntilTimestamp

#

if it doesn't return null, they're timedout

boreal iron
#

muted and timeouts are different things

spark flint
#

if I dont use roles for mutes?

boreal iron
#

Also I don’t see how somebody should effectively be muted without roles

#

(without using timeouts)

#

How would you overwrite his permissions in the channels to prevent him from sending a message?

#

You can’t.

earnest phoenix
#

Needing some help with my manifest.json file for my chrome extension

#

{
    "manifest_version": 3,
    "name": "Test Extension",
    "version": "1.3",
    "icons": {"128": "images/logo128.png"},
    "description": "description.",
    "background": {
        "service_worker": "page.js"
    },
    "content_scripts": [
        {
            "matches": [
                "https://www.facebook.com/*",
                "https://www.twitter.com/*",
                "https://www.instagram.com/*",
                "<all_urls>"
            ],
            "js": [
                "content.js"
             ],
            "run_at": "document_end",
            
            "all_frames": true
        }
    ],

    "content_security_policy": {
        "extension_pages": "script-src 'self' https://ajax.googleapis.com; object-src 'self'"
       },




    "action": {
        "browser_style": true,
        "default_icon": {
          "16": "images/logo.png"
        },
        "default_title": "tester",
        "default_popup": "popup.html",
        "theme_icons": [{
          "light": "images/logo.png",
          "size": 16
        }, {
          "light": "images/logo64.png",
          "size": 64
        }]
      },








    "options_ui":{
        "page": "options.html"
    },

    "permissions": [
        "storage",
        "unlimitedStorage",
        "tabs"
       ],

       "host_permissions": [
        "https://ajax.googleapis.com/"
       ],

    "incognito": "split"
 }```
#

That's the file but my error is : 'content_security_policy.extension_pages': Insecure CSP value "https://ajax.googleapis.com" in directive 'script-src'. Could not load manifest.

eternal solar
#

how can i make fetch to work infinite times? as long as bot is alive

#

i tried making an infinite loop but it didn't work on discord.js

boreal iron
#

You will have to respect the rate limit in order to fetch data continuously

#

But I doubt it takes long until you get banned from using the API if you only fetch data

eternal solar
#

im using yt api

boreal iron
#

You may wanna provide more details when asking a question

#

What data do you wanna fetch?

eternal solar
#

someone's yt channel data

#

his yt videos

quartz kindle
#

explain what you want to do, show code examples

feral aspen
#

What are the prerequisites to make a dashboard for a discord bot?

sharp geyser
#

Have a bot

#

Also know how to interact with oauth2

feral aspen
#

Continue?

sharp geyser
#

I mean those are the biggest ones

#

Once you have oauth2 you can do virtually anything those other dashboards do with discord related stuff

#

Like getting the users guilds to add a bot to, getting their username, avatar, etc

quartz kindle
#

know the difference between backend and frontend

#

knowing full stack development

lyric mountain
#

learning how to setup websockets

quartz kindle
#

you can do without websockets, depending on your needs

feral aspen
#

Ahh, web sockets, lemme search that.

lyric mountain
boreal iron
#

Why desync? Save all your personal settings in your database the bot also uses

quartz kindle
#

depends on what they want to do with their dashboards

feral aspen
#

Uhh, just explanation on what you mean with desync? A scenario, like, please.

quartz kindle
#

not all dashboards have live updates and shit

boreal iron
#

What’s the sense of interact with your bot directly via sockets and the bot stores the settings you set in your database

#

One step less

boreal iron
#

You fetch your data on request when loading the site

lyric mountain
feral aspen
#

What does websockets do exactly?

boreal iron
#

Not any data has to be available in a cache at any time

quartz kindle
#

without reloading the website

feral aspen
#

Ohh, that's websockets??

lyric mountain
#

like a tether or smth

#

that way you can receive events without sending requests

#

basically what happens with bots <--> discord

feral aspen
boreal iron
#

Absolutely unnecessary but okay

feral aspen
#

I mean, I know most websites use "websockets".

quartz kindle
#

the main difference between websockets and ajax, is that all ajax updates have to be initiated by the user, ie, you cannot receive an update from your server if you dont request the update from the browser of have the browser request for updates every x time
with websockets the server can send you stuff and trigger updates in the browser without the user doing anything

lament rock
#

websockets are still technically a request, just the tcp socket isn't closed once the initial data is finished transferring

feral aspen
#

Fair enough, fair enough. So how does it work, is it some sort of add-in code which functions or do you need to follow such documentations?

quartz kindle
#

there is a websocket built into the browser

#

you need a websocket server on your server

feral aspen
#

As I'm currently looking for a simple video idea on getting started with Discord.JS dashboards to get the main idea of trying to use a websocket server on my server.

lyric mountain
#

it doesn't really matter what lib u use for the bot

feral aspen
quartz kindle
#

wherever you website is going to be hosted

near stratus
lament rock
#

If you're trying to make your own client/server for backend, you need a ws library installed or use the sockets attached to your req you send/receive and follow the websocket specification

quartz kindle
#

also keep in mind that not all websocket libs are interchangeable

#

for example ws is not 100% compatible with browser websocket

boreal iron
#

Or simply build a dashboard without websockets and request your personal settings from your database once the user loads the website

#

Instead of over complicating things

lament rock
#

Polling is a bad idea for frequently changing data

#

but not the worst idea

#

websockets can have more overhead

near stratus
lament rock
#

Depends on the dashboard

boreal iron
lament rock
#

I allow users to view music queues in realtime on my bot's dashboard and that requires websockets

near stratus
feral aspen
#

Alright, for now I have a web-hosting plan.
And instead of using the file manager in the plesk to host my website, I want to use a VPS.

I will be able to achieve so by changing my DNS records, by the looks of it.

boreal iron
#

I feel like he simply wants to show some personal settings user can set for their guilds

feral aspen
#

I can still host the website on the same VPS the bot is hosted in, I believe.

lament rock
near stratus
#

I got a better idea
Just ask him

boreal iron
#

Eww

near stratus
#

@feral aspen What functions do you need for that bot dashboard ?

feral aspen
#

Functions? What do you mean "functions"?

boreal iron
#

Features

near stratus
lament rock
#

What do you wanna do with it

feral aspen
#

I mean, for now, I just want to set it up by at least having it to show the server count and the member count on the website.

boreal iron
#

Just let the user set specific settings of your bot in their guild?

#

One time

quartz kindle
feral aspen
lament rock
#

Websockets are an option, but might be overkill

quartz kindle
#

i mean, you first decide if you want that or not, so you can decide if you need websockets or not

lament rock
#

I mentioned they have more overhead than polling in certain situations

feral aspen
#

I mean, I want to use web-sockets, yes.

near stratus
quartz kindle
#

but you want to use them because you need them or because they sound fancy?

feral aspen
quartz kindle
#

lmao

#

polling = requesting an update every x time

#

instead of websocket

boreal iron
#

Simply update the data every 15 mins for example

#

Nobody needs live data

feral aspen
boreal iron
#

Not for something unnecessary like a bot

feral aspen
#

Other than that, I want to make the dashboard to, for example, change the prefix of the server we're configuring.

In addition to the checks I'll have to program, such as:

  • Making sure the bot is in the server.
  • You logged in.
  • etc.
near stratus
boreal iron
#

Query your database to get the current settings like the prefix, then push the changes to your database once the user edits it

feral aspen
#

However, not sure what "polling" is.

near stratus
feral aspen
#

Aha.

boreal iron
near stratus
boreal iron
#

It’s literally exact the same like updating your guild count on topgg

feral aspen
#

Ohh, fair enough. 👍

boreal iron
#

While you can update it like every few seconds the website pulls the data every hour from the database

#

Live stats are simply an unnecessary resource waste

#

For something unnecessary like a discord bot

feral aspen
boreal iron
#

Over complicating stuff especially if you start building stuff to get experienced isn’t really needed

#

But yeah, just my opinion

feral aspen
#

Alright, for sure. I'll just need to build the files for now and know what I'm doing.

boreal iron
#

Yes, knowing what you’re doing will help you a lot

feral aspen
#

Also, should I use next.js, express.js?

lament rock
#

I went for pain and did no middleware

#

middleware shouldn't be as bloated as some of them are

#

realistically, it should just be some utility stuff like providing path and query string

#

bc http server doesn't give that to you straight up

quartz kindle
#

raw http > *

wheat mesa
#

does anyone know how to implement a generational index

#

(as simply as possible preferably)

#

I got some boilerplate from online, but I have no idea if the methods I implemented are correct (especially allocate) ```rs
#[derive(Eq, PartialEq)]
struct GenerationalIndex {
index: usize,
generation: u64,
}

impl GenerationalIndex {
pub fn new(index: usize, generation: u64) -> Self {
GenerationalIndex { index, generation }
}

pub fn index(&self) -> usize {
    self.index
}

}

#[derive(Debug)]
struct AllocatorEntry {
is_live: bool,
generation: u64,
}

impl AllocatorEntry {
pub fn new(is_live: bool, generation: u64) -> Self {
AllocatorEntry { is_live, generation }
}
}

#[derive(Debug)]
struct GenerationalIndexAllocator {
entries: Vec<AllocatorEntry>,
free: Vec<usize>,
}

impl GenerationalIndexAllocator {
pub fn new() -> Self {
GenerationalIndexAllocator { entries: Vec::new(), free: Vec::new() }
}
pub fn allocate(&mut self) -> GenerationalIndex {
if self.free.is_empty() {
self.entries.push(AllocatorEntry::new(false, 0));
GenerationalIndex::new(self.entries.len() - 1, 0)
} else {
// fix
GenerationalIndex::new(0, 0)
}
}

pub fn deallocate(&mut self, index: GenerationalIndex) -> bool {
    self.free.push(index.index);
    match self.entries.get(index.index) {
        Some(entry) => true,
        None => false
    }
}

pub fn is_live(&self, index: GenerationalIndex) -> bool {
    if self.free.contains(&index.index) {
        false
    } else {
        if let Some(entry) = self.entries.get(index.index) {
            return entry.is_live;
        }
        false
    }
}

}

struct ArrayEntry<T> {
value: T,
generation: u64,
}

struct GenerationalIndexArray<T>(Vec<Option<ArrayEntry<T>>>);

impl<T> GenerationalIndexArray<T> {
// pub fn set(&mut self, index: GenerationalIndex, )
}

#

I have no idea if any of that is right

fathom sonnet
#

HEY GUYS, so i making my "own verison" of reaction roles, and i ran onto this error, idk why it is happening, seriously.

This is ss of error and my code: Error appears ob line 57

wheat mesa
#

then GuildData.roles is undefined

fathom sonnet
earnest phoenix
#

Also making a reaction roles feature in your bot nowadays is pointless, Discord has made a built-in feature that does the same thing but much better, it's called "Role Prompts"

fathom sonnet
earnest phoenix
#

It's still experimental yes, but it's going to be released very soon

fathom sonnet
#

really loved when this happens xd

lyric mountain
#

tf is bson?

#

ah, mongo

earnest phoenix
#

Son of a b

stiff lynx
#

how can I create a category and inside that category create a channel?

#

creating a channel inside the category is with the parent id, right?

lyric mountain
#

creating a category returns a channel

earnest phoenix
lyric mountain
#

create a channel inside it

stiff lynx
#

discord.js

fathom sonnet
stiff lynx
#

first I would like to create che category

lyric mountain
#

just chain requests

stiff lynx
#

but idk how to create a category

earnest phoenix
earnest phoenix
#

Well GUILD_CATEGORY to be precise

fathom sonnet
lyric mountain
#

review ur data structure

wheat mesa
#

kuuhaku you're a data structures man right

lyric mountain
#

that means u have something like ```json
{
"something": {
"abc": {
"something": {
"abc": {
...
}
}
}
}
}

fathom sonnet
#

like array?

#

yes

lyric mountain
#

no, like a horse pulling a car that's pulling a horse that's pulling a car that's...you get it

#

you have a looped structure

fathom sonnet
#

ahh, got it

wheat mesa
#

It's like ```
A has B in it
B has A in it

#

doesn't make sense, because then there would be an infinite structure

lyric mountain
#

to visualize

fathom sonnet
#

hah this is what i have:

#

sooo, Guild: is string and saves guild id,
user is array and it should save multiple users

#

like u can have them more muted

lyric mountain
#

that shouldn't cause that issue

fathom sonnet
#

but duration, reasons are string

lyric mountain
#

you probably have something else

fathom sonnet
#

i think...if i cange them...

#

second

lyric mountain
#

like this

#

GuildData.roles has GuildData.roles

#

but GuildData.roles also has GuildData.roles

wheat mesa
#

eh that looks fine to me

#

spread syntax

lyric mountain
#

ah, true

#

nvm then

wheat mesa
#

either way here I'd be doing GuildData.roles.push(newRole) instead of that

fathom sonnet
#

that is for self roles

#

i deleted it

earnest phoenix
# lyric mountain like this

@fathom sonnet The first statement in that if statement is also wrong, because you're trying to reassign a constant variable

#

You've declared the roleData variable with the const variable, so it's constant but you're reassigning it there

wheat mesa
#

I am struggling with this ECS

#

:C

fathom sonnet
earnest phoenix
#

Oh

fathom sonnet
#

xd

#

this is basicly all for timeout.js ```js
const { SlashCommandBuilder } = require('@discordjs/builders')
const { MessageEmbed } = require('discord.js')
const Schema = require('../../models/timeout-schema')
// const { OWNER_ID } = require('../../config/cfg.json')

module.exports = {
data: new SlashCommandBuilder()
.setName('timeout')
.setDescription('Timeout a user for a set amount of time')
.addUserOption(option =>
option.setName('user')
.setDescription('The user to timeout')
.setRequired(true)
)
.addStringOption(option =>
option
.setName('duration')
.setDescription('Duration of the timeout (In Minutes) ')
.setRequired(true)
)
.addStringOption(option =>
option
.setName('reason')
.setDescription('The reason for the timeout')
.setRequired(false)

),
async execute(interaction, client) {
    try {

        if(!interaction.member.permissions.has('DEAFEN_MEMBERS') /*|| !interaction.member.id === OWNER_ID */) {
            interaction.reply('You are not allowed to use this command!!')
            return 
        }

        let user = interaction.options.getUser('user')
        let member = interaction.guild.members.cache.get(user.id) || await interaction.guild.members.fetch(user.id).cache                
        let duration = Number(interaction.options.getString('duration')) // Getting number from string
        let reason = interaction.options.getString('reason')
        if(!reason) reason = "No reason given" // If no reason is given, set it to "No reason given"
        
        let embed = new MessageEmbed()
        let embedPublic = new MessageEmbed()
        // need to get choices from option
            


            // DM Embed
            embed = new MessageEmbed()
            .setTitle('Timeout')
            .setDescription('You have been timed out for **' + duration + ' minutes.' + '\n**Reason: ** ' + reason + '**')
            .setThumbnail(member.user.avatarURL({dynamic: true, size: 512}))
            .setColor('#F66969')
            .setTimestamp()
            user.send({embeds: [embed]}).catch(() => { interaction.reply({ content: `I am unable to send message to ${user} because they either blocked communication with the BOT, or they have closed DM's.` }) })


            // Add the role to the user
            member.timeout(duration, reason)




            // remove role from user after duration has passed
            embedPublic = new MessageEmbed()
            .setTitle('User Timeouted')
            .setDescription(`${user.username} has been timeouted for **${duration}** minutes.
**Reason**: ${reason}`)
            .setColor('#A7FFBE')
            .setTimestamp()
            interaction.reply({embeds: [embed]})
            



        Schema.findOne({ Guild: interaction.guild.id }, (err, data) => {
            
            if(data) {
                data.User = member,
                data.Duration = duration
                data.Reason = reason
                data.save()

            }
            else {
                new Schema({
                    Guild:  interaction.guild.id,
                    User: member,
                    Duration: duration,
                    Reason: reason,
                }).save()

            }
        })

    } catch(err) {
            console.log(err)}
}

}

stiff lynx
#

how can I set the permissions for the category for only administrator?

earnest phoenix
stiff lynx
earnest phoenix
#

Yeah, it's recommended to rather save the ID and fetch it when needed, or save other information if necessary, not the whole instance

stiff lynx
#

let member = interaction.guild.members.cache.get(user.id) || await interaction.guild.members.fetch(user.id).cache

what is this?

#

y u cache before fetching?

#

and y are you doing both

#

fetch is more than enough

lyric mountain
#

he's probably checking if it's cached before attempting a fetch

earnest phoenix
#

The fetch() method checks for the cache first, so it's better to just call the fetch method

stiff lynx
#

there is a difference in the speed?

lyric mountain
#

if fetch didn't check the cache, yes, a huge one

stiff lynx
#

all is cached in discord.js lmao

fathom sonnet
stiff lynx
fathom sonnet
#

on any other cmd

earnest phoenix
#

It's actually wrong though, because you're accessing the property of a promise

fathom sonnet
#

soo to just fetch?

earnest phoenix
#
const member = await interaction.guild.members
  .fetch(user.id)
  .catch(() => null); // To handle the error if the member is not found.

Should be enough

stiff lynx
#
const action = await modal.guild.channels.create(`${nomeCategoria}`, {
                type: 'GUILD_CATEGORY',
                permissionOverwrites: [
                    {
                        id: modal.user.id,
                        allow: ["ADMINISTRATOR"],
                    }]
            })```

How can I properly set the permissions? never did that in my life, I want to set the category only for admins and the channels created for admins and the user that used the button (it is a ticket system)
earnest phoenix
stiff lynx
#

so not to everyone : js deny: [Permissions.FLAGS.EVERYONE],?

earnest phoenix
#

For that, you would need to set the id property to the guild ID, as the ID of the everyone role is the same as the guild ID

stiff lynx
#

REALLY? wow, that's cool

earnest phoenix
#

And for the permissions, set the deny property to an array that includes the VIEW_CHANNEL permission

fathom sonnet
#

i goona delete all of this dbs and start using excel as database

#

...

stiff lynx
lyric mountain
#

excel is a game engine not a database

earnest phoenix
stiff lynx
#

modal have the same properties of interaction

fathom sonnet
#

tnx

earnest phoenix
stiff lynx
stiff lynx
#

sorry for the how the code is invented, I wrote it from my phone 💀

earnest phoenix
#

Yeah that should work, just Id to id mmLol

lyric mountain
#

Id != id

stiff lynx
#

above is in the right way

winged linden
#

yo got a question, what should i do if i got rate limited

#

i have a bulkassign role, it got rate limited

#

bot still works but the it doesnt assign roles

earnest phoenix
#

All you can do is wait

winged linden
#

how much usually?

#

and whats the rate limit? much many can i send per second

earnest phoenix
#

Ratelimits all go away after a certain amount of time, it's better to assign the roles in-between timeouts so it doesn't get ratelimited

winged linden
lyric mountain
earnest phoenix
#

It would be better to assign roles in-between every 10 seconds or more, usually up to 1 minute just in case

#

But 20-30 seconds should also be fine

stiff lynx
#

the property in the channel creation for creating it in a category?

feral aspen
earnest phoenix
#

For the other option, you can follow the CategoryCreateChannelOptions hyperlink above it

earnest phoenix
# feral aspen I'm confused, they changed it from `await createConnection({})` to what? https:/...

Basically what they're telling you is that, currently the Connection class isn't actually a real connection, it's just a place where information is stored for other connections, and QueryRunner class is the real connection which is created by the createConnection() function, but in the future the Connection class will be renamed to DataSource to reflect what it actually is and what it is used for, and the QueryRunner class will be renamed to Connection, to reflect that it's the real connection, so the new real connections will be created with the create() method of the Connection (renamed QueryRunner) class in the future

feral aspen
#

Ohh, so if I would want to create a connection, it would be what, particularly?

#

QueryRunner.create()?

earnest phoenix
#

It would look something like this

import { Connection } from 'typeorm'; // Or whatever it's name is.

const connection = Connection.create(/* options */);
#

As the QueryRunner class will be renamed to Connection to make it less confusing and reflect what it actually is, as mentioned

earnest phoenix
civic hinge
#

Hey, so... Ive got some questions regarding permission checks...

Send message

Checks if the bot has the permission
if (message.guild.me.permissions.has("SEND_MESSAGES"))
Checks if it has permission for that channel
if (message.channel.permissionsFor(message.guild.me).has("SEND_MESSAGES"))
Are those correct/enough?

Managing roles

Checking if the bot can manage roles
if (message.member.guild.me.permissions.has("MANAGE_ROLES"))
Then after that I check to see its hierarchy and only if the bots role is higher will I add the role

Would that be enough to make sure roles are always able to be assigned if if has permissions and doesnt error out?

feral aspen
#

Since createConnection() wouldn't work, either.

earnest phoenix
earnest phoenix
feral aspen
#

It's deprecated.

earnest phoenix
#

I think they screwed up the way they're explaining how it'll be treated and what you should use

feral aspen
#

Yeah, unfortunately.

earnest phoenix
#

Where even are you reading that from?

#

It's not on TypeORM's README

civic hinge
earnest phoenix
#

That error usually occurs when the bot doesn't have access to a channel, settings tab, feature, or anything similar

#

I suppose in this case it's probably the channels, the bot also needs the VIEW_CHANNEL permission to view the channel in the first place

civic hinge
earnest phoenix
#

In that case yes, it's able to view the channel; if it's not because of the channels then it's caused by one of the others I mentioned

civic hinge
winged linden
#

what yall do to run the command slowly and assign roles slowly not to get rate limited

lyric mountain
#

sleep

wheat mesa
#

ECS is melting my brain

#

just wrote 314 lines of code, the render system works first try

#

But now I'm wondering how I'm meant to actually use the ECS

nimble cobalt
#

Ecs sucks , it happens with me too

wheat mesa
#

I'm trying my very best to avoid OOP type stuff

earnest phoenix
#

So I'm currently hosting my site and on the DNS records my Content on cloudfare is 35.186.245.55 for repl hosting but how do I change that so I can host it on vsc?

quartz kindle
earnest phoenix
#

well

#

putting it on vsc and then making it connect to the domain

#

then i host it on my vps

quartz kindle
earnest phoenix
#

alr thanks

quartz kindle
#

hence its recommended to go directly to vps

earnest phoenix
#

Yeah

quartz kindle
#

you can test your website on your pc without the domain

earnest phoenix
#

yeah

quartz kindle
#

just by going to localhost

earnest phoenix
#

yeah

sharp geyser
#

Unless you are talking about something else when creating a connection to your database

#
import { DataSource } from 'typeorm'

const datasource = new DataSource({
  host: blah
  user: blah
})

await datasource.initialize() // or initiate can't remember
earnest phoenix
#

I don't use TypeORM so better to tell that to the other guy asking it troll

sharp geyser
#

right

#

@feral aspen use this ^

#

Twas a message and someone deleted it :c

hidden gorge
#

what is GATEWAY_GUILD_MEMBERS Intent and GATEWAY_MESSAGE_CONTENT intent?

hidden gorge
#

thanks

quartz kindle
#

funny (atrocious) typescript/typechecking moments: js let resolver; const promise = new Promise(resolve => { resolver = resolve; }) resolver() // error using variable before assignment ```js
let resolver;
const promise = new Promise(resolve => {
resolver = resolve;
})
(() => resolver())() // works

sharp geyser
#

Makes sense

#

Although wouldn't that error since there is no semi after defining what promise is?

quartz kindle
#

yes it would lel

#

but ignoring that, both work fine in js

#

but for some reason ts doesnt see the variable defined if you use it directly

#

even tjough it is

#

but if you wrap it in something, then suddenly it sees the definition

sharp geyser
#

ts is weird like that, it doesn't recognize what it's new type is even after reassignment

#

I've had times where I had to cast what it should be after reassignment cause it still think it is it's original definition

quartz kindle
#

shit like this is why i hate ts

sharp geyser
#

I'm really hating rust rn mmLol

#

I am starting to think trying to make a parser is a bit too much for a beginner

#

even with a well displayed book on how to do it

quartz kindle
#

lel

#

im not even gonna start with rust

sharp geyser
#

I mean rust looks nice and I do really love it

#

But sometimes it's concepts can be a pain to wrap my head around

lament rock
#

something about not knowing the callback is called on the same loop

#

because if it wasn't called immediately, then that would error

sharp geyser
#

Borrowing and ownership was a circus for me

#

lifetimes also make virtually no sense to me

split hazel
#

rust mfs realizing you cant own something in a computer

sharp geyser
quartz kindle
#

user with root/admin account: I OWN YOU

sharp geyser
#

tim do you like cashews?

split hazel
#

now im trying to figure out why my diffie hellman exchange produces two completely different secrets

#

stupid database

#

stupid c++

quartz kindle
#

why are /tenor and /giphy not available on mobile dafuq

split hazel
#

stupid openssl

sharp geyser
quartz kindle
#

angery

sharp geyser
#

I was thinking of looking at C

#

but I am unsure if I wanna go down that rollercoaster yet

#

so far I think ima stick with rust for a while and see what I can accomplish

quartz kindle
#

make a bot in rust

#

and be ahead of the competition

split hazel
#

i would use c if it wasnt for the fact is has like no built in features

sharp geyser
#

I honestly could but I am not smart enough yet to do anything advance in rust

#

I haven't even interacted with dbs yet

sharp geyser
quartz kindle
#

love reinventing wheels

sharp geyser
#

isn't that what you do with C?

#

make everything yourself even if it has already been made

split hazel
#

i have a bunch of objects written in c for my os so I can use them but i dont know how reliable they are yet

#

so i only use them for my os

sharp geyser
#

you'll find out

#

when ur OS crashes

quartz kindle
#

os = operation speedy

sharp geyser
#

top secret shit tim how'd you know?

split hazel
sharp geyser
#

looks like we gotta take you out

split hazel
#

i also written a flexible array class

#

and no my os isnt dead i work on it all the time i just dont update the repo 💀

sharp geyser
#

looks rather dead

#

4 months since last commit

#

smh

split hazel
#

last change was like 4 days ago lol

#

if i worked on my os every day id go insane

sharp geyser
#

Isn't that what happened to TempleOS dood

split hazel
#

i still have a bug to fix

#

that guy was insane before he even made it

sharp geyser
#

@quartz kindle never answered my question on whether you like cashews

#

smh

quartz kindle
#

meh

#

i like cashew juice and cashew nuts, the fruit not so much

#

windows suffers a bsod, mac suffers a kernel panic, speedyos suffers an operation speedy

#

:^)

split hazel
sharp geyser
#

make bad code?

split hazel
#

no

#

make a linked list

quartz kindle
#

naisu

#

why cant they do it?

split hazel
#

btw i let copilot write a single function for me for the linked list and it completely fucked it up

#

i wasnt paying attention so i just went "ok"

#

even copilot cant make a linked list

quartz kindle
#

lel

split hazel
#

copilot absolutely sucks with c/c++/assembly

#

it cant even move a number into a register in assembly without fucking it up

winged linden
split hazel
#

ask discord to stop

quartz kindle
#

learning about typescript+jsdoc shenanigans

#

before (tons of type errors)

#

have to add extra variables to type cast stuff correctly

#

otherwise you have to do shit like (type bla (type unknown (value)))

sharp geyser
#

👀

#

can't you just give type to timeout and then add the values you need then set timer to timeout?

#

why make a new variable

quartz kindle
#

adding properties to existing objects is a pain

#

typescript first complains that property X does not exist in object Y

#

then you type X with & { props }

#

and it complains object Y cannot be assigned to type X with props because it lacks the new props

sharp geyser
#

tf

quartz kindle
#

ex ```js
type bla = Error
const myvar: bla = new Error()
myvar.code = 10 // error, type bla does not have prop "code"

type bla = Error & { code: number }
const myvar: bla = new Error() // error, Error object does not have prop "code"

#

one way to fix is type bla = Error & { code?: number } but i dont want code to be optional, because then i have to type guard it everywhere

#

another way is to do shit like const myvar: bla = new Error() as unknown as bla

#

but in jsdoc syntax it looks like hell

#

cannot simply do const myvar: bla = new Error() as bla because it errors again with "object Error cannot be assigned to bla because its missing property code"

sharp geyser
#

I mean one hacky way to do it is to override Error

quartz kindle
#

well yes, in some places i have a class that extends error

#

but i dont wanna to that for every single little thing

sharp geyser
#

I don't mean by extending it

quartz kindle
#

well i dont think jsdoc has that

#

The @override tag indicates that a symbol overrides a symbol with the same name in a parent class.

sharp geyser
#

Ah I see

quartz kindle
#

only works for stuff with the same name

sharp geyser
#

There's gotta be a better way to do it

split hazel
#

welcome to typescript

#

you spend more time trying to fix language issues rather than writing code

quartz kindle
#

yup

#

i switched type checking to strict (i thought i already had it on, turns out i didnt)

#

and i got 100+ errors

#

lmao

split hazel
#

a statically typed language running on a dynamically typed language just doesnt work well

quartz kindle
#

yeah

#

well im not using full typescript

#

im using type checked js with jsdoc

wheat mesa
#

I think ts is fine

#

if you're fighting the compiler a ton then you're either doing something obscure or doing something wrong

quartz kindle
#

i often do obscure things

split hazel
#

same

wheat mesa
#

for the average program ts is very helpful

#

dynamic typing is good in moderation imo

split hazel
#

you cant lie though ts limits the full potential of javascript

wheat mesa
#

because it's supposed to

quartz kindle
#

like taking variables out of their scopes, ie promise resolvers and http req/res objects

wheat mesa
#

that's the tradeoff

split hazel
#

whether its for the better or worse

wheat mesa
#

you sacrifice unsafe assumptions for a safer type system

#

for obscure/advanced things, sure, probably gets in the way. For things like react and any sort of API wrapper? A miracle

quartz kindle
#

typechecked js in action:

wheat mesa
#

I really want to write my own mini ECS but this is hard :C

quartz kindle
#

it doesnt look half bad and its still 100% js meaning it will run without compilation

#

and ts can still do strict typechecking on it

#

best of both worlds