-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathcommands.ts
647 lines (583 loc) · 20.8 KB
/
commands.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
import fetch from "node-fetch";
import { Message, TextChannel } from "discord.js";
import cooldown from "./cooldown";
import { ChannelHandlers } from "../types";
import {
isStaff,
isBotDisabledInChannel,
notifyUserBotResponseWasPrevented
} from "../utils";
const EMBED_COLOR = 7506394;
type Categories = "Reactiflux" | "Communication" | "Web" | "React/Redux";
type Command = {
words: string[];
help: string;
category: Categories;
handleMessage: (msg: Message) => void;
};
const sortedCategories: Categories[] = [
"Reactiflux",
"Communication",
"Web",
"React/Redux"
];
const commandsList: Command[] = [
{
words: [`!commands`],
help: `lists all available commands`,
category: "Reactiflux",
handleMessage: msg => {
const commandsMessage = createCommandsMessage();
msg.channel.send({
embed: {
title: "Available Help Commands",
type: "rich",
description: commandsMessage,
color: EMBED_COLOR
},
reply: msg.author
});
}
},
{
words: [`!rrlinks`],
help: `shares a repository of helpful links regarding React and Redux`,
category: "React/Redux",
handleMessage: msg => {
msg.channel.send({
embed: {
title: "Helpful links",
type: "rich",
description: `Reactiflux's Mark Erikson has put together a curated list of useful React & Redux links for developers of all skill levels. Check out https://github.com/markerikson/react-redux-links`,
color: EMBED_COLOR
}
});
}
},
{
words: [`!xy`],
help: `explains the XY problem`,
category: "Communication",
handleMessage: msg => {
msg.channel.send({
embed: {
title: "The XY Issue",
type: "rich",
description: `You may be experiencing an XY problem: http://xyproblem.info/ . Try to explain your end goal, instead of the error you got stuck on. Maybe there's a better way to approach the problem.`,
color: EMBED_COLOR
}
});
}
},
{
words: [`!ymnnr`],
help: `links to the You Might Not Need Redux article`,
category: "React/Redux",
handleMessage: msg => {
msg.channel.send({
embed: {
title: "You Might Not Need Redux",
type: "rich",
description: `People often choose Redux before they need it. “What if our app doesn’t scale without it?
https://medium.com/@dan_abramov/you-might-not-need-redux-be46360cf367`,
color: EMBED_COLOR
}
});
}
},
{
words: [`!derived`],
help: `Links to the React docs advice to avoid copying props to state`,
category: "React/Redux",
handleMessage: msg => {
msg.channel.send({
embed: {
title:
"You might not need getDerivedStateFrom props or state at all!",
type: "rich",
description: `Copying data from React props to component state is usually not necessary, and should generally be avoided. The React team offered advice on when "derived state" may actually be needed:
https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html`,
color: EMBED_COLOR
}
});
}
},
{
words: [`!su`, `!stateupdates`],
help: `Explains the implications involved with state updates being asynchronous`,
category: "React/Redux",
handleMessage: msg => {
msg.channel.send({
embed: {
title: "State Updates May Be Asynchronous",
type: "rich",
description: `Often times you run into an issue like this
\`\`\`js
const handleEvent = e => {
setState(e.target.value);
console.log(state);
}
\`\`\`
where \`state\` is not the most up to date value when you log it. This is caused by state updates being asynchronous.
Check out these resources for more information:
https://gist.github.com/bpas247/e177a772b293025e5324219d231cf32c
https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous
https://blog.isquaredsoftware.com/2020/05/blogged-answers-a-mostly-complete-guide-to-react-rendering-behavior/#render-batching-and-timing`,
color: EMBED_COLOR
}
});
}
},
{
words: [`!bind`],
help: `explains how and why to bind in React applications`,
category: "React/Redux",
handleMessage: msg => {
msg.channel.send({
embed: {
title: "Binding functions",
type: "rich",
description: `In JavaScript, a class function will not be bound to the instance of the class, this is why you often see messages saying that you can't access something of undefined.
In order to fix this, you need to bind your function, either in constructor:
\`\`\`js
class YourComponent extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
// you can access \`this\` here, because we've
// bound the function in constructor
}
}
\`\`\`
or by using class properties babel plugin (it works in create-react-app by default!)
\`\`\`js
class YourComponent extends React.Component {
handleClick = () => {
// you can access \`this\` here just fine
}
}
\`\`\`
Check out https://reactkungfu.com/2015/07/why-and-how-to-bind-methods-in-your-react-component-classes/ for more informations`,
color: EMBED_COLOR
}
});
}
},
{
words: [`!lift`],
help: `links to the React docs regarding the common need to "lift" state`,
category: "React/Redux",
handleMessage: msg => {
msg.channel.send({
embed: {
title: "Lifting State Up",
type: "rich",
description: `Often, several components need to reflect the same changing data. We recommend lifting the shared state up to their closest common ancestor. Let’s see how this works in action.
https://reactjs.org/docs/lifting-state-up.html`,
color: EMBED_COLOR
}
});
}
},
{
words: [`!ask`],
help: `explains how to ask questions`,
category: "Reactiflux",
handleMessage: msg => {
msg.channel.send({
embed: {
title: "Asking to ask",
type: "rich",
description: `Instead of asking to ask, ask your question instead. People can help you better if they know your question.
Bad: "hey can anyone help me?"
Bad: "anyone good with redux?"
Good:
> I'm trying to fire a redux action from my component, but it's not getting to the reducer.
> \`\`\`js
> // snippet of code
> \`\`\`
> I'm seeing an error, but I don't know if it's related.
> \`Uncaught TypeError: undefined is not a function\``,
color: EMBED_COLOR
}
});
}
},
{
words: [`!code`, `!gist`],
help: `explains how to attach code`,
category: "Reactiflux",
handleMessage: msg => {
msg.channel.send({
embed: {
title: "Attaching Code",
type: "rich",
description: `\\\`\\\`\\\`js
// short code snippets go here
\\\`\\\`\\\`
Link a Gist to upload entire files: https://gist.github.com
Link a Code Sandbox to share runnable examples: https://codesandbox.io/s
Link a Code Sandbox to an existing GitHub repo: https://codesandbox.io/s/github/<username>/<reponame>
Link a TypeScript Playground to share types: https://www.typescriptlang.org/play
Link a Snack to share React Native examples: https://snack.expo.io
`,
color: EMBED_COLOR
}
});
}
},
{
words: [`!ping`],
help: `explains how to ping politely`,
category: "Reactiflux",
handleMessage: msg => {
msg.channel.send({
embed: {
title: "Don’t ping or DM other devs you aren’t actively talking to",
type: "rich",
description: `It’s very tempting to try to get more attention to your question by @-mentioning one of the high profile(or recently active) members of Reactiflux, but please don’t. They may not actually be online, they may not be able to help, and they may be in a completely different timezone–nobody likes push notifications at 3am from an impatient stranger.
Similarly, don’t DM other members without asking first. All of the same problems as @-mentioning apply, and private conversations can’t help anyone else. Your questions are likely not unique, and other people can learn from them when they’re kept public.`,
color: EMBED_COLOR
}
});
}
},
{
words: [`!inputs`],
help: `provides links to uncontrolled vs controlled components`,
category: "React/Redux",
handleMessage: msg => {
msg.channel.send({
embed: {
title: "Uncontrolled vs Controlled components",
type: "rich",
description: `In React, inputs can either be uncontrolled (traditional input) or be controlled via state.
Here's an article explaining the difference between the two: https://goshakkk.name/controlled-vs-uncontrolled-inputs-react/
`,
color: EMBED_COLOR
}
});
}
},
{
words: [`!move`],
help: `allows you to move the conversation to another channel \n\t(usage: \`!move #toChannel @person1 @person2 @person3\`)`,
category: "Reactiflux",
handleMessage: msg => {
const [, newChannel] = msg.content.split(" ");
try {
const targetChannel = msg.guild?.channels.cache.get(
newChannel.replace("<#", "").replace(">", "")
) as TextChannel;
if (!msg.mentions.members) return;
targetChannel.send(
`${msg.author} has opened a portal from ${
msg.channel
} summoning ${msg.mentions.members.map(i => i).join(" ")}`
);
} catch (e) {
console.log("Something went wrong when summoning a portal: ", e);
}
}
},
{
words: [`!mdn`],
help: `allows you to search something on MDN, usage: !mdn Array.prototype.map`,
category: "Web",
handleMessage: async msg => {
const [, ...args] = msg.content.split(" ");
const query = args.join(" ");
const [fetchMsg, res] = await Promise.all([
msg.channel.send(`Fetching "${query}"...`),
fetch(
`https://developer.mozilla.org/api/v1/search/en-US?highlight=false&q=${query}`
)
]);
const { documents } = await res.json();
const [topResult] = documents;
if (!topResult) {
fetchMsg.edit(`Could not find anything on MDN for '${query}'`);
return;
}
const {
title,
excerpt: description,
mdn_url: mdnUrl,
locale
} = topResult;
await msg.channel.send({
embed: {
type: "rich",
author: {
name: "MDN",
url: "https://developer.mozilla.org",
icon_url:
"https://developer.mozilla.org/static/img/opengraph-logo.72382e605ce3.png"
},
title,
description,
color: 0x83d0f2,
url: `https://developer.mozilla.org${mdnUrl}`
}
});
fetchMsg.delete();
}
},
{
words: [`!appideas`],
help: `provides a link to the best curated app ideas for beginners to advanced devs`,
category: "Web",
handleMessage: msg => {
msg.channel.send({
embed: {
title: "Florinpop17s Curated App Ideas!",
type: "rich",
description: `Sometimes it's tough finding inspiration, luckily this guy listed a bunch of stuff for you to pick from for your next project! Well sorted progression to confidence in web dev.
https://github.com/florinpop17/app-ideas
`,
color: EMBED_COLOR
}
});
}
},
{
words: [`!cors`],
help: `provides a link to what CORS is and how to fix it`,
category: "Web",
handleMessage: msg => {
msg.channel.send({
embed: {
title: "Understanding CORS",
type: "rich",
description: `
Cross-Origin Resource Sharing (CORS) is a mechanism that lets remote servers restrict which origin (i.e your website) can access it.
Read more at:
https://medium.com/@baphemot/understanding-cors-18ad6b478e2b
https://auth0.com/blog/cors-tutorial-a-guide-to-cross-origin-resource-sharing/
`,
color: EMBED_COLOR
}
});
}
},
{
words: [`!imm`, `!immutability`],
help: `provides resources for helping with immutability`,
category: "React/Redux",
handleMessage: msg => {
msg.channel.send({
embed: {
title: "Immutable updates",
type: "rich",
description: `Immutable updates involve modifying data by creating new, updated objects instead of modifying the original object directly.
You should not modify existing data directly in React or Redux, as mutating data can lead to bugs.
https://daveceddia.com/react-redux-immutability-guide/
https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns
`,
color: EMBED_COLOR
}
});
}
},
{
words: [`!redux`],
help: `Info and when and why to use Redux`,
category: "React/Redux",
handleMessage: msg => {
msg.channel.send({
embed: {
title: "When should you use Redux?",
type: "rich",
description: `Redux is still the most widely used state management tool for React, but it's important to always ask "what problems am I trying to solve?", and choose tools that solve those problems. Redux, Context, React Query, and Apollo all solve different problems, with some overlap.
See these articles for advice on what Redux does and when it makes sense to use it:
https://blog.isquaredsoftware.com/2018/03/redux-not-dead-yet/
https://changelog.com/posts/when-and-when-not-to-reach-for-redux
https://blog.isquaredsoftware.com/2017/05/idiomatic-redux-tao-of-redux-part-1/
`,
color: EMBED_COLOR
}
});
}
},
{
words: [`!render`],
help: `Explanation of how React rendering behavior works`,
category: "React/Redux",
handleMessage: msg => {
msg.channel.send({
embed: {
title: "How does React rendering behavior work?",
type: "rich",
description: `There are several common misunderstandings about how React renders components. It's important to know that:
- React re-renders components recursively by default
- State updates must be immutable
- Updates are usually batched together
- Context updates always cause components to re-render
See this post for a detailed explanation of how React rendering actually works:
https://blog.isquaredsoftware.com/2020/05/blogged-answers-a-mostly-complete-guide-to-react-rendering-behavior/
`,
color: EMBED_COLOR
}
});
}
},
{
words: [`!formatting`, `!prettier`],
help: `describes Prettier and explains how to use it to format code`,
category: "Reactiflux",
handleMessage: msg => {
msg.channel.send({
embed: {
title: "Formatting code with Prettier",
type: "rich",
description: `Inconsistent indentation and syntax can make it more difficult to understand code, create churn from style debates, and cause logic and syntax errors.
Prettier is a modern and well-supported formatter that completely reformats your code to be more readable and follow best practices.
To format some code without installing anything, use the playground: https://prettier.io/playground/
To enforce its style in your projects, use the CLI: https://prettier.io/docs/en/install.html
To integrate it into your editor: https://prettier.io/docs/en/editors.html`,
color: EMBED_COLOR
}
});
}
},
{
words: [`!gender`],
help: `reminds users to use gender-neutral language`,
category: "Communication",
handleMessage: msg => {
msg.channel.send({
embed: {
title: "Please use gender neutral language by default",
type: "rich",
description: `Unless someone has made their pronouns known, please use gender neutral language.
- Instead of "hey guys," try "hey folks", "hey all", or similar
- Use "they/them/theirs" if you aren't sure of someone's pronouns
- "thanks friend" instead of "thanks man"`,
color: EMBED_COLOR
}
});
}
},
{
words: [`!reactts`],
help: `Resources and tips for using React + TypeScript together`,
category: "React/Redux",
handleMessage: msg => {
msg.channel.send({
embed: {
title: "Resources for React + TypeScript",
type: "rich",
description: `The best resource for how to use TypeScript and React together is the React TypeScript CheatSheet. It has advice on how to type function components, hooks, event handlers, and much more:
https://react-typescript-cheatsheet.netlify.app/
Also, we advise against using the \`React.FC\` type for function components. Instead, declare the type of \`props\` directly, like:
\`function MyComp(props: MyCompProps) {}\`:
See this issue for details on why to avoid \`React.FC\`:
https://github.com/facebook/create-react-app/pull/8177
`,
color: EMBED_COLOR
}
});
}
},
{
words: [`!hooks`],
help: `Resources for learning React Hooks`,
category: "React/Redux",
handleMessage: msg => {
msg.channel.send({
embed: {
title: "Learning React Hooks",
type: "rich",
description: `React Hooks allow function components to have state, trigger side effects after rendering, and much more. Class components still work, but function components and hooks are now the standard approach used by the React community for any new code, and there are some new React features that only work with hooks.
The official React docs are the best resource for learning hooks:
https://reactjs.org/docs/hooks-intro.html
However, the React docs still teach classes in the tutorials. A rewrite is in progress, but until then, there's a "React with Hooks" version of the React docs that uses hooks and function components for all examples:
https://reactwithhooks.netlify.app/
This article explains why hooks are important and what problems they solve:
https://ui.dev/why-react-hooks/
`,
color: EMBED_COLOR
}
});
}
},
{
words: ["@here", "@everyone"],
help: "",
category: "Communication",
handleMessage: msg => {
if (!msg || !msg.guild) {
return;
}
const member = msg.guild.member(msg.author.id);
if (!member || isStaff(member)) {
return;
}
msg.channel.send({
embed: {
title: "Tsk tsk.",
type: "rich",
description: `Please do **not** try to use \`@here\` or \`@everyone\` - there are ${msg.guild.memberCount} members in Reactiflux. Everybody here is a volunteer, and somebody will respond when they can.`,
color: "#BA0C2F"
}
});
}
}
];
const createCommandsMessage = () => {
const groupedMessages: { [key in Categories]: Command[] } = {
Reactiflux: [],
Communication: [],
Web: [],
"React/Redux": []
};
// Omit any commands that are internal, like the `@here` warning
const visibleCommands = commandsList.filter(command => !!command.help);
visibleCommands.forEach(command => {
groupedMessages[command.category].push(command);
});
const categoryDescriptions = sortedCategories.map(category => {
const commands = groupedMessages[category];
// Mutating in map(), but whatever
commands.sort((a, b) => {
// Assume there's at least one trigger word per command
return a.words[0].localeCompare(b.words[0]);
});
const boldTitle = `**${category}**`;
const commandDescriptions = commands
.map(command => {
const formattedWords = command.words.map(word => `**\`${word}\`**`);
return `${formattedWords.join(", ")}: ${command.help}`;
})
.join("\n");
const categoryDescription = `${boldTitle}\n${commandDescriptions}`;
return categoryDescription;
});
return categoryDescriptions.join("\n\n").trim();
};
const commands: ChannelHandlers = {
handleMessage: ({ msg }) => {
if (!msg.guild && msg.channel.type !== "dm") {
return;
}
commandsList.forEach(command => {
const keyword = command.words.find(word => {
return msg.content.toLowerCase().includes(word);
});
if (keyword) {
if (cooldown.hasCooldown(msg.author.id, `commands.${keyword}`)) return;
const { name: channelName } = msg.channel as TextChannel;
const hasPreventedBotResponse = isBotDisabledInChannel(channelName);
if (hasPreventedBotResponse) {
notifyUserBotResponseWasPrevented(msg, channelName);
return;
}
cooldown.addCooldown(msg.author.id, `commands.${keyword}`);
command.handleMessage(msg);
}
});
}
};
export default commands;