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
967 changed files with 586098 additions and 95334 deletions

1
.babelrc Normal file
View File

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

View File

@@ -1,11 +0,0 @@
{
"extends": ["@commitlint/config-angular"],
"rules": {
"type-enum": [
2,
"always",
["chore", "build", "ci", "docs", "feat", "fix", "perf", "refactor", "revert", "style", "test", "types", "typings"]
],
"scope-case": [0]
}
}

View File

@@ -1,38 +0,0 @@
# Packages
node_modules/
# Log files
logs/
*.log
npm-debug.log*
# Runtime data
pids
*.pid
*.seed
# Env
.env
# Dist
dist/
# Miscellaneous
.tmp/
.vscode/*
!.vscode/extensions.json
!.vscode/settings.json
.idea/
.DS_Store
.turbo
tsconfig.tsbuildinfo
# yarn
.pnp.*
.yarn/*
!.yarn/cache
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions

9
.eslintrc Normal file
View File

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

View File

@@ -1,11 +0,0 @@
{
"root": true,
"extends": "marine/prettier/node",
"parserOptions": {
"project": "./tsconfig.eslint.json"
},
"ignorePatterns": ["**/dist/*"],
"env": {
"jest": true
}
}

1
.gitattributes vendored
View File

@@ -1 +0,0 @@
* 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']
method = 'squash'
[merge.message]
title = 'pull_request_title'
strip_html_comments = true
include_coauthors = true

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,91 +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|workflow|build|ci|chore|types|wip)(\(.+\))?: .{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.
### 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,18 +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 `yarn --immutable` ([install](https://yarnpkg.com/getting-started/install))
3. Run `yarn build` to build local packages
4. Code your heart out!
5. Run `yarn 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))

2
.github/FUNDING.yml vendored
View File

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

View File

@@ -1,145 +0,0 @@
name: Bug report
description: Report incorrect or unexpected behavior of a package
labels: [bug, need repro]
body:
- type: markdown
attributes:
value: |
Use Discord for questions: https://discord.gg/djs
- type: dropdown
id: package
attributes:
label: Which package is this bug report for?
options:
- discord.js
- builders
- collection
- rest
- proxy
- proxy-container
- voice
- ws
validations:
required: true
- type: textarea
id: description
attributes:
label: Issue description
description: |
Describe the issue in as much detail as possible.
Tip: You can attach images or log files by clicking this area to highlight it and then dragging files into it.
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: codesample
attributes:
label: Code sample
description: Include a reproducible, minimal code sample. This will be automatically formatted into code, so no need for backticks.
render: typescript
placeholder: |
Your code sample should be...
... Minimal - Use as little code as possible that still produces the same problem (and is understandable)
... Complete - Provide all parts someone else needs to reproduce your problem
... Reproducible - Test the code you're about to provide to make sure it reproduces the problem
- type: input
id: djs-version
attributes:
label: Package version
description: Which version of are you using? Run `npm list <package>` in your project directory and paste the output.
placeholder: We no longer support version 12 or earlier of discord.js
validations:
required: true
- type: input
id: node-version
attributes:
label: Node.js version
description: |
Which version of Node.js are you using? Run `node --version` in your project directory and paste the output.
If you are using TypeScript, please include its version (`npm list typescript`) as well.
placeholder: Node.js version 16.9+ is required for version 14.0.0+
validations:
required: true
- type: input
id: os
attributes:
label: Operating system
description: Which OS does your application run on?
- type: dropdown
id: priority
attributes:
label: Priority this issue should have
description: Please be realistic. If you need to elaborate on your reasoning, please use the Issue description field above.
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.
Tip: you can select multiple items
options:
- Not applicable (subpackage bug)
- 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 options for the `intents` key.
Tip: you can select multiple items
options:
- Not applicable (subpackage bug)
- No Intents
- Guilds
- GuildMembers
- GuildBans
- GuildEmojisAndStickers
- GuildIntegrations
- GuildWebhooks
- GuildInvites
- GuildVoiceStates
- GuildPresences
- GuildMessages
- GuildMessageReactions
- GuildMessageTyping
- DirectMessages
- DirectMessageReactions
- DirectMessageTyping
- MessageContent
- GuildScheduledEvents
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,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,50 +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: package
attributes:
label: Which package is the feature request for?
options:
- discord.js
- builders
- collection
- rest
- proxy
- proxy-container
- 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,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,8 +0,0 @@
addReviewers: true
reviewers:
- iCrawl
- SpaceEEC
- kyranet
- vladfrangu
numberOfReviewers: 0
runOnDraft: true

39
.github/labeler.yml vendored
View File

@@ -1,39 +0,0 @@
'packages:builders':
- packages/builders/*
- packages/builders/**/*
'packages:collection':
- packages/collection/*
- packages/collection/**/*
'packages:discord.js':
- packages/discord.js/*
- packages/discord.js/**/*
'packages:docgen':
- packages/docgen/*
- packages/docgen/**/*
'packages:proxy':
- packages/proxy/*
- packages/proxy/**/*
'packages:proxy-container':
- packages/proxy-container/*
- packages/proxy-container/**/*
'packages:rest':
- packages/rest/*
- packages/rest/**/*
'packages:voice':
- packages/voice/*
- packages/voice/**/*
'packages:website':
- packages/website/*
- packages/website/**/*
'packages:ws':
- packages/ws/*
- packages/ws/**/*

102
.github/labels.yml vendored
View File

@@ -1,102 +0,0 @@
- name: 'api changes'
color: '5663e9'
- name: 'api support'
color: '5663e9'
- name: 'backlog'
color: '7ef7ef'
- 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: 'discussion'
color: 'b6b1f9'
- name: 'discord'
color: '5663e9'
- 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: 'interactions'
color: '80c042'
- name: 'in progress'
color: 'ffccd7'
- name: 'in review'
color: 'aed5fc'
- name: 'invalid'
color: 'e4e669'
- name: 'need repro'
color: 'c66037'
- name: 'packages:builders'
color: 'fbca04'
- name: 'packages:collection'
color: 'fbca04'
- name: 'packages:discord.js'
color: 'fbca04'
- name: 'packages:docgen'
color: 'fbca04'
- name: 'packages:proxy'
color: 'fbca04'
- name: 'packages:proxy-container'
color: 'fbca04'
- name: 'packages:rest'
color: 'fbca04'
- name: 'packages:voice'
color: 'fbca04'
- name: 'packages:website'
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

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,162 +0,0 @@
name: Documentation
on:
push:
branches:
- 'main'
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:
name: Build documentation
runs-on: ubuntu-latest
env:
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
outputs:
BRANCH_NAME: ${{ steps.env.outputs.BRANCH_NAME }}
BRANCH_OR_TAG: ${{ steps.env.outputs.BRANCH_OR_TAG }}
SHA: ${{ steps.env.outputs.SHA }}
if: github.repository_owner == 'discordjs'
steps:
- name: Checkout repository
uses: actions/checkout@v3
with:
ref: ${{ github.event.inputs.ref || '' }}
- name: Install node.js v16
uses: actions/setup-node@v3
with:
node-version: 16
cache: 'yarn'
- name: Install dependencies
run: yarn --immutable
- name: Build dependencies
run: yarn build
- name: Build docs
run: yarn docs
- name: Upload docgen artifacts
uses: actions/upload-artifact@v3
with:
name: docgen
path: packages/*/docs/docs.json
- name: Upload api-extractor artifacts
uses: actions/upload-artifact@v3
with:
name: api-extractor
path: packages/*/docs/docs.api.json
- name: Set outputs for upload job
id: env
run: |
echo "::set-output name=BRANCH_NAME::${GITHUB_REF_NAME}"
echo "::set-output name=BRANCH_OR_TAG::${GITHUB_REF_TYPE}"
echo "::set-output name=SHA::${GITHUB_SHA}"
upload:
name: Upload Documentation
needs: build
strategy:
max-parallel: 1
fail-fast: false
matrix:
package: ['builders', 'collection', 'discord.js', 'proxy', 'rest', 'voice', 'ws']
runs-on: ubuntu-latest
env:
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
BRANCH_NAME: ${{ github.event.inputs.ref || needs.build.outputs.BRANCH_NAME }}
BRANCH_OR_TAG: ${{ github.event.inputs.ref_type || needs.build.outputs.BRANCH_OR_TAG }}
SHA: ${{ needs.build.outputs.SHA }}
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Install node.js v16
uses: actions/setup-node@v3
with:
node-version: 16
cache: 'yarn'
- name: Install dependencies
run: yarn --immutable
- name: Build actions
run: yarn workspace @discordjs/actions build
- name: Download docgen artifacts
uses: actions/download-artifact@v3
with:
name: docgen
path: docs
- name: Download api-extractor artifacts
uses: actions/download-artifact@v3
with:
name: api-extractor
path: docs
- name: Checkout docs repository
uses: actions/checkout@v3
with:
repository: 'discordjs/docs'
token: ${{ secrets.DJS_DOCS }}
path: 'out'
- name: Extract package and semver from tag
if: ${{ github.event.inputs.ref_type == 'tag' || env.BRANCH_OR_TAG == 'tag' }}
id: extract-tag
uses: ./packages/actions/src/formatTag
with:
tag: ${{ env.BRANCH_NAME }}
- name: Move docs to correct directory
if: ${{ (github.event.inputs.ref_type == 'tag' || env.BRANCH_OR_TAG == 'tag') && matrix.package == steps.extract-tag.outputs.package }}
env:
PACKAGE: ${{ steps.extract-tag.outputs.package }}
SEMVER: ${{ steps.extract-tag.outputs.semver }}
run: |
mkdir -p out/${PACKAGE}
mv docs/${PACKAGE}/docs/docs.json out/${PACKAGE}/${SEMVER}.json
if [[ $PACKAGE != "discord.js" ]]; then
mv docs/${PACKAGE}/docs/docs.api.json out/${PACKAGE}/${SEMVER}.api.json
fi
- name: Move docs to correct directory
if: ${{ github.event.inputs.ref_type == 'branch' || env.BRANCH_OR_TAG == 'branch' }}
env:
PACKAGE: ${{ matrix.package }}
run: |
mkdir -p out/${PACKAGE}
mv docs/${PACKAGE}/docs/docs.json out/${PACKAGE}/${BRANCH_NAME}.json
if [[ $PACKAGE != "discord.js" ]]; then
mv docs/${PACKAGE}/docs/docs.api.json out/${PACKAGE}/${BRANCH_NAME}.api.json
fi
- 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 ${BRANCH_OR_TAG} ${BRANCH_NAME}: ${SHA}" || true
git push

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@v3
- name: Label sync
uses: crazy-max/ghaction-github-labeler@v4
with:
github-token: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -1,27 +0,0 @@
name: npm auto deprecate
on:
schedule:
- cron: '0 1 * * *'
workflow_dispatch:
jobs:
npm-auto-deprecate:
name: npm auto deprecate
runs-on: ubuntu-latest
if: github.repository_owner == 'discordjs'
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Install node.js v16
uses: actions/setup-node@v3
with:
node-version: 16
cache: 'yarn'
- name: Install dependencies
run: yarn --immutable
- name: Deprecate versions
run: 'yarn npm-deprecate --name "*dev*" --package @discordjs/builders @discordjs/collection discord.js @discordjs/proxy @discordjs/rest @discordjs/voice'
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_PUBLISH_TOKEN }}

View File

@@ -1,17 +0,0 @@
name: 'PR Triage'
on:
pull_request_target:
jobs:
pr-triage:
name: PR Triage
runs-on: ubuntu-latest
steps:
- name: Automatically label PR
uses: actions/labeler@v4
with:
repo-token: '${{ secrets.GITHUB_TOKEN }}'
sync-labels: true
- name: Automatically assign reviewers
if: github.event.action == 'opened'
uses: kentaro-m/auto-assign-action@v1.2.1

View File

@@ -1,25 +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@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Login to DockerHub
run: echo ${{ secrets.DOCKER_ACCESS_TOKEN }} | docker login -u ${{ secrets.DOCKER_USERNAME }} --password-stdin
- name: Build the image
run: docker build -t discordjs/proxy:latest -f packages/proxy-container/Dockerfile .
- name: Push image to DockerHub
run: docker push discordjs/proxy:latest

View File

@@ -1,54 +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/builders'
folder: 'builders'
- package: '@discordjs/collection'
folder: 'collection'
- package: 'discord.js'
folder: 'discord.js'
- package: '@discordjs/proxy'
folder: 'proxy'
- package: '@discordjs/rest'
folder: 'rest'
- package: '@discordjs/voice'
folder: 'voice'
- package: '@discordjs/ws'
folder: 'ws'
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@v3
- name: Install node.js v16
uses: actions/setup-node@v3
with:
node-version: 16
registry-url: https://registry.npmjs.org/
cache: 'yarn'
- name: Install dependencies
run: yarn --immutable
- name: Build dependencies
run: yarn build
- name: Publish package
run: |
yarn workspace ${{ matrix.package }} release --preid "dev.$(date +%s)-$(git rev-parse --short HEAD)"
yarn workspace ${{ matrix.package }} npm publish --tag dev || true
env:
YARN_NPM_AUTH_TOKEN: ${{ secrets.NPM_PUBLISH_TOKEN }}

View File

@@ -1,25 +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@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Login to DockerHub
run: echo ${{ secrets.DOCKER_ACCESS_TOKEN }} | docker login -u ${{ secrets.DOCKER_USERNAME }} --password-stdin
- name: Build docker image
run: docker build -t discordjs/proxy:latest -f packages/proxy-container/Dockerfile .
- name: Tag image with major
run: docker tag discordjs/proxy discordjs/proxy:$(cut -d '.' -f1 <<< $(jq --raw-output '.version' packages/proxy-container/package.json))
- name: Push image to DockerHub
run: docker push --all-tags discordjs/proxy

View File

@@ -1,40 +0,0 @@
name: Tests
on:
push:
pull_request:
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
cancel-in-progress: true
jobs:
tests:
name: Tests
runs-on: ubuntu-latest
env:
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
NEXT_PUBLIC_LOCAL_DEV: true
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Install node.js v16
uses: actions/setup-node@v3
with:
node-version: 16
cache: 'yarn'
- name: Install dependencies
run: yarn install --immutable
- name: Build dependencies
run: yarn build
- name: ESLint
run: yarn lint
- name: Tests
run: yarn test
- name: Upload Coverage
if: github.repository_owner == 'discordjs'
uses: ./packages/actions/src/uploadCoverage

58
.gitignore vendored
View File

@@ -1,42 +1,40 @@
# Packages
node_modules/
# Created by https://www.gitignore.io
# Log files
logs/
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/
# Coverage directory used by tools like istanbul
coverage
# Miscellaneous
.tmp/
.vscode/*
!.vscode/extensions.json
!.vscode/settings.json
.idea/
.DS_Store
.turbo
tsconfig.tsbuildinfo
coverage/
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# yarn
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions
# node-waf configuration
.lock-wscript
# Cache
.prettiercache
.eslintcache
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# 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,4 +0,0 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
yarn commitlint --edit $1

View File

@@ -1,4 +0,0 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
yarn build && yarn lint-staged

View File

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

7
.npmignore Normal file
View File

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

View File

@@ -1,8 +0,0 @@
{
"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",
"antfu.unocss"
]
}

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
}
]
}

15
.vscode/settings.json vendored
View File

@@ -1,11 +1,6 @@
// Place your settings in this file to overwrite default and user settings.
{
"eslint.workingDirectories": [{ "pattern": "./packages/*" }],
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll": true,
"source.organizeImports": false
},
"unocss.root": "./packages/website",
"typescript.tsdk": "node_modules/typescript/lib"
}
"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
}
}
}
*/

View File

@@ -1,14 +0,0 @@
diff --git a/lib/TSDocConfigFile.js b/lib/TSDocConfigFile.js
index caf3515d60fd386c5909db5a0aa8b4180b10d602..6fa4f1984b6ba6b3a7aecd05e54477ebf141af94 100644
--- a/lib/TSDocConfigFile.js
+++ b/lib/TSDocConfigFile.js
@@ -31,8 +31,7 @@ const ajv_1 = __importDefault(require("ajv"));
const jju = __importStar(require("jju"));
const ajv = new ajv_1.default({ verbose: true });
function initializeSchemaValidator() {
- const jsonSchemaPath = resolve.sync('@microsoft/tsdoc/schemas/tsdoc.schema.json', { basedir: __dirname });
- const jsonSchemaContent = fs.readFileSync(jsonSchemaPath).toString();
+ const jsonSchemaContent = "{\"title\":\"TSDoc Configuration\",\"description\":\"Describes the TSDoc configuration for a TypeScript project\",\"type\":\"object\",\"properties\":{\"$schema\":{\"description\":\"Part of the JSON Schema standard, this optional keyword declares the URL of the schema that the file conforms to. Editors may download the schema and use it to perform syntax highlighting.\",\"type\":\"string\"},\"extends\":{\"description\":\"Optionally specifies one or more JSON config files that will be combined with this file. This provides a way for standard settings to be shared across multiple projects. Important: The \\\"extends\\\" paths are resolved using NodeJS module resolution, so a path to a local file MUST be prefixed with \\\"./\\\".\",\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"noStandardTags\":{\"description\":\"By default, the config file loader will predefine all of the standardized TSDoc tags. To disable this and start with a completely empty configuration, set \\\"noStandardTags\\\"=true.\",\"type\":\"boolean\"},\"tagDefinitions\":{\"description\":\"Additional tags to support when parsing documentation comments with TSDoc.\",\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/tsdocTagDefinition\"}},\"supportedHtmlElements\":{\"description\":\"The HTML element names that are supported in this configuration. Used in conjunction with the \\\"reportUnsupportedHtmlElements\\\" setting.\",\"type\":\"array\",\"items\":{\"type\":\"string\",\"pattern\":\"^[a-zA-Z0-9-]+$\"}},\"reportUnsupportedHtmlElements\":{\"description\":\"Whether an error should be reported when an unsupported HTML element is encountered in a doc comment. Defaults to \\\"true\\\" if the \\\"supportedHtmlElements\\\" field is present in this file, \\\"false\\\" if not.\",\"type\":\"boolean\"},\"supportForTags\":{\"description\":\"A collection of key/value pairs. The key is a TSDoc tag name (e.g. \\\"@myTag\\\") that must be defined in this configuration. The value is a boolean indicating whether the tag is supported. The TSDoc parser may report warnings when unsupported tags are encountered. If \\\"supportForTags\\\" is specified for at least one tag, then the \\\"reportUnsupportedTags\\\" validation check is enabled by default.\",\"type\":\"object\",\"patternProperties\":{\"@[a-zA-Z][a-zA-Z0-9]*$\":{\"type\":\"boolean\"}},\"additionalItems\":false}},\"required\":[\"$schema\"],\"additionalProperties\":false,\"definitions\":{\"tsdocTagDefinition\":{\"description\":\"Configuration for a custom supported TSDoc tag.\",\"type\":\"object\",\"properties\":{\"tagName\":{\"description\":\"Name of the custom tag. TSDoc tag names start with an at-sign (@) followed by ASCII letters using camelCase capitalization.\",\"type\":\"string\"},\"syntaxKind\":{\"description\":\"Syntax kind of the custom tag. \\\"inline\\\" means that this tag can appear inside other documentation sections (example: {@link}). \\\"block\\\" means that this tag starts a new documentation section (example: @remarks). \\\"modifier\\\" means that this tag's presence indicates an aspect of the associated API item (example: @internal).\",\"type\":\"string\",\"enum\":[\"inline\",\"block\",\"modifier\"]},\"allowMultiple\":{\"description\":\"If true, then this tag may appear multiple times in a doc comment. By default, a tag may only appear once.\",\"type\":\"boolean\"}},\"required\":[\"tagName\",\"syntaxKind\"],\"additionalProperties\":false}}}";
const jsonSchema = jju.parse(jsonSchemaContent, { mode: 'cjson' });
return ajv.compile(jsonSchema);
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1,11 +0,0 @@
nodeLinker: node-modules
plugins:
- path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs
spec: "@yarnpkg/plugin-interactive-tools"
- path: .yarn/plugins/@yarnpkg/plugin-workspace-tools.cjs
spec: "@yarnpkg/plugin-workspace-tools"
- path: .yarn/plugins/@yarnpkg/plugin-version.cjs
spec: "@yarnpkg/plugin-version"
yarnPath: .yarn/releases/yarn-3.2.1.cjs

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.

157
README.md
View File

@@ -1,130 +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://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>
</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)
discord.js is a powerful [Node.js](https://nodejs.org) 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/)
- Object-oriented
- Predictable abstractions
- Performant
- 100% coverage of the Discord API
## Installation
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.
**Node.js 16.9.0 or newer is required.**
### Installation
```sh-session
npm install discord.js
yarn add discord.js
pnpm add discord.js
```
**Requires node 0.12+**
### Optional packages
`npm install --save discord.js`
- [zlib-sync](https://www.npmjs.com/package/zlib-sync) for WebSocket data compression and inflation (`npm install zlib-sync`)
- [erlpack](https://github.com/discord/erlpack) for significantly faster WebSocket data (de)serialisation (`npm install discord/erlpack`)
- [bufferutil](https://www.npmjs.com/package/bufferutil) for a much faster WebSocket connection (`npm install bufferutil`)
- [utf-8-validate](https://www.npmjs.com/package/utf-8-validate) in combination with `bufferutil` for much faster WebSocket processing (`npm install utf-8-validate`)
- [@discordjs/voice](https://www.npmjs.com/package/@discordjs/voice) for interacting with the Discord Voice API (`npm install @discordjs/voice`)
If you don't need voice support:
## Example usage
`npm install --save --no-optional discord.js`
Install discord.js:
```sh-session
npm install discord.js
yarn add discord.js
pnpm add discord.js
```
Register a slash command against the Discord API:
---
### Example: ping-pong
```js
const { REST, Routes } = require('discord.js');
var Discord = require("discord.js");
const commands = [
{
name: 'ping',
description: 'Replies with Pong!',
},
];
var mybot = new Discord.Client();
const rest = new REST({ version: '10' }).setToken('token');
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(Routes.applicationCommands(CLIENT_ID), { body: commands });
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
```
Afterwards we can create a quite simple example bot:
```js
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
mybot.on("message", function(message) {
if(message.content === "ping") {
mybot.reply(message, "pong");
}
});
client.on('interactionCreate', async (interaction) => {
if (!interaction.isChatInputCommand()) return;
if (interaction.commandName === 'ping') {
await interaction.reply('Pong!');
}
});
client.login('token');
mybot.loginWithToken("token");
// If you still need to login with email and password, use mybot.login("email", "password");
```
---
## Links
### Contributing
- [Website](https://discord.js.org/) ([source](https://github.com/discordjs/discord.js/tree/main/packages/website))
- [Documentation](https://discord.js.org/#/docs)
- [Guide](https://discordjs.guide/) ([source](https://github.com/discordjs/guide))
See also the [Update Guide](https://discordjs.guide/additional-info/changes-in-v14.html), including updated and removed items in the library.
- [discord.js Discord server](https://discord.gg/djs)
- [Discord API Discord server](https://discord.gg/discord-api)
- [GitHub](https://github.com/discordjs/discord.js)
- [npm](https://www.npmjs.com/package/discord.js)
- [Related libraries](https://discord.com/developers/docs/topics/community-resources#libraries)
Feel free to contribute! Just clone the repo and edit the files in the **src folder, not the lib folder.**
### Extensions
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`
- [RPC](https://www.npmjs.com/package/discord-rpc) ([source](https://github.com/discordjs/RPC))
---
## Contributing
### Related Projects
Before creating an issue, please ensure that it hasn't already been reported/suggested, and double-check the
[documentation](https://discord.js.org/#/docs).
See [the contribution guide](https://github.com/discordjs/discord.js/blob/main/.github/CONTRIBUTING.md) if you'd like to submit a PR.
A list of other Discord API libraries [can be found here](https://discordapi.com/unofficial/libs.html)
## Help
---
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 don't hesitate to join our official [discord.js Server](https://discord.gg/djs).
### 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,95 +0,0 @@
import { relative, resolve } from 'node:path';
import glob from 'fast-glob';
import isCi from 'is-ci';
import typescript from 'rollup-plugin-typescript2';
import { defineBuildConfig, BuildEntry } from 'unbuild';
interface ConfigOptions {
entries: (BuildEntry | string)[];
minify: boolean;
emitCJS: boolean;
externals: string[];
cjsBridge: boolean;
sourcemap: boolean;
preserveModules: boolean;
preserveModulesRoot: string;
declaration: boolean;
typeCheck: boolean;
}
export function createUnbuildConfig({
entries = [{ builder: 'rollup', input: 'src/index' }],
minify = false,
emitCJS = true,
cjsBridge = true,
externals = [],
sourcemap = true,
preserveModules = true,
preserveModulesRoot = 'src',
declaration = true,
typeCheck = isCi,
}: Partial<ConfigOptions> = {}) {
const files = glob
.sync('**', { cwd: 'src' })
.map((file) => [`${file.slice(0, -2)}cjs`, `${file.slice(0, -2)}mjs`])
.flat();
return defineBuildConfig({
entries,
clean: true,
rollup: {
esbuild: {
minify,
minifyIdentifiers: false,
},
emitCJS,
cjsBridge,
json: {
namedExports: false,
preferConst: true,
},
},
externals: [...files, ...externals],
hooks: {
'rollup:options': (_, options) => {
// @ts-expect-error: This will always be an array
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
options.output![0] = {
// @ts-expect-error: This will always be an array
...options.output![0],
sourcemap,
preserveModules,
preserveModulesRoot,
};
if (emitCJS) {
// @ts-expect-error: This will always be an array
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
options.output![1] = {
// @ts-expect-error: This will always be an array
...options.output![1],
sourcemap,
preserveModules,
preserveModulesRoot,
};
}
if (declaration) {
options.plugins?.unshift(
typescript({
check: typeCheck,
tsconfig: relative(__dirname, resolve(process.cwd(), 'tsconfig.json')),
tsconfigOverride: {
compilerOptions: {
emitDeclarationOnly: true,
},
},
}),
);
}
},
},
});
}

View File

@@ -1,26 +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:
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

@@ -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"];

2946
lib/Client/InternalClient.js Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,407 @@
"use strict";
/* global Buffer */
/**
* Resolves supplied data type to a Channel. If a String, it should be a Channel ID.
* @typedef {(Channel|Server|Message|User|String)} ChannelResolvable
*/
/**
* Resolves supplied data type to a TextChannel or PMChannel. If a String, it should be a Channel ID.
* @typedef {(TextChannel|PMChannel|Server|Message|User|String)} TextChannelResolvable
*/
/**
* If given an array, turns it into a newline-separated string.
* @typedef {(String|Array)} StringResolvable
*/
/**
* Resolves supplied data type to a Message. If a channel, it is the latest message from that channel.
* @typedef {(Message|TextChannel|PMChannel)} MessageResolvable
*/
/**
* Resolves supplied data type to a Server. If a String, it should be the server's ID.
* @typedef {(Server|ServerChannel|Message|String)} ServerResolvable
*/
/**
* Resolves supplied data type to something that can be attached to a message. If a String, it can be an URL or a path to a local file.
* @typedef {(String|ReadableStream|Buffer)} FileResolvable
*/
/**
* Resolves supplied data type to an invite ID. If a String, it should be an ID or a direct URL to the invite.
* @typedef {(Invite|String)} InviteIDResolvable
*/
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var _fs = require("fs");
var _fs2 = _interopRequireDefault(_fs);
var _superagent = require("superagent");
var _superagent2 = _interopRequireDefault(_superagent);
var _StructuresUser = require("../../Structures/User");
var _StructuresUser2 = _interopRequireDefault(_StructuresUser);
var _StructuresChannel = require("../../Structures/Channel");
var _StructuresChannel2 = _interopRequireDefault(_StructuresChannel);
var _StructuresTextChannel = require("../../Structures/TextChannel");
var _StructuresTextChannel2 = _interopRequireDefault(_StructuresTextChannel);
var _StructuresVoiceChannel = require("../../Structures/VoiceChannel");
var _StructuresVoiceChannel2 = _interopRequireDefault(_StructuresVoiceChannel);
var _StructuresServerChannel = require("../../Structures/ServerChannel");
var _StructuresServerChannel2 = _interopRequireDefault(_StructuresServerChannel);
var _StructuresPMChannel = require("../../Structures/PMChannel");
var _StructuresPMChannel2 = _interopRequireDefault(_StructuresPMChannel);
var _StructuresRole = require("../../Structures/Role");
var _StructuresRole2 = _interopRequireDefault(_StructuresRole);
var _StructuresServer = require("../../Structures/Server");
var _StructuresServer2 = _interopRequireDefault(_StructuresServer);
var _StructuresMessage = require("../../Structures/Message");
var _StructuresMessage2 = _interopRequireDefault(_StructuresMessage);
var _StructuresInvite = require("../../Structures/Invite");
var _StructuresInvite2 = _interopRequireDefault(_StructuresInvite);
var _StructuresWebhook = require("../../Structures/Webhook");
var _StructuresWebhook2 = _interopRequireDefault(_StructuresWebhook);
var _VoiceVoiceConnection = require("../../Voice/VoiceConnection");
var _VoiceVoiceConnection2 = _interopRequireDefault(_VoiceVoiceConnection);
var Resolver = (function () {
function Resolver(internal) {
_classCallCheck(this, Resolver);
this.internal = internal;
}
Resolver.prototype.resolveToBase64 = function resolveToBase64(resource) {
if (resource instanceof Buffer) {
resource = resource.toString("base64");
resource = "data:image/jpg;base64," + resource;
}
return resource;
};
Resolver.prototype.resolveInviteID = function resolveInviteID(resource) {
if (resource instanceof _StructuresInvite2["default"]) {
return resource.id;
}
if (typeof resource === "string" || resource instanceof String) {
if (resource.indexOf("http") === 0) {
var split = resource.split("/");
return split.pop();
}
return resource;
}
return null;
};
Resolver.prototype.resolveServer = function resolveServer(resource) {
if (resource instanceof _StructuresServer2["default"]) {
return resource;
}
if (resource instanceof _StructuresServerChannel2["default"]) {
return resource.server;
}
if (resource instanceof String || typeof resource === "string") {
return this.internal.servers.get("id", resource);
}
if (resource instanceof _StructuresMessage2["default"]) {
if (resource.channel instanceof _StructuresTextChannel2["default"]) {
return resource.channel.server;
}
}
return null;
};
Resolver.prototype.resolveRole = function resolveRole(resource) {
if (resource instanceof _StructuresRole2["default"]) {
return resource;
}
if (resource instanceof String || typeof resource === "string") {
var role = null;
for (var _iterator = this.internal.servers, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var server = _ref;
if (role = server.roles.get("id", resource)) {
return role;
}
}
}
return null;
};
Resolver.prototype.resolveFile = function resolveFile(resource) {
if (typeof resource === "string" || resource instanceof String) {
if (/^https?:\/\//.test(resource)) {
return new Promise(function (resolve, reject) {
_superagent2["default"].get(resource).buffer().parse(function (res, cb) {
res.setEncoding("binary");
res.data = "";
res.on("data", function (chunk) {
res.data += chunk;
});
res.on("end", function () {
cb(null, new Buffer(res.data, "binary"));
});
}).end(function (err, res) {
if (err) {
return reject(err);
}
return resolve(res.body);
});
});
} else {
return Promise.resolve(resource);
}
}
return Promise.resolve(resource);
};
Resolver.prototype.resolveMentions = function resolveMentions(resource, channel) {
var _mentions = [];
var changed = resource;
for (var _iterator2 = resource.match(/<@\!?[0-9]+>/g) || [], _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var mention = _ref2;
// username mention
if (mention[2] === '!') {
var user = this.internal.users.get("id", mention.substring(3, mention.length - 1));
if (user) {
_mentions.push(user);
var details = channel.server && channel.server.detailsOf(user);
if (details) {
changed = changed.replace(new RegExp(mention, "g"), "@" + (details.nick || user.username + "#" + user.discriminator));
}
}
} else {
var user = this.internal.users.get("id", mention.substring(2, mention.length - 1));
if (user) {
_mentions.push(user);
changed = changed.replace(new RegExp(mention, "g"), "@" + (user.username + "#" + user.discriminator));
}
}
}
if (channel && channel.server && channel.server.roles) {
for (var _iterator3 = resource.match(/<@&[0-9]+>/g) || [], _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var mention = _ref3;
// role mention
var role = channel.server.roles.get("id", mention.substring(3, mention.length - 1));
if (role) {
changed = changed.replace(new RegExp(mention, "g"), "@" + role.name);
}
}
}
for (var _iterator4 = resource.match(/<#[0-9]+>/g) || [], _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) {
var _ref4;
if (_isArray4) {
if (_i4 >= _iterator4.length) break;
_ref4 = _iterator4[_i4++];
} else {
_i4 = _iterator4.next();
if (_i4.done) break;
_ref4 = _i4.value;
}
var mention = _ref4;
// channel mention
var channel = this.internal.channels.get("id", mention.substring(2, mention.length - 1));
if (channel) {
changed = changed.replace(new RegExp(mention, "g"), "#" + channel.name);
}
}
return [_mentions, changed];
};
Resolver.prototype.resolveString = function resolveString(resource) {
// accepts Array, Channel, Server, User, Message, String and anything
// toString()-able
if (resource instanceof Array) {
resource = resource.join("\n");
}
return resource.toString();
};
Resolver.prototype.resolveUser = function resolveUser(resource) {
/*
accepts a Message, Channel, Server, String ID, User, PMChannel
*/
if (resource instanceof _StructuresUser2["default"]) {
return resource;
}
if (resource instanceof _StructuresMessage2["default"]) {
return resource.author;
}
if (resource instanceof _StructuresTextChannel2["default"]) {
var lmsg = resource.lastMessage;
if (lmsg) {
return lmsg.author;
}
}
if (resource instanceof _StructuresServer2["default"]) {
return resource.owner;
}
if (resource instanceof _StructuresPMChannel2["default"]) {
return resource.recipient;
}
if (resource instanceof String || typeof resource === "string") {
return this.internal.users.get("id", resource);
}
return null;
};
Resolver.prototype.resolveWebhook = function resolveWebhook(resource) {
/*
accepts a Webhook
*/
if (resource instanceof _StructuresWebhook2["default"]) {
return Promise.resolve(resource);
}
if (resource instanceof String || typeof resource === "string") {
var server = this.internal.servers.find(function (s) {
return s.webhooks.has("id", resource);
});
if (server) {
return Promise.resolve(server.webhooks.get("id", resource));
}
}
var error = new Error("Could not resolve webhook");
error.resource = resource;
return Promise.reject(error);
};
Resolver.prototype.resolveMessage = function resolveMessage(resource) {
// accepts a Message, PMChannel & TextChannel
if (resource instanceof _StructuresTextChannel2["default"] || resource instanceof _StructuresPMChannel2["default"]) {
return resource.lastMessage;
}
if (resource instanceof _StructuresMessage2["default"]) {
return resource;
}
return null;
};
Resolver.prototype.resolveChannel = function resolveChannel(resource) {
/*
accepts a Message, Channel, VoiceConnection, Server, String ID, User
*/
if (resource instanceof _StructuresMessage2["default"]) {
return Promise.resolve(resource.channel);
}
if (resource instanceof _StructuresChannel2["default"]) {
return Promise.resolve(resource);
}
if (resource instanceof _VoiceVoiceConnection2["default"]) {
return Promise.resolve(resource.voiceChannel);
}
if (resource instanceof _StructuresServer2["default"]) {
return Promise.resolve(resource.defaultChannel);
}
if (resource instanceof String || typeof resource === "string") {
var user = this.internal.users.get("id", resource);
if (user) {
resource = user;
} else {
return Promise.resolve(this.internal.channels.get("id", resource) || this.internal.private_channels.get("id", resource));
}
}
if (resource instanceof _StructuresUser2["default"]) {
// see if a PM exists
for (var _iterator5 = this.internal.private_channels, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : _iterator5[Symbol.iterator]();;) {
var _ref5;
if (_isArray5) {
if (_i5 >= _iterator5.length) break;
_ref5 = _iterator5[_i5++];
} else {
_i5 = _iterator5.next();
if (_i5.done) break;
_ref5 = _i5.value;
}
var pmchat = _ref5;
if (pmchat.recipients.length === 1 && pmchat.recipient && pmchat.recipient.equals(resource)) {
return Promise.resolve(pmchat);
}
}
// PM does not exist :\
return this.internal.startPM(resource);
}
var error = new Error("Could not resolve channel");
error.resource = resource;
return Promise.reject(error);
};
return Resolver;
})();
exports["default"] = Resolver;
module.exports = exports["default"];

189
lib/Constants.js Normal file
View File

@@ -0,0 +1,189 @@
"use strict";
exports.__esModule = true;
var Constants = {};
var API = Constants.API = "https://discordapp.com/api";
exports.API = API;
var CDN = Constants.CDN = "https://cdn.discordapp.com";
exports.CDN = CDN;
var Endpoints = Constants.Endpoints = {
// general endpoints
LOGIN: API + "/auth/login",
LOGOUT: API + "/auth/logout",
ME: API + "/users/@me",
ME_CHANNELS: API + "/users/@me/channels",
ME_SERVER: function ME_SERVER(serverID) {
return Endpoints.ME + "/guilds/" + serverID;
},
OAUTH2_APPLICATION: function OAUTH2_APPLICATION(appID) {
return API + "/oauth2/applications/" + appID;
},
ME_NOTES: API + "/users/@me/notes",
GATEWAY: API + "/gateway",
AVATAR: function AVATAR(userID, avatar) {
return API + "/users/" + userID + "/avatars/" + avatar + ".jpg";
},
INVITE: function INVITE(id) {
return API + "/invite/" + id;
},
// emojis
EMOJI: function EMOJI(emojiID) {
return CDN + "/emojis/" + emojiID + ".png";
},
// servers
SERVERS: API + "/guilds",
SERVER: function SERVER(serverID) {
return Endpoints.SERVERS + "/" + serverID;
},
SERVER_ICON: function SERVER_ICON(serverID, hash) {
return Endpoints.SERVER(serverID) + "/icons/" + hash + ".jpg";
},
SERVER_PRUNE: function SERVER_PRUNE(serverID) {
return Endpoints.SERVER(serverID) + "/prune";
},
SERVER_EMBED: function SERVER_EMBED(serverID) {
return Endpoints.SERVER(serverID) + "/embed";
},
SERVER_INVITES: function SERVER_INVITES(serverID) {
return Endpoints.SERVER(serverID) + "/invites";
},
SERVER_ROLES: function SERVER_ROLES(serverID) {
return Endpoints.SERVER(serverID) + "/roles";
},
SERVER_BANS: function SERVER_BANS(serverID) {
return Endpoints.SERVER(serverID) + "/bans";
},
SERVER_INTEGRATIONS: function SERVER_INTEGRATIONS(serverID) {
return Endpoints.SERVER(serverID) + "/integrations";
},
SERVER_MEMBERS: function SERVER_MEMBERS(serverID) {
return Endpoints.SERVER(serverID) + "/members";
},
SERVER_CHANNELS: function SERVER_CHANNELS(serverID) {
return Endpoints.SERVER(serverID) + "/channels";
},
SERVER_WEBHOOKS: function SERVER_WEBHOOKS(serverID) {
return Endpoints.SERVER(serverID) + "/webhooks";
},
// channels
CHANNELS: API + "/channels",
CHANNEL: function CHANNEL(channelID) {
return Endpoints.CHANNELS + "/" + channelID;
},
CHANNEL_MESSAGES: function CHANNEL_MESSAGES(channelID) {
return Endpoints.CHANNEL(channelID) + "/messages";
},
CHANNEL_INVITES: function CHANNEL_INVITES(channelID) {
return Endpoints.CHANNEL(channelID) + "/invites";
},
CHANNEL_TYPING: function CHANNEL_TYPING(channelID) {
return Endpoints.CHANNEL(channelID) + "/typing";
},
CHANNEL_PERMISSIONS: function CHANNEL_PERMISSIONS(channelID) {
return Endpoints.CHANNEL(channelID) + "/permissions";
},
CHANNEL_MESSAGE: function CHANNEL_MESSAGE(channelID, messageID) {
return Endpoints.CHANNEL_MESSAGES(channelID) + "/" + messageID;
},
CHANNEL_PINS: function CHANNEL_PINS(channelID) {
return Endpoints.CHANNEL(channelID) + "/pins";
},
CHANNEL_PIN: function CHANNEL_PIN(channelID, messageID) {
return Endpoints.CHANNEL_PINS(channelID) + "/" + messageID;
},
CHANNEL_WEBHOOKS: function CHANNEL_WEBHOOKS(channelID) {
return Endpoints.CHANNEL(channelID) + "/webhooks";
},
// webhooks
WEBHOOKS: API + "/webhooks",
WEBHOOK: function WEBHOOK(webhookID) {
return Endpoints.WEBHOOKS + "/" + webhookID;
},
WEBHOOK_WITH_TOKEN: function WEBHOOK_WITH_TOKEN(webhookID, webhookToken) {
return Endpoints.WEBHOOKS + "/" + webhookToken;
},
WEBHOOK_MESSAGE: function WEBHOOK_MESSAGE(webhookID, webhookToken) {
return Endpoints.WEBHOOK(webhookID) + "/" + webhookToken;
},
WEBHOOK_MESSAGE_SLACK: function WEBHOOK_MESSAGE_SLACK(webhookID, webhookToken) {
return Endpoints.WEBHOOK_MESSAGE(webhookID, webhookToken) + "/slack";
},
// friends
FRIENDS: API + "/users/@me/relationships"
};
exports.Endpoints = Endpoints;
var Permissions = Constants.Permissions = {
// general
createInstantInvite: 1 << 0,
kickMembers: 1 << 1,
banMembers: 1 << 2,
administrator: 1 << 3,
manageChannels: 1 << 4,
manageChannel: 1 << 4,
manageServer: 1 << 5,
changeNickname: 1 << 26,
manageNicknames: 1 << 27,
manageRoles: 1 << 28,
managePermissions: 1 << 28,
// text
readMessages: 1 << 10,
sendMessages: 1 << 11,
sendTTSMessages: 1 << 12,
manageMessages: 1 << 13,
embedLinks: 1 << 14,
attachFiles: 1 << 15,
readMessageHistory: 1 << 16,
mentionEveryone: 1 << 17,
// voice
voiceConnect: 1 << 20,
voiceSpeak: 1 << 21,
voiceMuteMembers: 1 << 22,
voiceDeafenMembers: 1 << 23,
voiceMoveMembers: 1 << 24,
voiceUseVAD: 1 << 25
};
exports.Permissions = Permissions;
var PacketType = Constants.PacketType = {
CHANNEL_CREATE: "CHANNEL_CREATE",
CHANNEL_DELETE: "CHANNEL_DELETE",
CHANNEL_UPDATE: "CHANNEL_UPDATE",
MESSAGE_CREATE: "MESSAGE_CREATE",
MESSAGE_DELETE: "MESSAGE_DELETE",
MESSAGE_DELETE_BULK: "MESSAGE_DELETE_BULK",
MESSAGE_UPDATE: "MESSAGE_UPDATE",
PRESENCE_UPDATE: "PRESENCE_UPDATE",
READY: "READY",
RESUME: "RESUME",
SERVER_BAN_ADD: "GUILD_BAN_ADD",
SERVER_BAN_REMOVE: "GUILD_BAN_REMOVE",
SERVER_CREATE: "GUILD_CREATE",
SERVER_DELETE: "GUILD_DELETE",
SERVER_MEMBER_ADD: "GUILD_MEMBER_ADD",
SERVER_MEMBER_REMOVE: "GUILD_MEMBER_REMOVE",
SERVER_MEMBER_UPDATE: "GUILD_MEMBER_UPDATE",
SERVER_MEMBERS_CHUNK: "GUILD_MEMBERS_CHUNK",
SERVER_ROLE_CREATE: "GUILD_ROLE_CREATE",
SERVER_ROLE_DELETE: "GUILD_ROLE_DELETE",
SERVER_ROLE_UPDATE: "GUILD_ROLE_UPDATE",
SERVER_SYNC: "GUILD_SYNC",
SERVER_UPDATE: "GUILD_UPDATE",
TYPING: "TYPING_START",
USER_UPDATE: "USER_UPDATE",
USER_NOTE_UPDATE: "USER_NOTE_UPDATE",
VOICE_STATE_UPDATE: "VOICE_STATE_UPDATE",
FRIEND_ADD: "RELATIONSHIP_ADD",
FRIEND_REMOVE: "RELATIONSHIP_REMOVE"
};
exports.PacketType = PacketType;
exports["default"] = Constants;

50
lib/Structures/Channel.js Normal file
View File

@@ -0,0 +1,50 @@
"use strict";
exports.__esModule = true;
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _UtilEquality = require("../Util/Equality");
var _UtilEquality2 = _interopRequireDefault(_UtilEquality);
var _UtilArgumentRegulariser = require("../Util/ArgumentRegulariser");
var Channel = (function (_Equality) {
_inherits(Channel, _Equality);
function Channel(data, client) {
_classCallCheck(this, Channel);
_Equality.call(this);
this.id = data.id;
this.client = client;
}
Channel.prototype["delete"] = function _delete() {
return this.client.deleteChannel.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments));
};
_createClass(Channel, [{
key: "createdAt",
get: function get() {
return new Date(+this.id / 4194304 + 1420070400000);
}
}, {
key: "isPrivate",
get: function get() {
return !this.server;
}
}]);
return Channel;
})(_UtilEquality2["default"]);
exports["default"] = Channel;
module.exports = exports["default"];

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