#development

1 messages ยท Page 1517 of 1

earnest phoenix
#

Actually undefined

opal plank
#

or that

#

yeah

#

it just doesnt return

harsh blade
#

uhh dosent message.author just tag the users ID without pinging?

opal plank
#

huh?

#

message.author is an object

#

not a strin

distant cobalt
#

if i were to change the member's nickname, i just put the nickname i want in the () ?

opal plank
#

ig you want to make it a mention, do toString()

harsh blade
#

oh what

opal plank
earnest phoenix
#

<Message>.author gets converted into the user's mention if it gets concatenated to a string

distant cobalt
opal plank
#

im fairly certain you need to do toString() to get a mention

#

i dont think author by itself resolves on a mention

harsh blade
#

Now im confused

earnest phoenix
#

${message.author} and message.author.toString()

harsh blade
earnest phoenix
#

Both gives a mention

harsh blade
#

Oh

#

Thank you!

opal plank
#

thats confusing

#

why does message.author resolve on that?

pale vessel
#

because ` turns it to a string

cinder patio
#

because js calls the toString() method automatically

opal plank
#

normally i'td be resolved into [Object] no?

pale vessel
#

that .toString()s it

earnest phoenix
#

Concatenating it like '' + message.author will be their ID, but concatenating it like ${message.author} or message.author.toString() will become their mention

harsh blade
#

ooh

opal plank
#

hmmm thats a quirky thing i wasnt aware of

harsh blade
#

im just dumb lol

distant cobalt
#

wait a sec

harsh blade
#

My goal is to learn discord.js or js in 2021 bruh

distant cobalt
#

i thought i put this in my if function?

if(guild.me.permissions.has('MANAGE_NICKNAMES')){```
it says that missing perms
opal plank
#

the normal approach is learning js, THEN doing a bot

earnest phoenix
#

You should learn JS before discord.js

solemn latch
#

if you have all of 2021, i would spend a few months on JS

opal plank
#

a bot isnt something simple and uses advanced stuff from js

distant cobalt
cinder patio
#

no clue how they got the ID from that

earnest phoenix
#

I mean maybe but the return value isn't the same

opal plank
#

oh, @umbral zealot

distant cobalt
opal plank
#

before you leave

#

i did the thing yesterday

#

im about to finish some last touches, but thats improvements, the whole thing is in place already

umbral zealot
#

nice

opal plank
#

ty for yesterday

earnest phoenix
harsh blade
harsh blade
#

its taking his own messages as the event?

#

its made to reply to "help"

earnest phoenix
#

Make it ignore itself and the other bots

distant cobalt
harsh blade
dusky sundial
#

Make an if statement that returns if the message author is the bot

solemn latch
#

probably shouldnt respond to every message with the word help in it.

opal plank
#

user.bot

earnest phoenix
distant cobalt
opal plank
#

user.bot is true if its a bot, false if it isnt, check that

pale vessel
earnest phoenix
#

Not understandable enough?

dusky sundial
#

Also, I got another issue with MariaDB that confuses me

distant cobalt
#

theres a role for every bot that you invite right? It's impossible to delete that role because it's managed by discord right?

pale vessel
#

Which is weird, the number is useless

harsh blade
#
if (message.content.includes("help")) {
    console.log("help from " + message.author.toString())
    message.channel.send("Hello, " + message.author.toString() + "! My main purpose is to manage tickets, but I have some other commands too!\n use **,help** to see the list of commands!")
  }
solemn latch
#

if you invite the bot with 0 perms it wont make the role

cinder patio
#

that's so inconsistent

earnest phoenix
#

<Guild>.me.roles.highest.position < <GuildMember>.roles.highest.position

earnest phoenix
#

Dotpost combo broken

pale vessel
dusky sundial
harsh blade
#

How do i define this
if (message.content.includes("help")) {
to only listen to users

distant cobalt
#

i can check it by

if(guild.me.roles.highest.position){

}```?
opal plank
#

zugirf

#

really

harsh blade
#

hey

opal plank
#

learn js first

solemn latch
#

pretty sure people gave you copy paste examples

harsh blade
#

Ok

weary widget
#

does anyone know why youtube_dl is not importing? when i try to import it it just gives me a generic error of "can't import module" and when i do pip freeze it is listed as installed

earnest phoenix
opal plank
#

you'll be coming back here every 5 minutes if you dont

harsh blade
#

ok

distant cobalt
harsh blade
#

Look

#

Im trying ok?

earnest phoenix
#

And?

opal plank
#

i know, im not trying to scare you away

distant cobalt
#

Ohhhhhh

#

nvm

#

lol

opal plank
#

just letting you know to focus on JS first, not on d.js

#

here, let me give you a quick help

distant cobalt
#

lol

cinder patio
#

Why does javascript not automatically call toString when an object is being added to a string, and more importantly why is message.author turned to the id

opal plank
#

make a test.js

#

@harsh blade

harsh blade
#

why?

opal plank
#

trust me

solemn latch
harsh blade
#

this sounds like an awful way to phihising tokens :/

opal plank
#

just do it

earnest phoenix
sudden geyser
#

youtube_dl is correct.

earnest phoenix
#

๐Ÿ—ฟ

sudden geyser
harsh blade
#

done?

opal plank
#

okay, now, heres the tip

#

take a look at this

#

see on the left side? those are basically the categories or things you gotta check

#

now, i'd like you to skim at least through:
Maps, functions, variables, arrays

solemn latch
#

there is a best practices thing too, which has some good suggestions

opal plank
#

whenever you are reading one of those, put some dummy code in your test.js

#

so you can play with the code yourself

#

just add code in your test.js and then run node test.js

solemn latch
opal plank
#

its basically: Read the guide, and try yourself sort of thing

earnest phoenix
opal plank
#

AT LEAST those, pereferably learn the rest too, but this should give you some footing on js

#

like i mentioned, read one of those topics, try it on test.js and run with node test.js to run whatever you put in test.js

#

rinse and repeat

mellow kelp
#

why does w3schools still use var for everything tho

opal plank
#

cuz old shit

sudden geyser
#

It's JS documentation is outdated but can be easy to grasp.

weary widget
solemn latch
#

in their best practices it even says dont use global variables KEKW

sudden geyser
#

eh, global variables can be useful

opal plank
#

but hey, use var

#

dont do globals

#

bad

mellow kelp
#

cant believe there are still people with full knowledge of js who use var

opal plank
#

var has its uses

#

but the majority of people will never have a proper one

sudden geyser
#

If I don't want to pass around some state across my files and scopes globals are helpful -- when they need to live throughout the entire lifespan of the program at least smirk

opal plank
#

why not attach it to process?

mellow kelp
#

well globals are kinda useful for splitting stuff in browser javascript

opal plank
sudden geyser
#

What's the difference at that point?

opal plank
#

none, they both are idiot stuff to do

sudden geyser
#

nah

opal plank
#

though attaching to process can be handier

#

i was THIS close from attaching my client onto process

#

but decided not to

mellow kelp
#

yeah probably better that way

#

i just pass the client around with function params

opal plank
#

400 servers in 2 weeks

sudden geyser
#

like, take a logger variable. I don't need to attach it to some other variable and pass it around. Attaching it to some other variable so you can use it everywhere else doesn't have much of a difference imo. I understand why people see not using globals as better practice

dusky sundial
#

Bruh I'm getting a headache tylerrage

lament rock
#

To bounce around locally scoped variables to other files or other scopes, you could create a file which only exports an Object then Object.assign to that Object and require the Object in other files.

sudden geyser
#

example pls

opal plank
#

on the 27th it was at 160, on the 24th it was at 110, so roughly 2 weeks for 400 guilds

#

2.5 i guess

#

just do -bots userid

#

this one im showing is GenshinUtils

#

ding ding, correct

lament rock
#

passthrough.js

module.exports = {};

index.js

const passthrough = require("./passthrough.js");

const client = new Client(options);

Object.assign(passthrough, { client });
require("./utils.js");

utils.js

const passthrough = require("./passthrough.js");

const { client } = passthrough;

console.log(client);

output

Client {
   token: "blah"
   user: [ClientUser]
   someOtherProp: "idk"
}
opal plank
#

ty hug

#

took a while to do ngl, i guess around 1 or 2h

#

its actually not that complicated either apart from the frames

mellow kelp
#

yea animations are simpler than i thought

harsh blade
#

Does it matter where these closing brackets are }

mellow kelp
#

@keyframes and transform: translate am i right?

opal plank
#

yup

#

i did some basic animation

mellow kelp
#

epik

opal plank
#

i saw something similar on a friend's company website, decided to yoink it

mellow kelp
#

floating animations are subtle but make stuff look better

opal plank
#

i was actually thinking about tilting based on scroll, but decided against it

#

to keep the invite and vote stuck in position and follow the page along as you scroll

#

and then add translation on scrolling

#

make some smooth animation during the transition

#

but thats a lot more math involved than i'd like to admit

#

tl;dr cba

mellow kelp
#

sass could help

opal plank
#

was about to ask that

#

its doable with css, its just a hell lot of math im not in the mood for

#

and for something that minor

#

page is already unique as is

mellow kelp
#

yeah the page's cool right now

opal plank
#

ty

dusky sundial
#

Swapping from Vultr to Galaxygate reduced my bots latency by like 75ms Thinking

solemn latch
#

what was the location for the vultr vps?

dusky sundial
#

Amsterdam, I believe

solemn latch
#

probably why then

dusky sundial
#

Yeah, makes sense

earnest phoenix
#

api latency for me is 30ms

#

but probably because it's a london server

drowsy grail
#

vultr is nice but the price/ram just didn't work for me

dusky sundial
#

I liked the fact that they charge hourly instead of monthly. Makes it easier to try different plans without paying for the entire month.

solemn latch
#

thats the benefit of very large providers, they can do stuff like that efficently.

pale vessel
solemn latch
#

oh man, a headache and a half

earnest phoenix
#

lmao

quartz kindle
#

vultr's ssds are one of the best tho, from what i've heard

#

over 1gbps r/w speeds

earnest phoenix
#
  • { display: none }
tardy hornet
#

Hi guys, dont know if its the right channel to ask for it , But, when I am trying to trasfer my bot to my linux vps, and once I am typing node . it gives me this error:

Error: Cannot find module '/root/Among Us Bot/node_modules/sqlite3/lib/binding/napi-v6-linux-x64/node_sqlite3.node'
Require stack:
- /root/Among Us Bot/node_modules/sqlite3/lib/sqlite3-binding.js
- /root/Among Us Bot/node_modules/sqlite3/lib/sqlite3.js
- /root/Among Us Bot/index.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:815:15)
    at Function.Module._load (internal/modules/cjs/loader.js:667:27)
    at Module.require (internal/modules/cjs/loader.js:887:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/root/Among Us Bot/node_modules/sqlite3/lib/sqlite3-binding.js:4:15)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Module.require (internal/modules/cjs/loader.js:887:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/root/Among Us Bot/node_modules/sqlite3/lib/sqlite3-binding.js',
    '/root/Among Us Bot/node_modules/sqlite3/lib/sqlite3.js',
    '/root/Among Us Bot/index.js'
  ]
}
quartz kindle
#

you need to reinstall your modules

distant cobalt
cinder patio
#

users don't have roles, and message.author is a User

#

use message.member

distant cobalt
#

so how about message.member

#

okay

cinder patio
#

ye

distant cobalt
cinder patio
#

what is mentionedRole

distant cobalt
#

mentionedRole is defined here

const mentionedRole = message.mentions.roles.first();```
stark abyss
cinder patio
#

a Role doesn't have a roles property, it's not a member

distant cobalt
#

soo

cinder patio
#

If message.member.roles.highest is a role, and to get it's position you do.position, how would you get the position of mentionedRole, which is already a role

long marsh
#

How do you guys track statistics on your bot?

distant cobalt
#

so i just do js mentionedRole.position

cinder patio
#

yeah

distant cobalt
quartz kindle
long marsh
# quartz kindle what kind of statistics?

Most used command, how many guilds its in, etc.

Basically asking for other people's strategies. If someone asked me "What is your most popular command" -> I couldn't tell them. Naively, I could just keep a counter and update a graph overtime; however, I just didn't know if there was already a pre-build solution for something like this.

quartz kindle
#

i dont keep statistics for that

long marsh
#

Well, dbl-bot keeps track of the builds and such on my behalf ... but most used commands overtime and such would probably be beneficial. Like said, I could custom build something that keeps a counter ... just wasn't sure.

quartz kindle
#

you'll need to do that yes

#

if you want a fully featured solution, look into a time series database

#

they are optimized for storing logs for example

#

then you can query it in all sorts of ways, get the times of the day with most usage, etc

long marsh
#

Yep, I've used time series databases before ๐Ÿ‘

#

Just didn't want to invest in that ๐Ÿ˜ฌ

quartz kindle
#

you can self host one

tulip ledge
#

is there by any chance a ratelimit on webhooks? As my code just gets stuck on "await" for creating a webhook for 15 minutes after I used it too much

quartz kindle
#

it probably does then

tulip ledge
#
    if (!webhook) {
      try {
        webhook = await channel.createWebhook(name, {
          avatar: avatar
        });
      } catch {
        channel.send("Something went wrong please wait a minute and try again.")
      }
    }

it just gets stuck here

quartz kindle
#

since its on the channel route, its possible it shares or has similar limits as other channel-specific limits

#

for example, only being able to change the channel name twice every 10 minutes

distant cobalt
#

on djs, how do i change a role's color using hexcode?

earnest phoenix
#

...pass the hex

distant cobalt
#

ik

#

but how do you change a role's color?

quartz kindle
#

role.edit({color:"bla"}) or that ^

distant cobalt
earnest phoenix
#

also that

dense surge
#

Could someone help me code my bot

lusty quest
harsh blade
solemn latch
#

message isnt defined

lusty quest
#

define message

pale vessel
#

have you tried reading the error

lusty quest
#

make sure you run it inside the message event

harsh blade
pale vessel
#

i c

harsh blade
#

im just 2 dumb u see

solemn latch
#

many errors are plain English.

harsh blade
#

im not from england

lusty quest
#

im not from england and still understand it

earnest phoenix
#

you're aware... england isn't the only country where english is spoken, right?

harsh blade
#

yall rude

earnest phoenix
#

hey don't blame us on your incompetency

harsh blade
#

ok cool

quartz kindle
#

X is not defined means that X does not exist in the place where you're trying to use it

#

meaning, you're trying to use something out of place or in the wrong place

misty sigil
long marsh
#

Just submitted my discord bot's verification approval. How long did it take for anyone else that's done that?

pale vessel
#

Like 40 days

mellow kelp
#

you mean discord verification or top.gg?

long marsh
#

Discord verification

#

Damn, 40 days?

pale vessel
#

It should take around a week now

mellow kelp
#

that one's just 5 days or so

long marsh
#

They just reopened the form from the holidays. I'm curious how long it's going to take ๐Ÿ˜ฌ

#

It has been closed / greyed out since Dec. 24th

mellow kelp
#

an article they made says 4-5 business days or something

long marsh
#

That's unfortunate

#

My hopes of actually doing a marketing campaign this week are shattered ๐Ÿ˜ข

mellow kelp
#

well at least it's not too long

#

yeah thats the bad thing

#

after 4-5 days, a bot probably won't appear anymore on the "new trending bots" section

long marsh
#

Yeah, my bot has been off of that for a while. I mean I simply can't pay to place my bot on an advertisement.

pale vessel
#

Their article said the same thing at that time

long marsh
#

To be fair, it was a longer process back then before they mandated it ... right?

#

And you got that nice shiny early bot developer badge

mellow kelp
#

ohh yeah that thing

pale vessel
#

I was lucky enough

#

Auctions helped

mellow kelp
#

i didn't get to verify my bot in time

long marsh
#

I didn't start developing my bot until Nov, lol

#

Now there's fishing, hunting, town / grid management, connect4, tictactoe, full economy system, store, bag, etc.

#

Been grinding

mellow kelp
#

cool stuff

broken matrix
#

@earnest phoenix

slim void
#

in python how to I stop a if statment

#

I tried using break but only works for while loops

mellow kelp
#

pretty sure you can't break out of if statements

slim void
#

why

lusty quest
#

does py got return?

slim void
#
if message.content == "hey":
              await self.delete(message, warning=f'{message.author.mention}, hey')```
mellow kelp
#

yeah it has return

slim void
#

I want to break out of this

#

using return doesn't break it

lusty quest
#

why did you want to break out of an if statement?

mellow kelp
#

i don't think you need break

slim void
#

Because it's checking if it is gonna start with a https://

#

else moving down the lines

mellow kelp
#

just use another if statement

slim void
#

look

lusty quest
#

then execute IF its valid

slim void
#
@commands.Cog.listener()
    async def on_message(self, message):
        if self.config.get('status', True) and message.channel.id in self.config.get('channel_ids', []):
            if message.content == "hey":
              await self.delete(message, warning=f'{message.author.mention}, hey')
              
            if message.author.bot:
                await asyncio.sleep(5)
                await self.delete(message, warning=None)

            elif len(message.attachments):
                if len(message.attachments) > 1: #message.attachments[0].filename.endswith('.gif')
                    await self.delete(message, warning=f'{message.author.mention}, send 1 emoji at a time.')
                elif not (message.attachments[0].filename.endswith('.png') or message.attachments[0].filename.endswith('.jpeg') or message.attachments[0].filename.endswith('.jpg') or message.attachments[0].filename.endswith('.mp4')):
                    await self.delete(message, warning=f'{message.author.mention} ![incorrect](https://cdn.discordapp.com/emojis/780990204177154088.webp?size=128 "incorrect") Only images/captions/gifs are allowed in this channel!')

            else:
                await self.delete(message, warning=f'{message.author.mention} ![incorrect](https://cdn.discordapp.com/emojis/780990204177154088.webp?size=128 "incorrect") Only images/captions/gifs are allowed in this channel!')```
lusty quest
#

if not dont execute

slim void
#

see

#

if msg == "hey" break

#

how to ?

mellow kelp
#

you can just use return

#

you're inside a function

slim void
#

I did it b4

#

I did return and it didn't stop it lol

pale vessel
#

where did you put it

slim void
#

is it return None?

#
            if message.content == "hey":
              await self.delete(message, warning=f'{message.author.mention}, hey')
              return```
#

like this

mellow kelp
#

then the condition you set wasn't true

slim void
#

whenever I use return

#

I get a error

#

is it return None?

pale vessel
#

return should work

slim void
#

nope

#

error

pale vessel
#

did await self.delete(message, warning=f'{message.author.mention}, hey') work

slim void
#

yeah that alone works, it respnds with hey

#

but then keeps moving which I don't want

mellow kelp
#

yeah but what error

slim void
#

let me get ti

#

I guess that's not rlly helpful

#

that's all I'm getting

mellow kelp
#

well idk what cogs are KEKW

slim void
#

return just doesn't work

mellow kelp
#

i dont even use python actually

#

imma head out

pale vessel
#

well you can just use else

#

but that's running away from the problem

slim void
#

yeah

faint prism
#

Hey, I need a JS-native (not using node) solution for getting today's date, and today's date minus 7 days. Can someone point me in the right direction?

solemn latch
#

id use Date

mellow kelp
#

get the date in ms

solemn latch
mellow kelp
#

or yeah i think the Date class has methods for that

slim void
#
if message.content.startswith == "https://":```
#

is there a better way to check if this is a link?

#

because this isn't working, and it's not efficient

earnest phoenix
#

make a request to it

slim void
#

huh

earnest phoenix
#

there's no way to verify if a string is a valid, working link without making a request to it

slim void
#

I wanna check if there is a link in the msg

mellow kelp
#

also use some regex to check beforehand

slim void
#

so test the link via bot?

#

I don't get it

#

let me search

faint prism
#

That's pretty much what I needed

slim void
#

@earnest phoenix

#

I don't wanna test if the link is valid

pale vessel
#

๐Ÿ“

slim void
#

Just if it is a link

earnest phoenix
#

oh

slim void
#

how would I do thwat?

earnest phoenix
#
mellow kelp
solemn latch
#

i cant even read that regex KEKW

slim void
#
http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+```
#

regex hurts my eyes

#

so see if this is contained.. in the msg?

#

or am I thinking wrong ๐Ÿ˜‚

earnest phoenix
#

match it against the message content

#

if the match returns something

#

there's a link

slim void
#
  regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?ยซยปโ€œโ€โ€˜โ€™]))"
    url = re.findall(regex,string)```
#

I found this online, is this the right path?

earnest phoenix
#

i don't do py so no idea

slim void
#

ah

#

well I will look into it

#

thx

#
            if message.content.startswith("https://"):
              #ignore```
#

Also.. I just simply wanna know for future builds, why did this not work lol

#

I don't see what I did wrong

#

it's exactly how it's suppose to be

earnest phoenix
#

that checks if your message starts with exactly that

#

it won't detect .https://

#

it will detect

#

https://

slim void
#

yes

#

Ik

blazing portal
#

is that js?

slim void
#

I did https://

#

and it didn't detect it

earnest phoenix
#

๐Ÿค”

#

Is it possible to see from which application the specific bearer token comes from?

slim void
#

That's why I'm saying..

earnest phoenix
#

what is your actual goal

slim void
#

I also did python if message.content.contains("https://"): #ignore

#

and it didn't detect if https:// was in the msg

earnest phoenix
#

you can't

earnest phoenix
slim void
#

it doesn't hmm

earnest phoenix
#

can you share a bigger snippet

slim void
#
    @commands.Cog.listener()
    async def on_message(self, message):
        if self.config.get('status', True) and message.channel.id in self.config.get('channel_ids', []):
            if message.content.contains("https://"):
              #ignore
            else:
              
              if message.author.bot:
                  await asyncio.sleep(5)
                  await self.delete(message, warning=None)

              elif len(message.attachments):
                  if len(message.attachments) > 1: #message.attachments[0].filename.endswith('.gif')
                      await self.delete(message, warning=f'{message.author.mention}, send 1 emoji at a time.')
                  elif not (message.attachments[0].filename.endswith('.png') or message.attachments[0].filename.endswith('.jpeg') or message.attachments[0].filename.endswith('.jpg') or message.attachments[0].filename.endswith('.mp4')):
                      await self.delete(message, warning=f'{message.author.mention} ![incorrect](https://cdn.discordapp.com/emojis/780990204177154088.webp?size=128 "incorrect") Only images/captions/gifs are allowed in this channel!')

              else:
                  await self.delete(message, warning=f'{message.author.mention} ![incorrect](https://cdn.discordapp.com/emojis/780990204177154088.webp?size=128 "incorrect") Only images/captions/gifs are allowed in this channel!')
#

discord broke some formats

earnest phoenix
#

that's super weird

slim void
#

ik

#

it's making no sense rn

earnest phoenix
#

tried printing inside the first if?

slim void
#

ok

#

and seeing if it displays?

earnest phoenix
#

yup

final valve
#

Hi

#

Just joined

slim void
#

testing rn

#
AttributeError: 'str' object has no attribute 'contains'```
@earnest phoenix
#

hmm

#

wat

earnest phoenix
#

python doesn't have a contains method then

proven lantern
#

__contains__()

slim void
#

ben wdum

proven lantern
slim void
#

so

#

if message.content.contains("https://"):

#

it' not like this"

fierce ether
#

why does this not display? <img src="<%- user.avatar %>" alt="Profile Photo">

slim void
#

you know what

fierce ether
#

user.avatar displays 4115e7278b04e8e40117dd55e700b291

slim void
#

I'm gonna just use classic python

#

if "str" in ..

earnest phoenix
#

can confirm __contains__ works

slim void
#

so contains?

proven lantern
#

in and __contains__ are the same. in uses contains

faint prism
#

Before I do something really hacky to get this to work, can someone point me in the right direction to get the output of a date in the format of MM-DD-YYYY?

slim void
#

ok

faint prism
#

JS

var endDate = new Date(Date.now())
var startDate = new Date(today - 7 * 24 * 60 * 60 * 1000)
#

I'm trying to get the MM-DD-YYYY string of those.
Very unfamiliar with JS. But I need it for an API Testing script

slender thistle
proven lantern
#

there are getter methods on the date object

#

i think the month is off by 1

pale vessel
#

Use new Date().toISOString()

faint prism
faint prism
proven lantern
#

getFullYear()

faint prism
#

Much better

proven lantern
#

.getMonth() + 1

faint prism
#

Why is the month - 1?

proven lantern
#

0 based index

faint prism
#

lol

#

but why month and not the rest?

proven lantern
#

tricks

faint prism
#

๐Ÿคทโ€โ™‚๏ธ alright, lol. What a strange language

pale vessel
#

It's not that bad new Date().toISOString().split("T")[0].split("-").reverse().join("-")

faint prism
#

"11-01-2021"
almost

proven lantern
#

the date should never go first

pale vessel
#

ah MDY

faint prism
#

yeah

#

I was looking for the equivalent of:

moment().subtract(0, 'day').format("MM-DD-YYYY"))
moment().subtract(7, 'day').format("MM-DD-YYYY"))

Without moment

hollow helm
#

kredet ples

blazing portal
#

you can use moment in js too

faint prism
#

I can't require. I'm not in nodejs

#

In a ECMAScript ECMA environment for JMeter

#

Thanks all

fierce ether
#

<img src="https://cdn.discordapp.com/avatars/<%user.id%>/<%user.avatar%>.png" alt="Profile Photo"> but if i log the link its correct so whats the problem?

tardy hornet
#

can someone help me?
when I am trying to start my node folder, it gives me this error:
Error: Cannot find module '/root/Among Us Bot/node_modules/sqlite3/lib/binding/napi-v6-linux-x64/node_sqlite3.node
(I am using ubuntu)

solemn latch
#

try reinstalling your modules

proven lantern
#

make sure sqlite3 is in you package.json

tardy hornet
tardy hornet
#

still didnt work

earnest phoenix
pale vessel
# faint prism yeah

new Date().toISOString().split("T")[0].split("-").sort((x, y) => y == 1 ? 1 : -1); lmao

solemn leaf
#

I need help with lua Im trying to take a screenshot of an emulator then write a file that is a png

#

this is the docs for the emulator

#

I tried doing

        local file = io.open("screen.png", "bw+")
        file:write(gui.gdscreenshot())
#

but it kept crashing it

quartz kindle
#

run npm i

tardy hornet
#

@quartz kindle can i just delete the sqlite3 module?

slim heart
#

is there a reason why

{
  backdrop-filter: blur(20px);
}

doesn't work on ios?

#loader {
    position: fixed;
    backdrop-filter: blur(20px);
    height: -webkit-fill-available;
    width: -webkit-fill-available;
    z-index: 10;
    margin: 0;
    top: 0;
}```
quartz kindle
#

if you copied your node_modules folder from your pc to your server, delete all of it

#

node_modules should never be copied, always reinstalled

tardy hornet
#

when ever i try to download it it says

quartz kindle
#

try npm install sqlite3 --build-from-source

tardy hornet
#

@quartz kindle did much larger error

#

i need to reinstall python?

quartz kindle
#

you likely need to install build tools

tardy hornet
#

npm i build tools

#

?

quartz kindle
#

sudo apt install build-essential

#

on ubuntu

golden condor
#

What os is the server

#

Although that looks like you should install python

tardy hornet
#

same error @quartz kindle

golden condor
#

Do you have python installed?

tardy hornet
#

yes

golden condor
#

Can you try run the python command as it may not be in the bin

tardy hornet
#

what is the python command?

golden condor
#

Just python

tardy hornet
#

just to type python there?

solemn leaf
tardy hornet
golden condor
#

Yes

quartz kindle
#

type python --version

tardy hornet
#

but i do have it

#

will it just fix it if i rebuild all of my modules?

#

???

#

like uninstall all of it

#

then npm i

#

?

#

@quartz kindle

rose warren
#

What's the rate limit info on renaming a channel?

solemn latch
#

probably pretty low

rose warren
#

I guessed that

blazing portal
#

2 times within 10 minutes or something

rose warren
#

But I'd like to find some docs

nimble sky
#

My emoji size downscales in embeds the bigger I make them... How can i make my emoji appear bigger in my embeds??

blazing portal
#

I have been looking for them to document that a while now. I haven't been able to find it, as they only have the General Rate Limit topic. But it's very close to 2 times per 10 minutes per channel

rose warren
#

Once an hour is probably ok right? side_eyes_anim

solemn latch
#

discord doesnt provide the ratelimits

blazing portal
#

yes once an hour is fine

solemn latch
#

since ratelimits are dynamic

tardy hornet
#

but i have python on my pc tho?!?!?!

nimble sky
#

set the env variable

nimble sky
quartz kindle
#

Did you install build-essential?

#

Whats your vps's operating system?

tardy hornet
#

i really dont know what more to do

quartz kindle
#

well you could answer my questions

tardy hornet
#

i just downloaded python on it

solemn latch
#

what about the other questions

tardy hornet
tardy hornet
quartz kindle
#

.>

solemn latch
#

not sure how people can help you debug then

quartz kindle
drowsy grail
#

does anyone use pm2 with djs

quartz kindle
#

yes

earnest phoenix
nimble sky
#

How the f do i make emojis appear bigger in embeds? They are soooo small.. I have rescaled them and tried just about everything I can think of.

earnest phoenix
#

IJPKJOIKLNHBIUYGTCDV HJ

nimble sky
eternal osprey
#

hey guys

#

how would i loop through a json file to find a specific name?

#

Like i want to find evan in a json file of names.

nimble sky
#

well could be both, either your code or the site.

quartz kindle
lament rock
earnest phoenix
#

FAC

eternal osprey
earnest phoenix
solemn latch
#

looks like an array to me

eternal osprey
#

huh

quartz kindle
eternal osprey
#

but it is wrapped in [] so they are objects

earnest phoenix
#

help me pls

eternal osprey
#

or have i learned it wrong

quartz kindle
#

[] is array

#

{} is object

eternal osprey
eternal osprey
nimble sky
lament rock
#

Are you putting any text in the same fields

earnest phoenix
rustic nova
#

what image

craggy pine
nimble sky
craggy pine
#

I think that reply for for me.
I'm just pointing it out since they went back to support. ๐Ÿ‘

rustic nova
craggy pine
#

I think they meant to reply to me.

rustic nova
#

i was referring to @earnest phoenix

#

oh then

nimble sky
craggy pine
quartz kindle
distant cobalt
#

on DJS how do i check if a user's account is under 10 days old?

eternal osprey
#

hey```js
if (message.content.startsWith("!specific")) {
let params = message.content.trim().split(/ +/g);
console.log(params[1]);
const main = require("./dex.json");
const found = main.find(element => element == params[1])
message.channel.send(found)
spawnHello();

};``` i want to use the variable found all the way down the code
#

in a function

#

but ofc it is undefined if i represent it like this,.

#

how would i make the variable found defined in general?

quartz kindle
#

then compare it to the current date

distant cobalt
quartz kindle
distant cobalt
#

How do i get the current date?

eternal osprey
quartz kindle
#

new Date() for the date object, Date.now() for the current timestamp

distant cobalt
#

okay

eternal osprey
#
let found; 
    if (message.content.startsWith("!specific")) {
        let params = message.content.trim().split(/ +/g);
        console.log(params[1]);
        const main = require("./dex.json");
        found = main.find(element => element == params[1])
        message.channel.send(found)
        spawnHello();
       ```hmm like this? It looks kinda sketchy
#

as we are already defining found right>?

#

so it would give an error that it is already declared

#

@quartz kindle

quartz kindle
#

youre assigning not declaring

distant cobalt
quartz kindle
#

yes

lament rock
#

createdAt is a Date. Date.now returns a number

eternal osprey
#

it is still not defined

#

the function is literally defined all the way down the code

quartz kindle
eternal osprey
#

400 lines further

#

okay

distant cobalt
quartz kindle
#

use createdTimestamp

distant cobalt
#

okay

eternal osprey
distant cobalt
#
if(member.user.createdTimestamp - Date.now() < 10){

}``` this is right ?
lament rock
#

<Date>.getTime() alternatively
Then just check for if now - (10 days as ms) > created time stamp

#

That will aways return false

eternal osprey
#

@quartz kindle ping me when you know the answer.

distant cobalt
lament rock
#

no lol. user.createdAt is a Date. You want to compare a number to a number and Date.now already returns a number

eternal osprey
#

owh

eternal osprey
#

sheee tim is writing for ages. Have i fucked it up that hard?

lament rock
#

user.createdAt // Date
<Date>.getTime() // number
Date.now() // number
user.createdAt.getTime() // number

(Date.now() - (1000 * 60 * 60 * 24 * 10)) > user.createdAt.getTime() // boolean

quartz kindle
#
client.on("...", () => {
  if(...) {
    let abc = 10; // declared inside the block, only valid inside the block
    console.log(abc) // 10
  }
  console.log(abc) // error, abc is not defined

  let something; // declared outside the block, valid in the outer block and in all inner blocks
  if(...) {
    something = 10;
    console.log(something) // 10
  }
  console.log(something) // 10
})

console.log(abc) // error
console.log(something) // error
// this is outside the block where either of them were declared

function bla() {
  console.log(abc) // error
  console.log(something) // error
  // this is a separate block, its still outside the block where both of them were created
}
#

@eternal osprey

long marsh
#

โ€œAwsomeโ€ ๐Ÿง

harsh blade
#

Everything else but this line works :-: Any ideas? been fiddling around with this for quite a while

lament rock
#

log the value of message

harsh blade
#
                console.log(image);
                const imageembed = new Discord.MessageEmbed()
                    .setTitle(subRedditName)
                    .setImage(image)
                    .setColor(9384170)
                    .setDescription(`[${title}](${link})`)
                    .setURL(`https://reddit.com/${subRedditName}`)
                message.channel.send(imageembed)
#

thats having the issues

earnest phoenix
#

How can i add a .then after a forEach, it say, .then() is not a function

Like that

message.guild.members.cache.forEach(m => {
console.log(m.user.username)
}).then(console.log('Finished'))
quartz kindle
harsh blade
lament rock
harsh blade
quartz kindle
lament rock
#

message is obviously defined. Log the value of message

lament rock
harsh blade
#
const https = require('https');
const Discord = require('discord.js');
const url = 'https://www.reddit.com/r/meme/hot/.json?limit=100'

module.exports = {
    name: 'meme',
    description: 'sends meme',
    execute(message, args) {

        https.get(url, (result) => {
            var body = ''
            result.on('data', (chunk) => {
                body += chunk
            })

            result.on('end', () => {
                var response = JSON.parse(body)
                var index = response.data.children[Math.floor(Math.random() * 99) + 1].data

                if (index.post_hint !== 'image') {

                    var text = index.selftext
                    const textembed = new Discord.MessageEmbed()
                        .setTitle(subRedditName)
                        .setColor(9384170)
                        .setDescription(`[${title}](${link})\n\n${text}`)
                        .setURL(`https://reddit.com/${subRedditName}`)

                    message.channel.send(textembed)
                }

                var image = index.preview.images[0].source.url.replace('&amp;', '&')
                var title = index.title
                var link = 'https://reddit.com' + index.permalink
                var subRedditName = index.subreddit_name_prefixed

                if (index.post_hint !== 'image') {
                    const textembed = new Discord.RichEmbed()
                        .setTitle(subRedditName)
                        .setColor(9384170)
                        .setDescription(`[${title}](${link})\n\n${text}`)
                        .setURL(`https://reddit.com/${subRedditName}`)

                    message.channel.send(textembed)
                }
lament rock
#

now is the current timestamp in milliseconds. 1000 * 60 * 60 * 24 * 10 = 10 days as milliseconds.
if (now - 10days > user created at as a number) doThis()

distant cobalt
#

ok

harsh blade
#

wait nevermind, managed to fix it bruh
just needed to define the message which i forgot

#

its 2 am bruw

drowsy grail
#
pgrep 'node' | xargs ps -o pid,user,%mem,command -p $1 | sort -b -k3 -r | tee /dev/stderr | awk '{mem += $3;} END {print mem}'; echo '%MEM TOTAL'```
lil command to show how much memory node processes are using, for some reason pm2 doesn't show you an accurate number
long marsh
#

๐Ÿ‘€

lament rock
#

or in native JS

const ram = process.memoryUsage()
console.log(ram.rss - (ram.heapTotal - ram.heapUsed))
long marsh
#

Heh, or in Docker

docker ps -q | xargs docker stats --no-stream
#

KIDDING

earnest phoenix
#

hey

long marsh
#

๐Ÿ‘‹

#

Also, hey Zero!

earnest phoenix
#

how can i check if an id is inside the db? i'm using easy.database cause i have about 5 IDs only

solemn latch
#

never heard of it, should look at the docs for that database

earnest phoenix
#

i mean check the data inside the db

#

get data

distant cobalt
#
client.on('guildMemberAdd', member => {

    const embed = new Discord.MessageEmbed()
        .setTitle('Member Joined')
        .setAuthor(member.user.displayAvatarURL(), member.user.tag)
        .setDescription(`\`${member.user.tag}\` has joined the server.`)
        .setThumbnail(member.user.displayAvatarURL())
        .setFooter(`Member ID: ${member.user.id}`)
        .setColor('GREEN')
        .setTimestamp()
    member.guild.channels.cache.get('779410338336210956').send(embed).catch(console.error);

    if((Date.now() - (1000 * 60 * 60 * 24 * 10)) > user.createdAt.getTime()){
        const embed2 = new Discord.MessageEmbed()
            .setTitle('![warning1](https://cdn.discordapp.com/emojis/798320022182690817.webp?size=128 "warning1") Warning!')
            .setDescription('User has joined the server and user\'s account age is under 10 days!')
            .setColor('ORANGE')
            .setFooter(`Account Creation: ${member.user.createdAt}`)
            .setTimestamp()
        member.guild.channels.cache.get('779410338336210956').send(embed2).catch(console.error);
    }
})``` when a user joins the server nothing happens
solemn latch
drowsy grail
long marsh
quartz kindle
#

i ran that and got a very similar result to what pm2 shows

drowsy grail
quartz kindle
#

it should show correctly if you set the sharding manager to worker mode

drowsy grail
#

because it's displaying my memory use as 110mb while each shard is running around 400-500mb each

#

yea, I'm using process mode

#

is worker mode favorable?

quartz kindle
#

its more memory efficient since there's only one node.js instance controlling all threads

lament rock
#

workers share the same memory spaces and caches

#

it's just spreading the ws connections across different threads

drowsy grail
#

and they can restart individually as well?

quartz kindle
#

yes

lament rock
#

uhhhh. Depends on what you mean by restart

#

workers share the same global variables, so process.exit ing 1 of them exits all of them

distant cobalt
#
client.on('guildMemberAdd', member => {

    const embed = new Discord.MessageEmbed()
        .setTitle('Member Joined')
        .setAuthor(member.user.displayAvatarURL(), member.user.tag)
        .setDescription(`\`${member.user.tag}\` has joined the server.`)
        .setThumbnail(member.user.displayAvatarURL())
        .setFooter(`Member ID: ${member.user.id}`)
        .setColor('GREEN')
        .setTimestamp()
    member.guild.channels.cache.get('779410338336210956').send(embed).catch(console.error);

    if((Date.now() - (1000 * 60 * 60 * 24 * 10)) > user.createdAt.getTime()){
        const embed2 = new Discord.MessageEmbed()
            .setTitle('![warning1](https://cdn.discordapp.com/emojis/798320022182690817.webp?size=128 "warning1") Warning!')
            .setDescription('User has joined the server and user\'s account age is under 10 days!')
            .setColor('ORANGE')
            .setFooter(`Account Creation: ${member.user.createdAt}`)
            .setTimestamp()
        member.guild.channels.cache.get('779410338336210956').send(embed2).catch(console.error);
    }
})``` when a user joins the server nothing happens
solemn latch
#

is the member in the guild that channel is in? member.guild.channels.cache.get('779410338336210956')

quartz kindle
#

In Worker threads, this function stops the current thread rather than the current process.

lament rock
#

Oh. Huh. I thought you had to send the worker a specific signal to kill specifically

drowsy grail
#

so does that mean you can fetch a single user object across any shard?

lament rock
#

yeah

quartz kindle
#

no

lament rock
#

Don't they share the same caches?

quartz kindle
#

you still need broadcastEval

#

workers still have separate heaps

drowsy grail
#

icic

lament rock
#

heaps or caches?

quartz kindle
#

heap memory

#

which includes djs caches

lament rock
#

I was told worker_threads share the same memory space

quartz kindle
#

and any user code

#

from an operating system point of view they do, they are seen as a single process with multiple threads

drowsy grail
#

well I faced a roadblock with sharding earlier since I can only listen to dms on shard 0

quartz kindle
#

workers share the same node.js process, so you dont need separate node.js instances

#

but they have separate heaps

drowsy grail
#

so I'm just trying to figure out if I can pass objects between shards more easily

#

i see

lament rock
#

Node docs declare they share the same global constant which would imply require cache would be shared since the require global would be the same across each thread

lament rock
#

re-reading the docs to find where. I remember reading that somewhere which is why I initially migrated to worker threads

quartz kindle
#

if you have 2 shards using workers, and you eval client.guilds.cache.size, you'll see half of the total guilds

lament rock
#

Okay. Now I'm reading that 2 workers can't mutate the same reference which is two completely different things

drowsy grail
#

why does a cluster use less memory? because there's only one node process?

#

*worker

lament rock
#

There's some overhead with node, so yes

quartz kindle
#

worker threads CAN share memory, but its more complicated than that

drowsy grail
#

makes sense

lament rock
#

I did read there was a SharedArrayBuffer class

quartz kindle
#

you can transfer buffers from one worker to another, and there is a sharedArrayBuffer

#

but only buffers and http handles are transferable objects

#

you cant transfer objects

lament rock
#

so then, they do share the same memory space, but they don't

quartz kindle
#

like, if you create a buffer in worker 1

solemn latch
#

gotta love programming

quartz kindle
#

and you transfer it to worker 2

#

it will stop existing in worker 1

#

if you try to access the reference it will throw an error

#

the memory address was transfered ownership to worker 2

solemn latch
#

so its a handoff more than shared memory?

quartz kindle
#

if you dont transfer it, it will create copy instead

#

the SharedArrayBuffer class is the only exception, it can be transfered across workers without losing ownership

lament rock
#

Alright. That makes more sense. Is the standard send duplicating or is it transferring ref ownership?

quartz kindle
#

its the only truly shared memory

solemn latch
#

i could see both being used frequently

drowsy grail
#

tim where'd you learn all this

lament rock
#

Also, I haven't bothered to check if you can only post primitive values or fully instanciated classes from another worker.

quartz kindle
#

port.postMessage(value[, transferList])

#

thats how you transfer between workers

lament rock
#

Alright so it is transferring

quartz kindle
#

you put values, ie an object, a class, a function, etc, in the value field

#

then you put any transferable thing you want to transfer in the transferList

#

if you put a buffer in the value, and in the transferList, it will be transfered. if you put it only in the value, it will be copied

#

transferList may be a list of ArrayBuffer, MessagePort and FileHandle objects. After transferring, they are not usable on the sending side of the channel anymore (even if they are not contained in value). Unlike with child processes, transferring handles such as network sockets is currently not supported.

If value contains SharedArrayBuffer instances, those are accessible from either thread. They cannot be listed in transferList.

value may still contain ArrayBuffer instances that are not in transferList; in that case, the underlying memory is copied rather than moved.

lament rock
#

What if you post a class which has a property that references something in use by one worker? Would it be duplicated or would all of the child references be transferred?

quartz kindle
#

a class is not transferable, it will be copied

lament rock
#

Alright. I see.

quartz kindle
#

all references it contains should be copied with it

#

passing data between workers does not have the same limitations as IPC between child processes (which needs to serialize to json)

drowsy grail
#

that is super cool

quartz kindle
#

you can send more complex data without any problems

#

value may contain circular references.
value may contain instances of builtin JS types such as RegExps, BigInts, Maps, Sets, etc.
value may contain typed arrays, both using ArrayBuffers and SharedArrayBuffers.
value may contain WebAssembly.Module instances.
value may not contain native (C++-backed) objects other than MessagePorts, FileHandles, and KeyObjects.

distant cobalt
lament rock
#

Oh. That's nice. I was assuming it was only primitive objects that could be transferred

#

Or just passing a reference which you could mutate across workers

#

Guess I'll have to make some optimizations and possibly use SharedArrayBuffer

quartz kindle
#

nothing except SharedArrayBuffer can exist in more than one worker simultaneously

lament rock
#

Unfortunate

quartz kindle
#

there is a propostal for a GrowableSharedArrayBuffer

#

i cant wait for it

lament rock
#

What would that implicate?

quartz kindle
#

SharedArrayBuffer cannot be resized

#

if you create one 4mb big, it stays 4mb big

lament rock
#

Is there a max ArrayBuffer size

quartz kindle
#

depends on node, os, etc, but im pretty sure it should handle at least 4gb

lament rock
#

Oh okay. So just the default max memory size

#

I wonder how a resizable SharedArrayBuffer would work; If they'd just do it similar to Objects where data added after instanciation is just appending a reference to another address

quartz kindle
#

i dont think so

lament rock
#

Unless you can resize in C++

quartz kindle
#

arraybuffers are essentially low level memory blocks, pretty sure they are contiguous

lament rock
#

Ah I see

quartz kindle
#

the proposal also includes ResizableArrayBuffer

#

but the shared one is only growable, not resizable

#

because they deemed it dangerous to shrink shared memory

lament rock
#

I can probably see why

#

Although node doesn't particularly have to be safe. Lower level languages can be unsafe

quartz kindle
#

but they dont want node to be unsafe

#

they want it to be idiot proof

#

well, if you really want to, just code in c++

#

pretty sure you can multithread all you want in c++ land, then just interface it with node-addon-api

lament rock
#

Does that basically just implement the node interpreter?

#

nvm. Reading the git

#

At that point, I'd just rewrite the entire application in a lower level language

quartz kindle
#

node itself is built in c++

#

so you can integrate your own c++ code as a shared library and similar

lament rock
quartz kindle
#

you can easily cause segfaults with N-api xD

#

maybe also wiht wasm

earnest phoenix
#

doing user32 calls from cpp and then interfacing it

quartz kindle
#

ye

opal plank
#

time to learn cpp

#

cant steal my js code if it aint in js WeSmart

quartz kindle
#

wasm :^)

earnest phoenix
#

this + webpack + javascript obfuscator will protect your source a fuckton

sudden geyser
lament rock
#

time to completely clean my git history and implement this

sudden geyser
#

Why do that

lament rock
#

public source code but non permissive license is what's currently implemented, but just for the meme lords that wanna try to recreate some of my systems. I'm relatively small currently so could be easy for someone to pull

late spade
#

Hi

#

Does anyone know how to code a dm help command on DBscript

shy turret
#

Does anyone know good places to advertise a game?

solemn latch
#

steam

shy turret
#

too poor

#

requires $5

gilded olive
#

That is quite low

sudden geyser
#

I remember using Steam when I only spent $4.54

#

Dark days

distant cobalt
#
const role = message.guild.roles.cache.find(role => role.id === '798347600910614538');
message.member.add(role)```
mellow kelp
#

member doesn't have an add() method

#

you could use member.roles.add('role-id')

distant cobalt
#

okay

crimson vapor
#
distant cobalt
#
const role = message.guild.roles.cache.find(role => role.id === '798347600910614538');``` how do i change this to tostring?
crimson vapor
#

change what to string?

distant cobalt
#

The role

#

it's in a title

crimson vapor
#

if you are displaying on a web page or something, use Role.name

#

iirc

#

because role.toString() replaces it with the mention

#

iirc

distant cobalt
#

okay

#

do remove a role you just do message.member.roles.remove(role here) right?

sudden geyser
#

See the docs!

analog horizon
#

is there a minimum age to verify a bot

#

like when you verify your identity on stripe

lyric mountain
lyric mountain
#

14 in some places

analog horizon
#

oh so if ur allowed on discord ur allowed to basically

lyric mountain
#

Stripe itself doesn't impose any age rule, it's discord who will handle the data

distant cobalt
#
{
    "token":"No stealing my token dude"
}```

```js
client.login(require('./config.json').token);``` so i put my token in a JSON file. WHen i put it into a panel for hosting, can the devleopers of the hosting panel see the token?
lyric mountain
#

If you share the file, yes

earnest phoenix
#

they would see it regardless because those are their machines

lyric mountain
#

Json files are normal files

distant cobalt
#

uhh how do i make it not visible or unable to ope nthe JSON file?

lyric mountain
#

Use environment var maybe

distant cobalt
#

How do i use that?

earnest phoenix
#

again they would see it because those are their machines

lyric mountain
#

Or use some external file storage

earnest phoenix
#

they won't use it though, stop being paranoid

distant cobalt
#

okay

shy turret
lyric mountain
#

I guess so, it'd be quite easy to get $5 wallet

sturdy dock
#

So my bot currently stores all user data in (persistent) arrays but if I am correct this won't work if/when I use sharding. What would be the best way to have a single database all shards can access at once? library is discordjs

#

mysql db?

lyric mountain
#

Ok, let's start again

#

Persistent arrays?

sturdy dock
#

yeah...

#

dont question it

lyric mountain
#

Dot dot dot

#

Ok, what kind of data are you storing?

sturdy dock
#

probably not the smartest decision

#

user balances

#

and inventories

lyric mountain
#

Does it have a lot of relationships?

sturdy dock
#

it's an economy

#

with cross-server interaction

#

so it has to be a singular DB

lyric mountain
#

No, i mean

#

Is everything isolated or everything is linked together?

sturdy dock
#

linked

#

cross server

lyric mountain
#

Stop saying cross server

#

That's irrelevant

sturdy dock
#

what do you mean by linked

lyric mountain
#

Do you have sql knowledge?

sturdy dock
#

i've used phpmyadmin

lyric mountain
sturdy dock
#

but mostly for webdev

#

sorry if i'm not following you, this is kinda new to me lmao

lyric mountain
#

User A has inventory, balance, sub-inventories, cart, etc etc

#

Sorry for the delay

sturdy dock
#

no worries

#

yes

#

user ID is linked to other data values

lyric mountain
#

By linked I mean tables that access data stored in another table

#

Relationships

sturdy dock
#

ok ok i gotcha

#

yep

#

it does

hard anchor
#

Hi everyone, I need help on discord.js, someone knows how to send images in a JSON file

lyric mountain
#

Then sql is probably the best solution

#

Have you used sql before?

sturdy dock
#

would i make a single database server, then each of the shards links up to that endpoint?

#

yeah

lyric mountain
#

Phpmyadmin isn't sql, it's a database manager

sturdy dock
#

but mostly for wordpress

#

yeah

#

i think i used mariadb?

lyric mountain
#

Ok, so you know basic CRUD operations? (create, read, update, delete)

sturdy dock
#

not... really

#

i can read up on that

lyric mountain
#

What I mean is like:

#

CREATE TABLE bla bla bla

#

SELECT * FROM bla bla bla

#

UPDATE bla bla bla SET bla bleh

sturdy dock
#

hmm

#

not really nope

#

i've used visual DB managers but none of the code

lyric mountain
#

You'll need to practice it a bit then, since you'll need to use CRUD for operations inside the code

sturdy dock
#

will do for sure

lyric mountain
#

About the database, I suggest postgresql

#

It does have Phppgadmin if you're used to php-based managers

sturdy dock
#

gotcha

#

oh that's nice

lyric mountain
#

And pgadmin4 if you wanna go fancy

sturdy dock
#

haven't touched sql in years so ill have to relearn a lot but tysm!!

#

what's the best npm module for interacting with DBs?

lyric mountain
#

That's something I can't answer, im not used at all with node

sturdy dock
#

alright

#

thanks so much for your help though, i really appreciate it

lyric mountain
#

I'd suggest also reading about OneToMany/ManyToOne/ManyToMany relationships, you'll use it a lot

#

And basic database sanitization, to keep your data safe

sturdy dock
#

will do

#

thanks again

topaz prairie
#

I'm a little stuck on posting server count and shard count, the following code isnt working, ive also tried logging something if the post is successful but nothing has been logged

client.on('ready', () => {
    setInterval(() => {
        dbl.postStats(client.guilds.cache.size);
    }, 1800000);
});```
lyric mountain
sudden geyser
#

Did you wait for the interval to actually trigger

topaz prairie
#

oh ok thanks

cerulean ingot
#

how would i make certain features only accessible to premium users

earnest phoenix
#

check if the user is premium before executing the command...?

drifting wedge
#

how can i align something to the bottom of the page?

hard anchor
#

Hi, does anyone know how to create an anti raid bot? for discord.js

vernal basin
#

been a while since I've done this, is this not how promises are resolved

mellow kelp
#

you probably wanna use async/await

vernal basin
#

do you have any examples of that

mellow kelp
#
async function fetchJSON(url) {
  // Imagine get() is a fetch function or something idk
  const res = await get(url); 
  const json = JSON.parse(res.data);

  return json;
}
#

you can use await to resolve promises inside async functions

#

and any async function by itself returns a Promise instead

sudden geyser
# vernal basin been a while since I've done this, is this not how promises are resolved

You can use .then/.catch or async/await like Cholo demonstrated. The code you showed is correct, but the .then(...) part is useless because .then returns a promise holding the value of whatever was evaluated in the .then function you passed.

So, think of members.fetch(theID) is Promise<A>. .then(val => {return val;}) returns Promise<B> with B being the value of calling val => {return val;}.

vernal basin
#

ah so the key is to use .catch?

sudden geyser
#

If you need to handle an error, use .catch. It still returns a promise.

vernal basin
#

oh

sudden geyser
#

If you want the value inside the promise, you need to use .then or await. What to remember is you can't access the promise value directly.

mellow kelp
#

wait yeah thats a lot simpler KEKW

#

ignore what i said

timid widget
#

TypeError: message.guild.channels.find is not a function

#

any fix?

sudden geyser
#

To get the collection, use .channels.cache

vernal basin
#

so a corrected version of this would be

async function getUser(theID)
{
  let x = await message.guild.members.fetch(theID)
  return x;
}
#

?

#

oh wait i have to use await

mellow kelp
#

well i mean

sudden geyser
#

An async function returns a promise resolving to whatever value is returned from the function

mellow kelp
#

you can just avoid async/await altogether

#

well that also works

vernal basin
#

oh so i have to resolve it

#
function resolveAfter2Seconds(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
}

async function f1() {
  var x = await resolveAfter2Seconds(10);
  console.log(x); // 10
}

f1();

so in this example the 1st function returns a new promise that resolves to x, so when f1 is called it unboxes the promise and returns 10?

misty sigil
#
    client.db.redis.get(`${data[0]}_p`, function(err, d) {
      console.log(err, d);
      if (d) {
        return d;
      } else {
        // eslint-disable-next-line max-len
        const find = client.db.collection('prefixes').findOne({'g_id': data[0]}).then((doc) => doc.prefix || undefined);
        if (find) {
          client.db.redis.set(`${data[0]}_p`, find);
          return find;
        } else {
          client.db.redis.set(`${data[0]}_p`, 'ab!');
          return 'ab!';
        }
      }
    });``` just me being a twat or should this work?
#

i can console.log it and d is the prefix

#

but it returns undefined

mellow kelp
#

that works exactly as you intend

sudden geyser
#

The callback's value won't be used.

#

So returning a value means nothing.

misty sigil
#

oh right

sudden geyser
#

So either chain it with another callback or use promises as an alternative

mellow kelp
#

you can promisify it and use async/await

drifting wedge
#

if i use a div to make a box

#

how can i add an href to it?

vernal basin
#
function getMember(theID) {
  return message.guild.members.fetch(theID);
}
async function getUser(theID) {
  return await getMember(theID);
} 
#

does this also work?

mellow kelp
#

yea

#

both of those work exactly the same way

vernal basin
#

okay

#

this seems awfully circuitous to find a member by ID

#

is there a faster way

#

or maybe a way to encase 1 function in the other to tidy the code?

mellow kelp
vernal basin
#

okay

mellow kelp
#

that's pretty much everything

#

@drifting wedge you can wrap the div around an anchor tag

vernal basin
#

tysm, was really confused about promises LOL

mellow kelp
#

apparently that's semantically correct as of html5

drifting wedge
#

wdym anchor tag?