#development

1 messages · Page 1570 of 1

eternal osprey
#

it does not return anything

#
{
    "1721138": {
        "ability": "Corrosion",
        "iv": 88,
        "stamina": 96,
        "hp": 338,
        "speed": 50,
        "attack": 16,
        "defense": 28,
        "specialattack": 234,
        "specialdefense": 307,
        "id": 367,
        "name": "Huntail",
        "level": 18,
        "catchChance": 0.8333333333333334,
        "spawnId": 4236884,
        "owner": "345138133429649408",
        "catchTime": "01/18/2021 9:49 PM",
        "nickname": ""
    }```this is how the object looks
tight plinth
#

anyway, I have a bot that sends some things daily, and i want the user to easily edit the time where the bot will send the things like this:

User input: `!settings time 7AM`
Bot output: Successfully set the time of when I will send the facts to **7AM CET**!```The timezone will be CET no matter what, and i want the bot to set something like `Date.now() + time until 7AM CET` to it's db. How can I make that happen?
#

@eternal osprey I would not recommend using JSON as a database personally, as it can easily break and/or be corrupted

eternal osprey
#

But i need to do this in json tho.

tight plinth
#

o

lament rock
#

If you absolutely need something high level, use sqlite

lament rock
tight plinth
#

minutes

#

(thanks google) I guess js Date.parse("5/4/2021 7:30 AM") works, but im pretty sure the user will be able to abuse it and set the time to 69 years somehow

lyric mountain
#

then just use regex to match keywords

lament rock
#

Okay. I think it would be within reason to have a single interval which queries the database every minute to see if there are any reminders meant to be sent within that minute.

The alternative would be to store intervals in a Map keyed by user IDs and clear the Interval then re-set.

I think having possibly a bunch of timers ticking on a single thread wouldn't be the best idea. That being said, I would go for the query database option

eternal osprey
#
let last1 = Object.values(mons).find(m => m.name === `${found.name}`)
                        fs.writeFileSync("./mons.json", JSON.stringify(mons), e =>{
                            //Handle error
                             last1.owner = `${targetMember.id}`; //Setting the owner ID
                            });
                                ```i am trying to change the owner ids.
#

it is not working tho

humble rock
#
module.exports = class BaseEvent {
    name;
    
    constructor(name) {
        this.name = name;
    }

    async run(client, ...args) {};
}

i got this error:
TypeError: Class extends value undefined is not a constructor or null

lament rock
#

declaring class properties is only necessary in TypeScript

humble rock
#

ok

#

nope

#

it still doesn't work

lament rock
#

Well. The error doesn't correspond with that code block. Look at the stack to see where the error is coming from. The issue is trying to extend something which is undefined or null or doesn't have any constructor signatures

humble rock
#
const { BaseEvent } = require('../Bases/BaseEvent');

module.exports = class Ready extends BaseEvent {
    constructor() {
        super("ready")
    }

    async run(client) {
        const guildcount = client.guild.cache.size
        const username = client.user.username

        console.log(`${username} is now ready!`)
        client.user.setActivity(` over ${guildcount}`, { type: 'WATCHING' })
    }
}
lament rock
#

do not deconstruct the require
Export is of type BaseEvent
not { BaseEvent: typeof BaseEvent }

humble rock
#

can you modify as well my text

lament rock
#

All you need to change is the require statement. The export of that file is a class. Not an Object holding the class instance

opal plank
#

yo, what does discord use for colors again?

#

its not hex

lament rock
#

Idk if it's rgb

opal plank
#

i forgot the number name for the values

#

its not rgb

lament rock
#

figured

opal plank
#

its something else, but i forgot how to search color number

#

it just says color code

#

but whats the actual name of those color codes

#

its not hex for sure, not rgb either

lament rock
#

Discord.js logic to parse strings to number seems to suggest it's hex.

Their use of 0xffffff is hex

opal plank
#

ugh thats annoying cuz the raw api uses integerrs

#

not hex

prime fox
#

uhhh

#

someone help

#

for some reason my site only loads on edge

lament rock
prime fox
prime fox
#

nvm it was the service-worker script

lament rock
# opal plank ty ❤️

mhm. I guess I should clarify that that was converting hex to what Discord accepts. Idk the inverse of that operation

fierce ether
#
     await reaction.message.reactions.remove(matchEmojis[3])``` whats correct way of removing a reaction by id?
opal plank
lament rock
#

Message.reactions is of type ReactionManager

fierce ether
#

thx

keen bison
#

my bot uses heroku redis as a cloud storage system

#

and im on 9 of my 50 alloted MB
and its throwing a memory full error

#

i dont know why

#

and everything ive done to fix it deosnt work

#

help

#

;(

nocturne geode
#

anyone know why when i type !help in discord nothing actually happens?

lyric mountain
keen bison
#

yes

dusky sundial
nocturne geode
#

im not sure

lyric mountain
#

it's reaching the max memo

dusky sundial
lament rock
#

50MB alloc AlienPersianDerp

nocturne geode
#

i cant see the console for the bot though

dusky sundial
#

Why not?

nocturne geode
#

i dont know how

keen bison
dusky sundial
#

How are you running the bot then?

lament rock
#

Pretty sure Redis instances and application dynos are separate

lyric mountain
#

the bot itself also uses memory

keen bison
#

redis.exceptions.ResponseError: OOM command not allowed when used memory > 'maxmemory'.

nocturne geode
#

im running it of heroku and before i could see the console now its changed and im not sure where to find it

lyric mountain
#

your redis is sharing memory with your bot

#

it's expected to reach memo limit

dusky sundial
#

Well, I'm pretty sure .setTitle() is supposed to take a string

keen bison
#

it shouldnt bcause the bot itslef is quite small

#

its like 50kb

lyric mountain
#

don't see file size

#

file sizes are irrelevant

nocturne geode
#

oh yeah it should and i dont have a string

lyric mountain
#

even a small bot could use 4GB of memory

dusky sundial
#

C-create one? upsidedown_thinking

lament rock
#

I would love to see a Discord bot which only takes 50kb of mem

lyric mountain
#

that's not a bot, that's a microprocessor KEKW

lament rock
#

I probably couldn't even write a gateway lib which fits in that memory space

lyric mountain
#

think of bots as being balloons

#

when you use it it inflates

nocturne geode
#

it works now ty for the help

dusky sundial
#

You should figure out how to see the terminal, otherwise you're gonna have a really hard time

nocturne geode
#

yeah ill try to figure it out

lyric mountain
#

heroku's teminal is in the log tab

nocturne geode
#

wheres the log tab?

lyric mountain
#

dropdown menu on the top right

keen bison
#

it doesnt use that much mem

nocturne geode
#

i think mines different or something

proven lantern
#

I think i found a discord bug. when someone uses a one time use invite link to a voice channel they can always view the channel even if i remove their view permission.

dusky sundial
keen bison
#

yes but well within limits

#

still returning the oom memory error

quartz kindle
#

your redis is 50mb or 500mb?

lament rock
#

50mb is extraordinarily small for a redis instance

quartz kindle
#

wtf

#

the free version is only 25mb lmao

#

also fucking 15 bucks a month, and guess how much you get

#

fucking 50mb

#

LMAO

astral forge
#

I need help, my commands arent responding

lament rock
#

Jesus christ

#

What a scam

astral forge
#

bruh how

quartz kindle
#

fucking 1gb redis instance costs 200 bucks per month

#

LMAO

astral forge
#

Can someone help please?

quartz kindle
#

guess how much 100gb costs

#

(their max plan)

astral forge
#

??

lament rock
#

Tell me the number

quartz kindle
lament rock
#

Holy fucking shit

astral forge
#

can anyone help me? please?

quartz kindle
#

show code

#

and errors/logs

astral forge
#

thats the thing.

#

there is no error

#

it just wont respond to the command

fierce ether
#

trying to create a convert time function js convertTime(time){ const m = moment(time) return m.toNow(); } using ?time 2d

#

how am i going wrong?

#

always returns in a day

astral forge
#

oops

lament rock
#

So, then it's a logical issue with finding a command and calling the function to execute

quartz kindle
#

hence "show code"

astral forge
#

theres the code

#

I need help with this issue, my bot isn't working and it's not Saying the Logs

quartz kindle
#

hastebin pls

astral forge
#

well yea

#

like one or two things in there are from pastebin

#

but its been working fine

#

until now idk why

lament rock
#

He meant put the code in hastebin so we can see it. We don't wanna download a text file to help you

astral forge
#

oh LMFAO

#

lmao i just exposed my self

#

then

lament rock
astral forge
#

eh idc im a begineer so

alpine coyote
#

Hey

quartz kindle
#

"i copied this code from internet, why not work"

astral forge
astral forge
#

so

#

idk what u mean

quartz kindle
#

then why it doesnt anymore?

#

did you change anything

astral forge
#

nope

lament rock
#

have you tried restarting the process

astral forge
#

yes

#

like 100 times

#

and ive kicked the bot

#

and made it rejoin

#

still does not work

lament rock
#

Lol okay

astral forge
#

oh did i post it in the wrong thing lmao

#

or will that work too

#

i did hatebin instead of hastebin on accident lol

quartz kindle
#

doesnt matter, as long as we can read the code without having to download anything

#

i dont use python but i remember someone saying you shouldnt mix commands with events

#

try removing the message event and see if the other commands work

#

also, is the bot even logged in?

astral forge
#

when did i mix commands and events

lament rock
#

You're writing annotations for both client commands and events

astral forge
#

where

#

what line

lament rock
#

You literally have written
@client.command() and @client.event
Those are annotations for client commands and events

astral forge
#

oh right here?

lament rock
#

Yeah. And also the message event

astral forge
#

so should i put the event before the command

slate rose
#

Hello, So am currently trying to animate the Creators avatars on my bots page on top.gg. I need some help cause I am not mentally there with css. I tried a few different things and they failed 1105_prez_cry . If you know how to do this please dm me cause i'm peepoDumb .

lament rock
#

Don't mix them in the same file is what the suggestion looks like

astral forge
#

so like this?

lament rock
#

css animations HideThePain

astral forge
#

like this?

lament rock
#

No. Try putting them in different files or remove the events and test

astral forge
#

oh

slate rose
lament rock
slate rose
#

Pain

#

Hello, So am currently trying to animate the Creators avatars on my bots page on top.gg. I need some help cause I am not mentally there with css. I tried a few different things and they failed 1105_prez_cry . If you know how to do this please dm me cause i'm peepoDumb .

#

Please and thanks

astral forge
#

why is it giving me errors

#

then

#

if i put it in a different file

lament rock
#

well. What are the errors

astral forge
#

lol

#

wait a minute dont clown me

#

im new to python

#

just tell me what im doing wrong

slate rose
lament rock
#

client isn't defined. You'll have to export client to that file somehow

astral forge
#

oh wait

slate rose
#

So I just get ignored but this guy gets help 4_sad

lament rock
#

I'm not a front end developer

slate rose
lament rock
#

For a good reason, too

astral forge
#

got it

slate rose
#

k

astral forge
#

whenever i run the event code

#

it just crashes

lament rock
#

lmao

astral forge
#

what

lament rock
#

Just try removing the event code temporarily. Only run the client commands to see if they work

astral forge
#

this is my event code

#

POG

#

it works without events

#

then how am i supposed to get events

#

i found out whats wrong

#

mixing them is fine

#

or atleast it works

#

but there was one that messed everything up lmao

quartz kindle
#

i remember someone saying that if you use the commands extension, then it will create an internal on_message to handle the commands for you

#

and if you write your own on_message you're basically disabling the one responsible for the commands

astral forge
#

lol

#

what should i replace it with

#

??

slate rose
#

Helllo, so I need help with my bot

#

V

#

this is my glitch project

#

my bot does not want to go online

astral forge
#

LMFAO

#

code

#

oh wait

#

oh nvm i dont know js

#

i used to

slate rose
#

rip

#

bruh

astral forge
#

import discord

#

is what im used to lmao

#

i fixed the mod mail thing btw

worn siren
#

For some reason, this returns true for both me (boosting for 5 months) and my friend (boosting for one week)
I'm trying to make it return true when they've been boosting for more than a week, and false if not.

fierce ether
#
  const enabled = player.plugins.banned.enabled
    const time = player.plugins.banned.time
    if(enabled == true && Date.now - time >= 0) return user.send(bannedFromMatchmaking)``` this would return if enabled and the time is still not finish correcT?
opal plank
#

@fierce ether or.... you could just ```ts
if(enabled && Date.now() > time) //do stuff

quartz kindle
#

if premiumSinceTimestamp > Date.now() - 1week

hearty remnant
#

So due to the nature of globalchat I am working on global bans

thorny abyss
#

eyo anyone can help me on how to avoid TypeError: unexpected type, use Uint8Array in discord js?

mellow kelp
#

you're passing a wrong type to an argument or something

thorny abyss
#

It seems like it is thrown inside the api from time to time but it always crashes the bot when it happens

#

like once every month

thorny abyss
#
TypeError: unexpected type, use Uint8Array
at checkArrayTypes (/var/www/git.jmk.cloud/node_modules/tweetnacl/nacl-fast.js:2165:13)
at Object.nacl.secretbox.open (/var/www/git.jmk.cloud/node_modules/tweetnacl/nacl-fast.js:2190:3)
at PacketHandler.parseBuffer (/var/www/git.jmk.cloud/node_modules/discord.js/src/client/voice/receiver/PacketHandler.js:61:36)
at PacketHandler.push (/var/www/git.jmk.cloud/node_modules/discord.js/src/client/voice/receiver/PacketHandler.js:93:25)
at Socket. (/var/www/git.jmk.cloud/node_modules/discord.js/src/client/voice/networking/VoiceUDPClient.js:131:76)
at Socket.emit (events.js:315:20)
at UDP.onMessage [as onmessage] (dgram.js:919:8)
#

heres the whole message if you need it

mellow kelp
#

does it say the line in your code where it went wrong?

thorny abyss
#

its not in my code its in the node module thats the problem

mellow kelp
#

hm

#

no idea then

thorny abyss
#

aight thanks anywayys

hearty remnant
#

@thorny abyss I have a script to auto restart on crash

#

Want it

thorny abyss
#

sure

quartz kindle
#

either your audio stream got corrupted at some point, or it tried to play an invalid file

thorny abyss
#

That actually makes sense thanks alot!

#

Only thing thats weird: Shouldn't the stacktrace go up to the method that triggers the playing?

#

meaning up to my code?

quartz kindle
#

no

#

because the error is not caused by the triggering

thorny abyss
#

i see

quartz kindle
#

its caused in the middle of the stream, and by then the code that started the playing is already long gone

thorny abyss
#

makes sense im gonna take a look at the files then

#

thanks

agile lance
#
let money = db.all().filter(data => data.ID.startsWith(`bal`)).sort((a, b) => b.data - a.data)
        money.length = 10;
        let finalLb = "";
        for (var i in money) {
          
          finalLb += `**${money.indexOf(money[i])+1}.** | ${money[i].ID.slice(25)} - \`${money[i].data}🪙\`\n`;
        }
        
        
        const embed = new discord.MessageEmbed()
        .setTitle("Global Leaderboard")
        .setColor("#ff0000")
        .addField(`Leaderboard`, finalLb, false)
        message.channel.send(embed);
}```

Issue: Returns embed that is messed up [shown below].
quartz kindle
#

money[i].data is an object

#

you cant concatenate it like that

agile lance
#

how do i turn that into the amount of money the user has?

quartz kindle
#

either concatenate the individual properties of the object, or serialize it to JSON

agile lance
#

using quick.db is a pain

#

Why does money[i].ID.slice(25) return undefined?

quartz kindle
#

console.log(money[i].data)

agile lance
#

Ok

quartz kindle
#

console.log ID as well

#

you're slicing 25 characters off of it, so if the ID is anything smaller than 25 characters , it will basically make it empty

agile lance
hollow stump
#

Anyone have any idea how to (from the discord API/endpoints) have a wrapper see if channel is nsfw channel?

agile lance
#

Thats what money[i].data returns

#

If I slice none will it return the full user id?

quartz kindle
#

see, data is an object that contains 2 ids and 2 values

#

which of those do you want to show in the embed?

agile lance
#

User ID and the bal

#

So like

#

#1 | USER ID - USER BAL

#

I need it to show all people though for the leaderboard

quartz kindle
#

yes but you have 2 users in that data

#

for some reason

agile lance
#

Yeah as 2 people have used my bot

quartz kindle
#

yes, but arent ids supposed to be saved in money[i].ID?

agile lance
#

In quick.db the ID is the name of the db

#

So if I logged sau

#

db.all();

#

It will look like

#

{
ID: 'bal',
data: { user id: bal, user id2: bal2 }
}

quartz kindle
#

so then you want to loop over data, not over money

agile lance
#

Its easier to show you 1 sex

#

sec*

quartz kindle
#

yes but you got your for loop wrong then

limpid moth
#

I want my bot to determine wether or not the message sent starts with the text "owo" and if it does then search through the array "list" if the message has any one of the values of the array

    const msg = message.content.toLowerCase();


    // Counting code
        if (msg.startsWith('owo')) {

            const afterowo = msg.slice(3).trim().split(/ +/);

            for (let i = 0; i < list.length; i++) {

                if (afterowo === (list[i])) {
                    message.channel.send('That was a command!');
                }
                else {
                    message.channel.send('That was not a command');
                }
                break;

            }

    }
quartz kindle
#

or are there multiple things with ID bal?

agile lance
#

Only 1 thing has id bal

quartz kindle
#

then get the thing with id bal, then loop over its data

#

not over itself

#

for(i in money.data)

agile lance
#

Ok

#

Is that all to change?

#

or do I have to change everything to money.data

quartz kindle
#

everything

#
for(let id in money.data) {
  `${id} - ${money.data[id]}`
}
agile lance
#

Ok

#

So finalLb += `**${money.indexOf(money[i])+1}.** | ${money[i].ID.slice(25)} - \`${money[i].data}🪙\`\n`;

quartz kindle
#

also dont use filter

#

use find

agile lance
#

Alr

quartz kindle
#

and no need to sort

#

if there is only one bal

agile lance
#

I thought I need sort for highest to lowest?

quartz kindle
#

data is not an array, its an object

agile lance
#

oh

quartz kindle
#

objects are not ordered

#

if you want to sort data, you have to convert it to array

agile lance
#
          
          finalLb += `**${money.indexOf(money[i].data)+1}.** | ${money[i].data.ID} - \`${money[i].data}🪙\`\n`;
        }```
#

Will this work?

quartz kindle
#

no

agile lance
#

Ahh I dont understand at all

quartz kindle
limpid moth
#

Ok

agile lance
#

Nothing seems to work for my leaderboard

#

I’ve used source code with a separate instance and still failed, idk whats wrong

quartz kindle
#

your code is simply incorrect for what you want to achieve

agile lance
#

I’ve spent like

#

40+ hours on it

#

And cant get it right

quartz kindle
#

first of all, if you have only 1 bal, then you should store is as a key

#

db.set("bal", { user1: balance1, user2:balance2, etc... })

agile lance
#

If I switch to say, mongoDB, and use zapmongo’s built in leaderboard function, will that work better?

quartz kindle
#

then you access it using db.get() instead of db.all()

lyric mountain
#

If it was only sql...lul

quartz kindle
lyric mountain
#

Select * from user order by balance desc

agile lance
#

mongo is probably better anywho

quartz kindle
#

probably

#

but your issue is not quick.db

#

its your code lol

agile lance
#

yeah but mongo db has a built in lb function

#

Lol

quartz kindle
#

which you can accomplish with 2 lines of code

lyric mountain
#

Built-in stuff are kinda dangerous I'd say

#

Like, you're stuck to whatever method it uses

quartz kindle
#

lets say you have the object bal like this ```js
obj = {
ID: "Bal",
data: {
"345346346": 1,
"498376083": 50
}
}

agile lance
#

yeah

quartz kindle
#
sortedarray = Object.entries(obj.data).sort((a,b) => b[1] - a[1])
#

that will give you this

#

[["4545345", 50], ["45394579", 1]]

#

or the other way around, i never rememeber which way is descending or ascending

#

its just a matter of switching a and b

lyric mountain
#

It'll be descending ig

quartz kindle
#

then you can simply do ```js
for(let user of sortedarray) {
field += ${user[0]} - ${user[1]} \n
}

agile lance
#

Yeah how will I make it show what rank they are?

lyric mountain
#

Indexed for loop

agile lance
#

Or for say, add a medal next to rank 1?

#

so like

quartz kindle
#

like the top 3 have medals?

agile lance
#

for(let i; i < user.length; i++) {
// code
}?

quartz kindle
#

yes

agile lance
quartz kindle
#

you can do that

#

for(let i = 0; i < sortedarray.length; i++)

agile lance
#

Is “Object” a built in js thing?

quartz kindle
#

then instead of user[0] and user[1], you have to do sortedarray[i][0] and sortedarray[i][1]

#

yes

lyric mountain
#

So it's the deepest u can go in classes' hierarchy

quartz kindle
#

Object.keys() creates an array or keys
Object.values() creates an array of values
Object.entries() creates an array of key,value pairs

agile lance
#

So I can basically do the Object.entries(db.all().find(dta => dta.ID == "bal")).sort((a, b) => a[1] - b[1]);

quartz kindle
#

yes

lyric mountain
#

B - A

agile lance
#

alr

#

ill try it

#

ill do medals later. i just want the lb to function

#

Code is let sorted = Object.entries(db.all().find(dta => dta.ID == "bal")).sort((a, b) => a[1] - b[1]); let field = " " for(let user of sorted) { field += `${user[0]} - ${user[1]}` } message.channel.send(new discord.MessageEmbed() .setTitle("**Global Leaderboard**") .setDescription(field) )

quartz kindle
#

Object.entries(db.all().find(dta => dta.ID == "bal").data).sort((a, b) => a[1] - b[1]);

agile lance
#

Ohh

#

Forgot a key part

quartz kindle
#

use \n for newlines

agile lance
#

Ok

#

Can I use like \tab to separate the user id from the bal, or just keep it with -

quartz kindle
#

not sure if tab will work, you can try

agile lance
#

How can I limit it?

#

can I like use a .length and set that to a fixed amount?

#

To show say, 10 people at max

limpid moth
# quartz kindle both afterowo and list are arrays, so you cant compare them like that. use array...

Must have done something wrong :/

    const msg = message.content.toLowerCase();
    const afterowo = msg.slice(3).trim().split(/ +/);
    function checkCommand() {
        return afterowo === list;
    }
    // Counting code
        if (msg.startsWith('owo')) {

            if (list.some(checkCommand) === true) {
                message.channel.send('That was a command.');

            }
            else if (list.some(checkCommand) === false) {
                message.channel.send('That was not a command');
            }


    else if (msg.includes('owo')) {

        message.channel.send('👍');

    }
quartz kindle
#

you can truncate the array by overriding its length

#

sorted.length = 10

limpid moth
quartz kindle
#

you're missing the includes, and also the parameter for some

agile lance
pale vessel
#

If the array is smaller than the length you set it to, you'll have <empty item> filling the rest

agile lance
#

i also made it show tag by fetching the user through client’s cache and returning user.tag

agile lance
quartz kindle
#

you can

#

but its easier to just put an if

#

if(sorted.length > 10) sorted.length = 10

agile lance
#

Okay

#

I could do like

#

o yea

limpid moth
quartz kindle
#

.some iterates over each item of the array

#

so array.some(item => do something with item)

#

for each item of the array, you want to check if it exists in the other array

agile lance
#

it randomly stopped working

quartz kindle
#

so array.some(item => otherarray.includes(item))

agile lance
#

Cannot read property of 0 of undefined

#
sorted.length = 10
let field = " ";
for(let user of sorted) {
field += `User: ${user[0]} - Balance: ${user[1]}\n`
}
message.channel.send(new discord.MessageEmbed()
.setTitle("**Global Leaderboard**")
.setColor("BLUE")
.addField("**Balance Leaderboard**", field)
)```
limpid moth
#

Then you need to define the thing that is undefined

agile lance
#

Uhm

#

It isnt that easy

#

I’m pulling 0 from a array

#

Index 0

jolly mortar
#

does anyone know how to make the bot send a message as soon as someone invites it to their server

dusky sundial
#

Could you use php to check if a specific python process is running?

quartz kindle
#

if(sorted.length > 10) sorted.length = 10

agile lance
#

Ohhh i forgot

#

My bad

jolly mortar
#

i got it to send a plain message but when i try to use a embed it dosnt work anymore

agile lance
#

I was like "Why isnt this working??"

dusky sundial
jolly mortar
#

lemmi find it rq

#
      .setTitle("test")
      .addField("test")
  .setTimestamp();
    message.channel.send(embed);
  }```
#

is what i put after the code that makes it send a message when its added

dusky sundial
#

Does it give you any errors when you try it?

jolly mortar
#

no

#

its just that it dosnt send after the 2nd time

agile lance
#

client.users.cache.get(user[0]).tag is returning undefined

#

user[0] returns a id

#

idk if this will work but I can try client.users.cache.find(u => u.id == user[0]).tag

dusky sundial
agile lance
#

nope neither works

jolly mortar
# dusky sundial Could you show the code for the entire event?
let defaultChannel = "";
    guild.channels.cache.forEach((channel) => {
      if(channel.type == "text" && defaultChannel == "") {
        if(channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
          defaultChannel = channel;
        }
      }
    })
 let embed = new Discord.MessageEmbed()
      .setTitle("test")
      .addField("test")
  .setTimestamp();
    defaultChannel.send(embed);
   })```
pale vessel
#

you should check if defaultChannel exists before sending the message

dusky sundial
jolly mortar
#

yea i updated it

pale vessel
#

Also, instead of using forEach, just use collection.find()
guild.channels.cache.find(x => x.type == "text" && x.permissionsFor(guild.me).has("SEND_MESSAGES"))

#

much more simpler and it won't continue looping once it finds an element that matches the filter

jolly mortar
#

it works now yay

#

ty

agile lance
#
{
  '737918277866487928': 400,
  '705731402972528690': 55474,
  '733912649418670080': 25,
  '752770336591839272': 150,
  '586391264350699551': 150,
  '719775900337700876': 50,
  '804079538257657866': 1000,
  '803199405598572554': 50,
  '807170169474383895': 425,
  '803711637105278978': 225,
  '804779119791046657': 50,
  '802096152295112735': 175,
  '781055840488259604': 50
}
#

Is that a object

#

or an array?

dusky sundial
#

Pretty sure that's a json object

agile lance
#

Okay ty

opal plank
#

rule of the thumb

dusky sundial
#

surround it with [] to make an array

opal plank
#

starts with {} is object

#

[] array

#

() {} or () => {} function

agile lance
#

okay

#

How do you tell if a user can’t be dm’d

#

with .catch it doesnt reply anything like I tried

#

.catch(err => message.reply('can not dm.\n\n Back end error: '+err);

pale vessel
#

You can only catch it

agile lance
#

It logs the error but doesnt reply to the user running the cmd saying it cant be dms

opal plank
#

WHERE did you put that catch ?

#

if tis logging the error, you either didnt give the full snippet or its THROWING the error(not logging)

agile lance
#

I put it right after it sends the user so it says

opal plank
#

show full snippet

agile lance
#

message.author.send(...).catch(err => message.reply("You have dms turned off!"))

opal plank
agile lance
#

and in console it says

#
    at RequestHandler.execute (/home/runner/Augusts-bot-PRIVATE/node_modules/discord.js/src/rest/RequestHandler.js:154:13)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async RequestHandler.push (/home/runner/Augusts-bot-PRIVATE/node_modules/discord.js/src/rest/RequestHandler.js:39:14)
(node:499) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)```
opal plank
#

then what is that thing above?

#

.catch(err => message.reply('can not dm.\n\n Back end error: '+err);

agile lance
#

that was what i tried the first time

#

it disnt work

#

so i changed it

#

still didnt work

opal plank
#

use a try/catch with await then

agile lance
#

ok

solemn leaf
#

Errwinn

#

Pleasee

#

Dont teach bad habits

opal plank
#

huh?

solemn leaf
#

((err) plsss

opal plank
#

what bad habits?

#

they arent even using the error though

solemn leaf
#

Then just do

#

()

opal plank
#

¯_(ツ)_/¯

#

too tired for that today

#

lets just say after this major rewrite my brain is barely functioning anymore

solemn leaf
#

Dont rewrite your brain

vale raptor
#

(discord.js) anyone know more specifically what "DiscordAPIError: Missing Access" might mean in the context of a guild fetch promise being rejected? it seems to happen at random times, with random guild ids, causing some fetches to fail for a reason I can't figure out.

agile lance
#

means it has no access to the server/channel your fetching

#
if(sorted.length > 10) sorted.length = 10
let sorted2 = Object.entries(db.all().find(dta2 => dta2.ID == "level").data).sort((a, b) => b[1] - a[1])
if(sorted2.length > 10) sorted2.length = 10
let field = " ";
let field2 = " ";
for(let user of sorted) {
field += `User: ${client.users.cache.find(u2 => u2.id == user[0]).tag} - Balance: ${user[1]}\n`
}
for(let user of sorted2) {
field2 += `User: ${client.users.cache.find(u => u.id == user[0]).tag} - Level: ${user[1]}\n`
}
message.channel.send(new discord.MessageEmbed()
.setTitle("**Global Leaderboard**")
.setColor("BLUE")
.addField("**Balance Leaderboard**", field)
.addField("**XP Leaderboard**", field2)
).catch(() => null)```

Error: Cannot read property of tag of undefined.

The code worked fine until I added the xp lb, whats the issue?
opal plank
#

likely you trying to fetch a guild that is still cached but they already removed your bot from it

vale raptor
#

no, I know it's happening in guilds that are using it currently. I've had it fail to fetch my own guild from the cache.

opal plank
#

then no, im not sure why that would ever happen

vale raptor
#

strange, it seems to happen in bursts too. sometimes there will be no errors for hours, then suddenly 3 people using the bot will throw 3 separate missing access errors.

#

I know this is too little information to really diagnose, I guess I'm just hoping someone else has experienced the same thing.

lyric mountain
#

Maybe some command is trying to access a channel it doesn't has access to

#

Also dm will throw that error if it's closed iirc

vale raptor
#

it happens in channels that I know the bot has access to, and the method throwing the error is client.guilds.fetch.

#

but it doesn't happen consistently in any channels

agile lance
#

pull from cache

#

and try to use .find not .catch

vale raptor
#

are you suggesting I check the cache first, then if nothing comes back, try .fetch? is that not what fetch already does?

agile lance
#

client.guilds.fetch is not a function

#

you have to fetch from cache

earnest phoenix
#

uh

#

no

vale raptor
#

client.guilds.fetch is definitely a function

#

I've been using it

earnest phoenix
#

cache is a collection

mellow kelp
agile lance
#

it always told me it wasnt

#

so i always use .cache.fetch

vale raptor
#

the cache is a collection, and I'm not seeing a fetch method on the collection type. are you sure?

agile lance
#

oh wait

#

im mixing .fetch up with .find

#

my bad

vale raptor
#

plus if I just checked the cache, I'd still have to hit the API in some cases when the guild hasn't been cached recently.

mellow kelp
#

bruh

slate oyster
#

I successfully got Chatlink to double up as a bridge on the alpha version of my bot!

sour warren
#

is it a website?

slate oyster
sour warren
#

oh

#

whats that your on

slate oyster
sour warren
#

ok

lusty quest
#

you could use webhooks to mimic the user who send the message. the user will still have the Bot tag but also you could have the users PFP and Nick

sour warren
oak cliff
#

-faq 13 @sour warren

gilded plankBOT
sour warren
#

wrong website

pale vessel
#

You can't

#

Don't you need a user token for that?

#

Which means that you can't since it counts as self botting

#

It's not documented in docs, only the GET operation is

summer torrent
#

wait you can't change vanity url of server with bot?

pale vessel
#

Have you tried this

#

br

#

Try it ig

#

It might still work even if it's not documented

#

Also, it's body, not payload

#

Also, the method should be PATCH I think

#

Not POST

earnest phoenix
#

isn't the vanity url only modifiable by the guild owner

summer torrent
#

nope

earnest phoenix
#

huh interesting

pale vessel
#
fetch("https://www.discord.com/api/v6/guilds/762359120031907871/vanity-url", {
        method: "PATCH",
        headers: { "authorization": `Bot ${client.token}`, "content-type": "application/json" },
        body: JSON.stringify({ code: "test458" })
});```might work, can't test it
#

Since you use Discord.js you can just use js client.api.guilds[<guiild id>]["vanity-url"].patch({ data: { code: <new vanity> } });

#

Yes

#

yes

agile lance
#

How do I sort a object in alphabetical order

summer torrent
#

what lang

agile lance
#

js

#

Also how do I delete a specific thing in a quick.db database?

#

Like I have a notes command

#

How do I delete a specific note

summer torrent
#

.delete(...)

agile lance
#

that clears the whole db I believe

#

according to the docs atleast

terse jasper
#

in ... u write what u wanna delete

#

i think

agile lance
#

i need to clear only 1

summer torrent
#

for example

db.set("mynotes_1", "hello world")

db.delete("mynotes_1")
#

oh

terse jasper
agile lance
#

hm

#

i can to do db.delete(notes, flitteredNote)

earnest phoenix
#

can i send a code i can't understand what's wrong?

agile lance
#

sure

earnest phoenix
#

const Discord = require('discord.js');
module.exports = {
name: '8ball',
cooldown: 6,
description: '8Ball',
permissions: 'SEND_MESSAGES',
execute(client, message, args) {
if (!message.length == 4) {
return message.reply('Please ask a valid question')
} let responses = [
'Maybe.',
'Certainly not.',

    ];
        let response =
            responses[Math.floor(Math.random() * responses.length)];
    const Embed = new Discord.MessageEmbed()
        .setColor('RANDOM')
        .setTitle('8ball')
        .setAuthor('SD-14 Bot', '')
        .setDescription('Gives A Answer As Yes/No')
        .setThumbnail(\`${message.author.avatarURL({ dynamic: true })}`)
        .addFields(
            { name: \`My Answer\`, value: \`${responses[response]}` }
        )
        .setTimestamp()
        .setFooter(\`Requested By: ${message.author.username+message.author.id}`);

    message.channel.send(Embed);
}

};

summer torrent
#

use codeblock please

earnest phoenix
#

ok

#

1 sec

#
const Discord = require('discord.js');
module.exports = {
    name: '8ball',
    cooldown: 6,
    description: '8Ball',
    permissions: 'SEND_MESSAGES',
    execute(client, message, args) {
        if (!message.length == 4) {
            return message.reply('Please ask a valid question')
        } let responses = [
            'Maybe.',
            'Certainly not.',

        ];
            let response =
                responses[Math.floor(Math.random() * responses.length)];
        const Embed = new Discord.MessageEmbed()
            .setColor('RANDOM')
            .setTitle('8ball')
            .setAuthor('SD-14 Bot', '')
            .setDescription('Gives A Answer As Yes/No')
            .setThumbnail(`${message.author.avatarURL({ dynamic: true })})
            .addFields(
                { name: \My Answer`, value: `${responses[response]} }
            )
            .setTimestamp()
            .setFooter(\Requested By: ${message.author.username+message.author.id}`);

        message.channel.send(Embed);
    }
};
earnest phoenix
#

I am new to JavaScript

agile lance
#

how do you slice the first character of a string?

earnest phoenix
#

slice(0)

agile lance
#

ty brutha

earnest phoenix
#

wut?

pale vessel
#

slice(1)

earnest phoenix
#

^

#

even better

#

index the string

near stratus
agile lance
#

How can I remove this comma

#

infront of every not besides top

earnest phoenix
#

isn't the first index 0?

agile lance
#

idk

summer torrent
#

show code

pale vessel
summer torrent
#

you are doing join(",") probably

kind crescent
earnest phoenix
agile lance
agile lance
kind crescent
agile lance
#
  .setTitle('Your Notes')
  .setColor('RED')
  .setDescription(`${no}\n`)
  message.reply(eme)```
#

I can send my add notes command

#
if(!args.join(" ")|| n >= 10) return message.reply(`Error ID 166. Missing argument or exceeding note limit of 10!`)
message.reply('Note added.')
await db.push('note.'+message.author.id, args.join(' ')+'\n')
return db.add('notes.'+message.author.id, 1);```
lusty quest
#

you get the , bcs you display an array. idk if join() will actually remove the ,

kind crescent
#

have you tried

.setDescription(`${no.join('\n')`)
agile lance
#

no lemme try

#

works like a charm tyvm @kind crescent

kind crescent
buoyant sinew
#

or try catch error if you wont like errors in console

eternal osprey
#
    const mons = require("./mons.json");
            console.log(found.name)
            console.log(founds.name)
                        let last1 = Object.values(mons).find(m => m.name === `${found.name}`)
                        fs.writeFileSync("./mons.json", JSON.stringify(mons), e =>{
                            //Handle error
                             last1.owner = `${targetMember.id}`; //Setting the owner ID
                            });
                                let last2 = Object.values(mons).find(m => m.name === `${founds.name}`)
                                 fs.writeFileSync("./mons.json", JSON.stringify(mons), e => {
                                    
                                     last2.owner = `${firstmember}`; //Setting the owner ID
                                    });
                        ```
 hey so i am trying to change the value of key owner.
however it does not work, nor does it change anything.
```js

{
    "1721138": {
        "ability": "Corrosion",
        "iv": 88,
        "stamina": 96,
        "hp": 338,
        "speed": 50,
        "attack": 16,
        "defense": 28,
        "specialattack": 234,
        "specialdefense": 307,
        "id": 367,
        "name": "Huntail",
        "level": 18,
        "catchChance": 0.8333333333333334,
        "spawnId": 4236884,
        "owner": "345138133429649408",
        "catchTime": "01/18/2021 9:49 PM",
        "nickname": ""
    }```
this is how the object looks like
lusty quest
#

why did you still use json as a "db"

#

Object.1721138.owner did you tryed this?

eternal osprey
#

i have looped thrtough the file to find the mons which name is the same as was put in

#

and named it last1

#

and later on changing it using last1.owner = ${variable}

#

@lusty quest

lusty quest
#

yea this will probably not work with the object you provided

eternal osprey
lusty quest
#

bcs of the id

#

if you get the object as the one you send earlyer you have to use the path ive provided otherwise you wont find it

eternal osprey
#

where is that id above ability then defined?

#

I am literally confused

#
var correctID;``` it is the correctid
#

but that was never passed into the json

#

might have found the solution

#

mons.[correctID].owner is what i should call

#

found.correctID

#
 let last1 = Object.values(mons).find(m => m.correctID === `${found.correctID}`)
                        fs.writeFileSync("./mons.json", JSON.stringify(mons), e =>{
                            //Handle error
                             last1.owner = `${targetMember.id}`; //Setting the owner ID
                            });
                                let last2 = Object.values(mons).find(m => m.correctID === `${founds.correctID}`)
                                 fs.writeFileSync("./mons.json", JSON.stringify(mons), e => {
                                    
                                     last2.owner = `${firstmember}`; //Setting the owner ID
                                    });``` so it would be like this right? @lusty quest
eternal osprey
#

any help please?

foggy robin
#

I need some help im trying to do simple pages for a help command I use commando but dont like the help command it has

pure lion
#

Can we use opengraphics for our bot page?

crystal wigeon
#

hey umm are setintervals and settimeouts considered event blocks? also do they cause lag?

earnest phoenix
#

what do you mean by event blocks

earnest phoenix
#

if you're thinking of opengl... uh no

#

that's not a web library

#

there's webgl but that's only accessible via js

kind crescent
#

and the amount of lag they cause is only the same as running the specified function every n seconds

pure lion
earnest phoenix
#

nope

#

the meta tags are scraped at top level, meaning the first head element that occurs

#

(which is going to be top.gg's head element)

pure lion
#

Ah okay

#

What do you need help with?

earnest phoenix
#

...log inside of the try

#

if an error happens the flow will stop going through the try block and will jump to the catch block

fluid basin
#

.finally

#

if your language supports it

earnest phoenix
#

finally will occur regardless whether an error happened or not

fluid basin
#

hm

#

makes sense

sacred aurora
#

can i use custom dns for get request in node js?

fluid basin
#

uh yes

warm marsh
#
try
{
  // do code
  console.log("fine?");
}
catch(err)
{
  // do something with err
  console.log(err);
}```
sacred aurora
#

how

warm marsh
#

?

sacred aurora
#

that'll do

warm marsh
#

huh?

fluid basin
sacred aurora
#

the webpage im trying to scrape can't be accessed from the server

#

403 error

fluid basin
#

that means your IP is likely to be flagged and blocked, this has little relation to dns if the webpage is blocking requests from your server

#

you will either need to use a VPN or a proxy to scrape the site

earnest phoenix
#

^

sacred aurora
#

hmmm

earnest phoenix
#

you need a proxy, not a different DNS

sacred aurora
#

how can i do that

#

does axios have built in proxy option?

earnest phoenix
#

google it

fluid basin
#

you will need a proxy info

#

and there is a way to set it in axios

earnest phoenix
#

you're also probably going to have to buy a proxy list, 99.9% of free public proxies are already blocked by most major services

hoary pumice
#

What the difference between
message.reply and message.channel.send?

modest maple
zenith terrace
#

oh message.reply actually replies now

modest maple
#

idk im assuming it does

#

if it doesnt then gj d.js

zenith terrace
#

oh yea ur python arent you

modest maple
#

well mostly python but yeah

summer torrent
zenith terrace
#

no

rigid maple
summer torrent
#

client.getLevel doesn't exist

rigid maple
#

what should I do

summer torrent
#

create...??

quartz kindle
#

did you copy this code from somewhere?

summer torrent
#

^

quartz kindle
#

or did you create getLevel yourself?

#

getLevel is not part of discord.js

#

its a user-created thing

alpine coyote
#

How can I snooze Team on

pale vessel
#

Elaborate

lament rock
#

The shit you type in google vs the shit you ask in a dev question channel

#

The vanity url should always be a string

#

You need to await the fetchVanityData

const url = await guild.fetchVanityData().then(v => v.code);
pale vessel
#

destructure

tight plinth
#

what's the best module to do http requests in js

lament rock
#

not axios or node-fetch

#

I was unironically thinking of switching to the built in http lib

tight plinth
#

so what should i use

#

the built in http lib sounds like pain

lament rock
#

It is. A few people in my dev server seemed to rave over one called centra

#

I have no personal opinion on what to use

tight plinth
#

hm

#

i found one called "got"

lament rock
#

got's api sucks

opal plank
#

tim is the one that recommended got iirc

#

im personally a fan of axios

#

does most of the jobs for you

#

parsing, error cacthing/handling, intercepts shit, its everything i need tbh

lament rock
#

axios logs the errors regardless of if you put it in a try catch block or not

#

I hate that

#

What it logs is large and unnecessary info

opal plank
#

huh? i never noticed that

#

i dont think its does that ophidian

lament rock
#

Believe me. It does. I wrote a rest lib and returned errors to the user level but there was no way I could handle them in my application like I did with discord.js.

opal plank
#

its just really not doing it for me

#

do you have a test snippet?

#

either fixed in last patch or somethings up

lament rock
#

Not on hand. I'd have to write something

opal plank
#

im gonna be honest, i've never noticed that error logging you're mentioning, though its entirely possible i overlooked it, since i log a lot of errors

#

i think of my console as my friend, the only instance i dont log stuff is in prod

#

for that i have custom dumps and handler for it

lament rock
#

My console is flooded with bad http reqs

#

in prod

opal plank
#

hmmm thats odd tbh

lament rock
#

Mostly just unauthorized

tiny ruin
#

hey guys, I'm using djs and I want to make embed with variable number of fields in embed.
Ex. an array has x strings in it and I want every string in separate embed field

#

Is it possible?

cinder patio
#

yeah, just loop through the array of strings

tiny ruin
#

how? I know it sounds easy

opal plank
#

for() loop

cinder patio
tiny ruin
#

I mean create embed fields

pale vessel
#

yes?

#

apply the same concept

tiny ruin
#

ik how to loop.. but I want to create embed fields at each iteration

pale vessel
#
const embed = <embed>

for (cond) {
    <add field>
}```?
cinder patio
#

Do you use the MessageEmbed object to create embeds or do you just use raw objects

opal plank
#

remember that theres a limit to how many firleds you can add

#

which i dont remember back of my head, 25 or something

earnest phoenix
pale vessel
#

25 yes

tiny ruin
#

how many emojis discord server can have?

#

max level 3

pale vessel
#

250

#

Not sure if it's both animated and static or 250 for both

tiny ruin
#

Should I make embed pagination or display emojis => role map in fields (maybe 25 emojis per field)

pale vessel
#

Pagination imo

#

Fields can be big

#

If you don't want reaction pagination you can make the user specify the page

tiny ruin
#

thanks

slender thistle
earnest phoenix
#
if (!kullanıcı) return message.channel.send(`Cihazını görmek istediğiniz kullanıcıyı etiketleyin!`);
let p = Object.keys(kullanıcı.presence.clientStatus).join(',')
let cihazisim = p
.replace(`mobile`,`Mobil`)
.replace(`desktop`,`Bilgisayar`)
.replace(`web`,`İnternet Tarayıcısı`)```
where is the error i have "cannot convert undefined or null to object"
#

i am using d.js v12

#

@earnest phoenix

tired panther
#

@earnest phoenix kullanci is just a user and not Object with many keys

#

you can join them like kullanci.join(' ,')

earnest phoenix
#

i will try thanks

crystal wigeon
#

i have 3 such intervals that run every 3 mins and one runs every 3 hours, and 1 2 hours, and few other setTimeouts that run like after 15secs but these are cleared

kind crescent
#

Ive had one command before that ran every 2 seconds. Didnt cause lag for me

#

I suppose it depends what your intervals are actually doing

earnest phoenix
#

Hello,
I would like to know if in discord.js it is possible when we put an invitation link in the status its automatically ranks us? thank you in advance

crystal wigeon
#

my intervals make DB calls and updates

#

i dont think it would cause lag since they are async

#

also is it really not possible to serialize the message and client object that djs gives? ;-;

earnest phoenix
#

don't mix sync/async and serial/parallel execution

#

they're two different things

crystal wigeon
#

well nodejs nothing really executes parallely

#

so i thought the DB queries were causing lag which in deed took like 800ms - 1.2secs even more, i optimized those to 200ms or less

#

but the lag still persisted

#

so that wasnt the bottleneck

#

i thoguht maybe there some event loop block in my code

#

but my for loops are async

modest maple
#

serial/parallel execution
concurrency != parallel pithink

earnest phoenix
crystal wigeon
#

well i've never used it xd

modest maple
#

JS can use multiple threads, but async is always ran on the same single threaded event loop

crystal wigeon
#

also i could use a second hand to review my code to figure out bottle neck

#

let me know if anyone can help

earnest phoenix
#

as to why your bot is lagging, the only way to find that out is to debug your code and track performance

crystal wigeon
#

yep i tried most of it

#

the lag only shows up when 2k people are using it

#

when i running my test bot

#

i see literally no lag

#

which is used by like 5 - 10 people

#

the same functions in both

feral aspen
#

In the guildMemberAdd event, there is no message, so how can I do this? let role = message.guild.roles.cache.get(server.mainRole);

crystal wigeon
#

client.guild

earnest phoenix
#

get the guild from the member

crystal wigeon
#

or that

#

xd

feral aspen
#

let role = bot.guilds.roles.cache.get(server.mainRole);?

#

guilds or guild?

earnest phoenix
#

no

feral aspen
#

Oh.

crystal wigeon
#

member.guild

earnest phoenix
feral aspen
#

OH.

#

🤦‍♂️

crystal wigeon
#

when the guild member event occurs you get the member

#

in the callback

feral aspen
#

member.guild.

earnest phoenix
#

i really need to get a colored role so people stop ignoring me

earnest phoenix
#

(i was kidding :p)

feral aspen
#

let role = member.guild.roles.cache.get(server.mainRole);

modest maple
#

people like to selectively listen to people only if its what they wanna here

earnest phoenix
#

@crystal wigeon it isn't because djs objects are too complex and have recursive properties

#

map properties you want to your own object

crystal wigeon
#

ye its the recursive that gets me grr. member.guilds.role haiz if i wanted this i have to serialize every single prop lol

#

just hinking of a way to make it easier

#

mmm

tender basin
#

Hey folks, got question developing such algorithm that can take Spotify album image colour palette as input and return matching or suitable background colour that can be used, any idea if such thing can be achieved? would appreciate some of your thought process. 🙂

earnest phoenix
#

at the top of my mind, you would just go pixel by pixel and save the most dominant colors

modest maple
#

If you're using python Numpy can be pretty good for this or OpenCV

tender basin
#

colour that will possible be available lets say in this example green yellow and blue is give as input then my algorithm should workout the best possible output from that

#

okay, I have seen that too

modest maple
#

your easiest solution is calculating the dominant colour

#

and matching that to x background or just using that dominant colour

#

Median cut is an algorithm to sort data of an arbitrary number of dimensions into series of sets by recursively cutting each set of data at the median point along the longest dimension. Median cut is typically used for color quantization. For example, to reduce a 64k-colour image to 256 colours, median cut is used to find 256 colours that match...

feral aspen
#
const { Schema, model } = require("mongoose");

const serverSchema = Schema({
    name: String,
    serverID: String,
    prefix: String,
    test: Boolean
});

module.exports = model("Server", serverSchema);

Hey, just quick question regarding MongoDB, I'd like to ask why whenever I add a new line such as test: Boolean, it doesn't update for all the saved ones that are in the database, and whenever the new command features wants to use the test: Boolean, it would simply not find it for the ones that are in the database as it didn't update to all the saved ones! What can I do?

This is also how it registers it..

if(!server) {
            const newServer = new Server({
                name: guild.name,
                serverID: guild.id,
                prefix: process.env.PREFIX
            });
            newServer.save().catch(err => console.log(err));
        } else {
            return;
        };

I can simply just add the test: Boolean alright, but what about all the current saved ones? It doesn't update, what can I do?

tender basin
#

agreed, I think should avoid complicating and thanks for the suggestion. 😊

opal plank
#

overcomplicating is my middle name mmulu

feral aspen
#

What can I do though! :(

tender basin
#

this is also good example of simple solution

kind crescent
feral aspen
kind crescent
#

Create a new command that runs that.

#

Or have it run with the ready event

rugged cobalt
#

I'm currently having this issue where I'm trying to delete the obj (as defined in Guild.js) from the guildConfig collection. But when I try it, it just says that there were none found. It only works if I manually add in the _id to the admins object along with copying the actual id from the document. Anyone know how I can work around this https://srcb.in/dO70QonTqz

feral aspen
quartz kindle
#

just create a server with express or something similar

modest maple
#

just use nodejs' rate http lib bigbrain

quartz kindle
#

rate?

edgy tapir
#

how to check if a member didn't send any amount after the command in discord.py ? like !clear [amount]

feral aspen
lusty quest
#

just modify your model to contain the wanted new value and run a updateMany query to make the change on all existing documents

crystal wigeon
#

hey

#

also

#

quick question

#

so a Promise() without await is considered synchronous? can it cause event blocks?

#

something like

#

func() { new Promise(
Promise.all()
) }

#

something like this

#

i feel like it would cause blocks?

earnest phoenix
#

promises are always async

#

removing await will make it non-blocking

crystal wigeon
#

so using await will make it blocking?

tender basin
#
from PIL import Image

def colorPicker():
  example_image = Image.open('image url here')
  image_colour = example_image.getpixel((250, 100))
  print(image_color)

This solved my spotify colour picker from album image, but for pure accuracy can use K-Means Clustering in OpenCV but for simplicity this is does the job for the time being I have tried with various song on spotify so far the accuracy for the colour palette is decent. 😊

crystal wigeon
#

async func () {
return await new Promise(async () => {
return await Promise.all([])
}
}

#

would this cause event blocks?

lyric mountain
#

To get the average color you could just iterate over all pixels and exclude white and black tho

lyric mountain
#

Because the method it's in is async

#

It'll block only if you await it too

crystal wigeon
#

so awaiting the func would block it?

modest maple
#

i think you're missing the entire point of async/await and promises

crystal wigeon
#

well, im slow xd

#

just making sure that im not doing it wrong tho

crystal wigeon
#

if im correct

modest maple
#

🤨 You know the whole point of async and await is to provide a higher level non-blocking api over promises right?

crystal wigeon
#

yeah but the reason im using promise all is to avoid for (...) loop since i want them to run parallely or something

#

because i wanna avoid nested for loops

modest maple
#

if you call a async function from a synchronous context you're blocking the current thread to allow the event loop to manage the context to give the concurrency aspect

crystal wigeon
quartz kindle
crystal wigeon
#

they just push to an array

#

outter array ig

modest maple
#

then what is the point of them being asynchronous pithink

crystal wigeon
#

sowwy im slow :p

quartz kindle
#

for example, no matter how much async you use, if deep down the core code is sync, it will block

#

there are only 2 types of true asynchronous code

#

streams and event loop skipping

crystal wigeon
modest maple
quartz kindle
#

I/O like file reads, networks requests, TCP, etc... are all done through streams. a request is opened, and the data starts flowing in chunks, so it doesnt block

#

event loop skipping is a way to manually break down synchronous code by using setImmediate

#

so you have to look at what the actual code is doing

#

for example, a database request deep down uses streams, so it is true async

#

you can confidently use them knowing it wont block

earnest phoenix
#

Co

quartz kindle
#

but numeric calculations, no matter how complex, are not async

#

unless you explicitly break them down in chunks using setImmediate

#

actually there are 3 types, timers are also async

#

but they can be grouped together with setImmediate kinda

modest maple
#

well... Timers are synchronous they can just use the eventloop to schedule their execution at a given time

quartz kindle
#

ye

#

they are event loop skippers

#

just like setImmediate

modest maple
#

Go's entire runtime are just loop skippers mmLol

quartz kindle
#

xD

modest maple
#

which as much as its useful to not worry about it's execution being blocking or not

#

it basically nuked it ability to expand it syntax and execution logic

restive furnace
#

Imagine making async code whike you could make synchronous code

modest maple
#

most async things are 90% synchronous

#

The entirety of my async web server is written with synchronous code mmLol

earnest phoenix
#

and then you start using a language where you're free to use threading mmLol

#

threads is where it gets wild

restive furnace
#

threads are nice

earnest phoenix
#

it took me almost a month to actually understand their lifespan in c#

quartz kindle
#

threads are easy in node

restive furnace
#

dataraces is what i like mmLol

quartz kindle
#

its just a pain to share data with them

modest maple
#

I just go with async + threads mmLol

earnest phoenix
#

race conditions are a pain

#

and then you fall back to locking, making it sync again

modest maple
#

actors™️

quartz kindle
#

async locking

restive furnace
#

^ has not been implemented even today

modest maple
restive furnace
#

nou

#

well atleast in C

modest maple
#

again, thats completely un-true

earnest phoenix
#

afaik C languages don't have true async lock

#

there's semaphores and shit

restive furnace
#

imagine asynchronous C, how fast OSes would be

#

async + threads

modest maple
#

pithink Do you think OS' are synchronous

restive furnace
#

well some of them are

modest maple
#

👀 That would be one fecking slow OS

earnest phoenix
#

none of them are

#

there's operations that some OS' do synchronously but all of them work in an asynchronous context

quartz kindle
#

the very essence of multitasking is based on that

#

otherwise how would OSs multitask on single core 90s cpus

modest maple
#

most modern OS' utilize work stealing to properly balance tasks

fierce ether
#
const getInformation = await client.playerModel.find({ })
        .map((v) => v.id) ``` this should return all ids in the collection?
cinder patio
#

try it

fierce ether
#

i did

cinder patio
#

and?

fierce ether
#

it returns the whole collection

opal plank
#

lol feud

#

making them answer their own question

tight plinth
#

so I have an object like this:json { "location": { "name": "Blois", "region": "Centre", "country": "France", "lat": 47.58, "lon": 1.33, "tz_id": "Europe/Paris", "localtime_epoch": 1612714370, "localtime": "2021-02-07 17:12" }, "forecast_day": { "temp_c": 35.4 } }and a string provided by the user with placeholders such as [location.name] or [forecast_day.temp_c] in it. Is there an efficient way to replace the placeholders in the string with the values in the object without using 15 string.replace in js?

opal plank
#

you could just regex it (or better yet, properly split with)

#

actually

#

let me get a step

#

1 sec

cinder patio
#

just split by a dot and loop through all props? Why use replace

#

oh

#

in the same stirng

#

string*

opal plank
#

get all entries of the content

#

then split by .

#

get first entry of each iteration, on the split, check if your object has that property

#

Object.hasOwnProperty(regex[0])

#

if it does, then you assign that property to the second value

#

regex[1]

#

regex being one entry of your regexed item, split by .

#

keep in mind regex is slow af