Merge branch 'indev'

This commit is contained in:
Amish Shah
2016-09-04 13:27:23 +01:00
302 changed files with 9233 additions and 534911 deletions

View File

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

View File

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

133
.eslintrc.json Normal file
View File

@@ -0,0 +1,133 @@
{
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 6
},
"env": {
"es6": true,
"node": true
},
"rules": {
"no-extra-parens": ["warn", "all", {
"nestedBinaryExpressions": false
}],
"valid-jsdoc": ["error", {
"requireReturn": false,
"requireReturnDescription": false,
"preferType": {
"String": "string",
"Number": "number",
"Boolean": "boolean",
"Function": "function",
"object": "Object",
"date": "Date",
"error": "Error"
},
"prefer": {
"return": "returns"
}
}],
"accessor-pairs": "warn",
"array-callback-return": "error",
"complexity": "warn",
"consistent-return": "error",
"curly": ["error", "multi-line", "consistent"],
"dot-location": ["error", "property"],
"dot-notation": "error",
"eqeqeq": "error",
"no-empty-function": "error",
"no-floating-decimal": "error",
"no-implied-eval": "error",
"no-invalid-this": "error",
"no-lone-blocks": "error",
"no-multi-spaces": "error",
"no-new-func": "error",
"no-new-wrappers": "error",
"no-new": "error",
"no-octal-escape": "error",
"no-return-assign": "error",
"no-self-compare": "error",
"no-sequences": "error",
"no-throw-literal": "error",
"no-unmodified-loop-condition": "error",
"no-unused-expressions": "error",
"no-useless-call": "error",
"no-useless-concat": "error",
"no-useless-escape": "error",
"no-void": "error",
"no-warning-comments": "warn",
"wrap-iife": "error",
"yoda": "error",
"no-label-var": "error",
"no-shadow": "error",
"no-undef-init": "error",
"callback-return": "error",
"handle-callback-err": "error",
"no-mixed-requires": "error",
"no-new-require": "error",
"no-path-concat": "error",
"no-process-env": "error",
"array-bracket-spacing": "error",
"block-spacing": "error",
"brace-style": ["error", "1tbs", { "allowSingleLine": true }],
"comma-dangle": ["error", "always-multiline"],
"comma-spacing": "error",
"comma-style": "error",
"computed-property-spacing": "error",
"consistent-this": ["error", "$this"],
"eol-last": "error",
"func-names": "error",
"func-style": ["error", "declaration", { "allowArrowFunctions": true }],
"indent": ["error", 2, { "SwitchCase": 1 }],
"key-spacing": "error",
"keyword-spacing": "error",
"max-depth": "error",
"max-len": ["error", 120, 2],
"max-nested-callbacks": ["error", { "max": 4 }],
"max-statements-per-line": ["error", { "max": 2 }],
"new-cap": "error",
"newline-per-chained-call": ["error", { "ignoreChainWithDepth": 3 }],
"no-array-constructor": "error",
"no-inline-comments": "error",
"no-lonely-if": "error",
"no-mixed-operators": "error",
"no-multiple-empty-lines": ["error", { "max": 2, "maxEOF": 1, "maxBOF": 0 }],
"no-new-object": "error",
"no-spaced-func": "error",
"no-trailing-spaces": "error",
"no-unneeded-ternary": "error",
"no-whitespace-before-property": "error",
"object-curly-spacing": ["error", "always"],
"operator-assignment": "error",
"operator-linebreak": ["error", "after"],
"padded-blocks": ["error", "never"],
"quote-props": ["error", "as-needed"],
"quotes": ["error", "single", { "avoidEscape": true, "allowTemplateLiterals": true }],
"semi-spacing": "error",
"semi": "error",
"space-before-blocks": "error",
"space-before-function-paren": ["error", "never"],
"space-in-parens": "error",
"space-infix-ops": "error",
"space-unary-ops": "error",
"spaced-comment": "error",
"unicode-bom": "error",
"arrow-body-style": "error",
"arrow-spacing": "error",
"no-duplicate-imports": "error",
"no-useless-computed-key": "error",
"no-useless-constructor": "error",
"prefer-arrow-callback": "error",
"prefer-rest-params": "error",
"prefer-spread": "error",
"prefer-template": "error",
"rest-spread-spacing": "error",
"template-curly-spacing": "error",
"yield-star-spacing": "error"
}
}

76
.gitignore vendored
View File

@@ -1,40 +1,38 @@
# Created by https://www.gitignore.io
hydrabot/config.json
hydrabot/authority.json
hydrabot/tokencache.json
esdoc/
.tmp/
### Node ###
# Logs
logs
*.log
# Runtime data
pids
*.pid
*.seed
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# node-waf configuration
.lock-wscript
# 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
# Created by https://www.gitignore.io
.tmp/
.vscode/
### Node ###
# Logs
logs
*.log
test/auth.json
# Runtime data
pids
*.pid
*.seed
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# node-waf configuration
.lock-wscript
# 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

10
.jscsrc Normal file
View File

@@ -0,0 +1,10 @@
{
"preset": "airbnb",
"validateIndentation": "\t",
"maximumLineLength": 140,
"maxErrors": 5000,
"disallowMultipleVarDecl": false,
"disallowSpacesInsideObjectBrackets": false,
"disallowMixedSpacesAndTabs": false,
"excludeFiles": []
}

View File

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

View File

@@ -1,14 +1,7 @@
language: node_js
node_js:
- stable
cache:
directories:
- node_modules
branches:
only:
- master
- indev
- indev-rewrite
before_install: npm install -g grunt-cli eslint
install: npm install
before_script: grunt --dev
language: node_js
node_js:
- "6"
cache:
directories:
- node_modules
install: npm install

30
.vscode/launch.json vendored
View File

@@ -1,30 +0,0 @@
{
"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
}
]
}

View File

@@ -1,6 +0,0 @@
// Place your settings in this file to overwrite default and user settings.
{
"editor.wrappingColumn": 0,
"editor.formatOnType": true,
"files.trimTrailingWhitespace": true
}

220
.vscode/tasks.json vendored
View File

@@ -1,220 +0,0 @@
// 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,7 +0,0 @@
### 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`

View File

@@ -199,4 +199,3 @@
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.

129
README.md
View File

@@ -1,77 +1,52 @@
<p align="center">
<a href="https://hydrabolt.github.io/discord.js">
<img alt="discord.js" src="http://i.imgur.com/sPOLh9y.png" width="546">
</a>
</p>
[![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)
[![NPM](https://nodei.co/npm/discord.js.png?downloads=true&stars=true)](https://nodei.co/npm/discord.js/)
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.
### Installation
**Requires node 0.12+**
`npm install --save discord.js`
If you don't need voice support:
`npm install --save --no-optional discord.js`
---
### Example: ping-pong
```js
var Discord = require("discord.js");
var mybot = new Discord.Client();
mybot.on("message", function(message) {
if(message.content === "ping") {
mybot.reply(message, "pong");
}
});
mybot.loginWithToken("token");
// If you still need to login with email and password, use mybot.login("email", "password");
```
---
### Contributing
Feel free to contribute! Just clone the repo and edit the files in the **src folder, not the lib folder.**
Whenever you come to making a pull request, make sure it's to the *indev* branch and that you have built the lib files by running `grunt --dev`
---
### Related Projects
A list of other Discord API libraries [can be found here](https://discordapi.com/unofficial/libs.html)
---
### Links
**[Documentation](http://discordjs.readthedocs.org/en/latest/)**
**[GitHub](https://github.com/discord-js/discord.js)**
**[Wiki](https://github.com/discord-js/discord.js/wiki)**
**[Website](http://hydrabolt.github.io/discord.js/)**
**[NPM](http://npmjs.com/package/discord.js)**
---
### Contact
If you have an issue or want to know if a feature exists, [read the documentation](http://discordjs.readthedocs.org/en/latest/) before contacting me about any issues! If it's badly/wrongly implemented, let me know!
If you would like to contact me, you can create an issue on the GitHub repo, e-mail me via the one available on my NPM profile.
Alternatively, you could just send a DM to **hydrabolt** in [**Discord API**](https://discord.gg/0SBTUU1wZTYd2XyW).
<p align="center">
<a href="https://hydrabolt.github.io/discord.js">
<img alt="discord.js" src="http://i.imgur.com/sPOLh9y.png" width="546"><br />
</a>
</p>
[![npm](https://img.shields.io/npm/v/discord.js.svg?maxAge=2592000)](https://www.npmjs.com/package/discord.js)
[![Build Status](https://travis-ci.org/hydrabolt/discord.js.svg)](https://travis-ci.org/hydrabolt/discord.js)
[![David](https://img.shields.io/david/hydrabolt/discord.js.svg?maxAge=2592000)](https://david-dm.org/hydrabolt/discord.js)
[![npm](https://img.shields.io/npm/dt/discord.js.svg?maxAge=2592000)](https://www.npmjs.com/package/discord.js)
[![NPM](https://nodei.co/npm/discord.js.png?downloads=true&stars=true)](https://nodei.co/npm/discord.js/)
discord.js is a a powerful node.js module that allows you to interact with the [Discord API](https://discordapp.com/developers/docs/intro).
## Installation
**Requires node 6.0.0 and above**
```bash
npm install --save discord.js
# or, if you don't want voice support:
npm install --save --no-optional discord.js
```
By default, discord.js uses [opusscript](https://www.npmjs.com/package/opusscript) when playing audio over voice connections. If you're looking to play over multiple voice connections, it might be better to install [node-opus](https://www.npmjs.com/package/node-opus). discord.js will automatically prefer node-opus over opusscript.
## Example Usage
```js
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.on('ready', () => {
console.log('I am ready!');
});
bot.on('message', message => {
if (message.content === 'ping') {
message.reply('pong');
}
});
bot.login('your token');
```
## Links
* [Website](http://hydrabolt.github.io/discord.js/)
* [Documentation](http://hydrabolt.github.io/discord.js/#!/docs/tag/master)
* [GitHub](https://github.com/hydrabolt/discord.js)
* [NPM](https://www.npmjs.com/package/discord.js)
* [Examples](https://github.com/hydrabolt/discord.js/tree/master/examples)
* [Related Libraries](https://discordapi.com/unofficial/libs.html)
## Contact
Before reporting an issue, please read the [documentation](http://hydrabolt.github.io/discord.js/#!/docs/tag/master). If you can't find help there, you can find help in the [Discord API Server](https://discord.gg/rV4BwdK).

View File

@@ -1,8 +0,0 @@
# 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,192 +0,0 @@
# 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."

View File

@@ -1,292 +0,0 @@
# -*- 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.0.0'
# The full version, including alpha/beta/rc tags.
release = '8.0.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.")

10
docs/custom/avatar.js Normal file
View File

@@ -0,0 +1,10 @@
const fs = require('fs');
module.exports = {
category: 'Examples',
name: 'Avatars',
data:
`\`\`\`js
${fs.readFileSync('./docs/custom/examples/avatar.js').toString('utf-8')}
\`\`\``,
};

View File

@@ -0,0 +1,11 @@
# About the Rewrite
The rewrite takes a much more OOP approach than previous versions, which allows code to be much more manageable.
It's been rebuilt from the ground up and should be much more stable, fixing caching issues that affected
older versions and it also has support for new Discord Features, such as emojis.
## Upgrading your code
The rewrite has a _lot_ of breaking changes. Major methods, e.g. `client.sendMessage(channel, message)` have been moved
from the Client class towards their respective classes - `textChannel.sendMessage(message)`. You can find out the full
extent of these changes by looking at the classes in the documentation.
Additionally, some event names and parameters have changed - you should revisit these.

View File

@@ -0,0 +1,16 @@
<p align="center">
<a href="https://hydrabolt.github.io/discord.js">
<img alt="discord.js" src="http://i.imgur.com/sPOLh9y.png" width="546">
</a>
</p>
[![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)
[![NPM](https://nodei.co/npm/discord.js.png?downloads=true&stars=true)](https://nodei.co/npm/discord.js/)
# Welcome!
Welcome to the discord.js rewrite documentation. The rewrite has taken a lot of time, but it should be much more
stable and performance-friendly than previous versions.
## Installation
`npm i --save hydrabolt/discord.js#indev-rewrite`

View File

@@ -0,0 +1,30 @@
/*
Send a user a link to their avatar
*/
// import the discord.js module
const Discord = require('discord.js');
// create an instance of a Discord Client, and call it bot
const bot = new Discord.Client();
// the token of your bot - https://discordapp.com/developers/applications/me
const token = 'your bot token here';
// the ready event is vital, it means that your bot will only start reacting to information
// from Discord _after_ ready is emitted.
bot.on('ready', () => {
console.log('I am ready!');
});
// create an event listener for messages
bot.on('message', message => {
// if the message is "what is my avatar",
if (message.content === 'what is my avatar') {
// send the user's avatar URL
message.reply(message.author.avatarURL);
}
});
// log our bot in
bot.login(token);

View File

@@ -0,0 +1,30 @@
/*
A ping pong bot, whenever you send "ping", it replies "pong".
*/
// import the discord.js module
const Discord = require('discord.js');
// create an instance of a Discord Client, and call it bot
const bot = new Discord.Client();
// the token of your bot - https://discordapp.com/developers/applications/me
const token = 'your bot token here';
// the ready event is vital, it means that your bot will only start reacting to information
// from Discord _after_ ready is emitted.
bot.on('ready', () => {
console.log('I am ready!');
});
// create an event listener for messages
bot.on('message', message => {
// if the message is "ping",
if (message.content === 'ping') {
// send "pong" to the same channel.
message.channel.sendMessage('pong');
}
});
// log our bot in
bot.login(token);

17
docs/custom/index.js Normal file
View File

@@ -0,0 +1,17 @@
const files = [
require('./welcome'),
require('./updating'),
require('./ping_pong'),
require('./avatar'),
];
const categories = {};
for (const file of files) {
file.category = file.category.toLowerCase();
if (!categories[file.category]) {
categories[file.category] = [];
}
categories[file.category].push(file);
}
module.exports = categories;

10
docs/custom/ping_pong.js Normal file
View File

@@ -0,0 +1,10 @@
const fs = require('fs');
module.exports = {
category: 'Examples',
name: 'Ping Pong',
data:
`\`\`\`js
${fs.readFileSync('./docs/custom/examples/ping_pong.js').toString('utf-8')}
\`\`\``,
};

7
docs/custom/updating.js Normal file
View File

@@ -0,0 +1,7 @@
const fs = require('fs');
module.exports = {
category: 'General',
name: 'Updating your code',
data: fs.readFileSync('./docs/custom/documents/updating.md').toString('utf-8'),
};

7
docs/custom/welcome.js Normal file
View File

@@ -0,0 +1,7 @@
const fs = require('fs');
module.exports = {
category: 'General',
name: 'Welcome',
data: fs.readFileSync('./docs/custom/documents/welcome.md').toString('utf-8'),
};

1
docs/docs.json Normal file

File diff suppressed because one or more lines are too long

View File

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

View File

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

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

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

@@ -1,31 +0,0 @@
.. 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`_

View File

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

View File

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

View File

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

View File

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

@@ -1,59 +0,0 @@
.. 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_

View File

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

View File

@@ -1,180 +0,0 @@
.. 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, 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_
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

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

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

View File

@@ -1,109 +0,0 @@
.. 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.
--------
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);
}
-----
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
-----------------
Sends Hello to "general" in "my_server".
.. code-block:: javascript
var channel = client.servers.get("name", "my_server").channels.get("name", "general");
client.sendMessage(channel, "Hello");
You can also use a `Message`_ object as an parameter. This example sends "Hello" to the channel the message was sent from.
.. code-block:: javascript
client.on('message', function(message) {
client.sendMessage(message, "Hello");
});
You can send DMs to a user with a `User`_ object. This will send "Hello" as an DM to the author of the received message.
.. code-block:: javascript
client.on('message', function(message) {
client.sendMessage(message.author, "Hello");
});
Replying to messages
------------------
Sends "@author Hello!".
.. code-block:: javascript
client.on('message', function(message) {
client.reply(message, 'Hello!');
});

View File

@@ -0,0 +1,4 @@
{
"GEN_VERSION": 12,
"COMPRESS": false
}

View File

@@ -0,0 +1,24 @@
/* eslint no-console:0 no-return-assign:0 */
const parse = require('jsdoc-parse');
module.exports = class DocumentationScanner {
constructor(generator) {
this.generator = generator;
}
scan(directory) {
return new Promise((resolve, reject) => {
const stream = parse({
src: [`${directory}*.js`, `${directory}**/*.js`],
});
let json = '';
stream.on('data', chunk => json += chunk.toString('utf-8'));
stream.on('error', reject);
stream.on('end', () => {
json = JSON.parse(json);
resolve(json);
});
});
}
};

View File

@@ -0,0 +1,114 @@
const DocumentedClass = require('./types/DocumentedClass');
const DocumentedInterface = require('./types/DocumentedInterface');
const DocumentedTypeDef = require('./types/DocumentedTypeDef');
const DocumentedConstructor = require('./types/DocumentedConstructor');
const DocumentedMember = require('./types/DocumentedMember');
const DocumentedFunction = require('./types/DocumentedFunction');
const DocumentedEvent = require('./types/DocumentedEvent');
const GEN_VERSION = require('./config.json').GEN_VERSION;
class Documentation {
constructor(items, custom) {
this.classes = new Map();
this.interfaces = new Map();
this.typedefs = new Map();
this.custom = custom;
this.parse(items);
}
registerRoots(data) {
for (const item of data) {
switch (item.kind) {
case 'class':
this.classes.set(item.name, new DocumentedClass(this, item));
break;
case 'interface':
this.interfaces.set(item.name, new DocumentedInterface(this, item));
break;
case 'typedef':
this.typedefs.set(item.name, new DocumentedTypeDef(this, item));
break;
default:
break;
}
}
}
findParent(item) {
if (['constructor', 'member', 'function', 'event'].indexOf(item.kind) > -1) {
if (this.classes.get(item.memberof)) {
return this.classes.get(item.memberof);
}
if (this.interfaces.get(item.memberof)) {
return this.interfaces.get(item.memberof);
}
}
return;
}
parse(items) {
this.registerRoots(
items.filter(
item => ['class', 'interface', 'typedef'].indexOf(item.kind) > -1
)
);
const members = items.filter(
item => ['class', 'interface', 'typedef'].indexOf(item.kind) === -1
);
const unknowns = new Map();
for (const member of members) {
let item;
switch (member.kind) {
case 'constructor':
item = new DocumentedConstructor(this, member);
break;
case 'member':
item = new DocumentedMember(this, member);
break;
case 'function':
item = new DocumentedFunction(this, member);
break;
case 'event':
item = new DocumentedEvent(this, member);
break;
default:
unknowns.set(member.kind, member);
break;
}
if (!item) {
continue;
}
const parent = this.findParent(member);
if (!parent) {
console.log(new Error(`${member.name || member.directData.name} has no accessible parent`));
continue;
}
parent.add(item);
}
if (unknowns.size > 0) {
Array.from(unknowns.keys()).map(
k => console.log(`Unknown documentation kind ${k} - \n${JSON.stringify(unknowns.get(k))}\n`
));
}
}
serialize() {
const meta = {
version: GEN_VERSION,
date: Date.now(),
};
const serialized = {
meta,
classes: Array.from(this.classes.values()).map(c => c.serialize()),
interfaces: Array.from(this.interfaces.values()).map(i => i.serialize()),
typedefs: Array.from(this.typedefs.values()).map(t => t.serialize()),
custom: this.custom,
};
return serialized;
}
}
module.exports = Documentation;

View File

@@ -0,0 +1,30 @@
/* eslint no-console:0 no-return-assign:0 */
const GEN_VERSION = require('./config.json').GEN_VERSION;
const compress = require('./config.json').COMPRESS;
const DocumentationScanner = require('./doc-scanner');
const Documentation = require('./documentation');
const fs = require('fs-extra');
const zlib = require('zlib');
const custom = require('../custom/index');
const docScanner = new DocumentationScanner(this);
function parseDocs(json) {
console.log(`${json.length} items found`);
const documentation = new Documentation(json, custom);
console.log('serializing');
let output = JSON.stringify(documentation.serialize(), null, 0);
if (compress) {
console.log('compressing');
output = zlib.deflateSync(output).toString('utf8');
}
console.log('writing to docs.json');
fs.writeFileSync('./docs/docs.json', output);
}
console.log(`using format version ${GEN_VERSION}`);
console.log('scanning for documentation');
docScanner.scan('./src/')
.then(parseDocs)
.catch(console.error);

View File

@@ -0,0 +1,83 @@
const DocumentedItem = require('./DocumentedItem');
const DocumentedItemMeta = require('./DocumentedItemMeta');
const DocumentedConstructor = require('./DocumentedConstructor');
const DocumentedFunction = require('./DocumentedFunction');
const DocumentedMember = require('./DocumentedMember');
const DocumentedEvent = require('./DocumentedEvent');
/*
{ id: 'VoiceChannel',
longname: 'VoiceChannel',
name: 'VoiceChannel',
scope: 'global',
kind: 'class',
augments: [ 'GuildChannel' ],
description: 'Represents a Server Voice Channel on Discord.',
meta:
{ lineno: 7,
filename: 'VoiceChannel.js',
path: 'src/structures' },
order: 232 }
*/
class DocumentedClass extends DocumentedItem {
constructor(docParent, data) {
super(docParent, data);
this.props = new Map();
this.methods = new Map();
this.events = new Map();
}
add(item) {
if (item instanceof DocumentedConstructor) {
if (this.classConstructor) {
throw new Error(`Doc ${this.directData.name} already has constructor - ${this.directData.classConstructor}`);
}
this.classConstructor = item;
} else if (item instanceof DocumentedFunction) {
if (this.methods.get(item.directData.name)) {
throw new Error(`Doc ${this.directData.name} already has method ${item.directData.name}`);
}
this.methods.set(item.directData.name, item);
} else if (item instanceof DocumentedMember) {
if (this.props.get(item.directData.name)) {
throw new Error(`Doc ${this.directData.name} already has prop ${item.directData.name}`);
}
this.props.set(item.directData.name, item);
} else if (item instanceof DocumentedEvent) {
if (this.events.get(item.directData.name)) {
throw new Error(`Doc ${this.directData.name} already has event ${item.directData.name}`);
}
this.events.set(item.directData.name, item);
}
}
registerMetaInfo(data) {
super.registerMetaInfo(data);
this.directData = data;
this.directData.meta = new DocumentedItemMeta(this, data.meta);
}
serialize() {
super.serialize();
const { id, name, description, meta, augments, access } = this.directData;
const serialized = {
id,
name,
description,
meta: meta.serialize(),
extends: augments,
access,
};
if (this.classConstructor) {
serialized.classConstructor = this.classConstructor.serialize();
}
serialized.methods = Array.from(this.methods.values()).map(m => m.serialize());
serialized.properties = Array.from(this.props.values()).map(p => p.serialize());
serialized.events = Array.from(this.events.values()).map(e => e.serialize());
return serialized;
}
}
module.exports = DocumentedClass;

View File

@@ -0,0 +1,46 @@
const DocumentedItem = require('./DocumentedItem');
const DocumentedParam = require('./DocumentedParam');
/*
{ id: 'Client()',
longname: 'Client',
name: 'Client',
kind: 'constructor',
description: 'Creates an instance of Client.',
memberof: 'Client',
params:
[ { type: [Object],
optional: true,
description: 'options to pass to the client',
name: 'options' } ],
order: 10 }
*/
class DocumentedConstructor extends DocumentedItem {
registerMetaInfo(data) {
super.registerMetaInfo(data);
this.directData = data;
const newParams = [];
for (const param of data.params) {
newParams.push(new DocumentedParam(this, param));
}
this.directData.params = newParams;
}
serialize() {
super.serialize();
const { id, name, description, memberof, access, params } = this.directData;
return {
id,
name,
description,
memberof,
access,
params: params.map(p => p.serialize()),
};
}
}
module.exports = DocumentedConstructor;

View File

@@ -0,0 +1,80 @@
const DocumentedItem = require('./DocumentedItem');
const DocumentedItemMeta = require('./DocumentedItemMeta');
const DocumentedParam = require('./DocumentedParam');
/*
{
"id":"Client#event:guildMemberRolesUpdate",
"longname":"Client#event:guildMemberRolesUpdate",
"name":"guildMemberRolesUpdate",
"scope":"instance",
"kind":"event",
"description":"Emitted whenever a Guild Member's Roles change - i.e. new role or removed role",
"memberof":"Client",
"params":[
{
"type":{
"names":[
"Guild"
]
},
"description":"the guild that the update affects",
"name":"guild"
},
{
"type":{
"names":[
"Array.<Role>"
]
},
"description":"the roles before the update",
"name":"oldRoles"
},
{
"type":{
"names":[
"Guild"
]
},
"description":"the roles after the update",
"name":"newRoles"
}
],
"meta":{
"lineno":91,
"filename":"Guild.js",
"path":"src/structures"
},
"order":110
}
*/
class DocumentedEvent extends DocumentedItem {
registerMetaInfo(data) {
this.directData = data;
this.directData.meta = new DocumentedItemMeta(this, data.meta);
const newParams = [];
data.params = data.params || [];
for (const param of data.params) {
newParams.push(new DocumentedParam(this, param));
}
this.directData.params = newParams;
}
serialize() {
super.serialize();
const { id, name, description, memberof, meta, params } = this.directData;
return {
id,
name,
description,
memberof,
meta: meta.serialize(),
params: params.map(p => p.serialize()),
};
}
}
module.exports = DocumentedEvent;

View File

@@ -0,0 +1,91 @@
const DocumentedItem = require('./DocumentedItem');
const DocumentedItemMeta = require('./DocumentedItemMeta');
const DocumentedVarType = require('./DocumentedVarType');
const DocumentedParam = require('./DocumentedParam');
/*
{
"id":"ClientUser#sendTTSMessage",
"longname":"ClientUser#sendTTSMessage",
"name":"sendTTSMessage",
"scope":"instance",
"kind":"function",
"inherits":"User#sendTTSMessage",
"inherited":true,
"implements":[
"TextBasedChannel#sendTTSMessage"
],
"description":"Send a text-to-speech message to this channel",
"memberof":"ClientUser",
"params":[
{
"type":{
"names":[
"String"
]
},
"description":"the content to send",
"name":"content"
}
],
"examples":[
"// send a TTS message..."
],
"returns":[
{
"type":{
"names":[
"Promise.<Message>"
]
}
}
],
"meta":{
"lineno":38,
"filename":"TextBasedChannel.js",
"path":src/structures/interface"
},
"order":293
}
*/
class DocumentedFunction extends DocumentedItem {
registerMetaInfo(data) {
super.registerMetaInfo(data);
this.directData = data;
this.directData.meta = new DocumentedItemMeta(this, data.meta);
this.directData.returns = new DocumentedVarType(this, data.returns ? data.returns[0].type : {
names: ['null'],
});
const newParams = [];
for (const param of data.params) {
newParams.push(new DocumentedParam(this, param));
}
this.directData.params = newParams;
}
serialize() {
super.serialize();
const {
id, name, description, memberof, examples, inherits, inherited, meta, returns, params, access,
} = this.directData;
const serialized = {
id,
access,
name,
description,
memberof,
examples,
inherits,
inherited,
meta: meta.serialize(),
returns: returns.serialize(),
params: params.map(p => p.serialize()),
};
serialized.implements = this.directData.implements;
return serialized;
}
}
module.exports = DocumentedFunction;

View File

@@ -0,0 +1,32 @@
const DocumentedClass = require('./DocumentedClass');
/*
{ id: 'TextBasedChannel',
longname: 'TextBasedChannel',
name: 'TextBasedChannel',
scope: 'global',
kind: 'interface',
classdesc: 'Interface for classes that have text-channel-like features',
params: [],
meta:
{ lineno: 5,
filename: 'TextBasedChannel.js',
path: 'src/structures/interface' },
order: 175 }
*/
class DocumentedInterface extends DocumentedClass {
registerMetaInfo(data) {
super.registerMetaInfo(data);
this.directData = data;
// this.directData.meta = new DocumentedItemMeta(this, data.meta);
}
serialize() {
const serialized = super.serialize();
serialized.description = this.directData.classdesc;
return serialized;
}
}
module.exports = DocumentedInterface;

View File

@@ -0,0 +1,17 @@
class DocumentedItem {
constructor(parent, info) {
this.parent = parent;
this.directData = {};
this.registerMetaInfo(info);
}
registerMetaInfo() {
return;
}
serialize() {
return;
}
}
module.exports = DocumentedItem;

View File

@@ -0,0 +1,29 @@
const cwd = (`${process.cwd()}\\`).replace(/\\/g, '/');
const backToForward = /\\/g;
const DocumentedItem = require('./DocumentedItem');
/*
{ lineno: 7,
filename: 'VoiceChannel.js',
path: 'src/structures' },
*/
class DocumentedItemMeta extends DocumentedItem {
registerMetaInfo(data) {
super.registerMetaInfo(data);
this.directData.line = data.lineno;
this.directData.file = data.filename;
this.directData.path = data.path.replace(backToForward, '/').replace(cwd, '');
}
serialize() {
super.serialize();
const { line, file, path } = this.directData;
return { line, file, path };
}
}
module.exports = DocumentedItemMeta;

View File

@@ -0,0 +1,58 @@
const DocumentedItem = require('./DocumentedItem');
const DocumentedItemMeta = require('./DocumentedItemMeta');
const DocumentedVarType = require('./DocumentedVarType');
const DocumentedParam = require('./DocumentedParam');
/*
{ id: 'Client#rest',
longname: 'Client#rest',
name: 'rest',
scope: 'instance',
kind: 'member',
description: 'The REST manager of the client',
memberof: 'Client',
type: { names: [ 'RESTManager' ] },
access: 'private',
meta:
{ lineno: 32,
filename: 'Client.js',
path: 'src/client' },
order: 11 }
*/
class DocumentedMember extends DocumentedItem {
registerMetaInfo(data) {
super.registerMetaInfo(data);
this.directData = data;
this.directData.meta = new DocumentedItemMeta(this, data.meta);
this.directData.type = new DocumentedVarType(this, data.type);
if (data.properties) {
const newProps = [];
for (const param of data.properties) {
newProps.push(new DocumentedParam(this, param));
}
this.directData.properties = newProps;
} else {
data.properties = [];
}
}
serialize() {
super.serialize();
const { id, name, description, memberof, type, access, meta, properties } = this.directData;
return {
id,
name,
description,
memberof,
type: type.serialize(),
access,
meta: meta.serialize(),
props: properties.map(p => p.serialize()),
};
}
}
module.exports = DocumentedMember;

View File

@@ -0,0 +1,36 @@
const DocumentedItem = require('./DocumentedItem');
const DocumentedVarType = require('./DocumentedVarType');
/*
{
"type":{
"names":[
"Guild"
]
},
"description":"the roles after the update",
"name":"newRoles"
}
*/
class DocumentedParam extends DocumentedItem {
registerMetaInfo(data) {
super.registerMetaInfo(data);
this.directData = data;
this.directData.type = new DocumentedVarType(this, data.type);
}
serialize() {
super.serialize();
const { name, description, type, optional } = this.directData;
return {
name,
description,
optional,
type: type.serialize(),
};
}
}
module.exports = DocumentedParam;

View File

@@ -0,0 +1,44 @@
const DocumentedItem = require('./DocumentedItem');
const DocumentedItemMeta = require('./DocumentedItemMeta');
const DocumentedVarType = require('./DocumentedVarType');
/*
{ id: 'StringResolvable',
longname: 'StringResolvable',
name: 'StringResolvable',
scope: 'global',
kind: 'typedef',
description: 'Data that can be resolved to give a String...',
type: { names: [ 'String', 'Array', 'Object' ] },
meta:
{ lineno: 142,
filename: 'ClientDataResolver.js',
path: 'src/client' },
order: 37 }
*/
class DocumentedTypeDef extends DocumentedItem {
registerMetaInfo(data) {
super.registerMetaInfo(data);
this.directData = data;
this.directData.meta = new DocumentedItemMeta(this, data.meta);
this.directData.type = new DocumentedVarType(this, data.type);
}
serialize() {
super.serialize();
const { id, name, description, type, access, meta } = this.directData;
return {
id,
name,
description,
type: type.serialize(),
access,
meta: meta.serialize(),
};
}
}
module.exports = DocumentedTypeDef;

View File

@@ -0,0 +1,50 @@
const DocumentedItem = require('./DocumentedItem');
/*
{
"names":[
"String"
]
}
*/
const regex = /([\w]+)([^\w]+)/;
const regexG = /([\w]+)([^\w]+)/g;
function splitVarName(str) {
if (str === '*') {
return ['*', ''];
}
const matches = str.match(regexG);
const output = [];
if (matches) {
for (const match of matches) {
const groups = match.match(regex);
output.push([groups[1], groups[2]]);
}
} else {
output.push([str.match(/(\w+)/g)[0], '']);
}
return output;
}
class DocumentedVarType extends DocumentedItem {
registerMetaInfo(data) {
super.registerMetaInfo(data);
this.directData = data;
}
serialize() {
super.serialize();
const names = [];
for (const name of this.directData.names) {
names.push(splitVarName(name));
}
return {
types: names,
};
}
}
module.exports = DocumentedVarType;

View File

@@ -1,66 +0,0 @@
.. 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`_.
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

View File

@@ -1,62 +0,0 @@
.. 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/

View File

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

View File

@@ -1,45 +0,0 @@
.. 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)``.

View File

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

View File

@@ -1,34 +0,0 @@
.. _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
.. _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

View File

@@ -1,39 +0,0 @@
/* 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");
}

View File

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

View File

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

View File

@@ -1,161 +0,0 @@
/* 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();
}

View File

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

View File

@@ -1,31 +0,0 @@
/*
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);

View File

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

View File

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

@@ -1,73 +0,0 @@
/*
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

@@ -1,46 +0,0 @@
/* 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);

View File

@@ -1,40 +0,0 @@
/*
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);

View File

@@ -1,30 +0,0 @@
/* 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);

View File

@@ -1,31 +0,0 @@
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);

View File

@@ -1,53 +0,0 @@
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"])
};

View File

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

View File

@@ -1,616 +0,0 @@
"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 _InternalClient=require("./InternalClient");var _InternalClient2=_interopRequireDefault(_InternalClient);var _events=require("events");var _events2=_interopRequireDefault(_events);var _StructuresPMChannel=require("../Structures/PMChannel");var _StructuresPMChannel2=_interopRequireDefault(_StructuresPMChannel); // This utility function creates an anonymous error handling wrapper function
// for a given callback. It is used to allow error handling inside the callback
// and using other means.
function errorCallback(callback){return function(error){callback(error);throw error;};} // This utility function creates an anonymous handler function to separate the
// error and the data arguments inside a callback and return the data if it is
// eventually done (for promise propagation).
function dataCallback(callback){return function(data){callback(null,data);return data;};} /**
* Used to interface with the Discord API.
*/var Client=(function(_EventEmitter){_inherits(Client,_EventEmitter); /**
* Used to instantiate Discord.Client
* @param {ClientOptions} [options] options that should be passed to the Client.
* @example
* // creates a new Client that will try to reconnect whenever it is disconnected.
* var client = new Discord.Client({
* autoReconnect : true
* });
*/function Client(){var options=arguments.length <= 0 || arguments[0] === undefined?{}:arguments[0];_classCallCheck(this,Client);_EventEmitter.call(this); /**
* Options that were passed to the client when it was instantiated.
* @readonly
* @type {ClientOptions}
*/this.options = options || {};this.options.compress = options.compress || !process.browser;this.options.autoReconnect = options.autoReconnect || true;this.options.rateLimitAsError = options.rateLimitAsError || false;this.options.largeThreshold = options.largeThreshold || 250;this.options.maxCachedMessages = options.maxCachedMessages || 1000;this.options.guildCreateTimeout = options.guildCreateTimeout || 1000;this.options.shardId = options.shardId || 0;this.options.shardCount = options.shardCount || 0;this.options.disableEveryone = options.disableEveryone || false;if(typeof options.shardCount === "number" && typeof options.shardId === "number" && options.shardCount > 0){this.options.shard = [options.shardId,options.shardCount];} /**
* Internal Client that the Client wraps around.
* @readonly
* @type {InternalClient}
*/this.internal = new _InternalClient2["default"](this);} /**
* The users that the Client is aware of. Only available after `ready` event has been emitted.
* @type {Cache<User>} a Cache of the Users
* @readonly
* @example
* // log usernames of the users that the client is aware of
* for(var user of client.users){
* console.log(user.username);
* }
*/ /**
* Log the client in using a token. If you want to use methods such as `client.setUsername` or `client.setAvatar`, you must also pass the email and password parameters.
* @param {string} token A valid token that can be used to authenticate the account.
* @param {string} [email] Email of the Discord Account.
* @param {string} [password] Password of the Discord Account.
* @param {function(err: Error, token: string)} [callback] callback callback to the method
* @returns {Promise<string, Error>} Resolves with the token if the login was successful, otherwise it rejects with an error.
* @example
* // log the client in - callback
* client.login("token123", null, null, function(error, token){
* if(!error){
* console.log(token);
* }
* });
* @example
* // log the client in - promise
* client.login("token123")
* .then(token => console.log(token))
* .catch(err => console.log(err));
*/Client.prototype.loginWithToken = function loginWithToken(token){var email=arguments.length <= 1 || arguments[1] === undefined?null:arguments[1];var password=arguments.length <= 2 || arguments[2] === undefined?null:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function() /*err, token*/{}:arguments[3];if(typeof email === "function"){ // email is the callback
callback = email;email = null;password = null;}return this.internal.loginWithToken(token,email,password).then(dataCallback(callback),errorCallback(callback));}; /**
* Log the client in using an email and password.
* @param {string} email Email of the Discord Account.
* @param {string} password Password of the Discord Account.
* @param {function(err: Error, token: string)} [callback] callback callback to the method
* @returns {Promise<string, Error>} Resolves with the token if the login was successful, otherwise it rejects with an error.
* @example
* // log the client in - callback
* client.login("jeff@gmail.com", "password", function(error, token){
* if(!error){
* console.log(token);
* }
* });
* @example
* // log the client in - promise
* client.login("jeff@gmail.com", "password")
* .then(token => console.log(token))
* .catch(err => console.log(err));
*/Client.prototype.login = function login(email,password){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, token*/{}:arguments[2];return this.internal.login(email,password).then(dataCallback(callback),errorCallback(callback));}; /**
* Logs the client out gracefully and closes all WebSocket connections. Client still retains its Caches.
* @param {function(err: Error)} [callback] callback callback to the method
* @returns {Promise<null, Error>} Resolves with null if the logout was successful, otherwise it rejects with an error.
* @example
* // log the client out - callback
* client.logout(function(error){
* if(error){
* console.log("Couldn't log out.");
* }else{
* console.log("Logged out!");
* }
* });
* @example
* // log the client out - promise
* client.logout()
* .then(() => console.log("Logged out!"))
* .catch(error => console.log("Couldn't log out."));
*/Client.prototype.logout = function logout(){var callback=arguments.length <= 0 || arguments[0] === undefined?function() /*err, {}*/{}:arguments[0];return this.internal.logout().then(dataCallback(callback),errorCallback(callback));}; /**
* Similar to log out but this should be used if you know you aren't going to be creating the Client again later in your program.
* @param {function(err: Error)} [callback] callback callback to the method
* @returns {Promise<null, Error>} Resolves with null if the destruction was successful, otherwise it rejects with an error.
* @example
* // destroy the client - callback
* client.destroy(function(error){
* if(error){
* console.log("Couldn't destroy client.");
* }else{
* console.log("Client destroyed!");
* }
* });
* @example
* // destroy the client - promise
* client.destroy()
* .then(() => console.log("Client destroyed!"))
* .catch(error => console.log("Couldn't destroy client."));
*/Client.prototype.destroy = function destroy(){var _this=this;var callback=arguments.length <= 0 || arguments[0] === undefined?function() /*err, {}*/{}:arguments[0];return this.internal.logout().then(function(){return _this.internal.disconnected(true);}).then(dataCallback(callback),errorCallback(callback));}; /**
* Sends a text message to the specified destination.
* @param {TextChannelResolvable} destination where the message should be sent
* @param {StringResolvable} content message you want to send
* @param {MessageOptions} [options] options you want to apply to the message
* @param {function(err: Error, msg: Message)} [callback] to the method
* @returns {Promise<Message, Error>} Resolves with a Message if successful, otherwise rejects with an Error.
* @example
* // sending messages
* client.sendMessage(channel, "Hi there!");
* client.sendMessage(user, "This is a PM message!");
* client.sendMessage(server, "This message was sent to the #general channel of the server!");
* client.sendMessage(channel, "This message is TTS.", {tts : true});
* @example
* // callbacks
* client.sendMessage(channel, "Hi there!", function(err, msg){
* if(err){
* console.log("Couldn't send message");
* }else{
* console.log("Message sent!");
* }
* });
* @example
* // promises
* client.sendMessage(channel, "Hi there!")
* .then(msg => console.log("Message sent!"))
* .catch(err => console.log("Couldn't send message"));
*/Client.prototype.sendMessage = function sendMessage(destination,content){var options=arguments.length <= 2 || arguments[2] === undefined?{}:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function() /*err, msg*/{}:arguments[3];if(typeof options === "function"){ // options is the callback
callback = options;options = {};}if(typeof content === "object" && content.file){ // content has file
options = content;content = "";}return this.internal.sendMessage(destination,content,options).then(dataCallback(callback),errorCallback(callback));}; /**
* Sends a TTS text message to the specified destination.
* @param {TextChannelResolvable} destination where the message should be sent
* @param {StringResolvable} content message you want to send
* @param {function(err: Error, msg: Message)} [callback] to the method
* @returns {Promise<Message, Error>} Resolves with a Message if successful, otherwise rejects with an Error.
* @example
* // sending messages
* client.sendTTSMessage(channel, "This message is TTS.");
* @example
* // callbacks
* client.sendTTSMessage(channel, "Hi there!", function(err, msg){
* if(err){
* console.log("Couldn't send message");
* }else{
* console.log("Message sent!");
* }
* });
* @example
* // promises
* client.sendTTSMessage(channel, "Hi there!")
* .then(msg => console.log("Message sent!"))
* .catch(err => console.log("Couldn't send message"));
*/Client.prototype.sendTTSMessage = function sendTTSMessage(destination,content){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, msg*/{}:arguments[2];return this.sendMessage(destination,content,{tts:true}).then(dataCallback(callback),errorCallback(callback));}; /**
* Replies to the author of a message in the same channel the message was sent.
* @param {MessageResolvable} message the message to reply to
* @param {StringResolvable} content message you want to send
* @param {MessageOptions} [options] options you want to apply to the message
* @param {function(err: Error, msg: Message)} [callback] to the method
* @returns {Promise<Message, Error>} Resolves with a Message if successful, otherwise rejects with an Error.
* @example
* // reply to messages
* client.reply(message, "Hello there!");
* client.reply(message, "Hello there, this is a TTS reply!", {tts:true});
* @example
* // callbacks
* client.reply(message, "Hi there!", function(err, msg){
* if(err){
* console.log("Couldn't send message");
* }else{
* console.log("Message sent!");
* }
* });
* @example
* // promises
* client.reply(message, "Hi there!")
* .then(msg => console.log("Message sent!"))
* .catch(err => console.log("Couldn't send message"));
*/Client.prototype.reply = function reply(message,content){var options=arguments.length <= 2 || arguments[2] === undefined?{}:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function() /*err, msg*/{}:arguments[3];if(typeof options === "function"){ // options is the callback
callback = options;options = {};}var msg=this.internal.resolver.resolveMessage(message);if(msg){if(!(msg.channel instanceof _StructuresPMChannel2["default"])){content = msg.author + ", " + content;}return this.internal.sendMessage(msg,content,options).then(dataCallback(callback),errorCallback(callback));}var err=new Error("Destination not resolvable to a message!");callback(err);return Promise.reject(err);}; /**
* Replies to the author of a message in the same channel the message was sent using TTS.
* @param {MessageResolvable} message the message to reply to
* @param {StringResolvable} content message you want to send
* @param {function(err: Error, msg: Message)} [callback] to the method
* @returns {Promise<Message, Error>} Resolves with a Message if successful, otherwise rejects with an Error.
* @example
* // reply to messages
* client.replyTTS(message, "Hello there, this is a TTS reply!");
* @example
* // callbacks
* client.replyTTS(message, "Hi there!", function(err, msg){
* if(err){
* console.log("Couldn't send message");
* }else{
* console.log("Message sent!");
* }
* });
* @example
* // promises
* client.replyTTS(message, "Hi there!")
* .then(msg => console.log("Message sent!"))
* .catch(err => console.log("Couldn't send message"));
*/Client.prototype.replyTTS = function replyTTS(message,content){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, msg*/{}:arguments[2];return this.reply(message,content,{tts:true}).then(dataCallback(callback),errorCallback(callback));}; /**
* Deletes a message (if the client has permission to)
* @param {MessageResolvable} message the message to delete
* @param {MessageDeletionOptions} [options] options to apply when deleting the message
* @param {function(err: Error)} [callback] callback to the method
* @returns {Promise<null, Error>} Resolves with null if the deletion was successful, otherwise rejects with an Error.
* @example
* // deleting messages
* client.deleteMessage(message);
* client.deleteMessage(message, {wait:5000}); //deletes after 5 seconds
* @example
* // deleting messages - callback
* client.deleteMessage(message, function(err){
* if(err){
* console.log("couldn't delete");
* }
* });
* @example
* // deleting messages - promise
* client.deleteMessage(message)
* .then(() => console.log("deleted!"))
* .catch(err => console.log("couldn't delete"));
*/Client.prototype.deleteMessage = function deleteMessage(message){var options=arguments.length <= 1 || arguments[1] === undefined?{}:arguments[1];var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];if(typeof options === "function"){ // options is the callback
callback = options;options = {};}return this.internal.deleteMessage(message,options).then(dataCallback(callback),errorCallback(callback));}; /**
* Bulk deletes messages (if the client has permission to)
* @param {Array<MessageResolvable>} message the message to delete
* @param {function(err: Error)} [callback] callback to the method
* @returns {Promise<null, Error>} Resolves with null if the deletion was successful, otherwise rejects with an Error.
* @example
* // deleting messages
* client.deleteMessages([message1, message2]);
*/Client.prototype.deleteMessages = function deleteMessages(messages){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.deleteMessages(messages).then(dataCallback(callback),errorCallback(callback));}; /**
* Edits a previously sent message (if the client has permission to)
* @param {MessageResolvable} message the message to edit
* @param {StringResolvable} content the new content of the message
* @param {MessageOptions} [options] options to apply to the message
* @param {function(err: Error, msg: Message)} [callback] callback to the method
* @returns {Promise<Message, Error>} Resolves with the newly edited message if successful, otherwise rejects with an Error.
* @example
* // editing messages
* client.updateMessage(message, "This is an edit!");
* @example
* // editing messages - callback
* client.updateMessage(message, "This is an edit!", function(err, msg){
* if(err){
* console.log("couldn't edit");
* }
* });
* @example
* // editing messages - promise
* client.updateMessage(message, "This is an edit!")
* .then(msg => console.log("edited!"))
* .catch(err => console.log("couldn't edit"));
*/Client.prototype.updateMessage = function updateMessage(message,content){var options=arguments.length <= 2 || arguments[2] === undefined?{}:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function() /*err, msg*/{}:arguments[3];if(typeof options === "function"){ // options is the callback
callback = options;options = {};}return this.internal.updateMessage(message,content,options).then(dataCallback(callback),errorCallback(callback));}; /**
* Gets the logs of a channel with a specified limit, starting from the most recent message.
* @param {TextChannelResolvable} where the channel to get the logs of
* @param {Number} [limit=50] Integer, the maximum amount of messages to retrieve
* @param {ChannelLogsOptions} [options] options to use when getting the logs
* @param {function(err: Error, logs: Array<Message>)} [callback] callback to the method
* @returns {Promise<Array<Message>, Error>} Resolves with an array of messages if successful, otherwise rejects with an error.
* @example
* // log content of last 500 messages in channel - callback
* client.getChannelLogs(channel, 500, function(err, logs){
* if(!err){
* for(var message of logs){
* console.log(message.content);
* }
* }
* });
* @example
* // log content of last 500 messages in channel - promise
* client.getChannelLogs(channel, 500)
* .then(logs => {
* for(var message of logs){
* console.log(message.content);
* }
* })
* .catch(err => console.log("couldn't fetch logs"));
*/Client.prototype.getChannelLogs = function getChannelLogs(where){var limit=arguments.length <= 1 || arguments[1] === undefined?50:arguments[1];var options=arguments.length <= 2 || arguments[2] === undefined?{}:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function() /*err, logs*/{}:arguments[3];if(typeof options === "function"){ // options is the callback
callback = options;options = {};}else if(typeof limit === "function"){ // options is the callback
callback = limit;limit = 50;}return this.internal.getChannelLogs(where,limit,options).then(dataCallback(callback),errorCallback(callback));}; /**
* Gets a single message of a server
* @param {ChannelResolvable} channel to get the message from
* @param {function(err: Error, msg: Message} [callback] callback to the method
* @returns {Promise<Message, Error>} Resolves with a message if the request was successful, otherwise rejects with an error.
* @example
* // get message object off a snowflake and log its content - callback
* client.getMessage(channel, '192696158886428672', function(err, msg) {
* if(!err) {
* console.log(msg.content);
* } else {
* console.log("couldn't get the message");
* }
* }
* @example
* //get message object off a snowflake and log its content - promise
* client.getMessage(channel, '192696158886428672')
* .then(msg => {
* console.log(msg.content);
* })
* .catch(err => console.log("couldn't get the message"));
*/Client.prototype.getMessage = function getMessage(channel,messageID){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, msg*/{}:arguments[2];return this.internal.getMessage(channel,messageID).then(dataCallback(callback),errorCallback(callback));}; /**
* Pins a message to a channel.
* @param {MessageResolvable} message to pin.
* @returns {Promise<null, Error>} resolves null if successful, otherwise rejects with an error.
* @example
* // pin message - callback
* client.pinMessage(msg, (err) => {
* if(!err) {
* console.log("Successfully pinned message")
* } else {
* console.log("Couldn't pin the message: " + err);
* }
* });
* @example
* // pin message - promise
* client.pinMessage(msg)
* .then(() => {
* console.log("Successfully pinned message");
* })
* .catch(err => console.log("Couldn't pin the message: " + err));
*/Client.prototype.pinMessage = function pinMessage(msg){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err*/{}:arguments[1];return this.internal.pinMessage(msg).then(dataCallback(callback),errorCallback(callback));}; /**
* Unpins a message to a server.
* @param {MessageResolvable} message to unpin.
* @returns {Promise<null, Error>} resolves null if successful, otherwise rejects with an error.
* @example
* // unpin message - callback
* client.unpinMessage(msg, (err) => {
* if(!err) {
* console.log("Successfully unpinned message")
* } else {
* console.log("Couldn't pin the message: " + err);
* }
* });
* @example
* // unpin message - promise
* client.unpinMessage(msg)
* .then(() => {
* console.log("Successfully unpinned message");
* })
* .catch(err => console.log("Couldn't unpin the message: " + err));
*/Client.prototype.unpinMessage = function unpinMessage(msg){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err*/{}:arguments[1];return this.internal.unpinMessage(msg).then(dataCallback(callback),errorCallback(callback));}; /**
* Gets all pinned messages of a channel.
* @param {TextChannelResolvable} where to get the pins from.
* @returns {Promise<Array<Message>, Error>} Resolves with an array of messages if successful, otherwise rejects with an error.
* @example
* // log all pinned messages - callback
* client.getPinnedMessages(channel, (err, messages) => {
* if(!err) {
* for(var message of messages) {
* console.log(message.content);
* }
* } else {
* console.log("Couldn't fetch pins: " + err);
* }
* });
* @example
* // log all pinned messages - promise
* client.getPinnedMessages(channel)
* .then(messages => {
* for(var message of messages) {
* console.log(message.content);
* }
* })
* .catch(err => console.log("Couldn't fetch pins: " + err));
*/Client.prototype.getPinnedMessages = function getPinnedMessages(channel){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, messages*/{}:arguments[1];return this.internal.getPinnedMessages(channel).then(dataCallback(callback),errorCallback(callback));}; /**
* Gets the banned users of a server (if the client has permission to)
* @param {ServerResolvable} server server to get banned users of
* @param {function(err: Error, bans: Array<User>)} [callback] callback to the method
* @returns {Promise<Array<User>, Error>} Resolves with an array of users if the request was successful, otherwise rejects with an error.
* @example
* // loop through banned users - callback
* client.getBans(server, function(err, bans){
* if(!err){
* for(var user of bans){
* console.log(user.username + " was banned from " + server.name);
* }
* }
* });
* @example
* // loop through banned users - promise
* client.getBans(server)
* .then(bans => {
* for(var user of bans){
* console.log(user.username + " was banned from " + server.name);
* }
* })
* .catch(err => console.log("couldn't get bans"));
*/Client.prototype.getBans = function getBans(server){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, bans*/{}:arguments[1];return this.internal.getBans(server).then(dataCallback(callback),errorCallback(callback));}; /**
* Sends a file (embedded if possible) to the specified channel.
* @param {TextChannelResolvable} destination channel to send the file to
* @param {FileResolvable} attachment the file to send
* @param {string} name name of the file, especially including the extension
* @param {function(err: Error, msg: Message)} [callback] callback to the method
* @returns {Promise<msg: Message, err: Error>} resolves with the sent file as a message if successful, otherwise rejects with an error
* @example
* // send a file - callback
* client.sendFile(channel, new Buffer("Hello this a text file"), "file.txt", function(err, msg){
* if(err){
* console.log("Couldn't send file!");
* }
* });
* @example
* // send a file - promises
* client.sendFile(channel, "C:/path/to/file.txt", "file.txt")
* .then(msg => console.log("sent file!"))
* .catch(err => console.log("couldn't send file!"));
*/Client.prototype.sendFile = function sendFile(destination,attachment,name,content){var callback=arguments.length <= 4 || arguments[4] === undefined?function() /*err, m*/{}:arguments[4];if(typeof content === "function"){ // content is the callback
callback = content;content = undefined; // Will get resolved into original filename in internal
}if(typeof name === "function"){ // name is the callback
callback = name;name = undefined; // Will get resolved into original filename in internal
}return this.internal.sendFile(destination,attachment,name,content).then(dataCallback(callback),errorCallback(callback));}; /**
* Client accepts the specified invite to join a server. If the Client is already in the server, the promise/callback resolve immediately.
* @param {InviteIDResolvable} invite invite to the server
* @param {function(err: Error, server: Server)} [callback] callback to the method.
* @returns {Promise<Server, Error>} resolves with the newly joined server if succesful, rejects with an error if not.
* @example
* // join a server - callback
* client.joinServer("https://discord.gg/0BwZcrFhUKZ55bJL", function(err, server){
* if(!err){
* console.log("Joined " + server.name);
* }
* });
* @example
* // join a server - promises
* client.joinServer("https://discord.gg/0BwZcrFhUKZ55bJL")
* .then(server => console.log("Joined " + server.name))
* .catch(err => console.log("Couldn't join!"));
*/Client.prototype.joinServer = function joinServer(invite){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, srv*/{}:arguments[1];return this.internal.joinServer(invite).then(dataCallback(callback),errorCallback(callback));}; /**
* Creates a Discord Server and joins it
* @param {string} name the name of the server
* @param {region} [region=london] the region of the server
* @param {function(err: Error, server: Server)} [callback] callback to the method
* @returns {Promise<Server, Error>} resolves with the newly created server if successful, rejects with an error if not.
* @example
* //creating a server - callback
* client.createServer("discord.js", "london", function(err, server){
* if(err){
* console.log("could not create server");
* }
* });
* @example
* //creating a server - promises
* client.createServer("discord.js", "london")
* .then(server => console.log("Made server!"))
* .catch(error => console.log("Couldn't make server!"));
*/Client.prototype.createServer = function createServer(name){var region=arguments.length <= 1 || arguments[1] === undefined?"london":arguments[1];var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, srv*/{}:arguments[2];return this.internal.createServer(name,region).then(dataCallback(callback),errorCallback(callback));}; /**
* Leaves a Discord Server
* @param {ServerResolvable} server the server to leave
* @param {function(err: Error)} [callback] callback to the method
* @returns {Promise<null, Error>} resolves null if successful, otherwise rejects with an error.
*/Client.prototype.leaveServer = function leaveServer(server){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.leaveServer(server).then(dataCallback(callback),errorCallback(callback));}; // def updateServer
Client.prototype.updateServer = function updateServer(server,options,region){var callback=arguments.length <= 3 || arguments[3] === undefined?function() /*err, srv*/{}:arguments[3];if(typeof region === "function"){ // region is the callback
callback = region;region = undefined;}else if(region && typeof options === "string"){options = {name:options,region:region};}return this.internal.updateServer(server,options).then(dataCallback(callback),errorCallback(callback));}; /**
* Deletes a Discord Server
* @param {ServerResolvable} server the server to leave
* @param {function(err: Error)} [callback] callback to the method
* @returns {Promise<null, Error>} resolves null if successful, otherwise rejects with an error.
*/Client.prototype.deleteServer = function deleteServer(server){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.deleteServer(server).then(dataCallback(callback),errorCallback(callback));}; // def createChannel
Client.prototype.createChannel = function createChannel(server,name){var type=arguments.length <= 2 || arguments[2] === undefined?"text":arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function() /*err, channel*/{}:arguments[3];if(typeof type === "function"){ // options is the callback
callback = type;type = "text";}return this.internal.createChannel(server,name,type).then(dataCallback(callback),errorCallback(callback));}; // def deleteChannel
Client.prototype.deleteChannel = function deleteChannel(channel){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.deleteChannel(channel).then(dataCallback(callback),errorCallback(callback));}; // def banMember
Client.prototype.banMember = function banMember(user,server){var length=arguments.length <= 2 || arguments[2] === undefined?1:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function() /*err, {}*/{}:arguments[3];if(typeof length === "function"){ // length is the callback
callback = length;length = 1;}return this.internal.banMember(user,server,length).then(dataCallback(callback),errorCallback(callback));}; // def unbanMember
Client.prototype.unbanMember = function unbanMember(user,server){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.unbanMember(user,server).then(dataCallback(callback),errorCallback(callback));}; // def kickMember
Client.prototype.kickMember = function kickMember(user,server){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.kickMember(user,server).then(dataCallback(callback),errorCallback(callback));}; // def moveMember
Client.prototype.moveMember = function moveMember(user,channel){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.moveMember(user,channel).then(dataCallback(callback),errorCallback(callback));}; // def muteMember
Client.prototype.muteMember = function muteMember(user,server){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.muteMember(user,server).then(dataCallback(callback),errorCallback(callback));}; // def unmuteMember
Client.prototype.unmuteMember = function unmuteMember(user,server){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.unmuteMember(user,server).then(dataCallback(callback),errorCallback(callback));}; // def deafenMember
Client.prototype.deafenMember = function deafenMember(user,server){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.deafenMember(user,server).then(dataCallback(callback),errorCallback(callback));}; // def undeafenMember
Client.prototype.undeafenMember = function undeafenMember(user,server){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.undeafenMember(user,server).then(dataCallback(callback),errorCallback(callback));}; // def setNickname
Client.prototype.setNickname = function setNickname(server,nick,user){var callback=arguments.length <= 3 || arguments[3] === undefined?function() /*err, {}*/{}:arguments[3];if(typeof user === "function"){ // user is the callback
callback = user;user = null;}if(!user){user = this.user;}return this.internal.setNickname(server,nick,user).then(dataCallback(callback),errorCallback(callback));}; // def setNote
Client.prototype.setNote = function setNote(user,note){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.setNote(user,note).then(dataCallback(callback),errorCallback(callback));}; // def createRole
Client.prototype.createRole = function createRole(server){var data=arguments.length <= 1 || arguments[1] === undefined?null:arguments[1];var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, role*/{}:arguments[2];if(typeof data === "function"){ // data is the callback
callback = data;data = null;}return this.internal.createRole(server,data).then(dataCallback(callback),errorCallback(callback));}; // def updateRole
Client.prototype.updateRole = function updateRole(role){var data=arguments.length <= 1 || arguments[1] === undefined?null:arguments[1];var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, role*/{}:arguments[2];if(typeof data === "function"){ // data is the callback
callback = data;data = null;}return this.internal.updateRole(role,data).then(dataCallback(callback),errorCallback(callback));}; // def deleteRole
Client.prototype.deleteRole = function deleteRole(role){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.deleteRole(role).then(dataCallback(callback),errorCallback(callback));}; // def addMemberToRole
Client.prototype.addMemberToRole = function addMemberToRole(member,role){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.addMemberToRole(member,role).then(dataCallback(callback),errorCallback(callback));}; // def addUserToRole
Client.prototype.addUserToRole = function addUserToRole(member,role){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.addMemberToRole(member,role,callback);}; // def addUserToRole
Client.prototype.memberHasRole = function memberHasRole(member,role){return this.internal.memberHasRole(member,role);}; // def addUserToRole
Client.prototype.userHasRole = function userHasRole(member,role){return this.memberHasRole(member,role);}; // def removeMemberFromRole
Client.prototype.removeMemberFromRole = function removeMemberFromRole(member,role){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.removeMemberFromRole(member,role).then(dataCallback(callback),errorCallback(callback));}; // def removeUserFromRole
Client.prototype.removeUserFromRole = function removeUserFromRole(member,role){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.removeMemberFromRole(member,role,callback);}; // def createInvite
Client.prototype.createInvite = function createInvite(chanServ,options){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, invite*/{}:arguments[2];if(typeof options === "function"){ // options is the callback
callback = options;options = undefined;}return this.internal.createInvite(chanServ,options).then(dataCallback(callback),errorCallback(callback));}; // def deleteInvite
Client.prototype.deleteInvite = function deleteInvite(invite){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.deleteInvite(invite).then(dataCallback(callback),errorCallback(callback));}; // def getInvite
Client.prototype.getInvite = function getInvite(invite){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, inv*/{}:arguments[1];return this.internal.getInvite(invite).then(dataCallback(callback),errorCallback(callback));}; // def getInvites
Client.prototype.getInvites = function getInvites(channel){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, inv*/{}:arguments[1];return this.internal.getInvites(channel).then(dataCallback(callback),errorCallback(callback));}; // def overwritePermissions
Client.prototype.overwritePermissions = function overwritePermissions(channel,role){var options=arguments.length <= 2 || arguments[2] === undefined?{}:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function() /*err, {}*/{}:arguments[3];return this.internal.overwritePermissions(channel,role,options).then(dataCallback(callback),errorCallback(callback));}; // def setStatus
Client.prototype.setStatus = function setStatus(idleStatus,game){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];if(typeof game === "function"){ // game is the callback
callback = game;game = null;}else if(typeof idleStatus === "function"){ // idleStatus is the callback
callback = idleStatus;game = null;}return this.internal.setStatus(idleStatus,game).then(dataCallback(callback),errorCallback(callback));}; // def sendTyping
Client.prototype.sendTyping = function sendTyping(channel){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.sendTyping(channel).then(dataCallback(callback),errorCallback(callback));}; // def setChannelTopic
Client.prototype.setChannelTopic = function setChannelTopic(channel,topic){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.setChannelTopic(channel,topic).then(dataCallback(callback),errorCallback(callback));}; // def setChannelName
Client.prototype.setChannelName = function setChannelName(channel,name){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.setChannelName(channel,name).then(dataCallback(callback),errorCallback(callback));}; // def setChannelPosition
Client.prototype.setChannelPosition = function setChannelPosition(channel,position){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.setChannelPosition(channel,position).then(dataCallback(callback),errorCallback(callback));}; // def setChannelUserLimit
Client.prototype.setChannelUserLimit = function setChannelUserLimit(channel,limit){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.setChannelUserLimit(channel,limit).then(dataCallback(callback),errorCallback(callback));}; // def setChannelBitrate
Client.prototype.setChannelBitrate = function setChannelBitrate(channel,kbitrate){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.setChannelBitrate(channel,kbitrate).then(dataCallback(callback),errorCallback(callback));}; // def updateChannel
Client.prototype.updateChannel = function updateChannel(channel,data){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.updateChannel(channel,data).then(dataCallback(callback),errorCallback(callback));}; // def startTyping
Client.prototype.startTyping = function startTyping(channel){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.startTyping(channel).then(dataCallback(callback),errorCallback(callback));}; // def stopTyping
Client.prototype.stopTyping = function stopTyping(channel){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.stopTyping(channel).then(dataCallback(callback),errorCallback(callback));}; // def updateDetails
Client.prototype.updateDetails = function updateDetails(details){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.updateDetails(details).then(dataCallback(callback),errorCallback(callback));}; // def setUsername
Client.prototype.setUsername = function setUsername(name){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.setUsername(name).then(dataCallback(callback),errorCallback(callback));}; // def setAvatar
Client.prototype.setAvatar = function setAvatar(avatar){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.setAvatar(avatar).then(dataCallback(callback),errorCallback(callback));}; // def joinVoiceChannel
Client.prototype.joinVoiceChannel = function joinVoiceChannel(channel){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, channel*/{}:arguments[1];return this.internal.joinVoiceChannel(channel).then(dataCallback(callback),errorCallback(callback));}; // def leaveVoiceChannel
Client.prototype.leaveVoiceChannel = function leaveVoiceChannel(chann){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.leaveVoiceChannel(chann).then(dataCallback(callback),errorCallback(callback));}; // def addFriend
Client.prototype.addFriend = function addFriend(user){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.addFriend(user).then(dataCallback(callback),errorCallback(callback));}; // def removeFriend
Client.prototype.removeFriend = function removeFriend(user){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.removeFriend(user).then(dataCallback(callback),errorCallback(callback));}; // def getOAuthApplication
Client.prototype.getOAuthApplication = function getOAuthApplication(appID){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, bans*/{}:arguments[1];if(typeof appID === "function"){ // appID is the callback
callback = appID;appID = null;}return this.internal.getOAuthApplication(appID).then(dataCallback(callback),errorCallback(callback));}; // def awaitResponse
Client.prototype.awaitResponse = function awaitResponse(msg){var toSend=arguments.length <= 1 || arguments[1] === undefined?null:arguments[1];var _this2=this;var options=arguments.length <= 2 || arguments[2] === undefined?null:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function() /*err, newMsg*/{}:arguments[3];var ret;if(toSend){if(typeof toSend === "function"){ // (msg, callback)
callback = toSend;toSend = null;options = null;}else { // (msg, toSend, ...)
if(options){if(typeof options === "function"){ //(msg, toSend, callback)
callback = options;options = null;ret = this.sendMessage(msg,toSend);}else { //(msg, toSend, options, callback)
ret = this.sendMessage(msg,toSend,options);}}else { // (msg, toSend) promise
ret = this.sendMessage(msg,toSend);}}}if(!ret){ret = Promise.resolve();} // (msg) promise
return ret.then(function(){return _this2.internal.awaitResponse(msg);}).then(dataCallback(callback),errorCallback(callback));};Client.prototype.setStatusIdle = function setStatusIdle(){var callback=arguments.length <= 0 || arguments[0] === undefined?function() /*err, {}*/{}:arguments[0];return this.internal.setStatus("idle").then(dataCallback(callback),errorCallback(callback));};Client.prototype.setStatusOnline = function setStatusOnline(){var callback=arguments.length <= 0 || arguments[0] === undefined?function() /*err, {}*/{}:arguments[0];return this.internal.setStatus("online").then(dataCallback(callback),errorCallback(callback));};Client.prototype.setStatusActive = function setStatusActive(callback){return this.setStatusOnline(callback);};Client.prototype.setStatusHere = function setStatusHere(callback){return this.setStatusOnline(callback);};Client.prototype.setStatusAvailable = function setStatusAvailable(callback){return this.setStatusOnline(callback);};Client.prototype.setStatusAway = function setStatusAway(callback){return this.setStatusIdle(callback);};Client.prototype.setPlayingGame = function setPlayingGame(game){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.setStatus(null,game,callback);};Client.prototype.setStreaming = function setStreaming(name,url,type){var callback=arguments.length <= 3 || arguments[3] === undefined?function() /*err, {}*/{}:arguments[3];return this.setStatus(null,{name:name,url:url,type:type},callback);}; //def forceFetchUsers
Client.prototype.forceFetchUsers = function forceFetchUsers(callback){return this.internal.forceFetchUsers().then(callback);};_createClass(Client,[{key:"users",get:function get(){return this.internal.users;} /**
* The server channels the Client is aware of. Only available after `ready` event has been emitted.
* @type {Cache<ServerChannel>} a Cache of the Server Channels
* @readonly
* @example
* // log the names of the channels and the server they belong to
* for(var channel of client.channels){
* console.log(`${channel.name} is part of ${channel.server.name}`)
* }
*/},{key:"channels",get:function get(){return this.internal.channels;} /**
* The servers the Client is aware of. Only available after `ready` event has been emitted.
* @type {Cache<Server>} a Cache of the Servers
* @readonly
* @example
* // log the names of the servers
* for(var server of client.servers){
* console.log(server.name)
* }
*/},{key:"servers",get:function get(){return this.internal.servers;} /**
* The PM/DM chats the Client is aware of. Only available after `ready` event has been emitted.
* @type {Cache<PMChannel>} a Cache of the PM/DM Channels.
* @readonly
* @example
* // log the names of the users the client is participating in a PM with
* for(var pm of client.privateChannels){
* console.log(`Participating in a DM with ${pm.recipient}`)
* }
*/},{key:"privateChannels",get:function get(){return this.internal.private_channels;} /**
* The friends that the Client is aware of. Only available after `ready` event has been emitted.
* @type {Cache<User>|null} a Cache of friend Users (or null if bot account)
* @readonly
* @example
* // log names of the friends that the client is aware of
* for(var user of client.friends){
* console.log(user.username);
* }
*/},{key:"friends",get:function get(){return this.internal.friends;} /**
* The incoming friend requests that the Client is aware of. Only available after `ready` event has been emitted.
* @type {Cache<User>|null} a Cache of incoming friend request Users (or null if bot account)
* @readonly
* @example
* // log names of the incoming friend requests that the client is aware of
* for(var user of client.incomingFriendRequests){
* console.log(user.username);
* }
*/},{key:"incomingFriendRequests",get:function get(){return this.internal.incoming_friend_requests;} /**
* The outgoing friend requests that the Client is aware of. Only available after `ready` event has been emitted.
* @type {Cache<User>} a Cache of outgoing friend request Users
* @readonly
* @example
* // log names of the outgoing friend requests that the client is aware of
* for(var user of client.outgoingFriendRequests){
* console.log(user.username);
* }
*/},{key:"outgoingFriendRequests",get:function get(){return this.internal.outgoing_friend_requests;} /**
* A cache of active voice connection of the Client, or null if not applicable. Only available after `ready` event has been emitted.
* @type {Cache<VoiceConnection>} a Cache of Voice Connections
*/},{key:"voiceConnections",get:function get(){return this.internal.voiceConnections;} /**
* The first voice connection the bot has connected to. Available for backwards compatibility.
* @type {VoiceConnection} first voice connection
*/},{key:"voiceConnection",get:function get(){return this.internal.voiceConnection;} /**
* Unix timestamp of when the Client first emitted the `ready `event. Only available after `ready` event has been emitted.
* @type {Number} timestamp of ready time
* @example
* // output when the client was ready
* console.log("I was first ready at " + client.readyTime);
*/},{key:"readyTime",get:function get(){return this.internal.readyTime;} /**
* How long the client has been ready for in milliseconds. Only available after `ready` event has been emitted.
* @type {Number} number in milliseconds representing uptime of the client
* @example
* // log how long the client has been up for
* console.log("I have been online for " + client.uptime + " milliseconds");
*/},{key:"uptime",get:function get(){return this.internal.uptime;} /**
* A User object that represents the account the client is logged into. Only available after `ready` event has been emitted.
* @type {User} user representing logged in account of client.
* @example
* // log username of logged in account of client
* console.log("Logged in as " + client.user.username);
*/},{key:"user",get:function get(){return this.internal.user;} /**
* Object containing user-agent information required for API requests. If not modified, it will use discord.js's defaults.
* @type {UserAgent}
* @example
* // log the stringified user-agent:
* console.log(client.userAgent.full);
*/},{key:"userAgent",get:function get(){return this.internal.userAgent;}, /**
* Set the user-agent information provided. Follows the UserAgent typedef format excluding the `full` property.
* @type {UserAgent}
*/set:function set(userAgent){this.internal.userAgent = userAgent;}}]);return Client;})(_events2["default"]);exports["default"] = Client;module.exports = exports["default"];

View File

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

File diff suppressed because one or more lines are too long

View File

@@ -1,34 +0,0 @@
"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 _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.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.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"];

View File

@@ -1,8 +0,0 @@
"use strict";exports.__esModule = true;var Constants={};var API=Constants.API = "https://discordapp.com/api";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;}, // 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";}, // 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;}, // friends
FRIENDS:API + "/users/@me/relationships"};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};Constants.PacketType = {CHANNEL_CREATE:"CHANNEL_CREATE",CHANNEL_DELETE:"CHANNEL_DELETE",CHANNEL_UPDATE:"CHANNEL_UPDATE",MESSAGE_CREATE:"MESSAGE_CREATE",MESSAGE_DELETE:"MESSAGE_DELETE",MESSAGE_UPDATE:"MESSAGE_UPDATE",PRESENCE_UPDATE:"PRESENCE_UPDATE",READY:"READY",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_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["default"] = Constants;module.exports = exports["default"];

View File

@@ -1 +0,0 @@
"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"];

View File

@@ -1,7 +0,0 @@
"use strict";exports.__esModule = true;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var _Constants=require("../Constants");var ChannelPermissions=(function(){function ChannelPermissions(permissions){_classCallCheck(this,ChannelPermissions);this.permissions = permissions;}ChannelPermissions.prototype.serialise = function serialise(explicit){var _this=this;var hp=function hp(perm){return _this.hasPermission(perm,explicit);};return { // general
createInstantInvite:hp(_Constants.Permissions.createInstantInvite),kickMembers:hp(_Constants.Permissions.kickMembers),banMembers:hp(_Constants.Permissions.banMembers),managePermissions:hp(_Constants.Permissions.managePermissions),manageChannel:hp(_Constants.Permissions.manageChannel),manageServer:hp(_Constants.Permissions.manageServer), // text
readMessages:hp(_Constants.Permissions.readMessages),sendMessages:hp(_Constants.Permissions.sendMessages),sendTTSMessages:hp(_Constants.Permissions.sendTTSMessages),manageMessages:hp(_Constants.Permissions.manageMessages),embedLinks:hp(_Constants.Permissions.embedLinks),attachFiles:hp(_Constants.Permissions.attachFiles),readMessageHistory:hp(_Constants.Permissions.readMessageHistory),mentionEveryone:hp(_Constants.Permissions.mentionEveryone), // voice
voiceConnect:hp(_Constants.Permissions.voiceConnect),voiceSpeak:hp(_Constants.Permissions.voiceSpeak),voiceMuteMembers:hp(_Constants.Permissions.voiceMuteMembers),voiceDeafenMembers:hp(_Constants.Permissions.voiceDeafenMembers),voiceMoveMembers:hp(_Constants.Permissions.voiceMoveMembers),voiceUseVAD:hp(_Constants.Permissions.voiceUseVAD)};};ChannelPermissions.prototype.serialize = function serialize(){ // ;n;
return this.serialise();};ChannelPermissions.prototype.hasPermission = function hasPermission(perm){var explicit=arguments.length <= 1 || arguments[1] === undefined?false:arguments[1];if(perm instanceof String || typeof perm === "string"){perm = _Constants.Permissions[perm];}if(!perm){return false;}if(!explicit){ // implicit permissions allowed
if(!!(this.permissions & _Constants.Permissions.manageRoles)){ // manageRoles allowed, they have all permissions
return true;}}return !!(this.permissions & perm);};return ChannelPermissions;})();exports["default"] = ChannelPermissions;module.exports = exports["default"];

View File

@@ -1 +0,0 @@
"use strict";exports.__esModule = true;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var Invite=(function(){function Invite(data,chan,client){_classCallCheck(this,Invite);this.maxAge = data.max_age;this.code = data.code;if(chan){this.channel = chan;this.server = chan.server;}else {this.channel = data.channel;this.server = data.guild;}this.revoked = data.revoked;this.createdAt = Date.parse(data.created_at);this.temporary = data.temporary;this.uses = data.uses;this.maxUses = data.max_uses;if(data.inviter){this.inviter = client.internal.users.get("id",data.inviter.id);}this.xkcd = data.xkcdpass;}Invite.prototype.toString = function toString(){return "https://discord.gg/" + this.code;};Invite.prototype["delete"] = function _delete(){return this.client.deleteInvite.apply(this.client,reg(this,arguments));};Invite.prototype.join = function join(){return this.client.joinServer.apply(this.client,reg(this,arguments));};return Invite;})();exports["default"] = Invite;module.exports = exports["default"];

View File

@@ -1,8 +0,0 @@
"use strict"; /**
* Options that can be applied to a message before sending it.
* @typedef {(object)} MessageOptions
* @property {boolean} [tts=false] Whether or not the message should be sent as text-to-speech.
*/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 _UtilCache=require("../Util/Cache");var _UtilCache2=_interopRequireDefault(_UtilCache);var _User=require("./User");var _User2=_interopRequireDefault(_User);var _UtilArgumentRegulariser=require("../Util/ArgumentRegulariser");var _UtilEquality=require("../Util/Equality");var _UtilEquality2=_interopRequireDefault(_UtilEquality);var Message=(function(_Equality){_inherits(Message,_Equality);function Message(data,channel,client){var _this=this;_classCallCheck(this,Message);_Equality.call(this);this.channel = channel;this.server = channel.server;this.client = client;this.nonce = data.nonce;this.attachments = data.attachments;this.tts = data.tts;this.embeds = data.embeds;this.timestamp = Date.parse(data.timestamp);this.everyoneMentioned = data.mention_everyone || data.everyoneMentioned;this.pinned = data.pinned;this.id = data.id;if(data.edited_timestamp){this.editedTimestamp = Date.parse(data.edited_timestamp);}if(data.author instanceof _User2["default"]){this.author = data.author;}else if(data.author){this.author = client.internal.users.add(new _User2["default"](data.author,client));}this.content = data.content;var mentionData=client.internal.resolver.resolveMentions(data.content,channel);this.cleanContent = mentionData[1];this.mentions = [];mentionData[0].forEach(function(mention){ // this is .add and not .get because it allows the bot to cache
// users from messages from logs who may have left the server and were
// not previously cached.
if(mention instanceof _User2["default"]){_this.mentions.push(mention);}else {_this.mentions.push(client.internal.users.add(new _User2["default"](mention,client)));}});}Message.prototype.isMentioned = function isMentioned(user){user = this.client.internal.resolver.resolveUser(user);if(!user){return false;}for(var _iterator=this.mentions,_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 mention=_ref;if(mention.id == user.id){return true;}}return false;};Message.prototype.toString = function toString(){return this.content;};Message.prototype["delete"] = function _delete(){return this.client.deleteMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};Message.prototype.update = function update(){return this.client.updateMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};Message.prototype.edit = function edit(){return this.client.updateMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};Message.prototype.reply = function reply(){return this.client.reply.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};Message.prototype.replyTTS = function replyTTS(){return this.client.replyTTS.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};Message.prototype.pin = function pin(){return this.client.pinMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};Message.prototype.unpin = function unpin(){return this.client.unpinMessage.apply(this.client,req(this,arguments));};_createClass(Message,[{key:"sender",get:function get(){return this.author;}}]);return Message;})(_UtilEquality2["default"]);exports["default"] = Message;module.exports = exports["default"];

View File

@@ -1 +0,0 @@
"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 _Channel2=require("./Channel");var _Channel3=_interopRequireDefault(_Channel2);var _User=require("./User");var _User2=_interopRequireDefault(_User);var _UtilCache=require("../Util/Cache");var _UtilCache2=_interopRequireDefault(_UtilCache);var _UtilArgumentRegulariser=require("../Util/ArgumentRegulariser");var PMChannel=(function(_Channel){_inherits(PMChannel,_Channel);function PMChannel(data,client){_classCallCheck(this,PMChannel);_Channel.call(this,data,client);this.type = data.type || "text";this.lastMessageID = data.last_message_id || data.lastMessageID;this.messages = new _UtilCache2["default"]("id",client.options.maxCachedMessages);this.recipient = this.client.internal.users.add(new _User2["default"](data.recipient,this.client));} /* warning! may return null */PMChannel.prototype.toString = function toString(){return this.recipient.toString();};PMChannel.prototype.sendMessage = function sendMessage(){return this.client.sendMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};PMChannel.prototype.send = function send(){return this.client.sendMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};PMChannel.prototype.sendTTSMessage = function sendTTSMessage(){return this.client.sendTTSMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};PMChannel.prototype.sendTTS = function sendTTS(){return this.client.sendTTSMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};PMChannel.prototype.sendFile = function sendFile(){return this.client.sendFile.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};PMChannel.prototype.startTyping = function startTyping(){return this.client.startTyping.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};PMChannel.prototype.stopTyping = function stopTyping(){return this.client.stopTyping.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};PMChannel.prototype.getLogs = function getLogs(){return this.client.getChannelLogs.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};PMChannel.prototype.getMessage = function getMessage(){return this.client.getMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};_createClass(PMChannel,[{key:"lastMessage",get:function get(){return this.messages.get("id",this.lastMessageID);}}]);return PMChannel;})(_Channel3["default"]);exports["default"] = PMChannel;module.exports = exports["default"];

View File

@@ -1,6 +0,0 @@
"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 _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var _Constants=require("../Constants");var PermissionOverwrite=(function(){function PermissionOverwrite(data){_classCallCheck(this,PermissionOverwrite);this.id = data.id;this.type = data.type; // member or role
this.deny = data.deny;this.allow = data.allow;} // returns an array of allowed permissions
PermissionOverwrite.prototype.setAllowed = function setAllowed(allowedArray){var _this=this;allowedArray.forEach(function(permission){if(permission instanceof String || typeof permission === "string"){permission = _Constants.Permissions[permission];}if(permission){_this.allow |= 1 << permission;}});};PermissionOverwrite.prototype.setDenied = function setDenied(deniedArray){var _this2=this;deniedArray.forEach(function(permission){if(permission instanceof String || typeof permission === "string"){permission = _Constants.Permissions[permission];}if(permission){_this2.deny |= 1 << permission;}});};_createClass(PermissionOverwrite,[{key:"allowed",get:function get(){var allowed=[];for(var permName in _Constants.Permissions) {if(permName === "manageRoles" || permName === "manageChannels"){ // these permissions do not exist in overwrites.
continue;}if(!!(this.allow & _Constants.Permissions[permName])){allowed.push(permName);}}return allowed;} // returns an array of denied permissions
},{key:"denied",get:function get(){var denied=[];for(var permName in _Constants.Permissions) {if(permName === "manageRoles" || permName === "manageChannels"){ // these permissions do not exist in overwrites.
continue;}if(!!(this.deny & _Constants.Permissions[permName])){denied.push(permName);}}return denied;}}]);return PermissionOverwrite;})();exports["default"] = PermissionOverwrite;module.exports = exports["default"];

View File

@@ -1,23 +0,0 @@
"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 _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var _Constants=require("../Constants");var _UtilArgumentRegulariser=require("../Util/ArgumentRegulariser"); /*
example data
{ position: -1,
permissions: 36953089,
name: '@everyone',
managed: false,
id: '110007368451915776',
hoist: false,
color: 0 }
*/var DefaultRole=[_Constants.Permissions.createInstantInvite,_Constants.Permissions.readMessages,_Constants.Permissions.readMessageHistory,_Constants.Permissions.sendMessages,_Constants.Permissions.sendTTSMessages,_Constants.Permissions.embedLinks,_Constants.Permissions.attachFiles,_Constants.Permissions.readMessageHistory,_Constants.Permissions.mentionEveryone,_Constants.Permissions.voiceConnect,_Constants.Permissions.voiceSpeak,_Constants.Permissions.voiceUseVAD].reduce(function(previous,current){return previous | current;},0);var Role=(function(){function Role(data,server,client){_classCallCheck(this,Role);this.position = data.position || -1;this.permissions = data.permissions || (data.name === "@everyone"?DefaultRole:0);this.name = data.name || "@everyone";this.managed = data.managed || false;this.id = data.id;this.hoist = data.hoist || false;this.color = data.color || 0;this.server = server;this.client = client;this.mentionable = data.mentionable || false;}Role.prototype.serialise = function serialise(explicit){var _this=this;var hp=function hp(perm){return _this.hasPermission(perm,explicit);};return { // general
createInstantInvite:hp(_Constants.Permissions.createInstantInvite),kickMembers:hp(_Constants.Permissions.kickMembers),banMembers:hp(_Constants.Permissions.banMembers),manageRoles:hp(_Constants.Permissions.manageRoles),manageChannels:hp(_Constants.Permissions.manageChannels),manageServer:hp(_Constants.Permissions.manageServer), // text
readMessages:hp(_Constants.Permissions.readMessages),sendMessages:hp(_Constants.Permissions.sendMessages),sendTTSMessages:hp(_Constants.Permissions.sendTTSMessages),manageMessages:hp(_Constants.Permissions.manageMessages),embedLinks:hp(_Constants.Permissions.embedLinks),attachFiles:hp(_Constants.Permissions.attachFiles),readMessageHistory:hp(_Constants.Permissions.readMessageHistory),mentionEveryone:hp(_Constants.Permissions.mentionEveryone), // voice
voiceConnect:hp(_Constants.Permissions.voiceConnect),voiceSpeak:hp(_Constants.Permissions.voiceSpeak),voiceMuteMembers:hp(_Constants.Permissions.voiceMuteMembers),voiceDeafenMembers:hp(_Constants.Permissions.voiceDeafenMembers),voiceMoveMembers:hp(_Constants.Permissions.voiceMoveMembers),voiceUseVAD:hp(_Constants.Permissions.voiceUseVAD)};};Role.prototype.serialize = function serialize(){ // ;n;
return this.serialise();};Role.prototype.hasPermission = function hasPermission(perm){var explicit=arguments.length <= 1 || arguments[1] === undefined?false:arguments[1];if(perm instanceof String || typeof perm === "string"){perm = _Constants.Permissions[perm];}if(!perm){return false;}if(!explicit){ // implicit permissions allowed
if(!!(this.permissions & _Constants.Permissions.manageRoles)){ // manageRoles allowed, they have all permissions
return true;}} // e.g.
// !!(36953089 & Permissions.manageRoles) = not allowed to manage roles
// !!(36953089 & (1 << 21)) = voice speak allowed
return !!(this.permissions & perm);};Role.prototype.setPermission = function setPermission(permission,value){if(permission instanceof String || typeof permission === "string"){permission = _Constants.Permissions[permission];}if(permission){ // valid permission
if(value){this.permissions |= permission;}else {this.permissions &= ~permission;}}};Role.prototype.setPermissions = function setPermissions(obj){var _this2=this;obj.forEach(function(value,permission){if(permission instanceof String || typeof permission === "string"){permission = _Constants.Permissions[permission];}if(permission){ // valid permission
_this2.setPermission(permission,value);}});};Role.prototype.colorAsHex = function colorAsHex(){var val=this.color.toString(16);while(val.length < 6) {val = "0" + val;}return "#" + val;};Role.prototype["delete"] = function _delete(){return this.client.deleteRole.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};Role.prototype.edit = function edit(){return this.client.updateRole.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};Role.prototype.update = function update(){return this.client.updateRole.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};Role.prototype.addMember = function addMember(member,callback){return this.client.addMemberToRole.apply(this.client,[member,this,callback]);};Role.prototype.addUser = function addUser(member,callback){return this.client.addUserToRole.apply(this.client,[member,this,callback]);};Role.prototype.removeMember = function removeMember(member,callback){return this.client.removeMemberFromRole.apply(this.client,[member,this,callback]);};Role.prototype.removeUser = function removeUser(member,callback){return this.client.removeUserFromRole.apply(this.client,[member,this,callback]);};Role.prototype.mention = function mention(){if(this.mentionable)return "<@&" + this.id + ">";return this.name;};Role.prototype.toString = function toString(){return this.mention();};_createClass(Role,[{key:"createdAt",get:function get(){return new Date(+this.id / 4194304 + 1420070400000);}}]);return Role;})();exports["default"] = Role;module.exports = exports["default"];

File diff suppressed because one or more lines are too long

View File

@@ -1 +0,0 @@
"use strict";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");}}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 _Channel2=require("./Channel");var _Channel3=_interopRequireDefault(_Channel2);var _UtilCache=require("../Util/Cache");var _UtilCache2=_interopRequireDefault(_UtilCache);var _PermissionOverwrite=require("./PermissionOverwrite");var _PermissionOverwrite2=_interopRequireDefault(_PermissionOverwrite);var _ChannelPermissions=require("./ChannelPermissions");var _ChannelPermissions2=_interopRequireDefault(_ChannelPermissions);var _UtilArgumentRegulariser=require("../Util/ArgumentRegulariser");var ServerChannel=(function(_Channel){_inherits(ServerChannel,_Channel);function ServerChannel(data,client,server){var _this=this;_classCallCheck(this,ServerChannel);_Channel.call(this,data,client);this.name = data.name;this.type = data.type;this.position = data.position;this.permissionOverwrites = data.permissionOverwrites || new _UtilCache2["default"]();this.server = server;if(!data.permissionOverwrites){data.permission_overwrites.forEach(function(permission){_this.permissionOverwrites.add(new _PermissionOverwrite2["default"](permission));});}}ServerChannel.prototype.permissionsOf = function permissionsOf(userOrRole){userOrRole = this.client.internal.resolver.resolveUser(userOrRole);if(userOrRole){if(this.server.ownerID === userOrRole.id){return new _ChannelPermissions2["default"](4294967295);}var everyoneRole=this.server.roles.get("id",this.server.id);var userRoles=[everyoneRole].concat(this.server.rolesOf(userOrRole) || []);var userRolesID=userRoles.filter(function(v){return !!v;}).map(function(v){return v.id;});var roleOverwrites=[],memberOverwrites=[];this.permissionOverwrites.forEach(function(overwrite){if(overwrite.type === "member" && overwrite.id === userOrRole.id){memberOverwrites.push(overwrite);}else if(overwrite.type === "role" && ~userRolesID.indexOf(overwrite.id)){roleOverwrites.push(overwrite);}});var permissions=0;for(var _iterator=userRoles,_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 serverRole=_ref;if(serverRole){permissions |= serverRole.permissions;}}for(var _iterator2=roleOverwrites.concat(memberOverwrites),_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 overwrite=_ref2;if(overwrite){permissions = permissions & ~overwrite.deny;permissions = permissions | overwrite.allow;}}return new _ChannelPermissions2["default"](permissions);}else {userOrRole = this.client.internal.resolver.resolveRole(userOrRole);if(userOrRole){var permissions=this.server.roles.get("id",this.server.id).permissions | userOrRole.permissions;var overwrite=this.permissionOverwrites.get("id",this.server.id);permissions = permissions & ~overwrite.deny | overwrite.allow;overwrite = this.permissionOverwrites.get("id",userOrRole.id);if(overwrite){permissions = permissions & ~overwrite.deny | overwrite.allow;}return new _ChannelPermissions2["default"](permissions);}else {return null;}}};ServerChannel.prototype.permsOf = function permsOf(user){return this.permissionsOf(user);};ServerChannel.prototype.mention = function mention(){return "<#" + this.id + ">";};ServerChannel.prototype.toString = function toString(){return this.mention();};ServerChannel.prototype.setName = function setName(){return this.client.setChannelName.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};ServerChannel.prototype.setPosition = function setPosition(){return this.client.setChannelPosition.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};ServerChannel.prototype.update = function update(){return this.client.updateChannel.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};return ServerChannel;})(_Channel3["default"]);exports["default"] = ServerChannel;module.exports = exports["default"];

View File

@@ -1 +0,0 @@
"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 _ServerChannel2=require("./ServerChannel");var _ServerChannel3=_interopRequireDefault(_ServerChannel2);var _UtilCache=require("../Util/Cache");var _UtilCache2=_interopRequireDefault(_UtilCache);var _UtilArgumentRegulariser=require("../Util/ArgumentRegulariser");var TextChannel=(function(_ServerChannel){_inherits(TextChannel,_ServerChannel);function TextChannel(data,client,server){_classCallCheck(this,TextChannel);_ServerChannel.call(this,data,client,server);this.topic = data.topic;this.lastMessageID = data.last_message_id || data.lastMessageID;this.messages = new _UtilCache2["default"]("id",client.options.maxCachedMessages);} /* warning! may return null */TextChannel.prototype.setTopic = function setTopic(){return this.client.setChannelTopic.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.sendMessage = function sendMessage(){return this.client.sendMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.send = function send(){return this.client.sendMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.sendTTSMessage = function sendTTSMessage(){return this.client.sendTTSMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.sendTTS = function sendTTS(){return this.client.sendTTSMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.sendFile = function sendFile(){return this.client.sendFile.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.getLogs = function getLogs(){return this.client.getChannelLogs.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.getMessage = function getMessage(){return this.client.getMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.startTyping = function startTyping(){return this.client.startTyping.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.stopTyping = function stopTyping(){return this.client.stopTyping.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};_createClass(TextChannel,[{key:"lastMessage",get:function get(){return this.messages.get("id",this.lastMessageID);}}]);return TextChannel;})(_ServerChannel3["default"]);exports["default"] = TextChannel;module.exports = exports["default"];

View File

@@ -1 +0,0 @@
"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 _Constants=require("../Constants");var _UtilArgumentRegulariser=require("../Util/ArgumentRegulariser");var User=(function(_Equality){_inherits(User,_Equality);function User(data,client){_classCallCheck(this,User);_Equality.call(this);this.client = client;this.username = data.username;this.discriminator = data.discriminator;this.id = data.id;this.avatar = data.avatar;this.bot = !!data.bot;this.status = data.status || "offline";this.game = data.game || null;this.typing = {since:null,channel:null};this.note = data.note || null;this.voiceChannel = null;this.voiceState = {};this.speaking = false;}User.prototype.mention = function mention(){return "<@" + this.id + ">";};User.prototype.toString = function toString(){return this.mention();};User.prototype.equalsStrict = function equalsStrict(obj){if(obj instanceof User)return this.id === obj.id && this.username === obj.username && this.discriminator === obj.discriminator && this.avatar === obj.avatar && this.status === obj.status && (this.game === obj.game || this.game && obj.game && this.game.name === obj.game.name);else return false;};User.prototype.equals = function equals(obj){if(obj instanceof User)return this.id === obj.id && this.username === obj.username && this.discriminator === obj.discriminator && this.avatar === obj.avatar;else return false;};User.prototype.sendMessage = function sendMessage(){return this.client.sendMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};User.prototype.send = function send(){return this.client.sendMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};User.prototype.sendTTSMessage = function sendTTSMessage(){return this.client.sendTTSMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};User.prototype.sendTTS = function sendTTS(){return this.client.sendTTSMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};User.prototype.sendFile = function sendFile(){return this.client.sendFile.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};User.prototype.startTyping = function startTyping(){return this.client.startTyping.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};User.prototype.stopTyping = function stopTyping(){return this.client.stopTyping.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};User.prototype.addTo = function addTo(role,callback){return this.client.addMemberToRole.apply(this.client,[this,role,callback]);};User.prototype.removeFrom = function removeFrom(role,callback){return this.client.removeMemberFromRole.apply(this.client,[this,role,callback]);};User.prototype.getLogs = function getLogs(){return this.client.getChannelLogs.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};User.prototype.getMessage = function getMessage(){return this.client.getMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};User.prototype.hasRole = function hasRole(role){return this.client.memberHasRole.apply(this.client,[this,role]);};_createClass(User,[{key:"createdAt",get:function get(){return new Date(+this.id / 4194304 + 1420070400000);}},{key:"avatarURL",get:function get(){if(!this.avatar){return null;}else {return _Constants.Endpoints.AVATAR(this.id,this.avatar);}}},{key:"name",get:function get(){return this.username;}}]);return User;})(_UtilEquality2["default"]);exports["default"] = User;module.exports = exports["default"];

View File

@@ -1,3 +0,0 @@
"use strict";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");}}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 _ServerChannel2=require("./ServerChannel");var _ServerChannel3=_interopRequireDefault(_ServerChannel2);var _UtilCache=require("../Util/Cache");var _UtilCache2=_interopRequireDefault(_UtilCache);var _UtilArgumentRegulariser=require("../Util/ArgumentRegulariser");var VoiceChannel=(function(_ServerChannel){_inherits(VoiceChannel,_ServerChannel);function VoiceChannel(data,client,server){_classCallCheck(this,VoiceChannel);_ServerChannel.call(this,data,client,server);this.members = data.members || new _UtilCache2["default"]();this.userLimit = data.user_limit || 0;this._bitrate = data.bitrate || 64000; // incase somebody wants to access the bps value???
this.bitrate = Math.round(this._bitrate / 1000); // store as kbps
}VoiceChannel.prototype.join = function join(){var callback=arguments.length <= 0 || arguments[0] === undefined?function(){}:arguments[0];return this.client.joinVoiceChannel.apply(this.client,[this,callback]);};VoiceChannel.prototype.setUserLimit = function setUserLimit(){return this.client.setChannelUserLimit.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};VoiceChannel.prototype.setBitrate = function setBitrate(){return this.client.setChannelBitrate.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};return VoiceChannel;})(_ServerChannel3["default"]);exports["default"] = VoiceChannel;module.exports = exports["default"];

View File

@@ -1 +0,0 @@
"use strict";exports.__esModule = true;exports.reg = reg;function reg(c,a){return [c].concat(Array.prototype.slice.call(a));}

View File

@@ -1,2 +0,0 @@
"use strict";exports.__esModule = true;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var Bucket=(function(){ // Adapted from Eris
function Bucket(tokenLimit,interval){_classCallCheck(this,Bucket);this.tokenLimit = tokenLimit;this.interval = interval;this.extraTime = 500;this.lastReset = this.tokens = this.lastSend = 0;this._queue = [];}Bucket.prototype.queue = function queue(func){this._queue.push(func);this.check();};Bucket.prototype.check = function check(){var _this=this;if(this.timeout || this._queue.length === 0){return;}if(this.lastReset + this.interval + this.extraTime < Date.now()){this.lastReset = Date.now();this.tokens = Math.max(0,this.tokens - this.tokenLimit);}var val;while(this._queue.length > 0 && this.tokens < this.tokenLimit) {this.tokens++;this._queue.shift()();this.lastSend = Date.now();}if(this._queue.length > 0 && !this.timeout){this.timeout = setTimeout(function(){_this.timeout = null;_this.check();},this.tokens < this.tokenLimit?1:Math.max(0,this.lastReset + this.interval + this.extraTime - Date.now()));}};return Bucket;})();exports["default"] = Bucket;module.exports = exports["default"];

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