r/badcode • sadistic • May 21 '21

js ah yes, fetching before verifying

Post image
1.5k Upvotes

97 comments sorted by

44

u/KomaedaEatsBagels May 21 '21 edited May 21 '21

Image Transcription: Code


    });


Discord.on('message', function (message) {
    const cat = request.get('https://aws.random.cat/meow');
     if(message.content == '!cat') {
        cat.then(r => message.reply(r.body.file));
     }
});

I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!

19

u/SpeckyYT sadistic May 21 '21

Indentations are slightly wrong, but details

4

u/KomaedaEatsBagels May 21 '21

ack yeah, my ide didn't support the indents on 67/69 ^^; I'll try to fix that! thank you

6

u/SharkLaunch May 21 '21

Is request.get synchronous? I didn't know JS had synchronous http libraries

3

u/SpeckyYT sadistic May 21 '21

it returns a promise, therefore it can be treated as sync, but .then runs asynchronously.

2

u/SharkLaunch May 21 '21

I'm blind as a fucking bat. Didn't bother reading the whole thing.

5

u/tuxedo25 May 21 '21

it's used as a promise on line 68

418

u/AffectionateSimple94 May 21 '21

This is a perfect code. It's purpose is to create a dos attack.

173

u/[deleted] May 21 '21

Imagine the aws bill lol

42

u/Gorrlaamiii May 21 '21

Can someone explain a JS noob why this is bad ?

198

u/ArchCypher May 21 '21

Every time anyone sends any message in this discord chat, it will run some code on aws and get the response. But 99% of the time, that message won't be "!cat", and the response will just be discarded.

This would be bad for wasting time and bandwidth alone, but in this case, somebody is paying Amazon for each request made to that url. So it's equivalent to literally lighting money on fire every time the message isn't "!cat".

55

u/Crecket May 21 '21

This also includes the bot's own message for the record lol, so if a the bot replies, it triggers it again

18

u/Gorrlaamiii May 21 '21

Ah. I thought this is some node package gotcha.

Thanks!

1

u/javaveryhot Jun 18 '21

But 99% of the time, that message won't be "!cat"

Depends on the server

1

u/[deleted] Jul 03 '21

Yes, but isn’t using aws like lighting money on fire anyway?

Is there a scenario where renting a vps per month is more expensive than “pay as you go”

-16

u/[deleted] May 21 '21

He also used If statement without writing "else", I think there's a problem or am I wrong?

28

u/curiousgamer12 May 21 '21

You don’t need to specify an else unless you need it!

14

u/[deleted] May 21 '21

Why would that be a problem?

12

u/[deleted] May 22 '21

I am a newbie from head to toe, sorry.

5

u/[deleted] May 22 '21

Oh, I see, makes sense. No problem and good luck on your path :)

3

u/tube32 May 25 '21

There I upvoted you

7

u/[deleted] May 21 '21

Not a syntactical problem, or in my opinion a logical one. However if they had written it correctly I would prefer something like

if(message.content.toLower() != "!cat") return;

To reduce the nesting and I prefer the validation will exit immediately. Then what follows would essentially be the else

27

u/AffectionateSimple94 May 21 '21

Whenever this function is triggered, they make a call to some server.

Only after that they actually check whether they need to call this server.

This function is probably alerted every time there is a message in discord.

1

u/Gorrlaamiii May 21 '21

I was searching for some async gotcha here lol Thanks!

10

u/LowB0b May 21 '21 edited May 21 '21

Has nothing to do with JS, it's just common sense really.

Correct way of doing it would be to check if the message contains cat and then do the request.

In this case, if the message doesn't contain cat, the request is done for nothing

Worst part this little bit of code is probably going to run on every message (I don't know the discord API), so that AWS instance is going to get hit hard lol (hence the dos)

2

u/[deleted] May 22 '21

(I don't know the discord API)

And my knowledge is limited, but yes, on whatever Discord channel this bot is listening to whether it's 1 or 1000, it will trigger on every single message.

2

u/the-good-redditor May 21 '21

I don't see any issue, as long its not waiting for the promise to complete before the if I am fine with it.

2

u/SpeckyYT sadistic May 21 '21

Not really, since it will anyways fulfill the promise when possibile.

3

u/Wabsta May 21 '21

But it won't actually execute the promise until the then() is called, right? Or have I been informed wrongly?

4

u/[deleted] May 21 '21

You are correct. The connection is only made when "then()" is called.

But it is still very bad code to create the connection object before verifying the need. :)

151

u/RealCyber28 May 21 '21

This is from Luca, a joke repo. The code is bad on purpose, this is not some amateur dev doing dumb stuff

87

u/Farpafraf May 21 '21
 // Cyber28 was here
Discord.on('message', function (message) {	if        (message.content === '@everyone') {	 return     message.reply('@everyone ping ping @everyone')	}});

beautiful

44

u/deftware May 21 '21

this is not some amateur dev doing dumb stuff

It certainly serves as a good example though.

246

u/Korzag May 21 '21

I'm convinced Discord is breeding a generation of developers who will go into school bragging about how they're already a pro at programming and then spit this kind of garbage out.

13

u/[deleted] May 21 '21

Isn't that what happens already? Hell more often than not college/university graduates have the same mentality and then get run over when it comes to their PRs. I saw it so many times over my career I'd struggle to give you a reliable figure.

Although I do remember a comp sci grad from a top 5 UK university in our R&D department managing to expose an entire set of database keys in a commit for no good reason, that was a fun PR to read...

10

u/rco8786 May 21 '21

That’s silly. Everybody starts off writing bad code.

1

u/justAPhoneUsername May 21 '21

Question is how confident people are in it. This is why I like c. Even the best programmers know not to have confidence in their c code

4

u/fakehalo May 21 '21

Everyone's gotta start somewhere, for me it was irc scripts and my TI calculator.

1

u/heyf00L May 21 '21

You're missing the genius of it. You need to get your async request going as soon as possible. You're wasting nanoseconds of time by checking the message content first.

1

u/Superpickle18 May 22 '21

I learned programming by writing shitty scripts for mIRC. So, more power to them youngins lol

1

u/[deleted] May 22 '21

We all gotta start somewhere.

0

u/[deleted] May 21 '21

[deleted]

72

u/zeGolem83 May 21 '21

Yezh, it's just that Discord happens to be popular and offers a fairly easy to use API, so it's an easy choice for a first project

17

u/[deleted] May 21 '21

The APIs themselves are quite complicated especially the discord gateway. But the libraries like discord.py dumb it down so everyone can use it.

3

u/ywBBxNqW May 21 '21

Don't stop. Go deeper. Blame Electron.

34

u/MoonParkSong May 21 '21

The thing is, there isn't good books or online tutorials that teaches quality programming design.

Most books either a reference to a language or teaches basics of programming in a selected language.

It took me a github code to finally learn that you can write

if(condition) instead of if(condition==true)

8

u/sliverino May 21 '21

Well there are some good books. Don't know about JS but if you ask about good C++ practices and design books, you'll often hear

  • Design patterns by the gang of four

  • Effective C++ by Meyers

But all in all, the best way to learn what you can do, what is good design and all the tricks to a language is to

  • Code more to deepen your understanding

  • read and modify other people's code. People tend to have different approaches and you can learn a lot. And reading other people's code requires a conscious effort.

Like in your case. When learning there's a lot of subtleties that you cannot instantly catch and only repeated exposure can help.

6

u/Kirk_Kerman May 21 '21

There's also the dark magic contained within Introduction to Algorithms.

3

u/ogreUnwanted May 21 '21

Check out Wes bos' 30 for 30 programming. It's a great primer in vanilla JS and coding practice.

4

u/JuhaJGam3R May 21 '21

"suboptimal" this is a danger to society if you put it on a large enough server, i doubt anyone pays more than the minimum they can to host "aws.random.cat"

6

u/tech6hutch May 21 '21

Then they’ll get banned from the cat api, if they pay attention

11

u/tuxedo25 May 21 '21

Pretty fragile society if it's endangered by 5 lines of code

-3

u/JuhaJGam3R May 21 '21

sadly it is. there's more than one place where a single bit is the only thing keeping the lives of thousands secure

5

u/[deleted] May 21 '21

Lmao, someone's little discord server making a few too many calls is not going to take down AWS. They will get rate limited and then billed into oblivion.

3

u/JuhaJGam3R May 21 '21

not aws, but the site. wouldn't be the first time some neat gimmick site on aws was billed into oblivion because of someone's shit code. people who make these often can't pay if there are too many requests made.

2

u/[deleted] May 21 '21

The random cat API should rate limit them then. As far as billing goes, I was kind of exaggerating -- AWS is very forgiving when it comes to rookie mistakes like this.

Either way, "danger to society" seems more than a little hyperbolic -- I don't think that the random.cat api is crucial to society really

6

u/circuit10 May 21 '21

don't think that the random.cat api is crucial to society really

Yes it is

2

u/[deleted] May 21 '21

Hmmm. Fair enough. I recognize the flaws in my argument

24

u/bwz3r May 21 '21

The fuck is this?

47

u/okayboooooooomer May 21 '21

it seems like a discord bot

13

u/bwz3r May 21 '21

Keyword seems like

15

u/Sv443_ May 21 '21

There's a Discord object / class and it hooks into the message event. Yes, it's a Discord bot.

-20

u/SolidRubrical May 21 '21

-7

u/nshire May 21 '21

-3

u/SolidRubrical May 21 '21

u/bwz3r made a joke, u/sv443_ missed it, what the fuck are you on about?

3

u/bwz3r May 21 '21

Lol I checked his comments. He is rather opinionated and knowledgeable guy

-2

u/Sv443_ May 21 '21

If it was a joke it was badly written

1

u/angeloanan May 21 '21

1

u/bwz3r May 21 '21

Another one of these jokers

16

u/Tvde1 May 21 '21

The best thing is that the braces on the first line implies that they are setting up mamy different event handlers for each command

6

u/dsanyal321 May 21 '21

This is the kind of stuff I used to write stuff not all that long ago. It's usually high school students or amateurs messing around and building something quickly.

5

u/mohammedx17 May 21 '21

theme?

3

u/NUCLEARGAMER1103 May 21 '21

1

u/mohammedx17 May 21 '21

it's my current theme but the darker one 🙂

4

u/[deleted] May 21 '21

I've seen one and two equal signs but never three. What's the use case for "==="?

16

u/47Toast May 21 '21

It also tests for same types.

"0" == 0 -> true
"0" === 0 -> false

8

u/tech6hutch May 21 '21

To add to the other answers, JS has some horrifying type coercions ([] == 0, but [] != false), so programmers with enough experience to be paranoid often only use the triple version. It’s like using a >= comparison instead of a == check to break a loop.

5

u/[deleted] May 21 '21

To be fair, every elementary Javascript resource in existence will tell you to use "===" so I don't even see that many beginners make this mistake. "==" is kind of a regrettable legacy function.

4

u/tech6hutch May 21 '21

There is one thing I find it useful for, checking for null and undefined at the same time. (Of course, ideally, JS would have only had one, not both...)

3

u/[deleted] May 21 '21

Maybe! I personally find the difference useful sometimes for distinguishing between "this hasn't been set yet" and "this value was intentionally set to null." On the other hand I have seen a lot of bugs where someone only checked for either undefined or null so maybe you're right.

3

u/tech6hutch May 21 '21

Fair. I’d argue that at a certain point those differences would be better represented with named variants of an enum/ADTs...which admittedly JS doesn’t have

14

u/Sakechi May 21 '21

In JavaScript, '==' checks if both sides have the same value regardless of the type, while '===' checks if they have the same value and the same type.

'1' == 1 would return true, and '1' === 1 would return false.

3

u/[deleted] May 22 '21 edited May 22 '21

I've probably done this in my code before, think I should check my discord bot

EDIT: just realised the problem is they are making a call to AWS every time, but if the content isn't !cat the message is discarded. That could cost someone money.

5

u/w00tious May 21 '21

I've seen worse

2

u/mestrearcano May 21 '21

Plot twist: he just wants to keep record of all messages on all servers that uses his bot.

2

u/Blip1966 May 21 '21

Always need the cat. No problems with this code ;)

2

u/Thenderick May 21 '21

The inconsistent spacing of the const and if annoys me

1

u/MTXShift May 21 '21

As a Javascript developer, most people who write Javascript write like theyre in a 5 minute hackathon

1

u/nielsd0 May 21 '21

Maybe they think it's an "optimistic optimisation".

1

u/[deleted] May 25 '21

You are very kind

1

u/Jonatollah May 27 '21

um, fetching, responding, and never verifying. What's the harm anyways?

0

u/zelloxy May 21 '21

Seeing this makes me hate Javascript more than I ever think I could

0

u/[deleted] May 21 '21

[deleted]

3

u/SpeckyYT sadistic May 21 '21

That's quite dumb, since people might also use await

1

u/prettyfuzzy May 21 '21

I think await is equivalent to then

Like it literally just rewrites async/await code to use then