Compare commits

..

18 Commits

Author SHA1 Message Date
Jacob
780cbadd79 Properly export constants using named exports - v8 (#871)
* Properly export constants so they can be imported using named imports which are present throughout the lib.

* run grunt
2016-11-05 11:21:02 +00:00
Austin Huang
af0663e915 Update docs_user.rst (#797)
typo
2016-10-14 00:33:26 -04:00
abalabahaha
07fbf8df56 Update docs 2016-10-08 06:57:01 +09:00
Jacob
72be5e6498 v8 - Emit error event on sendTyping falures instead of failing silently (#769)
* Properly emit error on sendTyping failure.

* Properly emit error on sendTyping failure.
2016-10-03 14:44:17 -07:00
abalabahaha
2b1fcf168c Deminify files 2016-10-02 13:25:00 +09:00
abalabahaha
d0e38c721d 8.2.0 2016-10-02 13:23:34 +09:00
abalabahaha
972558f030 Fix redeclaration 2016-10-02 13:11:26 +09:00
Jacob
015eb9c546 add Webhook structure (#764) 2016-10-01 21:02:48 -07:00
abalabahaha
76dd4f74da Fix arbitrary ffmpeg 2016-10-02 12:44:59 +09:00
Jacob
c00d209014 add webhooks v8 (#759)
* add webhook structure and getChannelWebhooks as well as getServerWebhooks

* add sendMessage

* add the ability to edit create and delete hooks

* remove server wide cache and add getter.
2016-10-01 11:53:14 +01:00
abalabahaha
d22ca969db Add more undefined checks 2016-09-27 15:36:15 +09:00
abalabahaha
ba0c8c45fc Fix potentially long websocket messages 2016-09-25 08:30:08 +09:00
abalabahaha
3bc6ea455d Fix voice channel joining 2016-09-19 03:41:08 +09:00
abalabahaha
53ecaab12a Default message.content to normal message 2016-09-18 09:46:46 +09:00
abalabahaha
34323c869e Gateway v6 support 2016-09-18 09:26:29 +09:00
abalabahaha
d96f5d1e30 Userbots on gateway v5 2016-09-18 08:50:32 +09:00
abalabahaha
4139401f1b Experimental gateway v5 support 2016-09-18 08:14:26 +09:00
abalabahaha
e3c7fd70e1 Attempting gateway v4 2016-09-18 07:59:35 +09:00
1475 changed files with 586107 additions and 173697 deletions

1
.babelrc Normal file
View File

@@ -0,0 +1 @@
{}

View File

@@ -1,13 +0,0 @@
{
"$schema": "https://json.schemastore.org/commitlintrc.json",
"extends": ["@commitlint/config-angular"],
"rules": {
"type-enum": [
2,
"always",
["chore", "build", "ci", "docs", "feat", "fix", "perf", "refactor", "revert", "style", "test", "types"]
],
"scope-case": [0],
"subject-exclamation-mark": [0]
}
}

View File

@@ -1,67 +0,0 @@
# Packages
**/node_modules
# Log files
**/logs
**/*.log
**/npm-debug.log*
# Runtime data
**/pids
**/*.pid
**/*.seed
# Env
**/.env
# Dist
**/dist/
**/dist-docs/
# Miscellaneous
**/.tmp
**/.vscode
**/.idea
**/.DS_Store
**/.turbo
**/tsconfig.tsbuildinfo
**/coverage
**/__tests__
**/out
# yarn
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions
# Cache
**/.prettiercache
**/.eslintcache
**/.vercel
# Docker specific
**/.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

9
.eslintrc Normal file
View File

@@ -0,0 +1,9 @@
{
"env": {
"es6": true,
"node": true
},
"ecmaFeatures": {
"modules": true
}
}

2
.gitattributes vendored
View File

@@ -1,2 +0,0 @@
* text=auto eol=lf
pnpm-lock.yaml linguist-generated=true text=auto eol=lf

11
.github/.kodiak.toml vendored
View File

@@ -1,11 +0,0 @@
version = 1
[merge]
require_automerge_label = false
blocking_labels = ['blocked', 'in review']
method = 'squash'
[merge.message]
title = 'pull_request_title'
strip_html_comments = true
include_coauthors = true

24
.github/CODEOWNERS vendored
View File

@@ -1,24 +0,0 @@
# Learn how to add code owners here:
# https://help.github.com/articles/about-code-owners
* @iCrawl
/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/create-discord-bot/ @discordjs/guide
/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,76 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to make participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery and unwelcome sexual attention or
advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic
address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies within all project spaces, and it also applies when
an individual is representing the project or its community in public spaces.
Examples of representing a project or community include using an official
project e-mail address, posting via an official social media account, or acting
as an appointed representative at an online or offline event. Representation of
a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at https://discord.gg/djs. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq

View File

@@ -1,92 +0,0 @@
## Git Commit Message Convention
> This is adapted from [Angular's commit convention](https://github.com/conventional-changelog/conventional-changelog/tree/master/packages/conventional-changelog-angular).
#### TL;DR:
Messages must be matched by the following regex:
```js
/^(revert: )?(feat|fix|docs|style|refactor|perf|test|build|ci|chore|types)(\(.+\))?!?: .{1,72}/;
```
#### Examples
Appears under "Features" header, `GuildMember` subheader:
```
feat(GuildMember): add 'tag' method
```
Appears under "Bug Fixes" header, `Guild` subheader, with a link to issue #28:
```
fix(Guild): handle events correctly
close #28
```
Appears under "Performance Improvements" header, and under "Breaking Changes" with the breaking change explanation:
```
perf(core): improve patching by removing 'bar' option
BREAKING CHANGE: The 'bar' option has been removed.
```
The following commit and commit `667ecc1` do not appear in the changelog if they are under the same release. If not, the revert commit appears under the "Reverts" header.
```
revert: feat(Managers): add Managers
This reverts commit 667ecc1654a317a13331b17617d973392f415f02.
```
### Full Message Format
A commit message consists of a **header**, **body** and **footer**. The header has a **type**, **scope** and **subject**:
```
<type>(<scope>): <subject>
<BLANK LINE>
<body>
<BLANK LINE>
<footer>
```
The **header** is mandatory and the **scope** of the header is optional.
If the commit contains **Breaking Changes**, a `!` can be added before the `:` as an indicator.
### Revert
If the commit reverts a previous commit, it should begin with `revert:`, followed by the header of the reverted commit. In the body, it should say: `This reverts commit <hash>.`, where the hash is the SHA of the commit being reverted.
### Type
If the prefix is `feat`, `fix` or `perf`, it will appear in the changelog. However, if there is any [BREAKING CHANGE](#footer), the commit will always appear in the changelog.
Other prefixes are up to your discretion. Suggested prefixes are `docs`, `chore`, `style`, `refactor`, and `test` for non-changelog related tasks.
### Scope
The scope could be anything specifying the place of the commit change. For example `GuildMember`, `Guild`, `Message`, `TextChannel` etc...
### Subject
The subject contains a succinct description of the change:
- use the imperative, present tense: "change" not "changed" nor "changes"
- don't capitalize the first letter
- no dot (.) at the end
### Body
Just as in the **subject**, use the imperative, present tense: "change" not "changed" nor "changes".
The body should include the motivation for the change and contrast this with previous behavior.
### Footer
The footer should contain any information about **Breaking Changes** and is also the place to
reference GitHub issues that this commit **Closes**.
**Breaking Changes** should start with the word `BREAKING CHANGE:` with a space or two newlines. The rest of the commit message is then used for this.

View File

@@ -1,49 +0,0 @@
# Contributing
**The issue tracker is only for bug reports and enhancement suggestions. If you have a question, please ask it in the [Discord server](https://discord.gg/djs) instead of opening an issue you will get redirected there anyway.**
If you wish to contribute to the discord.js codebase or documentation, feel free to fork the repository and submit a
pull request. We use ESLint to enforce a consistent coding style, so having that set up in your editor of choice
is a great boon to your development process.
## Setup
To get ready to work on the codebase, please do the following:
1. Fork & clone the repository, and make sure you're on the **main** branch
2. Run `pnpm install --frozen-lockfile` ([install](https://pnpm.io/installation))
3. Run `pnpm run build` to build local packages
4. Code your heart out!
5. Run `pnpm run test` to run ESLint and ensure any JSDoc changes are valid
6. [Submit a pull request](https://github.com/discordjs/discord.js/compare) (Make sure you follow the [conventional commit format](https://github.com/discordjs/discord.js/blob/main/.github/COMMIT_CONVENTION.md))
## Testing changes locally
If you want to test changes you've made locally, you can do so by using `pnpm link <package-you-want-to-link-to-your-current-package>`. This will create a symlink to your local copy of the discord.js libraries.
1. Create a new directory `mkdir discordjs-test` and move into it `cd discordjs-test`
2. Initialize a new pnpm project `pnpm init`
3. Now link the discord.js package from the directory you cloned earlier `pnpm link {PATH_TO_DISCORDJS_REPO}/packages/<package>`. (e.g. `pnpm link ~/discord.js/packages/rest`)
4. Import the package in your source code and test them out!
### Working with TypeScript packages
When testing local changes, you may notice you need to manually recompile TypeScript projects on every change in order to get the latest code changes to test locally.
To avoid this you can use the `--watch` parameter in the package build script to automatically recompile the project when changes are detected.
For example, to automatically recompile the `@discordjs/rest` project when changes are detected, run `pnpm turbo run build --filter='@discordjs/rest' -- --watch` in the root folder of where you cloned the discord.js repo.
## Adding new packages
If you'd like to create another package under the `@discordjs` organization run the following command:
```sh
pnpm run create-package <package-name> [package-description]
```
This will create new package directory under `packages/` with the required configuration files. You may begin
to make changes within the `src/` directory. You may also need to:
- Update workflows that utilize packages
- Update the CODEOWNERS file

2
.github/FUNDING.yml vendored
View File

@@ -1,2 +0,0 @@
github: [iCrawl, amishshah, vladfrangu, kyranet]
open_collective: discordjs

View File

@@ -1,139 +0,0 @@
name: Bug report
description: Report an issue with discord.js or another package.
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 discord.js, including other packages.
- type: dropdown
id: package
attributes:
label: Which package is this bug report for?
options:
- discord.js
- brokers
- builders
- collection
- core
- create-discord-bot
- formatters
- next
- proxy
- proxy-container
- rest
- ui
- util
- voice
- ws
validations:
required: true
- type: textarea
id: description
attributes:
label: Issue description
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
validations:
required: true
- type: textarea
id: code_sample
attributes:
label: Code sample
description: |
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.12.1 (`npm ls discord.js` or another package)
- Node.js 16.11.0 (`node --version`)
- TypeScript 5.1.6 (`npm ls typescript` if you use it)
- 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
- type: dropdown
id: partials
attributes:
label: Which partials do you have configured?
description: Check your `Client` constructor for the `partials` key.
options:
- Not applicable
- No Partials
- User
- Channel
- GuildMember
- Message
- Reaction
- GuildScheduledEvent
- ThreadMember
multiple: true
validations:
required: true
- type: dropdown
id: intents
attributes:
label: Which gateway intents are you subscribing to?
description: Check your `Client` constructor for the `intents` key.
options:
- Not applicable
- No Intents
- Guilds
- GuildMembers
- GuildModeration
- GuildEmojisAndStickers
- GuildIntegrations
- GuildWebhooks
- GuildInvites
- GuildVoiceStates
- GuildPresences
- GuildMessages
- GuildMessageReactions
- GuildMessageTyping
- DirectMessages
- DirectMessageReactions
- DirectMessageTyping
- MessageContent
- GuildScheduledEvents
- AutoModerationConfiguration
- AutoModerationExecution
- GuildMessagePolls
- DirectMessagePolls
multiple: true
validations:
required: true
- type: input
id: dev_release
attributes:
label: I have tested this issue on a development release
placeholder: d23280c (commit hash)
description: |
The issue might already be fixed in a development release or main. This is not required, but helps us greatly.
[discord.js only] To install the latest development release run `npm i discord.js@dev` in your project directory.
Run `npm list discord.js` and use the last part of the printed information (`d23280c` for `discord.js@xx.x.x-dev.1530234593.d23280c`)

View File

@@ -1,58 +0,0 @@
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

@@ -1,59 +0,0 @@
name: Feature request
description: Request a new feature (discord.js accepts documented features of the official Discord developer API only!)
labels: [feature request]
body:
- type: markdown
attributes:
value: |
We can only implement features that Discord publishes, documents, and merges into the Discord API documentation.
We do not implement unreleased features.
Use Discord for questions: https://discord.gg/djs
- type: dropdown
id: application_or_package
attributes:
label: Which application or package is this feature request for?
options:
- discord.js
- Documentation
- Guide
- brokers
- builders
- collection
- core
- create-discord-bot
- formatters
- next
- proxy
- proxy-container
- rest
- ui
- util
- voice
- ws
validations:
required: true
- type: textarea
id: description
attributes:
label: Feature
description: A clear and concise description of what the problem is, or what feature you want to be implemented.
placeholder: I'm always frustrated when..., Discord has recently released..., A good addition would be...
validations:
required: true
- type: textarea
id: solution
attributes:
label: Ideal solution or implementation
description: A clear and concise description of what you want to happen.
validations:
required: true
- type: textarea
id: alternatives
attributes:
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
attributes:
label: Other context
description: Any other context, screenshots, or file uploads that help us understand your feature request.

View File

@@ -1,5 +0,0 @@
blank_issues_enabled: false
contact_links:
- name: Discord server
url: https://discord.gg/djs
about: Please visit our Discord server for questions and support requests.

View File

@@ -1,12 +0,0 @@
**Please describe the changes this PR makes and why it should be merged:**
**Status and versioning classification:**
<!--
Please move lines that apply to you out of the comment:
- Code changes have been tested against the Discord API, or there are no code changes
- I know how to update typings and have done so, or typings don't need updating
- This PR changes the library's interface (methods or parameters added)
- This PR includes breaking changes (methods removed or renamed, parameters moved or removed)
- This PR **only** includes non-code changes, like changes to documentation, README, etc.
-->

7
.github/SUPPORT.md vendored
View File

@@ -1,7 +0,0 @@
# Seeking support?
We only use this issue tracker for bug reports and feature request. We are not able to provide general support or answer questions in the form of GitHub issues.
For general questions about discord.js installation and use please use the dedicated support channels in our Discord server: https://discord.gg/djs
Any issues that don't directly involve a bug or a feature request will likely be closed and redirected.

View File

@@ -1,51 +0,0 @@
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 (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\nbrokers\\n"
packages:builders:
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\nbuilders\\n"
packages:collection:
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\ncollection\\n"
packages:core:
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\ncore\\n"
packages:create-discord-bot:
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\ncreate-discord-bot\\n"
packages:discord.js:
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\ndiscord.js\\n"
packages:formatters:
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\nformatters\\n"
packages:next:
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\nnext\\n"
packages:proxy:
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\nproxy\\n"
packages:proxy-container:
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\nproxy-container\\n"
packages:rest:
- "### 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 (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\nvoice\\n"
packages:ws:
- "### Which (application|package|application or package) is this (bug
report|feature request) for\\?\\n\\nws\\n"

100
.github/labeler.yml vendored
View File

@@ -1,100 +0,0 @@
apps:guide:
- changed-files:
- any-glob-to-any-file:
- apps/guide/*
- apps/guide/**/*
apps:website:
- changed-files:
- any-glob-to-any-file:
- apps/website/*
- apps/website/**/*
packages:api-extractor:
- changed-files:
- any-glob-to-any-file:
- packages/api-extractor/*
- packages/api-extractor/**/*
packages:api-extractor-model:
- changed-files:
- any-glob-to-any-file:
- packages/api-extractor-model/*
- packages/api-extractor-model/**/*
packages:brokers:
- changed-files:
- any-glob-to-any-file:
- packages/brokers/*
- packages/brokers/**/*
packages:builders:
- changed-files:
- any-glob-to-any-file:
- packages/builders/*
- packages/builders/**/*
packages:collection:
- changed-files:
- any-glob-to-any-file:
- packages/collection/*
- packages/collection/**/*
packages:core:
- changed-files:
- any-glob-to-any-file:
- packages/core/*
- packages/core/**/*
packages:create-discord-bot:
- changed-files:
- any-glob-to-any-file:
- packages/create-discord-bot/*
- packages/create-discord-bot/**/*
packages:discord.js:
- changed-files:
- any-glob-to-any-file:
- packages/discord.js/*
- packages/discord.js/**/*
packages:docgen:
- changed-files:
- any-glob-to-any-file:
- packages/docgen/*
- packages/docgen/**/*
packages:formatters:
- changed-files:
- any-glob-to-any-file:
- packages/formatters/*
- packages/formatters/**/*
packages:next:
- changed-files:
- any-glob-to-any-file:
- packages/next/*
- packages/next/**/*
packages:proxy:
- changed-files:
- any-glob-to-any-file:
- packages/proxy/*
- packages/proxy/**/*
packages:proxy-container:
- changed-files:
- any-glob-to-any-file:
- packages/proxy-container/*
- packages/proxy-container/**/*
packages:rest:
- changed-files:
- any-glob-to-any-file:
- packages/rest/*
- packages/rest/**/*
packages:ui:
- changed-files:
- any-glob-to-any-file:
- packages/ui/*
- packages/ui/**/*
packages:util:
- changed-files:
- any-glob-to-any-file:
- packages/util/*
- packages/util/**/*
packages:voice:
- changed-files:
- any-glob-to-any-file:
- packages/voice/*
- packages/voice/**/*
packages:ws:
- changed-files:
- any-glob-to-any-file:
- packages/ws/*
- packages/ws/**/*

124
.github/labels.yml vendored
View File

@@ -1,124 +0,0 @@
- name: api changes
color: '5663e9'
- name: api support
color: '5663e9'
- name: apps:guide
color: fbca04
- name: apps:website
color: fbca04
- name: backlog
color: 7ef7ef
- name: backport
color: 88aabb
- name: blocked
color: fc1423
- name: bug
color: d73a4a
- name: caching
color: 80c042
- name: chore
color: ffffff
- name: ci
color: 0075ca
- name: dependencies
color: 276bd1
- name: discord
color: '5663e9'
- name: discussion
color: b6b1f9
- name: documentation
color: 0075ca
- name: duplicate
color: cfd3d7
- name: error handling
color: 80c042
- name: feature request
color: fcf95a
- name: gateway
color: 80c042
- name: good first issue
color: 7057ff
- name: has PR
color: 4b1f8e
- name: help wanted
color: '008672'
- name: in progress
color: ffccd7
- name: in review
color: aed5fc
- name: interactions
color: 80c042
- name: invalid
color: e4e669
- name: need repro
color: c66037
- name: packages:api-extractor
color: fbca04
- name: packages:api-extractor-model
color: fbca04
- name: packages:brokers
color: fbca04
- name: packages:builders
color: fbca04
- name: packages:collection
color: fbca04
- name: packages:core
color: fbca04
- name: packages:create-discord-bot
color: fbca04
- name: packages:discord.js
color: fbca04
- name: packages:docgen
color: fbca04
- name: packages:formatters
color: fbca04
- name: packages:next
color: fbca04
- name: packages:proxy
color: fbca04
- name: packages:proxy-container
color: fbca04
- name: packages:rest
color: fbca04
- name: packages:ui
color: fbca04
- name: packages:util
color: fbca04
- name: packages:voice
color: fbca04
- name: packages:ws
color: fbca04
- name: performance
color: 80c042
- name: permissions
color: 80c042
- name: priority:high
color: fc1423
- name: question (please use Discord instead)
color: d876e3
- name: ratelimits
color: 80c042
- name: refactor
color: 1d637f
- name: regression
color: ea8785
- name: REST
color: 80c042
- name: semver:major
color: c10f47
- name: semver:minor
color: e4f486
- name: semver:patch
color: e8be8b
- name: sharding
color: 80c042
- name: tests
color: f06dff
- name: threads
color: 80c042
- name: typings
color: 80c042
- name: utility
color: 80c042
- name: wontfix
color: ffffff

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

18
.github/tsc.json vendored
View File

@@ -1,18 +0,0 @@
{
"problemMatcher": [
{
"owner": "tsc",
"pattern": [
{
"regexp": "^(?:\\s+\\d+\\>)?([^\\s].*)\\((\\d+),(\\d+)\\)\\s*:\\s+(error|warning|info)\\s+(\\w{1,2}\\d+)\\s*:\\s*(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"code": 5,
"message": 6
}
]
}
]
}

View File

@@ -1,35 +0,0 @@
# https://docs.github.com/actions/using-workflows/caching-dependencies-to-speed-up-workflows#force-deleting-cache-entries
name: Cleanup caches
on:
pull_request:
types:
- closed
workflow_dispatch:
jobs:
cleanup:
name: Cleanup caches
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Cleanup caches
run: |
gh extension install actions/gh-actions-cache
REPO=${{ github.repository }}
BRANCH="refs/pull/${{ github.event.pull_request.number }}/merge"
echo "Fetching list of cache key"
cacheKeysForPR=$(gh actions-cache list -R $REPO -B $BRANCH | cut -f 1 )
## Setting this to not fail the workflow while deleting cache keys.
set +e
echo "Deleting caches..."
for cacheKey in $cacheKeysForPR
do
gh actions-cache delete $cacheKey -R $REPO -B $BRANCH --confirm
done
echo "Done"
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -1,50 +0,0 @@
name: Deprecate version
on:
workflow_dispatch:
inputs:
package:
description: Package
required: true
type: choice
options:
- '@discordjs/brokers'
- '@discordjs/builders'
- '@discordjs/collection'
- '@discordjs/core'
- 'create-discord-bot'
- '@discordjs/formatters'
- 'discord.js'
- '@discordjs/next'
- '@discordjs/proxy'
- '@discordjs/rest'
- '@discordjs/util'
- '@discordjs/voice'
- '@discordjs/ws'
version:
description: Version(s)
required: true
type: string
message:
description: Deprecation message
required: false
type: string
jobs:
deprecate:
runs-on: ubuntu-latest
if: github.repository_owner == 'discordjs'
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install Node.js v20
uses: actions/setup-node@v4
with:
node-version: 20
- name: Install dependencies
uses: ./packages/actions/src/pnpmCache
- name: Deprecate
run: pnpm exec npm-deprecate --name "${{inputs.version}}" --message "${{inputs.message || 'This version is deprecated. Please use a newer version.'}}" --package ${{inputs.package}}
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_PUBLISH_TOKEN }}

View File

@@ -1,280 +0,0 @@
name: Documentation
on:
push:
branches:
- 'main'
paths:
- 'packages/*/src/**'
- '!packages/create-discord-bot/**'
- '!packages/proxy-container/**'
- '!packages/ui/**'
tags:
- '**'
workflow_dispatch:
inputs:
ref:
description: 'The branch, tag or SHA to checkout'
required: true
ref_type:
type: choice
description: 'Branch or tag'
options:
- branch
- tag
required: true
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
cancel-in-progress: true
jobs:
build-docs:
name: Build & upload documentation
runs-on: ubuntu-latest
env:
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
REF_TYPE: ${{ inputs.ref_type || github.ref_type }}
if: github.repository_owner == 'discordjs'
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
ref: ${{ inputs.ref || '' }}
- name: Install Node.js v20
uses: actions/setup-node@v4
with:
node-version: 20
- name: Install dependencies
uses: ./packages/actions/src/pnpmCache
- name: Build dependencies
run: pnpm run build
- name: Checkout main repository
if: ${{ inputs.ref && inputs.ref != 'main' }}
uses: actions/checkout@v4
with:
path: 'main'
- name: Build main
if: ${{ inputs.ref && inputs.ref != 'main' }}
shell: bash
run: |
cd main
pnpm install --frozen-lockfile --prefer-offline --loglevel error
pnpm run build
cd ..
- name: Extract package and semver from tag
if: ${{ env.REF_TYPE == 'tag' }}
id: extract-tag
uses: ./packages/actions/src/formatTag
with:
tag: ${{ inputs.ref || github.ref_name }}
- name: Apply tag to api-extractor config
if: ${{ env.REF_TYPE == 'tag' && !inputs.ref }}
run: sed -i 's!https://github.com/discordjs/discord.js/tree/main!https://github.com/discordjs/discord.js/tree/${{ github.ref_name }}!' "packages/${{ steps.extract-tag.outputs.package}}/api-extractor.json"
- name: Build docs
run: pnpm run docs
- name: Build docs with main api-extractor
if: ${{ inputs.ref && inputs.ref != 'main' }}
run: |
declare -a PACKAGES=("brokers" "builders" "collection" "core" "discord.js" "formatters" "next" "proxy" "rest" "util" "voice" "ws")
for PACKAGE in "${PACKAGES[@]}"; do
cd "packages/${PACKAGE}"
sed -i 's!https://github.com/discordjs/discord.js/tree/main!https://github.com/discordjs/discord.js/tree/${{ inputs.ref }}!' api-extractor.json
../../main/packages/api-extractor/bin/api-extractor run --local --minify
../../main/packages/scripts/bin/generateSplitDocumentation.js
cd ../..
done
- name: Checkout docs repository
uses: actions/checkout@v4
with:
repository: 'discordjs/docs'
token: ${{ secrets.DJS_DOCS }}
path: 'out'
- name: Upload documentation to database
if: ${{ env.REF_TYPE == 'tag' && (!inputs.ref || inputs.ref == 'main') }}
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
CF_D1_DOCS_API_KEY: ${{ secrets.CF_D1_DOCS_API_KEY }}
CF_D1_DOCS_ID: ${{ secrets.CF_D1_DOCS_ID }}
CF_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }}
BLOB_READ_WRITE_TOKEN: ${{ secrets.BLOB_READ_WRITE_TOKEN }}
CF_R2_DOCS_URL: ${{ secrets.CF_R2_DOCS_URL }}
CF_R2_DOCS_ACCESS_KEY_ID: ${{ secrets.CF_R2_DOCS_ACCESS_KEY_ID }}
CF_R2_DOCS_SECRET_ACCESS_KEY: ${{ secrets.CF_R2_DOCS_SECRET_ACCESS_KEY }}
CF_R2_DOCS_BUCKET: ${{ secrets.CF_R2_DOCS_BUCKET }}
CF_R2_DOCS_BUCKET_URL: ${{ secrets.CF_R2_DOCS_BUCKET_URL }}
uses: ./packages/actions/src/uploadDocumentation
with:
package: ${{ steps.extract-tag.outputs.package }}
version: ${{ steps.extract-tag.outputs.semver }}
- name: Upload documentation to database
if: ${{ env.REF_TYPE == 'tag' && inputs.ref && inputs.ref != 'main' }}
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
CF_D1_DOCS_API_KEY: ${{ secrets.CF_D1_DOCS_API_KEY }}
CF_D1_DOCS_ID: ${{ secrets.CF_D1_DOCS_ID }}
CF_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }}
BLOB_READ_WRITE_TOKEN: ${{ secrets.BLOB_READ_WRITE_TOKEN }}
CF_R2_DOCS_URL: ${{ secrets.CF_R2_DOCS_URL }}
CF_R2_DOCS_ACCESS_KEY_ID: ${{ secrets.CF_R2_DOCS_ACCESS_KEY_ID }}
CF_R2_DOCS_SECRET_ACCESS_KEY: ${{ secrets.CF_R2_DOCS_SECRET_ACCESS_KEY }}
CF_R2_DOCS_BUCKET: ${{ secrets.CF_R2_DOCS_BUCKET }}
CF_R2_DOCS_BUCKET_URL: ${{ secrets.CF_R2_DOCS_BUCKET_URL }}
uses: ./main/packages/actions/src/uploadDocumentation
with:
package: ${{ steps.extract-tag.outputs.package }}
version: ${{ steps.extract-tag.outputs.semver }}
- name: Upload split documentation to blob storage
if: ${{ env.REF_TYPE == 'tag' && (!inputs.ref || inputs.ref == 'main') }}
env:
BLOB_READ_WRITE_TOKEN: ${{ secrets.BLOB_READ_WRITE_TOKEN }}
CF_R2_DOCS_URL: ${{ secrets.CF_R2_DOCS_URL }}
CF_R2_DOCS_ACCESS_KEY_ID: ${{ secrets.CF_R2_DOCS_ACCESS_KEY_ID }}
CF_R2_DOCS_SECRET_ACCESS_KEY: ${{ secrets.CF_R2_DOCS_SECRET_ACCESS_KEY }}
CF_R2_DOCS_BUCKET: ${{ secrets.CF_R2_DOCS_BUCKET }}
uses: ./packages/actions/src/uploadSplitDocumentation
with:
package: ${{ steps.extract-tag.outputs.package }}
version: ${{ steps.extract-tag.outputs.semver }}
- name: Upload split documentation to blob storage
if: ${{ env.REF_TYPE == 'tag' && inputs.ref && inputs.ref != 'main' }}
env:
BLOB_READ_WRITE_TOKEN: ${{ secrets.BLOB_READ_WRITE_TOKEN }}
CF_R2_DOCS_URL: ${{ secrets.CF_R2_DOCS_URL }}
CF_R2_DOCS_ACCESS_KEY_ID: ${{ secrets.CF_R2_DOCS_ACCESS_KEY_ID }}
CF_R2_DOCS_SECRET_ACCESS_KEY: ${{ secrets.CF_R2_DOCS_SECRET_ACCESS_KEY }}
CF_R2_DOCS_BUCKET: ${{ secrets.CF_R2_DOCS_BUCKET }}
uses: ./main/packages/actions/src/uploadSplitDocumentation
with:
package: ${{ steps.extract-tag.outputs.package }}
version: ${{ steps.extract-tag.outputs.semver }}
- name: Move docs to correct directory
if: ${{ env.REF_TYPE == 'tag' }}
env:
PACKAGE: ${{ steps.extract-tag.outputs.package }}
SEMVER: ${{ steps.extract-tag.outputs.semver }}
run: |
mkdir -p "out/${PACKAGE}"
if [[ "${PACKAGE}" == "discord.js" ]]; then
mv "packages/${PACKAGE}/docs/docs.json" "out/${PACKAGE}/${SEMVER}.json"
mv "packages/${PACKAGE}/docs/docs.api.json" "out/${PACKAGE}/${SEMVER}.api.json"
else
mv "packages/${PACKAGE}/docs/docs.api.json" "out/${PACKAGE}/${SEMVER}.api.json"
fi
- name: Upload documentation to database
if: ${{ env.REF_TYPE == 'branch' && (!inputs.ref || inputs.ref == 'main') }}
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
CF_D1_DOCS_API_KEY: ${{ secrets.CF_D1_DOCS_API_KEY }}
CF_D1_DOCS_ID: ${{ secrets.CF_D1_DOCS_ID }}
CF_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }}
BLOB_READ_WRITE_TOKEN: ${{ secrets.BLOB_READ_WRITE_TOKEN }}
CF_R2_DOCS_URL: ${{ secrets.CF_R2_DOCS_URL }}
CF_R2_DOCS_ACCESS_KEY_ID: ${{ secrets.CF_R2_DOCS_ACCESS_KEY_ID }}
CF_R2_DOCS_SECRET_ACCESS_KEY: ${{ secrets.CF_R2_DOCS_SECRET_ACCESS_KEY }}
CF_R2_DOCS_BUCKET: ${{ secrets.CF_R2_DOCS_BUCKET }}
CF_R2_DOCS_BUCKET_URL: ${{ secrets.CF_R2_DOCS_BUCKET_URL }}
uses: ./packages/actions/src/uploadDocumentation
- name: Upload documentation to database
if: ${{ env.REF_TYPE == 'branch' && inputs.ref && inputs.ref != 'main' }}
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
CF_D1_DOCS_API_KEY: ${{ secrets.CF_D1_DOCS_API_KEY }}
CF_D1_DOCS_ID: ${{ secrets.CF_D1_DOCS_ID }}
CF_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }}
BLOB_READ_WRITE_TOKEN: ${{ secrets.BLOB_READ_WRITE_TOKEN }}
CF_R2_DOCS_URL: ${{ secrets.CF_R2_DOCS_URL }}
CF_R2_DOCS_ACCESS_KEY_ID: ${{ secrets.CF_R2_DOCS_ACCESS_KEY_ID }}
CF_R2_DOCS_SECRET_ACCESS_KEY: ${{ secrets.CF_R2_DOCS_SECRET_ACCESS_KEY }}
CF_R2_DOCS_BUCKET: ${{ secrets.CF_R2_DOCS_BUCKET }}
CF_R2_DOCS_BUCKET_URL: ${{ secrets.CF_R2_DOCS_BUCKET_URL }}
uses: ./main/packages/actions/src/uploadDocumentation
- name: Upload split documentation to blob storage
if: ${{ env.REF_TYPE == 'branch' && (!inputs.ref || inputs.ref == 'main') }}
env:
BLOB_READ_WRITE_TOKEN: ${{ secrets.BLOB_READ_WRITE_TOKEN }}
CF_R2_DOCS_URL: ${{ secrets.CF_R2_DOCS_URL }}
CF_R2_DOCS_ACCESS_KEY_ID: ${{ secrets.CF_R2_DOCS_ACCESS_KEY_ID }}
CF_R2_DOCS_SECRET_ACCESS_KEY: ${{ secrets.CF_R2_DOCS_SECRET_ACCESS_KEY }}
CF_R2_DOCS_BUCKET: ${{ secrets.CF_R2_DOCS_BUCKET }}
uses: ./packages/actions/src/uploadSplitDocumentation
- name: Upload split documentation to blob storage
if: ${{ env.REF_TYPE == 'branch' && inputs.ref && inputs.ref != 'main' }}
env:
BLOB_READ_WRITE_TOKEN: ${{ secrets.BLOB_READ_WRITE_TOKEN }}
CF_R2_DOCS_URL: ${{ secrets.CF_R2_DOCS_URL }}
CF_R2_DOCS_ACCESS_KEY_ID: ${{ secrets.CF_R2_DOCS_ACCESS_KEY_ID }}
CF_R2_DOCS_SECRET_ACCESS_KEY: ${{ secrets.CF_R2_DOCS_SECRET_ACCESS_KEY }}
CF_R2_DOCS_BUCKET: ${{ secrets.CF_R2_DOCS_BUCKET }}
uses: ./main/packages/actions/src/uploadSplitDocumentation
- name: Move docs to correct directory
if: ${{ env.REF_TYPE == 'branch' }}
run: |
declare -a PACKAGES=("brokers" "builders" "collection" "core" "discord.js" "formatters" "next" "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"
mv "packages/${PACKAGE}/docs/docs.api.json" "out/${PACKAGE}/${GITHUB_REF_NAME}.api.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: |
cd out
git config user.name github-actions[bot]
git config user.email 41898282+github-actions[bot]@users.noreply.github.com
git add .
git commit -m "Docs build for ${GITHUB_REF_TYPE} ${GITHUB_REF_NAME}: ${GITHUB_SHA}" || true
git push
build-indices:
needs: build-docs
name: Build & upload search indices
runs-on: ubuntu-latest
env:
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
if: github.repository_owner == 'discordjs'
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install Node.js v20
uses: actions/setup-node@v4
with:
node-version: 20
- name: Install dependencies
uses: ./packages/actions/src/pnpmCache
- name: Build dependencies
run: pnpm run build
- name: Upload search indices to meilisearch
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
SEARCH_API_URL: ${{ secrets.SEARCH_API_URL }}
SEARCH_API_KEY: ${{ secrets.SEARCH_API_KEY }}
uses: ./packages/actions/src/uploadSearchIndices

View File

@@ -1,14 +0,0 @@
name: 'Issue Labeler'
on:
issues:
types: [opened]
jobs:
issue-triage:
runs-on: ubuntu-latest
steps:
- uses: github/issue-labeler@v3.4
with:
repo-token: '${{ secrets.GITHUB_TOKEN }}'
configuration-path: .github/issue-labeler.yml
not-before: 2023-01-13T10:25:03.847Z
enable-versioned-regex: 0

View File

@@ -1,23 +0,0 @@
name: Label sync
on:
schedule:
- cron: '0 0 * * *'
workflow_dispatch:
push:
branches:
- main
paths:
- '.github/labels.yml'
jobs:
label-sync:
name: Label sync
runs-on: ubuntu-latest
if: github.repository_owner == 'discordjs'
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Label sync
uses: crazy-max/ghaction-github-labeler@v5
with:
github-token: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -1,19 +0,0 @@
name: Lock Ancient Issues
on:
schedule:
- cron: '0 16 * * *'
workflow_dispatch:
concurrency:
group: lock
jobs:
action:
runs-on: ubuntu-latest
permissions:
issues: write
steps:
- uses: dessant/lock-threads@v5
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
issue-inactive-days: 365
issue-lock-reason: resolved
process-only: issues

View File

@@ -1,35 +0,0 @@
name: 'PR Triage'
on:
pull_request_target:
types:
- opened
- edited
- reopened
- synchronize
jobs:
label:
name: Label
if: github.event.action != 'edited'
runs-on: ubuntu-latest
steps:
- name: Label pull request
uses: actions/labeler@v5
with:
repo-token: '${{ secrets.GITHUB_TOKEN }}'
sync-labels: true
validate-title:
name: Validate title
if: github.event.action != 'synchronize'
runs-on: ubuntu-latest
steps:
- name: Validate pull request title
env:
TITLE: ${{ github.event.pull_request.title }}
run: |
REGEX="^(revert: )?(feat|fix|docs|style|refactor|perf|test|build|ci|chore|types)(\\(.+\\))?!?: .{1,72}$"
echo "Title: \"$TITLE\""
if [[ ! "$TITLE" =~ $REGEX ]]; then
exit 1
fi

View File

@@ -1,30 +0,0 @@
name: Publish dev docker images
on:
schedule:
- cron: '0 */12 * * *'
workflow_dispatch:
jobs:
docker-publish:
name: Docker publish
runs-on: ubuntu-latest
if: github.repository_owner == 'discordjs'
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install Node.js v20
uses: actions/setup-node@v4
with:
node-version: 20
- name: Install dependencies
uses: ./packages/actions/src/pnpmCache
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to DockerHub
run: echo ${{ secrets.DOCKER_ACCESS_TOKEN }} | docker login -u ${{ secrets.DOCKER_USERNAME }} --password-stdin
- name: Build & push docker image
run: docker build -f packages/proxy-container/Dockerfile -t discordjs/proxy:latest --push .

View File

@@ -1,84 +0,0 @@
name: Publish dev
on:
schedule:
- cron: '0 */12 * * *'
workflow_dispatch:
jobs:
npm-publish:
name: npm publish
strategy:
fail-fast: false
matrix:
include:
- package: '@discordjs/brokers'
folder: 'brokers'
- package: '@discordjs/builders'
folder: 'builders'
- package: '@discordjs/collection'
folder: 'collection'
- package: '@discordjs/core'
folder: 'core'
- package: '@discordjs/formatters'
folder: 'formatters'
- package: 'discord.js'
folder: 'discord.js'
- package: '@discordjs/next'
folder: 'next'
- package: '@discordjs/proxy'
folder: 'proxy'
- package: '@discordjs/rest'
folder: 'rest'
- package: '@discordjs/util'
folder: 'util'
- package: '@discordjs/voice'
folder: 'voice'
- package: '@discordjs/ws'
folder: 'ws'
runs-on: ubuntu-latest
permissions:
id-token: write
env:
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
if: github.repository_owner == 'discordjs'
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install Node.js v20
uses: actions/setup-node@v4
with:
node-version: 20
registry-url: https://registry.npmjs.org/
- name: Check the current development version
id: release-check
run: |
if [[ $(npm view ${{ matrix.package }}@dev version | grep -e "$(git rev-parse --short HEAD)") ]]; \
then echo "RELEASE=0" >> "$GITHUB_OUTPUT"; \
else echo "RELEASE=1" >> "$GITHUB_OUTPUT"; \
fi
- name: Install dependencies
if: steps.release-check.outputs.release == '1'
uses: ./packages/actions/src/pnpmCache
- name: Build dependencies
if: steps.release-check.outputs.release == '1'
run: pnpm run build
- name: Publish package
if: steps.release-check.outputs.release == '1'
run: |
pnpm --filter=${{ matrix.package }} run release --preid "dev.$(date +%s)-$(git rev-parse --short HEAD)" --skip-changelog
pnpm --filter=${{ matrix.package }} publish --provenance --no-git-checks --tag dev || true
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_PUBLISH_TOKEN }}
- name: Deprecate prior development releases
if: steps.release-check.outputs.release == '1'
run: pnpm exec npm-deprecate --name "*dev*" --message "This version is deprecated. Please use a newer version." --package ${{ matrix.package }}
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_PUBLISH_TOKEN }}

View File

@@ -1,27 +0,0 @@
name: Publish docker images
on:
workflow_dispatch:
jobs:
docker-publish:
name: Docker publish
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install Node.js v20
uses: actions/setup-node@v4
with:
node-version: 20
- name: Install dependencies
uses: ./packages/actions/src/pnpmCache
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to DockerHub
run: echo ${{ secrets.DOCKER_ACCESS_TOKEN }} | docker login -u ${{ secrets.DOCKER_USERNAME }} --password-stdin
- name: Build & push docker image
run: docker build -f packages/proxy-container/Dockerfile -t discordjs/proxy:$(cut -d '.' -f1 <<< $(jq --raw-output '.version' packages/proxy-container/package.json)) --push .

View File

@@ -1,41 +0,0 @@
name: Publish Release
on:
release:
types: [released]
jobs:
npm-publish:
name: npm publish
runs-on: ubuntu-latest
permissions:
id-token: write
env:
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
if: github.repository_owner == 'discordjs'
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install Node.js v20
uses: actions/setup-node@v4
with:
node-version: 20
registry-url: https://registry.npmjs.org/
- name: Install dependencies
uses: ./packages/actions/src/pnpmCache
- name: Build dependencies
run: pnpm run build
- name: Extract package and semver from tag
id: extract-tag
uses: ./packages/actions/src/formatTag
with:
tag: ${{ github.ref_name }}
- name: Publish package
run: |
pnpm --filter=${{ steps.extract-tag.outputs.subpackage == 'true' && '@discordjs/' || '' }}${{ steps.extract-tag.outputs.package }} publish --provenance --no-git-checks
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_PUBLISH_TOKEN }}

View File

@@ -1,66 +0,0 @@
name: Tests
on:
push:
pull_request:
concurrency:
# Group based on workflow name and PR if it exists, if no PR, let it run so carryforward flags work
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
tests:
name: Tests
runs-on: ubuntu-latest
env:
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install Node.js v20
uses: actions/setup-node@v4
with:
node-version: 20
- name: Install dependencies
uses: ./packages/actions/src/pnpmCache
- name: Build dependencies (PR)
if: ${{ github.event_name != 'push' }}
run: pnpm exec turbo run build --filter="...[origin/${{ github.event_name == 'pull_request' && github.event.pull_request.base.ref || 'main' }}]" --concurrency=4
- name: Build dependencies (Push)
if: ${{ github.event_name == 'push' }}
run: pnpm exec turbo run build --filter="...[HEAD^1]" --concurrency=4
- name: Tests (PR)
if: ${{ github.event_name != 'push' }}
run: pnpm exec turbo run test --filter="...[origin/${{ github.event_name == 'pull_request' && github.event.pull_request.base.ref || 'main' }}]" --concurrency=4
- name: Tests (Push)
if: ${{ github.event_name == 'push' }}
run: pnpm exec turbo run test --filter="...[HEAD^1]" --concurrency=4
- name: ESLint (PR)
if: ${{ github.event_name != 'push' }}
run: pnpm exec turbo run lint --filter="...[origin/${{ github.event_name == 'pull_request' && github.event.pull_request.base.ref || 'main' }}]" --concurrency=4 -- --format=compact
- name: ESLint (Push)
if: ${{ github.event_name == 'push' }}
run: pnpm exec turbo run lint --filter="...[HEAD^1]" --concurrency=4 -- --format=compact
- name: Docs (PR)
if: ${{ github.event_name != 'push' }}
run: pnpm exec turbo run docs --filter="...[origin/${{ github.event_name == 'pull_request' && github.event.pull_request.base.ref || 'main' }}]" --concurrency=4
- name: Docs (Push)
if: ${{ github.event_name == 'push' }}
run: pnpm exec turbo run docs --filter="...[HEAD^1]" --concurrency=4
- name: Upload Coverage
if: github.repository_owner == 'discordjs'
uses: ./packages/actions/src/uploadCoverage
with:
codecov_token: ${{ secrets.CODECOV_TOKEN }}

64
.gitignore vendored
View File

@@ -1,54 +1,40 @@
# Packages
node_modules
# Created by https://www.gitignore.io
# Log files
hydrabot/config.json
hydrabot/authority.json
hydrabot/tokencache.json
esdoc/
.tmp/
### Node ###
# Logs
logs
*.log
npm-debug.log*
# Runtime data
pids
*.pid
*.seed
# Env
.env
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Dist
dist
dist-docs
# Miscellaneous
.tmp
.vscode/*
!.vscode/extensions.json
!.vscode/settings.json
.idea
.DS_Store
.turbo
tsconfig.tsbuildinfo
# Coverage directory used by tools like istanbul
coverage
out
package.tgz
tsup.config.bundled*
vitest.config.ts.timestamp*
# Deno
deno.lock
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bun
bun.lockb
# node-waf configuration
.lock-wscript
# yarn
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Cache
.prettiercache
.eslintcache
.vercel
# Dependency directory
# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git
node_modules
test/auth.json
examples/auth.json
docs/_build

View File

@@ -1 +0,0 @@
pnpm exec commitlint --edit $1

View File

@@ -1 +0,0 @@
pnpm run build:affected && pnpm exec lint-staged

View File

@@ -1,6 +0,0 @@
{
"$schema": "https://json.schemastore.org/lintstagedrc.schema.json",
"*": "prettier --ignore-unknown --write",
"{src/**,__tests__/**}.{mjs,js,cjs,ts,tsx}": "eslint --fix",
"src/**.ts": "vitest related --run --config ../../vitest.config.ts"
}

7
.npmignore Normal file
View File

@@ -0,0 +1,7 @@
.vscode/
docs/
examples/
web-dist/
src/
.travis.yml
TODO.md

6
.npmrc
View File

@@ -1,6 +0,0 @@
auto-install-peers=false
resolution-mode=highest
public-hoist-pattern[]=*eslint*
public-hoist-pattern[]=*prettier*
public-hoist-pattern[]=*@rushstack/node-core-library*
public-hoist-pattern[]=*jju*

View File

@@ -1,5 +0,0 @@
CODEOWNERS
CHANGELOG.md
tsup.config.bundled*
vitest.config.ts.timestamp*
pnpm-lock.yaml

View File

@@ -1,9 +0,0 @@
{
"$schema": "https://json.schemastore.org/prettierrc.json",
"printWidth": 120,
"useTabs": true,
"singleQuote": true,
"quoteProps": "as-needed",
"trailingComma": "all",
"endOfLine": "lf"
}

13
.travis.yml Normal file
View File

@@ -0,0 +1,13 @@
language: node_js
node_js:
- stable
cache:
directories:
- node_modules
branches:
only:
- master
- indev
before_install: npm install -g grunt-cli eslint
install: npm install
before_script: grunt --dev

View File

@@ -1,13 +0,0 @@
{
"recommendations": [
"esbenp.prettier-vscode",
"dbaeumer.vscode-eslint",
"tamasfe.even-better-toml",
"github.vscode-pull-request-github",
"codezombiech.gitignore",
"eamodio.gitlens",
"christian-kohler.npm-intellisense",
"christian-kohler.path-intellisense",
"unifiedjs.vscode-mdx"
]
}

30
.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,30 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "node",
"request": "launch",
"program": "./entrypoint.js",
"stopOnEntry": false,
"args": [],
"cwd": ".",
"runtimeExecutable": null,
"runtimeArgs": [
"--nolazy"
],
"env": {
"NODE_ENV": "development"
},
"externalConsole": false,
"sourceMaps": false,
"outDir": null
},
{
"name": "Attach",
"type": "node",
"request": "attach",
"port": 5858
}
]
}

35
.vscode/settings.json vendored
View File

@@ -1,31 +1,6 @@
// Place your settings in this file to overwrite default and user settings.
{
"eslint.validate": ["javascript", "javascriptreact", "typescript", "typescriptreact"],
"eslint.useFlatConfig": true,
"eslint.workingDirectories": [{ "directory": "${workspaceFolder}" }, { "pattern": "./packages/*/" }],
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": "never",
"source.fixAll.eslint": "explicit",
"source.fixAll": "explicit"
},
"editor.trimAutoWhitespace": false,
"files.associations": {
"api-extractor.json": "jsonc",
"api-extractor-docs.json": "jsonc",
"tsconfig.json": "jsonc",
"tsconfig.eslint.json": "jsonc",
"tsconfig.docs.json": "jsonc"
},
"files.insertFinalNewline": true,
"files.eol": "\n",
"npm.packageManager": "pnpm",
"typescript.tsdk": "node_modules/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true,
"unocss.disable": true,
"deno.enable": false,
"deno.enablePaths": ["./packages/create-discord-bot/template/Deno"],
"deno.lint": false,
"deno.unstable": [],
"deno.config": "./packages/create-discord-bot/template/Deno/deno.jsonc"
}
"editor.wrappingColumn": 0,
"editor.formatOnType": true,
"files.trimTrailingWhitespace": true
}

220
.vscode/tasks.json vendored Normal file
View File

@@ -0,0 +1,220 @@
// Available variables which can be used inside of strings.
// ${workspaceRoot}: the root folder of the team
// ${file}: the current opened file
// ${fileBasename}: the current opened file's basename
// ${fileDirname}: the current opened file's dirname
// ${fileExtname}: the current opened file's extension
// ${cwd}: the current working directory of the spawned process
// A task runner that calls the Typescript compiler (tsc) and
// Compiles a HelloWorld.ts program
{
"version": "0.1.0",
"command" : "babel",
"isShellCommand": true,
"tasks": [
{
"taskName": "watch",
"suppressTaskName": true,
"isBuildCommand": true,
"isWatching": true,
"args": [
"src", "--out-dir", "lib", "-w", "--loose=all"
]
}
]
}
// A task runner that calls the Typescript compiler (tsc) and
// compiles based on a tsconfig.json file that is present in
// the root of the folder open in VSCode
/*
{
"version": "0.1.0",
// The command is tsc. Assumes that tsc has been installed using npm install -g typescript
"command": "tsc",
// The command is a shell script
"isShellCommand": true,
// Show the output window only if unrecognized errors occur.
"showOutput": "silent",
// Tell the tsc compiler to use the tsconfig.json from the open folder.
"args": ["-p", "."],
// use the standard tsc problem matcher to find compile problems
// in the output.
"problemMatcher": "$tsc"
}
*/
// A task runner configuration for gulp. Gulp provides a less task
// which compiles less to css.
/*
{
"version": "0.1.0",
"command": "gulp",
"isShellCommand": true,
"tasks": [
{
"taskName": "less",
// Make this the default build command.
"isBuildCommand": true,
// Show the output window only if unrecognized errors occur.
"showOutput": "silent",
// Use the standard less compilation problem matcher.
"problemMatcher": "$lessCompile"
}
]
}
*/
// Uncomment the following section to use gulp in a watching mode that compiles a
// less file. The gulp task prints "[hh:mm:ss] Starting 'clean-styles'" to the console
// when existing css files get deleted and "[hh:mm:ss] Finished 'styles'" when the
// overall less compilation has finished. When the clean pattern is detect internal less
// problems are cleaned. When the finshed pattern is detected in the output less
// problems are published.
/*
{
"version": "0.1.0",
"command": "gulp",
"isShellCommand": true,
"tasks": [
{
"taskName": "watch-less",
// Make this the default build command.
"isBuildCommand": true,
// Show the output window only if unrecognized errors occur.
"showOutput": "silent",
// Task is running in watching mode.
"isWatching": true,
"problemMatcher": {
// Use the standard less compilation problem matcher as the base.
"base": "$lessCompile",
// A regular expression signalling that a watched task begins executing (usually triggered through file watching).
"watchedTaskBeginsRegExp": "^\\[\\d+:\\d+:\\d+\\] Starting 'clean-styles'\\.\\.\\.$",
// A regular expression signalling that a watched tasks ends executing.
"watchedTaskEndsRegExp": "^\\[\\d+:\\d+:\\d+\\] Finished 'styles' after \\d+"
}
}
]
}
*/
// Uncomment the following section to use jake to build a workspace
// cloned from https://github.com/Microsoft/TypeScript.git
/*
{
"version": "0.1.0",
// Task runner is jake
"command": "jake",
// Need to be executed in shell / cmd
"isShellCommand": true,
"showOutput": "silent",
"tasks": [
{
// TS build command is local.
"taskName": "local",
// Make this the default build command.
"isBuildCommand": true,
// Show the output window only if unrecognized errors occur.
"showOutput": "silent",
// Use the redefined Typescript output problem matcher.
"problemMatcher": [
"$tsc"
]
}
]
}
*/
// Uncomment the section below to use msbuild and generate problems
// for csc, cpp, tsc and vb. The configuration assumes that msbuild
// is available on the path and a solution file exists in the
// workspace folder root.
/*
{
"version": "0.1.0",
"command": "msbuild",
"args": [
// Ask msbuild to generate full paths for file names.
"/property:GenerateFullPaths=true"
],
"taskSelector": "/t:",
"showOutput": "silent",
"tasks": [
{
"taskName": "build",
// Show the output window only if unrecognized errors occur.
"showOutput": "silent",
// Use the standard MS compiler pattern to detect errors, warnings
// and infos in the output.
"problemMatcher": "$msCompile"
}
]
}
*/
// Uncomment the following section to use msbuild which compiles Typescript
// and less files.
/*
{
"version": "0.1.0",
"command": "msbuild",
"args": [
// Ask msbuild to generate full paths for file names.
"/property:GenerateFullPaths=true"
],
"taskSelector": "/t:",
"showOutput": "silent",
"tasks": [
{
"taskName": "build",
// Show the output window only if unrecognized errors occur.
"showOutput": "silent",
// Use the standard MS compiler pattern to detect errors, warnings
// and infos in the output.
"problemMatcher": [
"$msCompile",
"$lessCompile"
]
}
]
}
*/
// A task runner example that defines a problemMatcher inline instead of using
// a predfined one.
/*
{
"version": "0.1.0",
"command": "tsc",
"isShellCommand": true,
"args": ["HelloWorld.ts"],
"showOutput": "silent",
"problemMatcher": {
// The problem is owned by the typescript language service. Ensure that the problems
// are merged with problems produced by Visual Studio's language service.
"owner": "typescript",
// The file name for reported problems is relative to the current working directory.
"fileLocation": ["relative", "${cwd}"],
// The actual pattern to match problems in the output.
"pattern": {
// The regular expression. Matches HelloWorld.ts(2,10): error TS2339: Property 'logg' does not exist on type 'Console'.
"regexp": "^([^\\s].*)\\((\\d+|\\d+,\\d+|\\d+,\\d+,\\d+,\\d+)\\):\\s+(error|warning|info)\\s+(TS\\d+)\\s*:\\s*(.*)$",
// The match group that denotes the file containing the problem.
"file": 1,
// The match group that denotes the problem location.
"location": 2,
// The match group that denotes the problem's severity. Can be omitted.
"severity": 3,
// The match group that denotes the problem code. Can be omitted.
"code": 4,
// The match group that denotes the problem's message.
"message": 5
}
}
}
*/

7
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,7 @@
### Contributing
We welcome contributions, but we ask that you follow a few simple guidelines
1. Please check the indev branch to make sure the issue hasn't already been patched.
2. If the issue hasn't been patched, edit the files in the **src folder**
3. Prior to making the PR, build the lib files by running `grunt --dev`

15
LICENSE
View File

@@ -175,8 +175,18 @@
END OF TERMS AND CONDITIONS
Copyright 2021 Noel Buechler
Copyright 2015 Amish Shah
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@@ -189,3 +199,4 @@
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

140
README.md
View File

@@ -1,89 +1,77 @@
<div align="center">
<br />
<p>
<a href="https://discord.js.org"><img src="https://discord.js.org/static/logo.svg" width="546" alt="discord.js" /></a>
</p>
<br />
<p>
<a href="https://discord.gg/djs"><img src="https://img.shields.io/discord/222078108977594368?color=5865F2&logo=discord&logoColor=white" alt="Discord server" /></a>
<a href="https://www.npmjs.com/package/discord.js"><img src="https://img.shields.io/npm/v/discord.js.svg?maxAge=3600" alt="npm version" /></a>
<a href="https://www.npmjs.com/package/discord.js"><img src="https://img.shields.io/npm/dt/discord.js.svg?maxAge=3600" alt="npm downloads" /></a>
<a href="https://github.com/discordjs/discord.js/actions"><img src="https://github.com/discordjs/discord.js/actions/workflows/test.yml/badge.svg" alt="Tests status" /></a>
<a href="https://github.com/discordjs/discord.js/commits/main"><img src="https://img.shields.io/github/last-commit/discordjs/discord.js.svg?logo=github&logoColor=ffffff" alt="Last commit." /></a>
<a href="https://github.com/discordjs/discord.js/graphs/contributors"><img src="https://img.shields.io/github/contributors/discordjs/discord.js.svg?maxAge=3600&logo=github&logoColor=fff&color=00c7be" alt="contributors" /></a>
<a href="https://codecov.io/gh/discordjs/discord.js"><img src="https://codecov.io/gh/discordjs/discord.js/branch/main/graph/badge.svg?precision=2" alt="Code coverage" /></a>
</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>
<p align="center">
<a href="https://hydrabolt.github.io/discord.js">
<img alt="discord.js" src="http://hydrabolt.github.io/discord.js/res/logo.png" width="546">
</a>
</p>
## About
[![Build Status](https://travis-ci.org/hydrabolt/discord.js.svg)](https://travis-ci.org/hydrabolt/discord.js) [![Documentation Status](https://readthedocs.org/projects/discordjs/badge/?version=latest)](http://discordjs.readthedocs.org/en/latest/?badge=latest)
This repository contains multiple packages with separate [releases][github-releases]. You can find the assembled Discord API wrapper at [`discord.js`][source]. It is a powerful [Node.js](https://nodejs.org/en) module that allows you to easily interact with the [Discord API](https://discord.com/developers/docs/intro).
[![NPM](https://nodei.co/npm/discord.js.png?downloads=true&stars=true)](https://nodei.co/npm/discord.js/)
## Packages
- `discord.js` ([source][source]) - A powerful Node.js module for interacting with the Discord API
- `@discordjs/brokers` ([source][brokers-source]) - A collection of brokers for use with discord.js
- `@discordjs/builders` ([source][builders-source]) - A utility package for easily building Discord API payloads
- `@discordjs/collection` ([source][collection-source]) - A powerful utility data structure
- `@discordjs/core` ([source][core-source]) - A thinly abstracted wrapper around the core components of the Discord API
- `@discordjs/formatters` ([source][formatters-source]) - A collection of functions for formatting strings
- `@discordjs/proxy` ([source][proxy-source]) - A wrapper around `@discordjs/rest` for running an HTTP proxy
- `@discordjs/rest` ([source][rest-source]) - A module for interacting with the Discord REST API
- `@discordjs/voice` ([source][voice-source]) - A module for interacting with the Discord Voice API
- `@discordjs/util` ([source][util-source]) - A collection of utility functions
- `@discordjs/ws` ([source][ws-source]) - A wrapper around Discord's gateway
discord.js is a node module used as a way of interfacing with [Discord](https://discordapp.com/). It is a very useful module for creating bots.
## Links
### Installation
- [Website][website] ([source][website-source])
- [Documentation][documentation]
- [Guide][guide] ([source][guide-source])
Also see the v13 to v14 [Update Guide][guide-update], which includes updated and removed items from the library.
- [discord.js Discord server][discord]
- [Discord API Discord server][discord-api]
- [GitHub][source]
- [npm][npm]
- [Related libraries][related-libs]
**Requires node 0.12+**
### Extensions
`npm install --save discord.js`
- [RPC][rpc] ([source][rpc-source])
If you don't need voice support:
## Contributing
`npm install --save --no-optional discord.js`
Please read through our [contribution guidelines][contributing] before starting a pull request. We welcome contributions of all kinds, not just code! If you're stuck for ideas, look for the [good first issue][good-first-issue] label on issues in the repository. If you have any questions about the project, feel free to ask them on [Discord][discord]. Before creating your own issue or pull request, always check to see if one already exists! Don't rush contributions, take your time and ensure you're doing it correctly.
---
## Help
### Example: ping-pong
```js
var Discord = require("discord.js");
If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please join our [Discord server][discord].
var mybot = new Discord.Client();
[website]: https://discord.js.org
[website-source]: https://github.com/discordjs/discord.js/tree/main/apps/website
[documentation]: https://discord.js.org/docs
[guide]: https://discordjs.guide/
[guide-source]: https://github.com/discordjs/guide
[guide-update]: https://discordjs.guide/additional-info/changes-in-v14.html
[discord]: https://discord.gg/djs
[discord-api]: https://discord.gg/discord-api
[source]: https://github.com/discordjs/discord.js/tree/main/packages/discord.js
[npm]: https://www.npmjs.com/package/discord.js
[related-libs]: https://discord.com/developers/docs/topics/community-resources#libraries
[rpc]: https://www.npmjs.com/package/discord-rpc
[rpc-source]: https://github.com/discordjs/RPC
[contributing]: https://github.com/discordjs/discord.js/blob/main/.github/CONTRIBUTING.md
[github-releases]: https://github.com/discordjs/discord.js/releases
[brokers-source]: https://github.com/discordjs/discord.js/tree/main/packages/brokers
[builders-source]: https://github.com/discordjs/discord.js/tree/main/packages/builders
[collection-source]: https://github.com/discordjs/discord.js/tree/main/packages/collection
[core-source]: https://github.com/discordjs/discord.js/tree/main/packages/core
[formatters-source]: https://github.com/discordjs/discord.js/tree/main/packages/formatters
[proxy-source]: https://github.com/discordjs/discord.js/tree/main/packages/proxy
[rest-source]: https://github.com/discordjs/discord.js/tree/main/packages/rest
[voice-source]: https://github.com/discordjs/discord.js/tree/main/packages/voice
[util-source]: https://github.com/discordjs/discord.js/tree/main/packages/util
[ws-source]: https://github.com/discordjs/discord.js/tree/main/packages/ws
[good-first-issue]: https://github.com/discordjs/discord.js/contribute
mybot.on("message", function(message) {
if(message.content === "ping") {
mybot.reply(message, "pong");
}
});
mybot.loginWithToken("token");
// If you still need to login with email and password, use mybot.login("email", "password");
```
---
### Contributing
Feel free to contribute! Just clone the repo and edit the files in the **src folder, not the lib folder.**
Whenever you come to making a pull request, make sure it's to the *indev* branch and that you have built the lib files by running `grunt --dev`
---
### Related Projects
A list of other Discord API libraries [can be found here](https://discordapi.com/unofficial/libs.html)
---
### Links
**[Documentation](http://discordjs.readthedocs.org/en/latest/)**
**[GitHub](https://github.com/discord-js/discord.js)**
**[Wiki](https://github.com/discord-js/discord.js/wiki)**
**[Website](http://hydrabolt.github.io/discord.js/)**
**[NPM](http://npmjs.com/package/discord.js)**
---
### Contact
If you have an issue or want to know if a feature exists, [read the documentation](http://discordjs.readthedocs.org/en/latest/) before contacting me about any issues! If it's badly/wrongly implemented, let me know!
If you would like to contact me, you can create an issue on the GitHub repo, e-mail me via the one available on my NPM profile.
Alternatively, you could just send a DM to **hydrabolt** in [**Discord API**](https://discord.gg/0SBTUU1wZTYd2XyW).

8
TODO.md Normal file
View File

@@ -0,0 +1,8 @@
# Things yet to be implemented:
* Unbanning
* Re-ordering of roles (no effect, just aesthetics)
* Normalising attachments and embeds of messages
* Normalising parameter types
* More Documentation
* Voice Chat

View File

@@ -1,425 +0,0 @@
/**
* Config file for API Extractor. For more info, please visit: https://api-extractor.com
*/
{
"$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
/**
* Optionally specifies another JSON config file that this file extends from. This provides a way for
* standard settings to be shared across multiple projects.
*
* If the path starts with "./" or "../", the path is resolved relative to the folder of the file that contains
* the "extends" field. Otherwise, the first path segment is interpreted as an NPM package name, and will be
* resolved using NodeJS require().
*
* SUPPORTED TOKENS: none
* DEFAULT VALUE: ""
*/
// "extends": "./shared/api-extractor-base.json"
// "extends": "my-package/include/api-extractor-base.json"
/**
* Determines the "<projectFolder>" token that can be used with other config file settings. The project folder
* typically contains the tsconfig.json and package.json config files, but the path is user-defined.
*
* The path is resolved relative to the folder of the config file that contains the setting.
*
* The default value for "projectFolder" is the token "<lookup>", which means the folder is determined by traversing
* parent folders, starting from the folder containing api-extractor.json, and stopping at the first folder
* that contains a tsconfig.json file. If a tsconfig.json file cannot be found in this way, then an error
* will be reported.
*
* SUPPORTED TOKENS: <lookup>
* DEFAULT VALUE: "<lookup>"
*/
// "projectFolder": "..",
/**
* (REQUIRED) Specifies the .d.ts file to be used as the starting point for analysis. API Extractor
* analyzes the symbols exported by this module.
*
* The file extension must be ".d.ts" and not ".ts".
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
*/
"mainEntryPointFilePath": "<projectFolder>/dist-docs/index.d.ts",
/**
* A list of NPM package names whose exports should be treated as part of this package.
*
* For example, suppose that Webpack is used to generate a distributed bundle for the project "library1",
* and another NPM package "library2" is embedded in this bundle. Some types from library2 may become part
* of the exported API for library1, but by default API Extractor would generate a .d.ts rollup that explicitly
* imports library2. To avoid this, we can specify:
*
* "bundledPackages": [ "library2" ],
*
* This would direct API Extractor to embed those types directly in the .d.ts rollup, as if they had been
* local files for library1.
*/
"bundledPackages": [],
/**
* Determines how the TypeScript compiler engine will be invoked by API Extractor.
*/
"compiler": {
/**
* Specifies the path to the tsconfig.json file to be used by API Extractor when analyzing the project.
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* Note: This setting will be ignored if "overrideTsconfig" is used.
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: "<projectFolder>/tsconfig.json"
*/
// "tsconfigFilePath": "<projectFolder>/tsconfig.json",
/**
* Provides a compiler configuration that will be used instead of reading the tsconfig.json file from disk.
* The object must conform to the TypeScript tsconfig schema:
*
* http://json.schemastore.org/tsconfig
*
* If omitted, then the tsconfig.json file will be read from the "projectFolder".
*
* DEFAULT VALUE: no overrideTsconfig section
*/
"overrideTsconfig": {
"compilerOptions": {
// Type Checking
"allowUnreachableCode": false,
"allowUnusedLabels": false,
"exactOptionalPropertyTypes": true,
"noFallthroughCasesInSwitch": true,
"noImplicitOverride": true,
"noImplicitReturns": true,
"noPropertyAccessFromIndexSignature": false,
"noUncheckedIndexedAccess": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"strict": true,
// Modules
"allowArbitraryExtensions": false,
"allowImportingTsExtensions": false,
"module": "ESNext",
"moduleResolution": "nodenext",
"resolveJsonModule": true,
"resolvePackageJsonExports": false,
"resolvePackageJsonImports": false,
// Emit
"declaration": true,
"declarationMap": true,
"importHelpers": false,
"newLine": "lf",
"noEmitHelpers": true,
"outDir": "dist",
"removeComments": false,
"sourceMap": true,
// Interop Constraints
"esModuleInterop": false,
"forceConsistentCasingInFileNames": true,
"isolatedModules": true,
// Language and Environment
"experimentalDecorators": true,
"lib": ["ESNext"],
"target": "ES2022",
"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
* dependencies contain declarations that are incompatible with the TypeScript engine that API Extractor uses
* for its analysis. Where possible, the underlying issue should be fixed rather than relying on skipLibCheck.
*
* DEFAULT VALUE: false
*/
// "skipLibCheck": true,
},
/**
* Configures how the API report file (*.api.md) will be generated.
*/
"apiReport": {
/**
* (REQUIRED) Whether to generate an API report.
*/
"enabled": false
/**
* The filename for the API report files. It will be combined with "reportFolder" or "reportTempFolder" to produce
* a full file path.
*
* The file extension should be ".api.md", and the string should not contain a path separator such as "\" or "/".
*
* SUPPORTED TOKENS: <packageName>, <unscopedPackageName>
* DEFAULT VALUE: "<unscopedPackageName>.api.md"
*/
// "reportFileName": "<unscopedPackageName>.api.md",
/**
* Specifies the folder where the API report file is written. The file name portion is determined by
* the "reportFileName" setting.
*
* The API report file is normally tracked by Git. Changes to it can be used to trigger a branch policy,
* e.g. for an API review.
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: "<projectFolder>/temp/"
*/
// "reportFolder": "<projectFolder>/temp/",
/**
* Specifies the folder where the temporary report file is written. The file name portion is determined by
* the "reportFileName" setting.
*
* After the temporary file is written to disk, it is compared with the file in the "reportFolder".
* If they are different, a production build will fail.
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: "<projectFolder>/temp/"
*/
// "reportTempFolder": "<projectFolder>/temp/"
},
/**
* Configures how the doc model file (*.api.json) will be generated.
*/
"docModel": {
/**
* (REQUIRED) Whether to generate a doc model file.
*/
"enabled": true,
/**
* The output path for the doc model file. The file extension should be ".api.json".
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: "<projectFolder>/temp/<unscopedPackageName>.api.json"
*/
"apiJsonFilePath": "<projectFolder>/docs/docs.api.json"
},
/**
* Configures how the .d.ts rollup file will be generated.
*/
"dtsRollup": {
/**
* (REQUIRED) Whether to generate the .d.ts rollup file.
*/
"enabled": false,
/**
* Specifies the output path for a .d.ts rollup file to be generated without any trimming.
* This file will include all declarations that are exported by the main entry point.
*
* If the path is an empty string, then this file will not be written.
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: "<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.
* This file will include only declarations that are marked as "@public", "@beta", or "@alpha".
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: ""
*/
// "alphaTrimmedFilePath": "<projectFolder>/dist/<unscopedPackageName>-alpha.d.ts",
/**
* Specifies the output path for a .d.ts rollup file to be generated with trimming for a "beta" release.
* This file will include only declarations that are marked as "@public" or "@beta".
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: ""
*/
// "betaTrimmedFilePath": "<projectFolder>/dist/<unscopedPackageName>-beta.d.ts",
/**
* Specifies the output path for a .d.ts rollup file to be generated with trimming for a "public" release.
* This file will include only declarations that are marked as "@public".
*
* If the path is an empty string, then this file will not be written.
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: ""
*/
// "publicTrimmedFilePath": "<projectFolder>/dist/<unscopedPackageName>-public.d.ts",
/**
* When a declaration is trimmed, by default it will be replaced by a code comment such as
* "Excluded from this release type: exampleMember". Set "omitTrimmingComments" to true to remove the
* declaration completely.
*
* DEFAULT VALUE: false
*/
// "omitTrimmingComments": true
},
/**
* Configures how the tsdoc-metadata.json file will be generated.
*/
"tsdocMetadata": {
/**
* Whether to generate the tsdoc-metadata.json file.
*
* DEFAULT VALUE: true
*/
// "enabled": true,
/**
* Specifies where the TSDoc metadata file should be written.
*
* The path is resolved relative to the folder of the config file that contains the setting; to change this,
* prepend a folder token such as "<projectFolder>".
*
* The default value is "<lookup>", which causes the path to be automatically inferred from the "tsdocMetadata",
* "typings" or "main" fields of the project's package.json. If none of these fields are set, the lookup
* falls back to "tsdoc-metadata.json" in the package folder.
*
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
* DEFAULT VALUE: "<lookup>"
*/
// "tsdocMetadataFilePath": "<projectFolder>/dist/tsdoc-metadata.json"
},
/**
* Specifies what type of newlines API Extractor should use when writing output files. By default, the output files
* will be written with Windows-style newlines. To use POSIX-style newlines, specify "lf" instead.
* To use the OS's default newline kind, specify "os".
*
* DEFAULT VALUE: "crlf"
*/
"newlineKind": "lf",
/**
* Configures how API Extractor reports error and warning messages produced during analysis.
*
* There are three sources of messages: compiler messages, API Extractor messages, and TSDoc messages.
*/
"messages": {
/**
* Configures handling of diagnostic messages reported by the TypeScript compiler engine while analyzing
* the input .d.ts files.
*
* TypeScript message identifiers start with "TS" followed by an integer. For example: "TS2551"
*
* DEFAULT VALUE: A single "default" entry with logLevel=warning.
*/
"compilerMessageReporting": {
/**
* Configures the default routing for messages that don't match an explicit rule in this table.
*/
"default": {
/**
* Specifies whether the message should be written to the the tool's output log. Note that
* the "addToApiReportFile" property may supersede this option.
*
* Possible values: "error", "warning", "none"
*
* Errors cause the build to fail and return a nonzero exit code. Warnings cause a production build fail
* and return a nonzero exit code. For a non-production build (e.g. when "api-extractor run" includes
* the "--local" option), the warning is displayed but the build will not fail.
*
* DEFAULT VALUE: "warning"
*/
"logLevel": "warning"
/**
* When addToApiReportFile is true: If API Extractor is configured to write an API report file (.api.md),
* then the message will be written inside that file; otherwise, the message is instead logged according to
* the "logLevel" option.
*
* DEFAULT VALUE: false
*/
// "addToApiReportFile": false
}
// "TS2551": {
// "logLevel": "warning",
// "addToApiReportFile": true
// },
//
// . . .
},
/**
* Configures handling of messages reported by API Extractor during its analysis.
*
* API Extractor message identifiers start with "ae-". For example: "ae-extra-release-tag"
*
* DEFAULT VALUE: See api-extractor-defaults.json for the complete table of extractorMessageReporting mappings
*/
"extractorMessageReporting": {
"default": {
"logLevel": "warning"
// "addToApiReportFile": false
},
// Disable the following warning:
// (ae-missing-release-tag) "x" is part of the package's API, but it is missing a release tag (@alpha, @beta, @public, or @internal)
"ae-missing-release-tag": {
"logLevel": "none"
}
// "ae-extra-release-tag": {
// "logLevel": "warning",
// "addToApiReportFile": true
// },
//
// . . .
},
/**
* Configures handling of messages reported by the TSDoc parser when analyzing code comments.
*
* TSDoc message identifiers start with "tsdoc-". For example: "tsdoc-link-tag-unescaped-text"
*
* DEFAULT VALUE: A single "default" entry with logLevel=warning.
*/
"tsdocMessageReporting": {
"default": {
"logLevel": "warning"
// "addToApiReportFile": false
}
// "tsdoc-link-tag-unescaped-text": {
// "logLevel": "warning",
// "addToApiReportFile": true
// },
//
// . . .
}
}
}

View File

@@ -1,36 +0,0 @@
{
"$schema": "https://biomejs.dev/schemas/1.5.3/schema.json",
"formatter": {
"enabled": true,
"formatWithErrors": false,
"indentStyle": "tab",
"indentWidth": 2,
"lineWidth": 120,
"lineEnding": "lf",
"ignore": [
".turbo",
".vercel",
".contentlayer",
".next",
"coverage",
"dist",
"dist-docs",
"docs",
"CHANGELOG.md",
"tsup.config.bundled*"
]
},
"javascript": {
"formatter": {
"enabled": true,
"quoteStyle": "single",
"quoteProperties": "asNeeded",
"trailingComma": "all",
"semicolons": "always"
}
},
"files": {
"ignoreUnknown": true,
"maxSize": 1000000
}
}

View File

@@ -1,27 +0,0 @@
codecov:
notify:
after_n_builds: 6
strict_yaml_branch: main
coverage:
range: '50...90'
status:
project:
default:
target: auto
threshold: 5%
informational: true
patch: off
flag_management:
default_rules:
carryforward: true
statuses:
- type: project
target: auto
threshold: 2%
informational: true
comment:
require_changes: true
after_n_builds: 6

192
docs/Makefile Normal file
View File

@@ -0,0 +1,192 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " applehelp to make an Apple Help Book"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
@echo " coverage to run coverage check of the documentation (if enabled)"
clean:
rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/discordjs.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/discordjs.qhc"
applehelp:
$(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp
@echo
@echo "Build finished. The help book is in $(BUILDDIR)/applehelp."
@echo "N.B. You won't be able to view it unless you put it in" \
"~/Library/Documentation/Help or install it in your application" \
"bundle."
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/discordjs"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/discordjs"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
coverage:
$(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage
@echo "Testing of coverage in the sources finished, look at the " \
"results in $(BUILDDIR)/coverage/python.txt."
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."

292
docs/conf.py Normal file
View File

@@ -0,0 +1,292 @@
# -*- coding: utf-8 -*-
#
# discord.js documentation build configuration file, created by
# sphinx-quickstart on Fri Sep 25 17:25:49 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import shlex
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'discord.js'
copyright = u'2015-2016, hydrabolt'
author = u'hydrabolt'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '8.2.0'
# The full version, including alpha/beta/rc tags.
release = '8.2.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
#html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
#html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'discordjsdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'discordjs.tex', u'discord.js Documentation',
u'hydrabolt', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'discordjs', u'discord.js Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'discordjs', u'discord.js Documentation',
author, 'discordjs', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
if not os.environ.get('READTHEDOCS', None) == 'True':
try:
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
except ImportError:
print("sphinx_rtd_theme not found! Do 'pip install sphinx_rtd_theme' to make local builds use the RTD theme.")

61
docs/docs_cache.rst Normal file
View File

@@ -0,0 +1,61 @@
.. include:: ./vars.rst
Cache
=====
**extends Array**
A Cache object extends an Array (so it can be used like a regular array) but introduces helper functions to make it more useful when developing with discord.js. Unlike a regular array, it doesn't care about the instance or prototype of an object, it works purely on properties.
**Examples:**
.. code-block:: js
client.users.get("id", 11238414);
client.channels.getAll("name", "general");
--------
Functions
---------
get(key, value)
~~~~~~~~~~~~~~~
Returns a contained object where ``object[key] == value``. Also works if value is a regex or a function. Returns the first object found that matches the criteria.
get(value)
~~~~~~~~~~
Returns a contained object where ``object["id"] == value``. Shorthand for ``get("id", value)``. Returns ``null`` if ID is not found.
getAll(key, value)
~~~~~~~~~~~~~~~~~~
Similar to ``cache.get(key, value)``, but returns a Cache of any objects that meet the criteria.
has(key, value)
~~~~~~~~~~~~~~~
Returns `true` if there is an object that meets the condition ``object[key] == value`` in the cache
add(data)
~~~~~~~~~
Adds an object to the Cache as long as all the other objects in the cache don't have the same ID as it.
update(old, data)
~~~~~~~~~~~~~~~~~
Updates an old object in the Cache (if it exists) with the new one.
remove(data)
~~~~~~~~~~~~
Removes an object from the cache if it exists.
random()
~~~~~~~~~~~~
Get a random object from the cache.

43
docs/docs_channel.rst Normal file
View File

@@ -0,0 +1,43 @@
.. include:: ./vars.rst
Channel
=======
**extends** Equality_
The Channel class is the base class for all types of channel.
--------
Attributes
----------
id
~~
The ID of the channel, a `String`.
client
~~~~~~
The Client_ that cached the channel.
isPrivate
~~~~~~~~~
Indicates whether the channel is PM channel, is `Boolean`.
createdAt
~~~~~~~~~
A `Date` referring to when the channel was created.
--------
Functions
---------
delete()
~~~~~~~~~~~~~~~
Deletes the channel.

View File

@@ -0,0 +1,42 @@
.. include:: ./vars.rst
ChannelPermissions
==================
ChannelPermissions is used to represent the final permissions of a user in a channel, to see exactly what they are and aren't allowed to do.
**Examples:**
.. code-block:: js
var user_permissions = channel.permissionsOf(user);
var can_mention_everyone = user_permissions.hasPermission("mentionEveryone");
--------
Functions
---------
serialize()
~~~~~~~~~~~
**Aliases:** `serialise`
Returns an object containing permission names and values. E.g:
.. code-block:: js
{
createInstantInvite : true,
kickMembers : false
}
For more on valid permission names, see `Permission Constants`_.
hasPermission(permission)
~~~~~~~~~~~~~~~~~~~~~~~~~
Sees whether the user has the permission given.
- **permission** - See `Permission Constants`_ for valid permission names.

1042
docs/docs_client.rst Executable file

File diff suppressed because it is too large Load Diff

26
docs/docs_equality.rst Normal file
View File

@@ -0,0 +1,26 @@
.. include:: ./vars.rst
Equality
========
The Equality class is used to see if two objects are equal, based on ``object_1.id === object_2.id``.
If any class in Discord extends equality, it means you should never the default equality operands (``==`` & ``===``) as they could potentially be different instances and therefore appear not to be equal. Instead, use ``equalityObject.equals()`` as shown below.
.. code-block:: js
object1.equals(object2); // GOOD ✓
object1 == object2; // BAD ✖
--------
Functions
---------
equals(object)
~~~~~~~~~~~~~~
Returns true if the specified object is the same as this one.
- **object** - Any `object` with an ``id`` property.

91
docs/docs_invite.rst Normal file
View File

@@ -0,0 +1,91 @@
.. include:: ./vars.rst
Invite
======
Used to represent data of an invite.
--------
Attributes
----------
maxAge
~~~~~~
`Number`, how long (in seconds) the invite has since creation before expiring.
code
~~~~
`String`, the invite code.
server
~~~~~~
The Server_ the invite is for.
channel
~~~~~~~
The ServerChannel_ the invite is for.
revoked
~~~~~~~
`Boolean`, whether the invite has been revoked or not.
createdAt
~~~~~~~~~
`Number`, timestamp of when the invite was created.
temporary
~~~~~~~~~
`Boolean`, whether the invite is temporary or not.
uses
~~~~
`Number`, uses of the invite remaining.
maxUses
~~~~~~~
`Number`, maximum uses of the invite.
inviter
~~~~~~~
User_ who sent/created the invite.
xkcd
~~~~
`Boolean`, whether the invite is intended to be easy to read and remember by a human.
--------
Functions
---------
toString()
~~~~~~~~~~
Returns the invite URL.
delete(`callback`)
~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.deleteInvite(invite, callback)``
| **See** client.deleteInvite_
join(`callback`)
~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.joinServer(invite, callback)``
| **See** client.joinServer_
.. _client.deleteInvite : ./docs_client.html#deleteinvite-invite-callback
.. _client.joinServer : ./docs_client.html#joinserver-invite-callback

149
docs/docs_message.rst Normal file
View File

@@ -0,0 +1,149 @@
.. include:: ./vars.rst
Message
=======
**extends** Equality_
A Message object is used to represent the data of a message.
--------
Attributes
----------
channel
~~~~~~~
The channel the message was sent in, either a TextChannel_ or PMChannel_.
server
~~~~~~~
The Server_ the message was sent in. Will be undefined if the message was sent in a PMChannel_.
client
~~~~~~
The Client_ that cached the message.
attachments
~~~~~~~~~~~
A raw array of attachment objects.
tts
~~~
`Boolean`, true if the message was text-to-speech.
embeds
~~~~~~
A raw array of embed objects.
timestamp
~~~~~~~~~
`Number`, timestamp of when the message was sent.
everyoneMentioned
~~~~~~~~~~~~~~~~~
`Boolean`, true if ``@everyone`` was mentioned.
id
~~
`String`, ID of the message.
editedTimestamp
~~~~~~~~~~~~~~~
Timestamp on when the message was last edited, `Number`. Potentially null.
author
~~~~~~
**Alias:** `sender`
The User_ that sent the message.
content
~~~~~~~
`String`, content of the message.
cleanContent
~~~~~~~
`String`, content of the message with valid user mentions (<@123>) replaced with "@username".
mentions
~~~~~~~~
A array of User_ objects that were mentioned in the message.
pinned
~~~~~~
`Boolean`, true if the message is pinned to its channel.
Functions
---------
isMentioned(user)
~~~~~~~~~~~~~~~~~
Returns true if the given user was mentioned in the message.
- **user** - A `User Resolvable`_
toString()
~~~~~~~~~~
Returns the content of the Message.
delete(`options`, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.deleteMessage(message, options, callback)``
| **See** client.deleteMessage_
update(content, `options`, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.updateMessage(message, content, options, callback)``
| **Aliases** `edit`
| **See** client.updateMessage_
reply(content, `options`, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.reply(message, content, options, callback)``
| **See** client.reply_
replyTTS(content, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.replyTTS(message, content, callback)``
| **See** client.replyTTS_
pin(`callback`)
~~~~~~~~~~~~~~~
| **Shortcut of** ``client.pinMessage(message, callback)``
| **See** client.pinMessage_
unpin(`callback`)
~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.unpinMessage(message, callback)``
| **See** client.unpinMessage_
.. _client.deleteMessage : ./docs_client.html#deletemessage-message-options-callback
.. _client.updateMessage : ./docs_client.html#updatemessage-message-content-options-callback
.. _client.reply : ./docs_client.html#reply-message-content-options-callback
.. _client.replyTTS : ./docs_client.html#replytts-message-content-callback
.. _client.pinMessage : ./docs_client.html#pinmessage-message-callback
.. _client.unpinMessage : ./docs_client.html#unpinmessage-message-callback

View File

@@ -0,0 +1,58 @@
.. include:: ./vars.rst
Permission Constants
====================
In discord.js, you can handle permissions in two ways. The preferred way is to just use the string name of the permission, alternatively you can use ``Discord.Constants.Permissions["permission name"]``.
--------
Valid Permission Names
----------------------
.. code-block:: js
{
// general
administrator,
createInstantInvite,
kickMembers,
banMembers,
manageRoles,
managePermissions,
manageChannels,
manageChannel,
manageServer,
changeNickname,
manageNicknames,
// text
readMessages,
sendMessages,
sendTTSMessages,
manageMessages,
embedLinks,
attachFiles,
readMessageHistory,
mentionEveryone,
// voice
voiceConnect,
voiceSpeak,
voiceMuteMembers,
voiceDeafenMembers,
voiceMoveMembers,
voiceUseVAD
};
Preferred Way
-------------
The preferred way of using permissions in discord.js is to just use the name. E.g:
``role.hasPermission("voiceUseVAD")``
Alternative
-----------
You can also go the long way round and use the numerical permission like so:
``role.hasPermission( Discord.Constants.Permissions.voiceUseVAD )``

View File

@@ -0,0 +1,31 @@
.. include:: ./vars.rst
PermissionOverwrite
===================
PermissionOverwrite is used to represent data about permission overwrites for roles or users in channels.
--------
Attributes
----------
id
~~
`String`, the ID of the PermissionOverwrite. If ``overwrite.type`` is ``role``, this is the role's ID. Otherwise, it is a User_ overwrite.
type
~~~~
`String`, type of the overwrite. Either ``member`` or ``role``.
allowed
~~~~~~~
Returns the permissions explicitly allowed by the overwrite. An `Array` of Strings, which are names of permissions. More can be found at `Permission Constants`_
denied
~~~~~~
Returns the permissions explicitly denied by the overwrite. An `Array` of Strings, which are names of permissions. More can be found at `Permission Constants`_

90
docs/docs_pmchannel.rst Normal file
View File

@@ -0,0 +1,90 @@
.. include:: ./vars.rst
PMChannel
=========
**extends** Channel_
A PMChannel is a Private/Direct channel between the Client and another user.
--------
Attributes
----------
messages
~~~~~~~~
A Cache_ of Message_ objects.
recipient
~~~~~~~~~
The User_ that is the recipient of the Channel.
lastMessage
~~~~~~~~~~~
The last Message_ sent in the channel, may be null if no messages have been sent during the time the bound Client_ has been online.
--------
Functions
---------
toString()
~~~~~~~~~~
Returns a mention of the recipient.
sendMessage(content, `options`, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.sendMessage(channel, content, options, callback)``
| **Aliases** `send`
| **See** client.sendMessage_
sendTTSMessage(content, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.sendTTSMessage(channel, content, callback)``
| **Aliases** `sendTTS`
| **See** client.sendTTSMessage_
sendFile(attachment, name, content, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.sendFile(channel, attachment, name, content, callbasck)``
| **See** client.sendFile_
startTyping(`callback`)
~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.startTyping(channel, callback)``
| **See** client.startTyping_
stopTyping(`callback`)
~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.stopTyping(channel, callback)``
| **See** client.stopTyping_
getLogs(`limit`, `options`, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.getChannelLogs(channel, limit, options, callback)``
| **See** client.getChannelLogs_
getMessage(messageID, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.getMessage(channel, messageID, callback)``
| **See** client.getMessage_
.. _client.sendMessage : ./docs_client.html#sendmessage-channel-content-options-callback
.. _client.sendTTSMessage : ./docs_client.html#sendttsmessage-channel-content-callback
.. _client.sendFile : ./docs_client.html#sendfile-channel-attachment-name-content-callback
.. _client.startTyping : ./docs_client.html#starttyping-channel-callback
.. _client.stopTyping : ./docs_client.html#stoptyping-channel-callback
.. _client.getChannelLogs : ./docs_client.html#getchannellogs-channel-limit-options-callback
.. _client.getMessage : ./docs_client.html#getmessage-channel-messageid-callback

100
docs/docs_resolvables.rst Normal file
View File

@@ -0,0 +1,100 @@
.. include:: ./vars.rst
Resolvables
===========
In discord.js, the aim is to allow the end developer to have freedom in what sort of data types they supply. References to any sort of resolvable basically mean what types of data you can provide. The different resolvables are shown before:
--------
Channel Resolvable
------------------
A Channel Resolvable allows:
- Channel_
- Server_
- Message_
- User_ (in some instances)
- String of Channel ID
- String of User ID
File Resolvable
---------------
A File Resolvable allows:
- URL
- Local file path
- Readable stream
Role Resolvable
---------------
A Role Resolvable allows:
- Role ID
- Role_
Voice Channel Resolvable
------------------------
A Voice Channel Resolvable allows:
- VoiceChannel_
- Voice Channel ID
Message Resolvable
------------------
A Message Resolvable allows:
- Message_
- TextChannel_
- PMChannel_
User Resolvable
---------------
A User Resolvable allows:
- User_
- Message_
- TextChannel_
- PMChannel_
- Server_
- String of User ID
String Resolvable
-----------------
A String Resolvable allows:
- Array
- String
Server Resolvable
-----------------
A Server Resolvable allows:
- Server_
- ServerChannel_
- Message_ (only for messages from server channels)
- String of Server ID
Invite ID Resolvable
--------------------
An Invite ID Resolvable allows:
- Invite_
- String containing either a http link to the invite or the invite code on its own.
Base64 Resolvable
-----------------
A Base64 Resolvable allows:
- Buffer
- String

115
docs/docs_role.rst Normal file
View File

@@ -0,0 +1,115 @@
.. include:: ./vars.rst
Role
====
Represents data for a Server Role.
--------
Attributes
----------
position
~~~~~~~~
`Number`, position of the role when viewing the roles of a server.
name
~~~~
`String`, name of the role.
managed
~~~~~~~
`Boolean`, whether Discord has created the role itself. Currently only used for Twitch integration.
id
~~
`String`, ID of the role.
hoist
~~~~~
`Boolean`, whether the role should be displayed as a separate category in the users section.
color
~~~~~
`Number`, a base 10 colour. Use ``role.colorAsHex()`` to get a hex colour instead.
server
~~~~~~
The Server_ the role belongs to.
client
~~~~~~
The Client_ that cached the role.
createdAt
~~~~~~~~~
A `Date` referring to when the role was created.
Functions
---------
serialise()
~~~~~~~~~~~
**Aliases:** `serialize`
Makes an object with the permission names found in `Permission Constants`_ and a boolean value for them.
hasPermission(permission)
~~~~~~~~~~~~~~~~~~~~~~~~~
Sees whether the role has the permission given.
- **permission** - See `Permission Constants`_ for valid permission names.
colorAsHex()
~~~~~~~~~~~~
Returns the role's colour as hex, e.g. ``#FF0000``.
mention()
~~~~~~~~~
Returns a valid string that can be sent in a message to mention the role. By default, ``role.toString()`` does this so by adding a role object to a string, e.g. ``role + ""``, their mention code will be retrieved. If the role isn't mentionable, its name gets returned.
delete()
~~~~~~~~
| **Shortcut of** ``client.deleteRole(role)``
| **See** client.deleteRole_
update(data)
~~~~~~~~~~~~
| **Shortcut of** ``client.updateRole(role, data)``
| **Aliases** `edit`
| **See** client.updateRole_
addMember(member, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.addMemberToRole(member, roles, callback)``
| **Aliases** `addUser`
| **See** client.addMemberToRole_
removeMember(member, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.removeMemberFromRole(member, roles, callback)``
| **Aliases** `removeUser`
| **See** client.removeMemberFromRole_
.. _client.deleteRole : ./docs_client.html#deleterole-role-callback
.. _client.updateRole : ./docs_client.html#updaterole-role-data-callback
.. _client.addMemberToRole : ./docs_client.html#addmembertorole-member-role-callback
.. _client.removeMemberFromRole : ./docs_client.html#removememberfromrole-member-role-callback

189
docs/docs_server.rst Normal file
View File

@@ -0,0 +1,189 @@
.. include:: ./vars.rst
Server
======
**extends** Equality_
Stores information about a Discord Server.
--------
Attributes
----------
client
~~~~~~
The Client_ that cached the Server.
region
~~~~~~
`String`, region of the server.
name
~~~~
`String`, name of the server.
id
~~
`String`, ID of the server - never changes.
members
~~~~~~~
Members of the server, a Cache_ of User_ objects.
channels
~~~~~~~~
Channels in the server, a Cache_ of ServerChannel_ objects.
roles
~~~~~
Roles of the server, a Cache_ of Role_ objects.
icon
~~~~
ID/Hash of server icon, use ``server.iconURL`` for an URL to the icon.
afkTimeout
~~~~~~~~~~
`Number`, the AFK timeout in seconds before a user is classed as AFK. If there isn't an AFK timeout, this will be null.
afkChannel
~~~~~~~~~~
The channel where AFK users are moved to, ServerChannel_ object. If one isn't set, this will be null.
defaultChannel
~~~~~~~~~~~~~~
**Aliases** `generalChannel, general`
The ``#general`` ServerChannel_ of the server.
owner
~~~~~
The founder of the server, a User_ object.
iconURL
~~~~~~~
The URL of the Server's icon. If the server doesn't have an icon, this will be null.
createdAt
~~~~~~~~~
A `Date` referring to when the server was created.
Functions
---------
rolesOfUser(user)
~~~~~~~~~~~~~~~~~
**Aliases**: `rolesOf`, `rolesOfMember`
Returns an array of the roles affecting a user server-wide.
usersWithRole(role)
~~~~~~~~~~~~~~~~~
**Aliases**: `membersWithRole`
Returns an array of users that have the specified role.
detailsOfUser(user)
~~~~~~~~~~~~~~~~~~~
**Aliases** `detailsOf`, `detailsOfMember`
Returns an object containing metadata of a user within the server, containing a structure similar to the following:
.. code-block:: js
{
joinedAt: 1449339323747,
roles: [],
mute: false,
selfMute: false,
deaf: false,
selfDeaf: false,
nick: 'Nickname'
}
leave()
~~~~~~~
| **Shortcut of** ``client.leaveServer(server)``
| **Aliases** `delete`
| **See** client.leaveServer_
createInvite(`options`, `callback`)
~~~~~~~
| **Shortcut of** ``client.createInvite(server, options, callback)``
| **See** client.createInvite_
createRole(`data`, `callback`)
~~~~~~~
| **Shortcut of** ``client.createRole(server, data, callback)``
| **See** client.createRole_
createChannel(name, `type`, `callback`)
~~~~~~~
| **Shortcut of** ``client.createChannel(server, name, type, callback)``
| **See** client.createChannel_
getBans(`callback`)
~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.getBans(server, callback)``
| **See** client.getBans_
banMember(user, `length`, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.banMember(member, server, length, callback)``
| **Aliases** `banUser, ban`
| **See** client.banMember_
unbanMember(user, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.unbanMember(member, server, callback)``
| **Aliases** `unbanUser, unban`
| **See** client.unbanMember_
kickMember(user, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.kickMember(member, server, callback)``
| **Aliases** `kickUser, kick`
| **See** client.kickMember_
setNickname(nickname, user, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.setNickname(server, nickname, user, callback)``
| **See** client.setNickname_
.. _client.leaveServer : ./docs_client.html#leaveserver-server-callback
.. _client.createInvite : ./docs_client.html#createinvite-channel-options-callback
.. _client.createRole : ./docs_client.html#createrole-server-data-callback
.. _client.createChannel : ./docs_client.html#createchannel-server-name-type-callback
.. _client.banMember : ./docs_client.html#banmember-user-server-length-callback
.. _client.unbanMember : ./docs_client.html#unbanmember-user-server-callback
.. _client.kickMember : ./docs_client.html#kickmember-user-server-callback
.. _client.setNickname : ./docs_client.html#setNickname-server-nickname-user-callback
.. _client.getBans : ./docs_client.html#getbans-server-callback

View File

@@ -0,0 +1,59 @@
.. include:: ./vars.rst
ServerChannel
=============
**extends** Channel_
A ServerChannel is a Channel_ that belongs to a Server_.
--------
Attributes
----------
name
~~~~
`String`, name of the channel.
type
~~~~
`String`, either ``voice`` or ``text``.
position
~~~~~~~~
`Number`, position in the channel list.
permissionOverwrites
~~~~~~~~~~~~~~~~~~~~
Cache_ of all the PermissionOverwrite_ objects affecting the channel.
server
~~~~~~
Server_ the channel belongs to.
Functions
---------
permissionsOf(userOrRole)
~~~~~~~~~~~~~~~~~~~
**Aliases:** permsOf
Returns a ChannelPermissions_ object of a user or role's permissions in that channel.
mention()
~~~~~~~~~
Returns a `string` that can be used in discord messages to mention a channel. `serverChannel.toString()` defaults to this.
update(data, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.updateChannel(channel, data, callback)``
| **See** client.updateChannel_

99
docs/docs_textchannel.rst Normal file
View File

@@ -0,0 +1,99 @@
.. include:: ./vars.rst
TextChannel
===========
**extends** ServerChannel_
A text channel of a server.
--------
Attributes
----------
topic
~~~~~
The topic of the channel, a `String`.
lastMessage
~~~~~~~~~~~
Last Message_ sent in the channel. May be null if no messages sent whilst the Client was online.
messages
~~~~~~~~
A Cache_ of Message_ objects.
--------
Functions
---------
setTopic(topic, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.setChannelTopic(channel, topic, callback)``
| **See** client.setChannelTopic_
setNameAndTopic(name, topic, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.setChannelNameAndTopic(channel, name, topic, callback)``
| **See** client.setChannelNameAndTopic_
sendMessage(content, `options`, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.sendMessage(channel, content, options, callback)``
| **Aliases** `send`
| **See** client.sendMessage_
sendTTSMessage(content, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.sendTTSMessage(channel, content, callback)``
| **Aliases** `sendTTS`
| **See** client.sendTTSMessage_
sendFile(attachment, name, content, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.sendFile(channel, attachment, name, content, callbasck)``
| **See** client.sendFile_
startTyping(`callback`)
~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.startTyping(channel, callback)``
| **See** client.startTyping_
stopTyping(`callback`)
~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.stopTyping(channel, callback)``
| **See** client.stopTyping
getLogs(`limit`, `options`, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.getChannelLogs(channel, limit, options, callback)
| **See** client.getChannelLogs_
getMessage(messageID, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.getMessage(channel, messageID, callback)``
| **See** client.getMessage_
.. _client.sendMessage : ./docs_client.html#sendmessage-channel-content-options-callback
.. _client.sendTTSMessage : ./docs_client.html#sendttsmessage-channel-content-callback
.. _client.sendFile : ./docs_client.html#sendfile-channel-attachment-name-content-callback
.. _client.startTyping : ./docs_client.html#starttyping-channel-callback
.. _client.stopTyping : ./docs_client.html#stoptyping-channel-callback
.. _client.getChannelLogs : ./docs_client.html#getchannellogs-channel-limit-options-callback
.. _client.getMessage : ./docs_client.html#getmessage-channel-messageid-callback
.. _client.setChannelTopic : ./docs_client.html#setchanneltopic-channel-topic-callback
.. _client.setChannelNameAndTopic : ./docs_client.html#setchannelnameandtopic-channel-name-topic-callback

180
docs/docs_user.rst Executable file
View File

@@ -0,0 +1,180 @@
.. include:: ./vars.rst
User
====
**extends** Equality_
Stores information about users.
--------
Attributes
----------
client
~~~~~~
The Client_ that created the user.
username
~~~~~~~~
_Alias_ : ``name``
`String`, username of the User.
discriminator
~~~~~~~~~~~~~
`Integer` from 0-9999, don't use this to identify users. Used to separate the user from the 9998 others that may have the same username. Made redundant by ``user.id``.
id
~~
`String` (do not parse to an Integer, will become inaccurate). The ID of a user, never changes.
avatar
~~~~~~
`String`, the ID/hash of a user's avatar. To get a path to their avatar, see ``user.avatarURL``.
status
~~~~~~
The status of a user, `String`. Either ``online``, ``offline`` or ``idle``.
game
~~~~
The game object of a user. `null` if not playing a game, otherwise `Object` containing the following values:
.. code-block:: js
{
name : 'Game Name' //Name of game user is playing
}
typing
~~~~~~
`Object` containing the following values:
.. code-block:: js
{
since : 1448038288519, //timestamp of when
channel : <Channel Object> // channel they are typing in.
}
avatarURL
~~~~~~~~~
A valid URL to the user's avatar if they have one, otherwise null.
bot
~~~
A boolean that represents if the user is an official OAuth bot account or not.
voiceChannel
~~~~~~~~~~~~
The VoiceChannel_ the user is connected to. If they aren't in any voice channels, this will be ``null``.
createdAt
~~~~~~~~~
A `Date` referring to when the user was created.
note
~~~~
The note of the user, `String`.
speaking
~~~~~~~~
A boolean that represents whether or not the user is speaking in a voice channel, default is `false`.
Functions
---------
mention()
~~~~~~~~~
Returns a valid string that can be sent in a message to mention the user. By default, ``user.toString()`` does this so by adding a user object to a string, e.g. ``user + ""``, their mention code will be retrieved.
sendMessage(content, `options`, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.sendMessage(channel, content, options, callback)``
| **Aliases** `send`
| **See** client.sendMessage_
sendTTSMessage(content, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.sendTTSMessage(channel, content, callback)``
| **Aliases** `sendTTS`
| **See** client.sendTTSMessage_
sendFile(attachment, name, content, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.sendFile(channel, attachment, name, content, callback)``
| **See** client.sendFile_
startTyping(`callback`)
~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.startTyping(channel, callback)``
| **See** client.startTyping_
stopTyping(`callback`)
~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.stopTyping(channel, callback)``
| **See** client.stopTyping_
addTo(role, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.addMemberToRole(member, role, callback)``
| **See** client.addMemberToRole_
removeFrom(role, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.removeMemberFromRole(member, role, callback)``
| **See** client.removeMemberFromRole_
getLogs(`limit`, `options`, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.getChannelLogs(channel, limit, options, callback)``
| **See** client.getChannelLogs_
getMessage(messageID, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.getMessage(channel, messageID, callback)``
| **See** client.getMessage_
hasRole(role)
~~~~~~~~~~~~
| **Shortcut of** ``client.memberHasRole(member, role)``
| **See** client.memberHasRole_
.. _client.addMemberToRole : ./docs_client.html#addmembertorole-member-role-callback
.. _client.removeMemberFromRole : ./docs_client.html#removememberfromrole-member-role-callback
.. _client.memberHasRole : ./docs_client.html#memberhasrole-member-role
.. _client.sendMessage : ./docs_client.html#sendmessage-channel-content-options-callback
.. _client.sendTTSMessage : ./docs_client.html#sendttsmessage-channel-content-callback
.. _client.sendFile : ./docs_client.html#sendfile-channel-attachment-name-content-callback
.. _client.startTyping : ./docs_client.html#starttyping-channel-callback
.. _client.stopTyping : ./docs_client.html#stoptyping-channel-callback
.. _client.getChannelLogs : ./docs_client.html#getchannellogs-channel-limit-options-callback
.. _client.getMessage : ./docs_client.html#getmessage-channel-messageid-callback

View File

@@ -0,0 +1,54 @@
.. include:: ./vars.rst
VoiceChannel
============
**extends** ServerChannel_
A voice channel of a server. Currently, the voice channel class has no differences to the ServerChannel class.
--------
Attributes
----------
members
~~~~~~~~
A Cache_ of Users_ that are connected to the voice channel
userLimit
~~~~~~~~
The maximum amount of users that can connect to the voice channel. If it's 0, there is no limit
bitrate
~~~~~~~~
The bitrate of the voice channel (in kb/s).
Functions
---------
setUserLimit(limit, `callback`)
~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.setChannelUserLimit(channel, limit, callback)``
| **See** client.setChannelUserLimit_
setBitrate(kbitrate, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.setChannelBitrate(channel, kbitrate, callback)``
| **See** client.setChannelBitrate_
join(`callback`)
~~~~~~~~~~~~~~~~~
| **Shortcut of** ``client.joinVoiceChannel(channel, callback)``
| **See** client.joinVoiceChannel_
.. _client.setChannelUserLimit : ./docs_client.html#setchanneluserlimit-channel-limit-callback
.. _client.setChannelBitrate : ./docs_client.html#setchannelbitrate-channel-bitrate-callback
.. _client.getBans : ./docs_client.html#joinvoicechannel-channel-callback

View File

@@ -0,0 +1,151 @@
.. include:: ./vars.rst
VoiceConnection
===============
discord.js currently supports sending audio data over Discord voice chat. A voice connection can be initiated using
client.joinVoiceChannel_ and then later accessed again using the `client.voiceConnection` property. You can play something
using the `playXYZ` methods and then later stop the playback and listen for events that tell you about the playback status.
Note that discord.js does not support receiving data from voice yet, only sending.
--------
Attributes
----------
voiceChannel
~~~~~~~~~~~~
VoiceChannel_ that the connection is for
client
~~~~~~
Client_ the connection belongs to
token
~~~~~
The token used to authenticate with Discord
server
~~~~~~
The Server_ on which the voice connection takes place
encoder
~~~~~~~
The AudioEncoder_ used to encode data in this particular session
playingIntent
~~~~~~~~~~~~~
A stream intent used to bind events to the voice connection
playing
~~~~~~~
Whether or not the bot is currently playing something
paused
~~~~~~
Whether or not the playback is currently paused
streamTime
~~~~~~~~~~
The amount of time the current track has been playing for, in milliseconds
Functions
---------
playFile(path, `options`, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Plays a file to the voice channel. The file can be in practically any format; if you're looking for a list, look here: `Format list`_.
In addition to a file path local to your computer, it can also accept a URL, however this is not recommended as the entire content of the URL will be read before any playback starts.
This can cause delays from seconds to minutes - you can use `playRawStream` with a Stream obtained from the URL instead.
The `options` object can be used to control playback properties, currently, it allows setting the seek (in seconds) using the `seek` property, and the volume using the `volume` property, which can be in any of the following formats:
- A number representing the linear change in volume; 1 is equal to no change, 0 is completely silent, 0.5 is half the regular volume and 2 is double the regular volume.
- A string representing the linear change in volume, if this is more convenient for you.
- A string representing decibel gain, where `"0dB"` is no change, `"-3dB"` is half the volume (in linear units), `"+6dB"` is four times the volume (in linear units) and so on.
It is recommended to change the volume, because the default of 1 is usually too loud. (A reasonable setting is `0.25` or `"-6dB"`).
The callback will be called immediately after playback has *started*, it will have an error object and the stream intent as its parameters. The callback will only receive
an error if the encoding fails, for playback errors, you can bind a function to the `error` event of the intent. The intent supports the following events:
- The `time` event is emitted every packet (20 milliseconds) and has the current playback time in milliseconds as its only parameter. The playback time can also be checked at any time using the `streamTime` attribute.
- The `end` event is emitted once playback ends. Depending on various factors, it may be emitted a couple seconds earlier than the actual stream ending, you may have to add an offset if necessary.
- The `error` event is emitted if an error happens during playback, such as failing to send a packet.
The intent can later be accessed again using the `playingIntent` property. If you prefer _Promises over callbacks, this method will return a promise you can use in the same way as the callback.
playRawStream(stream, `options`, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This method is used in much the same way as `playFile`, except it plays data back from a stream containing audio data instead of a file or URL.
| See voiceConnection.playFile_ for usage information.
playArbitraryFFmpeg(ffmpegOptions, `volume`, `callback`)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This method can be used to play data obtained from an arbitrary call to ffmpeg. Note that the array of options given as the parameter will
still be concatenated with the following options so it can be used with Discord:
.. code::
-loglevel 0
-f s16le
-ar 48000
-ac 2
pipe:1
setSpeaking(value)
~~~~~~~~~~~~~~~~~~
Sets whether or not the user is speaking (green circle around user on the official client). discord.js does this automatically when playing something,
but you may want to spoof it or manually disable it.
- **value** - `true` or `false`: whether or not you want the bot to show as speaking
setVolume(volume)
~~~~~~~~~~~~~
Sets the current volume of the connecion. 1.0 is normal, 0.5 is half as loud, 2.0 is twice as loud.
getVolume()
~~~~~~~~~~~~~
Returns the current volume. 1.0 is normal, 0.5 is half as loud, 2.0 is twice as loud.
pause()
~~~~~~~
Pauses the current connection's audio.
resume()
~~~~~~~~
Resumes the current connection's audio.
stopPlaying()
~~~~~~~~~~~~~
Stops the current playback immediately. After this method has finished, it is safe to play something else.
destroy()
~~~~~~~~~
Disconnects from the voice server and destroys all network connection. It's impossible to play anything on this connection afterwards, you will have to re-initiate
a connection using client.joinVoiceChannel_. This method also calls `stopPlaying` internally, you don't have to do that yourself.
.. _Format list: https://ffmpeg.org/general.html#File-Formats
.. _voiceConnection.playFile: ./docs_voiceconnection.html#playfile-path-options-callback
.. _client.joinVoiceChannel: ./docs_client.html#joinvoicechannel-channel-callback

323
docs/examples.rst Normal file
View File

@@ -0,0 +1,323 @@
.. include:: ./vars.rst
Usage Examples
==============
Not all of these are standalone examples, many of them are usage examples. If you're a beginner to Discord.js, we encourage you to look through these examples to get a hang of the way things work using the library.
.. warning :: Please do not copy/paste code directly from these examples. Try to learn from and adapt these pieces of code to your specific situation.
.. note :: We use `Template Literals`_ in these examples. These are an ES6 feature and may not be fully supported in your environment. In this case, it is safe to use other methods of concatenating strings.
-----
Logging In
----------
Logs the Client_ in, allowing you to begin working with the Discord API.
Logging in with a username and password
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
**Do not use a normal user account for large or public bots. This is considered abuse of the API and can land you in trouble.**
.. code-block:: javascript
const Discord = require('discord.js');
var client = new Discord.Client();
client.login('mybot@example.com', 'password', output);
function output(error, token) {
if (error) {
console.log(`There was an error logging in: ${error}`);
return;
} else
console.log(`Logged in. Token: ${token}`);
}
Logging in with a token
~~~~~~~~~~~~~~~~~~~~~~~
You can get your bot's token using the `My Applications`_ page on the Discord Developers site.
.. code-block:: javascript
const Discord = require('discord.js');
var client = new Discord.Client();
client.loginWithToken('token', output);
function output(error, token) {
if (error) {
console.log(`There was an error logging in: ${error}`);
return;
} else
console.log(`Logged in. Token: ${token}`);
}
-----
Logging Out
----------
The logOut function should be used if you intend to reconnect with the same process. The function takes one parameter, which is a callback.
.. code-block:: javascript
client.logOut((err) => {
console.log(err);
});
However, if you want to completely shut down your application, use destroy.
.. code-block:: javascript
client.destroy((err) => {
console.log(err);
});
-----
Receiving Messages
------------------
Here we will demonstrate receiving messages and logging them to the console.
.. code-block:: javascript
client.on('message', function(message) {
if (message.channel.isPrivate) {
console.log(`(Private) ${message.author.name}: ${message.content}`);
} else {
console.log(`(${message.server.name} / ${message.channel.name}) ${message.author.name}: ${message.content}`);
}
});
-----
Sending messages
-----------------
In the same channel
~~~~~~~~~~~~~~~~~~~
This is by far the most common way people will send a message in the Discord API. Here we will send a message to the same Channel_ we received a message from in the above example.
.. code-block:: javascript
client.on('message', function(message) {
// Don't forget to log the message!
client.sendMessage(message.channel, "Hello!");
});
You can also use a `Message`_ resolvable as an parameter. This example does the same thing as above.
.. code-block:: javascript
client.on('message', function(message) {
client.sendMessage(message, "Hello!");
});
You can also directly reply to messages. This does the same as adding an @mention in front of your text.
Sends "@author Hello!"
.. code-block:: javascript
client.on('message', function(message) {
client.reply(message, "Hello!");
});
To a specific server and channel
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sends "Hello" to the default Channel_ in the Server_ "My Server". Note that this does not require any sort of received message to be activated, however if there are multiple servers with the name "My Server", a random one will be chosen.
See Cache_ for more details on getting specific objects and resolvables.
.. code-block:: javascript
var channel = client.servers.get("name", "My Server").defaultChannel;
client.sendMessage(channel, "Hello");
Private Messages
~~~~~~~~~~~~~~~~
You can also send private messages to a user with a User_ object. This will send "Hello!" as a private message to the original author of the received message.
Do note however, that a PMChannel_ is not the same as a ServerChannel_ and therefore does not have the same properties such as ``server`` and ``name``.
.. code-block:: javascript
client.on('message', function(message) {
client.sendMessage(message.author, "Hello!");
});
-----
Sending files
-----------------
The process of sending files is similar to how you send messages.
The first parameter takes an `Channel Resolvable`_ or `User Resolvable`_. The User Resolvable will send the file as a DM, and the Channel Resolvable will send the file to a text channel.
The next parameter is a `File Resolvable`_.
The third parameter lets you name your file. This is optional.
The fourth parameter lets you add a message. This is optional.
The last parameter is a callback. It takes an error and a `Message`_ object.
URL
~~~~~~~~~~~~~~~~
.. code-block:: javascript
client.on('message', function(message) {
client.sendFile(message, 'http://i.imgur.com/6CbxaPc.jpg', 'kappa.jpg', 'Check out this cool file!', (err, m) => {
if (err) console.log(err);
});
});
Local file
~~~~~~~~~~~~~~~~
.. code-block:: javascript
client.on('message', function(message) {
client.sendFile(message, '/assets/dank_meme.jpg', 'dank_meme.jpg', 'Check out this cool file!', (err, m) => {
if (err) console.log(err);
});
});
Buffer
~~~~~~~~~~~~~~~~
Send data from streams.
.. code-block:: javascript
const fs = require('fs');
client.on('message', function(message) {
var stream = fs.createReadStream('/assets/dank_meme.jpg');
var chunks = [];
stream.on('data', (dataChunk) => {
chunks.push(dataChunk);
});
stream.on('end' () => {
client.sendFile(message, Buffer.concat(chunks), 'dank_meme.jpg', 'Check out this cool file!');
});
});
-----
Deleting messages
-----------------
The deleteMessage function takes an `Message Resolvable`_ as the first parameter. The second parameter is a callback.
This snippet will delete the received message.
.. code-block:: javascript
client.on('message', function(message) {
client.deleteMessage(message);
});
You can also delete multiple messages with the deleteMessages function. It takes an array of `Message Resolvable`_ s.
This code deletes all the messages recieved every 10 seconds.
.. code-block:: javascript
var messages = [];
client.on('message', function(message) {
messages.push(message);
});
function clear() {
client.deleteMessages(messages);
messages = [];
}
setInterval(clear, 10000);
-----
Status updates
-----------------
Updating your status is very simple.
The ready event needs to be emitted before you can use theese functions.
You can either use the setStatus function or you can use helpers.
This will set the status to online and playing Call of Duty: Black Ops 10.
.. code-block:: javascript
client.on('ready', () => {
client.setStatus('online', 'Call of Duty: Black Ops 10');
});
You can also use the setPlayingGame function, if you just want to set your game...
.. code-block:: javascript
client.on('ready', () => {
client.setPlayingGame('Call of Duty: Black Ops 10');
});
...and setStatusIdle/setStatusOnline, if you just want to change your status.
.. code-block:: javascript
client.on('ready', () => {
client.setStatusIdle(); // Now idle
setTimeout(() => { client.setStatusOnline(); }, 10000); // Set the status back to online after 10 seconds.
});
Set streaming
~~~~~~~~~~~~~~~~
You can even set the streaming status.
The setStreaming function takes 3 parameters, and one callback.
The first defines the name of the game, the second the URL to a twitch.tv channel and the third a type where 1 = streamnig.
.. code-block:: javascript
client.on('ready', () => {
client.setStreaming('Call of Duty: Black Ops 10', 'https://www.twitch.tv/lirik', 1);
});
You can also use the setStatus function to do this.
.. code-block:: javascript
client.on('ready', () => {
var opts = {
name: 'Call of Duty: Black Ops 10',
url: 'https://www.twitch.tv/lirik',
type: 1
};
client.setStatus(null, opts);
});
-----

69
docs/index.rst Normal file
View File

@@ -0,0 +1,69 @@
.. include:: ./vars.rst
Welcome to discord.js's documentation!
======================================
discord.js is an easy-to-use and intuitive JavaScript API for Discord_. It's fairly high level, so if you're
looking for something low level, check out `discord.io`_.
if you're having problems, check out the `troubleshooting guide`_.
If you're looking for docs for discord.js 9.0.0 and above, try visiting `the new docs site`_.
Feel free to make any contributions you want, whether it be through creating an issue, giving a suggestion or making a pull request!
.. note:: This documentation is still a work-in-progress, apologies if something isn't yet documented!
.. _docs:
.. toctree::
:maxdepth: 1
:caption: General
installing
migrating
troubleshooting
examples
.. toctree::
:maxdepth: 1
:caption: Documentation
docs_client
docs_server
docs_user
docs_message
docs_invite
docs_voiceconnection
.. toctree::
:maxdepth: 1
:caption: Channel Documentation
docs_channel
docs_pmchannel
docs_serverchannel
docs_textchannel
docs_voicechannel
.. toctree::
:maxdepth: 1
:caption: Permission Documentation
docs_permissionconstants
docs_role
docs_permissionoverwrite
docs_channelpermissions
.. toctree::
:maxdepth: 1
:caption: Utility Documentation
docs_cache
docs_equality
docs_resolvables
.. _Discord : https://discordapp.com/
.. _troubleshooting guide : troubleshooting.html
.. _discord.io : https://github.com/izy521/discord.io
.. _the new docs site : http://hydrabolt.github.io/discord.js

62
docs/installing.rst Normal file
View File

@@ -0,0 +1,62 @@
.. include:: ./vars.rst
Installing discord.js
=====================
To install discord.js, you need a few dependencies.
.. warning:: **When installing with any of these methods, you'll encounter some errors.** This is because an optional dependency isn't working properly, but discord.js should still work fine.
-----------
Windows
-------
------------
- You need `Visual Studio`_ and `Python 2.7`_.
Your Visual Studio installation ideally has to be recent, but you can try installing without it first. You can use **Express, Community, Enteprise** or any others apart from ``VS Code``.
- You (obviously) need `NodeJS`_. Node 4 or higher is recommended.
After you have installed these things, to install just run: ``npm install --save --msvs_version=2015 discord.js`` to install the latest version of discord.js for your project.
Additional Audio Support
~~~~~~~~~~~~~~~~~~~~~~~~
- Install `ffmpeg`_ and add it to your PATH.
-----------
Linux (Debian-based)
-----
-----------
- You (obviously) need `NodeJS Linux`_. Node 4 or higher is recommended.
.. code-block:: bash
$ sudo apt-get install build-essential
$ npm install --save discord.js
Additional Audio Support
~~~~~~~~~~~~~~~~~~~~~~~~
.. code-block:: bash
$ sudo apt-get install ffmpeg
Note: Ubuntu 14.04 needs to do:
.. code-block:: bash
$ sudo add-apt-repository ppa:mc3man/trusty-media && sudo apt-get update && sudo apt-get install ffmpeg
.. _Visual Studio : https://www.visualstudio.com/downloads/download-visual-studio-vs
.. _Python 2.7 : https://www.python.org/download/releases/2.7.8/
.. _ffmpeg : https://www.ffmpeg.org/download.html
.. _NodeJS : https://nodejs.org/en/download/
.. _NodeJS Linux : https://nodejs.org/en/download/package-manager/

263
docs/make.bat Normal file
View File

@@ -0,0 +1,263 @@
@ECHO OFF
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=_build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
set I18NSPHINXOPTS=%SPHINXOPTS% .
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^<target^>` where ^<target^> is one of
echo. html to make standalone HTML files
echo. dirhtml to make HTML files named index.html in directories
echo. singlehtml to make a single large HTML file
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. devhelp to make HTML files and a Devhelp project
echo. epub to make an epub
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. text to make text files
echo. man to make manual pages
echo. texinfo to make Texinfo files
echo. gettext to make PO message catalogs
echo. changes to make an overview over all changed/added/deprecated items
echo. xml to make Docutils-native XML files
echo. pseudoxml to make pseudoxml-XML files for display purposes
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
echo. coverage to run coverage check of the documentation if enabled
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
REM Check if sphinx-build is available and fallback to Python version if any
%SPHINXBUILD% 2> nul
if errorlevel 9009 goto sphinx_python
goto sphinx_ok
:sphinx_python
set SPHINXBUILD=python -m sphinx.__init__
%SPHINXBUILD% 2> nul
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
:sphinx_ok
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "singlehtml" (
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\discordjs.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\discordjs.ghc
goto end
)
if "%1" == "devhelp" (
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished.
goto end
)
if "%1" == "epub" (
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub file is in %BUILDDIR%/epub.
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
if errorlevel 1 exit /b 1
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdf" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf
cd %~dp0
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdfja" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf-ja
cd %~dp0
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "text" (
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The text files are in %BUILDDIR%/text.
goto end
)
if "%1" == "man" (
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The manual pages are in %BUILDDIR%/man.
goto end
)
if "%1" == "texinfo" (
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
goto end
)
if "%1" == "gettext" (
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
if errorlevel 1 exit /b 1
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
if errorlevel 1 exit /b 1
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
if errorlevel 1 exit /b 1
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
if "%1" == "coverage" (
%SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage
if errorlevel 1 exit /b 1
echo.
echo.Testing of coverage in the sources finished, look at the ^
results in %BUILDDIR%/coverage/python.txt.
goto end
)
if "%1" == "xml" (
%SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The XML files are in %BUILDDIR%/xml.
goto end
)
if "%1" == "pseudoxml" (
%SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml.
goto end
)
:end

45
docs/migrating.rst Normal file
View File

@@ -0,0 +1,45 @@
.. include:: ./vars.rst
Updating to v5.0.0
==================
If you're coming from versions below v5, you might find some changes. Here are the major changes:
Change 1
--------
.. code-block:: js
// OLD:
client.getUser();
client.getServer();
server.getMember(); // etc etc
// NEW:
client.users.get();
client.servers.get();
client.members.get();
Change 2
--------
.. code-block:: js
// OLD:
client.on("serverNewMember", (member, server) => {
});
// NEW:
client.on("serverNewMember", (server, user) => {
});
Change 3
---------
The Member Class has been removed, meaning you can't use ``member.permissionsIn(channel)``. To get permissions, use ``channel.permissionsOf(user)``.

51
docs/troubleshooting.rst Normal file
View File

@@ -0,0 +1,51 @@
.. include:: ./vars.rst
Troubleshooting
===============
General
-------
Occasionally, the API can stop working for whatever reason. If it was working previously and it stopped working on the same version, it means that either we screwed code up or there's been a change to the Discord API. You can try asking around in the `discord.js channel in the API server`_. You could also `make an issue`_ if one relating to a similar issue doesn't exist. Please post a stacktrace if there is one, and be as detailed as possible - *"the API isn't working"* doesn't help at all.
If there is already an issue, feel free to comment that you're also experiencing the same thing. This helps to see how widespread the bug is.
You can try reconnecting before submitting an issue, as sometimes some of the servers may be slightly different.
If you're your bot or client is exiting unexpectedly with no error, this is likely caused by websocket disconnects. Make sure you have ``autoReconnect`` enabled. See `Client`_.
Voice
------
Often, especially if you're on Windows, voice will not work out of the box.
Follow the steps below, one by one.
- Is your system supported? The following are:
- Linux x64 & ia32
- Linux ARM (Raspberry Pi 1 & 2)
- Mac OS X x64
- Windows x64
- Did you install Python 2.7.x correctly? Is it in your PATH? ``python -V``. If not, install it correctly or try reinstalling.
- **Windows** - See https://python.org/downloads/
- **Linux / Mac OS** - Unix systems should already have it installed, but if not, use the OS's package manager
- Did you install FFMPEG correctly? Is it in your PATH? ``ffmpeg -version``. If not, install it correctly or try reinstalling.
- **Windows** - `Follow this guide`_
- **Linux / Mac OS** - Use your OS's package manager
- Did you install the required C++ compiler tool for your OS? If not, install the corresponding program, **then** try reinstalling discord.js ``npm i -S discord.js``
- **Windows** - `Visual Studio 2015`_ with `C++ Support enabled`_
- **Linux** - build-essential
- **Mac OS** - Xcode CLI tools
If you're still having problems try
- ``npm cache clean``
- ``npm config set msvs_version 2015``
- ``npm i -S discord.js``
If nothing of the above helped, feel free to jump on the `discord.js channel in the API server`_
.. _discord.js channel in the API server : https://discord.gg/0SBTUU1wZTYcFtmP
.. _make an issue : https://github.com/hydrabolt/discord.js/issues
.. _Follow this guide : http://adaptivesamples.com/how-to-install-ffmpeg-on-windows/
.. _Visual Studio 2015 : https://www.visualstudio.com/en-us/downloads/download-visual-studio-vs.aspx
.. _C++ Support enabled : https://social.msdn.microsoft.com/Forums/getfile/740020

35
docs/vars.rst Normal file
View File

@@ -0,0 +1,35 @@
.. _Client : ./docs_client.html
.. _Cache : ./docs_cache.html
.. _User : ./docs_user.html
.. _Users : ./docs_user.html
.. _Server : ./docs_server.html
.. _Channel : ./docs_channel.html
.. _ServerChannel : ./docs_serverchannel.html
.. _TextChannel : ./docs_textchannel.html
.. _VoiceChannel : ./docs_voicechannel.html
.. _PMChannel : ./docs_pmchannel.html
.. _Message : ./docs_message.html
.. _Invite : ./docs_invite.html
.. _Equality : ./docs_equality.html
.. _Role : ./docs_role.html
.. _ChannelPermissions : ./docs_channelpermissions.html
.. _PermissionOverwrite : ./docs_permissionoverwrite.html
.. _Permission Constants : ./docs_permissionconstants.html
.. _Resolvables : ./docs_resolvables.html
.. _VoiceConnection : ./docs_voiceconnection.html
.. _Promises : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
.. _Template Literals : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
.. _EventEmitter : https://nodejs.org/api/events.html#events_class_events_eventemitter
.. _Channel Resolvable : http://discordjs.readthedocs.org/en/indev/docs_resolvables.html#channel-resolvable
.. _String Resolvable : http://discordjs.readthedocs.org/en/indev/docs_resolvables.html#string-resolvable
.. _Message Resolvable : http://discordjs.readthedocs.org/en/indev/docs_resolvables.html#message-resolvable
.. _Server Resolvable : http://discordjs.readthedocs.org/en/indev/docs_resolvables.html#server-resolvable
.. _Invite Resolvable : http://discordjs.readthedocs.org/en/indev/docs_resolvables.html#invite-id-resolvable
.. _User Resolvable : http://discordjs.readthedocs.org/en/indev/docs_resolvables.html#user-resolvable
.. _Base64 Resolvable : http://discordjs.readthedocs.org/en/indev/docs_resolvables.html#base64-resolvable
.. _VoiceChannel Resolvable : http://discordjs.readthedocs.org/en/indev/docs_resolvables.html#voice-channel-resolvable
.. _File Resolvable : http://discordjs.readthedocs.org/en/indev/docs_resolvables.html#file-resolvable
.. _Role Resolvable : http://discordjs.readthedocs.org/en/indev/docs_resolvables.html#role-resolvable
.. _My Applications : https://discordapp.com/developers/applications/me

39
entrypoint.js Normal file
View File

@@ -0,0 +1,39 @@
/* global process */
/*
this is the entrypoint file, when node finally catches
up with all ES6 drafts etc, the entrypoint file will stop
using the transpiled ES5 and switch straight to the ES6
code. This allows for easier debugging and potentially
faster execution!
*/
var v = process.version;
if(v.charAt(0) === "v"){
v = v.substring(1);
}
v = v.split(".");
var major = parseInt(v[0]),
minor = parseInt(v[1]),
patch = parseInt(v[2]);
if((major == 0 && minor < 12) || (major == 0 && minor == 12 && patch < 7)) {
if(!process.env.OVERRIDE_DISCORD_MIN_VERSION) {
throw new Error(
"discord.js doesn't support node versions less than 0.12.7.\n"+
"If you /really/ want to run it on this node " + process.version + ", then set OVERRIDE_DISCORD_MIN_VERSION as an environment variable.\n"+
"This is unsupported and WILL cause problems."
)
}
}
// at the moment no node version has full ES6 support
use5();
function use6(){
module.exports = require("./src/index.js");
}
function use5(){
module.exports = require("./lib/index.js");
}

4
esdoc.json Normal file
View File

@@ -0,0 +1,4 @@
{
"source": "./src",
"destination": "./esdoc"
}

View File

@@ -1,139 +0,0 @@
import unocss from '@unocss/eslint-plugin';
import common from 'eslint-config-neon/flat/common.js';
import edge from 'eslint-config-neon/flat/edge.js';
import next from 'eslint-config-neon/flat/next.js';
import node from 'eslint-config-neon/flat/node.js';
import prettier from 'eslint-config-neon/flat/prettier.js';
import react from 'eslint-config-neon/flat/react.js';
import typescript from 'eslint-config-neon/flat/typescript.js';
// import oxlint from 'eslint-plugin-oxlint';
import merge from 'lodash.merge';
import tseslint from 'typescript-eslint';
const commonFiles = '{js,mjs,cjs,ts,mts,cts,jsx,tsx}';
const commonRuleset = merge(...common, { files: [`**/*${commonFiles}`] });
const nodeRuleset = merge(...node, { files: [`**/*${commonFiles}`] });
const typeScriptRuleset = merge(...typescript, {
files: [`**/*${commonFiles}`],
languageOptions: {
parserOptions: {
warnOnUnsupportedTypeScriptVersion: false,
allowAutomaticSingleRunInference: true,
project: ['tsconfig.eslint.json', 'packages/*/tsconfig.eslint.json'],
},
},
rules: {
'@typescript-eslint/consistent-type-definitions': [2, 'interface'],
'@typescript-eslint/naming-convention': [
2,
{
selector: 'typeParameter',
format: ['PascalCase'],
custom: {
regex: '^\\w{3,}',
match: true,
},
},
],
},
settings: {
'import/resolver': {
typescript: {
project: ['tsconfig.eslint.json', 'packages/*/tsconfig.eslint.json'],
},
},
},
});
const reactRuleset = merge(...react, {
files: [`packages/ui/**/*${commonFiles}`],
rules: {
'@next/next/no-html-link-for-pages': 0,
'react/react-in-jsx-scope': 0,
'react/jsx-filename-extension': [1, { extensions: ['.tsx'] }],
},
});
const prettierRuleset = merge(...prettier, { files: [`**/*${commonFiles}`] });
// const oxlintRuleset = merge({ rules: oxlint.rules }, { files: [`**/*${commonFiles}`] });
export default tseslint.config(
{
ignores: [
'**/node_modules/',
'.git/',
'**/dist/',
'**/template/',
'**/coverage/',
'**/storybook-static/',
'**/.next/',
'packages/discord.js/',
],
},
commonRuleset,
nodeRuleset,
typeScriptRuleset,
{
files: ['**/*{ts,mts,cts,tsx}'],
rules: { 'jsdoc/no-undefined-types': 0 },
},
{
files: [`packages/{api-extractor,brokers,create-discord-bot,docgen,ws}/**/*${commonFiles}`],
rules: { 'n/no-sync': 0 },
},
{
files: [`packages/rest/**/*${commonFiles}`],
rules: {
'n/prefer-global/url': 0,
'n/prefer-global/url-search-params': 0,
'n/prefer-global/buffer': 0,
'n/prefer-global/process': 0,
'no-restricted-globals': 0,
'unicorn/prefer-node-protocol': 0,
},
},
{
files: [`packages/voice/**/*${commonFiles}`],
rules: { 'no-restricted-globals': 0 },
},
{
files: [`packages/api-extractor-model/**/*${commonFiles}`],
rules: {
'@typescript-eslint/no-namespace': 0,
'no-prototype-builtins': 0,
'consistent-this': 0,
'unicorn/no-this-assignment': 0,
'@typescript-eslint/no-this-alias': 0,
},
},
{
files: [`packages/api-extractor/**/*${commonFiles}`],
rules: {
'consistent-this': 0,
'unicorn/no-this-assignment': 0,
'@typescript-eslint/no-this-alias': 0,
},
},
{
files: [`packages/{api-extractor,api-extractor-model,api-extractor-utils}/**/*${commonFiles}`],
rules: { '@typescript-eslint/naming-convention': 0 },
},
reactRuleset,
{
files: [`packages/ui/**/*${commonFiles}`],
plugins: { '@unocss': unocss },
rules: {
'@unocss/order': 2,
},
},
{
files: ['**/*{js,mjs,cjs,jsx}'],
rules: { 'tsdoc/syntax': 0 },
},
prettierRuleset,
// oxlintRuleset,
);

View File

@@ -0,0 +1,3 @@
# Analysis Bot
Analysis Bot provides Analysis and Utility to Discord Users!

View File

@@ -0,0 +1,161 @@
/* global process */
var Discord = require("../../");
var bot = new Discord.Client();
var auth = require("../auth.json");
var request = require("superagent");
var loose = false;
bot.on("message", msg => {
if (!msg.content.startsWith("$")) return;
msg.content = msg.content.substr(1);
if (msg.content === "stats") {
msg.reply([
"I am connected/have access to:",
`${bot.servers.length} servers`,
`${bot.channels.length} channels`,
`${bot.users.length} users`,
]);
}
else if (msg.content.startsWith("startplaying")) {
var game = msg.content.split(" ").slice(1).join(" ");
bot.setPlayingGame(game);
}
else if (msg.content.startsWith("setname") && loose) {
bot.setUsername(msg.content.split(" ").slice(1).join(" ")).then(() => {
msg.reply("Done!");
});
}
else if (msg.content === "updateav") {
request
.get("https://api.github.com/search/repositories?q=discord.js")
.end((err, res) => {
if (err) {
return;
}
var text = res.body.items[0].stargazers_count
bot.updateDetails({
username : "d.js star bot - " + text,
avatar: getStars(text)
}).then(() => {
msg.reply("Success!");
});
});
}
else if (msg.content.startsWith("setavatar") && loose) {
request
.get(msg.content.split(" ")[1])
.end((err, res) => {
bot.updateDetails({
avatar: getStars(text)
}).then(() => {
msg.reply("done!");
});
});
}
else if (msg.content === "away") {
bot.setStatusIdle();
}
else if (msg.content === "here") {
bot.setStatusOnline();
}
else if (msg.content === "randomUser") {
var random = bot.users.random();
msg.reply([
random.username,
"avatar: ", random.avatarURL
]);
}
else if (msg.content.startsWith("mimic") && loose) {
var toMimic = msg.mentions[0];
if (!toMimic) {
return;
}
if (!toMimic.avatar) {
bot.updateDetails({
username: toMimic.username,
avatar: null
});
return;
}
request
.get(toMimic.avatarURL)
.end((err, res) => {
bot.updateDetails({
username: toMimic.username,
avatar: res.body
}).then(() => {
msg.reply("Done!");
});
});
}
});
setInterval(() => {
request
.get("https://api.github.com/search/repositories?q=discord.js")
.end((err, res) => {
if (err) {
return;
}
var text = res.body.items[0].stargazers_count
bot.updateDetails({
username : "d.js star bot - " + text,
avatar: getStars(text)
}).then(() => {
console.log("many successes");
});
});
}, 60000);
bot.on("disconnected", () => {
console.log("Disconnected, exiting!");
process.exit();
})
bot.loginWithToken(auth.token);
function getStars(text) {
var Canvas = require('canvas')
, Image = Canvas.Image
, canvas = new Canvas(90, 90)
, ctx = canvas.getContext('2d');
ctx.fillStyle = "black";
ctx.fillRect(0, 0, 90, 90);
ctx.font = '45px Arial';
ctx.fillStyle = "white";
ctx.fillText(text, (ctx.measureText(text).width / 2) - 5, 60);
ctx.strokeStyle = 'rgb(255,255,255)';
return canvas.toDataURL();
}

3
examples/auth.json Normal file
View File

@@ -0,0 +1,3 @@
{
"token": "Your bot token here"
}

31
examples/avatar.js Normal file
View File

@@ -0,0 +1,31 @@
/*
this bot is an avatar bot, and will give a user their avatar's URL
*/
var Discord = require("../");
var AuthDetails = require("./auth.json");
var bot = new Discord.Client();
bot.on("ready", () => {
console.log(`Ready to begin! Serving in ${bot.channels.length} channels`);
});
bot.on("disconnected", () => {
console.log("Disconnected!");
process.exit(1); //exit node.js with an error
});
bot.on("message", (msg) => {
// if the message is avatar
if (msg.content === "avatar") {
bot.reply(msg, "Here is the URL for your avatar: " + msg.author.avatarURL);
}
});
bot.loginWithToken(AuthDetails.token);

5
examples/jsconfig.json Normal file
View File

@@ -0,0 +1,5 @@
{
"compilerOptions": {
"target": "ES6"
}
}

View File

@@ -0,0 +1,72 @@
var Discord = require("../../");
// Get the token
var AuthDetails = require("../auth.json");
var bot = new Discord.Client();
bot.on("ready", function () {
console.log(`Ready to begin! Serving in ${bot.channels.length} channels`);
});
bot.on("disconnected", function () {
console.log("Disconnected!");
process.exit(1); //exit node.js with an error
});
bot.on("message", function (msg) {
if (msg.content === "skype") {
//stop the user from speaking in the channel:
bot.overwritePermissions(msg.channel, msg.author, {
sendMessages: false
});
// send a barely funny message ;)
bot.reply(msg, "How dare you mention that!");
}
if (msg.content === "discord") {
var role = msg.server.roles.get("name", "good people");
// if the role doesn't exist, make it
if (!role) {
bot.createRole(msg.server, {
name: "good people",
color: "0000FF", // blue
hoist: true // make a seperate category in the users list
}).then(createdRole => {
role = createdRole;
}).catch(console.log);
}
bot.addMemberToRole(msg.author, role);
bot.reply(msg, "Welcome to the good people!");
}
if (msg.content === "remove me") {
// remove the user from the good people list, if it exists
var role = msg.server.roles.get("name", "good people");
if (role) { // if the role exists
if (msg.author.hasRole(role)) {
// remove the member from the role
bot.removeMemberFromRole(msg.author, role);
bot.reply(msg, "Removed!")
} else {
bot.reply(msg, "You're not in the role!");
}
} else {
// role doesn't exist
bot.reply(msg, "The role doesn't even exist!");
}
}
});
bot.loginWithToken(AuthDetails.token);

View File

@@ -0,0 +1,73 @@
/*
this bot will demonstrate the different ways you
can create colors in Discord.
*/
var Discord = require("../../");
// Get the email and password
var AuthDetails = require("../auth.json");
var bot = new Discord.Client();
bot.on("ready", function () {
console.log("Ready to begin! Serving in " + bot.channels.length + " channels");
});
bot.on("disconnected", function () {
console.log("Disconnected!");
process.exit(1); //exit node.js with an error
});
bot.on("message", function (msg) {
// to use this example, you first have to send 'create role'
// you can then change colors afterwards.
if (msg.content === "create role") {
// create the role and add the user to it
bot.createRole(msg.server, {
name: "Custom Colors",
hoist: true, // so it is visible in the members list
}).then(createdRole => { // this is executed when the role has been created
// adds the sernder to the role
bot.addMemberToRole(msg.author, createdRole).then(() => {
bot.reply(msg, "Added you to the role!");
});
});
}
else if (msg.content.startsWith("custom color")) {
// valid custom colors must follow the format of any of the following:
/*
#ff0000 <- valid 7 digit hex (including #)
ff0000 <- valid 6 digit hex
16711680 <- valid decimal number (this if #ff0000 as a decimal)
*/
var colorName = msg.content.split(" ")[2];
// get the role by its name
var role = msg.server.roles.get("name", "Custom Colors");
// updates the role with the given color
bot.updateRole(role, {
color: colorName
}).then(function (role) {
// this executes if the change was successful
bot.reply(msg, "Done! Using the color " + colorName);
}).catch(function (e) {
// this executes if it wasn't successful
bot.reply(msg, "An error occurred. Was that a valid hex/dec color?");
});
}
});
bot.loginWithToken(AuthDetails.token);

View File

@@ -0,0 +1,46 @@
/* this bot will see if a user can send TTS messages */
var Discord = require("../../");
var AuthDetails = require("../auth.json");
var bot = new Discord.Client();
bot.on("ready", () => {
console.log("Ready to begin!");
});
bot.on("message", (msg) => {
var user = msg.author;
if(msg.content === "can I tts?"){
// get the evaluated permissions for a user in the channel they asked
var permissions = msg.channel.permissionsOf(user);
if(permissions.sendTTSMessages)
bot.reply(msg, "You ***can*** send TTS messages.");
else
bot.reply(msg, "You ***can't*** send TTS messages.");
} else if(msg.content === "what are my full permissions?") {
// get the serialised permissions of the user
var permissions = msg.channel.permissionsOf(user).serialise();
// if you want to stringify permissions, they need to be serialised first.
bot.reply(msg, JSON.stringify(permissions, null, 4).replace(/true/g, "**true**"));
}
/*
for a list of more permissions, go to
http://discordjs.readthedocs.io/en/indev/docs_permissionconstants.html
*/
})
bot.loginWithToken(AuthDetails.token);

40
examples/pingpong.js Normal file
View File

@@ -0,0 +1,40 @@
/*
This bot is a ping pong bot, and every time a message
beginning with "ping" is sent, it will reply with
"pong!".
*/
var Discord = require("../");
// Get the email and password
var AuthDetails = require("./auth.json");
var bot = new Discord.Client();
//when the bot is ready
bot.on("ready", () => {
console.log(`Ready to begin! Serving in ${bot.channels.length} channels`);
});
//when the bot disconnects
bot.on("disconnected", () => {
//alert the console
console.log("Disconnected!");
//exit node.js with an error
process.exit(1);
});
//when the bot receives a message
bot.on("message", msg => {
//if message begins with "ping"
if (msg.content.startsWith("ping")) {
//send a message to the channel the ping message was sent in.
bot.sendMessage(msg, "pong!");
//alert the console
console.log("pong-ed " + msg.author.username);
}
});
bot.loginWithToken(AuthDetails.token);

30
examples/send-files.js Normal file
View File

@@ -0,0 +1,30 @@
/* this bot will send an image to a channel */
var Discord = require("../");
var AuthDetails = require("./auth.json");
var bot = new Discord.Client();
bot.on("ready", () => {
console.log("Ready to begin!");
});
bot.on("message", (msg) => {
if (msg.content === "photos") {
bot.sendFile(msg, "./test/image.png", "photo.png", (err, sentMessage) => {
if (err)
console.log("Couldn't send image: ", err);
});
}
else if (msg.content === "file") {
bot.sendFile(msg.channel, new Buffer("Text in a file!"), "file.txt", (err, sentMessage) => {
if (err)
console.log("Couldn't send file: ", err)
});
}
});
bot.loginWithToken(AuthDetails.token);

31
examples/tonicdev.js Normal file
View File

@@ -0,0 +1,31 @@
var Discord = require('discord.js');
const token = ''; // token for bot login
//when the bot is ready
bot.on("ready", () => {
console.log(`Ready to begin! Serving in ${bot.channels.length} channels`);
});
//when the bot disconnects
bot.on("disconnected", () => {
//alert the console
console.log("Disconnected!");
//exit node.js with an error
process.exit(1);
});
//when the bot receives a message
bot.on("message", msg => {
//if message begins with "ping"
if (msg.content.startsWith("ping")) {
//send a message to the channel the ping message was sent in.
bot.sendMessage(msg, "pong!");
//alert the console
console.log("pong-ed " + msg.author.username);
}
});
bot.loginWithToken(token);

53
gruntfile.js Normal file
View File

@@ -0,0 +1,53 @@
module.exports = function (grunt) {
require('load-grunt-tasks')(grunt);
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
// define source files and their destinations
babel: {
options: {
loose: "all",
compact: !grunt.option('dev')
},
dist: {
files: [{
expand: true,
cwd: "src/",
src: ["**/**.*"],
dest: "lib/",
ext: ".js"
}]
}
},
browserify: {
dist: {
files: {
'web-dist/discord.<%= pkg.version %>.js': ["lib/index.js"],
},
options: {
browserifyOptions: {
standalone: "Discord"
}
}
}
},
uglify: {
min: {
files: {
"./web-dist/discord.min.<%= pkg.version %>.js": "./web-dist/discord.<%= pkg.version %>.js"
}
}
}
});
// load plugins
grunt.loadNpmTasks('grunt-browserify');
grunt.loadNpmTasks('grunt-contrib-uglify');
// register at least this one task
grunt.registerTask('default', ['babel']);
grunt.registerTask('web', ['browserify', "uglify"]);
grunt.registerTask("dist", ["babel", "browserify", "uglify"])
};

6
jsconfig.json Normal file
View File

@@ -0,0 +1,6 @@
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs"
}
}

1543
lib/Client/Client.js Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,11 @@
"use strict";
exports.__esModule = true;
exports["default"] = {
IDLE: 0,
LOGGING_IN: 1,
LOGGED_IN: 2,
READY: 3,
DISCONNECTED: 4
};
module.exports = exports["default"];

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