#development

1 messages · Page 87 of 1

compact pier
#

What I had in my mind is like create 2 seperate app, for 2 different function, like query or mutation

quartz kindle
#

the main thing you have to think about is "if i run my app twice, and split the load evenly between the two, will it still work correctly?"

quartz kindle
#

but at some point, one of those microarchitecture components will require horizontal scaling

compact pier
#

that is a very importain step too, I think the both apps are working seperated, so they won't have issue

quartz kindle
#

so you will also have to answer the same question

compact pier
#

but should I build a microarchitecture from beginning, or I should just build a normal app?

quartz kindle
#

if you think your app will grow that much, you can start with microarchitecture from the beginning, otherwise dont bother

#

its simpler to just make your app horizontally scalable

compact pier
#

Well I think, if you build an app that uses microarchitecture, it would be good + in your cv :>

quartz kindle
#

i guess

compact pier
#

ahh

quartz kindle
#

lets say your app does a lot of things, involving routing, database read/write, authentication, and such

compact pier
#

but I still don't know, if you can host 2 different app that uses the same url

quartz kindle
#

a microarchitecture design would have different processes handle different things, but that also means lots of data being send across your internal network, which also introduces a strain

#

a "normal" design would have all of those things happen inside the same process, receive request, access db, authenticate, write something, respond

compact pier
#

yes, that is correct

quartz kindle
#

a horizontal scalable model would do exactly the same thing, but in a way that if you run that same process multiple times, it will still work

compact pier
#

"if you run that same process multiple times, it will still work", what do you mean by that?

#

like having 2 auth microservice? and it will still work?

quartz kindle
#

having 2 "normal" designed processes

compact pier
#

ah

#

but different function

quartz kindle
#

they have the same function

#

but do not interfere with each other, and both work standalone

#

thats basically what you need if you want to use kubernetes in the future for example

compact pier
#

oh, yeah makes sense

quartz kindle
#

so you can add/remove processes according to load without breaking anything

#

the main thing to take care of is, is your app stateful or stateless?

#

for example, if 1 user makes 2 requests

#

and each of those 2 requests end up in 2 different processes

#

are both processes able to fully respond without the knowledge of each other or the user's previous requests?

compact pier
#

I think kubernetes will handle the request to the correct service, by using "load balancer", if I remembered correctly

#

and let say if user use login function, it will call
load balancer -> login service -> database service

quartz kindle
#

yes, but that is still vertical scaling

compact pier
#

mhmm

quartz kindle
#

imagine you reach a point where you need load balancer -> 2 login services -> 2 database services

compact pier
#

it will works the same

quartz kindle
#

if designed correctly yes

compact pier
#

ok, so I will start read more about microarchitecture

#

thank you :D

quartz kindle
#

microarchitecture is good, but by itself it does not solve the problem of scalability

#

to actually solve scalability, the answer is horizontal design, both for microarchitecture or not

compact pier
quartz kindle
#

there are other ways of communicating

lyric mountain
quartz kindle
#

indeed

#

database replication is a pain, glad i never had to deal with that

hidden gorge
#

So im using await interaction.guild.members.ban(user);
How do I add a reason to the ban?

quartz kindle
hidden gorge
#

thanks tim

#

@quartz kindle Im more confused now

rustic nova
#

by adding the reason parameter to the function

hidden gorge
#

how do i add the reason in ban(user, [reason]?

quartz kindle
#

.ban(user, { reason: "abc" })

hidden gorge
#

expected ,

sharp geyser
#

huh

hidden gorge
#

fixed

sharp geyser
#

why would that possibly make sense

lyric mountain
#

docs aren't hard to understand, ur code editor will also show u what ur supposed to add

sharp geyser
#

unless he is using notepad ++

quartz kindle
#

in most docs, [abc] means abc is optional

hidden gorge
#

im using visual studios

lyric mountain
#

code, don't forget the word "code"

hidden gorge
#

thank you it works now

earnest phoenix
#

@lyric mountainhey can u help me

#

@sharp geyser

lyric mountain
#

u didn't ask anything

earnest phoenix
#

and giveaways

#

@lyric mountain

lyric mountain
#

can u stop pinging

#

and yes, invite tracker

quartz kindle
#

this server is for help with coding bots, not help with using existing bots

lyric mountain
#

oh wait, u want help abt the bot itself

#

then no, I cant help

hidden gorge
#

why does it show the id on my laptop but mentions the user on my ipad?

#

im using const user = interaction.options.getUser("user");

lyric mountain
#

titles cant have markdown

hidden gorge
#

it doesnt

#

oh

#

wait

#

im using ```js
.setTitle(${user} has been kicked.)

compact pier
#

You should use it in description

#

you can't mention in title

lyric mountain
#

yes, mention is markdown too

compact pier
#

you can display user's name, instead mention them

hidden gorge
#

fixed just add .tag to the ${user}

odd citrus
#

i used css

hidden gorge
#

how do i get a users status?

#

and add it into an embed

#
.setDescription(`${user} Joined ${interaction.guild.name} on ${user.joinedAt}. Account Created on ${user.createdAt}. User status: Soon...`)```
#

i want to replace soon... with the status of user

digital swan
#

Have you looked at the discord.js docs

hidden gorge
#

yes

#

makes no sense

digital swan
#

😱

hidden gorge
#

thanks

sharp geyser
#

Why did they move something like that to the guild member object

#

it makes more sense to put it on the user

hidden gorge
#

undefined

deft wolf
#

user.presence.status

hidden gorge
#

TypeError: Cannot read properties of undefined (reading 'status')

#

@deft wolf

deft wolf
#

Do you have an intent for presence?

sharp geyser
#

Don't forget if you dont have the presence intent you wont get any presence data

hidden gorge
#

yes

#

actually oops

#

i dont

sharp geyser
#

Also this intent is a priv intent so you gotta enable it in the bot dashboard

hidden gorge
#

what is the Name for the presence intent?

sharp geyser
hidden gorge
#

thanls

#

i added it and still TypeError: Cannot read properties of undefined (reading 'status')

sharp geyser
#

Show how you are doing it

hidden gorge
#

this is my intents btw const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildPresences] });

sharp geyser
#

ok how are you doing the other thing tho

hidden gorge
#

and the Line
js .setDescription(`${user} Joined ${interaction.guild.name} on ${user.joinedAt}. Account Created on ${user.createdAt}. User status: ${user.presence.status}`)

deft wolf
#

We mainly care about who this user is, how you get him

hidden gorge
#
module.exports = {
    data: new SlashCommandBuilder()
        .setName("user")
        .setDescription("User Info")
        .addUserOption(option =>
            option
              .setName("user")
              .setDescription("User to get info of")
              .setRequired(true)),
              
    async execute(interaction) {

        const user = interaction.options.getUser("user");
sharp geyser
#

So in the terms of discord.js presence is not a valid thing on user

#

you will have to convert that into a member object

#
import { Client, ClientOptions } from 'discord.js';

interface IAtomClientOptions {}

declare module 'discord.js' {
    interface Client {
        options: IAtomClientOptions | ClientOptions;
    }
}

export class AtomClient extends Client {}

So I was trying to find a way to just make the options prop that djs client normally has and merge my own option interface into it but I still run into an error of a type mismatch

#

is it not possible to do this?

#

I swear I did it at one point

#

I also tried using & instead of | same thing

digital swan
sharp geyser
#

Thats cause when you force fetch you essentially just get the raw user data

#

they dont parse it into a their own user object

wheat mesa
#

Something like that

sharp geyser
#
    constructor(token: string, options: IAtomClientOptions, djsOptions?: ClientOptions) {
        super(djsOptions ?? {} as ClientOptions);
        this.atomOptions = options
    }

this works yes

earnest phoenix
#

The reason you have to import everything from discord.js is because if you don't, then it won't declare everything else that already exists in the module

sharp geyser
#

cause by default if I pass options?: ClientOptions to super then it will complain that it could possibly be undefined

#

but I also don't wanna make it required to have to supply options to the client

#

Actually wait, they require you to supply intents now dont they, so this doesn't matter

sharp geyser
#

[class TestCommand extends Command]
if (importedCommand instanceof Command)
Yet this equates to false?

#

or am I misunderstanding

#

Does inheritance not mean it is an instanceof?

lyric mountain
#

it should

#

at least in java it does

sharp geyser
#

ye idk why its equating to false

lyric mountain
#

just to check real quick

sharp geyser
#
    public async addMultipleIn(path: string, options: { subdirectories?: boolean } = {}) {
        options = Object.assign({ subdirectories: true }, options);

        const files: Array<string> = await this._getFiles(path, options.subdirectories);

        for (let file of files) {
            if (!['js', 'ts'].includes(file.split('.')[1])) continue;

            const filepath = resolve(path, file);

            try {
                let importedCommand = require(filepath).default;

                console.log(importedCommand);

                if (importedCommand instanceof Command) {
                    this.components.set(importedCommand.id, importedCommand);
                    console.log(this.components);
                }
            } catch (e: any) {
                throw new Error(e);
            }
        }
    }

but cause of that this isn't being added to the collection

lyric mountain
lament rock
#

half a second to eval. Yikes

lyric mountain
#

that's cuz I didn't eval recently

#

so it had to start the compiler

lament rock
#

ah

lyric mountain
#

gets much faster with subsequent runs

sharp geyser
lyric mountain
#

Perhaps it's some js peculiarity

wheat mesa
lyric mountain
#

Also try logging importesCommand's class

#

See if it's what ur expecting to be

wheat mesa
#

I'm like 90% sure it's because what you're importing cannot be used with instanceof because you're comparing the class definition instead of an actual object instantiation

#

importing a file doesn't mean you instantiated an object of it yet

earnest phoenix
#

The instanceof operator will only return true if the value's prototype chain has that class anywhere, so there's a high chance you've done something that made it lose that prototype

#

The "prototype chain" may seem a bit vague here but this may be able to explain it:

class Foo {}
class Bar extends Foo {}

const bar = new Bar();

console.log(bar instanceof Bar); // true
console.log(bar instanceof Foo); // true, because class `Bar` extends class `Foo`
console.log(bar instanceof Object); // true, because classes have a prototype of Object internally 
lyric mountain
#

That's more vague lul

sharp geyser
#

I’m so fucking dumb thank you

hidden gorge
#

is it a good idea to go refresh my slash commands everytime i start my index.js?

solemn latch
#

if your bot gets restarted a lot youll possibly get ratelimited

hidden gorge
#

ValidationError: bans validation failed: Active: Cast to Boolean failed for value "[Function: Boolean]" (type function) at path "Active" because of "CastError"

Command Saving Data

data = new db({Guild: String, Channel: String, Active: Boolean})
                            data.save()```

Schema
```js
const { Schema, model } = require("mongoose");

module.exports = model("bans", new Schema({ Guild: String, Channel: String, Active: Boolean }));
sudden geyser
lyric mountain
#

Ah wait, that's a model declaration

hidden gorge
#

yeah

lyric mountain
#

What does ur editor says?

#

Like, it should tell you the proper syntax no?

#

If all else fails, check the docs

hidden gorge
#

no syntax errors

wheat mesa
#

I highly doubt that this is the only code related to your issue

#

you're giving something a function when it expects a boolean

#

where do you use this model @hidden gorge

hidden gorge
#

in my ban command

wheat mesa
#

show where you use it

#

telling me where without more context doesn't help lol

wide herald
lyric mountain
#

This relates back to the fact that being a programmer isn't knowing how to write, but knowing how to write proper questions

#

Actually, programming is surprisingly close to linguistics

sharp geyser
#

Collection(0) [Map] {} the collection is still empty despite the if statement now evaluating true

#

But it is only empty when accessing it outside the scope of where I am setting it

#
            try {
                let importedCommand = new (require(filepath).default)();
                if (importedCommand instanceof Command) {
                    this.components.set(importedCommand.id, importedCommand);
                    console.log(this.components);
                }
            } catch (e: any) {
                throw new Error(e);
            }

here it isn't empty, but if I make an instance of CommandManager and call .addMultipleIn where this code is at and then check <CommandManager>.components it is empty

sharp geyser
#

Still cant tell why the collection is emptying

sharp geyser
#

So the issue apparently was cause I wasn't awaiting the addMultipleIn and logging it in that async func

sterile brook
#

The answers always on surface

sharp geyser
#

on(eventName: 'commandsLoaded', listener: (loaded: boolean) => { loaded: boolean }) {} is this not how I would make my own definition for an event name with specific "callback" props

sharp geyser
#

fixed this as well

#

but now I am running into the issue of the emitter either not emitting, or it is emitting but it isn't being caught cause

    cmdManager.on('commandsLoaded', (loaded) => {
        console.log(loaded);
        if (loaded) console.log('Loaded Commands Successfully!');
    });

this doesn't seem to be working

lament rock
#

unreachable code probably

sharp geyser
#

you are available

#

help

#

I solved the issue but I dont know if this is a viable solution

#

it was a race condition

#

the emitter was firing before the listener was attached and this is the solution I came up with

lament rock
#

For instant things, use setImmediate

sharp geyser
#

Is this the best solution?

lament rock
#

If stuff needs to be on a tick later than the current tick then yes

sharp geyser
#

😔

#

it looks so ugly

#

Should I make a system of just auto detecting commands or should I leave it how I have it.

lament rock
#

don't fix a working system

#

unless you like pain

#

which is probably the case since you code

sharp geyser
tulip ledge
lament rock
#

some modules do not have typings which you can make by doing such a thing

slender wagon
#

how could i solve this issue with modals in mobile

feral aspen
hidden gorge
#

how do i make an embed say how many channels a server has in js v14?

sudden geyser
mortal ferry
#

Whenever i try adding a background banner to the bot it gives me an error. How do i do this? i am using imgur

This is the banner:

sharp geyser
#

it gives you an error hmmm I wonder what the error is?

mortal ferry
#

here is the link i am putting in: https://imgur.com/gallery/zReJYpE

neon leaf
#

try with https://i.imgur.com/AQgvdPs.jpeg

mortal ferry
#

Thanks

mortal ferry
neon leaf
compact pier
#

Is there any way to test dbl webhook on my local machine?

quartz kindle
#

yes, but you will likely need to port forward your router/modem

#

@earnest phoenix i has question

#

consider the following code:

#
let myFunction1 = function() {
  setTimeout(() => console.log("timeout"), 0);
  setImmediate(() => console.log("immediate"));
  process.nextTick(() => console.log("nextTick"));
}

let myFunction2 = function() {
  process.nextTick(() => console.log("nextTick"));
  setTimeout(() => console.log("timeout"), 0);
  setImmediate(() => console.log("immediate"));
}

let myFunction3 = function() {
  setImmediate(() => console.log("immediate"));
  process.nextTick(() => console.log("nextTick"));
  setTimeout(() => console.log("timeout"), 0);
}

myFunction1();
myFunction2();
myFunction3();
#

i get 3 different outputs depending on where i run it

#

lmao

#

nwjs/node-webkit:

#

node with js file

#

node repl

#

from what i know, the correct output should be the third one, but when the code is run from a js file, for some reason the timeouts are executed before the immediates

#

im assuming nwjs has some weird shit going on, because timeouts should not run on the current event loop even when set to 0

#

(also nwjs is running node 17, the other two are running node 19)

sharp geyser
quartz kindle
sharp geyser
quartz kindle
sharp geyser
#

How do you make your own event emitter /s

#

But nah, serious question

#

I am making a class that wraps around an event emitter right. But I have a question regarding how the events actually work

quartz kindle
#

its a simple "store function and run it later"

sharp geyser
#

So say I have a class that extends an event emitter, and I have another class extending an event emitter, we will call these classes A & B

Class A emits an event, is class B able to then listen to that event or is it specific only to class A?

#

or are events accessible no matter what as long as its the same process?

quartz kindle
#

class B would need to register an event listener on class A

sharp geyser
#

How would that look?

quartz kindle
#
class A extends EventEmitter {

}

class B extends EventEmitter {
  constructor() {
    this.A = new A();
    this.A.on("something", this.run.bind(this));
  }
  run() {}
}

const thing = new B();
``` one example
#

another way is to pass an instance of A into the constructor of B

quartz kindle
sharp geyser
#

🤔

#

That might get a little annoying

quartz kindle
#

if you want to "merge" two different emitters, the correct way is to add a listener to their events and re-emit them

#

there are other more hacky ways to do it tho

sharp geyser
#

Yea cause what I am trying to do is allow my listener class to listen to custom events emitted by the CMD Handler and Listener Handler, while also listening on discord.js events

#

That looks like it could get very annoying quickly going that route

quartz kindle
#

for example

#

this is a typical shard manager for discord shards

#

the manager listens to events from all shards and re-emits them

#

and adds the shard id

sharp geyser
#

mmmm

#

Is there no easier way to just merge all the emitters together so I can just listen to them on one base class

quartz kindle
#

there is one hacky way

#

more than one actually

sharp geyser
#

What is the easiest to implement

wheat mesa
#

I believe I know what you're trying to do misty, you made a custom client class and you want it to emit all of the same events (plus some of your own) that a djs client does because you extended it

#

am I right

#

if I am, that might help tim with your solution

sharp geyser
#

I did indeed make a custom client class

quartz kindle
#
class A extends EventEmitter {
  on(...args) {
   this.B.on(...args);
   this.C.on(...args); 
  }
}
``` that would be one way i guess ```js
class A extends EventEmitter {
  constructor() {
    super();
    this.B = new B();
    this._events = this.B._events;
  }
}
``` that would be another hacky way i guess
sharp geyser
#

I also have a Command Handler and ListenerHandler class that emit their own events

wheat mesa
#

this makes me appreciate the relative simplicity of java in a way

#

been using it for the past few days, been pretty refreshing

sharp geyser
#

😔

wheat mesa
sharp geyser
#

and that just grabs the events from all the other classes that can emit them

quartz kindle
#

yeah sort of

#

the second method would be easier to do

#

you just override the object that holds the functions for each emitter

wheat mesa
#

yeah for some reason I'm actually leaning towards the 2nd method even though it's arguably hackier

quartz kindle
#

the first method you would also need to override all other event listener methods such as removeListener

sharp geyser
#

😔

#

ye nvm fuck that one

quartz kindle
#

this would be the best method i can think of ```js
class A extends EventEmitter {
constructor() {
super();
this.B = new B();
this.C = new C();
this.events = {};
this._events = this.B._events = this.C._events = this.events;
}
}

#

basically the event list of all listeners is shared

sharp geyser
#

this._events is a thing?

quartz kindle
#

yes, its where the listener stores the events

sharp geyser
#

You sure?

quartz kindle
#

yes

sharp geyser
#

Cause ts doesn't seem to think so

quartz kindle
#

because its private

sharp geyser
#

😔

#

So if its private how am I supposed to override it

wheat mesa
#

//@ts-ignore I believe works kekw

#

something like that

sharp geyser
#

jeez

quartz kindle
sharp geyser
#

I will be frowned upon by ts enthusiasts but fuck it

wheat mesa
#

since it's compiled to js and there's no such thing as private in js, you should be able to tell ts to just ignore it and it'll work

quartz kindle
#

yes

#

you can also document it yourself

wheat mesa
#

I'd leave a comment on top of it explaining your logic on the ts-ignore though, just so you're not confused if you forget about it in the future

quartz kindle
#

also, there is ts-expect-error

#

which has the comment built in

wheat mesa
#

yeah

#

that

sharp geyser
#
import { EventEmitter } from 'events';
import { AtomClient, CommandManager, ListenerManager } from '../structures';

export class Listener extends EventEmitter {
    #CommandManager: CommandManager;
    #ListenerManager: ListenerManager;
    #AtomClient: AtomClient;

    #events: any;
    constructor() {
        super();
        this.#CommandManager = new CommandManager();
        this.#ListenerManager = new ListenerManager();
        this.#AtomClient = new AtomClient('', { intents: [] });
        this.#events = {};

        // @ts-expect-error _events is private
        this._events = this.#CommandManager._events = this.#ListenerManager._events = this.#AtomClient._events = this.#events;
    }
}

So something like this?

wheat mesa
#

as for your props, I'd use camelCase and just use the private modifier instead of a #

#

as for the other thing, tim will have to say if it's right or not

sharp geyser
#

I dislike camalCase

quartz kindle
sharp geyser
#

voltrex told me to use # over private so I have been ever since trollface

quartz kindle
#

you can also type your events object as Record<string, Function | Function[]>

lyric mountain
#

tf is a #

#

is that a valid variable char?

sharp geyser
#

Voltrex said the compiler doesn't really make shit private if you use private but # does

quartz kindle
#

so ts renames it to _

#

which is the common way to say something is private

#

but depending on your tsconfig, the privte keyword should be able to compile to # just as well

sharp geyser
#

This is what he said

quartz kindle
lyric mountain
#

couldn't they just use the standard private keyword?

#

or go the c# route and use _

quartz kindle
#

yes, but once compiled it will lose the privacy

sharp geyser
#

oh no

quartz kindle
#

the # character actually enforces the privacy even on pure js

sharp geyser
#

I think I may of fucked up

#

None of the events are listening anymore

#

well I fucked something up

quartz kindle
#

try making this.events public

sharp geyser
#

Still nothing

quartz kindle
#

console.log listener._events

sharp geyser
#

Just tried that doesn'tseem to even log it

quartz kindle
#

🤔

#

just tested here, works fine for me

#

try removing all the privates

sharp geyser
#
[Object: null prototype] {}

I also tried it outside the class to make sure and ye its empty

quartz kindle
#

if its null proto thta means the object was not overriden

#

because {} is not null proto

sharp geyser
#

So that means I am doing smth wrong

sharp geyser
quartz kindle
#

i found one issue, but even with that issue it still works for me lol

#

the _eventCount property of the other listeners is not updated

#

but the event still emits for me

sharp geyser
#

🤔

#

Why it no work for me then

#

Maybe it has something to do with the emitters themselves?

lament rock
#

make your own emitter lib

sharp geyser
#

No

#

but could it be an issue with the emitters?

lament rock
#

2nd year in a row no birthday role. Kinda whack

#

Issues with node itself are few and far between

sharp geyser
#

I am only asking cause
AtomClient extends Client (DJS) which extends BaseClient (DJS) which extends EventEmitter

#

I doubt this could cause issues but idk

wheat mesa
#

then look in the djs src to see what they do since Client does not directly extend eventemitter

quartz kindle
#

and console.log it again after overriding it

sharp geyser
#

nothing happens

#

it doesn't log anything

#

not even a new line

quartz kindle
#

?

#

show code

sharp geyser
#
import { EventEmitter } from 'events';
import { AtomClient, CommandManager, ListenerManager } from '../structures';
import { MergedEvents } from '../util';

export declare interface Listener {
    on<U extends keyof MergedEvents>(event: U, listener: MergedEvents[U]): this;
}

export class Listener extends EventEmitter {
    private CommandManager: CommandManager;
    private ListenerManager: ListenerManager;
    private AtomClient: AtomClient;
    public events: Record<string, Function | Function[]>;
    constructor() {
        super();
        this.CommandManager = new CommandManager();
        this.ListenerManager = new ListenerManager();
        this.AtomClient = new AtomClient('', { intents: [] });
        this.events = {};

        // @ts-ignore
        console.log(this._events);

        // @ts-expect-error _events is private
        this._events = this.CommandManager._events = this.ListenerManager._events = this.AtomClient._events = this.events;
    }
}```
quartz kindle
#

are you actually running the listener?

sharp geyser
#

👀

#

maybe

#

ahem

quartz kindle
#

const bla = new Listener()

sharp geyser
#

one momento

wheat mesa
#

classic misty

quartz kindle
#

also, for the _eventsCount issue, you can do ```js
Object.defineProperty(this.A, "_eventsCount", {
get: _ => this._eventsCount,
set: x => this._eventsCount = x
});

#

gotta love js's hackability

#

lets just redefine everything

sharp geyser
#

lmao

#

Well now im fucking event more shit up

quartz kindle
#

also, just found out something else

#

removeAllListeners resets the _events object back to default

#

so that would also need to be overriden

#

lmao

sharp geyser
#

BRUH

#

I am disliking this project more and more

quartz kindle
#

thats why its preferable to do it the normal way lmao

sharp geyser
#

How would I even override removeAllListeners?

#

What would it need to look like so it doesn't result it back to default just the same as what I am doingin the constructor or?

quartz kindle
#

something like this i guess (untested): ```js
class A extends EventEmitter {
constructor() {
super();
this.B = new B();
this.C = new C();
this.events = {};
this._events = this.B._events = this.C._events = this.events;

Object.defineProperty(this.B, "_eventsCount", {
  get: _ => this._eventsCount,
  set: x => this._eventsCount = x
});

Object.defineProperty(this.C, "_eventsCount", {
  get: _ => this._eventsCount,
  set: x => this._eventsCount = x
});

Object.defineProperty(this.B, "removeAllListeners", {
  value: this.removeAllListeners.bind(this)
}); 

Object.defineProperty(this.C, "removeAllListeners", {
  value: this.removeAllListeners.bind(this)
}); 

}
removeAllListeners() {
this.events = {};
this._events = this.B._events = this.C._events = this.events;
this._eventsCount = 0;
}
}

sharp geyser
#

Also I have a question

#

I saw this old djs framework that had an event listener setup where the listener was l like this

class ReadyListener<'Ready'> extends Listener {
  constructor() {
    super({
      emitter = "client",
      event = "ready",
      type = 'on'
    })
  }
  exec(client: Client) {
      console.log('client is ready')
  }
}

and later to actually listen on this event they register it in the handler itself like

class ListenerManager extends EventEmitter {
  register() {
    // they grab the emitter in the Listener Classes
    (emitter as EventEmitter)[type](event, exec)
  }
}
#

My question is, that is cool and all, but they also allow doing the same thing but for the command handler as well

#

so instead of the emitter being clientthey would put command but how does it recognize command.on?

#

Matter of fact just found some old code that does just this, it was a project I forked to help a friend out, but I don't quite get it

https://github.com/Mistyerious/shensuo/blob/134437934f5048390ce10d22af6ebb4855da4985/src/lib/events/EventHandler.ts

GitHub

🔧 | A simple, lightweight and flexible framework for discord.js on steroids. Bleeding edge features always up to date with discord.js master. - shensuo/EventHandler.ts at 134437934f5048390ce10d22af...

quartz kindle
#
(emitter as EventEmitter)[type](event, exec)
=
emitter["on"](event, exec)
sharp geyser
#

yes I know that

#

but emitter could be anything

#

client, command, or listener

#

but that still doesn't help me understand how it knows what to actually listen on

quartz kindle
#

dont they define everything here?

sharp geyser
#

yes but I asking

#

how does it client is a valid emitter

#

or is it just a classification

quartz kindle
#

the code for Listener should have the answer

sharp geyser
#
import { IEventOptions, UnionEvents } from '..';

// ! Won't import via barrel so I'm just doing it like this. Same holds true for handlers.
import { BaseModule } from '../extendable';
import { IntersectedEvents } from '../Types';

export abstract class Event<T extends UnionEvents> extends BaseModule {
    public readonly options: IEventOptions;

    public constructor(identifier: string, { emitter, category = 'default', event, type = 'on' }: IEventOptions) {
        super(identifier, { category });

        this.options = {
            emitter,
            category,
            event,
            type,
        };
    }

    public abstract exec(...args: IntersectedEvents[T]): any;
}

from that old code this is all it is

#

I still don't get how that works just by looking at this

wheat mesa
#

what the fuck lmfao

sharp geyser
#

This is very cursed code indeed

#

but I actually like its functionality so ima use it

quartz kindle
#

that project is split into so many parts that its indeed confusing

#

you need to start somewhere and follow the code

#

that Event class is meant to be extended by the user

#

myEvent extends Event

#

and the user should give it his own exec method

#

then the user should give this extended Event to the Event handler

#

EventHandler.register() expects an Event as the first argument

sharp geyser
#

I see

#

Also, this._events is an empty {} after overriding it

quartz kindle
#

should be working then

sharp geyser
#

its supposed to be empty?

quartz kindle
#

initially yes

#

then when you add events to it it will fill up

sharp geyser
#

well I am calling events on it

#

and it doesn't listen to them

quartz kindle
#

console.log it after doing .on()

#

also, you could always give this a try lol
https://www.npmjs.com/package/events-merge

#

7 years ago, but oh well

#

also, just thought of another way of overriding

#
class MyClass extends EventEmitter {
  constructor() {
    super();
    this.A = new EventEmitter();
    const emitter1 = this.emit;
    const emitter2 = this.A.emit;
    this.A.emit = function(...args) {
      emitter1(...args);
      return emitter2(...args);
    }
  }
}
``` something like this lol
#

(untested)

sharp geyser
#

ye the events aren't being listened to wtf

#

I have a test ready event and it doesn't log what I have

quartz kindle
#

console.log this._events before and after using .on

sharp geyser
#
[Object: null prototype] {}
[Object: null prototype] {}
#

😔

#

I can't work on this anymore right now I got work soon

#

Ima just push it to the repo and touch it later

earnest phoenix
#

atNull

sharp geyser
quartz kindle
#

which suggests you want it to be used like this ```js
new Listener("ready", "once")
new Listener("messageCreate", "on")
...

#

but if you want it to be used like that, then the Listener class cannot create new clients inside it

#

otherwise you will have a bunch of different clients around for each listener you create

craggy pine
#

So this is a question that probably answers itself but is there anyway to cerconvent the whole "Discord wont verify youtube music bots" by for instance maybe having the bot call an external thing to then maybe download a .mp3 of a youtube video once and store it into a folder then play it. That way if a user tries to play a song it can lookup if the mp3 exists first before attempting to download one. I know the data size could become rather large quick but would that possibly get around their terms and conditions since the bot is playing a .mp3 and not a direct youtube video.

earnest phoenix
#

That won't change anything because downloading the video or audio of a YouTube video goes against their terms of service regardless

craggy pine
#

Yeah I assumed so.

#

I can do what everyone else does and simply do soundcloud, but it really dwindles the amount of options users will receive.

solemn latch
#

I think theres other issues too.
Like just because its downloaded doesnt mean its not content off of youtube.

quartz kindle
craggy pine
#

I mean thats what my mindset was. Like Discord won't know where I'm getting the mp3's from

earnest phoenix
#

That's true, as long as you don't reveal it yourself

craggy pine
#

I mean also...

#

As it stands, I do list / tell in multiple commands and messages where the song came from, if I simply removed it all, would discord care? I mean I could be theoretically doing it off of soundcloud...

#

but they probably have ways to tell

quartz kindle
#

if they really want to figure it out, they can just pick a very specific video off youtube and try to run it on your bot, and check if it works and if the content is exactly the same

craggy pine
#

Yeah exactly. lol

#

Is a shame. I listen to a lot of music atleast through my bot that normally wouldn't be found via soundcloud or spotify and I'm sure a large amount of users do aswell

earnest phoenix
#

Yeah, YouTube contains almost every track users would ever want but unfortunately there's the YouTube ToS, but SoundCloud and similar aren't that bad though

#

The other platforms definitely contain 75% or so of all the tracks the users would want to listen to

craggy pine
#

I'd honestly be fine if there was a way to directly play spotify

#

However I don't believe or atleast haven't found a way to do spotify

earnest phoenix
#

Spotify has a private API to do that but you'd have to get in contact with them and pay to do so

craggy pine
#

I bet it's rather expensive.

earnest phoenix
#

It is

craggy pine
#

And probably wouldn't get approved for the case of what I'm trying to do.

earnest phoenix
#

I mean, then it wouldn't rely on YouTube which is so far the only banned source to play music from

#

There definitely are other sources who forbid playing their tracks outside of their platform but I don't think Discord cares about those, and you wouldn't be breaking Spotify's ToS either

craggy pine
#

I'll have to look into it but funds is not an option if it's too high

earnest phoenix
#

I think it's more expensive than OpenAI's APIs

craggy pine
earnest phoenix
#

That's possibly the case

craggy pine
#

Le sigh. Well I'll keep it YouTube until my bot gets closer to its 100 limit then I'll likely do soundcloud as the new primary. But because I allow creation of playlists through database, I'll definitely have to purge it.

earnest phoenix
#

Oh well, good luck with integrating a different source to play from and hoping it to go well

craggy pine
#

Yeah only reason I decided to do this project even with the TOS in place was because I did start it before it was, learned more about JS and got better, then decided to finish it

earnest phoenix
#

Understandable, have fun with that

formal jacinth
#

my bot is now almost three weeks in verify. Is that normal?

#

i added my bot on the second of January

lyric mountain
#

That's 2 weeks then

wheat mesa
#

@lyric mountain do you know of any good ways to call a function every x milliseconds in java? I'm making a mini game engine and I need to be able to call update(float dt) on a regular basis (about every 16ms), so I need it to be fast and lightweight

#

I tried using a swing timer but I believe that doesn't work unless I extend some sort of swing class

lyric mountain
#

ScheduledExecutorService is the class ur looking for

wheat mesa
#

Is it fast enough to handle something like that?

lyric mountain
#

Pretty much, it's the main and official method of making periodic executions

#

I don't remember the name of the function, just type Executors. and press ctrl space

#

Should be newScheduled something

wheat mesa
#

Executors.newScheduledThreadPool(1)

lyric mountain
#

Yes that

#

Save the executor service onto a final variable and use .schedule() to add tasks

#

Or submit, idk

#

Been a while since I used scheduled executor

wheat mesa
#

It doesn't seem to be running more than once

lyric mountain
#

Ctrl space, see all methods

#

You're looking for one that has 3 arguments

wheat mesa
#
public abstract class Game implements Runnable {
    public static final int DEFAULT_MAX_ENTITIES = 5000;
    private static final int UPDATE_DELAY_MS = 16;
    private ScheduledExecutorService timer = Executors.newScheduledThreadPool(1);
    protected Window window;
    protected World world;
    protected RenderSystem renderSystem;
    protected PhysicsSystem physicsSystem;

    public Game() {
        this(DEFAULT_MAX_ENTITIES);
    }

    public Game(int maxEntities) {
        // ...
        timer.scheduleAtFixedRate(this, 0, UPDATE_DELAY_MS, TimeUnit.MILLISECONDS);
    }

    @Override
    public void run() {
        this.update(1.0f / (UPDATE_DELAY_MS * 1000));
    }

    public void update(float dt) {
        // Update other systems here
        System.out.println("dt: " + dt);
        physicsSystem.update(dt);
        window.repaint();
    }
}
#

that's what I'm doing

#

can't seem to get it to run more than once

lyric mountain
#

Is the task finishing?

wheat mesa
#

I don't see why it wouldn't

lyric mountain
#

Cuz since u created a single thread pool, it won't execute the next task until the current finishes

wheat mesa
#

there's no infinite loops in there

#

so it should be finished long before the next one even runs in theory

lyric mountain
#

Hm, weird, it should work

#

Try following with the debugger to see what's happening

wheat mesa
#

and the systems are only running over 1 entity, so if it's THAT slow then there's a massive problem lol

lyric mountain
#

It isn't, ExecutorService is by far the most optimized thread manager in java

#

U could also try to use the old infinite loop method

wheat mesa
#

the infinite loop method doesn't work too well for what I'm doing unfortunately

lyric mountain
#

Why not?

wheat mesa
#

well actually I guess why not

#

definitely running now

#

I have a bug to fix rq before I can determine if everything is working tho hold on

lyric mountain
#

Weird, executor method should've worked too, I wonder why it didn't

#

Btw, make sure to create a new thread for that loop

#

Else u might hang the whole thread

wheat mesa
#

how would I do that

lyric mountain
#

Either with executors (make a global thread pool) or new Thread(() -> ...)

#

Just remember to kill the thread when u stop using it, if going the raw route

wheat mesa
#

Alright I'm doing this now, it's running in a loop properly ```java
public void run() {
new Thread(() -> {
while(true) {
this.update(1.0f / (UPDATE_DELAY_MS * 1000));
try {
Thread.sleep(UPDATE_DELAY_MS);
} catch(InterruptedException ignored) {}
}
}).start();
}

lyric mountain
#

Make the class implement closeable

#

And save the thread to a variable

wheat mesa
#

problem is that now my ECS isn't updating the positions of the transform components for some reason, super annoying

#

but I'll have to fix that later because I have to leave

lyric mountain
#

Transform? U using graphics2d?

wheat mesa
#

Yeah

lyric mountain
#

Remember g2d isn't thread-safe

wheat mesa
#

I’m using swing as the base unfortunately

lyric mountain
#

Yes, just make sure ur passing the update to the render thread properly

wheat mesa
#

The window paint method calls my render system update method with some double buffering enabled

lyric mountain
#

Like, don't update the g2d directly, instead defer to the render thread

wheat mesa
#

I’ll have to explain more in a little bit, gtg for like 45 mins

lyric mountain
sharp geyser
quartz kindle
#

like this

#
const listener = new Listener("ready", "once");
someManager.register(listener)
#

or you can do it like this ```js
const listener = new Listener("ready", "once", someManager);

#

in both cases someManager would contain the actual clients and emitters, not Listener

sharp geyser
#

I see

#

I’ll look at that when i get off work

tame dawn
#

How i can delete a conversation?

lyric mountain
#

U don't

tame dawn
#

So i have to do only by one ?

#

No other option available?

lyric mountain
#

You can't delete the other side's messages

#

You can close a conversation tho, but it'll still exist

sudden geyser
#

does closing a convo even do anything

#

on the bot side

lyric mountain
#

no idea

sharp geyser
#

Wait what

#

cant you just delete the messages or is this something entirely different from messages in a channel?

#

is this in a dm?

tame dawn
tame dawn
lyric mountain
#

you'll be spamming the api for no apparent reason

#

unless u sent mass ads and is trying to cover up your tracks

tame dawn
#

No ! It's conversation with girlfriend. 😂

lyric mountain
#

through a bot?

tame dawn
#

No just talking here in dms and want to delete now .

#

So if any idea how to delete it please tell me ...it's annoying me .

lyric mountain
#

so u mean your own dm

#

same thing, go over every message deleting every single message

#

or just close the convo, it wont delete the messages but it'll remove it from the list

tame dawn
tame dawn
#

So there is no option to select all types?

lyric mountain
#

no

tame dawn
#

There is alot of messages so i guess it's better to close dm 😂

#

I'm not going to delete one by one .. it'll take years to erase completely 😂

lyric mountain
#

if u don't mind the other side still being able to read them there's no reason to delete 'em

wheat mesa
#

Incriminating evidence from online “girlfriend” KEKW

#

ok so @lyric mountain I fixed my bug, turns out it was just moving the point so little that it wasn't showing up lol

#

Also, the issue with the scheduledexecutorservice was because I was getting an exception

#

I guess it started everything faster than then window could be created so it was null and then it stopped the task entirely after that

#

My next question: how do I clear the canvas each frame to draw everything again? Currently it never clears the frame despite me calling super.paintComponent(window) in my canvas class

#
public void paintComponent(Graphics window) {
        super.paintComponent(window); // I thought this was supposed to clear the window, no?

        Graphics2D graph = (Graphics2D) window;
        if(back == null) {
            back = (BufferedImage)(createImage(getWidth(),getHeight()));
        }

        Graphics graphToBack = back.createGraphics();

        renderSystem.update(graphToBack);

        graph.drawImage(back, null, 0, 0);
    }
wheat mesa
#

nvm got it, I don't need the if(back == null) block, no idea why I added that in the first place

worthy wadi
#

The bot needs its own bmw to respond, so it did not respond, which is proof that it is running at the same time as the bot message

sudden geyser
#

bmw?

rustic nova
#

bot needs its own bmw

craggy pine
quartz kindle
#

a bot with a bmw lmao

#

a bot richer than most of us

compact pier
#

I have a bmw too

#

but it is remote controlled

#

does localhost internet speed is actually depens on your internet cable or internet adapter?
it can goes up to 100gb if you have good equipments

solemn latch
#

if lets say the router supported 1gbps, but both computers could do 100gbps then Id be capped at 1gbps.

lyric mountain
#

it's annoying cuz sometimes shit happens and u wont know unless u put try-catches in the correct places

#

there's a way around it tho, I made a throwing functional interface, feel free to copy it if u want```java
@FunctionalInterface
public interface ThrowingConsumer<A> extends Consumer<A> {
void acceptThrows(A a) throws RuntimeException;

@Override
default void accept(A a) {
    try {
        acceptThrows(a);
    } catch (final Exception e) {
        // print the exception here

        throw new RuntimeException(e);
    }
}

}

#

you'll just need to make it a runnable instead of a consumer

quartz kindle
#

therefore its performance is mostly cpu/ram dependent, not network, and usually reaches speeds of 20+ gbps

compact pier
#

for ios development

#

I tried teamviewer, but they still communicate to third-party server

#

so it is really slow

#

I want it to be resposive, but still haven't found any solution for that

viral badge
#

tried AnyDesk? might be third party server too though, i'm unsure

viral badge
covert gale
#

It’s inside the same network

viral badge
#

localhost is the computer itself

#

127.0.0.1 / 0.0.0.0

covert gale
#

No

#

Local host can also be inside the same network

viral badge
#

how's that work?

covert gale
#

Everything’s routed inside the local network

#

It’s inside your local network and not going outside

viral badge
#

router: gives IPs to devices, how would you use localhost between those?

covert gale
#

If I ssh into a pc inside my network

#

That’s still local host

viral badge
#

how is it?

#

if i ssh localhost i'll be sshing to the same machine

quartz kindle
#

localhost/127.0.0.1 is inside the same machine, more specifically its the address of the loopback adapter/interface

viral badge
quartz kindle
#

other computers on the same network are LAN (local area network)

viral badge
#

btw guys my router counts LAN as WAN, any fix?
summary:
LAN connections: 1 Gbps, confirmed with file transfers etc
I had 100/10 Mbps (now 250/100) broadband bandwidth (WAN)
When above 100 Mbps LAN usage WAN would be unavailable (LAN would not be unavailable for clarity)

quartz kindle
#

uhh what

viral badge
#

if I sent more than 100 Mbps via scp for example (easiest way), WAN connections would stop working while that bandwidth was taken
router: Asus RT-AC58U
| |
pc1 pc2

#

have had that issue for 2 years now 💀 (aka ever since started testing it)

quartz kindle
#

you mean you lose internet access if you transfer a large file from one pc to another via lan?

viral badge
#

WAN access yes

quartz kindle
#

via wifi or cable?

viral badge
#

cable ofc

#

and in case i wasn't clear how it's not any cables or anything doing it
just sending 12 MBps (100 Mbps, which was my WAN bandwidth) would make WAN inaccessible
but I could transfer up to ~300 MBps or something like that (LAN, aka within the cables and machines)
(using 1 Gbps ethernet cables)

quartz kindle
#

sending files from pc1 to pc2 or vice versa is not affected by your wan speed, if both pcs are synched at 1gbps then the router should be able to deliver 1gbps between both pcs.
now if either pcs lose internet access while transferring (for example, ping google.com starts timing out while the transfer happens), could be that the router is being overloaded, or the pc's network interface is overloaded

viral badge
#

well no no, whole WAN stops working/freezes

#

and the router as said can handle 200+ MBps in LAN but WAN stops working at 12 MBps so (router should be able to handle 1700+ Mbps)

quartz kindle
#

i dont understand what you mean

#

WAN = internet access

viral badge
#

yes

#

when I transfer files using LAN connections, WAN stops working when LAN exceeds the WAN bandwidth

quartz kindle
#

thats what i said

#

if either pcs lose internet access while transferring (for example, ping google.com starts timing out while the transfer happens), could be that the router is being overloaded

viral badge
#

its not the pcs that lose access, its the router itself, so any device within the router doesn't have WAN access at that moment

quartz kindle
#

so the router is overloaded

viral badge
#

but that can't be, because it stops working when WAN bandwidth is filled by LAN

#

also now I got 250/100 Mbps bandwidth so I could test it now with 2.5x the transfer to see if it freezes WAN , which would also prove that it is not any overloading issue

quartz kindle
#

i've never heard of an issue like that

viral badge
#

💀

wheat mesa
#

major skill issue

viral badge
#

real

quartz kindle
#

how is your router configured?

viral badge
#

default pretty much

compact pier
#

does window screen mirror use third-party server?

#

they have some thing that used to control windows server

#

forgot the name

#

ah but it is not for mac

sudden geyser
#

source code from the dutch government

hushed robin
#

🤩

craggy pine
#

top tier coding right there.

cinder patio
#

this kinda stuff right here gives me confidence

sharp geyser
idle yarrow
#

Hello,
I created a bot with the Discord API. I am using Javascript (discord.js). I need to modify this bot by adding code that allows me to know (for users of a Discord server of a mobile game)

the date they joined the Discord
the duration of the period when they are online
the number of messages sent
the time frame of presence on the Discord
I was able to see what a potential code looks like but I know nothing about it.

I don't know the steps to take from A to Z. I am lost.
(i've Visual Studio Code, Node.js.)

sudden geyser
#

You likely want to play around with a GuildMember object

#

Which has properties like .joinedAt (a date representing when they joined the server)

#

Some things you want to implement (e.g. how long they've been online) are stateful things you'd need to track yourself. For example, listening to the presenceUpdate event and recording when a user's presence turns offline or not.

#

For your map, it would likely map from a guild member ID to a map recording when they were first considered online and the last time they were, in which you could just compute the difference

#

Of course, this information is in memory, which will be cleared on restart, but I don't know if that matters for your use case @idle yarrow

wooden wagon
#

Im currently developing the site of my bot https://nota.bot.
Any ideas on how to improve it?
Also there seems to sometimes be a problem with adding and removing snap behaviour (how-to-section), anyone having the same experience/know why adding snap sometimes lags you to a different part of the Page?

digital swan
#

this is very hard to read

wooden wagon
compact pier
#

it looks like the 90s ads

digital swan
wooden wagon
lyric mountain
wooden wagon
#

oh noooo xD

lyric mountain
#

tbh, I'd drop most of it and keep only ur logo + name

deft wolf
#

r/crappydesign moment pogey

wooden wagon
civic scroll
#

but it gives me that early 95' graphics

#

if you pixelate it

#

but i think you can put the text logo out

#

and the title below it

wooden wagon
#

okay so just change the logo to a plain coloured version?

civic scroll
#

if the bg is dark color
then logo text and title can be white-ish (85% white) to prevent some discomfort

#

but keep the "Kill the mayhem" red

#

for its badass vibe

civic scroll
#

but, at the end you do you

#

try and see what you like the best

wooden wagon
wooden wagon
lyric mountain
civic scroll
#

kuu look at hypergryph logo

lyric mountain
#

by little I mean like double the size

civic scroll
#

the eyes are smol

lyric mountain
civic scroll
lyric mountain
#

btw, intellij got a vscode-like theme 💀

wheat mesa
#

I kinda like it

wooden wagon
lyric mountain
#

tho I can edit it

#

orange-grey-purple looks better imo

civic scroll
#

but yes i made it

civic scroll
lyric mountain
#

I think u still can

civic scroll
#

i tried in new ui beta

lyric mountain
#

I'll enable it later, still reading what's new in this version

wooden wagon
civic scroll
#

thanks

#

that was my first react website

lyric mountain
#

hm, action preview is kinda neat

#

reader mode also got a "use my formatting" mode

civic scroll
lyric mountain
#

which doesn't format the source code but allows u to read however u like it

civic scroll
#

hmmmm

#

very neat

lyric mountain
#

apparently u can also work full on cloud with ij

#

hm, not so bad ig

#

tho the "run" button stands out like a sore thumb

#

but people should now stop calling jetbrains ides "visually outdated"

#

isense also looks cleaner

bright thorn
#

is nsfw content such as images and videos are allowed in discord bot?

earnest phoenix
eager ferry
#

cause he's a bold man

nocturne dagger
#

Hello

#

Is there a way to lock admin commands for a bot to only specific server/user?

#

Same way you can with permissions on slash commands I can't find the docs for it.

marsh bluff
torpid crystal
#

Am using canva package for making a profile card in a command in djs. I can add the user profile pic inside the image but how can I make it in a circle? It's taking the default square

craggy pine
#

canvas in node js?

lyric mountain
#

if u want different shapes you need to clip the image

torpid crystal
craggy pine
#

well kuu gave you the answer.

#

What I do is I keep the image square, but have transparency infront of the image to make it look circular.

lyric mountain
craggy pine
lyric mountain
#

did u draw the onigiri shape with paths?

craggy pine
#

nope

#

I did all of that in photoshop actually.

lyric mountain
#

ah, u simply overlaid the rest on top of the avatar

craggy pine
#

original.

#

simple solution but effective 😄

knotty quartz
#

I have a queerie

#

How can you use:

client.users.send('id', 'content');

To send a message to the DM (An embed to the target of the moderation command), as well as sending the embed in the server?

lyric mountain
#

that's definitely not how it works

knotty quartz
#

Idk, I've never sent DM messages and that's what coming up in the guide on search

lyric mountain
#

I bet it isn't, cuz client.users returns a collection, not a single user

#

use find to get the user u want, then use send

#

the rest is the same as sending a message to a normal channel

knotty quartz
lyric mountain
#

try to solve it first

#

the only error that might happen is that the user blocked ur bot (or doesn't exist)

#

so use .catch

knotty quartz
lyric mountain
#

no because it's a promise

wheat mesa
#

Use .get

#

Please

#

(If you have the ID)

knotty quartz
knotty quartz
wheat mesa
#

What

knotty quartz
#

.find() returned an error so i used .fetch()

lyric mountain
#

it returned an error because client.users doesn't have the actual users

#

either fetch or use .cache

knotty quartz
#

Im still trying to do catch

lyric mountain
#

wont work, fetch expects a param

knotty quartz
#

Unless it's because member is defined with options.getUser() so it already has the user.

#

Nvm

nocturne dagger
#

Is there a large response type field for slash commands

#

so it can have several lines

hushed robin
#

sadly

nocturne dagger
#

Ah okay

#

Thanks though

hushed robin
#

u could use a modal

neon leaf
#

is there a simpler way to turn a local loaded file into a url path while removing .html if enabled and using index.html as root?

let fileName = file.replace(folder, '').replace('/', '')
let pathName = path + folder.replace(fileName, '').replace(folder, '').slice(0, -1)
if (pathName.startsWith('.')) pathName = pathName.slice(-1)
if (remHTML && fileName === 'index.html') fileName = ''
else if (remHTML && fileName.endsWith('.html')) fileName = fileName.slice(0, -5)
else if (remHTML && fileName.endsWith('.htm')) fileName = fileName.slice(0, -4)
const urlName = `${pathName}/${fileName}`.endsWith('/')
    ? `${pathName}`
    : `${pathName}` === '/'
        ? `/${fileName}`
        : `${pathName}/${fileName}` ```
#

ig

const pathParser = (path: string) => {
    path = path.replace(/\/{2,}/g, '/')

    if (path.endsWith('/') && path !== '/') return path.slice(0, -1)
    if (!path.startsWith('/') && path !== '/') return `/${path}`

    return path
}

// ...

let fileName = file.replace(folder, '').replace('/', '')
const pathName = path + folder.replace(fileName, '').replace(folder, '').slice(0, -1)
if (remHTML && fileName === 'index.html') fileName = ''
else if (remHTML && fileName.endsWith('.html')) fileName.slice(0, -5)
else if (remHTML && fileName.endsWith('.htm')) fileName.slice(0, -4)
const urlName = pathParser(`${pathName}/${fileName}`)```
wheat mesa
#

my lord just use path in node please 😭

#

Probably has everything you need

neon leaf
#

you mean this?

let pathInfos = path.parse(file.replace(folder, ''))
if (pathInfos.base === 'index.html') pathInfos.base = ''
else if (pathInfos.ext === '.html') pathInfos.base = pathInfos.base.slice(0, -5)
else if (pathInfos.ext === '.htm') pathInfos.base = pathInfos.base.slice(0, -4)
const pathName = path.join(pathInfos.dir, pathInfos.base)```
slender wagon
#

now guys how do i solve something like this

#
  Type 'undefined' is not assignable to type 'string'.

The error ^

url = req.query.url?.toString()
craggy pine
#

It looks like .toString() cant be used on an undefined object

#

aka .url

#

could be wrong.

slender wagon
#

nope that's not it

#

ik it has to do with the type of req.query.url

#

cuz it takes a few types

#

not sure how i am supposed to limit it only to string

quartz kindle
slender wagon
#

bruh

#

had to use triple equals

#

now the only issue i have is the

No overload matches this call.
await pipeline(response.body, res);
#

error is for the response.body

quartz kindle
#

whats the type of response.body

#

and whats the signature of pipeline

slender wagon
#

I'll get back to it tomorrow Tim, thank you tho

scenic wolf
#

hello, good evening, someone who handles js to ask you a question?

#

I'm making a bot, but I'm having trouble with a command that I want it to respond differently
ex: command 'hello' and 'hello Juan' that are answered differently, the problem I have is that when I write 'hello Juan' it responds as 'hello'

#
   case "hola":
          reply(hola desconocido);
          break;
      case "hola":
          if (command.includes("juan")) {
              reply(hola juan!);
          } else {
              reply(que hola estas diciendo ?);
          }
          break;```
craggy pine
#

so it matches the first one and breaks.

scenic wolf
#

ah wait

craggy pine
#

what are you matching case too?

#

what's the switch()

scenic wolf
#
case "hello":{
  if (body.includes("juan")) {
      reply(`hello juan`);
  } else {
      reply(`hello who are you?`);
  }
  break;
  // Otros casos ...
    }
craggy pine
#

Then yeah that should fix your issue.

scenic wolf
#

i have 2 swtich ```js
const command = isCmd ? body.slice(0).trim().split(/ +/).shift().toLocaleLowerCase() : null
const task = isCmd ? body.slice(0).trim().split(/ +/).shift().toLocaleLowerCase() : null

craggy pine
#

You shouldn't have more than 1 switch reading your command

scenic wolf
#

The problem is that I get the same thing 😦

craggy pine
#
switch(what's in here?) {
case:
break
}
lyric mountain
#

Just a headsup, move away from switch/if-else asap

scenic wolf
#

em

lyric mountain
#

Commands are better done with a proper handler

craggy pine
#

I mean, also true.

lyric mountain
#

Else you'll get pasta al dente

scenic wolf
#

It is that the bot that I am, is the base like this of case break 😦

#

i tried but i got so confused :/

lyric mountain
#

are you new to coding?

scenic wolf
#

somenthing u.u

lyric mountain
#

I'd recommend attempting an easier project before starting a bot

craggy pine
#

Code cademy is what I used for learning JS

#

atleast basics 😄

lyric mountain
#

CA is nice because they give you actual projects to solve urself

craggy pine
#

Its not CA assuming your referring to me. They actually spell it cademy 😛

#

CC 5head

lyric mountain
#

credit card 👌

craggy pine
#

I'll take yours ty ver much

scenic wolf
#

oh

#

I think I found the reason

lyric mountain
#

they always ignore advices don't they?

scenic wolf
#

no no, that's not it 😦

#
const isCmd = body.startsWith('');
    const task = isCmd ? body.slice(0).trim().split(/ +/).shift().toLocaleLowerCase() : null
#

he had the startsWith

sterile brook
earnest phoenix
#
            const circle = {
                x: canvas.width / 2,
                y: canvas.height / 2,
                radius: 70,
            }
            
            // x = canvas.width / 2 - pfp.width / 2
            // y = 20
            // ctx.drawImage(pfp, x, y)
            
            ctx.beginPath();
            ctx.arc(circle.x, circle.y, circle.radius, 0, Math.PI * 2, true);
            ctx.closePath();
            ctx.clip();
            
            const avatar = await Canvas.loadImage(interaction.user.displayAvatarURL({ extension: 'jpg' }))
            console.log(avatar.height, avatar.width);
            
            // Compute aspectration
            const aspect = avatar.height / avatar.width;
            // Math.max is ued to have cover effect use Math.min for contain
            const hsx = circle.radius * Math.max(1.0 / aspect, 1.0);
            const hsy = circle.radius * Math.max(aspect, 1.0);
            // x - hsl and y - hsy centers the image
            ctx.drawImage(avatar,circle.x - hsx,circle.y - hsy,hsx * 2,hsy * 2);

this is an balance command and i am trying to resize the image im using canvas npm

#

can you tell me how i can resize?

south kiln
#
const { MessageEmbed } = require('discord.js');
const samp = require('samp-query');

module.exports = {
    name: 'server',
    aliases: [],
    description: 'Displays informations about SA:MP Server',
    run: async (client, message, args) => {
        const color = await message.guild?.members.fetch(message.client.user.id).then(color => color.displayHexColor) || '#000000';

        const ip = "123.456.789".split(':');
        const options = {
            host: ip[0],
            port: ip[1] || 7777
        };
    
        await samp(options, (error, query) => {
            if(error){
                const embed = new MessageEmbed()
                .setColor(color)
                .setTitle(`${options.host}:${options.port}`)
                .setDescription('Server is offline');
        
                return message.channel.send({ embeds: [embed] });
            }
            else{
                const cutomembed = new MessageEmbed()
                .setAuthor("APEX ROLEPLAY | SERVER STATUS")
                .addFields(
                    {name: '__Server Status__', value: `Online`, inline: true},
                    {name: '__Players__', value: `${query['online'] || 0}/${query['maxplayers'] || 0}`, inline: true},
                    {name: '__In-game Time__', value: query['rules']['worldtime'], inline: true},
                    {name: '__Server-ip__', value:`play.apexroleplay.in:5555`, inline: true},
                    {name: '__Language__', value: `Malayalam`, inline: true},
                    {name: '__Conecting Issue__', value: `[#966354834443886622](/guild/264445053596991498/channel/966354834443886622/)`, inline: true},
                )
                .setColor("#36393e")
                .setThumbnail("")
                .setImage("")
                .setFooter("Anandhu#1096 | Server Status")
    
                return message.channel.send({ embeds: [cutomembed], content : "**APEX ROLEPLAY | SERVER STATUS <@&1065600394723602515>**"});
            }
        });
    }
}```
#

Any one please help i want to change this code like automatically edit this embed when any change in player value oru ingametime value any know how to do this please ping me

earnest phoenix
#

Whenever I try to build it gets stuck here. Can you help me?

lyric mountain
#

ur not stuck, some things take time

pearl trail
sudden geyser
#

Python users, question on linting

#

pycodestyle or pylint

earnest phoenix
lyric mountain
#

But well, depends on what ur trying to compile

earnest phoenix
#

only 2 lines of code...

lyric mountain
#

Do u have many modules? Why are u compiling it?

torpid crystal
#

Suppose am making a command like this using canvas nodejs package, how can I make the avatar image smaller in size?

lyric mountain
#

Resize it

deft wolf
#

5head

lyric mountain
#

Like, literally, there's not much to answer

#

When ur drawing an image there are 4 params

#

The last 2 are the size

torpid crystal
#

😬 how can I do it that's what I wanted to ask, like any function for it or divide the width & length of the image.

torpid crystal
earnest phoenix
#

And i get this error when i compile with pkg. I using nexe-natives-fix and win-dpapi

lyric mountain
#

Why are u compiling it to begin with?

#

Simply run the bot

earnest phoenix
#

Bot for compile cods.

#

I'm not compiling bot.

lyric mountain
#

...you have no idea about what ur doing do you?

earnest phoenix
#

What you mean? lol

lyric mountain
#

Simply run node index.js

earnest phoenix
#

This bot compiles the code entered by the users and sends it to the user as an exe.

lyric mountain
#

Why?

earnest phoenix
#

Because why not, it is my project.

lyric mountain
#

That's a great way to either crash ur bot or get yourself banned

#

Besides, users wouldn't use that, or even know how to

#

Perhaps 5-10 users would ever touch that feature

#

If u still want to, don't use js, use a compiled language instead

#

Js can't compile to exe (without electron, which is...well, electron)

#

Even electron doesn't compile anything, it just wraps the project into something executable (u can unpack them easily)

earnest phoenix
#

This is not against discord tos

viral badge
#

ngl it would be a small target audience but make a JS to C++/ASM converter + compile and it'll be lit

digital oyster
#

sup, does anybody know if my bot creates an invite and sends it to me if it joins a new server is agains tos?

lyric mountain
#

it's known that executables sent on public servers are often scam attempts, people might report your bot even if it isn't

earnest phoenix
lyric mountain
#

...did u even read what I said?

#

all it takes is enough people to report your bot and it'll be taken down in no time

lyric mountain
viral badge
#

😏

earnest phoenix
#

Pkg is a shit

#

works for me and its not shit

viral badge
#

how would you mitigate "botting server count" then? 💀

viral badge
#

discord denies verification if bot is "botting server count" (obviously without actually "botting server count")
gets bot banned from verification as well

hushed robin
#

you don’t need to create an invite link to mitigate that though

viral badge
#

personally we made a thing that just autoleaves servers below 9 membercount 💯 that method worked out, though that was too late for the first bot my friend tried to verify since it gets banned 💀

hushed robin
#

yeah you don’t need to create an invite and give yourself access to the server to do that

viral badge
#

yup

hushed robin
#

so what’s your point with the above? 💀

viral badge
#

ruins the experience for tiny server owners but i suppose thats just another flaw with discord 🤷‍♂️

hushed robin
#

what

neon leaf
slender wagon
compact pier
neon leaf
#

it works on windows but uses \ instead of /

#

so In my case where im parsing paths to urls it breaks

quartz kindle
compact pier
#

can't your bot access server name anymore?

#

by using client.guilds

compact pier
deft wolf
#

Maybe the server is not cached

compact pier
deft wolf
#

Then you should normally be able to access the server name

#

Or you'll have to fetch those servers

ocean flint
viral badge
#

idk how strict it is we just wanted to be sure lol

lyric mountain
#

or join too many servers in a small timeframe

solemn latch
#

theres a lot of ways to get flagged from what discord has hinted at yeah

#

if you're doing one check it doesn't really help imo. Its possible your second bot would have been flagged if it was in the circumstance the first one was in.

hushed robin
#

and it was verified with no issues

knotty quartz
#

Hi

#

I forgot how to do if(user has role) {

#

is it ```js
if(interaction.user.id.hasroles('role') {
//command
}

lyric mountain
#

roles.includes

#

user.id is a string btw

#

when in doubt check the docs

solemn latch
#

.user is a user, which doesnt contain roles either.

lyric mountain
#

ah, that too

knotty quartz
deft wolf
#

No

lyric mountain
#

"a bit" is an understatement

#

read the next 2 comments after the one u pinged

knotty quartz
#

ohhh

tulip ledge
#

Anyone knows what its called to have a big field of names or numbers or something like that and you highlight a ton of them to form another word?
or how to do it?

wheat mesa
knotty quartz
wheat mesa
#

Brotha just look up “discord js documentation”

knotty quartz
#

Also I tried:

if(interaction.member.roles.include('1065733315849617528')) {
wheat mesa
#

Well once again .include is not a method, it’s .includes

wheat mesa
#

roles.cache.has() is probably what you’re looking for anyways

#

Or something like that, not entirely sure what you’re trying to do

sudden geyser
#

just look up the docs

wheat mesa
#

^^

knotty quartz
#

Thanks Waffle!

solemn latch
#

A big field of names is what I would call that

wheat mesa
#

An anagram?

tulip ledge
#

but I can't seem to get the function to work

lyric mountain
#

I don't even know what ur talking abt

neon leaf
#

is there any way to trick nodejs into thinking im on a different platform? so that for example the path package works like it would on windows with \ instead of linux /

tulip ledge
#

essentially I have a list of prime numbers now what I want to do is get a string of a certain width with an arbitrary amount of random prime numbers eg a string of length 7 would look like: "11 13 2" or "101 499" or a prime number of 7 long could also work for example for example but I can't seem to get it to work

lyric mountain
wheat mesa
#

Yeah that’s the OS itself

lyric mountain
#

There's a platform-agnostic way tho

#

By using Path

#

Which will convert your input to the proper format

wheat mesa
#

(As I said to him earlier but I was turned down)

lyric mountain
#

I 'member

chrome orbit