Compare commits

...

212 Commits

Author SHA1 Message Date
iCrawl
28f51791a2 chore(ws): release @discordjs/ws@0.8.3 2023-05-06 11:05:18 +02:00
DD
e6274681fd fix(WebSocketManager): properly emit shard error events (#9521)
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-05-05 20:17:05 +00:00
DD
00da44a120 fix(WebSocketShard): wait a little before reconnecting (#9517)
* fix(WebSocketShard): wait a little before reconnecting

* chore: leftover comment

---------

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-05-05 20:14:53 +00:00
Mateusz Burzyński
ab39683a50 chore: "hide" ./defaultWorker entrypoint with types: null (#9485)
* fix: move `types` condition to the front

* Update packages/ws/package.json

---------

Co-authored-by: Vlad Frangu <kingdgrizzle@gmail.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>
2023-05-05 20:08:12 +00:00
DD
3e80f0b384 tests(ws): fix tests (#9520) 2023-05-05 22:01:28 +02:00
iCrawl
e53b94c979 chore: remove cron 2023-05-05 21:21:09 +02:00
Almeida
6b2c3fb9d0 feat(Guild): safety alerts channel and mention raid protection (#8959)
* feat(Guild): add safety alerts channel and mention raid protection

* docs: add missing tag

* fix: keep other properties in triggerMetadata

* docs(Guild): update example usage

---------

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>
2023-05-05 18:39:58 +00:00
iCrawl
d8d21cf370 chore: cloudflare sponsorship 2023-05-05 20:29:10 +02:00
Aura Román
8e9a2b4630 perf(Role): linear speed position getter (#9493)
Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>
2023-05-05 12:49:00 +00:00
iCrawl
d4f12e0a0c chore: deps 2023-05-05 14:30:47 +02:00
Jiralite
d7b18f0681 types(StringSelectMenuComponentData): options is required (#9515)
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-05-05 12:28:39 +00:00
Jiralite
166c961261 fix(roleConnections): Fix body type for updateMetadataRecords() (#9516) 2023-05-05 09:42:12 +02:00
Jiralite
506f7fcd3b fix(guide): Fix unknown component in v14 update guide (#9514)
* chore(constants): update discord.js to 14.10.2

* feat(DocsLink): handle only a package

* fix(updating-to-v14): fix unknown component
2023-05-05 07:37:47 +00:00
Jiralite
51d53f5117 feat(guide): Add webhooks (#9479)
* feat: add page

* feat: add assets

* chore: DocsLink

Co-authored-by: Ryan Munro <monbrey@gmail.com>

* fix: config import

* fix: another assert bug

* chore: lint

* fix: actually fix the destructure

---------

Co-authored-by: Ryan Munro <monbrey@gmail.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-05-04 08:49:18 +00:00
Idris
aa32d67619 chore(voice-description): being consistency with Node.js casing (#9505)
docs(voice-description): being consistency with Node.js casing

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-05-04 08:44:35 +00:00
Suneet Tipirneni
4b077e679c refactor(guide): use @type comments for command data code (#9489)
* refactor(guide): use `@type` comments for command data code

* fix: typo

* fix: use correct doc comment

* fix: use one line

* feat: add param types

* fix: use command interaction instead

* Update apps/guide/src/content/03-creating-your-bot/03-adding-commands.mdx

Co-authored-by: Souji <timoqueezle@gmail.com>

* chore: lint

---------

Co-authored-by: Souji <timoqueezle@gmail.com>
Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>
2023-05-03 23:58:53 +00:00
iCrawl
c190c57d64 chore: re-apply patches 2023-05-03 18:25:20 +02:00
Jaw0r3k
423bfce286 docs: Add bug/feature form for ui and util (#9504)
feat: add tags for other packages
2023-05-03 16:20:09 +00:00
iCrawl
5d05b7230a chore: re-gen yarn.lock 2023-05-03 02:30:15 +02:00
iCrawl
7e875f6919 chore: refactor workspace 2023-05-03 02:14:22 +02:00
Qjuh
c429763be8 fix(WebSocketManager): emit raw ws events again (#9502) 2023-05-02 19:49:55 +00:00
Jiralite
1b7981e469 docs(Client): Update Sapphire's snowflake utility links (#9501) 2023-05-02 12:56:38 +02:00
Aura Román
f2ad0762c5 refactor(GuildChannel): simplify constructor (#9499) 2023-05-02 10:32:47 +00:00
iCrawl
6d7f3b0f5c chore(discord.js): release discord.js@14.10.2 2023-05-02 01:18:23 +02:00
Almeida
201b002ad4 fix: correct isJSONEncodable() import (#9495)
Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>
2023-05-01 22:25:51 +00:00
Almeida
b327f4925f fix(Client): generateInvite() scope validation (#9492) 2023-05-01 22:11:11 +00:00
iCrawl
e262df9117 chore(discord.js): release discord.js@14.10.1 2023-05-01 23:50:16 +02:00
iCrawl
7a761d4cfb chore: properly use cjs in module 2023-05-01 23:49:59 +02:00
iCrawl
ac9bf3ac06 fix(Client): spelling of InvalidScopesWithPermissions 2023-05-01 23:49:32 +02:00
iCrawl
133a6bbf49 chore(builders): release @discordjs/builders@1.6.3 2023-05-01 23:35:14 +02:00
iCrawl
63fc9f8504 chore(util): release @discordjs/util@0.3.1 2023-05-01 23:34:16 +02:00
Almeida
a9f2bff82a refactor(ShardClientUtil): logic de-duplication (#9491)
added docs to the `calculateShardId` function
2023-05-01 20:08:45 +00:00
Almeida
54ceedf6c5 refactor: remove @discordjs/util re-export (#9488) 2023-05-01 21:47:30 +02:00
Jiralite
36b7fb2f00 feat(guide): Update to 14.10.0 (#9487) 2023-05-01 21:05:29 +02:00
iCrawl
9a56edaf8c chore: add module resolution for the website 2023-05-01 18:21:02 +02:00
iCrawl
be81c8bf3b chore(discord.js): release discord.js@14.10.0 2023-05-01 17:42:07 +02:00
iCrawl
c77a1765c4 chore(core): release @discordjs/core@0.6.0 2023-05-01 17:35:40 +02:00
iCrawl
3665ad65d0 chore(ws): release @discordjs/ws@0.8.2 2023-05-01 17:34:27 +02:00
iCrawl
d4de1cd09e chore(proxy): release @discordjs/proxy@1.4.1 2023-05-01 17:31:00 +02:00
iCrawl
481bbc924f chore(rest): release @discordjs/rest@1.7.1 2023-05-01 17:29:19 +02:00
iCrawl
ca81e61b4c chore(formatters): release @discordjs/formatters@0.3.1 2023-05-01 17:24:36 +02:00
iCrawl
eb603c0d11 chore(util): release @discordjs/util@0.3.0 2023-05-01 17:22:55 +02:00
iCrawl
072c9da5df chore(collection): release @discordjs/collection@1.5.1 2023-05-01 17:20:16 +02:00
iCrawl
cd591327d6 chore(builders): release @discordjs/builders@1.6.2 2023-05-01 17:16:31 +02:00
iCrawl
71e67d8c97 chore(brokers): release @discordjs/brokers@0.2.1 2023-05-01 17:15:29 +02:00
Qjuh
a9e0de4288 refactor(WebSocketManager): use /ws package internally (#9099) 2023-05-01 17:08:23 +02:00
iCrawl
c5b4423a5a ci: properly add all tsconfig options 2023-05-01 16:44:36 +02:00
iCrawl
47b08be509 ci: fix start scripts for actions 2023-05-01 16:34:56 +02:00
iCrawl
2e0804ae92 ci: update node version 2023-05-01 16:27:29 +02:00
iCrawl
71983cc5d1 ci: make package optional for docs upload 2023-05-01 16:02:05 +02:00
iCrawl
0f3d870ce6 ci: properly look for docs 2023-05-01 15:57:28 +02:00
iCrawl
ce4e1fc2c6 ci: dramatically speed up docs building 2023-05-01 15:55:14 +02:00
iCrawl
0762ddb3f4 chore: deps 2023-05-01 15:29:51 +02:00
iCrawl
80af9696d3 build: leftover extensions 2023-05-01 15:23:15 +02:00
iCrawl
48cab844d4 build: switch to bundler moduleResolution 2023-05-01 13:14:13 +02:00
iCrawl
8b71f44b1f chore: deps 2023-05-01 12:05:55 +02:00
Almeida
f27631175a feat(ui): support embed image, thumbnail, author url, and url (#9478) 2023-04-30 16:56:34 +02:00
GrapeColor
ad217cc760 fix(ShardClientUtil): Fix client event names (#9474)
Co-authored-by: GrapeColor <grapecolor@users.noreply.github.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-30 10:16:44 +00:00
iCrawl
1ba7394a7d chore: deps 2023-04-30 09:01:17 +02:00
Jiralite
260c46d51c feat(guide): Add audit logs (#9429) 2023-04-30 07:50:14 +02:00
iCrawl
6229597db2 fix(guide): add more headings 2023-04-29 20:10:06 +02:00
iCrawl
8d212e4859 feat(guide): anchor links 2023-04-29 20:05:22 +02:00
iCrawl
51e8f02ef7 fix(ui): author and reply author spacing 2023-04-29 17:44:02 +02:00
Tetie
496c4e2884 feat(ui): support verified bots and colored authors (#9471)
Co-authored-by: Noel <buechler.noel@outlook.com>
2023-04-29 17:26:31 +02:00
Jiralite
77191a2e7b docs: Add new issue form for applications (#9470) 2023-04-28 21:47:19 +02:00
Jiralite
375483b0f9 feat(guide): Add threads (#9430) 2023-04-28 21:46:45 +02:00
Jiralite
17cd4b610a fix(guide): Show rest of TypeScript code block (#9465) 2023-04-28 21:46:27 +02:00
Suneet Tipirneni
988f8c7546 refactor(website): consolidate styling for buttons (#9466) 2023-04-28 21:42:47 +02:00
Jiralite
217e5d8100 fix(BaseClient): Prevent user agent mutation (#9425)
fix(BaseClient): prevent user agent mutation
2023-04-28 17:46:50 +00:00
Jaw0r3k
40d07fbbbd fix(BitField): use only enum names in iterating (#9357)
* fix: use only names in iterating bitfield

* fix: not a number

Co-authored-by: Vlad Frangu <kingdgrizzle@gmail.com>

* fix: serialize

Co-authored-by: SpaceEEC <spaceeec@yahoo.com>

---------

Co-authored-by: Vlad Frangu <kingdgrizzle@gmail.com>
Co-authored-by: SpaceEEC <spaceeec@yahoo.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-28 17:25:11 +00:00
anandre
1b15d31b5a docs(AutoModerationRule): update docs (#9464)
* Update AutoModerationRule.js

Update the docs descriptions for some of the AutoModerationRule methods to make them clearer and easier to understand

* Update AutoModerationRule.js

Updated the `exemptRoles` and `exemptChannels` parameter descriptions for their respective helper methods to match the typedef `AutoModerationRuleEditOptions`.

* Update AutoModerationRule.js

Update the `mentionTotalLimit` description to match the one in the `AutoModerationTriggerMetadataOptions` typdef.

* Update packages/discord.js/src/structures/AutoModerationRule.js

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>

---------

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-28 17:19:14 +00:00
Idris
d26df5faba types(AutoModerationActionMetadataOptions): make channel property optional (#9460)
* refactor(GuildMember): make _roles a getter and roles a normal prop

* types(AutoModerationActionMetadataOptions): make channel property optional

* fix: revert changes from another PR

---------

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-28 17:13:27 +00:00
Ryan Munro
78fe247fc4 feat(guide): port and update lots of stuff (#9385)
Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>
Co-authored-by: Noel <buechler.noel@outlook.com>
2023-04-27 20:58:25 +02:00
RanAS
36216c0e1a docs: include StreamType enum description in new docs (#9457) 2023-04-27 20:29:27 +02:00
Jiralite
6212bffa30 docs: Update example usage (#9461) 2023-04-27 20:28:44 +02:00
Suneet Tipirneni
b2e1bb92d0 fix(website): don't duplicate overloaded methods (#9462) 2023-04-27 20:25:23 +02:00
Almeida
2e09cb4c1f feat(ui): support embed fields, footer icon, and timestamp (#9442) 2023-04-25 19:05:14 +02:00
Michael H
1b4d34cebf chore: Add directory to package.json (#9456)
* chore: Add directory to package.json

* fix: run fmt

* fix: undo formatting
2023-04-25 14:27:44 +00:00
iCrawl
8153ca99ee ci: update formatting tag 2023-04-24 20:19:40 +02:00
iCrawl
43e205b840 chore: deps 2023-04-24 19:46:44 +02:00
Jiralite
c6ca5a83e7 docs(APITypes): Document role & user select menu components (#9435)
docs(APITypes): document select menu components

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-21 20:56:51 +00:00
Jiralite
5c52bb9590 docs(BaseMessageOptions): Fix embeds and components (#9437)
docs(BaseMessageOptions): fix embeds and components

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-21 20:43:17 +00:00
DD
a49ed0a2d5 refactor(proxy): rely on auth header instead (#9422)
* refactor(proxy): rely on auth header instead

* chore: typo

* chore: language

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>

* chore: more language

Co-authored-by: Aura Román <kyradiscord@gmail.com>

* chore: more language nitpicks

Co-authored-by: ckohen <chaikohen@gmail.com>

* fix: unnecessary async

---------

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>
Co-authored-by: Aura Román <kyradiscord@gmail.com>
Co-authored-by: ckohen <chaikohen@gmail.com>
2023-04-21 20:36:15 +00:00
Almeida
3e01f91bbb feat(Attachment): voice messages (#9392)
Co-authored-by: Tetie <tjvssr@gmail.com>
2023-04-21 11:09:37 +02:00
anandre
7d341000d4 docs(InteractionResponses): showModal docs change (#9434)
* Update InteractionResponses.js

Update the parameters for the showModal method

* Update APITypes.js

Add APIModalInteractionResponseCallbackData link for docs link for showModal method

* Update InteractionResponses.js

Change the order of parameters so the ModalBuilder is listed first

* Update APITypes.js

Disable the ESline line length rule for the APITypes file

* Update InteractionResponses.js

Add ModalComponentData to the JSDoc, it was omitted before.
2023-04-21 08:17:44 +00:00
Jiralite
b49c5c9f48 ci: Fix issue triage (#9433) 2023-04-20 20:41:21 +02:00
MrMythicalYT
ce287f21d1 docs: use ESM code in examples (#9427)
* docs(Partials): use import statement

* docs: update readme to ESM

---------

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-20 06:40:15 +00:00
MrMythicalYT
d6bca9bb4d docs: reference package names properly (#9426) 2023-04-20 06:25:32 +00:00
Jiralite
a2ab2b8717 feat(scripts): Sort issue labels (#9423)
feat(scripts): sort issue labels

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-19 20:09:05 +00:00
Suneet Tipirneni
ecd1b5da11 refactor(website): consolidate badge logic (#9417)
Co-authored-by: Noel <buechler.noel@outlook.com>
2023-04-19 18:58:35 +02:00
Jiralite
0eb866357b ci: Update actions (#9424) 2023-04-19 18:57:16 +02:00
Almeida
d2d27ce734 fix: use new permission name (#9274)
* fix: use new permission name

* docs: requested changes

---------

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-19 14:32:07 +00:00
Jiralite
603446a692 chore: Bump dependencies for template package (#9418)
* chore: bump dependencies

* chore: update .yarnrc.yml
2023-04-19 05:43:46 +00:00
Suneet Tipirneni
f1fdd5b010 refactor(website): extract shared code heading styling into component (#9414)
* refactor(website): extract shared code heading styling into component

* chore: remove redundant variable
2023-04-17 21:33:51 +00:00
DD
5d1a4c27d5 feat(core): abstract gateway (#9410)
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-17 20:05:05 +00:00
iCrawl
98a76db482 docs: generate static imports for types with api-extractor 2023-04-17 19:08:01 +02:00
Suneet Tipirneni
516c46117c feat(website): use tsdoc parameter names wherever possible (#9413)
Co-authored-by: Noel <buechler.noel@outlook.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-17 18:44:17 +02:00
Tetie
7d7972d239 chore(Client): robust error checking (#9390)
* chore: robust error checking

* fix: check for null

* chore: add period

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>

* fix: check for undefined correctly

* chore: robust error checking

* fix: check for null

* chore: add period

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>

* fix: check for undefined correctly

* fix: check for null

* fix: update typings

---------

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>
2023-04-17 15:05:32 +00:00
Jiralite
7b10e8cb63 feat: Add FAQ (#9407)
* feat: port over FAQ

* refactor: use async/await

Co-authored-by: Almeida <almeidx@pm.me>

* style: spacing

* refactor: use role id

* feat: more links!

* refactor: move comment up

* refactor: consistent naming style

---------

Co-authored-by: Almeida <almeidx@pm.me>
2023-04-17 08:31:53 +00:00
Jiralite
2f18323d2c fix(updating-to-v14): Parameter typo (#9408)
fix: parameter typo
2023-04-17 01:35:34 +00:00
Suneet Tipirneni
e04801bba1 fix(website): add equals to enum members (#9405) 2023-04-16 21:43:37 +00:00
iCrawl
09a9fb57e0 chore(core): release @discordjs/core@0.5.2 2023-04-16 23:02:41 +02:00
iCrawl
025b7aea29 chore(core): release @discordjs/core@0.5.1 2023-04-16 22:58:25 +02:00
iCrawl
7aa5ea731f chore(ws): release @discordjs/ws@0.8.1 2023-04-16 22:54:15 +02:00
iCrawl
f883279ab3 ci: re-add pr triage for labels 2023-04-16 22:50:43 +02:00
iCrawl
f1b2dec8e1 chore: add codeowners 2023-04-16 22:38:38 +02:00
Aura Román
0a1701b046 types(ChannelsAPI): use correct type for editMessage (#9399)
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-16 18:27:16 +00:00
Jiralite
5dcc6df224 fix(updating-to-v14): Prioritise JavaScript (#9401) 2023-04-16 20:22:41 +02:00
Jiralite
1c35425120 fix(collection): filter() markdown (#9402) 2023-04-16 20:21:47 +02:00
Jiralite
cf1f5c0f0c chore(async-await): Update to ESM (#9403) 2023-04-16 20:21:30 +02:00
iCrawl
a210fc64a2 fix(website): dark mode text color 2023-04-16 19:21:41 +02:00
iCrawl
24f17998c8 refactor(website): revise landing page 2023-04-16 19:10:50 +02:00
iCrawl
eda118dae9 fix(guide): optimize redirects on middleware level 2023-04-16 17:42:05 +02:00
iCrawl
f2fce0a7da refactor(guide): always redirect to introduction 2023-04-16 17:38:45 +02:00
Jiralite
29389e39f4 feat(BaseInteraction): Support new channel payload (#9337)
* feat(BaseInteraction): support new channel payload

* refactor(InteractionCreate): different approach

Co-Authored-By: Synbulat Biishev <contact@syjalo.dev>

---------

Co-authored-by: Synbulat Biishev <contact@syjalo.dev>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-16 14:28:32 +00:00
iCrawl
d5e9e36e8a fix(guide): let the breadcrumbs grow to the full size 2023-04-16 13:29:55 +02:00
iCrawl
8c0eb56ba5 fix(guide): ring cutoff on guide header 2023-04-16 13:02:10 +02:00
iCrawl
1b74c774c0 fix(website): cutoff ring outline in breadcrumbs 2023-04-16 11:22:16 +02:00
iCrawl
01949d6e3a fix(website): wrong breakpoint 2023-04-16 00:23:33 +02:00
iCrawl
3ea26cc1a6 refactor(website): only show search box on md and up 2023-04-16 00:17:12 +02:00
Suneet Tipirneni
a516d46f91 fix(website): right-align search bar (#9395) 2023-04-16 00:03:19 +02:00
iCrawl
b35b935679 fix(guide): sidebar types 2023-04-15 23:50:18 +02:00
iCrawl
0928c8f6ff fix(guide): remove astro leftovers 2023-04-15 23:37:19 +02:00
iCrawl
188d5eea28 chore: fix yarn.lock 2023-04-15 23:31:48 +02:00
iCrawl
412e4fffae build(website): prepare for turbopack 2023-04-15 18:15:24 +02:00
iCrawl
5e2f94c591 fix(website): max height 2023-04-15 14:28:20 +02:00
iCrawl
49627b1f46 chore(website): add banner 2023-04-15 14:03:03 +02:00
iCrawl
bcb48fea3e chore(website): redirect to core instead 2023-04-15 13:03:27 +02:00
iCrawl
c87e826087 style(website): remove dynamic width check 2023-04-15 04:43:23 +02:00
Ben
2dddbe1f32 feat(RoleTagData): add guildConnections (#9366)
* feat(roleTagData): add guildConnections

* feat(roletagdata): add guildConnections

* Update packages/discord.js/typings/index.d.ts

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>

---------

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>
Co-authored-by: space <spaceeec@yahoo.com>
2023-04-14 22:04:57 +00:00
Almeida
86e5f5a119 docs(Options): fix links and invalid syntax (#9322)
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-14 21:49:51 +00:00
BoogeyMan
300059cb26 docs: cleanup MessageCreateOptions and MessageReplyOptions (#9283)
* Fixed MessageReplyOptions

* updated MessageReplyOptions

* Deduplication - created BaseMessageCreateOptions

* Update packages/discord.js/src/structures/interfaces/TextBasedChannel.js

Co-authored-by: Jaw0r3k <jaworekwiadomosci@gmail.com>

* Fixed spacing

---------

Co-authored-by: Jaw0r3k <jaworekwiadomosci@gmail.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-14 21:46:15 +00:00
Erwan
d4c1fecbe2 fix(Message#editable): fix permissions check in locked threads (#9319)
fix(Message#editable): fix permissions check if channel is thread & locked

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-14 21:42:54 +00:00
Jiralite
79bcdfa767 docs(Events): Document auto moderation events (#9342)
docs(Events): document auto moderation events

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-14 21:39:35 +00:00
Jiralite
ca4de2d9c6 fix(BaseSelectMenuBuilder): Modify class to be abstract (#9358)
fix(BaseSelectMenuBuilder): abstraction

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-14 21:34:55 +00:00
Jiralite
794abe8450 refactor: Remove fromInteraction in internal channel creation (#9335)
refactor: remove `fromInteraction`
2023-04-14 21:29:27 +00:00
DD
02dfaf1aa2 refactor: abstract identify throttling and correct max_concurrency handling (#9375)
* refactor: properly support max_concurrency ratelimit keys

* fix: properly block for same key

* chore: export session state

* chore: throttler no longer requires manager

* refactor: abstract throttlers

* chore: proper member order

* chore: remove leftover debug log

* chore: use @link tag in doc comment

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>

* chore: suggested changes

* fix(WebSocketShard): cancel identify if the shard closed in the meantime

* refactor(throttlers): support abort signals

* fix: memory leak

* chore: remove leftover

---------

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-14 20:26:37 +00:00
Suneet Tipirneni
cac3c07729 fix(website): link dapi-types to proper website (#9388) 2023-04-14 20:53:57 +02:00
iCrawl
83143178aa ci: remove nextjs bundle analysis 2023-04-14 20:10:26 +02:00
iCrawl
615752e32b chore(website): cleanup ts-errors 2023-04-14 20:03:40 +02:00
iCrawl
2c25639a85 chore: update next.js dep 2023-04-14 19:23:59 +02:00
iCrawl
a76c1ddacc chore: fixup build and lint 2023-04-14 17:11:12 +02:00
Jiralite
0d0e4d1cb6 feat: Add changes from v13 to v14 (#9384) 2023-04-14 10:58:23 +02:00
iCrawl
d35f670d7a chore(website): move around static label 2023-04-14 10:33:20 +02:00
iCrawl
e4c5f794b0 fix(website): client-side rendering fallback 2023-04-13 23:29:45 +02:00
Jiralite
88cab1a0ec fix: Update DocsLink usage (#9382) 2023-04-13 22:55:15 +02:00
iCrawl
1c2cc09e05 fix(guide): temporary fix contentlayer dev 2023-04-13 22:28:33 +02:00
Jiralite
2a684361d4 fix(guide): Treeshake react-icons (#9381) 2023-04-13 22:09:40 +02:00
Almeida
66dc4014fe fix(interactions): make data parameter optional (#9379) 2023-04-13 22:01:08 +02:00
Jiralite
39c6694561 feat(DocsLink): Implement the component (#9380)
Co-authored-by: Noel <buechler.noel@outlook.com>
2023-04-13 21:55:15 +02:00
iCrawl
70da3746f8 fix(website): static badge and overload switcher 2023-04-13 20:56:44 +02:00
iCrawl
0340622f1a fix(ui): discord components 2023-04-13 20:15:59 +02:00
iCrawl
f36878677c chore: add chromatic 2023-04-13 19:41:23 +02:00
iCrawl
e5859b41cf chore: storybook 2023-04-13 19:09:56 +02:00
Jiralite
8218ffc78d types(CategoryChannel): Ensure parent and parentId are null (#9327)
types: ensure categories' parents are `null`
2023-04-13 16:10:53 +00:00
Jiralite
7ff3d528d9 types(GuildTextBasedChannel): Remove unnecessary exclusion of forum channels (#9326)
types(GuildTextBasedChannel): remove exclusion of forum channels

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-13 15:55:48 +00:00
Jiralite
0b7f296b62 chore(guide): Update pages (#9372) 2023-04-13 17:10:06 +02:00
Jiralite
85a379fdf8 feat(guide): How to contribute (#9376) 2023-04-13 14:19:43 +02:00
Jiralite
8ffcf77840 docs: add SnowflakeUtil (#9371) 2023-04-13 14:19:13 +02:00
iCrawl
fcb3a1ab27 fix(guide): update return link on 404 2023-04-12 01:04:36 +02:00
iCrawl
40be4f80dc fix(guide): light mode fix 2023-04-12 00:44:21 +02:00
iCrawl
ee907f32f3 feat(guide): sidebar 2023-04-12 00:39:35 +02:00
iCrawl
731ea5f3cb fix(website?): static params 2023-04-11 20:52:37 +02:00
iCrawl
24c462bf6f refactor(website): dark mode 2023-04-11 20:13:59 +02:00
iCrawl
78e02c4b63 fix(website): navigation and 404 2023-04-11 19:19:33 +02:00
iCrawl
dcf8757d35 ci: correct path again 2023-04-11 18:36:13 +02:00
iCrawl
a0c57abadd ci: uploading to before mv 2023-04-11 18:26:27 +02:00
iCrawl
1c5a6fa552 ci: update glob path 2023-04-11 18:12:56 +02:00
Jiralite
6a221a9676 fix(Property): Check for a property type excerpt (#9365) 2023-04-11 14:12:03 +02:00
DD
dcf58d8140 refactor(WebSocketShard): waitForEvent and its error handling (#9282)
* refactor(WebSocketShard): waitForEvent and its error handling

* chore: remove unnecessary error event

* chore: handle ECONNREFUSED/ECONNRESET

* fix: reset network error check

---------

Co-authored-by: Vlad Frangu <kingdgrizzle@gmail.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-11 11:10:32 +00:00
Jiralite
676307ff5c fix(core): Support attachment editing on interactions (#9356)
fix(core): support attachment editing on interactions

Co-authored-by: Vlad Frangu <kingdgrizzle@gmail.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-10 20:35:54 +00:00
Jiralite
23e0ac56f4 docs(formatters): Enhance the documentation (#9364) 2023-04-10 22:29:06 +02:00
Jiralite
8073561824 docs(builders): Add some basic documentation (#9359) 2023-04-10 22:09:51 +02:00
Jiralite
c0f2dd7131 docs: Use stable tag (#9343)
docs: use stable tag
2023-04-10 14:55:51 +00:00
Almeida
d6905b3b97 fix(website): dont show parameters header on functions without parameters (#9361) 2023-04-10 14:00:32 +02:00
Jiralite
774e23c572 fix(Function): Add link to source file (#9360) 2023-04-10 14:00:03 +02:00
Jiralite
1c8567f147 feat: Support @returns (#9362)
Co-authored-by: Noel <buechler.noel@outlook.com>
2023-04-10 13:59:29 +02:00
Jiralite
733c96c255 feat: Support @defaultValue (#9363) 2023-04-10 13:56:43 +02:00
iCrawl
69cdeb7296 ci: fix docs upload path 2023-04-10 13:23:27 +02:00
iCrawl
0019700869 chore(website): switch to revalidate on fetch level 2023-04-10 12:51:13 +02:00
iCrawl
3ea4d26ee9 fix(scripts): skip over namespaces 2023-04-09 19:32:41 +02:00
iCrawl
250eccf118 fix(website): members only on interfaces and classes 2023-04-09 19:12:42 +02:00
iCrawl
7d3827ebd1 fix(website): pass on revalidate 2023-04-09 18:55:59 +02:00
iCrawl
d1955f7c9e feat(website): static, optional, private, inherits, extends 2023-04-09 18:40:49 +02:00
iCrawl
6412da4921 feat: endpoint to retriveve memeber info 2023-04-09 14:21:45 +02:00
Jiralite
79123fb260 fix(ExcerptText): Use resolveItemURI() in excerpts (#9354)
Co-authored-by: Noel <buechler.noel@outlook.com>
2023-04-09 13:23:05 +02:00
iCrawl
3d2f4b405e chore(guide): bring guide up to speed 2023-04-09 12:41:02 +02:00
Almeida
bfee6c8d88 perf(RoleManager): dont call Role#position getter twice per role (#9352)
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-09 10:29:18 +00:00
Jiralite
fbbce3eb4b fix: Correct @link tags that involve parents (#9351) 2023-04-09 11:22:07 +02:00
Jiralite
b2eec5f9fc docs: Remove JSONEncondable (#9344)
docs: remove `JSONEncondable`

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-08 21:55:58 +00:00
Jiralite
b618e215f2 fix(util): Remove extra slash (#9347) 2023-04-08 23:51:58 +02:00
Jiralite
d66d113333 docs: Use @link in @see (#9348) 2023-04-08 23:50:58 +02:00
iCrawl
1b9d07f941 chore(website): downgrade planetscale dep 2023-04-07 21:25:15 +02:00
iCrawl
f893c6a357 chore: deps 2023-04-07 21:13:36 +02:00
iCrawl
687bbd889f chore(website): this may solve dynamic route problems
https://github.com/vercel/next.js/pull/47982
2023-04-07 20:54:16 +02:00
iCrawl
f195556b64 fix(website): downgrade nextjs 2023-04-07 20:10:20 +02:00
iCrawl
9aafdd6214 fix(website): model import 2023-04-07 13:41:19 +02:00
Jiralite
e3e7d500dc refactor: Use description constant in landing page (#9334) 2023-04-07 13:12:48 +02:00
iCrawl
3615e2f2d2 chore(website): deps 2023-04-07 13:10:01 +02:00
Tetie
a7425c29c4 fix: fix external links (#9313)
* fix: fix external links

* fix: fix external links

* fix: link to correct classes

* fix: fix JSONEncodable link

* chore: fix select menu link

* fix: fix external links

* fix: link to correct classes

* fix: fix JSONEncodable link

* chore: fix select menu link

* fix: fix collection#sweep url

* fix: fix subpackages urls

* fix: fix discord.js docs url

* Update packages/util/docs/README.md

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>

---------

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Co-authored-by: Aura Román <kyradiscord@gmail.com>
Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>
2023-04-07 10:35:56 +00:00
Suneet Tipirneni
c519fe66c9 refactor(ui): add 'use client' directives to client-only components (#9330) 2023-04-07 09:22:40 +02:00
Almeida
24f280290b fix(website): dont crash when serviceWorker is not available (#9331) 2023-04-07 09:22:09 +02:00
Almeida
6912faa9b3 fix(core): missed optional options (#9311)
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-04 18:37:26 +00:00
iCrawl
0645bf0f7f fix(website): edge-config fallback 2023-04-02 18:30:00 +02:00
iCrawl
6aba9e99eb ci: planetscale upload 2023-04-02 13:22:52 +02:00
iCrawl
5efdf57894 chore: deps 2023-04-02 12:59:19 +02:00
iCrawl
74059c9d97 chore(builders): release @discordjs/builders@1.6.1 2023-04-02 12:38:29 +02:00
iCrawl
8d345a041e chore: add next to packages 2023-04-02 02:50:27 +02:00
iCrawl
1cbd04e8fd build: git-cliff config 2023-04-02 01:55:39 +02:00
iCrawl
8592edba39 chore(discord.js): release discord.js@14.9.0 2023-04-02 01:52:41 +02:00
iCrawl
38f0986000 chore(ws): release @discordjs/ws@0.8.0 2023-04-02 01:51:56 +02:00
iCrawl
9e077b749c chore(voice): release @discordjs/voice@0.16.0 2023-04-02 01:51:50 +02:00
536 changed files with 17463 additions and 8298 deletions

View File

@@ -1,31 +1,33 @@
# Packages
node_modules/
**/node_modules
# Log files
logs/
*.log
npm-debug.log*
**/logs
**/*.log
**/npm-debug.log*
# Runtime data
pids
*.pid
*.seed
**/pids
**/*.pid
**/*.seed
# Env
.env
**/.env
# Dist
dist/
**/dist/
**/dist-docs/
# Miscellaneous
.tmp/
.vscode/*
.idea/
.DS_Store
.turbo
tsconfig.tsbuildinfo
coverage/
__tests__/
**/.tmp
**/.vscode
**/.idea
**/.DS_Store
**/.turbo
**/tsconfig.tsbuildinfo
**/coverage
**/__tests__
**/out
# yarn
.pnp.*
@@ -37,20 +39,29 @@ __tests__/
!.yarn/versions
# Cache
.prettiercache
.eslintcache
**/.prettiercache
**/.eslintcache
**/.vercel
# Docker specific
.cliff-jumperrc.json
api-extractor.json
.eslintrc.json
.lintstagedrc.cjs
.lintstagedrc.cjs
.prettierignore
.prettierrc.js
.prettierrc.cjs
cliff.toml
CHANGELOG.md
README.md
tsconfig.eslint.json
docs/
**/.cliff-jumperrc.json
**/api-extractor.json
**/api-extractor-docs.json
**/.eslintignore
**/.eslintrc.json
**/.lintstagedrc.js
**/.lintstagedrc.cjs
**/.lintstagedrc.json
**/.prettierignore
**/.prettierrc.js
**/.prettierrc.cjs
**/.prettierrc.json
**/cliff.toml
**/CHANGELOG.md
**/README.md
**/LICENSE
**/tsconfig.eslint.json
**/tsconfig.docs.json
**/docs/
**/vitest.config.ts

View File

@@ -2,13 +2,10 @@
"root": true,
"extends": ["neon/common", "neon/node", "neon/typescript", "neon/prettier"],
"parserOptions": {
"project": "./tsconfig.eslint.json"
"project": ["./tsconfig.eslint.json", "./apps/*/tsconfig.eslint.json", "./packages/*/tsconfig.eslint.json"]
},
"rules": {
"@typescript-eslint/consistent-type-definitions": ["error", "interface"]
},
"ignorePatterns": ["**/dist/*"],
"env": {
"jest": true
}
"ignorePatterns": ["**/dist/*"]
}

27
.github/CODEOWNERS vendored Normal file
View File

@@ -0,0 +1,27 @@
# Learn how to add code owners here:
# https://help.github.com/en/articles/about-code-owners
* @iCrawl
/apps/guide/ @discordjs/website @discordjs/guide
/apps/guide/src/content/ @discordjs/guide
/apps/website/ @discordjs/website
/packages/actions/ @discordjs/actions
/packages/api-extractor-utils/ @discordjs/api-extractor-utils
/packages/brokers/ @discordjs/brokers
/packages/builders/ @discordjs/builders
/packages/collection/ @discordjs/collection
/packages/core/ @discordjs/core
/packages/discord.js/ @discordjs/core
/packages/docgen/ @iCrawl
/packages/formatters/ @discordjs/formatters
/packages/next/ @discordjs/core
/packages/proxy/ @discordjs/proxy
/packages/proxy-container/ @discordjs/proxy
/packages/rest/ @discordjs/rest
/packages/scripts/ @discordjs/scripts
/packages/ui/ @discordjs/ui
/packages/util/ @discordjs/util
/packages/voice/ @discordjs/core
/packages/ws/ @discordjs/ws

View File

@@ -1,11 +1,13 @@
name: Bug report
description: Report incorrect or unexpected behavior of a package
description: Report an issue with discord.js or another package.
labels: [bug, need repro]
body:
- type: markdown
attributes:
value: |
Use Discord for questions: https://discord.gg/djs
Thank you for filing an issue! If you are here to ask a question, use Discord instead: https://discord.gg/djs
This issue form is for discord.js, including other packages.
- type: dropdown
id: package
attributes:
@@ -21,6 +23,8 @@ body:
- proxy
- proxy-container
- rest
- ui
- util
- voice
- ws
validations:
@@ -29,57 +33,44 @@ body:
id: description
attributes:
label: Issue description
description: |
Describe the issue in as much detail as possible.
Tip: You can attach images or log files by clicking this area to highlight it and then dragging files into it.
description: Describe the issue in as much detail as possible.
placeholder: |
Steps to reproduce with below code sample:
1. do thing
2. do thing in Discord client
3. observe behavior
4. see error logs below
1. Do thing
2. Do thing in Discord client
3. Observe behavior
4. See error logs below
validations:
required: true
- type: textarea
id: codesample
id: code_sample
attributes:
label: Code sample
description: Include a reproducible, minimal code sample. This will be automatically formatted into code, so no need for backticks.
render: typescript
placeholder: |
Your code sample should be...
... Minimal - Use as little code as possible that still produces the same problem (and is understandable)
... Complete - Provide all parts someone else needs to reproduce your problem
... Reproducible - Test the code you're about to provide to make sure it reproduces the problem
- type: input
id: djs-version
attributes:
label: Package version
description: Which version of the package are you using? Run `npm list <package>` in your project directory and paste the output.
placeholder: We no longer support version 12 or earlier of discord.js
validations:
required: true
- type: input
id: node-version
attributes:
label: Node.js version
description: |
Which version of Node.js are you using? Run `node --version` in your project directory and paste the output.
If you are using TypeScript, please include its version (`npm list typescript`) as well.
placeholder: Node.js version 16.9+ is required for version 14.0.0+
Your code sample should be:
1. Minimal - Use as little code as possible that still produces the same problem (and is understandable)
2. Complete - Provide all parts someone else needs to reproduce your problem
3. Reproducible - Test the code you're about to provide to make sure it reproduces the problem
This will be automatically formatted into code, so no need for backticks.
render: typescript
- type: textarea
id: versions
attributes:
label: Versions
description: List necessary versions here. This includes your package version, runtime version, operating system etc.
placeholder: |
- discord.js 14.9.0 (`npm ls discord.js` or another package)
- Node.js 16.9.0 (`node --version`)
- TypeScript 5.0.4 (`npm ls typescript` if you use it)
- macOS Ventura 13.3.1
validations:
required: true
- type: input
id: os
attributes:
label: Operating system
description: Which OS does your application run on?
- type: dropdown
id: priority
attributes:
label: Priority this issue should have
description: Please be realistic. If you need to elaborate on your reasoning, please use the Issue description field above.
label: Issue priority
description: Please be realistic. If you need to elaborate on your reasoning, please use the issue description field above.
options:
- Low (slightly annoying)
- Medium (should be fixed soon)
@@ -90,12 +81,9 @@ body:
id: partials
attributes:
label: Which partials do you have configured?
description: |
Check your Client constructor for the `partials` key.
Tip: you can select multiple items
description: Check your `Client` constructor for the `partials` key.
options:
- Not applicable (subpackage bug)
- Not applicable
- No Partials
- User
- Channel
@@ -111,12 +99,9 @@ body:
id: intents
attributes:
label: Which gateway intents are you subscribing to?
description: |
Check your Client constructor options for the `intents` key.
Tip: you can select multiple items
description: Check your `Client` constructor for the `intents` key.
options:
- Not applicable (subpackage bug)
- Not applicable
- No Intents
- Guilds
- GuildMembers
@@ -141,7 +126,7 @@ body:
validations:
required: true
- type: input
id: dev-release
id: dev_release
attributes:
label: I have tested this issue on a development release
placeholder: d23280c (commit hash)

View File

@@ -0,0 +1,58 @@
name: Websites bug report
description: Report an issue with the documentation or guide websites.
labels: [bug, need repro]
body:
- type: markdown
attributes:
value: |
Thank you for filing an issue! If you are here to ask a question, use Discord instead: https://discord.gg/djs
This issue form is for our documentation and guide websites.
- type: dropdown
id: application
attributes:
label: Which application is this bug report for?
options:
- Documentation
- Guide
validations:
required: true
- type: textarea
id: description
attributes:
label: Issue description
description: Describe the issue in as much detail as possible.
validations:
required: true
- type: textarea
id: steps_to_reproduce
attributes:
label: Steps to Reproduce
description: What steps must be taken to reproduce this issue?
placeholder: |
1. Visit a page
2. Click a link
3. ...
validations:
required: true
- type: textarea
id: versions
attributes:
label: Versions
description: List necessary versions here. This includes your browser, operating system etc.
placeholder: |
- Safari 16.4 (18615.1.26.11.23)
- macOS Ventura 13.3.1
validations:
required: true
- type: dropdown
id: priority
attributes:
label: Issue priority
description: Please be realistic. If you need to elaborate on your reasoning, please use the issue description field above.
options:
- Low (slightly annoying)
- Medium (should be fixed soon)
- High (immediate attention needed)
validations:
required: true

View File

@@ -9,11 +9,13 @@ body:
We do not implement unreleased features.
Use Discord for questions: https://discord.gg/djs
- type: dropdown
id: package
id: application_or_package
attributes:
label: Which package is this feature request for?
label: Which application or package is this feature request for?
options:
- discord.js
- Documentation
- Guide
- brokers
- builders
- collection
@@ -23,6 +25,8 @@ body:
- proxy
- proxy-container
- rest
- ui
- util
- voice
- ws
validations:
@@ -48,7 +52,7 @@ body:
label: Alternative solutions or implementations
description: A clear and concise description of any alternative solutions or features you have considered.
- type: textarea
id: additional-context
id: additional_context
attributes:
label: Other context
description: Any other context, screenshots, or file uploads that help us understand your feature request.

View File

@@ -1,8 +0,0 @@
addReviewers: true
reviewers:
- iCrawl
- SpaceEEC
- kyranet
- vladfrangu
numberOfReviewers: 0
runOnDraft: true

View File

@@ -1,24 +1,48 @@
apps:guide:
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\nGuide\\n"
apps:website:
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\nDocumentation\\n"
packages:brokers:
- '### Which package is this (bug report|feature request) for\?\n\nbrokers'
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\nbrokers\\n"
packages:builders:
- '### Which package is this (bug report|feature request) for\?\n\nbuilders'
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\nbuilders\\n"
packages:collection:
- '### Which package is this (bug report|feature request) for\?\n\ncollection'
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\ncollection\\n"
packages:core:
- '### Which package is this (bug report|feature request) for\?\n\ncore'
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\ncore\\n"
packages:discord.js:
- '### Which package is this (bug report|feature request) for\?\n\ndiscord.js'
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\ndiscord.js\\n"
packages:formatters:
- '### Which package is this (bug report|feature request) for\?\n\nformatters'
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\nformatters\\n"
packages:next:
- '### Which package is this (bug report|feature request) for\?\n\nnext'
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\nnext\\n"
packages:proxy:
- '### Which package is this (bug report|feature request) for\?\n\nproxy'
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\nproxy\\n"
packages:proxy-container:
- '### Which package is this (bug report|feature request) for\?\n\nproxy-container'
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\nproxy-container\\n"
packages:rest:
- '### Which package is this (bug report|feature request) for\?\n\nrest'
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\nrest\\n"
packages:ui:
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\ui\\n"
packages:util:
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\util\\n"
packages:voice:
- '### Which package is this (bug report|feature request) for\?\n\nvoice'
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\nvoice\\n"
packages:ws:
- '### Which package is this (bug report|feature request) for\?\n\nws'
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\nws\\n"

BIN
.github/powered-by-workers.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

View File

@@ -24,7 +24,7 @@ concurrency:
cancel-in-progress: true
jobs:
build:
name: Build documentation
name: Build & upload documentation
runs-on: ubuntu-latest
env:
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
@@ -36,10 +36,10 @@ jobs:
with:
ref: ${{ inputs.ref || '' }}
- name: Install node.js v16
- name: Install node.js v18
uses: actions/setup-node@v3
with:
node-version: 16
node-version: 18
- name: Install dependencies
uses: ./packages/actions/src/yarnCache
@@ -50,71 +50,6 @@ jobs:
- name: Build docs
run: yarn docs
- name: Upload docgen artifacts
uses: actions/upload-artifact@v3
with:
name: docgen
path: packages/*/docs/docs.json
- name: Upload api-extractor artifacts
uses: actions/upload-artifact@v3
with:
name: api-extractor
path: packages/*/docs/docs.api.json
upload:
name: Upload Documentation
needs: build
strategy:
max-parallel: 1
fail-fast: false
matrix:
package:
[
'brokers',
'builders',
'collection',
'core',
'discord.js',
'next',
'formatters',
'proxy',
'rest',
'util',
'voice',
'ws',
]
runs-on: ubuntu-latest
env:
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Install node.js v16
uses: actions/setup-node@v3
with:
node-version: 16
- name: Install dependencies
uses: ./packages/actions/src/yarnCache
- name: Build actions
run: yarn workspace @discordjs/actions build
- name: Download docgen artifacts
uses: actions/download-artifact@v3
with:
name: docgen
path: docs
- name: Download api-extractor artifacts
uses: actions/download-artifact@v3
with:
name: api-extractor
path: docs
- name: Checkout docs repository
uses: actions/checkout@v3
with:
@@ -129,22 +64,8 @@ jobs:
with:
tag: ${{ github.ref_name }}
- name: Move docs to correct directory
if: ${{ github.ref_type == 'tag' && matrix.package == steps.extract-tag.outputs.package }}
env:
PACKAGE: ${{ steps.extract-tag.outputs.package }}
SEMVER: ${{ steps.extract-tag.outputs.semver }}
run: |
mkdir -p out/${PACKAGE}
if [[ $PACKAGE == "discord.js" ]]; then
mv docs/${PACKAGE}/docs/docs.json out/${PACKAGE}/${SEMVER}.json
fi
if [[ $PACKAGE != "discord.js" ]]; then
mv docs/${PACKAGE}/docs/docs.api.json out/${PACKAGE}/${SEMVER}.api.json
fi
- name: Upload documentation to database
if: ${{ github.ref_type == 'tag' && matrix.package == steps.extract-tag.outputs.package }}
if: ${{ github.ref_type == 'tag' }}
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
uses: ./packages/actions/src/uploadDocumentation
@@ -153,16 +74,16 @@ jobs:
version: ${{ steps.extract-tag.outputs.semver }}
- name: Move docs to correct directory
if: ${{ github.ref_type == 'branch' }}
if: ${{ github.ref_type == 'tag' }}
env:
PACKAGE: ${{ matrix.package }}
PACKAGE: ${{ steps.extract-tag.outputs.package }}
SEMVER: ${{ steps.extract-tag.outputs.semver }}
run: |
mkdir -p out/${PACKAGE}
if [[ $PACKAGE == "discord.js" ]]; then
mv docs/${PACKAGE}/docs/docs.json out/${PACKAGE}/${GITHUB_REF_NAME}.json
fi
if [[ $PACKAGE != "discord.js" ]]; then
mv docs/${PACKAGE}/docs/docs.api.json out/${PACKAGE}/${GITHUB_REF_NAME}.api.json
mkdir -p "out/${PACKAGE}"
if [[ "${PACKAGE}" == "discord.js" ]]; then
mv "packages/${PACKAGE}/docs/docs.json" "out/${PACKAGE}/${SEMVER}.json"
else
mv "packages/${PACKAGE}/docs/docs.api.json" "out/${PACKAGE}/${SEMVER}.api.json"
fi
- name: Upload documentation to database
@@ -170,8 +91,20 @@ jobs:
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
uses: ./packages/actions/src/uploadDocumentation
with:
package: ${{ matrix.package }}
- name: Move docs to correct directory
if: ${{ github.ref_type == 'branch' }}
run: |
declare -a PACKAGES=("brokers" "builders" "collection" "core" "discord.js" "next" "formatters" "proxy" "rest" "util" "voice" "ws")
for PACKAGE in "${PACKAGES[@]}"; do
if [[ "${PACKAGE}" == "discord.js" ]]; then
mkdir -p "out/${PACKAGE}"
mv "packages/${PACKAGE}/docs/docs.json" "out/${PACKAGE}/${GITHUB_REF_NAME}.json"
else
mkdir -p "out/${PACKAGE}"
mv "packages/${PACKAGE}/docs/docs.api.json" "out/${PACKAGE}/${GITHUB_REF_NAME}.api.json"
fi
done
- name: Commit and push
run: |

View File

@@ -6,7 +6,7 @@ jobs:
issue-triage:
runs-on: ubuntu-latest
steps:
- uses: github/issue-labeler@v2.5
- uses: github/issue-labeler@v3.1
with:
repo-token: '${{ secrets.GITHUB_TOKEN }}'
configuration-path: .github/issue-labeler.yml

View File

@@ -10,7 +10,7 @@ jobs:
steps:
- name: Get Vercel preview URL
id: get_preview_url
uses: actions/github-script@v3
uses: actions/github-script@v6
with:
script: |
const comment = context.payload.comment;
@@ -53,7 +53,7 @@ jobs:
- name: Format lighthouse score
if: ${{ steps.get_preview_url.outputs.vercel_preview_url != '' }}
id: format_lighthouse_score
uses: actions/github-script@v3
uses: actions/github-script@v6
with:
script: |
const result = ${{ steps.lighthouse_audit.outputs.manifest }}[0].summary

View File

@@ -1,102 +0,0 @@
name: 'Next.js Bundle Analysis'
on:
push:
branches:
- 'main'
pull_request_target:
paths:
- 'apps/website/**'
workflow_dispatch:
defaults:
run:
working-directory: apps/website
permissions:
contents: read
actions: read
pull-requests: write
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Install node.js v16
uses: actions/setup-node@v3
with:
node-version: 16
- name: Install dependencies
uses: ./packages/actions/src/yarnCache
- name: Restore next build
uses: actions/cache@v3
id: restore-build-cache
env:
cache-name: cache-next-build
with:
path: apps/website/.next/cache
key: ${{ runner.os }}-build-${{ env.cache-name }}
- name: Build packages
run: yarn run --top-level build
- name: Build website
run: yarn workspace @discordjs/website run build:local
- name: Analyze bundle
run: npx -yes -p github:hashicorp/nextjs-bundle-analysis report
- name: Upload bundle
uses: actions/upload-artifact@v3
with:
name: bundle
path: apps/website/.next/analyze/__bundle_analysis.json
- name: Download base branch bundle stats
uses: dawidd6/action-download-artifact@v2
if: success() && github.event.number
with:
workflow: nextjs-bundle-analysis.yml
commit: ${{ github.event.pull_request.base.sha }}
path: apps/website/.next/analyze/base
- name: Compare with base branch bundle
if: success() && github.event.number
run: ls -laR .next/analyze/base && npx -yes -p github:hashicorp/nextjs-bundle-analysis compare
- name: Get comment body
id: get-comment-body
if: success() && github.event.number
uses: actions/github-script@v6
with:
result-encoding: string
script: |
const fs = require('fs');
const comment = fs.readFileSync('apps/website/.next/analyze/__bundle_analysis_comment.txt', 'utf8');
core.setOutput('body', comment);
- name: Find Comment
uses: peter-evans/find-comment@v2
if: success() && github.event.number
id: fc
with:
issue-number: ${{ github.event.number }}
body-includes: '<!-- __NEXTJS_BUNDLE -->'
- name: Create Comment
uses: peter-evans/create-or-update-comment@v2
if: success() && github.event.number && steps.fc.outputs.comment-id == 0
with:
issue-number: ${{ github.event.number }}
body: ${{ steps.get-comment-body.outputs.body }}
- name: Update Comment
uses: peter-evans/create-or-update-comment@v2
if: success() && github.event.number && steps.fc.outputs.comment-id != 0
with:
issue-number: ${{ github.event.number }}
body: ${{ steps.get-comment-body.outputs.body }}
comment-id: ${{ steps.fc.outputs.comment-id }}
edit-mode: replace

View File

@@ -12,10 +12,10 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v3
- name: Install node.js v16
- name: Install node.js v18
uses: actions/setup-node@v3
with:
node-version: 16
node-version: 18
- name: Install dependencies
uses: ./packages/actions/src/yarnCache

View File

@@ -11,7 +11,3 @@ jobs:
with:
repo-token: '${{ secrets.GITHUB_TOKEN }}'
sync-labels: true
- name: Automatically assign reviewers
if: github.event.action == 'opened'
uses: kentaro-m/auto-assign-action@v1.2.3

View File

@@ -12,10 +12,10 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v3
- name: Install node.js v16
- name: Install node.js v18
uses: actions/setup-node@v3
with:
node-version: 16
node-version: 18
- name: Install dependencies
uses: ./packages/actions/src/yarnCache
@@ -30,7 +30,7 @@ jobs:
run: echo ${{ secrets.DOCKER_ACCESS_TOKEN }} | docker login -u ${{ secrets.DOCKER_USERNAME }} --password-stdin
- name: Build the image
run: yarn docker build @discordjs/proxy-container -t discordjs/proxy:latest
run: yarn docker build --buildkit @discordjs/proxy-container -t discordjs/proxy:latest
- name: Push image to DockerHub
run: docker push discordjs/proxy:latest

View File

@@ -43,10 +43,10 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v3
- name: Install node.js v16
- name: Install node.js v18
uses: actions/setup-node@v3
with:
node-version: 16
node-version: 18
registry-url: https://registry.npmjs.org/
- name: Install dependencies

View File

@@ -9,10 +9,10 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v3
- name: Install node.js v16
- name: Install node.js v18
uses: actions/setup-node@v3
with:
node-version: 16
node-version: 18
- name: Install dependencies
uses: ./packages/actions/src/yarnCache
@@ -27,10 +27,7 @@ jobs:
run: echo ${{ secrets.DOCKER_ACCESS_TOKEN }} | docker login -u ${{ secrets.DOCKER_USERNAME }} --password-stdin
- name: Build docker image
run: yarn docker build @discordjs/proxy-container -t discordjs/proxy:latest
- name: Tag image with major
run: docker tag discordjs/proxy discordjs/proxy:$(cut -d '.' -f1 <<< $(jq --raw-output '.version' packages/proxy-container/package.json))
run: yarn docker build --buildkit @discordjs/proxy-container -t discordjs/proxy:$(cut -d '.' -f1 <<< $(jq --raw-output '.version' packages/proxy-container/package.json))
- name: Push image to DockerHub
run: docker push --all-tags discordjs/proxy

View File

@@ -14,10 +14,10 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v3
- name: Install node.js v16
- name: Install node.js v18
uses: actions/setup-node@v3
with:
node-version: 16
node-version: 18
registry-url: https://registry.npmjs.org/
- name: Install dependencies

View File

@@ -19,10 +19,10 @@ jobs:
with:
fetch-depth: 0
- name: Install node.js v16
- name: Install node.js v18
uses: actions/setup-node@v3
with:
node-version: 16
node-version: 18
- name: Install dependencies
uses: ./packages/actions/src/yarnCache

18
.gitignore vendored
View File

@@ -1,8 +1,8 @@
# Packages
node_modules/
node_modules
# Log files
logs/
logs
*.log
npm-debug.log*
@@ -15,20 +15,20 @@ pids
.env
# Dist
dist/
dist-docs/
dist
dist-docs
# Miscellaneous
.tmp/
.vscode/*
.tmp
.vscode
!.vscode/extensions.json
!.vscode/settings.json
.idea/
.idea
.DS_Store
.turbo
tsconfig.tsbuildinfo
coverage/
out/
coverage
out
# yarn
.pnp.*

View File

@@ -1,5 +1,5 @@
{
"*": "prettier --ignore-unknown --write",
"{src/**,__tests__/**}.{mjs,js,cjs,ts,tsx,astro}": "eslint --ext .mjs,.js,.cjs,.ts,.tsx,.astro --fix",
"{src/**,__tests__/**}.{mjs,js,cjs,ts,tsx}": "eslint --ext .mjs,.js,.cjs,.ts,.tsx --fix",
"src/**.ts": "vitest related --run --config ../../vitest.config.ts"
}

1
.prettierignore Normal file
View File

@@ -0,0 +1 @@
CODEOWNERS

View File

@@ -9,7 +9,6 @@
"christian-kohler.npm-intellisense",
"christian-kohler.path-intellisense",
"antfu.unocss",
"astro-build.astro-vscode",
"unifiedjs.vscode-mdx"
]
}

View File

@@ -1,7 +1,6 @@
{
"eslint.workingDirectories": [{ "pattern": "./apps/*" }, { "pattern": "./packages/*" }],
"eslint.validate": ["javascript", "javascriptreact", "astro", "typescript", "typescriptreact"],
"prettier.documentSelectors": ["**/*.astro"],
"eslint.validate": ["javascript", "javascriptreact", "typescript", "typescriptreact"],
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {

View File

@@ -0,0 +1,18 @@
diff --git a/package.json b/package.json
index fc35658a40f9ba3e3513c459ba9f4f6e1b3f59f5..bc35eda66f270c95ba52e721cb6976fd61622c58 100644
--- a/package.json
+++ b/package.json
@@ -26,11 +26,13 @@
},
"exports": {
".": {
+ "types": "./dist/index.d.ts",
"node": "./dist/index.js",
"default": "./browser/index.js"
},
"./package.json": "./package.json",
"./util": {
+ "types": "./dist/util.d.ts",
"node": "./dist/util.js",
"default": "./browser/dist/util.js"
}

View File

@@ -215,7 +215,8 @@ module.exports = {
await c({ workspace: e, report: t, destination: u });
});
}
await i.execUtils.pipevp('docker', ['build', ...this.args, '-f', s, '.'], {
const h = this.buildKit ? ['buildx', 'build'] : ['build'];
await i.execUtils.pipevp('docker', [...h, ...this.args, '-f', s, '.'], {
cwd: o,
strict: !0,
stdin: this.context.stdin,
@@ -241,6 +242,7 @@ module.exports = {
'yarn docker build --copy secret.key --copy config.json @foo/bar',
],
['Install production dependencies only', 'yarn docker build --production @foo/bar'],
['Build a Docker image using BuildKit', 'yarn docker build --buildkit @foo/bar'],
],
})),
d([r.Command.String()], f.prototype, 'workspaceName', void 0),
@@ -248,6 +250,7 @@ module.exports = {
d([r.Command.String('-f,--file')], f.prototype, 'dockerFilePath', void 0),
d([r.Command.Array('--copy')], f.prototype, 'copyFiles', void 0),
d([r.Command.Boolean('--production')], f.prototype, 'production', void 0),
d([r.Command.Boolean('--buildkit')], f.prototype, 'buildKit', void 0),
d([r.Command.Path('docker', 'build')], f.prototype, 'execute', null);
const u = { commands: [f] };
plugin = e;

File diff suppressed because one or more lines are too long

View File

@@ -1,5 +1,24 @@
logFilters:
# MISSING_PEER_DEPENDENCY
- code: YN0002
level: discard
# FETCH_NOT_CACHED
- code: YN0013
level: discard
# NODE_GYP_INJECTED
- code: YN0032
level: discard
# INCOMPATIBLE_PEER_DEPENDENCY
- code: YN0060
level: discard
nodeLinker: node-modules
packageExtensions:
'@storybook/core-common@*':
dependencies:
'@storybook/react-vite': 7.0.8
plugins:
- path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs
spec: '@yarnpkg/plugin-interactive-tools'
@@ -10,4 +29,4 @@ plugins:
- path: .yarn/plugins/@yarnpkg/plugin-docker-build.cjs
spec: 'https://github.com/Dcard/yarn-plugins/releases/latest/download/plugin-docker-build.js'
yarnPath: .yarn/releases/yarn-3.5.0.cjs
yarnPath: .yarn/releases/yarn-3.5.1.cjs

View File

@@ -13,6 +13,7 @@
</p>
<p>
<a href="https://vercel.com/?utm_source=discordjs&utm_campaign=oss"><img src="https://raw.githubusercontent.com/discordjs/discord.js/main/.github/powered-by-vercel.svg" alt="Vercel" /></a>
<a href="https://www.cloudflare.com"><img src="https://raw.githubusercontent.com/discordjs/discord.js/main/.github/powered-by-workers.png" alt="Cloudflare Workers" height="44" /></a>
</p>
</div>

View File

@@ -88,9 +88,44 @@
*
* DEFAULT VALUE: no overrideTsconfig section
*/
// "overrideTsconfig": {
// . . .
// }
"overrideTsconfig": {
// Type Checking
"allowUnreachableCode": false,
"allowUnusedLabels": false,
"exactOptionalPropertyTypes": true,
"noFallthroughCasesInSwitch": true,
"noImplicitOverride": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"strict": true,
"useUnknownInCatchVariables": true,
"noUncheckedIndexedAccess": true,
// Modules
"module": "ESNext",
"moduleResolution": "node",
"resolveJsonModule": true,
// Emit
"declaration": true,
"declarationMap": true,
"importHelpers": true,
"inlineSources": true,
"newLine": "lf",
"noEmitHelpers": true,
"outDir": "dist",
"removeComments": false,
"sourceMap": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
// Language and Environment
"experimentalDecorators": true,
"lib": ["ESNext"],
"target": "ES2021",
"useDefineForClassFields": true
}
/**
* This option causes the compiler to be invoked with the --skipLibCheck option. This option is not recommended
* and may cause API Extractor to produce incomplete or incorrect declarations, but it may be required when
@@ -181,7 +216,7 @@
/**
* (REQUIRED) Whether to generate the .d.ts rollup file.
*/
"enabled": false
"enabled": true,
/**
* Specifies the output path for a .d.ts rollup file to be generated without any trimming.
@@ -195,7 +230,7 @@
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: "<projectFolder>/dist/<unscopedPackageName>.d.ts"
*/
// "untrimmedFilePath": "<projectFolder>/dist/<unscopedPackageName>.d.ts",
"untrimmedFilePath": "<projectFolder>/dist-docs/index.d.ts"
/**
* Specifies the output path for a .d.ts rollup file to be generated with trimming for an "alpha" release.

1
apps/guide/.eslintignore Normal file
View File

@@ -0,0 +1 @@
next-env.d.ts

View File

@@ -1,5 +1,5 @@
{
"extends": ["../../.eslintrc.json", "neon/react", "neon/next", "neon/edge", "neon/prettier"],
"extends": ["../../.eslintrc.json", "neon/react", "neon/next", "neon/edge", "@unocss", "neon/prettier"],
"settings": {
"react": {
"version": "detect"

21
apps/guide/.gitignore vendored
View File

@@ -1,8 +1,8 @@
# Packages
node_modules/
node_modules
# Log files
logs/
logs
*.log
npm-debug.log*
@@ -16,18 +16,13 @@ pids
.env*.local
# Dist
dist/
typings/
.cache/
build/
.contentlayer
.next
public/searchIndex
src/styles/unocss.css
.next/
# Miscellaneous
.tmp/
coverage/
.vercel
public/searchIndex
.tmp
.vscode
lighthouse-results/
.contentlayer
lighthouse-results

View File

@@ -1,15 +1,7 @@
# Autogenerated
CHANGELOG.md
.contentlayer
.next
.turbo
dist/
docs/**/*
!docs/index.yml
!docs/README.md
coverage/
.cache
build/
.vscode
coverage
src/styles/unocss.css
api/
.next/
.vercel/
.cache/
next-env.d.ts

View File

@@ -1,7 +1 @@
module.exports = {
...require('../../.prettierrc.json'),
plugins: [
'prettier-plugin-tailwindcss', // MUST come last
],
pluginSearchDirs: false,
};
module.exports = require('../../.prettierrc.json');

View File

@@ -10,6 +10,7 @@
</p>
<p>
<a href="https://vercel.com/?utm_source=discordjs&utm_campaign=oss"><img src="https://raw.githubusercontent.com/discordjs/discord.js/main/.github/powered-by-vercel.svg" alt="Vercel" /></a>
<a href="https://www.cloudflare.com"><img src="https://raw.githubusercontent.com/discordjs/discord.js/main/.github/powered-by-workers.png" alt="Cloudflare Workers" height="44" /></a>
</p>
</div>

View File

@@ -1,11 +1,12 @@
import { remarkCodeHike } from '@code-hike/mdx';
import { defineDocumentType, makeSource } from 'contentlayer/source-files';
// import { type Node, toString } from 'hast-util-to-string';
// import { h } from 'hastscript';
// import { escape } from 'html-escaper';
// import rehypeAutolinkHeadings from 'rehype-autolink-headings';
import { type Node, toString } from 'hast-util-to-string';
import { h } from 'hastscript';
import { escape } from 'html-escaper';
import rehypeAutolinkHeadings from 'rehype-autolink-headings';
import rehypeSlug from 'rehype-slug';
import remarkGfm from 'remark-gfm';
import codeHikeThemeDarkPlus from './src/styles/code-hike-theme-dark-plus.json';
export const Content = defineDocumentType(() => ({
name: 'Content',
@@ -16,85 +17,78 @@ export const Content = defineDocumentType(() => ({
type: 'string',
required: true,
},
summary: {
type: 'string',
},
image: {
category: {
type: 'string',
required: true,
},
},
computedFields: {
slug: {
type: 'string',
resolve: (doc) => doc._raw.flattenedPath,
// eslint-disable-next-line unicorn/prefer-string-replace-all
resolve: (doc) => doc._raw.flattenedPath.replace(/\d+-/g, ''),
},
url: {
type: 'string',
resolve: (post) => `/posts/${post._raw.flattenedPath}`,
// eslint-disable-next-line unicorn/prefer-string-replace-all
resolve: (doc) => `/guide/${doc._raw.flattenedPath.replace(/\d+-/g, '')}`,
},
},
}));
// const LinkIcon = h(
// 'svg',
// {
// width: '1rem',
// height: '1rem',
// viewBox: '0 0 24 24',
// fill: 'none',
// stroke: 'currentColor',
// strokeWidth: '2',
// strokeLinecap: 'round',
// strokeLinejoin: 'round',
// },
// h('path', {
// // eslint-disable-next-line id-length
// d: 'M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71',
// }),
// h('path', {
// // eslint-disable-next-line id-length
// d: 'M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71',
// }),
// );
const LinkIcon = h(
'svg',
{
width: '1.25rem',
height: '1.25rem',
viewBox: '0 0 24 24',
fill: 'none',
stroke: 'currentColor',
strokeWidth: '2',
strokeLinecap: 'round',
strokeLinejoin: 'round',
},
h('path', {
// eslint-disable-next-line id-length
d: 'M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71',
}),
h('path', {
// eslint-disable-next-line id-length
d: 'M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71',
}),
);
// const createSROnlyLabel = (text: any) => {
// const node = h('span.sr-only', `Section titled ${escape(text)}`);
// node.properties!['is:raw'] = true;
// return node;
// };
const createSROnlyLabel = (text: any) => {
return h('span', { class: 'sr-only' }, `Section titled ${escape(text)}`);
};
export default makeSource({
contentDirPath: 'src/content',
documentTypes: [Content],
mdx: {
remarkPlugins: [remarkGfm, [remarkCodeHike, { theme: 'css-variables', lineNumbers: true }]],
remarkPlugins: [remarkGfm, [remarkCodeHike, { theme: codeHikeThemeDarkPlus, lineNumbers: true }]],
rehypePlugins: [
rehypeSlug,
// [
// rehypeAutolinkHeadings,
// {
// properties: {
// class:
// 'relative inline-flex w-6 h-6 place-items-center place-content-center outline-0 text-black dark:text-white ml-2',
// },
// behavior: 'after',
// group: async ({ tagName }: { tagName: string }) =>
// h('div', {
// class: `[&>*]:inline-block [&>h1]:m-0 [&>h2]:m-0 [&>h3]:m-0 [&>h4]:m-0 level-${tagName}`,
// tabIndex: -1,
// }),
// content: (heading: Node) => [
// h(
// `span.anchor-icon`,
// {
// ariaHidden: 'true',
// },
// LinkIcon,
// ),
// createSROnlyLabel(toString(heading)),
// ],
// },
// ],
[
rehypeAutolinkHeadings,
{
properties: {
class:
'relative inline-flex place-items-center place-content-center outline-none text-black dark:text-white pr-2 -ml-8 opacity-0 group-hover:opacity-100',
},
behavior: 'prepend',
content: (heading: Node) => [
h(
`span.anchor-icon`,
{
ariaHidden: 'true',
},
LinkIcon,
),
createSROnlyLabel(toString(heading)),
],
},
],
],
},
});

View File

@@ -1,7 +1,7 @@
// import { fileURLToPath } from 'node:url';
/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable @typescript-eslint/no-require-imports */
// import bundleAnalyzer from '@next/bundle-analyzer';
// import { withContentlayer } from 'next-contentlayer';
const { fileURLToPath } = require('node:url');
const bundleAnalyzer = require('@next/bundle-analyzer');
const { withContentlayer } = require('next-contentlayer');
@@ -9,19 +9,11 @@ const withBundleAnalyzer = bundleAnalyzer({
enabled: process.env.ANALYZE === 'true',
});
module.exports = withContentlayer(
withBundleAnalyzer({
module.exports = withBundleAnalyzer(
withContentlayer({
reactStrictMode: true,
eslint: {
ignoreDuringBuilds: true,
},
// Until Next.js fixes their type issues
typescript: {
ignoreBuildErrors: true,
},
experimental: {
appDir: true,
fallbackNodePolyfills: false,
},
images: {
dangerouslyAllowSVG: true,

View File

@@ -7,15 +7,15 @@
"test": "vitest run",
"test:lighthouse": "lighthouse http://localhost:3000 --output-path=./lighthouse-results",
"build:local": "yarn build:prod",
"build:prod": "yarn workspaces foreach -ptR run build && yarn build:css && yarn build:next",
"build:prod": "yarn build:css && yarn build:next",
"build:next": "next build",
"build:css": "yarn generate:css",
"build:analyze": "cross-env-shell ANALYZE=true yarn build:prod",
"build:analyze": "cross-env ANALYZE=true yarn build:prod",
"preview": "next start",
"dev": "concurrently 'yarn dev:css' 'yarn dev:next'",
"dev:next": "next dev",
"dev:css": "yarn generate:css --watch",
"generate:css": "unocss 'src/**/*.tsx' '../../packages/ui/src/lib/components/**/*.tsx' --out-file ./src/styles/unocss.css --config ../../unocss.config.ts",
"generate:css": "unocss 'src/**/*.tsx' 'contentlayer.config.ts' '../../packages/ui/src/lib/components/**/*.tsx' --out-file ./src/styles/unocss.css --config ../../unocss.config.ts",
"lint": "prettier --check . && cross-env TIMING=1 eslint src --ext .mjs,.js,.cjs,.ts,.tsx --format=pretty",
"format": "prettier --write . && cross-env TIMING=1 eslint src --ext .mjs,.js,.cjs,.ts,.tsx --fix --format=pretty",
"fmt": "yarn format"
@@ -36,65 +36,63 @@
],
"repository": {
"type": "git",
"url": "https://github.com/discordjs/discord.js.git"
"url": "https://github.com/discordjs/discord.js.git",
"directory": "apps/guide"
},
"bugs": {
"url": "https://github.com/discordjs/discord.js/issues"
},
"homepage": "https://discord.js.org",
"dependencies": {
"@code-hike/mdx": "^0.7.5-next.0",
"@code-hike/mdx": "^0.8.3",
"@discordjs/ui": "workspace:^",
"@react-icons/all-files": "^4.1.0",
"@vercel/analytics": "^0.1.11",
"@vercel/edge-config": "^0.1.5",
"@vercel/og": "^0.5.0",
"ariakit": "^2.0.0-next.43",
"@vercel/analytics": "^1.0.1",
"@vercel/edge-config": "^0.1.9",
"@vercel/og": "^0.5.4",
"ariakit": "^2.0.0-next.44",
"cmdk": "^0.2.0",
"contentlayer": "^0.3.1",
"next": "^13.2.4",
"next-contentlayer": "^0.3.1",
"contentlayer": "^0.3.2",
"next": "^13.4.0",
"next-contentlayer": "^0.3.2",
"next-themes": "^0.2.1",
"react": "^18.2.0",
"react-custom-scrollbars-2": "^4.5.0",
"react-dom": "^18.2.0",
"react-icons": "^4.8.0",
"react-use": "^17.4.0",
"rehype-autolink-headings": "^6.1.1",
"rehype-ignore": "^1.0.4",
"rehype-raw": "^6.1.1",
"rehype-slug": "^5.1.0",
"remark-gfm": "^3.0.1",
"sharp": "^0.32.0"
"sharp": "^0.32.1"
},
"devDependencies": {
"@next/bundle-analyzer": "^13.2.4",
"@next/bundle-analyzer": "^13.4.0",
"@testing-library/react": "^14.0.0",
"@testing-library/user-event": "^14.4.3",
"@types/node": "18.15.11",
"@types/react": "^18.0.31",
"@types/react-dom": "^18.0.11",
"@unocss/cli": "^0.50.6",
"@unocss/reset": "^0.50.6",
"@vitejs/plugin-react": "^3.1.0",
"@vitest/coverage-c8": "^0.29.8",
"@types/html-escaper": "^3.0.0",
"@types/node": "18.16.4",
"@types/react": "^18.2.5",
"@types/react-dom": "^18.2.3",
"@unocss/cli": "^0.51.8",
"@unocss/eslint-config": "^0.51.8",
"@unocss/reset": "^0.51.8",
"@vitejs/plugin-react": "^4.0.0",
"@vitest/coverage-c8": "^0.31.0",
"concurrently": "^8.0.1",
"cross-env": "^7.0.3",
"eslint": "^8.37.0",
"eslint-config-neon": "^0.1.41",
"eslint": "^8.39.0",
"eslint-config-neon": "^0.1.46",
"eslint-formatter-pretty": "^5.0.0",
"happy-dom": "^8.9.0",
"happy-dom": "^9.10.9",
"hast-util-to-string": "^2.0.0",
"hastscript": "^7.2.0",
"html-escaper": "^3.0.3",
"lighthouse": "^10.1.0",
"prettier": "^2.8.7",
"prettier-plugin-astro": "^0.8.0",
"prettier-plugin-tailwindcss": "^0.2.6",
"typescript": "^5.0.3",
"unocss": "^0.50.6",
"vercel": "^28.18.3",
"vitest": "^0.29.8"
"lighthouse": "^10.2.0",
"prettier": "^2.8.8",
"turbo": "^1.9.4-canary.9",
"typescript": "^5.0.4",
"unocss": "^0.51.8",
"vercel": "^29.1.1",
"vitest": "^0.31.0"
},
"engines": {
"node": ">=18.13.0"

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 164 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

View File

@@ -4,7 +4,7 @@ export default function Error({ error }: { error: Error }) {
console.error(error);
return (
<div className="mx-auto flex h-full max-w-lg flex-col place-content-center place-items-center gap-8 px-8 py-16 lg:px-6 lg:py-0">
<div className="mx-auto max-w-lg min-h-screen flex flex-col place-content-center place-items-center gap-8 px-8 py-16 lg:px-6 lg:py-0">
<h1 className="text-[9rem] font-black leading-none md:text-[12rem]">500</h1>
<h2 className="text-[2rem] md:text-[3rem]">Error.</h2>
</div>

View File

@@ -8,10 +8,10 @@ export default function GlobalError({ error }: { error: Error }) {
return (
<html className={inter.variable} lang="en" suppressHydrationWarning>
<body className="dark:bg-dark-800 bg-light-600">
<body className="bg-light-600 dark:bg-dark-600 dark:text-light-900">
<Providers>
<main className="mx-auto h-screen max-w-2xl">
<div className="mx-auto flex h-screen max-w-lg flex-col place-content-center place-items-center gap-8 px-8 py-16 lg:px-6 lg:py-0">
<main className="mx-auto max-w-2xl min-h-screen">
<div className="mx-auto max-w-lg min-h-screen flex flex-col place-content-center place-items-center gap-8 px-8 py-16 lg:px-6 lg:py-0">
<h1 className="text-[9rem] font-black leading-none md:text-[12rem]">500</h1>
<h2 className="text-[2rem] md:text-[3rem]">Error.</h2>
</div>

View File

@@ -0,0 +1 @@
export { default } from '~/app/not-found';

View File

@@ -3,7 +3,7 @@ import { notFound } from 'next/navigation';
import { Mdx } from '~/components/Mdx';
export async function generateStaticParams() {
return allContents.map((content) => ({ slug: content.slug }));
return allContents.map((content) => ({ slug: [content.slug] }));
}
export default function Page({ params }: { params: { slug: string[] } }) {
@@ -14,7 +14,7 @@ export default function Page({ params }: { params: { slug: string[] } }) {
}
return (
<article className="prose mx-auto max-w-4xl py-8">
<article className="max-w-none prose">
<Mdx code={content?.body.code ?? ''} />
</article>
);

View File

@@ -0,0 +1,25 @@
import type { PropsWithChildren } from 'react';
import { Providers } from './providers';
import Footer from '~/components/Footer';
import Header from '~/components/Header';
import { Nav } from '~/components/Nav';
export default function Layout({ children }: PropsWithChildren) {
return (
<Providers>
<main className="mx-auto max-w-7xl px-4 lg:max-w-full">
<Header />
<div className="relative top-6 mx-auto max-w-7xl gap-6 lg:max-w-full lg:flex">
<div className="lg:sticky lg:top-23 lg:h-[calc(100vh_-_105px)]">
<Nav />
</div>
<div className="mx-auto max-w-5xl min-w-xs w-full pb-10">
{children}
<Footer />
</div>
</div>
</main>
</Providers>
);
}

View File

@@ -0,0 +1,3 @@
export default function Page() {
return null;
}

View File

@@ -0,0 +1,8 @@
'use client';
import type { PropsWithChildren } from 'react';
import { NavProvider } from '~/contexts/nav';
export function Providers({ children }: PropsWithChildren) {
return <NavProvider>{children}</NavProvider>;
}

View File

@@ -1,5 +1,5 @@
import { Analytics } from '@vercel/analytics/react';
import type { Metadata } from 'next/types';
import type { Metadata } from 'next';
import type { PropsWithChildren } from 'react';
import { Providers } from './providers';
import { DESCRIPTION } from '~/util/constants';
@@ -44,7 +44,10 @@ export const metadata: Metadata = {
manifest: '/site.webmanifest',
themeColor: '#5865f2',
themeColor: [
{ media: '(prefers-color-scheme: light)', color: '#f1f3f5' },
{ media: '(prefers-color-scheme: dark)', color: '#181818' },
],
colorScheme: 'light dark',
appleWebApp: {
@@ -74,7 +77,7 @@ export const metadata: Metadata = {
export default function RootLayout({ children }: PropsWithChildren) {
return (
<html className={`${inter.variable} ${jetBrainsMono.variable}`} lang="en" suppressHydrationWarning>
<body className="dark:bg-dark-800 bg-light-600">
<body className="bg-light-600 dark:bg-dark-600 dark:text-light-900">
<Providers>{children}</Providers>
<Analytics />
</body>

View File

@@ -1,6 +1,6 @@
export default function Loading() {
return (
<div className="mx-4 flex min-h-screen flex-col items-center justify-center gap-4">
<div className="mx-4 min-h-screen flex flex-col items-center justify-center gap-4">
<svg
className="h-9 w-9 animate-spin text-black dark:text-white"
fill="none"

View File

@@ -2,12 +2,12 @@ import Link from 'next/link';
export default function NotFound() {
return (
<div className="mx-auto flex min-h-screen max-w-lg flex-col place-content-center place-items-center gap-8 px-8 py-16 lg:px-6 lg:py-0">
<div className="mx-auto max-w-lg min-h-screen flex flex-col place-content-center place-items-center gap-8 px-8 py-16 lg:px-6 lg:py-0">
<h1 className="text-[9rem] font-black leading-none md:text-[12rem]">404</h1>
<h2 className="text-[2rem] md:text-[3rem]">Not found.</h2>
<Link
className="bg-blurple focus:ring-width-2 flex h-11 transform-gpu cursor-pointer select-none appearance-none flex-row place-items-center rounded border-0 px-6 text-base font-semibold leading-none text-white no-underline outline-0 focus:ring focus:ring-white active:translate-y-px"
href="/docs/packages"
className="h-11 flex flex-row transform-gpu cursor-pointer select-none appearance-none place-items-center border-0 rounded bg-blurple px-6 text-base font-semibold leading-none text-white no-underline outline-none active:translate-y-px focus:ring focus:ring-width-2 focus:ring-white"
href="/guide"
>
Take me back
</Link>

View File

@@ -1,26 +1,3 @@
import Image from 'next/image';
import vercelLogo from '~/assets/powered-by-vercel.svg';
export default function Page() {
return (
<div className="mx-auto flex min-h-screen max-w-6xl flex-col place-items-center gap-12 px-8 py-16 lg:place-content-center lg:px-8 lg:py-0">
<div className="flex flex-row place-content-center">
<a
className="focus:ring-width-2 focus:ring-blurple rounded outline-0 focus:ring"
href="https://vercel.com/?utm_source=discordjs&utm_campaign=oss"
rel="noopener noreferrer"
target="_blank"
title="Vercel"
>
<Image
alt="Vercel"
blurDataURL="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAABLCAQAAAA1k5H2AAAAi0lEQVR42u3SMQEAAAgDoC251a3gL2SgmfBYBRAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARCAgwWEOSWBnYbKggAAAABJRU5ErkJggg=="
placeholder="blur"
priority
src={vercelLogo}
/>
</a>
</div>
</div>
);
return null;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

View File

@@ -1,3 +1,84 @@
export function DocsLink() {
return null;
import { FiExternalLink } from '@react-icons/all-files/fi/FiExternalLink';
import { BASE_URL, BASE_URL_LEGACY, PACKAGES, VERSION } from '~/util/constants';
interface DocsLinkOptions {
/**
* Whether to apply brackets to the end of the symbol to denote a method.
*
* @remarks Functions automatically infer this.
*/
brackets?: boolean;
/**
* The package.
*
* @defaultValue `'discord.js'`
*/
package?: (typeof PACKAGES)[number];
/**
* The initial documentation class, function, interface etc.
*
* @example `'Client'`
*/
parent?: string;
/**
* Whether to reference a static property.
*
* @remarks
* This should only be used for the https://discord.js.org domain
* as static properties are not identified in the URL.
*/
static?: boolean;
/**
* The symbol belonging to the parent.
*
* @example '`login'`
*/
symbol?: string;
/**
* The type of the {@link DocsLinkOptions.parent}.
*
* @example `'class'`
* @example `'Function'`
*/
type?: string;
}
export function DocsLink({
package: docs = PACKAGES[0],
type,
parent,
symbol,
brackets,
static: staticReference,
}: DocsLinkOptions) {
// In the case of no type and no parent, this will default to the entry point of the respective documentation.
let url = docs === PACKAGES[0] ? `${BASE_URL_LEGACY}/${VERSION}/general/welcome` : `${BASE_URL}/${docs}/stable`;
let text = `${docs === PACKAGES[0] ? '' : '@discordjs/'}${docs}`;
// If there is a type and parent, we need to do some parsing.
if (type && parent) {
const bracketText = brackets || type?.toUpperCase() === 'FUNCTION' ? '()' : '';
// Legacy discord.js documentation parsing.
if (docs === PACKAGES[0]) {
url = `${BASE_URL_LEGACY}/${VERSION}/${type}/${parent}`;
if (symbol) url += `?scrollTo=${symbol}`;
text = `${parent}${symbol ? (symbol.startsWith('s-') ? '.' : '#') : ''}${
// eslint-disable-next-line prefer-named-capture-group
symbol ? `${symbol.replace(/(e|s)-/, '')}` : ''
}${bracketText}`;
} else {
url += `/${parent}:${type}`;
if (symbol) url += `#${symbol}`;
text = `${parent}${symbol ? `${staticReference ? '.' : '#'}${symbol}` : ''}${bracketText}`;
}
}
return (
<a className="inline-flex flex-row place-items-center gap-1" href={url} rel="noopener noreferrer" target="_blank">
{text}
<FiExternalLink size={18} />
</a>
);
}

View File

@@ -1,10 +0,0 @@
import { FiExternalLink } from 'react-icons/fi';
export function ExternalLink({ href, title }: { href: string; title: string }) {
return (
<a className="text-blurple inline-flex place-items-center gap-2 text-sm font-semibold" href={href}>
<p>{title}</p>
<FiExternalLink size={18} />
</a>
);
}

View File

@@ -0,0 +1,100 @@
import Image from 'next/image';
import vercelLogo from '~/assets/powered-by-vercel.svg';
import workersLogo from '~/assets/powered-by-workers.png';
export default function Footer() {
return (
<footer className="md:pl-12 md:pr-12">
<div className="mx-auto max-w-6xl flex flex-col place-items-center gap-12 pt-12 lg:place-content-center">
<div className="w-full flex flex-col place-content-between place-items-center gap-12 md:flex-row md:gap-0">
<div className="flex flex-col gap-4 lg:flex-row">
<a
className="rounded outline-none focus:ring focus:ring-width-2 focus:ring-blurple"
href="https://vercel.com/?utm_source=discordjs&utm_campaign=oss"
rel="external noopener noreferrer"
target="_blank"
title="Vercel"
>
<Image
alt="Vercel"
blurDataURL="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAABLCAQAAAA1k5H2AAAAi0lEQVR42u3SMQEAAAgDoC251a3gL2SgmfBYBRAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARCAgwWEOSWBnYbKggAAAABJRU5ErkJggg=="
height={44}
placeholder="blur"
src={vercelLogo}
width={212}
/>
</a>
<a
className="rounded outline-none focus:ring focus:ring-width-2 focus:ring-blurple"
href="https://www.cloudflare.com"
rel="external noopener noreferrer"
target="_blank"
title="Cloudflare Workers"
>
<Image
alt="Cloudflare"
blurDataURL="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAABLCAQAAAA1k5H2AAAAi0lEQVR42u3SMQEAAAgDoC251a3gL2SgmfBYBRAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARCAgwWEOSWBnYbKggAAAABJRU5ErkJggg=="
height={44}
placeholder="blur"
priority
src={workersLogo}
/>
</a>
</div>
<div className="flex flex-row gap-6 md:gap-12">
<div className="flex flex-col gap-2">
<div className="text-lg font-semibold">Community</div>
<div className="flex flex-col gap-1">
<a
className="rounded outline-none focus:ring focus:ring-width-2 focus:ring-blurple"
href="https://discord.gg/djs"
rel="external noopener noreferrer"
target="_blank"
>
Discord
</a>
<a
className="rounded outline-none focus:ring focus:ring-width-2 focus:ring-blurple"
href="https://github.com/discordjs/discord.js/discussions"
rel="external noopener noreferrer"
target="_blank"
>
GitHub discussions
</a>
</div>
</div>
<div className="flex flex-col gap-2">
<div className="text-lg font-semibold">Project</div>
<div className="flex flex-col gap-1">
<a
className="rounded outline-none focus:ring focus:ring-width-2 focus:ring-blurple"
href="https://github.com/discordjs/discord.js"
rel="external noopener noreferrer"
target="_blank"
>
discord.js
</a>
<a
className="rounded outline-none focus:ring focus:ring-width-2 focus:ring-blurple"
href="https://discord.js.org/docs"
rel="noopener noreferrer"
target="_blank"
>
discord.js documentation
</a>
<a
className="rounded outline-none focus:ring focus:ring-width-2 focus:ring-blurple"
href="https://discord-api-types.dev"
rel="external noopener noreferrer"
target="_blank"
>
discord-api-types
</a>
</div>
</div>
</div>
</div>
</div>
</footer>
);
}

View File

@@ -0,0 +1,9 @@
import type { HTMLAttributes, PropsWithChildren } from 'react';
export function H1({ children, className, ...props }: PropsWithChildren<HTMLAttributes<HTMLHeadingElement>>) {
return (
<h1 className={`group ${className}`} {...props}>
{children}
</h1>
);
}

View File

@@ -0,0 +1,9 @@
import type { HTMLAttributes, PropsWithChildren } from 'react';
export function H2({ children, className, ...props }: PropsWithChildren<HTMLAttributes<HTMLHeadingElement>>) {
return (
<h2 className={`group ${className}`} {...props}>
{children}
</h2>
);
}

View File

@@ -0,0 +1,9 @@
import type { HTMLAttributes, PropsWithChildren } from 'react';
export function H3({ children, className, ...props }: PropsWithChildren<HTMLAttributes<HTMLHeadingElement>>) {
return (
<h3 className={`group ${className}`} {...props}>
{children}
</h3>
);
}

View File

@@ -0,0 +1,9 @@
import type { HTMLAttributes, PropsWithChildren } from 'react';
export function H4({ children, className, ...props }: PropsWithChildren<HTMLAttributes<HTMLHeadingElement>>) {
return (
<h4 className={`group ${className}`} {...props}>
{children}
</h4>
);
}

View File

@@ -0,0 +1,91 @@
'use client';
import { VscGithubInverted } from '@react-icons/all-files/vsc/VscGithubInverted';
import { VscMenu } from '@react-icons/all-files/vsc/VscMenu';
import { Button } from 'ariakit/button';
import dynamic from 'next/dynamic';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { Fragment, useMemo } from 'react';
import { useNav } from '~/contexts/nav';
const ThemeSwitcher = dynamic(async () => import('./ThemeSwitcher'));
export default function Header() {
const pathname = usePathname();
const { setOpened } = useNav();
const pathElements = useMemo(
() =>
pathname
.split('/')
.slice(1)
.map((path, idx, original) => (
<Link
className="rounded outline-none hover:underline focus:ring focus:ring-width-2 focus:ring-blurple"
href={`/${original.slice(0, idx + 1).join('/')}`}
key={`${path}-${idx}`}
>
{path}
</Link>
)),
[pathname],
);
const breadcrumbs = useMemo(
() =>
pathElements.flatMap((el, idx, array) => {
if (idx === 0) {
return (
<Fragment key={`${el.key}-${idx}`}>
<div className="mx-2">/</div>
<div>{el}</div>
<div className="mx-2">/</div>
</Fragment>
);
}
if (idx !== array.length - 1) {
return (
<Fragment key={`${el.key}-${idx}`}>
<div>{el}</div>
<div className="mx-2">/</div>
</Fragment>
);
}
return <div key={`${el.key}-${idx}`}>{el}</div>;
}),
[pathElements],
);
return (
<header className="sticky top-4 z-20 border border-light-900 rounded-md bg-white/75 shadow backdrop-blur-md dark:border-dark-100 dark:bg-dark-600/75">
<div className="block h-16 px-6">
<div className="h-full flex flex-row place-content-between place-items-center gap-8">
<Button
aria-label="Menu"
className="h-6 w-6 flex flex-row transform-gpu cursor-pointer select-none appearance-none place-items-center border-0 rounded bg-transparent p-0 text-sm font-semibold leading-none no-underline outline-none lg:hidden active:translate-y-px focus:ring focus:ring-width-2 focus:ring-blurple"
onClick={() => setOpened((open) => !open)}
>
<VscMenu size={24} />
</Button>
<div className="hidden lg:flex lg:grow lg:flex-row lg:overflow-hidden">{breadcrumbs}</div>
<div className="flex flex-row place-items-center gap-4">
<Button
aria-label="GitHub"
as="a"
className="h-6 w-6 flex flex-row transform-gpu cursor-pointer select-none appearance-none place-items-center border-0 rounded rounded-full bg-transparent p-0 text-sm font-semibold leading-none no-underline outline-none active:translate-y-px focus:ring focus:ring-width-2 focus:ring-blurple"
href="https://github.com/discordjs/discord.js"
rel="external noopener noreferrer"
target="_blank"
>
<VscGithubInverted size={24} />
</Button>
<ThemeSwitcher />
</div>
</div>
</div>
</header>
);
}

View File

@@ -2,6 +2,10 @@
import { Alert, Section, DiscordMessages, DiscordMessage, DiscordMessageEmbed } from '@discordjs/ui';
import { useMDXComponent } from 'next-contentlayer/hooks';
import { H1 } from './H1';
import { H2 } from './H2';
import { H3 } from './H3';
import { H4 } from './H4';
import { DocsLink } from '~/components/DocsLink';
import { ResultingCode } from '~/components/ResultingCode';
@@ -10,7 +14,19 @@ export function Mdx({ code }: { code: string }) {
return (
<Component
components={{ Alert, Section, DiscordMessages, DiscordMessage, DiscordMessageEmbed, DocsLink, ResultingCode }}
components={{
Alert,
Section,
DiscordMessages,
DiscordMessage,
DiscordMessageEmbed,
DocsLink,
ResultingCode,
h1: H1,
h2: H2,
h3: H3,
h4: H4,
}}
/>
);
}

View File

@@ -0,0 +1,30 @@
'use client';
import { Scrollbars } from 'react-custom-scrollbars-2';
import { Sidebar } from './Sidebar';
import { useNav } from '~/contexts/nav';
export function Nav() {
const { opened } = useNav();
return (
<nav
className={`dark:bg-dark-600/75 dark:border-dark-100 border-light-900 top-22 fixed bottom-4 left-4 right-4 z-20 mx-auto max-w-5xl rounded-md border bg-white/75 shadow backdrop-blur-md ${
opened ? 'block' : 'hidden'
} lg:min-w-xs lg:sticky lg:block lg:h-full lg:w-full lg:max-w-xs`}
>
<Scrollbars
autoHide
className="[&>div]:overscroll-none"
hideTracksWhenNotNeeded
renderThumbVertical={(props) => <div {...props} className="z-30 rounded bg-light-900 dark:bg-dark-100" />}
renderTrackVertical={(props) => (
<div {...props} className="absolute bottom-0.5 right-0.5 top-0.5 z-30 w-1.5 rounded" />
)}
universal
>
<Sidebar />
</Scrollbars>
</nav>
);
}

View File

@@ -1,70 +0,0 @@
import { Button } from 'ariakit/button';
import { useState, useEffect } from 'react';
import { FiCommand } from 'react-icons/fi';
import { VscColorMode, VscGithubInverted, VscMenu, VscSearch } from 'react-icons/vsc';
import { useMedia } from 'react-use';
import { Sidebar } from './Sidebar.jsx';
import type { MDXPage } from './SidebarItems.jsx';
export function Navbar({ pages }: { pages?: MDXPage[] | undefined }) {
const matches = useMedia('(min-width: 992px)', false);
const [opened, setOpened] = useState(false);
useEffect(() => {
if (matches) {
setOpened(false);
}
}, [matches]);
return (
<>
<header className="dark:bg-dark-400 dark:border-dark-100 bg-light-600 border-light-800 fixed left-0 top-0 z-20 w-full border-b">
<div className="block h-16 px-6">
<div className="flex h-full flex-row place-content-between place-items-center">
<Button
aria-label="Menu"
className="focus:ring-width-2 focus:ring-blurple flex h-6 w-6 transform-gpu cursor-pointer select-none appearance-none place-items-center rounded border-0 bg-transparent p-0 text-sm font-semibold leading-none no-underline outline-0 focus:ring active:translate-y-px lg:hidden"
onClick={() => setOpened((open) => !open)}
>
<VscMenu size={24} />
</Button>
<div className="hidden md:flex md:flex-row">Placeholder</div>
<div className="flex flex-row place-items-center gap-4">
<Button
as="div"
className="dark:bg-dark-800 focus:ring-width-2 focus:ring-blurple rounded bg-white px-4 py-2.5 outline-0 focus:ring"
// onClick={() => dialog?.toggle()}
>
<div className="flex flex-row place-items-center gap-4">
<VscSearch size={18} />
<span className="opacity-65">Search...</span>
<div className="opacity-65 flex flex-row place-items-center gap-2">
<FiCommand size={18} /> K
</div>
</div>
</Button>
<Button
aria-label="GitHub"
as="a"
className="focus:ring-width-2 focus:ring-blurple flex h-6 w-6 transform-gpu cursor-pointer select-none appearance-none place-items-center rounded rounded-full border-0 bg-transparent p-0 text-sm font-semibold leading-none no-underline outline-0 focus:ring active:translate-y-px"
href="https://github.com/discordjs/discord.js"
rel="noopener noreferrer"
target="_blank"
>
<VscGithubInverted size={24} />
</Button>
<Button
aria-label="Toggle theme"
className="focus:ring-width-2 focus:ring-blurple flex h-6 w-6 transform-gpu cursor-pointer select-none appearance-none place-items-center rounded rounded-full border-0 bg-transparent p-0 text-sm font-semibold leading-none no-underline outline-0 focus:ring active:translate-y-px"
// onClick={() => toggleTheme()}
>
<VscColorMode size={24} />
</Button>
</div>
</div>
</div>
</header>
<Sidebar opened={opened} pages={pages} />
</>
);
}

View File

@@ -1,22 +1,19 @@
import type { MarkdownHeading } from 'astro';
import { useEffect, useMemo, useState } from 'react';
import { useMemo, useState } from 'react';
import { Scrollbars } from 'react-custom-scrollbars-2';
import { VscListSelection } from 'react-icons/vsc';
import { useLocation } from 'react-use';
const LINK_HEIGHT = 30;
const INDICATOR_SIZE = 10;
const INDICATOR_OFFSET = (LINK_HEIGHT - INDICATOR_SIZE) / 2;
export function Outline({ headings }: { headings: MarkdownHeading[] }) {
const state = useLocation();
const [active, setActive] = useState(0);
export function Outline({ headings }: { headings: any[] }) {
// eslint-disable-next-line react/hook-use-state
const [active /* setActive */] = useState(0);
const headingItems = useMemo(
() =>
headings.map((heading, idx) => (
<a
className={`dark:border-dark-100 border-light-800 pl-6.5 focus:ring-width-2 focus:ring-blurple ml-[10px] border-l p-[5px] text-sm outline-0 focus:rounded focus:border-0 focus:ring ${
className={`dark:border-dark-100 border-light-800 pl-6.5 focus:ring-width-2 focus:ring-blurple ml-[10px] border-l p-[5px] text-sm outline-none focus:rounded focus:border-0 focus:ring ${
idx === active
? 'bg-blurple text-white'
: 'dark:hover:bg-dark-200 dark:active:bg-dark-100 hover:bg-light-700 active:bg-light-800'
@@ -32,18 +29,18 @@ export function Outline({ headings }: { headings: MarkdownHeading[] }) {
[headings, active],
);
useEffect(() => {
const idx = headings.findIndex((heading) => heading.slug === state.hash?.slice(1));
if (idx >= 0) {
setActive(idx);
}
}, [state, headings]);
// useEffect(() => {
// const idx = headings.findIndex((heading) => heading.slug === state.hash?.slice(1));
// if (idx >= 0) {
// setActive(idx);
// }
// }, [state, headings]);
return (
<Scrollbars
autoHide
hideTracksWhenNotNeeded
renderThumbVertical={(props) => <div {...props} className="dark:bg-dark-100 bg-light-900 z-30 rounded" />}
renderThumbVertical={(props) => <div {...props} className="z-30 rounded bg-light-900 dark:bg-dark-100" />}
renderTrackVertical={(props) => (
<div {...props} className="absolute bottom-0.5 right-0.5 top-0.5 z-30 w-1.5 rounded" />
)}
@@ -51,13 +48,13 @@ export function Outline({ headings }: { headings: MarkdownHeading[] }) {
>
<div className="flex flex-col break-all p-3 pb-8">
<div className="ml-2 mt-4 flex flex-row gap-2">
<VscListSelection size={25} />
{/* <VscListSelection size={25} /> */}
<span className="font-semibold">Contents</span>
</div>
<div className="ml-2 mt-4 flex flex-col gap-2">
<div className="relative flex flex-col">
<div
className="bg-blurple absolute h-[10px] w-[10px] rounded-full border-2 border-black dark:border-white"
className="absolute h-[10px] w-[10px] border-2 border-black rounded-full bg-blurple dark:border-white"
style={{
left: INDICATOR_SIZE / 2 + 0.5,
transform: `translateY(${active * LINK_HEIGHT + INDICATOR_OFFSET}px)`,

View File

@@ -1,7 +1,7 @@
export function PageButton({ url, title, direction }: { direction: 'next' | 'prev'; title: string; url: string }) {
return (
<a
className="bg-light-600 hover:bg-light-700 active:bg-light-800 dark:bg-dark-600 dark:hover:bg-dark-500 dark:active:bg-dark-400 focus:ring-width-2 focus:ring-blurple flex transform-gpu cursor-pointer select-none appearance-none flex-row flex-col place-items-center gap-2 rounded px-4 py-3 leading-none no-underline outline-0 focus:ring active:translate-y-px"
className="flex flex-row flex-col transform-gpu cursor-pointer select-none appearance-none place-items-center gap-2 rounded bg-light-600 px-4 py-3 leading-none no-underline outline-none active:translate-y-px active:bg-light-800 dark:bg-dark-600 hover:bg-light-700 focus:ring focus:ring-width-2 focus:ring-blurple dark:active:bg-dark-400 dark:hover:bg-dark-500"
href={url}
>
<h3 className="text-md font-semibold">{title}</h3>

View File

@@ -0,0 +1,8 @@
'use client';
import { Section as DJSSection, type SectionOptions } from '@discordjs/ui';
import type { PropsWithChildren } from 'react';
export function Section(options: PropsWithChildren<SectionOptions>) {
return <DJSSection {...options} />;
}

View File

@@ -1,24 +1,62 @@
import { Scrollbars } from 'react-custom-scrollbars-2';
import type { MDXPage } from './SidebarItems.jsx';
'use client';
import { allContents } from 'contentlayer/generated';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { Section } from './Section';
import { useNav } from '~/contexts/nav';
const items = allContents.map((content) => ({
title: content.title,
category: content.category,
slug: content.slug,
href: content.url,
}));
function transformItemsByCategory(allContents: typeof items) {
return allContents.reduce<Record<string, typeof items>>((accumulator: any, content) => {
if (!accumulator[content.category]) {
accumulator[content.category] = [];
}
accumulator[content.category].push(content);
return accumulator;
}, {});
}
const itemsByCategory = transformItemsByCategory(items);
export function Sidebar() {
const pathname = usePathname();
const { setOpened } = useNav();
export function Sidebar({ pages, opened }: { opened: boolean; pages?: MDXPage[] | undefined }) {
return (
<nav
className={`h-[calc(100vh - 65px)] dark:bg-dark-600 dark:border-dark-100 border-light-800 fixed bottom-0 left-0 top-[65px] z-20 w-full border-r bg-white ${
opened ? 'block' : 'hidden'
} lg:w-76 lg:max-w-76 lg:block`}
>
<Scrollbars
autoHide
hideTracksWhenNotNeeded
renderThumbVertical={(props) => <div {...props} className="dark:bg-dark-100 bg-light-900 z-30 rounded" />}
renderTrackVertical={(props) => (
<div {...props} className="absolute bottom-0.5 right-0.5 top-0.5 z-30 w-1.5 rounded" />
)}
universal
>
{pages ?? null}
</Scrollbars>
</nav>
<div className="flex flex-col gap-3 p-3">
{Object.keys(itemsByCategory).map((category, idx) => (
<Section
buttonClassName="bg-light-600 hover:bg-light-700 active:bg-light-800 dark:bg-dark-400 dark:hover:bg-dark-300 dark:active:bg-dark-400 focus:ring-width-2 focus:ring-blurple rounded p-3 outline-none focus:ring"
key={`${category}-${idx}`}
title={category}
>
{itemsByCategory[category]?.map((member, index) => (
<Link
className={`dark:border-dark-100 border-light-800 focus:ring-width-2 focus:ring-blurple ml-5 flex flex-col border-l p-[5px] pl-6 outline-none focus:rounded focus:border-0 focus:ring ${
decodeURIComponent(pathname ?? '') === member.href
? 'bg-blurple text-white'
: 'dark:hover:bg-dark-200 dark:active:bg-dark-100 hover:bg-light-700 active:bg-light-800'
}`}
href={member.href}
key={`${member.title}-${index}`}
onClick={() => setOpened(false)}
title={member.title}
>
<div className="flex flex-row place-items-center gap-2 lg:text-sm">
<span className="truncate">{member.title}</span>
</div>
</Link>
))}
</Section>
))}
</div>
);
}

View File

@@ -1,51 +0,0 @@
import { Section } from '@discordjs/ui';
import type { MDXInstance } from 'astro';
import { useEffect, useMemo, useState } from 'react';
import { useLocation } from 'react-use';
export type MDXPage = MDXInstance<{ category: string; title: string }>;
export function SidebarItems({ pages }: { pages: MDXPage[] }) {
const state = useLocation();
const [active, setActive] = useState<string | undefined>('');
const categories = useMemo(
() =>
pages.reduce<Record<string, MDXPage[]>>((acc, page) => {
if (acc[page.frontmatter.category]) {
acc[page.frontmatter.category]?.push(page);
} else {
acc[page.frontmatter.category] = [page];
}
return acc;
}, {}),
[pages],
);
useEffect(() => {
setActive(state.pathname);
}, [state]);
return Object.keys(categories).map((category, idx) => (
<Section key={`${category}-${idx}`} title={category}>
{categories[category]?.map((member, index) => (
<a
className={`dark:border-dark-100 border-light-800 focus:ring-width-2 focus:ring-blurple ml-5 flex flex-col border-l p-[5px] pl-6 outline-0 focus:rounded focus:border-0 focus:ring ${
(member.url || '/') === active
? 'bg-blurple text-white'
: 'dark:hover:bg-dark-200 dark:active:bg-dark-100 hover:bg-light-700 active:bg-light-800'
}`}
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
href={member.url || '/'}
key={`${member.frontmatter.title}-${index}}`}
title={member.frontmatter.title}
>
<div className="flex flex-row place-items-center gap-2 lg:text-sm">
<span className="truncate">{member.frontmatter.title}</span>
</div>
</a>
)) ?? null}
</Section>
));
}

View File

@@ -0,0 +1,20 @@
'use client';
import { VscColorMode } from '@react-icons/all-files/vsc/VscColorMode';
import { Button } from 'ariakit/button';
import { useTheme } from 'next-themes';
export default function ThemeSwitcher() {
const { resolvedTheme, setTheme } = useTheme();
const toggleTheme = () => setTheme(resolvedTheme === 'light' ? 'dark' : 'light');
return (
<Button
aria-label="Toggle theme"
className="h-6 w-6 flex flex-row transform-gpu cursor-pointer select-none appearance-none place-items-center border-0 rounded rounded-full bg-transparent p-0 text-sm font-semibold leading-none no-underline outline-none active:translate-y-px focus:ring focus:ring-width-2 focus:ring-blurple"
onClick={() => toggleTheme()}
>
<VscColorMode size={24} />
</Button>
);
}

View File

@@ -9,14 +9,13 @@ category: Home
<DiscordMessage
interaction={{
author: {
avatar:
'https://cdn.discordapp.com/guilds/222078108977594368/users/81440962496172032/avatars/c059c5d04d717ea05790f7a6447e4843.webp?size=160',
username: 'Crawl',
avatar: '/assets/old-guide.png',
username: 'discord.js',
},
command: 'upgrade',
command: '/upgrade',
}}
author={{
avatar: 'https://cdn.discordapp.com/avatars/474807795183648809/7f239a0776ff928b2182906a2b3743c9.webp?size=160',
avatar: '/assets/discordjs.png',
bot: true,
username: 'Guide Bot',
time: 'Today at 21:00',
@@ -30,14 +29,11 @@ category: Home
## Site
- Upgraded to [VuePress v2](https://v2.vuepress.vuejs.org/)
- New theme made to match the [discord.js documentation site](https://discord.js.org/)
- Discord message components upgraded to [@discord-message-components/vue](https://github.com/Danktuary/discord-message-components/blob/main/packages/vue/README.md)
- Many fixes in code blocks, grammar, consistency, etc.
We have moved from VuePress to [Next.js](https://nextjs.org/)! The source can be found [here](https://github.com/discordjs/discord.js/tree/main/apps/guide).
## Pages
All content has been updated to use discord.js v14 syntax. The v13 version of the guide can be found at [https://v13.discordjs.guide/](https://v13.discordjs.guide/).
All content has been updated to use discord.js v14 syntax. The v13 version of the guide can be found at https://v13.discordjs.guide.
### New
@@ -54,13 +50,13 @@ All content has been updated to use discord.js v14 syntax. The v13 version of th
- [Voice](/voice/): Rewritten to use the [_`@discordjs/voice`_](https://github.com/discordjs/discord.js/tree/main/packages/voice) package
- [Command handling](/creating-your-bot/command-handling.md/): Updated to use slash commands
- Obsolete sections removed
- _`client.on('message')`_ snippets updated to _`client.on('interactionCreate')`_
- [Message content will become a new privileged intent on August 31, 2022](https://support-dev.discord.com/hc/en-us/articles/4404772028055)
- _`client.on('message')`_ snippets updated to _`client.on(Events.InteractionCreate)`_
- [Message content became a privileged intent on August 31, 2022](https://support-dev.discord.com/hc/articles/4404772028055)
<DiscordMessages rounded>
<DiscordMessage
author={{
avatar: 'https://cdn.discordapp.com/avatars/474807795183648809/7f239a0776ff928b2182906a2b3743c9.webp?size=160',
avatar: '/assets/discordjs.png',
bot: true,
username: 'Guide Bot',
time: 'Today at 21:00',

View File

@@ -0,0 +1,198 @@
---
title: How to contribute
category: Home
---
# How to contribute
Since this guide is made specifically for the discord.js community, we want to be sure to provide the most relevant and up-to-date content. We will, of course, make additions to the current pages and add new ones as we see fit, but fulfilling requests is how we know we're providing content you all want the most.
Requests may be as simple as "add an example to the [frequently asked questions](/popular-topics/faq.html) page", or as elaborate as "add a page regarding [sharding](/sharding/)". We'll do our best to fulfill all requests, as long as they're reasonable.
To make a request, simply head over to [the repository's issue tracker](https://github.com/discordjs/discord.js/issues) and [create a new issue](https://github.com/discordjs/discord.js/issues/new)! Title it appropriately, and let us know exactly what you mean inside the issue description. Make sure that you've looked around the site before making a request; what you want to request might already exist!
<Alert title="Tip" type="success">
Remember that you can always [fork the repository](https://github.com/discordjs/discord.js/fork) and [make a pull
request](https://github.com/discordjs/discord.js/pulls) if you want to add anything to the guide yourself!
</Alert>
We'll also get into some of the more advanced features this guide does below.
## Components
Throughout the guide, you'll see some components from the _`@discordjs/ui`_ package:
- _`Alert`_
- _`Section`_
- _`DiscordMessages`_, _`DiscordMessage`_, and _`DiscordMessageEmbed`_
Check the source of this page to see them in action!
### Alert
This component may take a _`title`_ and a _`type`_ of _`'danger' | 'info' | 'success' | 'warning'`_.
This uses _`title="Alert" type="info"`_:
<Alert title="Alert" type="info">
Use these appropriately!
</Alert>
### Section
<Section title="Expand me!" padding defaultClosed background gutter>
Well, hello there!
Whenever some text does not need to be in the main body, you can put it here.
- _`title`_: The title that'll appear.
- _`padding`_: Adds padding.
- _`dense`_: When _`padding`_ is specified, _`dense`_ could make it appear, well, dense.
- _`defaultClosed`_ Whether the section is closed by default. This one was.
- _`background`_ Adds background to the content.
- _`gutter`_: This adds a very small appealing space between the expansion of the section and its content.
</Section>
### DiscordMessages, DiscordMessage, and DiscordMessageEmbed
<DiscordMessages>
<DiscordMessage
author={{
avatar: '/assets/discordjs.png',
bot: true,
time: 'Today at 21:00',
username: 'Guide Bot',
}}
>
A _`DiscordMessage`_ must be within _`DiscordMessages`_.
</DiscordMessage>
<DiscordMessage
author={{
avatar: '/assets/discordjs.png',
bot: true,
time: 'Today at 21:01',
username: 'Guide Bot',
}}
reply={{
author: {
avatar: '/assets/discordjs.png',
bot: true,
username: 'Guide Bot',
},
content: 'A _`DiscordMessage`_ must be within _`DiscordMessages`_.',
}}
time="21:02"
>
It's much better to see the source code of this page to replicate and learn!
</DiscordMessage>
<DiscordMessage
author={{
avatar: '/assets/discordjs.png',
bot: true,
time: 'Today at 21:02',
username: 'Guide Bot',
}}
>
This message depicts the use of embeds.
<>
<DiscordMessageEmbed
author={{
avatar: '/assets/discordjs.png',
username: 'Guide Bot',
}}
footer={{ content: 'Sometimes, titles just have to be.' }}
title={{ title: 'An amazing title' }}
>
This is a description. You can put a description here. It must be descriptive!
</DiscordMessageEmbed>
<DiscordMessageEmbed
author={{
avatar: '/assets/discordjs.png',
username: 'Guide Bot',
}}
footer={{ content: "When one amazing title just wasn't enough." }}
title={{ title: 'Another amazing title' }}
>
Multiple embeds!
</DiscordMessageEmbed>
</>
</DiscordMessage>
<DiscordMessage
author={{
avatar: '/assets/discordjs.png',
bot: true,
time: 'Today at 21:03',
username: 'Guide Bot',
}}
interaction={{
author: {
avatar: '/assets/discordjs.png',
bot: true,
username: 'Guide Bot',
},
command: '/interaction',
}}
>
Interactions are supported! I definitely used a command.
</DiscordMessage>
<DiscordMessage
author={{
avatar: '/assets/discordjs.png',
bot: true,
color: 'text-red-500',
time: 'Today at 21:04',
username: 'Guide Bot',
}}
reply={{
author: {
avatar: '/assets/snek-bot.jpeg',
bot: true,
verified: true,
color: 'text-blue-500',
username: 'Snek Bot',
},
content: 'You can also have verified bots, like me!',
}}
>
Display colors are supported as well!
</DiscordMessage>
</DiscordMessages>
## Code blocks
We use [Code Hike](https://codehike.org). Here are some example code blocks, which should be easy to grasp and learn upon reading the source code of this page:
<CH.Code>
```ts
const HELLO = 'hello' as const;
console.log(HELLO);
// "ts" is the language of the code block.
```
</CH.Code>
<CH.Code>
```ts fileName
const FILE_NAME = 'fileName' as const;
if (FILE_NAME.includes(' ')) throw new Error('Spaces cannot be used in file names.');
```
```ts anotherFileName
const FILE_NAME_2 = 'anotherFileName' as const;
// Putting code blocks together makes them appear in tabs, just like in your editor.
```
---
```ts requiredName
const FILE_NAME_3 = 'requiredName' as const;
if (!FILE_NAME) throw new Error('There must be a file name to use panels!');
// The --- divider was used to create a panel.
```
</CH.Code>
For more information, be sure to check out the [documentation](https://codehike.org/docs/ch-code).

View File

@@ -0,0 +1,102 @@
---
title: Installing Node.js and discord.js
category: Installations and preparations
---
# Installing Node.js and discord.js
## Installing Node.js
To use discord.js, you'll need to install [Node.js](https://nodejs.org/). discord.js v14 requires Node v16.9.0 or higher.
<Alert title="Tip" type="success">
To check if you already have Node installed on your machine \(e.g., if you're using a VPS\), run _`node -v`_ in your
terminal. If it outputs _`v16.9.0`_ or higher, then you're good to go! Otherwise, continue reading.
</Alert>
On Windows, it's as simple as installing any other program. Download the latest version from [the Node.js website](https://nodejs.org/), open the downloaded file, and follow the steps from the installer.
On macOS, either:
- Download the latest version from [the Node.js website](https://nodejs.org/), open the package installer, and follow the instructions
- Use a package manager like [Homebrew](https://brew.sh/) with the command _`brew install node`_
On Linux, you can consult [this page](https://nodejs.org/en/download/package-manager/) to determine how you should install Node. Native package managers often default to outdated versions of Node, so make sure you follow the recommended approach for your chosen Linux distribution carefully.
## Preparing the essentials
To use discord.js, you'll need to install it via npm \(Node's package manager\). npm comes with every Node installation, so you don't have to worry about installing that. However, before you install anything, you should set up a new project folder.
Navigate to a suitable place on your machine and create a new folder named _`discord-bot`_ (or whatever you want). Next you'll need to open your terminal.
### Opening the terminal
<Alert title="Tip" type="success">
If you use [Visual Studio Code](https://code.visualstudio.com/), you can press <kbd>Ctrl + `</kbd> (backtick) to open
its integrated terminal.
</Alert>
On Windows, either:
- <kbd>Shift + Right-click</kbd> inside your project directory and choose the "Open command window here" option
- Press <kbd>Win + R</kbd> and run _`cmd.exe`_, and then _`cd`_ into your project directory
On macOS, either:
- Open Launchpad or Spotlight and search for "Terminal"
- In your "Applications" folder, under "Utilities", open the Terminal app
On Linux, you can quickly open the terminal with <kbd>Ctrl + Alt + T</kbd>.
With the terminal open, run the _`node -v`_ command to make sure you've successfully installed Node.js. If it outputs _`v16.9.0`_ or higher, great!
### Initiating a project folder
<CH.Code lineNumbers={false}>
```sh npm
npm init; npm pkg set type="module"
```
```sh yarn
yarn init
# You must go into your package.json file and add "type": "module"
```
```sh pnpm
pnpm init; pnpm pkg set type="module"
```
</CH.Code>
This is the next command you'll be running. This command creates a _`package.json`_ file for you, which will keep track of the dependencies your project uses, as well as other info.
This command will ask you a sequence of questionsyou should fill them out as you see fit. If you're not sure of something or want to skip it as a whole, leave it blank and press enter. Setting the package type as _`module`_ tells Node that you'll be writing this project using ESM \(ECMAScript modules\), supporting the latest JavaScript syntax and features.
Once you're done with that, you're ready to install discord.js!
## Installing discord.js
Now that you've installed Node.js and know how to open your console and run commands, you can finally install discord.js! Run the following command in your terminal:
<CH.Code lineNumbers={false}>
```sh npm
npm install discord.js
```
```sh yarn
yarn add discord.js
```
```sh pnpm
pnpm add discord.js
```
</CH.Code>
And that's it! With all the necessities installed, you're almost ready to start coding your bot.
## Installing a linter
While you are coding, it's possible to run into numerous syntax errors or code in an inconsistent style. You should [install a linter](./setting-up-a-linter) to ease these troubles. While code editors generally can point out syntax errors, linters coerce your code into a specific style as defined by the configuration. While this is not required, it is advised.

View File

@@ -0,0 +1,6 @@
---
title: Setting up a linter
category: Installations and preparations
---
TODO: Rewrite. Placeholder page for ordering.

View File

@@ -0,0 +1,61 @@
---
title: Setting up a bot application
category: Installations and preparations
---
# Setting up a bot application
## Creating your bot
Now that you've installed Node, discord.js, and hopefully a linter, you're almost ready to start coding! The next step you need to take is setting up an actual Discord bot application via Discord's website.
It's effortless to create one. The steps you need to take are as follows:
1. Open the [Discord developer portal](https://discord.com/developers/applications) and log into your account.
2. Click on the "New Application" button.
3. Enter a name and confirm the pop-up window by clicking the "Create" button.
You should see a page like this:
![Successfully created application](/assets/create-app.png)
You can edit your application's name, description, and avatar here. Once you've saved your changes, move on by selecting the "Bot" tab in the left pane.
## Your bot's token
<Alert title="Important" type="danger">
This section is critical, so pay close attention. It explains what your bot token is, as well as the security aspects
of it.
</Alert>
On the bot tab, you'll see a section like this:
![Bot application](/assets/bot-user.png)
In this panel, you can give your bot a snazzy avatar, set its username, and make it public or private. Your bot's token will be revealed when you press the "Reset Token" button and confirm. When we ask you to paste your bot's token somewhere, this is the value that you need to put in. If you happen to lose your bot's token at some point, you need to come back to this page and reset your bot's token again which will reveal the new token, invalidating all old ones.
### What is a token, anyway?
A token is essentially your bot's password; it's what your bot uses to login to Discord. With that said, **it is vital that you do not ever share this token with anybody, purposely or accidentally**. If someone does manage to get a hold of your bot's token, they can use your bot as if it were theirs—this means they can perform malicious acts with it.
Tokens look like this: _`NzkyNzE1NDU0MTk2MDg4ODQy.X-hvzA.Ovy4MCQywSkoMRRclStW4xAYK7I`_ (don't worry, we immediately reset this token before even posting it here!). If it's any shorter and looks more like this: _`kxbsDRU5UfAaiO7ar9GFMHSlmTwYaIYn`_, you copied your client secret instead. Make sure to copy the token if you want your bot to work!
### Token leak scenario
Let's imagine that you have a bot on over 1,000 servers, and it took you many, many months of coding and patience to get it on that amount. Your bot's token gets leaked somewhere, and now someone else has it. That person can:
- Spam every server your bot is on;
- DM spam as many users as possible;
- Delete as many channels as possible;
- Kick or ban as many server members as possible;
- Make your bot leave all of the servers it has joined;
All that and much, much more. Sounds pretty terrible, right? So make sure to keep your bot's token as safe as possible!
In the [configuration files](../creating-your-bot/configuration-files) page of the guide, we cover how to safely store your bot's token in a configuration file.
<Alert title="Compromised tokens" type="danger">
If your bot token has been compromised by committing it to a public repository, posting it in discord.js support etc.
or otherwise see your bot's token in danger, return to this page and press "Reset Token". This will invalidate all old
tokens belonging to your bot. Keep in mind that you will need to update your bot's token where you used it before.
</Alert>

View File

@@ -0,0 +1,52 @@
---
title: Adding your bot to servers
category: Installations and preparations
---
# Adding your bot to servers
After you [set up a bot application](./setting-up-a-bot-application), you'll notice that it's not in any servers yet. So how does that work?
Before you're able to see your bot in your own (or other) servers, you'll need to add it by creating and using a unique invite link using your bot application's client id.
## Bot invite links
The basic version of one such link looks like this:
<CH.Code lineNumbers={false}>
```
https://discord.com/api/oauth2/authorize?client_id=123456789012345678&permissions=0&scope=bot%20applications.commands
```
</CH.Code>
The structure of the URL is quite simple:
- _`https://discord.com/api/oauth2/authorize`_ is Discord's standard structure for authorizing an OAuth2 application (such as your bot application) for entry to a Discord server.
- _`client_id=...`_ is to specify _which_ application you want to authorize. You'll need to replace this part with your client's id to create a valid invite link.
- _`permissions=...`_ describes the permissions that your bot will request to be granted by default upon joining the server you are adding it to.
- _`scope=bot%20applications.commands`_ specifies that you want to add this application as a Discord bot, with the ability to create slash commands.
<Alert title="Warning" type="warning">
If you get an error message saying "Bot requires a code grant", head over to your application's settings and disable
the "Require OAuth2 Code Grant" option. You shouldn't enable this option unless you know why you need to.
</Alert>
## Creating and using your invite link
To create an invite link, head back to the [My Apps](https://discord.com/developers/applications/me) page under the "Applications" section, click on your bot application, and open the OAuth2 page.
In the sidebar, you'll find the OAuth2 URL generator. Select the _`bot`_ and _`applications.commands`_ options. Once you select the _`bot`_ option, a list of permissions will appear, allowing you to configure the permissions your bot needs.
Grab the link via the "Copy" button and enter it in your browser. You should see something like this (with your bot's username and avatar):
![Bot Authorization page](/assets/bot-auth-page.png)
Choose the server you want to add it to and click "Authorize". Do note that you'll need the "Manage Server" permission on a server to add your bot there. This should then present you a nice confirmation message:
![Bot authorized](/assets/bot-authorized.png)
Congratulations! You've successfully added your bot to your Discord server. It should show up in your server's member list somewhat like this:
![Bot in server's member list](/assets/bot-in-memberlist.png)

View File

@@ -0,0 +1,132 @@
---
title: Configuration files
category: Creating your bot
---
# Configuration files
Once you [add your bot to a server](../installations-and-preparations/adding-your-bot-to-servers), the next step is to start coding and get it online! Let's start by creating a config file to prepare the necessary values your client will need.
As explained in the ["What is a token, anyway?"](../installations-and-preparations/setting-up-a-bot-application.md#what-is-a-token-anyway) section, your token is essentially your bot's password, and you should protect it as best as possible. This can be done through a _`config.json`_ file or by using environment variables.
Open your application in the [Discord Developer Portal](https://discord.com/developers/applications) and go to the "Bot" page to copy your token.
## Using config.json
Storing data in a _`config.json`_ file is a common way of keeping your sensitive values safe. Create a _`config.json`_ file in your project directory and paste in your token. You can access your token inside other files by importing this file.
<CH.Code lineNumbers={false}>
```json config.json
{
"token": "your-token-goes-here"
}
```
```js index.js
import config from './config.json' assert { type: 'json' };
console.log(config.token);
```
</CH.Code>
<Alert title="Danger" type="danger">
If you're using Git, you should not commit this file and should [ignore it via `.gitignore`](#git-and-gitignore).
</Alert>
## Using environment variables
Environment variables are special values for your environment (e.g., terminal session, Docker container, or environment variable file). You can pass these values into your code's scope so that you can use them.
One way to pass in environment variables is via the command line interface. When starting your app, instead of _`node index.js`_, use _`TOKEN=your-token-goes-here node index.js`_. You can repeat this pattern to expose other values as well.
You can access the set values in your code via the _`process.env`_ global variable, accessible in any file. Note that values passed this way will always be strings and that you might need to parse them to a number, if using them to do calculations.
<CH.Code lineNumbers={false} rows={3}>
```sh Shell
A=123 B=456 DISCORD_TOKEN=your-token-goes-here node index.js
```
```js index.js
console.log(process.env.A);
console.log(process.env.B);
console.log(process.env.DISCORD_TOKEN);
```
</CH.Code>
### Using dotenv
Another common approach is storing these values in a _`.env`_ file. This spares you from always copying your token into the command line. Each line in a _`.env`_ file should hold a _`KEY=value`_ pair.
You can use the [`dotenv` package](https://www.npmjs.com/package/dotenv) for this. Once installed, require and use the package to load your _`.env`_ file and attach the variables to _`process.env`_:
<CH.Code lineNumbers={false}>
```sh npm
npm install dotenv
```
```sh yarn
yarn add dotenv
```
```sh pnpm
pnpm add dotenv
```
</CH.Code>
<CH.Code lineNumbers={false} rows={7}>
```sh .env
A=123
B=456
DISCORD_TOKEN=your-token-goes-here
```
```js index.js
import { config } from 'dotenv';
config();
console.log(process.env.A);
console.log(process.env.B);
console.log(process.env.DISCORD_TOKEN);
```
</CH.Code>
<Alert title="Danger" type="danger">
If you're using Git, you should not commit this file and should [ignore it via `.gitignore`](#git-and-gitignore).
</Alert>
<Alert title="Online editors (Glitch, Heroku, Replit, etc.)" type="info">
While we generally do not recommend using online editors as hosting solutions, but rather invest in a proper virtual private server, these services do offer ways to keep your credentials safe as well! Please see the respective service's documentation and help articles for more information on how to keep sensitive values safe:
- Glitch: [Storing secrets in .env](https://glitch.happyfox.com/kb/article/18)
- Heroku: [Configuration variables](https://devcenter.heroku.com/articles/config-vars)
- Replit: [Secrets and environment variables](https://docs.replit.com/repls/secrets-environment-variables)
</Alert>
## Git and .gitignore
Git is a fantastic tool to keep track of your code changes and allows you to upload progress to services like [GitHub](https://github.com/), [GitLab](https://about.gitlab.com/), or [Bitbucket](https://bitbucket.org/product). While this is super useful to share code with other developers, it also bears the risk of uploading your configuration files with sensitive values!
You can specify files that Git should ignore in its versioning systems with a*`.gitignore`* file. Create a _`.gitignore`_ file in your project directory and add the names of the files and folders you want to ignore:
```
node_modules
.env
config.json
```
<Alert title="Tip" type="success">
Aside from keeping credentials safe, _`node_modules`_ should be included here. Since this directory can be restored based on the entries in your _`package.json`_ and _`package-lock.json`_ files by running _`npm install`_, it does not need to be included in Git.
You can specify quite intricate patterns in _`.gitignore`_ files, check out the [Git documentation on `.gitignore`](https://git-scm.com/docs/gitignore) for more information!
</Alert>

View File

@@ -0,0 +1,60 @@
---
title: Creating the main file
category: Creating your bot
---
# Creating the main file
<Alert title="Tip" type="success">
This page assumes you've already prepared the [configuration files](./configuration-files) from the previous page.
We're using the _`config.json`_ approach, however feel free to substitute your own!
</Alert>
Open your code editor and create a new file. We suggest that you save the file as _`index.js`_, but you may name it whatever you wish.
Here's the base code to get you started:
<CH.Code>
```js
// Require the necessary discord.js classes
import { Client, Events, GatewayIntentBits } from 'discord.js';
import config from './config.json' assert { type: 'json' };
// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
// When the client is ready, run this code (only once)
// We use 'c' for the event parameter to keep it separate from the already defined 'client'
client.once(Events.ClientReady, (c) => {
console.log(`Ready! Logged in as ${c.user.tag}`);
});
// Log in to Discord with your client's token
client.login(config.token);
```
</CH.Code>
This is how you create a client instance for your Discord bot and log in to Discord. The _`GatewayIntentBits.Guilds`_ intents option is necessary for the discord.js client to work as you expect it to, as it ensures that the caches for guilds, channels, and roles are populated and available for internal use.
<Alert title="Tip" type="success">
The term "guild" is used by the Discord API and in discord.js to refer to a Discord server.
</Alert>
Intents also define which events Discord should send to your bot, and you may wish to enable more than just the minimum. You can read more about the other intents on the [Intents topic](../popular-topics/intents).
## Running your application
Open your terminal and run _`node index.js`_ to start the process. If you see "Ready!" after a few seconds, you're good to go! The next step is to start adding [slash commands](./adding-commands) to develop your bot's functionality.
<Alert title="Tip" type="success">
You can open your _`package.json`_ file and edit the _`"main": "index.js"`_ field to point to your main file. You can then run _`node .`_ in your terminal to start the process!
After closing the process with _`Ctrl + C`_, you can press the up arrow on your keyboard to bring up the latest commands you've run. Pressing up and then enter after closing the process is a quick way to start it up again.
</Alert>
#### Resulting code
<ResultingCode path="creating-your-bot/initial-files" />

View File

@@ -0,0 +1,163 @@
---
title: Adding commands
category: Creating your bot
---
# Creating slash commands
Discord allows developers to register [slash commands](https://discord.com/developers/docs/interactions/application-commands), which provide users a first-class way of interacting directly with your application.
Slash commands provide a huge number of benefits over manual message parsing, including:
- Integration with the Discord client interface.
- Automatic command detection and parsing of the associated options/arguments.
- Typed argument inputs for command options, e.g. "String", "User", or "Role".
- Validated or dynamic choices for command options.
- In-channel private responses (ephemeral messages).
- Pop-up form-style inputs for capturing additional information.
...and many more!
<Alert title="Read first!" type="info">
For fully functional slash commands, there are three important pieces of code that need to be written. They are:
1. The individual command files, containing their definitions and functionality.
2. The [command handler](command-handling.html), which dynamically reads the files and executes the commands.
3. The [command deployment script](command-deployment.html), to register your slash commands with Discord so they appear in the interface.
These steps can be done in any order, but **all are required** before the commands are fully functional.
On this page, you'll complete Step 1. Make sure to also complete the other pages linked above!
</Alert>
## Before you continue
Assuming you've followed the guide so far, your project directory should look something like this:
```:no-line-numbers
discord-bot/
├── node_modules
├── config.json
├── index.js
├── package-lock.json
└── package.json
```
## Individual command files
Create a new folder named _`commands`_, which is where you'll store all of your command files.
At a minimum, the definition of a slash command must have a name and a description. Slash command names must be between 1-32 characters and contain no capital letters, spaces, or symbols other than _`-`_ and _`_`_. Using the builder, a simple _`ping`\_ command definition would look like this:
<CH.Code>
```js
/** @type {import('discord.js').RESTPostAPIApplicationCommandsJSONBody} */
export const data = {
name: 'ping',
description: 'Replies with Pong!',
};
```
</CH.Code>
A slash command also requires a function to run when the command is used, to respond to the interaction. Using an interaction response method confirms to Discord that your bot successfully received the interaction, and has responded to the user. Discord enforces this to ensure that all slash commands provide a good user experience (UX). Failing to respond will cause Discord to show that the command failed, even if your bot is performing other actions as a result.
The simplest way to acknowledge and respond to an interaction is the _`interaction.reply()`_ method. Other methods of replying are covered on the [Response methods](../slash-commands/response-methods) page later in this section.
<CH.Code>
```js
/** @param {import('discord.js').CommandInteraction} interaction */
export async function execute(interaction) {
await interaction.reply('Pong!');
}
```
</CH.Code>
<Alert title="@type and @param tags" type="info">
[`@type`](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#type) and
[`@param`](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#param-and-returns) tags allow you
to annotate your code with type information. The tags are not required for your code to run but provide autocomplete
and type information for fields and parameters, which can majorly improve your developer experience when working with
them.
</Alert>
Put these two together by creating a `commands/ping.js` file for your first command. Inside this file, you're going to define and export two items.
- The `data` property, which will provide the command definition shown above for registering to Discord.
- The `execute` method, which will contain the functionality to run from our event handler when the command is used.
The _`export`_ keyword ensures these values can be imported and read by other files; namely the command loader and command deployment scripts mentioned earlier.
<CH.Code>
```js commands/ping.js
/** @type {import('discord.js').RESTPostAPIApplicationCommandsJSONBody} */
export const data = {
name: 'ping',
description: 'Replies with Pong!',
};
/** @param {import('discord.js').CommandInteraction} interaction */
export async function execute(interaction) {
await interaction.reply('Pong!');
}
```
</CH.Code>
<Alert title="Tip" type="success">
[`module.exports`](https://nodejs.org/api/modules.html#modules_module_exports) is how you export data in Node.js so that you can [`require()`](https://nodejs.org/api/modules.html#modules_require_id) it in other files.
If you need to access your client instance from inside a command file, you can access it via `interaction.client`. If you need to access external files, packages, etc., you should `require()` them at the top of the file.
</Alert>
That's it for your basic ping command. Below are examples of two more commands we're going to build upon throughout the guide, so create two more files for these before you continue reading.
<CH.Code>
```js commands/user.js
/** @type {import('discord.js').RESTPostAPIApplicationCommandsJSONBody} */
export const data = {
name: 'user',
description: 'Provides information about the user.',
};
/** @param {import('discord.js').CommandInteraction} interaction */
export async function execute(interaction) {
// interaction.user is the object representing the User who ran the command
// interaction.member is the GuildMember object, which represents the user in the specific guild
await interaction.reply(
`This command was run by ${interaction.user.username}, who joined on ${interaction.member.joinedAt}.`,
);
}
```
```js commands/server.js
/** @type {import('discord.js').RESTPostAPIApplicationCommandsJSONBody} */
export const data = {
name: 'server',
description: 'Provides information about the server.',
};
/** @param {import('discord.js').CommandInteraction} interaction */
export async function execute(interaction) {
// interaction.guild is the object representing the Guild in which the command was run
await interaction.reply(`This server is ${interaction.guild.name} and has
${interaction.guild.memberCount} members.`);
}
```
</CH.Code>
#### Next steps
You can implement additional commands by creating additional files in the _`commands`_ folder, but these three are the ones we're going to use for the examples as we go on. For now let's move on to the code you'll need for command handling, to load the files and respond to incoming interactions.
#### Resulting code
<ResultingCode />

View File

@@ -0,0 +1,297 @@
---
title: Handling command interactions
category: Creating your bot
---
# Command handling
Unless your bot project is small, it's not a very good idea to have a single file with a giant _`if`_/_`else if`_ chain for commands. If you want to implement features into your bot and make your development process a lot less painful, you'll want to implement a command handler. Let's get started on that!
<Alert title="Read first!" type="info">
For fully functional slash commands, there are three important pieces of code that need to be written. They are:
1. The [individual command files](slash-commands), containing their definitions and functionality.
2. The command handler, which dynamically reads the files and executes the commands.
3. The [command deployment script](command-deployment), to register your slash commands with Discord so they appear in the interface.
These steps can be done in any order, but **all are required** before the commands are fully functional.
This page details how to complete **Step 2**. Make sure to also complete the other pages linked above!
</Alert>
## Loading command files
Now that your command files have been created, your bot needs to load these files on startup.
In your _`index.js`_ file, make these additions to the base template:
<CH.Code>
```js JavaScript mark=1:4,9
import { readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { Client, Collection, Events, GatewayIntentBits } from 'discord.js';
import config from './config.json' assert { type: 'json' };
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
const commands = new Collection();
client.once(Events.ClientReady, () => {
console.log('Ready!');
});
```
```ts TypeScript mark=1:11,16:21
import { readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import {
Client,
Collection,
Events,
GatewayIntentBits,
type RESTPostAPIChatInputApplicationCommandsJSONBody,
type ChatInputCommandInteraction,
} from 'discord.js';
import config from './config.json';
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
interface CommandModule {
data: RESTPostAPIChatInputApplicationCommandsJSONBody;
execute(interaction: ChatInputCommandInteraction): Promise<void>;
}
const commands = new Collection<string, CommandModule>();
client.once(Events.ClientReady, () => {
console.log('Ready!');
});
```
</CH.Code>
<Alert title="Tip" type="info">
- The [`fs`](https://nodejs.org/api/fs.html) module is Node's native file system module. _`readdir`_ is used to read
the _`commands`_ directory and identify our command files. - The [`path`](https://nodejs.org/api/path.html) module is
Node's native path utility module. _`join`_ helps construct paths to access files and directories. One of the
advantages of _`path.join`_ is that it automatically detects the operating system and uses the appropriate joiners. -
The [`url`](https://nodejs.org/api/url.html) module provides utilities for URL resolution and parsing.
_`fileURLToPath`_ ensuring a cross-platform valid absolute path string.
- The{' '}
<DocsLink type="class" parent="Collection" /> class extends JavaScript's native
[_`Map`_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) class, and includes
more extensive, useful functionality. _`Collection`_ is used to store and efficiently retrieve commands for execution.
</Alert>
Next, using the modules imported above, dynamically retrieve your command files with a few more additions to the _`index.js`_ file:
<CH.Code>
```js JavaScript focus=3:15
const commands = new Collection();
const commandsPath = fileURLToPath(new URL('commands', import.meta.url));
const commandFiles = await readdir(commandsPath).then((files) => files.filter((file) => file.endsWith('.js')));
for (const file of commandFiles) {
const filePath = join(commandsPath, file);
const command = await import(filePath);
// Set a new item in the Collection with the key as the command name and the value as the exported module
if ('data' in command && 'execute' in command) {
commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
```
```ts TypeScript focus=3:15
const commands = new Collection<string, CommandModule>();
const commandsPath = fileURLToPath(new URL('commands', import.meta.url));
const commandFiles = await readdir(commandsPath).then((files) => files.filter((file) => file.endsWith('.js')));
for (const file of commandFiles) {
const filePath = join(commandsPath, file);
const command = await import(filePath);
// Set a new item in the Collection with the key as the command name and the value as the exported module
if ('data' in command && 'execute' in command) {
commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
```
</CH.Code>
First, [url.fileURLToPath()](https://nodejs.org/api/url.html) helps to construct a path to the _`commands`_ directory. The [fs.readdir()](https://nodejs.org/api/fs.html#fspromisesreaddirpath-options) method then reads the path to the directory and returns a Promise which resolves to an array of all the file names it contains, currently _`['ping.js', 'server.js', 'user.js']`_. To ensure only command files get processed, _`Array.filter()`_ removes any non-JavaScript files from the array.
With the correct files identified, the last step is to loop over the array and dynamically set each command into the _`commands`_ Collection. For each file being loaded, check that it has at least the _`data`_ and _`execute`_ properties. This helps to prevent errors resulting from loading empty, unfinished or otherwise incorrect command files while you're still developing.
## Receiving command interactions
Every slash command is an _`interaction`_, so to respond to a command, you need to create a listener for the <DocsLink type="class" parent="Client" symbol="e-interactionCreate" /> event that will execute code when your application receives an interaction. Place the code below in the _`index.js`_ file you created earlier.
<CH.Code>
```js
client.on(Events.InteractionCreate, (interaction) => {
console.log(interaction);
});
```
</CH.Code>
Not every interaction is a slash command (e.g. _`MessageComponent`_ interactions). Make sure to only handle slash commands in this function by making use of the <DocsLink type="class" parent="BaseInteraction" symbol="isChatInputCommand" brackets /> method to exit the handler if another type is encountered. This method also provides type guarding for TypeScript users, narrowing the type from _`BaseInteraction`_ to <DocsLink type="class" parent="ChatInputCommandInteraction" />.
<CH.Code>
```js focus=2
client.on(Events.InteractionCreate, (interaction) => {
if (!interaction.isChatInputCommand()) return;
console.log(interaction);
});
```
</CH.Code>
## Executing commands
When your bot receives a <DocsLink type="class" parent="Client" symbol="e-interactionCreate" /> event, the interaction object contains all the information you need to dynamically retrieve and execute your commands!
Let's take a look at the _`ping`_ command again. Note the _`execute()`_ function that will reply to the interaction with "Pong!".
<CH.Code>
```js
export const data = {
name: 'ping',
description: 'Replies with Pong!',
};
export async function execute(interaction) {
await interaction.reply('Pong!');
}
```
</CH.Code>
First, you need to get the matching command from the _`commands`_ Collection based on the _`interaction.commandName`_. If no matching command is found, log an error to the console and ignore the event.
With the right command identified, all that's left to do is call the command's _`.execute()`_ method and pass in the _`interaction`_ variable as its argument. Note that the event listener has been made _`async`_, allowing Promises to be awaited. In case something goes wrong and the Promise rejects, catch and log any error to the console.
<CH.Code>
```js focus=4:20
// focus[37:42]
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand()) return;
const command = commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
if (interaction.replied || interaction.deferred) {
await interaction.followUp({ content: 'There was an error while executing this command!', ephemeral: true });
} else {
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
}
});
```
</CH.Code>
## Command categories
So far, all of your command files are in a single _`commands`_ folder. This is fine at first, but as your project grows, the number of files in the _`commands`_ folder will too. Keeping track of that many files can be a little tough. To make this a little easier, you can categorize your commands and put them in subfolders inside the _`commands`_ folder. You will have to make a few changes to your existing code in _`index.js`_ for this to work out.
If you've been following along, your project structure should look something like this:
![Project structure before sorting](/assets/before-sorting.png)
After moving your commands into subfolders, it will look something like this:
![Project structure after sorting](/assets/after-sorting.png)
<Alert title="Warning" type="warning">
Make sure you put every command file you have inside one of the new subfolders. Leaving a command file directly under
the _`commands`_ folder will create problems.
</Alert>
It is not necessary to name your subfolders exactly like we have named them here. You can create any number of subfolders and name them whatever you want. Although, it is a good practice to name them according to the type of commands stored inside them.
Back in your _`index.js`_ file, where the code to [dynamically read command files](#loading-command-files) is, use the same pattern to read the subfolder directories, and then require each command inside them.
<CH.Code>
```js JavaScript focus=3:7,19
const commands = new Collection();
const foldersPath = fileURLToPath(new URL('commands', import.meta.url));
const commandFolders = await readdir(foldersPath);
for (const folder of commandFolders) {
const commandsPath = join(foldersPath, folder);
const commandFiles = await readdir(commandsPath).then((files) => files.filter((file) => file.endsWith('.js')));
for (const file of commandFiles) {
const filePath = join(commandsPath, file);
const command = await import(filePath);
// Set a new item in the Collection with the key as the command name and the value as the exported module
if ('data' in command && 'execute' in command) {
commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
}
```
```ts Typescript mark=3:7,19
const commands = new Collection<string, CommandModule>();
const foldersPath = fileURLToPath(new URL('commands', import.meta.url));
const commandFolders = await readdir(foldersPath);
for (const folder of commandFolders) {
const commandsPath = join(foldersPath, folder);
const commandFiles = await readdir(commandsPath).then((files) => files.filter((file) => file.endsWith('.js')));
for (const file of commandFiles) {
const filePath = join(commandsPath, file);
const command = await import(filePath);
// Set a new item in the Collection with the key as the command name and the value as the exported module
if ('data' in command && 'execute' in command) {
commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
}
```
</CH.Code>
That's it! When creating new files for commands, make sure you create them inside one of the subfolders (or a new one) in the _`commands`_ folder.
#### Next steps
Your command files are now loaded into your bot, and the event listener is prepared and ready to respond. In the next section, we cover the final step - a command deployment script you'll need to register your commands so they appear in the Discord client.
#### Resulting code
<ResultingCode />
It also includes some bonus commands!

View File

@@ -0,0 +1,155 @@
---
title: Registering slash commands
category: Creating your bot
---
# Registering slash commands
<Alert title="Read first!" type="info">
For fully functional slash commands, you need three important pieces of code:
1. The [individual command files](slash-commands), containing their definitions and functionality.
2. The [command handler](command-handling), which dynamically reads the files and executes the commands.
3. The command deployment script, to register your slash commands with Discord so they appear in the interface.
These steps can be done in any order, but **all are required** before the commands are fully functional.
This page details how to complete **Step 3**. Make sure to also complete the other pages linked above!
</Alert>
## Command registration
Slash commands can be registered in two ways; in one specific guild, or for every guild the bot is in. We're going to look at single-guild registration first, as this is a good way to develop and test your commands before a global deployment.
Your application will need the _`applications.commands`_ scope authorized in a guild for any of its slash commands to appear, and to be able to register them in a specific guild without error.
Slash commands only need to be registered once, and updated when the definition (description, options etc) is changed. As there is a daily limit on command creations, it's not necessary nor desirable to connect a whole client to the gateway or do this on every _`ClientReady`_ event. As such, a standalone script using the lighter REST manager is preferred.
This script is intended to be run separately, only when you need to make changes to your slash command **definitions** - you're free to modify parts such as the execute function as much as you like without redeployment.
### Guild commands
Create a _`deploy-commands.js`_ file in your project directory. This file will be used to register and update the slash commands for your bot application.
Add two more properties to your _`config.json`_ file, which we'll need in the deployment script:
- _`clientId`_: Your application's client id ([Discord Developer Portal](https://discord.com/developers/applications) > "General Information" > application id)
- _`guildId`_: Your development server's id ([Enable developer mode](https://support.discord.com/hc/en-us/articles/206346498) > Right-click the server title > "Copy Server ID")
<CH.Code lineNumbers={false}>
```json
{
"token": "your-token-goes-here",
"clientId": "your-application-id-goes-here",
"guildId": "your-server-id-goes-here"
}
```
</CH.Code>
With these defined, you can use the deployment script below:
<CH.Code>
```js deploy-commands.js
import { REST, Routes } from 'discord.js';
import { readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import config from './config.json' assert { type: 'json' };
const { clientId, guildId, token } = config;
const commands = [];
// Grab all the command files from the commands directory you created earlier
const foldersPath = fileURLToPath(new URL('commands', import.meta.url));
const commandFolders = await readdir(foldersPath);
for (const folder of commandFolders) {
// Grab all the command files from the commands directory you created earlier
const commandsPath = join(foldersPath, folder);
const commandFiles = await readdir(commandsPath).then((files) => files.filter((file) => file.endsWith('.js')));
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) {
const filePath = join(commandsPath, file);
const command = await import(filePath);
if ('data' in command && 'execute' in command) {
commands.push(command.data.toJSON());
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
}
// Construct and prepare an instance of the REST module
const rest = new REST().setToken(token);
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
// The put method is used to fully refresh all commands in the guild with the current set
const data = await rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands });
console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) {
// And of course, make sure you catch and log any errors!
console.error(error);
}
```
</CH.Code>
Once you fill in these values, run _`node deploy-commands.js`_ in your project directory to register your commands to the guild specified. If you see the success message, check for the commands in the server by typing _`/`_! If all goes well, you should be able to run them and see your bot's response in Discord!
### Global commands
Global application commands will be available in all the guilds your application has the _`applications.commands`_ scope authorized in, and in direct messages by default.
To deploy global commands, you can use the same script from the [guild commands](#guild-commands) section and simply adjust the route in the script to _`.applicationCommands(clientId)`_
Test
<CH.Code rows="focus">
```js focus=5
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
// The put method is used to fully refresh all commands in the guild with the current set
const data = await rest.put(Routes.applicationCommands(clientId), { body: commands });
console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) {
// And of course, make sure you catch and log any errors!
console.error(error);
}
```
</CH.Code>
### Where to deploy
<Alert title="Tip" type="success">
Guild-based deployment of commands is best suited for development and testing in your own personal server. Once you're satisfied that it's ready, deploy the command globally to publish it to all guilds that your bot is in.
You may wish to have a separate application and token in the Discord Dev Portal for your dev application, to avoid duplication between your guild-based commands and the global deployment.
</Alert>
#### Further reading
You've successfully sent a response to a slash command! However, this is only the most basic of command event and response functionality. Much more is available to enhance the user experience including:
- applying this same dynamic, modular handling approach to events with an [Event handler](./event-handling).
- utilising the different [Response methods](../slash-commands/response-methods) that can be used for slash commands.
- expanding on these examples with additional validated option types in [Advanced command creation](../slash-commands/advanced-creation).
- adding formatted [Embeds](../popular-topics/embeds) to your responses.
- enhancing the command functionality with [Buttons](../interactions/buttons) and [Select Menus](../interactions/select-menus).
- prompting the user for more information with [Modals](../interactions/modals).
#### Resulting code
<ResultingCode path="creating-your-bot/command-deployment" />

View File

@@ -0,0 +1,219 @@
---
title: Event handling
category: Creating your bot
---
# Event handling
Node.js uses an event-driven architecture, making it possible to execute code when a specific event occurs. The discord.js library takes full advantage of this. You can visit the <DocsLink type="class" parent="Client" /> documentation to see the full list of events.
<Alert title="Tip" type="success">
This page assumes you've followed the guide up to this point, and created your _`index.js`_ and individual slash
commands according to those pages.
</Alert>
At this point, your `index.js` file has code for loading commands, and listeners for two events: `ClientReady` and `InteractionCreate`.
<CH.Code>
```js Commands
const commands = new Collection();
const foldersPath = fileURLToPath(new URL('commands', import.meta.url));
const commandFolders = await readdir(foldersPath);
for (const folder of commandFolders) {
const commandsPath = join(foldersPath, folder);
const commandFiles = await readdir(commandsPath).then((files) => files.filter((file) => file.endsWith('.js')));
for (const file of commandFiles) {
const filePath = join(commandsPath, file);
const command = await import(filePath);
// Set a new item in the Collection with the key as the command name and the value as the exported module
if ('data' in command && 'execute' in command) {
commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
}
```
```js ClientReady
client.once(Events.ClientReady, (c) => {
console.log(`Ready! Logged in as ${c.user.tag}`);
});
```
```js InteractionCreate
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand()) return;
const command = commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(`Error executing ${interaction.commandName}`);
console.error(error);
}
});
```
</CH.Code>
Currently, all of this code is in the _`index.js`_ file. <DocsLink type="class" parent="Client" symbol="e-ready" /> emits once when the _`Client`_ becomes ready for use, and <DocsLink type="class" parent="Client" symbol="e-interactionCreate" /> emits whenever an interaction is received.
Moving the event listener code into individual files is simple, and we'll be taking a similar approach to the [command handler](./handling-command-interactions).
## Individual event files
Your project directory should look something like this:
```
discord-bot/
├── commands/
├── node_modules/
├── config.json
├── deploy-commands.js
├── index.js
├── package-lock.json
└── package.json
```
Create an _`events`_ folder in the same directory. You can then move the code from your event listeners in _`index.js`_ to separate files: _`events/ready.js`_ and _`events/interactionCreate.js`_. The _`InteractionCreate`_ event is responsible for command handling, so the command loading code will move here too.
<CH.Code>
```js events/interactionCreate.js
import { readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { Collection, Events } from 'discord.js';
const commands = new Collection();
const foldersPath = fileURLToPath(new URL('commands', import.meta.url));
const commandFolders = await readdir(foldersPath);
for (const folder of commandFolders) {
const commandsPath = join(foldersPath, folder);
const commandFiles = await readdir(commandsPath).then((files) => files.filter((file) => file.endsWith('.js')));
for (const file of commandFiles) {
const filePath = join(commandsPath, file);
const command = await import(filePath);
// Set a new item in the Collection with the key as the command name and the value as the exported module
if ('data' in command && 'execute' in command) {
commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
}
export const data = {
name: Events.InteractionCreate,
};
export async function execute(interaction) {
if (!interaction.isChatInputCommand()) return;
const command = commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(`Error executing ${interaction.commandName}`);
console.error(error);
}
}
```
```js events/ready.js
import { Events } from 'discord.js';
export const data = {
name: Events.ClientReady,
once = true,
};
export async function execute(client) {
console.log(`Ready! Logged in as ${client.user.tag}`);
}
```
```js index.js
import { readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { Client, GatewayIntentBits } from 'discord.js';
import config from './config.json' assert { type: 'json' };
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.login(config.token);
```
</CH.Code>
The _`name`_ property states which event this file is for, and the _`once`_ property holds a boolean value that specifies if the event should run only once. You don't need to specify this in _`interactionCreate.js`_ as the default behavior will be to run on every event instance. The _`execute`_ function holds your event logic, which will be called by the event handler whenever the event emits.
## Reading event files
Next, let's write the code for dynamically retrieving all the event files in the _`events`_ folder. We'll be taking a similar approach to our [command handler](./handling-command-interactions). Place the new code highlighted below in your _`index.js`_.
_`fs.readdir()`_ combined with _`array.filter()`_ returns an array of all the file names in the given directory and filters for only _`.js`_ files, i.e. _`['ready.js', 'interactionCreate.js']`_.
<CH.Code>
```js focus=9:20
import { readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { Client, GatewayIntentBits } from 'discord.js';
import config from './config.json' assert { type: 'json' };
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
const eventsPath = fileURLToPath(new URL('events', import.meta.url));
const eventFiles = await readdir(eventsPath).then((files) => files.filter((file) => file.endsWith('.js')));
for (const file of eventFiles) {
const filePath = join(eventsPath, file);
const event = await import(filePath);
if (event.data.once) {
client.once(event.data.name, (...args) => event.execute(...args));
} else {
client.on(event.data.name, (...args) => event.execute(...args));
}
}
client.login(config.token);
```
</CH.Code>
You'll notice the code looks very similar to the command loading above it - read the files in the events folder and load each one individually.
The <DocsLink type="class" parent="Client" /> class in discord.js extends the [`EventEmitter`](https://nodejs.org/api/events.html#events_class_eventemitter) class. Therefore, the _`client`_ object exposes the [`.on()`](https://nodejs.org/api/events.html#events_emitter_on_eventname_listener) and [`.once()`](https://nodejs.org/api/events.html#events_emitter_once_eventname_listener) methods that you can use to register event listeners. These methods take two arguments: the event name and a callback function. These are defined in your separate event files as _`name`_ and _`execute`_.
The callback function passed takes argument(s) returned by its respective event, collects them in an _`args`_ array using the _`...`_ [rest parameter syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters), then calls _`event.execute()`_ while passing in the _`args`_ array using the _`...`_ [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). They are used here because different events in discord.js have different numbers of arguments. The rest parameter collects these variable number of arguments into a single array, and the spread syntax then takes these elements and passes them to the _`execute`_ function.
After this, listening for other events is as easy as creating a new file in the _`events`_ folder. The event handler will automatically retrieve and register it whenever you restart your bot.
<Alert title="Tip" type="success">
In most cases, you can access your _`client`_ instance in other files by obtaining it from one of the other discord.js
structures, e.g. _`interaction.client`_ in the _`InteractionCreate`_ event. You do not need to manually pass it to
your events.
</Alert>
## Resulting code
<ResultingCode />

View File

@@ -0,0 +1,496 @@
---
title: Frequently asked questions
category: Popular topics
---
# Frequently asked questions
## Legend
- _`client`_ is a placeholder for the <DocsLink type="class" parent="Client" /> object:
_`const client = new Client({ intents: [GatewayIntentBits.Guilds] });`_.
- _`interaction`_ is a placeholder for the <DocsLink type="class" parent="BaseInteraction" />:
_`client.on(Events.InteractionCreate, interaction => { ... });`_.
- _`guild`_ is a placeholder for the <DocsLink type="class" parent="Guild" /> object:
_`interaction.guild`_ or _`client.guilds.cache.get('id')`_
- _`voiceChannel`_ is a placeholder for the <DocsLink type="class" parent="VoiceChannel" />:
_`interaction.member.voice.channel`_.
For a more detailed explanation of the notations commonly used in this guide, the docs, and the support server, see [here](/additional-info/notation.md).
## Administrative
### How do I ban a user?
<CH.Code>
```js
const user = interaction.options.getUser('target');
await guild.members.ban(user);
```
</CH.Code>
### How do I unban a user?
<CH.Code>
```js
const user = interaction.options.getUser('target');
await guild.members.unban(user);
```
</CH.Code>
<Alert title="Tip" type="info">
Discord validates and resolves user ids for users not on the server in user slash command options. To retrieve and use
the full structure from the resulting interaction, you can use the{' '}
<DocsLink type="class" parent="CommandInteractionOptionResolver" symbol="getUser" brackets /> method.
</Alert>
### How do I kick a guild member?
<CH.Code>
```js
const member = interaction.options.getMember('target');
await member.kick();
```
</CH.Code>
### How do I timeout a guild member?
<CH.Code>
```js
const member = interaction.options.getMember('target');
await member.timeout(60_000); // Timeout for one minute
```
</CH.Code>
<Alert title="Tip" type="info">
Timeout durations are measured by the millisecond. The maximum timeout duration you can set is 28 days. To remove a
timeout set on a member, pass _`null`_ instead of a timeout duration.
</Alert>
### How do I add a role to a guild member?
<CH.Code>
```js
const role = interaction.options.getRole('role');
const member = interaction.options.getMember('target');
await member.roles.add(role);
```
</CH.Code>
### How do I check if a guild member has a specific role?
<CH.Code>
```js
const role = interaction.options.getRole('role');
const member = interaction.options.getMember('target');
if (member.roles.cache.has(role.id) {
// ...
}
```
</CH.Code>
### How do I limit a command to a single user?
<CH.Code>
```js
if (interaction.user.id === 'id') {
// ...
}
```
</CH.Code>
## Bot Configuration and Utility
### How do I set my bot's username?
<CH.Code>
```js
await client.user.setUsername('username');
```
</CH.Code>
### How do I set my bot's avatar?
<CH.Code>
```js
await client.user.setAvatar('URL or path');
```
</CH.Code>
### How do I set my playing status?
<CH.Code>
```js
client.user.setActivity('activity');
```
</CH.Code>
### How do I set my status to "Watching/Listening to/Competing in ..."?
<CH.Code>
```js
import { ActivityType } from 'discord.js';
client.user.setActivity('activity', { type: ActivityType.Watching });
client.user.setActivity('activity', { type: ActivityType.Listening });
client.user.setActivity('activity', { type: ActivityType.Competing });
```
</CH.Code>
<Alert title="Tip" type="info">
If you would like to set your activity upon startup, you can use the{' '}
<DocsLink type="typedef" parent="ClientOptions" /> object to set the appropriate
<DocsLink type="typedef" parent="PresenceData" />.
</Alert>
### How do I make my bot display online/idle/dnd/invisible?
<CH.Code>
```js
client.user.setStatus('online');
client.user.setStatus('idle');
client.user.setStatus('dnd');
client.user.setStatus('invisible');
```
</CH.Code>
### How do I set both status and activity in one go?
<CH.Code>
```js
client.user.setPresence({ activities: [{ name: 'activity' }], status: 'idle' });
```
</CH.Code>
## Miscellaneous
### How do I send a message to a specific channel?
<CH.Code>
```js
const channel = client.channels.cache.get('id');
await channel.send('content');
```
</CH.Code>
### How do I create a post in a forum channel?
<Alert title="Tip" type="info">
Currently, the only way to get tag ids is programmatically through{' '}
<DocsLink type="class" parent="ForumChannel" symbol="availableTags" />.
</Alert>
<CH.Code>
```js
const channel = client.channels.cache.get('id');
await channel.threads.create({
name: 'Post name',
message: { content: 'Message content' },
appliedTags: ['tagId', 'anotherTagId'],
});
```
</CH.Code>
### How do I DM a specific user?
<CH.Code>
```js
await client.users.send('id', 'content');
```
</CH.Code>
<Alert title="Tip" type="info">
If you want to send a direct message to the user who sent the interaction, you can use _`interaction.user.send()`_.
</Alert>
### How do I mention a specific user in a message?
<CH.Code>
```js
const user = interaction.options.getUser('target');
await interaction.reply(`Hi, ${user}.`);
await interaction.followUp(`Hi, <@${user.id}>.`);
```
</CH.Code>
<Alert title="Tip" type="info">
Mentions in embeds may resolve correctly in embed titles, descriptions and field values but will never notify the
user. Other areas do not support mentions at all.
</Alert>
### How do I control which users and/or roles are mentioned in a message?
Controlling which mentions will send a ping is done via the _`allowedMentions`_ option, which replaces _`disableMentions`_.
This can be set as a default in <DocsLink type="typedef" parent="ClientOptions" />, and controlled per-message sent by your bot.
<CH.Code>
```js
new Client({ allowedMentions: { parse: ['users', 'roles'] } });
```
</CH.Code>
Even more control can be achieved by listing specific _`users`_ or _`roles`_ to be mentioned by id, e.g.:
<CH.Code>
```js
await channel.send({
content: '<@123456789012345678> <@987654321098765432> <@&102938475665748392>',
allowedMentions: { users: ['123456789012345678'], roles: ['102938475665748392'] },
});
```
</CH.Code>
### How do I prompt the user for additional input?
<CH.Code>
```js
await interaction.reply('Please enter more input.');
const filter = (m) => interaction.user.id === m.author.id;
try {
const messages = await interaction.channel.awaitMessages({ filter, time: 60000, max: 1, errors: ['time'] });
await interaction.followUp(`You've entered: ${messages.first().content}`);
} catch {
await interaction.followUp('You did not enter any input!');
}
```
</CH.Code>
<Alert title="Tip" type="info">
If you want to learn more about this syntax or other types of collectors, check out [this dedicated guide page for
collectors](/popular-topics/collectors.md)!
</Alert>
### How do I block a user from using my bot?
<CH.Code>
```js
const blockedUsers = ['id1', 'id2'];
client.on(Events.InteractionCreate, (interaction) => {
if (blockedUsers.includes(interaction.user.id)) return;
});
```
</CH.Code>
<Alert title="Tip" type="info">
You do not need to have a constant local variable like _`blockedUsers`_ above. If you have a database system that you
use to store ids of blocked users, you can query the database instead.
</Alert>
<CH.Code>
```js
client.on(Events.InteractionCreate, async (interaction) => {
const blockedUsers = await database.query('SELECT user_id FROM blocked_users;');
if (blockedUsers.includes(interaction.user.id)) return;
});
```
</CH.Code>
Note that this is just a showcase of how you could do such a check.
### How do I react to the message my bot sent?
<CH.Code>
```js
const sentMessage = await interaction.channel.send('My message to react to.');
// Unicode emoji
await sentMessage.react('👍');
// Custom emoji
await sentMessage.react('123456789012345678');
await sentMessage.react('<emoji:123456789012345678>');
await sentMessage.react('<a:emoji:123456789012345678>');
await sentMessage.react('emoji:123456789012345678');
await sentMessage.react('a:emoji:123456789012345678');
```
</CH.Code>
<Alert title="Tip" type="info">
If you want to learn more about reactions, check out [this dedicated guide on
reactions](/popular-topics/reactions.md)!
</Alert>
### How do I restart my bot with a command?
<CH.Code>
```js
process.exit();
```
</CH.Code>
<Alert title="Warning" type="warning">
_`process.exit()`_ will only kill your Node process, but when using [PM2](https://pm2.keymetrics.io/), it will restart
the process whenever it gets killed. You can read our guide on PM2 [here](/improving-dev-environment/pm2.md).
</Alert>
### What is the difference between a User and a GuildMember?
A User represents a global Discord user, and a GuildMember represents a Discord user on a specific server. That means only GuildMembers can have permissions, roles, and nicknames, for example, because all of these things are server-bound information that could be different on each server that the user is in.
### How do I find all online members of a guild?
<CH.Code>
```js
// First use guild.members.fetch to make sure all members are cached
const fetchedMembers = await guild.members.fetch({ withPresences: true });
const totalOnline = fetchedMembers.filter((member) => member.presence?.status === 'online');
// Now you have a collection with all online member objects in the totalOnline variable
console.log(`There are currently ${totalOnline.size} members online in this guild!`);
```
</CH.Code>
<Alert title="Warning" type="warning">
This only works correctly if you have the _`GuildPresences`_ intent enabled for your application and client. If you
want to learn more about intents, check out [this dedicated guide on intents](/popular-topics/intents.md)!
</Alert>
### How do I check which role was added/removed and for which member?
<CH.Code>
```js
// Start by declaring a guildMemberUpdate listener
// This code should be placed outside of any other listener callbacks to prevent listener nesting
client.on(Events.GuildMemberUpdate, (oldMember, newMember) => {
// If the role(s) are present on the old member object but no longer on the new one (i.e role(s) were removed)
const removedRoles = oldMember.roles.cache.filter((role) => !newMember.roles.cache.has(role.id));
if (removedRoles.size > 0) {
console.log(`The roles ${removedRoles.map((r) => r.name)} were removed from ${oldMember.displayName}.`);
}
// If the role(s) are present on the new member object but are not on the old one (i.e role(s) were added)
const addedRoles = newMember.roles.cache.filter((role) => !oldMember.roles.cache.has(role.id));
if (addedRoles.size > 0) {
console.log(`The roles ${addedRoles.map((r) => r.name)} were added to ${oldMember.displayName}.`);
}
});
```
</CH.Code>
### How do I check the bot's ping?
There are two common measurements for bot pings. The first, **websocket heartbeat**, is the average interval of a regularly sent signal indicating the healthy operation of the websocket connection the library receives events over:
<CH.Code>
```js
await interaction.reply(`Websocket heartbeat: ${client.ws.ping}ms.`);
```
</CH.Code>
<Alert title="Tip" type="info">
If you're using [sharding](/sharding/), a specific shard's heartbeat can be found on the WebSocketShard instance,
accessible at _`client.ws.shards.get(id).ping`_.
</Alert>
The second, **Roundtrip Latency**, describes the amount of time a full API roundtrip (from the creation of the command message to the creation of the response message) takes. You then edit the response to the respective value to avoid needing to send yet another message:
<CH.Code>
```js
const sent = await interaction.reply({ content: 'Pinging...', fetchReply: true });
await interaction.editReply(`Roundtrip latency: ${sent.createdTimestamp - interaction.createdTimestamp}ms`);
```
</CH.Code>
### Why do some emojis behave weirdly?
If you've tried using [the usual method of retrieving unicode emojis](./reactions.md#unicode-emojis), you may have noticed that some characters don't provide the expected results. Here's a short snippet that'll help with that issue. You can toss this into a file of its own and use it anywhere you need! Alternatively feel free to simply copy-paste the characters from below:
<CH.Code>
```js index.js
import { emojiCharacters } from './emojiCharacters.js';
console.log(emojiCharacters.a); // 🇦
console.log(emojiCharacters[10]); // 🔟
console.log(emojiCharacters['!']); // ❗
```
{/* prettier-ignore */}
```js emojiCharacters.js
export const emojiCharacters = {
a: '🇦', b: '🇧', c: '🇨', d: '🇩',
e: '🇪', f: '🇫', g: '🇬', h: '🇭',
i: '🇮', j: '🇯', k: '🇰', l: '🇱',
m: '🇲', n: '🇳', o: '🇴', p: '🇵',
q: '🇶', r: '🇷', s: '🇸', t: '🇹',
u: '🇺', v: '🇻', w: '🇼', x: '🇽',
y: '🇾', z: '🇿', 0: '0⃣', 1: '1⃣',
2: '2⃣', 3: '3⃣', 4: '4⃣', 5: '5⃣',
6: '6⃣', 7: '7⃣', 8: '8⃣', 9: '9⃣',
10: '🔟', '#': '#️⃣', '*': '*️⃣',
'!': '❗', '?': '❓',
};
```
</CH.Code>
<Alert title="Tip" type="info">
You can use the <kbd>⌃ Control</kbd> <kbd>⌘ Command</kbd> <kbd>Space</kbd> keyboard shortcut to open up an emoji picker that can be used for quick, easy access to all the Unicode emojis available to you.
On Windows, the shortcut is <kbd>⊞</kbd> <kbd>.</kbd>.
</Alert>

View File

@@ -0,0 +1,165 @@
---
title: Audit logs
category: Popular topics
---
# Audit logs
## A Quick Background
Audit logs are an excellent moderation tool offered by Discord to know what happened in a server and usually by whom. Making use of audit logs requires the _`ViewAuditLog`_ permission. Audit logs may be fetched on a server, or they may be received via the gateway event <DocsLink type="class" parent="Client" symbol="e-guildAuditLogEntryCreate"/> which requires the _`GuildModeration`_ intent.
There are quite a few cases where you may use audit logs. This guide will limit itself to the most common use cases. Feel free to consult the [relevant Discord API page](https://discord.com/developers/docs/resources/audit-log) for more information.
Keep in mind that these examples explore a straightforward case and are by no means exhaustive. Their purpose is to teach you how audit logs work, and expansion of these examples is likely needed to suit your specific use case.
## Fetching Audit Logs
Let's start by glancing at the <DocsLink type="class" parent="Guild" symbol="fetchAuditLogs" brackets /> method and how to work with it. Like many discord.js methods, it returns a [Promise](../additional-info/understanding-async-await) containing the <DocsLink type="class" parent="GuildAuditLogs"/> object. This object has one property, _`entries`_, which holds a [Collection](../additional-info/collections) of <DocsLink type="class" parent="GuildAuditLogsEntry"/> objects, and consequently, the information you want to retrieve.
Here is the most basic fetch to look at some entries.
<CH.Code>
```js
const fetchedLogs = await guild.fetchAuditLogs();
const firstEntry = fetchedLogs.entries.first();
```
</CH.Code>
Simple, right? Now, let's look at utilizing its options:
<CH.Code>
```js
import { AuditLogEvent } from 'discord.js';
const fetchedLogs = await guild.fetchAuditLogs({
type: AuditLogEvent.InviteCreate,
limit: 1,
});
const firstEntry = fetchedLogs.entries.first();
```
</CH.Code>
This will return the first entry where an invite was created. You used _`limit: 1`_ here to specify only one entry.
## Receiving Audit Logs
Audit logs may be received via the gateway event <DocsLink type="class" parent="Client" symbol="e-guildAuditLogEntryCreate"/>.
This is the best way to receive audit logs if you want to monitor them. As soon as an audit log entry is created,
your application will receive an instance of this event. A common use case is to find out _who_ did the action that
caused the audit log event to happen.
### Who deleted a message?
One of the most common use cases for audit logs is understanding who deleted a message in a Discord server. If a user deleted another user's message, you can find out who did that as soon as you receive the corresponding audit log event.
<Alert title="Tip" type="info">
Messages deleted by their author or bots (excluding bulk deletes) do not generate audit log entries.
</Alert>
<CH.Code>
```js JavaScript
import { AuditLogEvent, Events } from 'discord.js';
client.on(Events.GuildAuditLogEntryCreate, async (auditLog) => {
// Define your variables.
// The extra information here will be the channel.
const { action, extra: channel, executorId, targetId } = auditLog;
// Check only for deleted messages.
if (action !== AuditLogEvent.MessageDelete) return;
// Ensure the executor is cached.
const executor = await client.users.fetch(executorId);
// Ensure the author whose message was deleted is cached.
const target = await client.users.fetch(targetId);
// Log the output.
console.log(`A message by ${target.tag} was deleted by ${executor.tag} in ${channel}.`);
});
```
```ts TypeScript
import { AuditLogEvent, Events } from 'discord.js';
client.on(Events.GuildAuditLogEntryCreate, async (auditLog) => {
// Define your variables.
// The extra information here will be the channel.
const { action, extra: channel, executorId, targetId } = auditLog;
// Check only for deleted messages.
if (action !== AuditLogEvent.MessageDelete) return;
// Ensure the executor is cached. The id definitely exists.
const executor = await client.users.fetch(executorId!);
// Ensure the author whose message was deleted is cached. The id definitely exists.
const target = await client.users.fetch(targetId!);
// Log the output.
console.log(`A message by ${target.tag} was deleted by ${executor.tag} in ${channel}.`);
});
```
</CH.Code>
With this, you now have a very simple logger telling you who deleted a message authored by another person.
### Who kicked a user?
This is very similar to the example above.
<CH.Code>
```js JavaScript
import { AuditLogEvent, Events } from 'discord.js';
client.on(Events.GuildAuditLogEntryCreate, async (auditLog) => {
// Define your variables.
const { action, executorId, targetId } = auditLog;
// Check only for kicked users.
if (action !== AuditLogEvent.MemberKick) return;
// Ensure the executor is cached.
const executor = await client.users.fetch(executorId);
// Ensure the kicked guild member is cached.
const kickedUser = await client.users.fetch(targetId);
// Now you can log the output!
console.log(`${kickedUser.tag} was kicked by ${executor.tag}.`);
});
```
```ts TypeScript
import { AuditLogEvent, Events } from 'discord.js';
client.on(Events.GuildAuditLogEntryCreate, async (auditLog) => {
// Define your variables.
const { action, executorId, targetId } = auditLog;
// Check only for kicked users.
if (action !== AuditLogEvent.MemberKick) return;
// Ensure the executor is cached. The id definitely exists.
const executor = await client.users.fetch(executorId!);
// Ensure the kicked guild member is cached. The id definitely exists.
const kickedUser = await client.users.fetch(targetId!);
// Now you can log the output!
console.log(`${kickedUser.tag} was kicked by ${executor.tag}.`);
});
```
</CH.Code>
If you want to check who banned a user, it's the same example as above except the _`action`_ should be _`AuditLogEvent.MemberBanAdd`_. You can check the rest of the types over at the [discord-api-types documentation](https://discord-api-types.dev/api/discord-api-types-v10/enum/AuditLogEvent).

View File

@@ -0,0 +1,202 @@
---
title: Threads
category: Popular topics
---
# Threads
Threads can be thought of as temporary sub-channels inside an existing channel to help better organize conversations in a busy channel.
## Thread related gateway events
<Alert title="Tip" type="info">
You can use the <DocsLink type="class" parent="BaseChannel" symbol="isThread" brackets /> type guard to make sure a
channel is a <DocsLink type="class" parent="ThreadChannel" />!
</Alert>
Threads introduce a number of new gateway events, which are listed below:
- <DocsLink type="class" parent="Client" symbol="e-threadCreate" />: Emitted whenever a thread is created or when the
client user is added to a thread.
- <DocsLink type="class" parent="Client" symbol="e-threadDelete" />: Emitted whenever a thread is deleted.
- <DocsLink type="class" parent="Client" symbol="e-threadUpdate" />: Emitted whenever a thread is updated (e.g. name
change, archive state change, locked state change).
- <DocsLink type="class" parent="Client" symbol="e-threadListSync" />: Emitted whenever the client user gains access to
a text or announcement channel that contains threads.
- <DocsLink type="class" parent="Client" symbol="e-threadMembersUpdate" />: Emitted whenever members are added or
removed from a thread. Requires <code>GuildMembers</code> privileged intent.
- <DocsLink type="class" parent="Client" symbol="e-threadMemberUpdate" />: Emitted whenever the client user's thread
member is updated.
## Creating and deleting threads
Threads are created and deleted using the <DocsLink type="class" parent="GuildTextThreadManager" /> of a text or announcement channel.
To create a thread, you call the <DocsLink type="class" parent="GuildTextThreadManager" symbol="create" brackets /> method:
<CH.Code>
```js
import { ThreadAutoArchiveDuration } from 'discord.js';
const thread = await channel.threads.create({
name: 'food-talk',
autoArchiveDuration: ThreadAutoArchiveDuration.OneHour,
reason: 'Needed a separate thread for food',
});
console.log(`Created thread: ${thread.name}`);
```
</CH.Code>
They can also be created from an existing message with the <DocsLink type="class" parent="Message" symbol="startThread" brackets /> method, but will be "orphaned" if that message is deleted.
<CH.Code>
```js focus=3[22:42]
import { ThreadAutoArchiveDuration } from 'discord.js';
const thread = await message.startThread({
name: 'food-talk',
autoArchiveDuration: ThreadAutoArchiveDuration.OneHour,
reason: 'Needed a separate thread for food',
});
console.log(`Created thread: ${thread.name}`);
```
</CH.Code>
The created thread and the message it originated from will share the same id. The type of thread created matches the parent channel's type.
To delete a thread, use the <DocsLink type="class" parent="ThreadChannel" symbol="delete" brackets /> method:
<CH.Code>
```js focus=2
const thread = channel.threads.cache.find((x) => x.name === 'food-talk');
if (thread.manageable) await thread.delete();
```
</CH.Code>
## Joining and leaving threads
To subscribe your client to a thread, use the <DocsLink type="class" parent="ThreadChannel" symbol="join" brackets /> method:
<CH.Code>
```js focus=2
const thread = channel.threads.cache.find((x) => x.name === 'food-talk');
if (thread.joinable) await thread.join();
```
</CH.Code>
And to leave one, use the <DocsLink type="class" parent="ThreadChannel" symbol="leave" brackets /> method:
<CH.Code>
```js focus=2
const thread = channel.threads.cache.find((x) => x.name === 'food-talk');
await thread.leave();
```
</CH.Code>
## Archiving, unarchiving, and locking threads
A thread can be either active or archived. Changing a thread from archived to active is referred to as unarchiving the thread. Threads that have _`locked`_ set to _`true`_ can only be unarchived by a member with the _`ManageThreads`_ permission.
Threads are automatically archived after inactivity. "Activity" is defined as sending a message, unarchiving a thread, or changing the auto-archive time.
To archive or unarchive a thread, use the <DocsLink type="class" parent="ThreadChannel" symbol="setArchived" brackets /> method and pass in a boolean parameter:
<CH.Code>
```js focus=2,3
const thread = channel.threads.cache.find((x) => x.name === 'food-talk');
await thread.setArchived(true); // Archived.
await thread.setArchived(false); // Unarchived.
```
</CH.Code>
This same principle applies to locking and unlocking a thread via the <DocsLink type="class" parent="ThreadChannel" symbol="setLocked" brackets /> method:
<CH.Code>
```js focus=2,3
const thread = channel.threads.cache.find((x) => x.name === 'food-talk');
await thread.setLocked(true); // Locked.
await thread.setLocked(false); // Unlocked.
```
</CH.Code>
## Private threads
Public threads are viewable by everyone who can view the parent channel of the thread. Private threads, however, are only viewable to those who are invited or have the _`ManageThreads`_ permission. Private threads can only be created on text channels.
To create a private thread, use the <DocsLink type="class" parent="GuildTextThreadManager" symbol="create" brackets /> method and pass in _`ChannelType.PrivateThread`_ as the _`type`_:
<CH.Code>
```js focus=1[10:21],6
import { ChannelType, ThreadAutoArchiveDuration } from 'discord.js';
const thread = await channel.threads.create({
name: 'mod-talk',
autoArchiveDuration: ThreadAutoArchiveDuration.OneHour,
type: ChannelType.PrivateThread,
reason: 'Needed a separate thread for moderation',
});
console.log(`Created thread: ${thread.name}`);
```
</CH.Code>
## Adding and removing members
You can add members to a thread with the <DocsLink type="class" parent="ThreadMemberManager" symbol="add" brackets /> method. The thread must be unarchived and you must be able to send messages in it.
<CH.Code>
```js focus=2
const thread = channel.threads.cache.find((x) => x.name === 'food-talk');
await thread.members.add('12345678901234567');
```
</CH.Code>
You can remove members from a thread with the <DocsLink type="class" parent="ThreadMemberManager" symbol="remove" brackets /> method. The thread must be unarchived and you must have the _`ManageThreads`_ permission unless the thread is private and you are the owner of it.
<CH.Code>
```js focus=2
const thread = channel.threads.cache.find((x) => x.name === 'food-talk');
await thread.members.remove('12345678901234567');
```
</CH.Code>
## Sending messages to threads with webhooks
It is possible for a webhook built on the parent channel to send messages to the channel's threads. For the purpose of this example, it is assumed a single webhook already exists for that channel. If you wish to learn more about webhooks, see our [webhook guide](./webhooks).
<CH.Code>
```js focus=4:7
const webhooks = await channel.fetchWebhooks();
const webhook = webhooks.first();
await webhook.send({
content: "Look ma! I'm in a thread!",
threadId: '123456789012345678',
});
```
</CH.Code>
And that's it! Now you know all there is to know on working with threads using discord.js!

View File

@@ -0,0 +1,229 @@
---
title: Webhooks
category: Popular topics
---
# Webhooks
Webhooks can send messages to a text channel without having to log in as a bot. They can also fetch, edit, and delete their own messages. There are a variety of methods in discord.js to interact with webhooks. In this section, you will learn how to create, fetch, edit, and use webhooks.
## What is a webhook
Webhooks are a utility used to send messages to text channels without needing a Discord application. Webhooks are useful for allowing something to send messages without requiring a Discord application. You can also directly edit or delete messages you sent through the webhook. There are two structures to make use of this functionality: <DocsLink type="class" parent="Webhook" /> and <DocsLink type="class" parent="WebhookClient" />. _`WebhookClient`_ is an extended version of a _`Webhook`_, which allows you to send messages through it without needing a bot client.
<Alert title="Tip" type="info">
If you would like to read about using webhooks through the API without discord.js, you can read about them
[here](https://discord.com/developers/docs/resources/webhook).
</Alert>
## Detecting webhook messages
Bots receive webhook messages in a text channel as usual. You can detect if a webhook sent the message by checking if the _`Message.webhookId`_ is not _`null`_. In this example, we return if a webhook sent the message.
<CH.Code>
```js
if (message.webhookId) return;
```
</CH.Code>
If you would like to get the webhook object that sent the message, you can use <DocsLink type="class" parent="Message" symbol="fetchWebhook" brackets />.
## Fetching webhooks
<Alert title="Tip" type="info">
Webhook fetching will always make use of collections and promises. If you do not understand either concept, revise
them, and then come back to this section. You can read about collections [here](../additional-info/collections), and
promises [here](../additional-info/understanding-async-await) and
[here](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Using_promises).
</Alert>
### Fetching all webhooks of a guild
If you would like to get all webhooks of a guild, you can use the <DocsLink type="class" parent="Guild" symbol="fetchWebhooks" brackets /> method. This will return a promise which will resolve into a collection of webhooks.
### Fetching webhooks of a channel
Webhooks belonging to a channel can be fetched using the <DocsLink type="class" parent="TextChannel" symbol="fetchWebhooks" brackets /> method. This will return a promise which will resolve into a collection of webhooks. A collection will be returned even if the channel contains a single webhook. If you are certain the channel contains a single webhook, you can use the <DocsLink package="collection" type="Class" parent="Collection" symbol="first" brackets /> method on the collection to get the webhook.
### Fetching a single webhook
#### Using client
You can fetch a specific webhook using its _`id`_ with the <DocsLink type="class" parent="Client" symbol="fetchWebhook" brackets /> method. You can obtain the webhook id by looking at its URL: the number after _`https://discord.com/api/webhooks/`_ is the _`id`_ and the part after that is the _`token`_.
#### Using the WebhookClient constructor
If you are not using a bot client, you can get a webhook by creating a new instance of _`WebhookClient`_ and passing the _`id`_ and _`token`_ into the constructor. These credentials do not require you to have a bot application, but it also offers limited information instead of fetching it using an authorized client.
<CH.Code>
```js
const webhookClient = new WebhookClient({ id: 'id', token: 'token' });
```
</CH.Code>
You can also pass in just a _`url`_:
<CH.Code>
```js
const webhookClient = new WebhookClient({ url: 'https://discord.com/api/webhooks/id/token' });
```
</CH.Code>
## Creating webhooks
### Creating webhooks through server settings
You can create webhooks directly through the Discord client. Go to Server Settings, and you will see an _`Integrations`_ tab.
![Integrations tab](/assets/integrations-tab.png)
If you already have created a webhook, the webhooks tab will look like this; you will need to click the _`View Webhooks`_ button.
![Integrations tab](/assets/integrations-view-tab.png)
Once you are there, click on the _`Create Webhook`_ / _`New Webhook`_ button; this will create a webhook. From here, you can edit the channel, the name, and the avatar. Copy the link, the first part is the id, and the second is the token.
![Creating a Webhook](/assets/webhook.png)
### Creating webhooks with discord.js
Webhooks can be created with the <DocsLink type="class" parent="TextChannel" symbol="createWebhook" brackets /> method.
<CH.Code>
```js
channel
.createWebhook({ name: 'Username', avatar: 'https://guide.discordjs.dev/assets/discordjs.png' })
.then((webhook) => console.log(`Created webhook ${webhook}`))
.catch(console.error);
```
</CH.Code>
## Editing webhooks
You can edit Webhooks and WebhookClients to change their name, avatar, and channel using <DocsLink type="class" parent="Webhook" symbol="edit" brackets />.
<CH.Code>
```js
webhook
.edit({ name: 'Username', avatar: 'https://guide.discordjs.dev/assets/discordjs.png', channel: '123456789012345678' })
.then((webhook) => console.log(`Edited webhook ${webhook}`))
.catch(console.error);
```
</CH.Code>
## Using webhooks
Webhooks can send messages to text channels, as well as fetch, edit, and delete their own. These methods are the same for both _`Webhook`_ and _`WebhookClient`_.
### Sending messages
Webhooks, like bots, can send up to 10 embeds per message. They can also send attachments and normal content. The <DocsLink type="class" parent="Webhook" symbol="send" brackets /> method is very similar to the method used for sending a message to a text channel. Webhooks can also choose how the username and avatar will appear when they send the message.
Example using a _`WebhookClient`_:
<CH.Code>
```js
import { EmbedBuilder, WebhookClient } from 'discord.js';
import config from './config.json' assert { type: 'json' };
const { webhookId, webhookToken } = config;
const webhookClient = new WebhookClient({ id: webhookId, token: webhookToken });
const embed = new EmbedBuilder().setTitle('Some Title').setColor(0x00ffff);
await webhookClient.send({
content: 'Webhook test',
username: 'some-username',
avatarURL: 'https://guide.discordjs.dev/assets/discordjs.png',
embeds: [embed],
});
```
</CH.Code>
Try to find a webhook your bot knows the token for. This makes sure your bot can execute the webhook later on.
<CH.Code>
```js
import { Client, EmbedBuilder, Events, GatewayIntentBits } from 'discord.js';
import config from './config.json' assert { type: 'json' };
const { token } = config;
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
const embed = new EmbedBuilder().setTitle('Some Title').setColor(0x00ffff);
client.once(Events.ClientReady, async () => {
const channel = client.channels.cache.get('123456789012345678');
try {
const webhooks = await channel.fetchWebhooks();
const webhook = webhooks.find((wh) => wh.token);
if (!webhook) return console.log('No webhook was found that I can use!');
await webhook.send({
content: 'Webhook test',
username: 'some-username',
avatarURL: 'https://guide.discordjs.dev/assets/discordjs.png',
embeds: [embed],
});
} catch (error) {
console.error('Error trying to send a message: ', error);
}
});
client.login(token);
```
</CH.Code>
### Fetching messages
You can use <DocsLink type="class" parent="Webhook" symbol="fetchMessage" brackets /> to fetch messages previously sent by the Webhook.
<CH.Code>
```js
const message = await webhookClient.fetchMessage('123456789012345678');
```
</CH.Code>
### Editing messages
You can use <DocsLink type="class" parent="Webhook" symbol="editMessage" brackets /> to edit messages previously sent by the Webhook.
<CH.Code>
```js
const message = await webhook.editMessage('123456789012345678', {
content: 'Edited!',
username: 'some-username',
avatarURL: 'https://guide.discordjs.dev/assets/discordjs.png',
embeds: [embed],
});
```
</CH.Code>
### Deleting messages
You can use <DocsLink type="class" parent="Webhook" symbol="deleteMessage" brackets /> to delete messages previously sent by the webhook.
<CH.Code>
```js
await webhookClient.deleteMessage('123456789012345678');
```
</CH.Code>

View File

@@ -102,15 +102,15 @@ Now that you know how Promises work and what they are used for, let's look at an
<CH.Code>
```js
const { Client, GatewayIntentBits } = require('discord.js');
import { Client, Events, GatewayIntentBits } from 'discord.js';
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.once('ready', () => {
client.once(Events.ClientReady, () => {
console.log('I am ready!');
});
client.on('interactionCreate', (interaction) => {
client.on(Events.InteractionCreate, (interaction) => {
if (!interaction.isChatInputCommand()) return;
if (interaction.commandName === 'react') {

Some files were not shown because too many files have changed in this diff Show More