#development

1 messages · Page 787 of 1

quartz kindle
fiery stream
#

ayy

#

im making a new disord bot should i use defualt js or typescript

#

idk the diff tho

earnest phoenix
#

one is typed one is not

#

one is prone to retardation one is not

fiery stream
#

and which one is which

uneven wyvern
#

@quartz kindle hm how why 25 and not 24?

earnest phoenix
#

typed is _type_script
the retarded one is javascript

#

thank you discord formatting

quartz kindle
#

typescript is converted to javascript in the end anyway

mossy vine
#

^

earnest phoenix
#

yeah

#

typescript is a superset of javascript

mossy vine
#

but at least it errors are compile time

earnest phoenix
#

however in js you see well uh

#

stupid people doing stupid things

#

e.g making up their own properties on objects

fiery stream
#

which one should i use

earnest phoenix
#

if you like strictly typed langauges; typescript, otherwise go for js

copper cradle
#

Go Lang

#

Or python

#

Js bad

fiery stream
#

js is best for dcord bots

earnest phoenix
#

lol no

fiery stream
#

it is atleast fo rme

copper cradle
#

Js === retarded //true

mossy vine
#

@copper cradle retarded is undefined

quartz kindle
#

@uneven wyvern "11001" = "yes,yes,no,no,yes" = "16,8,4,2,1" = "16 yes, 8 yes, 4 no, 2 no, 1 yes" = "16 + 8 + 1" = 25

fiery stream
#

yooooo

copper cradle
#

😔

earnest phoenix
#

singlethreaded will never be the best especially on something that's dependant on so many gateway events

fiery stream
#

is there any significant difference in code after compiling ys

#

ts

mossy vine
#

not really

copper cradle
#

Sometimes

uneven wyvern
#

OHH FUCK NOW I KNOW WHAT I DID WRONG ty Tim

copper cradle
#

If you try to turn esnext into es3

#

Say

quartz kindle
#

the difference is that supposedly ts compiles to "good and proper" js

copper cradle
#

async/await

quartz kindle
#

so your final js may look weird/complex, but maybe more efficient

copper cradle
#

Yes

fiery stream
#

and last question

copper cradle
#

Just learn python

#

Easy for begginers

#

And good af

fiery stream
#

ik python but i love to use js

copper cradle
#

Then learn Go

fiery stream
#

nah i would rather use rust

#

what ever

#

how do i compile all the files in ts

#

in single command

quartz kindle
#

with a compiler

copper cradle
#

tsc *. ts

#

I think

earnest phoenix
#

typescript docs cover that

mossy vine
#

rust is cool af

fiery stream
#

oof tim is apparently the smartest person in the workd

#

@mossy vine ikr

quartz kindle
#

i am the trollest

fiery stream
#

@copper cradle thx

grizzled raven
#

oh so now i know how binary works

#

i think

#

😳

#

wait obv not

earnest phoenix
#

it's not that hard

grizzled raven
#

let me rephrase

#

i think i know how to convert binary to numbers now cough

copper cradle
#

10101010 10101001 10101001

grizzled raven
#

no

earnest phoenix
#

to convert decimal to binary you divide your number by 2 until you get to 1/2, if you have remainder(s) in the division you write it up as a 1, if not, write it up as a 0, once you're done read it down to up and you got your binary num

#

i think numeric notiations is the first thing you cover in CS

fiery stream
#

ayyy

#

how do u make initial typescript proj

copper cradle
#

Like a js proyect

earnest phoenix
#

read 👏 the 👏 docs 👏

fiery stream
#

i found nothing about setting up proj

#

actually imma just use defualt js

#

nvm i found it

twin pendant
#

i wanna implement a music player into my bot, but i feel like it'll be very taxing on the hardware. anyone know if music systems take a lot of cpu/ram? (d.js)

modest maple
#

Yes they do

#

The bigger the bot, the more players the higher the usage

amber fractal
#

They eat cpu

twin pendant
#

mhmm might just stick to text & image based stuff then thanks

#

bc my vps has 1gig of ram hahah

tulip wave
#

each stream can easily take 20% of a single core

amber fractal
#

just get infinite cores

#

ez

twin pendant
#

damm, dont know what type of cpu i got but im sure its not gonna be that powerful on a vps hosting 60 other vm's

quartz kindle
#

imagine how much Rhythm costs per month

modest maple
#

Considering they run on multiple machines apot

#

Alot*

#

But also consider it's owned by digital ocean

#

Zero

#

Lmao

quartz kindle
#

its owned by DO?

#

was it made by them or did they buy it?

modest maple
#

Think it was made by one of the employees

quartz kindle
#

he better have gotten a large amount of cash for it

modest maple
#

I mean great publicity for DO for people wanting to host bots on their systems

#

Saying we host the biggest bot in discord

quartz kindle
#

yeah, but if it was made by an employee with his own free time and not like sponsored from the beginning

#

he better be getting a cut of the profits

#

else its a company abusing an employee's creation

twin pendant
#

true

quartz kindle
#

just like universities do with their students

#

getting most of the credits for the students' research and thesises

#

lul

blissful scaffold
#

I doubt they make any profits on Rhythm

twin pendant
#

how would you even profit off a bot?

blissful scaffold
#

He could have made it during work times, then it's usually fully owned by the company

twin pendant
#

showing ads on the website?

modest maple
#

They almost 100% will

#

And premium commands

#

People pay for premium features

twin pendant
#

oh yeah that

modest maple
#

And considering rythm has 6 million guilds and god knows how many users it seems pretty reasonable to ponder at the sheer amount they make on their premium commands that actually makes the audio quality alright not shit

quartz kindle
#

the value of a company/creation is not defined only by how much profit it gets

#

sometimes companies operate on negative income and are still worth millions

#

simply because of the market reach they have

#

rhythm has a reach of 5 million servers and god knows 50+ million people, who are directly interested in music, so its one hell of a market reach

#

imagine they suddenly decide to put youtube/radio style ads in their streaming

#

thats instant potential millions of people reached by a single ad

#

although how many people are actually listening to it is probably only a couple thousand lul

modest maple
#

Nah 5 mill servers your looking at maybe tens of thousands of players

#

chip gets around 70 - 100 players at a time with 14k servers

earnest phoenix
#

Is it possible to have the bot upload custom emoji to a server using the URL?

quartz kindle
#

yes

summer torrent
#

@earnest phoenix which library do you use

earnest phoenix
#

discord.js

quartz kindle
#

(for v11 stable)

summer torrent
#

^

earnest phoenix
#

perfect

#

thank you very much

abstract crow
#

Is there any way in VS2019 I can just view one tab at a time in an actual editing environment? I have these arrows and I don't like it. I am using Xamarin.IOS
https://images.vinniehat.com/i/z0iammz55urc6f2.png

That and to display the phone itself so I can see the notch

weak parrot
#

Haven't used Xamarin yet so sadly unable to help

topaz fjord
#

solution

#

use xcode

wet ferry
#

^

grizzled raven
#

dont doubt codingpro

topaz fjord
#

Anyone know how to serve gzip files with nginx

#

I'm using the compression plugin with webpack

tidal sparrow
#

anyone know any good mongodb hosts?

late hill
#

Host it on the system that'll use it if possible

amber fractal
late hill
#

mongodb doesn't require much so any server rly

amber fractal
#

but yeah if you can do it on your own system it'll be faster

late hill
#

If you can't and do need an "external" database, their free offer is pretty good, but if that doesn't meet your needs, I'd recommend just getting a vps and installing mongo on it yourself

#

You can probably get a better setup for less money

wicked pivot
#

possible to find in a precise channel a precise message example an id of user followed by its number of sanction? "

tidal sparrow
#

atlas won't work for me lmao

#

cheers 👍

hushed berry
#

@wicked pivot .....what

wicked pivot
#

this is more important
@hushed berry

hushed berry
#

???

wicked pivot
#

on the other hand I have another question how to put the date of creation of a user in day

amber fractal
#

@hushed berry idk if that's english

hushed berry
#

pensive

wicked pivot
hollow shadow
#

why 80% of the bots are made using js???

quartz kindle
#

because its currently the most popular language, plus its easy to learn compared to most others

weak parrot
#

looks at queue: unlikely mmLol

quartz kindle
#

whats the most popular in the queue?

weak parrot
#

No I mean that wouldn't be the reason for it being the most used language when looking at queue/a majority of bots that have been added as of late

sudden geyser
#

🥣

quartz kindle
#

you mean despite being easy to use (compared to most others) most bots are still shit, which suggests its not actually easy to learn?

weak parrot
#

No what I mean is a lot of them come from tutorials, templates and stuff like that

quartz kindle
#

oh lul

#

well then its the most popular for the simple fact of popularity and community enthusiasm

#

what a shit reason lmao

weak parrot
#

I mean documentation is also always a big reason

quartz kindle
#

js = herd mentality language

#

lang for the masses

weak parrot
#

Pretty much

amber fractal
#

2018 data*

weak parrot
#

Usually when you search for something Discord bot related JS based stuff will usually be one of the top results which obviously will pull even more people to it. It's usually people that where already programming or people programming long enough to want and try other languages that use something besides JS for their bots obviously not always the case but a lot of the time

#

World wide programming language usage doesn't hold much weight when talking about Discord bots

quartz kindle
amber fractal
#

arent those for questions tho

quartz kindle
#

most loved languages

#

lmao

#

Stack Overflow’s annual Developer Survey is the largest and most comprehensive survey of people who code around the world. Each year, we field a survey covering everything from developers’ favorite technologies to their job preferences. This year marks the ninth year we’ve published our annual Developer Survey results, and nearly 90,000 developers took the 20-minute survey earlier this year.

regal saddle
#

wait

#

python is the second? lol

sudden geyser
#

I can see people disliking Java

#

but our old timer C 😦

fiery stream
#

Why objective c

sudden geyser
#

apple

regal saddle
#

is JavaScript also counting for Java?

#

or is it so underrated? 😦

sudden geyser
#

Java and JavaScript are very different.

regal saddle
#

i know, but why isnt it listed?

#

oh nvm

#

there are 3 pictures and i only saw 2

stable horizon
#

Jesus rust is high

earnest phoenix
#

Hi, I have an oylan problem that sometimes my bot stops automatically, and since I can't really find the answer to the error code, it doesn't ruin my decision, I can't solve it if it stops automatically then start it Operating System Linux server (UBUNTU 18)

wicked pivot
#

is it possible to put the name of the custom status and not this?

zenith orchid
#

@wicked pivot wich lang?

#

Library*

wicked pivot
#

js

zenith orchid
#

user.presence.activities.find(a => a.type === "CUSTOM_STATUS").state for v.12

earnest phoenix
wheat jolt
#

What do you mean @earnest phoenix

zenith orchid
#

I think sending messages.

uneven wyvern
#

anyone can tell me why that doesn't creates an file?

    // a base64 string of a gif image
    
    // The absolute path of the new file with its name
    var filepath = "logindata.txt";

    // Save with a buffer as content from a base64 image
    fs.writeFile(filepath, new Buffer.from(genToken, "base64"), err => {
      if (err) throw err;

      console.log("The file was succesfully saved!");
    });
twilit rapids
#

The absolute path is the entire path to where you want to create the file

#

e.g. /root/myCoolFolder/logindata.tzt

uneven wyvern
#

oh

#
if (err) throw err;9:19 AM
9:19 AM
Error: ENOENT: no such file or directory, open 'app/logindata.txt'

the file exists but won't show

earnest phoenix
#

How can change authorized link
like when people add my bot in his servers after authorize open my own website link.

tight plinth
#

I'm searching a ez way to do a music bot in djs v12 without lavalink

earnest phoenix
#

@uneven wyvern use /app/ not app/ this can be the problem

uneven wyvern
#

it appeard but with no content in the file

earnest phoenix
#

What is in this file? Api key ? Token of your bot? You can use json this is more simple for use the content

uneven wyvern
#

Yeah Api Token what is generated by a lil fucntion

earnest phoenix
#

Oh

#

You can generate this api token directly in the code and use it

#

Store this in a file isn't good if this is valide only one time

uneven wyvern
#

@tight plinth AtlantaBot Source on GitHib is a whole Bot but also has a good Music Source

tight plinth
#

K I will try

fresh holly
#

Hello, I have a question for the DiscordBotList API in Java.

The token used to initialize the DiscordBotList object, is that of the discord bot ?

quartz kindle
#

DiscordBotList or Top.gg tokens are always the token you get in your bot's edit page in the top.gg website

#

never the discord login token

fresh holly
#

That's what I thought. So I did not find the token on the site :/

#

ah

#

no

#

it's good, Sorry

#

Thanks for reply

warm marsh
#

I know I'm probably being dumb right now, But I can't seem to find how to use lavalink anywhere. I've got it setup I just don't know how to use it.

earnest phoenix
#

How do I draw a line over if it's not an avatar gif
Disocrd.js v12

dusky marsh
#

@warm marsh it's just an api that you can use. It has various endpoints you can connect to to use it. Most languages have a client library tho so just find one and use it's documentation to go from there

warm marsh
#

I'm using it with lua and their documentation is terrible.

dusky marsh
#

lavalink has a documentation of the endpoints if you wanna make the requests yourself

warm marsh
#

Where?

dusky marsh
#

Lemme find it rq

sinful lotus
#

if you use d.js

#

just use the libraries

warm marsh
#

I'm using discordia

sinful lotus
#

if theres nothing there for your lib

#

im afaik you need to implement your own

dusky marsh
#

He says the discordia ll client sucks

#

Which I'm sure it does haha

sinful lotus
#

I just made my own lib on d.js

#

that works perfectly for my use case

#

other users also loved it

#

so I'm contented with it

dusky marsh
#

Ye same don't like relying on other libs

earnest phoenix
#

help accept my bot with new prefix s.

sinful lotus
#

nah its a public lib I created

earnest phoenix
#

s.

#

Help me

#

How do I draw a line over if it's not an avatar gif
Disocrd.js v12 || Sample

dusky marsh
#

Double tilde

#

~~text to strikethrough~~

earnest phoenix
#

But when it is gif, it does so

fresh holly
#

Can the votes take time before being counted ?

late hill
#

If you're just checking on the site, it uses cached values so it won't always be 100% accurate

fresh holly
#

hum, Even going through the DiscordBotList API?

late hill
#

The API should return live values, not sure because I don't use it

uneven wyvern
#

How can I list all People in a role

summer torrent
#

which library

uneven wyvern
#

discord.js master

summer torrent
late hill
#

And as stated in the description there^^ it'll just be cached members

#

So you might want to make sure all members of that guild are cached before doing so

fresh holly
#

The "player" variable is me but when I retrieve it if I am an administrator, it returns "false". And if I check the identifier of a person who voted, it also returns "false"

late hill
#

I'm pretty sure that admin check is for like admins of the site

fresh holly
#

ah ? It's not bot admin ? Okay why not but for the vote it doesn't change anything :/

bitter sundial
#

why would that have anything to do with your bot admin?

#

the admin thing in dbl is for the admin badge on the site and in

#

-bots

gilded plankBOT
#
Bots <:dblAdmin:483994951961673738>

@pliant gorge
@gilded plank
@abstract aspen

fresh holly
#

As we connect with a token provides for the management of our bot. it could have been the bot administrators.

#

but no problem that's one less worry.

#

now for the votes i'm having trouble doing something but I don't know.

late hill
#

hasVoted isn't as fast as just using the webhooks, but it should be fine for what you're doing I guess.
Did you make sure that it's actually returning false and not just something else in your code that's going wrong?

fresh holly
#

Yes i think. voted is a boolean and throwable is undefined so no error.

fresh holly
#

I found.

#

I'm stupid ^^

#

I did not give the correct bot identifier. xd

south plover
#

can someone help me please

#

@fresh holly

#

@bitter sundial

#

anyone

low wasp
#

Dont pong people

#

Just wait for someone to help

south plover
#

ok

#

can you help

#

me with this

slender thistle
#

Do any errors appear when you run the bot

south plover
#

yep

slender thistle
#

Would you mind showing them

south plover
#

ok wait

#

see

#

@slender thistle

slender thistle
#

... aside from that

south plover
#

nothing

slender thistle
#

are you sure the file is saved

south plover
#

yep

tight plinth
#

New hoister

south plover
#

hoister

#

??

restive furnace
#

ur name has special letters

modest maple
#

You actually mind sharing your full code

#

Not the lil core snippet that tells us nothing

south plover
#

how

short siren
#

copy + paste

visual sandal
#
message.guild.createRole({ name: 'Male', color: '#0000FF', hoist: true, mentionable: false });
#

umm so the code runs but doenst create any roles

#

any idea why?

small prairie
#

TypeError: Cannot read property 'send' of undefined
When i am using
client.channels.get("ID").send("blablabla")
Yes I checked ID Is Valid

#

discord.js

#

@visual sandal Runs Fine When I use eval dunno

visual sandal
#

ok

#

it used to work yesterday but stopped working

#

today

#

I didn't change much code but it skips all the roles i create using the bot

quartz kindle
#

what do you mean "it skips all roles i create"?

small prairie
#

Any Help For Me?

#

Still doesnt work

#

i use this in client.on ready event

quartz kindle
#

are you sure the id is valid? is it a dm channel? is the channel cached?

small prairie
#

Not DM When I Use !eavl Command It Works so i guess channel is cached

#

Plus Id Is Valid

#

Used to work Like an hour ago

#

Did some bug fixing and Voils

#

Voila*

#

@quartz kindle how Can I Check if channel Is Cached?

quartz kindle
#

basically client.channels.get() or client.channels.has()

#

get wil return undefined, has will return false

small prairie
#

I said I used client.channels.get.send

#

Oh se get is returning undefined

quartz kindle
#

try console.log(client.channels.get(id))

#

also try console.log(client.channels.size)

small prairie
#

Returning undefined

late hill
#

Maybe you're executing that before the client is ready

quartz kindle
late hill
#

Which means there's no channels at all yet

quartz kindle
#

he said hes using the ready event

small prairie
#

nah channels are 173

#

Yes i am using it after i set the status

late hill
#

ok nvm 🏃

quartz kindle
#

so channels.size logs 173?

small prairie
#

Yes

#

It Should Be more tbh

quartz kindle
#

try the channel.find

small prairie
#

Like WWAAAAY MORE

quartz kindle
#

try this then

#

console.log(client.guilds.filter(t => !t.available))

small prairie
#

It was 520+ Last time used my stats command

#

But the bot is working if i used !ping command while making the .send comment

#

'517265128647950347' => Guild {
0|server | members: Collection {},
0|server | channels: Collection {},
0|server | roles: Collection {},
0|server | presences: Collection {},
0|server | deleted: false,
0|server | available: false,
0|server | id: '517265128647950347' } }

#

Sent this

#

Oh Wait

#

This is guild

#

Server

#

Where i am checking

#

@quartz kindle Server is unavailable for the bot any fix?

#

Or Discord is buggy?

quartz kindle
#

that means the server is not available, that specific server might be having problems in the discord side

small prairie
#

Ah Discord Is Buggy

#

So i just gotta wait?

quartz kindle
#

you're on v11 stable right?

blissful scaffold
#

Your bot is on that server?

small prairie
#

I guess lemme check

#

@blissful scaffold Ofc How would it be in the client.guilds list

visual sandal
#

@quartz kindle sry for the ping but..
my message.guild.createRole() does not create a role or return an error.. just does nothing

#

and continues the code

quartz kindle
#

did you await it?

#

createRole is a promise

small prairie
#

@quartz kindle Yes

visual sandal
#

await doesn't work either

small prairie
#

Its 11v

#

11.5.1

#

how can i confirm tho?

modest maple
#
{'type': 'release_get', 'url': 'http://www.crunchyroll.com/en-gb/room-camp', 'name': 'Room camp', 'episode': '5'}
[10/02/20 | 14:00:06] Starting a new task
Sending Outbound response to Release.
[10/02/20 | 14:00:06] Returning Selenium_1 to free drivers, task complete
{'type': 'release_get', 'url': 'http://www.crunchyroll.com/en-gb/room-camp', 'name': 'Room camp', 'episode': '5'}
[10/02/20 | 14:00:07] Starting a new task
Sending Outbound response to Release.
[10/02/20 | 14:00:07] Returning Selenium_2 to free drivers, task complete```

We have this log, which is fine, appart from the fact that some how, the system it send two requests and adding two tasks even tho it shouldnt.

Code:

https://paste.pythondiscord.com/mibizubohe.py <--- Release event code
https://paste.pythondiscord.com/apagipahuc.py <--- Websocket organiser
quartz kindle
#

@small prairie pretty much the only thing you can do is add if(!guild.available) return

small prairie
#

Oof Lol

#

Thats a custom bot i made

#

Only for that server

quartz kindle
#

at least that way your bot will work without throwing errors

small prairie
#

Custom bot /:

quartz kindle
#

you can make it retry after x time if the guild is not available

small prairie
#

Uh Its on pm2

#

So its automatically relogging

quartz kindle
#

yeah but thats not ideal

#

thats basically spamming discord with logins

small prairie
#

Yeah I guess

#

I stopped the bot for now

modest maple
#
Response: daily_update
{'name': 'Room camp', 'url': 'http://www.crunchyroll.com/en-gb/room-camp', 'release_time': '14:00', 'episode': '5'}
{'name': 'Yatogame chan kansatsu nikki', 'url': 'http://www.crunchyroll.com/en-gb/yatogame-chan-kansatsu-nikki', 'release_time': '17:15', 'episode': '5'}
{'name': 'Seton academy join the pack', 'url': 'http://www.crunchyroll.com/en-gb/seton-academy-join-the-pack', 'release_time': '17:30', 'episode': '5'}
Response: daily_update
{'name': 'Room camp', 'url': 'http://www.crunchyroll.com/en-gb/room-camp', 'release_time': '14:00', 'episode': '5'}
{'name': 'Yatogame chan kansatsu nikki', 'url': 'http://www.crunchyroll.com/en-gb/yatogame-chan-kansatsu-nikki', 'release_time': '17:15', 'episode': '5'}
{'name': 'Seton academy join the pack', 'url': 'http://www.crunchyroll.com/en-gb/seton-academy-join-the-pack', 'release_time': '17:30', 'episode': '5'}``` 
Update to that, seems to be that the getting daily releases is causing it to add double the tasks to the sheduler
#

idek why

visual sandal
#

my code sends a message
then reacts to the message with emojis
then creates roles
everything used to work but now it doesn't

small prairie
#

My Bot Banned From a server Can That Be The Case? @quartz kindle

visual sandal
#

i changed noting related to it

quartz kindle
#

did it get banned from the server?

#

@visual sandal show the full code

small prairie
#

Not that one

#

Other

quartz kindle
#

then it shouldnt matter

small prairie
#

Can I Try Kicking and readding?

quartz kindle
#

sure

small prairie
#

Will It work?

quartz kindle
#

idk

#

try it

visual sandal
#

my code got too long

quartz kindle
#

pastebin

small prairie
#

Oof Didnt Work

visual sandal
#

if (command === setup) { // Setup a server with Jonin
var errMsg;
if (message.guild.channels.find(channel => channel.name === "server-roles")) {
message.channel.send(**Code 11** \${config.prefix}errcodes to view error type`); return; } message.guild.createChannel('server-roles', { type: 'channel', permissionOverwrites: [{ id: message.id, deny: ['MANAGE_MESSAGES'], allow: ['VIEW_CHANNEL'] }] }) .catch(console.error) .then(() => { message.guild.channels.find(channel => channel.name === "server-roles").send(Channel: Server Roles+\n+Status: Set-Up+\n+Set-Up Triggered by: + message.author.username) }) .then(() => { let setupEmbed = new Discord.RichEmbed() .setColor('#FF0092') .setTitle(Roles for guild + message.guild.name) .addField(Gender (Optional):, 💙Him/Guy\n❤️Her/Gal\n💚Them/Other`, true)
.setFooter('Provided by: Jonin');
message.guild.channels.find(channel => channel.name === "server-roles").send(setupEmbed).then(function (message) {
message.react("💙")
.then(() => message.react("❤️"))
.then(() => message.react("💚"))
})
.catch(console.error)
});

        message.guild.createRole({ name: 'Him/Guy', color: '#0000FF', hoist: true, mentionable: false });
        message.guild.createRole({ name: 'Her/Gal', color: '#FF0000', hoist: true, mentionable: false });
    console.log(`Done`);
#

sry

quartz kindle
#

@visual sandal dont put .catch() before .then()

visual sandal
#

ok

quartz kindle
#

you're not awaiting the promises either, and not catching the last two

visual sandal
#

so use .catch for creating roles

quartz kindle
#

you should change everything to async/await syntax

visual sandal
#

ok

quartz kindle
#

its better and more readable for using multiple promises

#

await message.guild.createRole()
await message.guild.createChannel()

visual sandal
#

yea.. i was still testing if it was working at all

quartz kindle
#

then you dont need catch nor then

visual sandal
#

ok thx

small prairie
#

Ah My Server was hacing problems

#

Having*

#

I did a hard restart and its work

#

although thanks @quartz kindle

earnest phoenix
#

@somber mesa

#

ohh

small prairie
#

Wait what

#

Still

#

Weird

#

@quartz kindle Its Like It Takes Time For Bot To Get That Server

next wedge
#
async def on_message_edit(before, after):
    with open("logs.json") as l:
        log = json.load(l)
    serverid = str(after.guild.id)
    if not serverid in log:
        return
    state = str(log[serverid]["state"])
    channel = client.get_channel(int(log[serverid]["channel"]))
    if state == "on":
        embed = discord.Embed(colour=discord.Colour.gold(), timestamp=datetime.datetime.utcnow())
        embed.set_author(name="Log", icon_url=client.user.avatar_url)
        embed.add_field(name="Log", value="Message Edited, Before: **{}**, After: **{}**!".format(before.content, after.content))
        embed.set_footer(text="GidBot | {}".format(v))
        await channel.send(embed=embed)```
#

Can someone help me why its doing this?

#

🤔

modest maple
#

whats the error

next wedge
#

Nothing, it just spams that random stuff when a message is edited.

modest maple
#

only thing i can see is multiple instances running

#

i cant see anything that sceams out at me

next wedge
#

:/

slender thistle
#

Add a check to compare before.content to after.content

next wedge
#

Huh, im noob 😂

#

Btw thanks, i'll try it.

earnest phoenix
#

can someone help with the javascript eval command? its sending multiple messages

#

dose it depends on my bot ping?

next wedge
#

Thanks its worked lol.

quartz kindle
#

@earnest phoenix show code

earnest phoenix
#

Ok

#
  if (typeof(text) === "string")
    return text.replace(/`/g, "`" + String.fromCharCode(8203)).replace(/@/g, "@" + String.fromCharCode(8203));
  else
      return text;
}

client.on("message", message => {
  const args = message.content.split(" ").slice(1);
 
  if (message.content.startsWith(config.prefix + "eval")) {
    if(message.author.id !== config.ownerID) return;
    try {
      const code = args.join(" ");
      let evaled = eval(code);
 
      if (typeof evaled !== "string")
        evaled = require("util").inspect(evaled);
 
      message.channel.send(clean(evaled), {code:"xl"});
    } catch (err) {
      message.channel.send(`\`ERROR\` \`\`\`xl\n${clean(err)}\n\`\`\``);
    }
  }
});
#

@quartz kindle

mossy vine
#

no

earnest phoenix
#

Mmmm

quartz kindle
#

@earnest phoenix does it send the same reply multiple times? or does it send different things? do you have other .on("message") in your code?

earnest phoenix
#

@quartz kindle same reply

#

i can show you in my server

zenith orchid
quartz kindle
#

pm2 log

#

see if there are errors

zenith orchid
quartz kindle
#

pm2 log --lines=100

#

to see more

dull terrace
#

Who's a python expert please?

zenith orchid
quartz kindle
#

@earnest phoenix be more specific, what part you need help?

slender thistle
#

Just describe the issue, Army_

dull terrace
#

This image from Juice Ping ?

quartz kindle
#

?

dull terrace
#

fail

copper cradle
#

Wtf

dull terrace
#

sorry

zenith orchid
#

@dull terrace yep

dull terrace
#

The problem is that for a few weeks I've been looking for a way to connect my bot to a voice chat room, I've looked at the documentation but I still can't find it.
Tim is witness x)

mossy vine
#

@earnest phoenix no

zenith orchid
#

I think my exec command.
@zenith orchid true?

#

Puffff

quartz kindle
#

@zenith orchid scroll up and check the error log as well

#

pm2 has 2 separate logs, normal log and error log

zenith orchid
#

I think this

quartz kindle
#

that still doesnt help, but for now try fixing your exec errors

zenith orchid
#

@quartz kindlethx, i fixed errs. Im waiting.

#

I hope fixed pm2 errs.

twin kestrel
#

Hi everyone!
I have been receiving several errors similar to this one for about 30 minutes:

Error: Shard 0's Client took too long to become ready.

I have verified that it was the connection of my bot with Discord and it seems to be all right, I did a speed test and it also seems to mark a good speed up and down

What could be happening? (I rule out problems with the firewall, I haven't modified anything like that) 😅

#

Another example of errors that I receive

Something took too long to do.

slender thistle
#

Sounds like blocking

twin kestrel
#

I already tried a test to make sure that my VM is not banned in the API and the data it provides is normal

modest maple
#

Sounds like blocking

twin kestrel
#

Lock in what way? 😅

slender thistle
#

a command in code that takes too long to execute

twin kestrel
#

It was the first thing I discarded

#

Error: Shard 0's Client took too long to become ready.
This error throws it at me because I have a webhook as soon as the client is ready

#

But neither does my bot appear online, that's the problem

modest maple
#

send your code

#

but pretty sure thats blocking the event

twin kestrel
#

I didn't change anything about the events in 1 month

#

I can't send the code

#

How strange, now if it connects (and I changed absolutely nothing)

#

Oh no

#

I already found the problem

#
curl -I https://discordapp.com/api/v7/gateway
HTTP/2 429
date: Mon, 10 Feb 2020 18:59:36 GMT
content-type: application/json
retry-after: 447
cache-control: no-cache
set-cookie: __cfduid=d87f1ad5b7c8a7b9df9ab0ce6efd744d61581361176; expires=Wed, 11-Mar-20 18:59:36 GMT; path=/; domain=.discordapp.com; HttpOnly; SameSite=Lax
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
server: cloudflare
cf-ray: 563052365b8bf1c6-ATL```
#

They limited my bot? 🤔

safe nacelle
#
    at Function.Module._resolveFilename (module.js:548:15)
    at Function.Module._load (module.js:475:25)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/rbd/pnpm-volume/85843778-0fdd-44f9-8e70-e4d22104fdd8/node_modules/.registry.npmjs.org/canvas/2.6.1/node_modules/canvas/lib/bindings.js:3:18)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)```
#

hm

shut cipher
#

What experience/languages would be needed to develop a web dashboard

visual sandal
#
message.guild.emojis.find(emoji => emoji.name === `Male`).delete().catch(console.error);

would this line properly find and delete a custom emoji by name...

uneven wyvern
#

@shut cipher html/css/js

#

all u basicly need

shut cipher
#

Kk ty

split hazel
#

and the main server that does everything can be anything ranging from python/js to java

#

pretty much every language

#

thats made to run server side

summer torrent
shut cipher
#

Is there a benefit to learning CSS instead of HTML

#

Because from what I’ve read these languages do the exact same shit

#

HTML, the Hypertext Markup Language, is a standard for describing the structure and presentation of information via the Internet. Web developers use HTML keywords or tags to instruct the Web browser application how to format and display the content of Web pages.

#

CSS is the language for describing the presentation of Web pages, including colors, layout, and fonts. It allows one to adapt the presentation to different types of devices, such as large screens, small screens, or printers. CSS is independent of HTML and can be used with any XML-based markup language.

visual sandal
#

Lmfaooo

#

well it doesn't work.. so help

#

?

modest maple
#

well does the guild have an emoji called male

visual sandal
#

yes.. the previous command creates the emoji.. but the "cleanup" command doesn't delete the emojis

#

i get this error

(node:4) UnhandledPromiseRejectionWarning: TypeError: message.guild.emojis.find(...).delete is not a function
modest maple
#

that error is pretty self explanitory

visual sandal
#

yea

#

ik

#

im dumb

earnest phoenix
#

@shut cipher html and css complement each other, so there isn't learning one over the other, you learn both for web work since html is mainly templating while css is styling the template

modest maple
#

big question here

#

do i:

#

upon a upvote

#

store time stamp

#

and have a loop checking if votes have an expired time stamp

#

or

earnest phoenix
#

no

modest maple
#

do i use my cron system to just shedule the removal

earnest phoenix
#

yes that

modest maple
#

thought so

earnest phoenix
#

looping when there isn't anything to do in the loop except an if check is stupid and expensive on cpu work

modest maple
#

what i was thinking]

#

altho i do need to check if my fucking system will actually not double trigger

#

for what ever reason it is doing it

#

but that might of been an invalid kwarg given on my end]

modest maple
split hazel
#

Does anyone know a dataset of toxic & neutral messages? All datasets i saw contain link, weird characters/unicode which hinder the networks training

#

Not too long comments either

blissful scaffold
#

if all the data sets contain messages that break your training network then it is probably the easiest to filter those messages out?

split hazel
#

Well yes but I also couldn't find a reasonable dataset

#

Most of them are tweets that aren't even accurately labeled as toxic or neutral

floral bloom
#

Discord.js
I have two questions.

#1 - How do you await a response in direct messages?
#2 - Is there a more efficient way to make a reaction collector/message collector?

Please ping with response.

earnest phoenix
#

what do you mean more efficient

#

and no, message collector

floral bloom
#

As in, if I have a menu where you click numbers to go to a new menu and also use a number to go to the previous page, how do I do this without having a billion .then(if () {} else if () {}) in the code?

#

Because the code already has over 300 lines of code. And that's with a command handler.

#

353

summer torrent
floral bloom
#

78% of that file is the reaction collector.

quartz kindle
#

you can have pages saved in an object or a class for example

#

then on reaction load x page

#

and go back to waiting

#

a recursive function for example

summer torrent
floral bloom
#

Thanks, I'll look into it! 🙂

earnest phoenix
#

Kral @summer torrent

summer torrent
#

?

wicked pivot
#

someone can help me

if(message.content.startsWith(prefix + "bannedinfo")){

      let GetIdUser = args[0]
      if(!GetIdUser)return message.reply("Indiquez l'id de le présumer ban")//State id to presume ban
      message.guild.fetchBans(true).then(bans => {
        let users = bans.filter(UserGet => UserGet.user.id === GetIdUser)

        if(users.first().username === undefined){
          return message.reply("L'utilisateur n'est pas ban / l'id indiquer n'est peut être pas la bonne")//User is not banned / the id indicated may not be the correct
        }else{
          return message.reply(users.first().reason)
        }
      })
    }```
quartz kindle
#

what is the problem

wicked pivot
#
if(users.first().username === undefined){
          return message.reply("L'utilisateur n'est pas ban / l'id indiquer n'est peut être pas la bonne")//User is not banned / the id indicated may not be the correct
        }``` I believe because whatever the id it sends me this
summer torrent
#

what is your djs version

wicked pivot
#

v11.5.1

earnest phoenix
#

DiscordAPIError: Unknown User from client.users.fetch("id")

#

every single fucking time

#

ive been sitting here for 2 fucking hours trying to fix this problem

quartz kindle
#

@earnest phoenix are you sure the id is valid?

#

@wicked pivot you can use fetchBan instead of fetchBans

#
message.guild.fetchBan(userID).then(ban => {
  if(ban) {
    // ban.reason
  }
}).catch(console.error)```
earnest phoenix
#

it is valid

#

im making a leaderboard command

#

and i want to fetch each user's id

#

to prevent usernames not appearing on a user's position

#

im using master

quartz kindle
#

show code

earnest phoenix
#
 let money = client.db.all().filter(data => data.ID.startsWith(`nw_`)).sort((a, b) => b.data - a.data)
    money.length = 10;
    var finalLb = ""
    var i = 0;
    var index = 0;
     for (i in money) {
      console.log(numparse(money[i].ID))
      let u = await client.users.fetch(numparse(money[i].ID)).catch(e => {})
       
      let a = await client.users.fetch("480933736276426750")
      console.log(a)
      finalLb += `**${++index}. ${u ? u.tag : "Unknown User#0000"}** - ${Number(money[i].data).toLocaleString()}${client.currencyEmote}\n`;  
    }

    const embed = new Discord.RichEmbed()
    .setAuthor(`Leaderboard - Economy`, message.guild.iconURL)
    .setFooter(client.user.tag, client.user.displayAvatarURL)
    .setColor(client.color)
    .setDescription(finalLb)
    .setTimestamp()
    message.channel.send(embed)
quartz kindle
#

what is numparse?

earnest phoenix
#

i used the num-parse module

quartz kindle
#

does it return a number?

#

if so, thats your problem

#

ids must be strings, not numbers

earnest phoenix
#

it does

#

return a number

#

theres these two annoying NaN which messes everything up

quartz kindle
#

you should not be parsing user ids as numbers

earnest phoenix
#

split it?

quartz kindle
#

user ids are bigger than javascripts maximum length for numbers

#

if you attempt to use an id as a number, the number will change/get rounded

#

see all numbers are ending with 00, one with 60

#

those ids are no longer valid

earnest phoenix
#

oh

south plover
#

is it's js

#

??

quartz kindle
#

what is?

south plover
#

java script

earnest phoenix
#

even if i didn't

#

use numparse

south plover
#

code

earnest phoenix
#

or split

#

theres this annoying

quartz kindle
#

javascript is js yes

earnest phoenix
#

really really annoying value that stays says its undefined

south plover
#

that code is of js

quartz kindle
#

yes, that is js

earnest phoenix
south plover
#

ohh valla

earnest phoenix
#

and when i try to split it

quartz kindle
#

if there is an undefined in your database, then you accidentally added it

earnest phoenix
#

it says cannot split something from undefined

#

how do i delete it

quartz kindle
#

see your database documentation for how to delete rows

earnest phoenix
#

i tried reading the docs

#

ok

quartz kindle
#

how are you logging those ids? console.log(money[i].ID)?

earnest phoenix
#

yes

#

when i eval money only

#

it doesn't return the undefined thing

#
[ { ID: 'nw_544922024301297691', data: '9833658' },
  { ID: 'nw_400845681574674442', data: '462045' },
  { ID: 'nw_401360645720899584', data: '100005' },
  { ID: 'nw_511776275552272387', data: '36288' },
  { ID: 'nw_555703466106814506', data: '31086' },
  { ID: 'nw_480933736276426763', data: '23595' },
  { ID: 'nw_477881279312822273', data: '18760' },
  { ID: 'nw_334514066724880385', data: '13000' },
  { ID: 'nw_364952394582196224', data: '10255' },
  { ID: 'nw_565099913269084180', data: '2806' } ]
quartz kindle
#

console.log(Object.entries(money))

#

oh wait

#

i know what the problem is

#

you give it length 10

#

if the length is smaller than 10, it will be filled with undefined's to become 10

#

so you have to if(money.length > 10) money.length = 10

earnest phoenix
#

ok

#

ty

earnest phoenix
#

still doesn't work @quartz kindle

#

the 11th result is still undefined

sinful lotus
#
money.filter(d => d).split(' ')

not really an efficient solution since you generate a new array but this will work.

why did you break your db at the first place

earnest phoenix
#

idk

#

it just appeared out of nowhere

#

This works this part where i defined the user it returns nothing

 money.forEach(async i => {
      let user = await client.users.fetch(i.ID.split('_')[1])
      finalLb += `**${++indexnum}. ${user.tag} - ${i.data}\n`
    })
quartz kindle
#

you cant do that

#

async forEach is the same as doing js for(...) { function() {} }

#

it will fire 10+ new async functions and not wait any of them

#

and if you set the length to 10, there should never be an 11th result

#

in fact you dont even need to set length like that in the first place

#

just use a regular for loop, this way to can limit it to 10 loops, and it will properly await async code

#
let money = client.db.all(...).filter(...).sort(...);
for(let i = 0; i < 10; i++) {
  let user = await client.users.fetch(money[i].ID.split("_")[1]);
}```
dusky marsh
#

for..of awaits async code properly as well correct?

quartz kindle
#

yes, for, for in, for of, while and do while

dusky marsh
#

basically forEach sucks haha

quartz kindle
#

kinda yes

#

it is much slower as well

dusky marsh
#

yeah i remember testing that at some point

#

its way slower

quartz kindle
#

because its basically not an actual standalone loop, it is a method on an array that acts as a helper to loop it

earnest phoenix
#

works! Ty ^-^

outer niche
#

I am trying to make a no role in server error but it is not working and no error message

async def info_error(ctx, error):
    if isinstance(error, commands.MissingRole):
        await ctx.send('I could not find that role.')```
modest maple
#

Well then it's not Erroring lmao

#

Or atleast Ur EH isn't getting tirggered by a error

slender thistle
#

Sounds like improper error handling to me

outer niche
#

I don't see that anything's wrong unless it would be MissingRole

slender thistle
#

You are not doing anything else if any other exception is raised

outer niche
#

?????

slender thistle
#

You are handling MissingRole but are you handling any other errors

outer niche
#

No

restive furnace
#

i think its @bot.on_command_error

outer niche
#

It is not

visual sandal
#

If I were to use multiple links when a command is used.. would that be spam.. (I only have that for my //support command)

late hill
#

The main reason it would look like spam is because all the links would get embedded?

#

If the embeds don't really matter, you could put the links inside <> which will stop the embed

#

You could also make your command output an embed, in which you could even use masked links [text](link) to possibly make things look better.

high wind
#

What are some good online javascript checkers

unique nimbus
#

wdym javascript checkers

high wind
#

like something that checks if your script is correct

#

doesnt have any errors

modest maple
#

You run it

#

:P

mossy vine
#

literally javascript

unique nimbus
#

yes

quartz kindle
#

well there are linters

#

a js linter can help you with code syntax and a few things, but will not detect execution errors

split hazel
#

For predicting if a message is toxic or not for example, is NLU best or NLP?

#

I heard NLU is recommended for such things but i want a confirmation

uneven wyvern
#

Is there an API or Node.js Module that gives me an URL of an Picture with a specific Hex Color?

for example the color given is: #ff0000 and then it returns me a picture with the color on it

tight plinth
#

using ytdl-core my bot can't find any video (it says 'video unavaible'). Why?

#

I treied with like 15 differents songs

mossy vine
#

have you tried with non copyrighted songs or whatever

uneven wyvern
#

well copyrighted work for me

tight plinth
#

I tried yes

mossy vine
tight plinth
#

even with things that are not songs

uneven wyvern
#

Oh ty @mossy vine

#

but it won't display in my embed

mossy vine
#

how are you using it

tight plinth
uneven wyvern
#

embed.setThumbnail(`https://api.alexflipnote.dev/color/image/${role.hexColor}`)

#

@mossy vine

tight plinth
#

I'm first ttying to get the play command to work before doing others ones

mossy vine
#

hm weird

#

i have no idea

tight plinth
#

maybe yt issue?

quartz kindle
uneven wyvern
#

yeah just saw that also

#

how can I remove the #?

earnest phoenix
#

.replace('#','')

quartz kindle
#

string.slice(1)

earnest phoenix
#

:/ oh...

mossy vine
#

both work

quartz kindle
#

string.split("").filter(t => t !== "#").join("")

#

lul

uneven wyvern
#

now it works lul ty Tim and Cyber28

mossy vine
#

string.split("").join("").filter(t => !["#"].includes(t)).join("").split("").join("")

tight plinth
#

bruh

uneven wyvern
#

jesus

quartz kindle
#

pastes slice(1) into jsfuck encoder

uneven wyvern
#

how can I select the first 3 strings of an array?

quartz kindle
#

top 3 according to what?

uneven wyvern
#

the first 3 strings

quartz kindle
#

array.slice(0,3) ?

uneven wyvern
#

oh

sharp bolt
#

Hi, the web version is with white screen in all browser , what can i do?

quartz kindle
#

what do you mean?

sharp bolt
#

the site cant open, just open white screen

#

discord web version

ruby talon
#

Hey.
Anyone know how to add args to a get request in js?
If it were python I would do this:

get(url + 'token/', data={'email': email})
#

Its a XMLhttprequest

#

I'm currently using this

req.send(JSON.stringify({email: _email}));

I receive the request in my server but not the data.

quartz kindle
#

http requests do not understand JSON data by default

#

if the request needs to be json, you need to specify content-type: application/json in the headers

#

else you need to format it as querystrings

zenith orchid
restive furnace
#

cause you probably allow the prohram heap size be that

#

ex on java you can set max heap

quartz kindle
#

heap size is not max mem

#

heap size is allocated memory, used heap size is actually used memory. if memory usage grows, heap size also grows

#

the system sees your program using 38mb, because the program reserved 38mb. but the program is actually only using 35mb

zenith orchid
#

Aaa

#

@quartz kindle thanks for supports.

solid pike
#

If a person speak french dm me please

summer torrent
#

process.cpuUsage() returning as:

{ user: 35334627, system: 5890661 }

How can I convert this to percent?

ruby talon
#

user/system*100 + '%' ?

restive furnace
#

actually (user/sysyem*100) + "%"

ruby talon
#

Whats the difference?

sudden geyser
#

There's no difference.

ruby talon
#

Tought so lol.

summer torrent
#

returned as: 596.9348231045501 is that correct?

ruby talon
#

oh nvm

#

none is correct.

#

It only shows the used.

#

You also need the total

#

Then add both and / by the total there is on ur machine.

#

What lang are you using?

summer torrent
#

oh ok I understand

ruby talon
#

@quartz kindle I tried the normal way and with querystrings.
My server just doens't say that it received any data.
I tried it with my python code and that did work, but I need js bcs it needs to run on a js only supported machine. -_-

summer torrent
#

What lang are you using?
@ruby talon js

ruby talon
#

Ait.
Idk how2 then xo

quartz kindle
#

@summer torrent cpu percentage is returned by counting cpu cycles over time

#

you need run process.cpuUsage once, then wait some time, then run it again, then calculate the difference

#

its a little complicated

ruby talon
#

Oh.
So you double run and then / the first by the second.

restive furnace
#

@ruby talon the diffence of this

actually (user/system*100) + "%"
was that it wouldnt return a error, as ur code would, cause you always need to (conting) + string if you do this, but if you just do counting then..

quartz kindle
#

i have a sample code for cpu calculation

ruby talon
#

@restive furnace depends on the lang.
Didn't knew it was js at the time. :))

sudden geyser
#

Freestyle wdym, are you thinking the % would add before the numbers?

ruby talon
#

I don't know a lot about js. :(
@quartz kindle

@quartz kindle I tried the normal way and with querystrings.
My server just doens't say that it received any data.
I tried it with my python code and that did work, but I need js bcs it needs to run on a js only supported machine. -_-

modest maple
#

xD

quartz kindle
#
let start = [process.hrtime(),process.cpuUsage()];
await new Promise(r => setTimeout(() => r(),100));
let elap = [process.hrtime(start[0]),process.cpuUsage(start[1])];
console.log(100.0 * ((elap[1].user / 1000) + (elap[1].system / 1000)) / (elap[0][0] * 1000 + elap[0][1] / 1000000))```
#

@ruby talon what is your server running on?

ruby talon
#

Flask.

#

(rest)

quartz kindle
#

what is your configuration for receiving?

#

are you receiving json data on the request body?

#

which content-type do you have set up?

#

a standard POST request done by xmlhttprequest should be something like this js xhttp.open("POST", "demo_post2.asp", true); xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.send("fname=Henry&lname=Ford");

#

if you need json, you need to change it accordingly: js xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xmlhttp.send(JSON.stringify({ "email": "hello@user.com", "response": { "name": "Tester" } }));

ruby talon
#

Its in the body, content-type: application/json.

req.open("GET", url + "token/", true);
req.setRequestHeader('Content-Type', 'application/json');
req.send(JSON.stringify({'email': _email}));

I tried these other req forms:

req.send(JSON.stringify({email: _email}));
req.send(JSON.stringify({'email': 'hard.coded@example.mail'}));
#

Is it because I'm using a GET request?
Isn't it possible to fetch data with a GET and having params in js or ...?

quartz kindle
#

usually GET requests only accept query string parameters in the url itself

ruby talon
#

Oh, but is it possible or do I need to rewrite my server code?

quartz kindle
#

so to do a proper GET request you would do ```js
req.open("GET", url + "token?fname=Henry&lname=Ford", true);
req.send();

#

to use json, you need your server to accept POST requests

ruby talon
#

How would I retrieve the data from a POST req then in js?

#

The same way as a GET request?

quartz kindle
#
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            this.responseText;
       }
    };
    xhttp.open("GET", "ajax_info.txt", true);
    xhttp.send();```
#

readyState 4 = request completed
this.responseText is the full response body as text

#

so you need to JSON.parse() it

#

the function must be set before calling .send()

#

the way to process the response is the same for GET and POST

ruby talon
#

Whats the difference between onreadystatechange and onload?

quartz kindle
#

im not sure actually

#

i think they are the same

#

but for some reason people have always used onreadystatechange

ruby talon
#

Ait.
I would assume that onreadystatechange gets triggered when the request its state chages. (pending ect idk but when console logging onreadystatechange gets triggered 4 times)
And onload only gets triggered when the request got a response.
¯_(ツ)_/¯

quartz kindle
ruby talon
#

Aha, thats why it gets triggered 4 times.

#

Thanks bro. ♥️
I'll rewrite my server and test the js code.
You're a good teacher. ^^

delicate zephyr
#

yea, Tim is really helpful

quartz kindle
#

lul

#

i'll open a js school someday i guess if this keeps up

amber fractal
#

Tim is omnipotent and omniscient. He knows everything, feels everything. He is the ultimate guide to js.

ruby talon
#

When ur a non native english speaker and u see this as chinese: omnipotent and omniscient

quartz kindle
#

lmao

mossy vine
#

@quartz kindle do it no balls

ruby talon
#

Tim do you have GitHub?

quartz kindle
#

ye

ruby talon
#

Send me pls papi.

amber fractal
#

If you study Tim's github you will become a god

quartz kindle
#

my github has almost nothing in it

#

lul

#

my bots are all private repos

#

because its all old shit code

#

and i dont want people to judge me

#

lmao

amber fractal
#

I just keep my shit code archived

#

I do have a lot of private repos that are up to date tho, just not open source

quartz kindle
#

most of my projects dont even get to github because im lazy to put them there

#

i only put it there if it starts getting big

#

and i dont wanna risk an hdd failure

amber fractal
#

I use it because I ran into a big problem and needed to reset my vps and had no backups, it was my fault though.

#

I just dont wanna lose my beautiful code

modest maple
#

alot of stuff i have as open source

#

some of my stuff is private like my School work

#

and an API that has to private stuff in

ruby talon
#

All my big projects are private. (Except for mySE)

#

xo

#

Already updated the server.

high wind
#

Every time i try to run my bot i run into the same error
SyntaxError: missing ) after argument list
I don't know what's happening here's my code

const client = new Discord.Client();

if(msg.author.id !== my-bots-id)
{
  client.on('message', msg =>
  {
    msg.content = msg.content += "m";
    msg.channel.send(msg.content);
    msg.delete();
  }
});

}

please help

ruby talon
#

@quartz kindle thanks, changing ecverything to a post request fixed it.

#

wtf's this syntax?
msg.content = msg.content += "m";

high wind
#

sorry i come from a c# background in programming

ruby talon
#

So?

high wind
#

i dont know javascript too well

ruby talon
#

It would even be wordse in C#.
You are trying to add a value to a var in a var.

#

Should be: msg.content += "m";
And now it will react to all messages.
I further don't know the dp.js syntax.

high wind
#

ok I changed that and its still outputting
SyntaxError: missing ) after argument list

ruby talon
#

Uhu, its bcs my eye fell on that and didn't fix the error xD

high wind
#

oh

ruby talon
#

Shouldn't it be like this?

const Discord = require("discord.js");
const client = new Discord.Client();

if(msg.author.id !== my-bots-id)
{
  client.on('message', msg =>
  {
    msg.content += "m";
    msg.channel.send(msg.content);
    msg.delete();
  });
}
amber fractal
#

Yes

#

He had the if closed with a }) and an extra }

ruby talon
#

^^

high wind
#

thanks

ruby talon
#

Doesn't your IDE give you an error for that?

high wind
#

no..

#

I'm using atom

ruby talon
#

What IDE are you using?

#

Oh, I prefer Webstorm or PHPstorm from Jetbrains. (I'm a lil Jetbrains fanboy tho xo)
Or VSCode.

high wind
#

its now outputting the error msg is not defined shouldn't it be defined with discord?

quartz kindle
#

your code is literally inside out

#

why are you checking the id of the message author BEFORE receiving a message?

amber fractal
#

Oh yeah lmao

#

I didnt even see that just saw the curly bracket and parenthesis error

quartz kindle
#
// nothing exists here
client.on("message", msg => {
  // now you have a message here. you can check the message author
})```
high wind
#

Thanks

#

It worked

#

The bot seems to only do that to my message once, doesnt delete my message and builds on its own message

quartz kindle
#

you need to ignore bots

#

else it will respond to itself

#

if(msg.author.bot) return

high wind
#

how do i use that?

earnest phoenix
#

lol

#

yikes

ruby talon
#

@quartz kindle how would you approach this?

const myArray = {first: "data", second: "data"};

function getItem(array, item) {
    console.log("Retrieving `" + item + "`");
    const myItem = array.item;
    console.log("Retrieved `" + item + "`");
    return myItem
}

console.log(getItem(myArray, "first"));
late hill
#

would be array[item]

ruby talon
#

Thanks. ^^

late hill
#

but I wouldn't use the term array

ruby talon
#

I know

quartz kindle
#

holy shit i was just finishing my framework for d.js master, and they just made a huge update that changed everything Lol

ruby talon
#

const arraymoprelikethis = ["jup"]

#

Whats the name for this in js?
{first: "data", second: "data"}
An object or?
I know that its called a dictionary in py.

quartz kindle
#

object

ruby talon
#

holy shit i was just finishing my framework for d.js master, and they just made a huge update that changed everything Lol
Rip...
object
Ait. ^^

high wind
#

Now it works but doesnt delete the previous message

#

nvm

ruby talon
#

How would you export (module.exports) a custom error?
eg:
myLib.js:

module.exports = { ExampleError: Error.ExampleError };

class ExampleError extends Error {
    constructor(message) {
        super(message);
        this.name = this.constructor.name;
        this.message = message;
    }
}

runFile.js:

const myLib = require("./myLib");

throw new myLib.ExampleError("Hello, world.");
#

NVM

#

Found it. ^^

uneven wyvern
#

I would also be interested how that works @ruby talon

sudden geyser
#

I don't think that edit will work

ruby talon
#

@sudden geyser it does.

sudden geyser
#

how though

ruby talon
#

oh

#

w8

#

Now it will. ^^

sudden geyser
#

yeah now, but classes are not hoisted to the top, so you may need to move it below

ruby talon
#

Wdym with that?

sudden geyser
#

well 1: the Error class does not share a property named ExampleError.
2: classes are not hoisted to the top of the file like functions are (class vs function). I believe you'd need to move module.exports below the class declaration then export it, but just export ExampleError instead of Error.ExampleError

#

If you try to require it from myLib, you'll probably get undefined the way you currently do it I believe

ruby talon
#

It works for me rn. ¯_(ツ)_/¯

#

And gotta keep the Error. infront of it.

#

Or it doesn't find it.

sudden geyser
#

@modern sable pls

ruby talon
#

@modern sable @static lantern is self advertising.

modern sable
#

ty

ruby talon
#

@quartz kindle, back to the XMLHTTPRequest.
I changed the onload to this:
In the fetch function:

req.onload = function() { return fetchData(req, "token"); }

Outside:

function fetchData(request, data) {
    const reqValue = JSON.parse(request.responseText);
    if (request.status === 400) throw new BadRequest(reqValue["error"]);
    else if (reqValue.statusCode === 401) throw new UnauthorizedError(reqValue["error"]);
    console.log(reqValue[data]);
    return reqValue[data];
}

Result:

Retrieving token...
Retrieved token:
undefined
zTWFfbT5RFNWgLGFIDxbuKuiTE4Zzc87fJwkTn9zmwY

The last thing is the expected token, but its console.log'ed in place of returned.
The undefined is returned, is there a chance you know why?

sudden geyser
#

And gotta keep the Error. infront of it.
Or it doesn't find it.
It won't find it because it hasn't been declared to its level. Classes are not hoisted, but functions are. And Error.ExampleError returned undefined for me, unless I'm missing something. ¯_(ツ)_/¯

ruby talon
#

IDK why, if I remove the error it gives me the undefined error.
Long live code lol.

sudden geyser
#

it's not a property of the Error constructor. all you need to do is export it after the class has been declared and remove the Error. from it.

#

such as module.exports = { ExampleError: ExampleError }

ruby talon
sudden geyser
#

has the class been declared above where you do UnauthorizedError: UnauthorizedError and in its scope

ruby talon
#

Oh whoops, I'm dumb.

#

@quartz kindle, back to the XMLHTTPRequest.
I changed the onload to this:
In the fetch function:

req.onload = function() { return fetchData(req, "token"); }

Outside:

function fetchData(request, data) {
    const reqValue = JSON.parse(request.responseText);
    if (request.status === 400) throw new BadRequest(reqValue["error"]);
    else if (reqValue.statusCode === 401) throw new UnauthorizedError(reqValue["error"]);
    console.log(reqValue[data]);
    return reqValue[data];
}

Result:

Retrieving token...
Retrieved token:
undefined
zTWFfbT5RFNWgLGFIDxbuKuiTE4Zzc87fJwkTn9zmwY

Expected result:

Retrieving token...
Retrieved token:
zTWFfbT5RFNWgLGFIDxbuKuiTE4Zzc87fJwkTn9zmwY
zTWFfbT5RFNWgLGFIDxbuKuiTE4Zzc87fJwkTn9zmwY

The last thing is the expected token, but its console.log'ed in place of returned.
The undefined is returned, is there a chance you know why?
Still unanswered

quartz kindle
#

where do you expect the result to be returned to?

#

what is the context from where the entire request is being made?

#

are you trying to do something like this? js function request(...) { x = new xmlhttp(...); x.onload = function() { return fetchData() } } let token = request(...);

#

@ruby talon

ruby talon
#

Remeber the functions with the XMLHTTPrequest from around an hour ago?
Its in this context.
If I place the function its code in the onload it does function.
But since I have to repeat the same code multiple times over an over again with little to no changes I tought it would be nice if it was in a function.

quartz kindle
#

yes but how is the code called?

#

because js is for the most part a non-blocking synchronous language

ruby talon
#

In a function.

quartz kindle
#

what calls the function?

#

show the Retrieving token...
Retrieved token:

#

part

ruby talon
#
get_token: function(url, _email) {
    const req = new XMLHttpRequest();
    req.open("POST", url + "token/", true);
    req.setRequestHeader('Content-Type', 'application/json');
    req.send(JSON.stringify({'email': _email}));
    req.onload = function() { return fetchData(req, "token"); }
}
const mySE = require('../mySE/meSE');

const local_url = "http://127.0.0.1:5000/", mail = "mail@mail.mail";

console.log("Retrieving token...");
const token = mySE.get_token(local_url, mail);
console.log("Retrieved token:\r\n" + token)
quartz kindle
#

see that is the problem

ruby talon
#

🙃

quartz kindle
#

js is for the most part non-blocking sync, which means this is what happens:

ruby talon
#

So I need to make it async?

quartz kindle
#

token -> fires function
function -> fires req.onload()
req.onload() begins waiting
function -> has nothing left to do here
function -> returns undefined
token -> received undefined

#

meanwhile req.onload is waiting in limbo, and when it returns, the value goes nowhere

#

so you need to make use of async yes

marble juniper
#
let call = await example.fetch('example')
#

E

ruby talon
#

If I make the get_token async do I need to make the fetchData async 2?

quartz kindle
#

there are many ways it can be done, traditionally everyone would use callbacks: ```js
function get_token(url,email,callback) {
x.onload = function() { callback(req); }
}
get_token(url,email,function(result) {
// result returned via callback
})

today, you can use the powerful async/await style as well as Promises, which is sort of an async task
ruby talon
#

BTW sorry if these are newby mistakes, I'm pretty new to JS.

marble juniper
#

whenever you are trying to fetch anything or simmilar you should use async as you never know when your request will return the data

#

for example http requests

#

or .then

#

im not good at explaining

#

but I think you get the point

quartz kindle
#

a Promise is created like this: js promise = new Promise((resolve,reject) => { // using arrow functions, or a normal function like this: function(resolve,relect) { if(error) { reject(error) } x.onload = function() { resolve(req) } })
then this promise can be accessed in a callback style, like this: js promise.then(result => { // use result here }).catch(e => { // catch error here }) or in the new async/await syntax: js result = await promise(); // error will be thrown like sync code in order to use async/await syntax, your code must be placed inside an async function, like this js async function() { result = await promise() } so unfortunately you cannot use async/await syntax in the global scope

marble juniper
#

but its useful

quartz kindle
#

you can create a function that immediately returns a promise like this ```js
function request() {
return new Promise((resolve,reject) => {
// do the entire xmlhttprequest here, then finally
x.onload = function() { resolve(result); }
});
}

#

then you can use it as a promise everywhere in your code: ```js
request.then(result => {
console.log(result)
});
async function() {
console.log(await request())
}

ruby talon
#

Jeesus f*ck

#

I'm a newbie and ur throwing pyramids at me xDD

quartz kindle
#

lmao

#

Promises can be daunting at first, it took me a while to understand them

#

but they are essentially what Tasks/Futures are in other languages

ruby talon
#

WaY eAsIeR in python, change my mind xD

modest maple
#

nah

#

python is equally as difficult if you do it properly

#

once you get used to the syntax its not that bad

quartz kindle
#

since XMLHTTPRequest is a very old api, it doesnt have any of this modern way of using it, so you have to wrap it

ruby talon
#

idk xo

quartz kindle
#

there is a newer api in browsers that might be less complicated, the Fetch api

modest maple
#

Gracias github

ruby talon
#

Its not exactly only for browsers.
Else I wouldvé used jQuery

quartz kindle
#

node/nw/electron?

ruby talon
#

Currently using node, its also meant to go into electron.

quartz kindle
#

if you have access to npm, you can use one of many http libraries out there

modest maple
#

what made you start using JS over python 🤔

quartz kindle
#

i recommend got

ruby talon
#

@modest maple I need to use it for this project.
And its all a learning experience, I also need to create the same lib in Cpp. xO

modest maple
#

oooF

#

cpp is gonna be fun xD

ruby talon
#

I already created a Python wrapper bcs thats my main lang, so its easy.

modest maple
#

whats the wrapper supposed todo?

ruby talon
#

Interact with my REST API xo

quartz kindle
#

in my opinion, although im not well versed in py or other langs, js is easier to use and requires less code to accomplish the same things, with the exception of decades old apis of course

modest maple
#

@quartz kindle cough cough* requests.get()

quartz kindle
#

and with the exception of node's low level apis

modest maple
#

python is litterally just

import requests

r = requests.get(url, payload)
r.json
#

you could do it with aiohttp also

#

depends if u need async or not

ruby talon
#

Jup.

quartz kindle
#

because essentially it has a built in api for it, which js doesnt

ruby talon
#

Requests is enough.

quartz kindle
#

but you can get any js lib and do the same thing

modest maple
#

cuz py better

#

xDDD

#

nah ik what u mean

ruby talon
#

Every lang has its pro's and cons.

modest maple
#

python is orientated around modules alot more than JS imo

quartz kindle
#

but for example, if you try manually coding an async task, using promises in js is easier than using futures/tasks in py, i think

modest maple
#

@quartz kindle theyre pretty similar

#

you can just return like a normal function

#

and the async generator handles the rest

#

if you have multiple tasks you can use gather

quartz kindle
#

doesnt that generate confusion between sync and async calls?

#

how do you know what is what, when reading the code

modest maple
#

not rlly

#

there is a big async in front of the function

#

and a await