diff --git a/.gitignore b/.gitignore index 9167b884f..5b0cfbfeb 100644 --- a/.gitignore +++ b/.gitignore @@ -35,4 +35,8 @@ build/Release node_modules test/auth.json examples/auth.json -docs/_build \ No newline at end of file +docs/_build + +# Secret keys +docs/deploy/deploy_key +docs/deploy/deploy_key.pub diff --git a/.travis.yml b/.travis.yml index 82e77e0af..310a7c4b1 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,3 +5,9 @@ cache: directories: - node_modules install: npm install +script: bash ./docs/deploy/deploy.sh +env: + global: + - ENCRYPTION_LABEL: "af862fa96d3e" + - COMMIT_AUTHOR_EMAIL: "amishshah.2k@gmail.com" + diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4afe7392a..4d1c83166 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -7,8 +7,8 @@ is a great boon to your coding process. To get ready to work on the codebase, please do the following: 1. Fork & clone the repository -2. Run `npm install`, or `npm install --no-optional` if you're not working on voice -3. Code your heart out! -4. Run `npm test` to run ESLint -5. Run `npm run docs` to build any documentation changes +2. Run `npm install` +3. If you're working on voice, also run `npm install node-opus` or `npm install opusscript` +4. Code your heart out! +5. Run `npm test` to run ESLint and ensure any JSDoc changes are valid 6. [Submit a pull request](https://github.com/hydrabolt/discord.js/compare) diff --git a/README.md b/README.md index 1a3e4472d..f4d11cd7a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@

- discord.js
+ discord.js

@@ -16,12 +16,14 @@ discord.js is a powerful node.js module that allows you to interact with the [Di ## Installation **Node.js 6.0.0 or newer is required.** -With voice support: `npm install --save discord.js --production` -Without voice support: `npm install --save discord.js --production --no-optional` +Without voice support: `npm install discord.js --save` +With voice support ([node-opus](https://www.npmjs.com/package/node-opus)): `npm install discord.js node-opus --save` +With voice support ([opusscript](https://www.npmjs.com/package/opusscript)): `npm install discord.js opusscript --save` +If both audio packages are installed, discord.js will automatically choose node-opus. -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. +The preferred audio engine is node-opus, as it performs significantly better than opusscript. +Using opusscript is only recommended for development on Windows, since getting node-opus to build there can be a bit of a challenge. +For production bots, using node-opus should be considered a necessity, especially if they're going to be running on multiple servers. ## Example Usage ```js @@ -41,17 +43,24 @@ client.on('message', message => { client.login('your token'); ``` +A bot template using discord.js can be generated using [generator-discordbot](https://www.npmjs.com/package/generator-discordbot). + ## Links * [Website](http://hydrabolt.github.io/discord.js/) -* [Discord.js Server](https://discord.gg/bRCvFy9) -* [Discord API Server](https://discord.gg/rV4BwdK) +* [Discord.js server](https://discord.gg/bRCvFy9) +* [Discord API server](https://discord.gg/rV4BwdK) * [Documentation](http://hydrabolt.github.io/discord.js/#!/docs/tag/master) -* [Legacy Documentation](http://discordjs.readthedocs.io/en/8.1.0/docs_client.html) +* [Legacy (v8) documentation](http://discordjs.readthedocs.io/en/8.2.0/docs_client.html) +* [Examples](https://github.com/hydrabolt/discord.js/tree/master/docs/custom/examples) * [GitHub](https://github.com/hydrabolt/discord.js) * [NPM](https://www.npmjs.com/package/discord.js) -* [Examples](https://github.com/hydrabolt/discord.js/tree/master/docs/custom/examples) -* [Related Libraries](https://discordapi.com/unofficial/libs.html) +* [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 ask in the official [Discord.js Server](https://discord.gg/bRCvFy9). +## Contributing +Before creating an issue, please ensure that it hasn't already been reported/suggested, and double-check the +[documentation](http://hydrabolt.github.io/discord.js/#!/docs/tag/master). +See [the contributing guide](CONTRIBUTING.md) if you'd like to submit a PR. + +## Help +If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle +nudge in the right direction, please don't hesitate to join our official [Discord.js Server](https://discord.gg/bRCvFy9). diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 000000000..f456e41cb --- /dev/null +++ b/docs/README.md @@ -0,0 +1,2 @@ +# discord.js docs +[View documentation here](http://hydrabolt.github.io/discord.js/#!/docs/) \ No newline at end of file diff --git a/docs/custom/documents/welcome.md b/docs/custom/documents/welcome.md index 74483b166..d2b50758c 100644 --- a/docs/custom/documents/welcome.md +++ b/docs/custom/documents/welcome.md @@ -20,12 +20,14 @@ stable and performant than previous versions. ## Installation **Node.js 6.0.0 or newer is required.** -With voice support: `npm install --save discord.js --production` -Without voice support: `npm install --save discord.js --production --no-optional` +Without voice support: `npm install discord.js --save` +With voice support ([node-opus](https://www.npmjs.com/package/node-opus)): `npm install discord.js node-opus --save` +With voice support ([opusscript](https://www.npmjs.com/package/opusscript)): `npm install discord.js opusscript --save` +If both audio packages are installed, discord.js will automatically prefer node-opus. -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. +The preferred audio engine is node-opus, as it performs significantly better than opusscript. +Using opusscript is only recommended for development on Windows, since getting node-opus to build there can be a bit of a challenge. +For production bots, using node-opus should be considered a necessity, especially if they're going to be running on multiple servers. ## Guides * [LuckyEvie's general guide](https://eslachance.gitbooks.io/discord-js-bot-guide/content/) @@ -33,15 +35,15 @@ discord.js will automatically prefer node-opus over opusscript. ## Links * [Website](http://hydrabolt.github.io/discord.js/) -* [Discord.js Server](https://discord.gg/bRCvFy9) -* [Discord API Server](https://discord.gg/rV4BwdK) +* [Discord.js server](https://discord.gg/bRCvFy9) +* [Discord API server](https://discord.gg/rV4BwdK) * [Documentation](http://hydrabolt.github.io/discord.js/#!/docs/tag/master) -* [Legacy Documentation](http://discordjs.readthedocs.io/en/8.1.0/docs_client.html) +* [Legacy (v8) documentation](http://discordjs.readthedocs.io/en/8.2.0/docs_client.html) +* [Examples](https://github.com/hydrabolt/discord.js/tree/master/docs/custom/examples) * [GitHub](https://github.com/hydrabolt/discord.js) * [NPM](https://www.npmjs.com/package/discord.js) -* [Examples](https://github.com/hydrabolt/discord.js/tree/master/docs/custom/examples) -* [Related Libraries](https://discordapi.com/unofficial/libs.html) +* [Related libraries](https://discordapi.com/unofficial/libs.html) ## Help -If you don't understand something in this documentation, you are experiencing problems, or you just need a gentle +If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don't hesitate to join our official [Discord.js Server](https://discord.gg/bRCvFy9). diff --git a/docs/custom/examples/webhook.js b/docs/custom/examples/webhook.js new file mode 100644 index 000000000..13cf7c883 --- /dev/null +++ b/docs/custom/examples/webhook.js @@ -0,0 +1,12 @@ +/* + Send a message using a webhook +*/ + +// import the discord.js module +const Discord = require('discord.js'); + +// create a new webhook +const hook = new Discord.WebhookClient('webhook id', 'webhook token'); + +// send a message using the webhook +hook.sendMessage('I am now alive!'); diff --git a/docs/custom/webhook.js b/docs/custom/webhook.js new file mode 100644 index 000000000..10f57f361 --- /dev/null +++ b/docs/custom/webhook.js @@ -0,0 +1,10 @@ +const fs = require('fs'); + +module.exports = { + category: 'Examples', + name: 'Webhooks', + data: +`\`\`\`js +${fs.readFileSync('./docs/custom/examples/webhook.js').toString('utf-8')} +\`\`\``, +}; diff --git a/docs/deploy/deploy.sh b/docs/deploy/deploy.sh new file mode 100644 index 000000000..fa0cdfa70 --- /dev/null +++ b/docs/deploy/deploy.sh @@ -0,0 +1,68 @@ +#!/bin/bash +# Adapted from https://gist.github.com/domenic/ec8b0fc8ab45f39403dd. + +set -e + +function build { + node docs/generator/generator.js +} + +# Ignore Travis checking PRs +if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then + echo "deploy.sh: Ignoring PR build" + build + exit 0 +fi + +# Ignore travis checking other branches irrelevant to users +if [ "$TRAVIS_BRANCH" != "master" -a "$TRAVIS_BRANCH" != "indev" ]; then + echo "deploy.sh: Ignoring push to another branch than master/indev" + build + exit 0 +fi + +SOURCE=$TRAVIS_BRANCH + +# Make sure tag pushes are handled +if [ -n "$TRAVIS_TAG" ]; then + echo "deploy.sh: This is a tag build, proceeding accordingly" + SOURCE=$TRAVIS_TAG +fi + +REPO=`git config remote.origin.url` +SSH_REPO=${REPO/https:\/\/github.com\//git@github.com:} +SHA=`git rev-parse --verify HEAD` + +TARGET_BRANCH="docs" + +# Checkout the repo in the target branch so we can build docs and push to it +git clone $REPO out -b $TARGET_BRANCH +cd out +cd .. + +# Build the docs +build + +# Move the generated JSON file to the newly-checked-out repo, to be committed +# and pushed +mv docs/docs.json out/$SOURCE.json + +# Commit and push +cd out +git config user.name "Travis CI" +git config user.email "$COMMIT_AUTHOR_EMAIL" + +git add . +git commit -m "Docs build: ${SHA}" + +ENCRYPTED_KEY_VAR="encrypted_${ENCRYPTION_LABEL}_key" +ENCRYPTED_IV_VAR="encrypted_${ENCRYPTION_LABEL}_iv" +ENCRYPTED_KEY=${!ENCRYPTED_KEY_VAR} +ENCRYPTED_IV=${!ENCRYPTED_IV_VAR} +openssl aes-256-cbc -K $ENCRYPTED_KEY -iv $ENCRYPTED_IV -in ../docs/deploy/deploy_key.enc -out deploy_key -d +chmod 600 deploy_key +eval `ssh-agent -s` +ssh-add deploy_key + +# Now that we're all set up, we can push. +git push $SSH_REPO $TARGET_BRANCH diff --git a/docs/deploy/deploy_key.enc b/docs/deploy/deploy_key.enc new file mode 100644 index 000000000..e03fc36d7 Binary files /dev/null and b/docs/deploy/deploy_key.enc differ diff --git a/docs/docs.json b/docs/docs.json deleted file mode 100644 index 73803dd45..000000000 --- a/docs/docs.json +++ /dev/null @@ -1 +0,0 @@ -{"meta":{"version":13,"date":1477163530228},"classes":[{"id":"Client","name":"Client","description":"The starting point for making a Discord Bot.","meta":{"line":17,"file":"Client.js","path":"src/client"},"extends":["EventEmitter"],"classConstructor":{"id":"Client()","name":"Client","memberof":"Client","params":[{"name":"options","description":"Options for the client","optional":true,"type":{"types":[[["ClientOptions",""]]]}}]},"methods":[{"id":"Client#login","name":"login","description":"Logs the client in. If successful, resolves with the account's token. If you're making a bot, it's\rmuch better to use a bot account rather than a user account.\rBot accounts have higher rate limits and have access to some features user accounts don't have. User bots\rthat are making a lot of API requests can even be banned.","memberof":"Client","examples":["// log the client in using a token\rconst token = 'my token';\rclient.login(token);","// log the client in using email and password\rconst email = 'user@email.com';\rconst password = 'supersecret123';\rclient.login(email, password);"],"meta":{"line":218,"file":"Client.js","path":"src/client"},"returns":{"types":[[["Promise",".<"],["string",">"]]]},"params":[{"name":"tokenOrEmail","description":"The token or email used for the account. If it is an email, a password _must_ be\rprovided.","type":{"types":[[["string",""]]]}},{"name":"password","description":"The password for the account, only needed if an email was provided.","optional":true,"type":{"types":[[["string",""]]]}}]},{"id":"Client#destroy","name":"destroy","description":"Destroys the client and logs out.","memberof":"Client","meta":{"line":227,"file":"Client.js","path":"src/client"},"returns":{"types":[[["Promise",""]]]},"params":[]},{"id":"Client#syncGuilds","name":"syncGuilds","description":"This shouldn't really be necessary to most developers as it is automatically invoked every 30 seconds, however\rif you wish to force a sync of Guild data, you can use this. Only applicable to user accounts.","memberof":"Client","meta":{"line":247,"file":"Client.js","path":"src/client"},"returns":{"types":[[["null",""]]]},"params":[{"name":"guilds","description":"An array of guilds to sync","optional":true,"type":{"types":[[["Array",".<"],["Guild",">"]]]}}]},{"id":"Client#fetchUser","name":"fetchUser","description":"Caches a user, or obtains it from the cache if it's already cached.\rIf the user isn't already cached, it will only be obtainable by OAuth bot accounts.","memberof":"Client","meta":{"line":262,"file":"Client.js","path":"src/client"},"returns":{"types":[[["Promise",".<"],["User",">"]]]},"params":[{"name":"id","description":"The ID of the user to obtain","type":{"types":[[["string",""]]]}}]},{"id":"Client#fetchInvite","name":"fetchInvite","description":"Fetches an invite object from an invite code.","memberof":"Client","meta":{"line":272,"file":"Client.js","path":"src/client"},"returns":{"types":[[["Promise",".<"],["Invite",">"]]]},"params":[{"name":"code","description":"the invite code.","type":{"types":[[["string",""]]]}}]},{"id":"Client#sweepMessages","name":"sweepMessages","description":"Sweeps all channels' messages and removes the ones older than the max message lifetime.\rIf the message has been edited, the time of the edit is used rather than the time of the original message.","memberof":"Client","meta":{"line":284,"file":"Client.js","path":"src/client"},"returns":{"types":[[["number",""]]]},"params":[{"name":"lifetime","description":"Messages that are older than this (in seconds)\rwill be removed from the caches. The default is based on the client's `message_cache_lifetime` option.","optional":true,"type":{"types":[[["number",""]]]}}]}],"properties":[{"id":"Client#options","name":"options","description":"The options the client was instantiated with","memberof":"Client","type":{"types":[[["ClientOptions",""]]]},"meta":{"line":28,"file":"Client.js","path":"src/client"},"props":[]},{"id":"Client#users","name":"users","description":"A Collection of the Client's stored users","memberof":"Client","type":{"types":[[["Collection",".<"],["string",", "],["User",">"]]]},"meta":{"line":91,"file":"Client.js","path":"src/client"},"props":[]},{"id":"Client#guilds","name":"guilds","description":"A Collection of the Client's stored guilds","memberof":"Client","type":{"types":[[["Collection",".<"],["string",", "],["Guild",">"]]]},"meta":{"line":97,"file":"Client.js","path":"src/client"},"props":[]},{"id":"Client#channels","name":"channels","description":"A Collection of the Client's stored channels","memberof":"Client","type":{"types":[[["Collection",".<"],["string",", "],["Channel",">"]]]},"meta":{"line":103,"file":"Client.js","path":"src/client"},"props":[]},{"id":"Client#token","name":"token","description":"The authorization token for the logged in user/bot.","memberof":"Client","type":{"types":[[["string",""]]]},"meta":{"line":109,"file":"Client.js","path":"src/client"},"props":[]},{"id":"Client#email","name":"email","description":"The email, if there is one, for the logged in Client","memberof":"Client","type":{"types":[[["string",""]]]},"meta":{"line":115,"file":"Client.js","path":"src/client"},"props":[]},{"id":"Client#password","name":"password","description":"The password, if there is one, for the logged in Client","memberof":"Client","type":{"types":[[["string",""]]]},"meta":{"line":121,"file":"Client.js","path":"src/client"},"props":[]},{"id":"Client#user","name":"user","description":"The ClientUser representing the logged in Client","memberof":"Client","type":{"types":[[["ClientUser",""]]]},"meta":{"line":127,"file":"Client.js","path":"src/client"},"props":[]},{"id":"Client#readyTime","name":"readyTime","description":"The date at which the Client was regarded as being in the `READY` state.","memberof":"Client","type":{"types":[[["Date",""]]]},"meta":{"line":133,"file":"Client.js","path":"src/client"},"props":[]},{"id":"Client#status","name":"status","description":"The status for the logged in Client.","memberof":"Client","type":{"types":[[["number",""]]]},"meta":{"line":166,"file":"Client.js","path":"src/client"},"props":[]},{"id":"Client#uptime","name":"uptime","description":"The uptime for the logged in Client.","memberof":"Client","type":{"types":[[["number",""]]]},"meta":{"line":175,"file":"Client.js","path":"src/client"},"props":[]},{"id":"Client#voiceConnections","name":"voiceConnections","description":"Returns a Collection, mapping Guild ID to Voice Connections.","memberof":"Client","type":{"types":[[["Collection",".<"],["string",", "],["VoiceConnection",">"]]]},"meta":{"line":184,"file":"Client.js","path":"src/client"},"props":[]},{"id":"Client#emojis","name":"emojis","description":"The emojis that the client can use. Mapped by emoji ID.","memberof":"Client","type":{"types":[[["Collection",".<"],["string",", "],["Emoji",">"]]]},"meta":{"line":193,"file":"Client.js","path":"src/client"},"props":[]}],"events":[{"id":"Client#event:channelUpdate","name":"channelUpdate","description":"Emitted whenever a channel is updated - e.g. name change, topic change.","memberof":"Client","meta":{"line":27,"file":"ChannelUpdate.js","path":"src/client/actions"},"params":[{"name":"oldChannel","description":"The channel before the update","type":{"types":[[["Channel",""]]]}},{"name":"newChannel","description":"The channel after the update","type":{"types":[[["Channel",""]]]}}]},{"id":"Client#event:guildUnavailable","name":"guildUnavailable","description":"Emitted whenever a guild becomes unavailable, likely due to a server outage.","memberof":"Client","meta":{"line":45,"file":"GuildDelete.js","path":"src/client/actions"},"params":[{"name":"guild","description":"The guild that has become unavailable.","type":{"types":[[["Guild",""]]]}}]},{"id":"Client#event:guildMemberRemove","name":"guildMemberRemove","description":"Emitted whenever a member leaves a guild, or is kicked.","memberof":"Client","meta":{"line":43,"file":"GuildMemberRemove.js","path":"src/client/actions"},"params":[{"name":"guild","description":"The guild that the member has left.","type":{"types":[[["Guild",""]]]}},{"name":"member","description":"The member that has left the guild.","type":{"types":[[["GuildMember",""]]]}}]},{"id":"Client#event:guildRoleCreate","name":"guildRoleCreate","description":"Emitted whenever a guild role is created.","memberof":"Client","meta":{"line":26,"file":"GuildRoleCreate.js","path":"src/client/actions"},"params":[{"name":"guild","description":"The guild that the role was created in.","type":{"types":[[["Guild",""]]]}},{"name":"role","description":"The role that was created.","type":{"types":[[["Role",""]]]}}]},{"id":"Client#event:guildRoleDelete","name":"guildRoleDelete","description":"Emitted whenever a guild role is deleted.","memberof":"Client","meta":{"line":40,"file":"GuildRoleDelete.js","path":"src/client/actions"},"params":[{"name":"guild","description":"The guild that the role was deleted in.","type":{"types":[[["Guild",""]]]}},{"name":"role","description":"The role that was deleted.","type":{"types":[[["Role",""]]]}}]},{"id":"Client#event:guildRoleUpdate","name":"guildRoleUpdate","description":"Emitted whenever a guild role is updated.","memberof":"Client","meta":{"line":34,"file":"GuildRoleUpdate.js","path":"src/client/actions"},"params":[{"name":"guild","description":"The guild that the role was updated in.","type":{"types":[[["Guild",""]]]}},{"name":"oldRole","description":"The role before the update.","type":{"types":[[["Role",""]]]}},{"name":"newRole","description":"The role after the update.","type":{"types":[[["Role",""]]]}}]},{"id":"Client#event:guildUpdate","name":"guildUpdate","description":"Emitted whenever a guild is updated - e.g. name change.","memberof":"Client","meta":{"line":27,"file":"GuildUpdate.js","path":"src/client/actions"},"params":[{"name":"oldGuild","description":"The guild before the update.","type":{"types":[[["Guild",""]]]}},{"name":"newGuild","description":"The guild after the update.","type":{"types":[[["Guild",""]]]}}]},{"id":"Client#event:messageUpdate","name":"messageUpdate","description":"Emitted whenever a message is updated - e.g. embed or content change.","memberof":"Client","meta":{"line":36,"file":"MessageUpdate.js","path":"src/client/actions"},"params":[{"name":"oldMessage","description":"The message before the update.","type":{"types":[[["Message",""]]]}},{"name":"newMessage","description":"The message after the update.","type":{"types":[[["Message",""]]]}}]},{"id":"Client#event:userUpdate","name":"userUpdate","description":"Emitted whenever a detail of the logged in User changes - e.g. username.","memberof":"Client","meta":{"line":33,"file":"UserUpdate.js","path":"src/client/actions"},"params":[{"name":"oldClientUser","description":"The client user before the update.","type":{"types":[[["ClientUser",""]]]}},{"name":"newClientUser","description":"The client user after the update.","type":{"types":[[["ClientUser",""]]]}}]},{"id":"Client#event:warn","name":"warn","description":"Emitted for general warnings","memberof":"Client","meta":{"line":340,"file":"Client.js","path":"src/client"},"params":[{"name":"The","description":"warning","type":{"types":[[["string",""]]]}}]},{"id":"Client#event:debug","name":"debug","description":"Emitted for general debugging information","memberof":"Client","meta":{"line":346,"file":"Client.js","path":"src/client"},"params":[{"name":"The","description":"debug information","type":{"types":[[["string",""]]]}}]},{"id":"Client#event:guildCreate","name":"guildCreate","description":"Emitted whenever the client joins a Guild.","memberof":"Client","meta":{"line":25,"file":"ClientDataManager.js","path":"src/client"},"params":[{"name":"guild","description":"The created guild","type":{"types":[[["Guild",""]]]}}]},{"id":"Client#event:channelCreate","name":"channelCreate","description":"Emitted whenever a Channel is created.","memberof":"Client","meta":{"line":11,"file":"ChannelCreate.js","path":"src/client/websocket/packets/handlers"},"params":[{"name":"channel","description":"The channel that was created","type":{"types":[[["Channel",""]]]}}]},{"id":"Client#event:channelDelete","name":"channelDelete","description":"Emitted whenever a Channel is deleted.","memberof":"Client","meta":{"line":14,"file":"ChannelDelete.js","path":"src/client/websocket/packets/handlers"},"params":[{"name":"channel","description":"The channel that was deleted","type":{"types":[[["Channel",""]]]}}]},{"id":"Client#event:channelPinsUpdate","name":"channelPinsUpdate","description":"Emitted whenever the pins of a Channel are updated. Due to the nature of the WebSocket event, not much information\rcan be provided easily here - you need to manually check the pins yourself.","memberof":"Client","meta":{"line":23,"file":"ChannelPinsUpdate.js","path":"src/client/websocket/packets/handlers"},"params":[{"name":"channel","description":"The channel that the pins update occured in","type":{"types":[[["Channel",""]]]}},{"name":"time","description":"The time of the pins update","type":{"types":[[["Date",""]]]}}]},{"id":"Client#event:guildBanAdd","name":"guildBanAdd","description":"Emitted whenever a member is banned from a guild.","memberof":"Client","meta":{"line":16,"file":"GuildBanAdd.js","path":"src/client/websocket/packets/handlers"},"params":[{"name":"guild","description":"The guild that the ban occurred in","type":{"types":[[["Guild",""]]]}},{"name":"user","description":"The user that was banned","type":{"types":[[["User",""]]]}}]},{"id":"Client#event:guildBanRemove","name":"guildBanRemove","description":"Emitted whenever a member is unbanned from a guild.","memberof":"Client","meta":{"line":13,"file":"GuildBanRemove.js","path":"src/client/websocket/packets/handlers"},"params":[{"name":"guild","description":"The guild that the unban occurred in","type":{"types":[[["Guild",""]]]}},{"name":"user","description":"The user that was unbanned","type":{"types":[[["User",""]]]}}]},{"id":"Client#event:guildDelete","name":"guildDelete","description":"Emitted whenever a Guild is deleted/left.","memberof":"Client","meta":{"line":13,"file":"GuildDelete.js","path":"src/client/websocket/packets/handlers"},"params":[{"name":"guild","description":"The guild that was deleted","type":{"types":[[["Guild",""]]]}}]},{"id":"Client#event:guildMembersChunk","name":"guildMembersChunk","description":"Emitted whenever a chunk of Guild members is received","memberof":"Client","meta":{"line":22,"file":"GuildMembersChunk.js","path":"src/client/websocket/packets/handlers"},"params":[{"name":"guild","description":"The guild that the chunks relate to","type":{"types":[[["Guild",""]]]}},{"name":"members","description":"The members in the chunk","type":{"types":[[["Array",".<"],["GuildMember",">"]]]}}]},{"id":"Client#event:message","name":"message","description":"Emitted whenever a message is created","memberof":"Client","meta":{"line":13,"file":"MessageCreate.js","path":"src/client/websocket/packets/handlers"},"params":[{"name":"message","description":"The created message","type":{"types":[[["Message",""]]]}}]},{"id":"Client#event:messageDelete","name":"messageDelete","description":"Emitted whenever a message is deleted","memberof":"Client","meta":{"line":13,"file":"MessageDelete.js","path":"src/client/websocket/packets/handlers"},"params":[{"name":"message","description":"The deleted message","type":{"types":[[["Message",""]]]}}]},{"id":"Client#event:messageDeleteBulk","name":"messageDeleteBulk","description":"Emitted whenever messages are deleted in bulk","memberof":"Client","meta":{"line":11,"file":"MessageDeleteBulk.js","path":"src/client/websocket/packets/handlers"},"params":[{"name":"messages","description":"The deleted messages, mapped by their ID","type":{"types":[[["Collection",".<"],["string",", "],["Message",">"]]]}}]},{"id":"Client#event:presenceUpdate","name":"presenceUpdate","description":"Emitted whenever a user changes one of their details or starts/stop playing a game","memberof":"Client","meta":{"line":55,"file":"PresenceUpdate.js","path":"src/client/websocket/packets/handlers"},"params":[{"name":"oldUser","description":"The user before the presence update","type":{"types":[[["User",""]]]}},{"name":"newUser","description":"The user after the presence update","type":{"types":[[["User",""]]]}}]},{"id":"Client#event:guildMemberAvailable","name":"guildMemberAvailable","description":"Emitted whenever a member becomes available in a large Guild","memberof":"Client","meta":{"line":62,"file":"PresenceUpdate.js","path":"src/client/websocket/packets/handlers"},"params":[{"name":"guild","description":"The guild that the member became available in","type":{"types":[[["Guild",""]]]}},{"name":"member","description":"The member that became available","type":{"types":[[["GuildMember",""]]]}}]},{"id":"Client#event:typingStart","name":"typingStart","description":"Emitted whenever a user starts typing in a channel","memberof":"Client","meta":{"line":54,"file":"TypingStart.js","path":"src/client/websocket/packets/handlers"},"params":[{"name":"channel","description":"The channel the user started typing in","type":{"types":[[["Channel",""]]]}},{"name":"user","description":"The user that started typing","type":{"types":[[["User",""]]]}}]},{"id":"Client#event:typingStop","name":"typingStop","description":"Emitted whenever a user stops typing in a channel","memberof":"Client","meta":{"line":61,"file":"TypingStart.js","path":"src/client/websocket/packets/handlers"},"params":[{"name":"channel","description":"The channel the user stopped typing in","type":{"types":[[["Channel",""]]]}},{"name":"user","description":"The user that stopped typing","type":{"types":[[["User",""]]]}}]},{"id":"Client#event:voiceStateUpdate","name":"voiceStateUpdate","description":"Emitted whenever a user changes voice state - e.g. joins/leaves a channel, mutes/unmutes.","memberof":"Client","meta":{"line":42,"file":"VoiceStateUpdate.js","path":"src/client/websocket/packets/handlers"},"params":[{"name":"oldMember","description":"The member before the voice state update","type":{"types":[[["GuildMember",""]]]}},{"name":"newMember","description":"The member after the voice state update","type":{"types":[[["GuildMember",""]]]}}]},{"id":"Client#event:disconnect","name":"disconnect","description":"Emitted whenever the client websocket is disconnected","memberof":"Client","meta":{"line":170,"file":"WebSocketManager.js","path":"src/client/websocket"},"params":[]},{"id":"Client#event:error","name":"error","description":"Emitted whenever the Client encounters a serious connection error","memberof":"Client","meta":{"line":206,"file":"WebSocketManager.js","path":"src/client/websocket"},"params":[{"name":"error","description":"The encountered error","type":{"types":[[["Error",""]]]}}]},{"id":"Client#event:ready","name":"ready","description":"Emitted when the Client becomes ready to start working","memberof":"Client","meta":{"line":216,"file":"WebSocketManager.js","path":"src/client/websocket"},"params":[]},{"id":"Client#event:reconnecting","name":"reconnecting","description":"Emitted when the Client tries to reconnect after being disconnected","memberof":"Client","meta":{"line":258,"file":"WebSocketManager.js","path":"src/client/websocket"},"params":[]},{"id":"Client#event:guildMemberAdd","name":"guildMemberAdd","description":"Emitted whenever a user joins a guild.","memberof":"Client","meta":{"line":636,"file":"Guild.js","path":"src/structures"},"params":[{"name":"guild","description":"The guild that the user has joined","type":{"types":[[["Guild",""]]]}},{"name":"member","description":"The member that has joined","type":{"types":[[["GuildMember",""]]]}}]},{"id":"Client#event:guildMemberUpdate","name":"guildMemberUpdate","description":"Emitted whenever a Guild Member changes - i.e. new role, removed role, nickname","memberof":"Client","meta":{"line":659,"file":"Guild.js","path":"src/structures"},"params":[{"name":"guild","description":"The guild that the update affects","type":{"types":[[["Guild",""]]]}},{"name":"oldMember","description":"The member before the update","type":{"types":[[["GuildMember",""]]]}},{"name":"newMember","description":"The member after the update","type":{"types":[[["GuildMember",""]]]}}]},{"id":"Client#event:guildMemberSpeaking","name":"guildMemberSpeaking","description":"Emitted once a Guild Member starts/stops speaking","memberof":"Client","meta":{"line":684,"file":"Guild.js","path":"src/structures"},"params":[{"name":"member","description":"The member that started/stopped speaking","type":{"types":[[["GuildMember",""]]]}},{"name":"speaking","description":"Whether or not the member is speaking","type":{"types":[[["boolean",""]]]}}]}]},{"id":"StreamDispatcher","name":"StreamDispatcher","description":"The class that sends voice packet data to the voice connection.\r```js\r// obtained using:\rvoiceChannel.join().then(connection => {\r // you can play a file or a stream here:\r connection.playFile('./file.mp3').then(dispatcher => {\r\r });\r});\r```","meta":{"line":20,"file":"StreamDispatcher.js","path":"src/client/voice/dispatcher"},"extends":["EventEmitter"],"methods":[{"id":"StreamDispatcher#end","name":"end","description":"Stops the current stream permanently and emits an `end` event.","memberof":"StreamDispatcher","meta":{"line":245,"file":"StreamDispatcher.js","path":"src/client/voice/dispatcher"},"returns":{"types":[[["null",""]]]},"params":[]},{"id":"StreamDispatcher#setVolume","name":"setVolume","description":"Sets the volume relative to the input stream - i.e. 1 is normal, 0.5 is half, 2 is double.","memberof":"StreamDispatcher","meta":{"line":262,"file":"StreamDispatcher.js","path":"src/client/voice/dispatcher"},"returns":{"types":[[["null",""]]]},"params":[{"name":"volume","description":"The volume that you want to set","type":{"types":[[["number",""]]]}}]},{"id":"StreamDispatcher#setVolumeDecibels","name":"setVolumeDecibels","description":"Set the volume in decibels","memberof":"StreamDispatcher","meta":{"line":270,"file":"StreamDispatcher.js","path":"src/client/voice/dispatcher"},"returns":{"types":[[["null",""]]]},"params":[{"name":"db","description":"The decibels","type":{"types":[[["number",""]]]}}]},{"id":"StreamDispatcher#setVolumeLogarithmic","name":"setVolumeLogarithmic","description":"Set the volume so that a perceived value of 0.5 is half the perceived volume etc.","memberof":"StreamDispatcher","meta":{"line":278,"file":"StreamDispatcher.js","path":"src/client/voice/dispatcher"},"returns":{"types":[[["null",""]]]},"params":[{"name":"value","description":"The value for the volume","type":{"types":[[["number",""]]]}}]},{"id":"StreamDispatcher#pause","name":"pause","description":"Stops sending voice packets to the voice connection (stream may still progress however)","memberof":"StreamDispatcher","meta":{"line":285,"file":"StreamDispatcher.js","path":"src/client/voice/dispatcher"},"returns":{"types":[[["null",""]]]},"params":[]},{"id":"StreamDispatcher#resume","name":"resume","description":"Resumes sending voice packets to the voice connection (may be further on in the stream than when paused)","memberof":"StreamDispatcher","meta":{"line":292,"file":"StreamDispatcher.js","path":"src/client/voice/dispatcher"},"returns":{"types":[[["null",""]]]},"params":[]}],"properties":[{"id":"StreamDispatcher#passes","name":"passes","description":"How many passes the dispatcher should take when sending packets to reduce packet loss. Values over 5\raren't recommended, as it means you are using 5x more bandwidth. You _can_ edit this at runtime.","memberof":"StreamDispatcher","type":{"types":[[["number",""]]]},"meta":{"line":40,"file":"StreamDispatcher.js","path":"src/client/voice/dispatcher"},"props":[]},{"id":"StreamDispatcher#time","name":"time","description":"how long the stream dispatcher has been \"speaking\" for","memberof":"StreamDispatcher","type":{"types":[[["number",""]]]},"meta":{"line":66,"file":"StreamDispatcher.js","path":"src/client/voice/dispatcher"},"props":[]},{"id":"StreamDispatcher#totalStreamTime","name":"totalStreamTime","description":"The total time, taking into account pauses and skips, that the dispatcher has been streaming for.","memberof":"StreamDispatcher","type":{"types":[[["number",""]]]},"meta":{"line":75,"file":"StreamDispatcher.js","path":"src/client/voice/dispatcher"},"props":[]},{"id":"StreamDispatcher#volume","name":"volume","description":"The volume of the stream, relative to the stream's input volume","memberof":"StreamDispatcher","type":{"types":[[["number",""]]]},"meta":{"line":254,"file":"StreamDispatcher.js","path":"src/client/voice/dispatcher"},"props":[]}],"events":[{"id":"StreamDispatcher#event:speaking","name":"speaking","description":"Emitted when the dispatcher starts/stops speaking","memberof":"StreamDispatcher","meta":{"line":43,"file":"StreamDispatcher.js","path":"src/client/voice/dispatcher"},"params":[{"name":"value","description":"Whether or not the dispatcher is speaking","type":{"types":[[["boolean",""]]]}}]},{"id":"StreamDispatcher#event:start","name":"start","description":"Emitted once the dispatcher starts streaming","memberof":"StreamDispatcher","meta":{"line":134,"file":"StreamDispatcher.js","path":"src/client/voice/dispatcher"},"params":[]},{"id":"StreamDispatcher#event:end","name":"end","description":"Emitted once the stream has ended. Attach a `once` listener to this.","memberof":"StreamDispatcher","meta":{"line":174,"file":"StreamDispatcher.js","path":"src/client/voice/dispatcher"},"params":[]},{"id":"StreamDispatcher#event:error","name":"error","description":"Emitted once the stream has encountered an error. Attach a `once` listener to this. Also emits `end`.","memberof":"StreamDispatcher","meta":{"line":182,"file":"StreamDispatcher.js","path":"src/client/voice/dispatcher"},"params":[{"name":"err","description":"The encountered error","type":{"types":[[["Error",""]]]}}]},{"id":"StreamDispatcher#event:debug","name":"debug","description":"Emitted when the stream wants to give debug information.","memberof":"StreamDispatcher","meta":{"line":195,"file":"StreamDispatcher.js","path":"src/client/voice/dispatcher"},"params":[{"name":"information","description":"The debug information","type":{"types":[[["string",""]]]}}]}]},{"id":"VoiceReceiver","name":"VoiceReceiver","description":"Receives voice data from a voice connection.\r```js\r// obtained using:\rvoiceChannel.join().then(connection => {\r const receiver = connection.createReceiver();\r});\r```","meta":{"line":18,"file":"VoiceReceiver.js","path":"src/client/voice/receiver"},"extends":["EventEmitter"],"methods":[{"id":"VoiceReceiver#recreate","name":"recreate","description":"If this VoiceReceiver has been destroyed, running `recreate()` will recreate the listener.\rThis avoids you having to create a new receiver.\rAny streams that you had prior to destroying the receiver will not be recreated.","memberof":"VoiceReceiver","meta":{"line":62,"file":"VoiceReceiver.js","path":"src/client/voice/receiver"},"returns":{"types":[[["null",""]]]},"params":[]},{"id":"VoiceReceiver#destroy","name":"destroy","description":"Destroy this VoiceReceiver, also ending any streams that it may be controlling.","memberof":"VoiceReceiver","meta":{"line":72,"file":"VoiceReceiver.js","path":"src/client/voice/receiver"},"returns":{"types":[[["null",""]]]},"params":[]},{"id":"VoiceReceiver#createOpusStream","name":"createOpusStream","description":"Creates a readable stream for a user that provides opus data while the user is speaking. When the user\rstops speaking, the stream is destroyed.","memberof":"VoiceReceiver","meta":{"line":91,"file":"VoiceReceiver.js","path":"src/client/voice/receiver"},"returns":{"types":[[["ReadableStream",""]]]},"params":[{"name":"user","description":"The user to create the stream for","type":{"types":[[["UserResolvable",""]]]}}]},{"id":"VoiceReceiver#createPCMStream","name":"createPCMStream","description":"Creates a readable stream for a user that provides PCM data while the user is speaking. When the user\rstops speaking, the stream is destroyed. The stream is 16-bit signed stereo PCM at 48KHz.","memberof":"VoiceReceiver","meta":{"line":106,"file":"VoiceReceiver.js","path":"src/client/voice/receiver"},"returns":{"types":[[["ReadableStream",""]]]},"params":[{"name":"user","description":"The user to create the stream for","type":{"types":[[["UserResolvable",""]]]}}]}],"properties":[{"id":"VoiceReceiver#destroyed","name":"destroyed","description":"Whether or not this receiver has been destroyed.","memberof":"VoiceReceiver","type":{"types":[[["boolean",""]]]},"meta":{"line":32,"file":"VoiceReceiver.js","path":"src/client/voice/receiver"},"props":[]},{"id":"VoiceReceiver#connection","name":"connection","description":"The VoiceConnection that instantiated this","memberof":"VoiceReceiver","type":{"types":[[["VoiceConnection",""]]]},"meta":{"line":37,"file":"VoiceReceiver.js","path":"src/client/voice/receiver"},"props":[]}],"events":[{"id":"VoiceReceiver#event:warn","name":"warn","description":"Emitted whenever a voice packet cannot be decrypted","memberof":"VoiceReceiver","meta":{"line":119,"file":"VoiceReceiver.js","path":"src/client/voice/receiver"},"params":[{"name":"message","description":"The warning message","type":{"types":[[["string",""]]]}}]},{"id":"VoiceReceiver#event:opus","name":"opus","description":"Emitted whenever voice data is received from the voice connection. This is _always_ emitted (unlike PCM).","memberof":"VoiceReceiver","meta":{"line":129,"file":"VoiceReceiver.js","path":"src/client/voice/receiver"},"params":[{"name":"user","description":"The user that is sending the buffer (is speaking)","type":{"types":[[["User",""]]]}},{"name":"buffer","description":"The opus buffer","type":{"types":[[["Buffer",""]]]}}]},{"id":"VoiceReceiver#event:pcm","name":"pcm","description":"Emits decoded voice data when it's received. For performance reasons, the decoding will only\rhappen if there is at least one `pcm` listener on this receiver.","memberof":"VoiceReceiver","meta":{"line":137,"file":"VoiceReceiver.js","path":"src/client/voice/receiver"},"params":[{"name":"user","description":"The user that is sending the buffer (is speaking)","type":{"types":[[["User",""]]]}},{"name":"buffer","description":"The decoded buffer","type":{"types":[[["Buffer",""]]]}}]}]},{"id":"VoiceConnection","name":"VoiceConnection","description":"Represents a connection to a Voice Channel in Discord.\r```js\r// obtained using:\rvoiceChannel.join().then(connection => {\r\r});\r```","meta":{"line":18,"file":"VoiceConnection.js","path":"src/client/voice"},"extends":["EventEmitter"],"methods":[{"id":"VoiceConnection#disconnect","name":"disconnect","description":"Disconnects the Client from the Voice Channel.","memberof":"VoiceConnection","meta":{"line":100,"file":"VoiceConnection.js","path":"src/client/voice"},"returns":{"types":[[["null",""]]]},"params":[{"name":"reason","description":"The reason of the disconnection","optional":true,"type":{"types":[[["string",""]]]}}]},{"id":"VoiceConnection#playFile","name":"playFile","description":"Play the given file in the voice connection.","memberof":"VoiceConnection","examples":["// play files natively\rvoiceChannel.join()\r .then(connection => {\r const dispatcher = connection.playFile('C:/Users/Discord/Desktop/music.mp3');\r })\r .catch(console.log);"],"meta":{"line":235,"file":"VoiceConnection.js","path":"src/client/voice"},"returns":{"types":[[["StreamDispatcher",""]]]},"params":[{"name":"file","description":"The path to the file","type":{"types":[[["string",""]]]}},{"name":"options","description":"Options for playing the stream","optional":true,"type":{"types":[[["StreamOptions",""]]]}}]},{"id":"VoiceConnection#playStream","name":"playStream","description":"Plays and converts an audio stream in the voice connection.","memberof":"VoiceConnection","examples":["// play streams using ytdl-core\rconst ytdl = require('ytdl-core');\rconst streamOptions = { seek: 0, volume: 1 };\rvoiceChannel.join()\r .then(connection => {\r const stream = ytdl('https://www.youtube.com/watch?v=XAWgeLF9EVQ', {filter : 'audioonly'});\r const dispatcher = connection.playStream(stream, streamOptions);\r })\r .catch(console.log);"],"meta":{"line":256,"file":"VoiceConnection.js","path":"src/client/voice"},"returns":{"types":[[["StreamDispatcher",""]]]},"params":[{"name":"stream","description":"The audio stream to play","type":{"types":[[["ReadableStream",""]]]}},{"name":"options","description":"Options for playing the stream","optional":true,"type":{"types":[[["StreamOptions",""]]]}}]},{"id":"VoiceConnection#playConvertedStream","name":"playConvertedStream","description":"Plays a stream of 16-bit signed stereo PCM at 48KHz.","memberof":"VoiceConnection","meta":{"line":267,"file":"VoiceConnection.js","path":"src/client/voice"},"returns":{"types":[[["StreamDispatcher",""]]]},"params":[{"name":"stream","description":"The audio stream to play.","type":{"types":[[["ReadableStream",""]]]}},{"name":"options","description":"Options for playing the stream","optional":true,"type":{"types":[[["StreamOptions",""]]]}}]},{"id":"VoiceConnection#createReceiver","name":"createReceiver","description":"Creates a VoiceReceiver so you can start listening to voice data. It's recommended to only create one of these.","memberof":"VoiceConnection","meta":{"line":277,"file":"VoiceConnection.js","path":"src/client/voice"},"returns":{"types":[[["VoiceReceiver",""]]]},"params":[]}],"properties":[{"id":"VoiceConnection#player","name":"player","description":"The player","memberof":"VoiceConnection","type":{"types":[[["BasePlayer",""]]]},"meta":{"line":33,"file":"VoiceConnection.js","path":"src/client/voice"},"props":[]},{"id":"VoiceConnection#endpoint","name":"endpoint","description":"The endpoint of the connection","memberof":"VoiceConnection","type":{"types":[[["string",""]]]},"meta":{"line":39,"file":"VoiceConnection.js","path":"src/client/voice"},"props":[]},{"id":"VoiceConnection#channel","name":"channel","description":"The VoiceChannel for this connection","memberof":"VoiceConnection","type":{"types":[[["VoiceChannel",""]]]},"meta":{"line":45,"file":"VoiceConnection.js","path":"src/client/voice"},"props":[]},{"id":"VoiceConnection#ready","name":"ready","description":"Whether or not the connection is ready","memberof":"VoiceConnection","type":{"types":[[["boolean",""]]]},"meta":{"line":58,"file":"VoiceConnection.js","path":"src/client/voice"},"props":[]}],"events":[{"id":"VoiceConnection#event:error","name":"error","description":"Emitted whenever the connection encounters a fatal error.","memberof":"VoiceConnection","meta":{"line":87,"file":"VoiceConnection.js","path":"src/client/voice"},"params":[{"name":"error","description":"The encountered error","type":{"types":[[["Error",""]]]}}]},{"id":"VoiceConnection#event:disconnected","name":"disconnected","description":"Emit once the voice connection has disconnected.","memberof":"VoiceConnection","meta":{"line":125,"file":"VoiceConnection.js","path":"src/client/voice"},"params":[{"name":"error","description":"The encountered error, if any","type":{"types":[[["Error",""]]]}}]},{"id":"VoiceConnection#event:ready","name":"ready","description":"Emitted once the connection is ready (joining voice channels resolves when the connection is ready anyway)","memberof":"VoiceConnection","meta":{"line":149,"file":"VoiceConnection.js","path":"src/client/voice"},"params":[]},{"id":"VoiceConnection#event:speaking","name":"speaking","description":"Emitted whenever a user starts/stops speaking","memberof":"VoiceConnection","meta":{"line":202,"file":"VoiceConnection.js","path":"src/client/voice"},"params":[{"name":"user","description":"The user that has started/stopped speaking","type":{"types":[[["User",""]]]}},{"name":"speaking","description":"Whether or not the user is speaking","type":{"types":[[["boolean",""]]]}}]}]},{"id":"Shard","name":"Shard","description":"Represents a Shard spawned by the ShardingManager.","meta":{"line":7,"file":"Shard.js","path":"src/sharding"},"classConstructor":{"id":"Shard()","name":"Shard","memberof":"Shard","params":[{"name":"manager","description":"The sharding manager","type":{"types":[[["ShardingManager",""]]]}},{"name":"id","description":"The ID of this shard","type":{"types":[[["number",""]]]}}]},"methods":[{"id":"Shard#send","name":"send","description":"Sends a message to the shard's process.","memberof":"Shard","meta":{"line":53,"file":"Shard.js","path":"src/sharding"},"returns":{"types":[[["Promise",".<"],["Shard",">"]]]},"params":[{"name":"message","description":"Message to send to the shard","type":{"types":[["*",""]]}}]},{"id":"Shard#eval","name":"eval","description":"Evaluates a script on the shard, in the context of the Client.","memberof":"Shard","meta":{"line":67,"file":"Shard.js","path":"src/sharding"},"returns":{"types":[[["Promise",".<*>"]]]},"params":[{"name":"script","description":"JavaScript to run on the shard","type":{"types":[[["string",""]]]}}]},{"id":"Shard#fetchClientValue","name":"fetchClientValue","description":"Fetches a Client property value of the shard.","memberof":"Shard","examples":["shard.fetchClientValue('guilds.size').then(count => {\r console.log(`${count} guilds in shard ${shard.id}`);\r}).catch(console.error);"],"meta":{"line":109,"file":"Shard.js","path":"src/sharding"},"returns":{"types":[[["Promise",".<*>"]]]},"params":[{"name":"prop","description":"Name of the Client property to get, using periods for nesting","type":{"types":[[["string",""]]]}}]}],"properties":[{"id":"Shard#manager","name":"manager","description":"The manager of the spawned shard","memberof":"Shard","type":{"types":[[["ShardingManager",""]]]},"meta":{"line":17,"file":"Shard.js","path":"src/sharding"},"props":[]},{"id":"Shard#id","name":"id","description":"The shard ID","memberof":"Shard","type":{"types":[[["number",""]]]},"meta":{"line":23,"file":"Shard.js","path":"src/sharding"},"props":[]},{"id":"Shard#process","name":"process","description":"The process of the shard","memberof":"Shard","type":{"types":[[["ChildProcess",""]]]},"meta":{"line":29,"file":"Shard.js","path":"src/sharding"},"props":[]}],"events":[]},{"id":"ShardingManager","name":"ShardingManager","description":"This is a utility class that can be used to help you spawn shards of your Client. Each shard is completely separate\rfrom the other. The Shard Manager takes a path to a file and spawns it under the specified amount of shards safely.\rThe Sharding Manager is still experimental","meta":{"line":14,"file":"ShardingManager.js","path":"src/sharding"},"extends":["EventEmitter"],"classConstructor":{"id":"ShardingManager()","name":"ShardingManager","memberof":"ShardingManager","params":[{"name":"file","description":"Path to your shard script file","type":{"types":[[["string",""]]]}},{"name":"totalShards","description":"Number of shards to default to spawning","optional":true,"type":{"types":[[["number",""]]]}},{"name":"respawn","description":"Respawn a shard when it dies","optional":true,"type":{"types":[[["boolean",""]]]}}]},"methods":[{"id":"ShardingManager#createShard","name":"createShard","description":"Spawns a single shard.","memberof":"ShardingManager","meta":{"line":58,"file":"ShardingManager.js","path":"src/sharding"},"returns":{"types":[[["Promise",".<"],["Shard",">"]]]},"params":[{"name":"id","description":"The ID of the shard to spawn. THIS IS NOT NEEDED IN ANY NORMAL CASE!","type":{"types":[[["number",""]]]}}]},{"id":"ShardingManager#spawn","name":"spawn","description":"Spawns multiple shards.","memberof":"ShardingManager","meta":{"line":76,"file":"ShardingManager.js","path":"src/sharding"},"returns":{"types":[[["Promise",".<"],["Collection",".<"],["number",", "],["Shard",">>"]]]},"params":[{"name":"amount","description":"Number of shards to spawn","optional":true,"type":{"types":[[["number",""]]]}},{"name":"delay","description":"How long to wait in between spawning each shard (in milliseconds)","optional":true,"type":{"types":[[["number",""]]]}}]},{"id":"ShardingManager#broadcast","name":"broadcast","description":"Send a message to all shards.","memberof":"ShardingManager","meta":{"line":111,"file":"ShardingManager.js","path":"src/sharding"},"returns":{"types":[[["Promise",".<"],["Array",".<"],["Shard",">>"]]]},"params":[{"name":"message","description":"Message to be sent to the shards","type":{"types":[["*",""]]}}]},{"id":"ShardingManager#broadcastEval","name":"broadcastEval","description":"Evaluates a script on all shards, in the context of the Clients.","memberof":"ShardingManager","meta":{"line":122,"file":"ShardingManager.js","path":"src/sharding"},"returns":{"types":[[["Promise",".<"],["Array",">"]]]},"params":[{"name":"script","description":"JavaScript to run on each shard","type":{"types":[[["string",""]]]}}]},{"id":"ShardingManager#fetchClientValues","name":"fetchClientValues","description":"Fetches a Client property value of each shard.","memberof":"ShardingManager","examples":["manager.fetchClientValues('guilds.size').then(results => {\r console.log(`${results.reduce((prev, val) => prev + val, 0)} total guilds`);\r}).catch(console.error);"],"meta":{"line":137,"file":"ShardingManager.js","path":"src/sharding"},"returns":{"types":[[["Promise",".<"],["Array",">"]]]},"params":[{"name":"prop","description":"Name of the Client property to get, using periods for nesting","type":{"types":[[["string",""]]]}}]}],"properties":[{"id":"ShardingManager#file","name":"file","description":"Path to the shard script file","memberof":"ShardingManager","type":{"types":[[["string",""]]]},"meta":{"line":27,"file":"ShardingManager.js","path":"src/sharding"},"props":[]},{"id":"ShardingManager#totalShards","name":"totalShards","description":"Amount of shards that this manager is going to spawn","memberof":"ShardingManager","type":{"types":[[["number",""]]]},"meta":{"line":37,"file":"ShardingManager.js","path":"src/sharding"},"props":[]},{"id":"ShardingManager#shards","name":"shards","description":"A collection of shards that this manager has spawned","memberof":"ShardingManager","type":{"types":[[["Collection",".<"],["number",", "],["Shard",">"]]]},"meta":{"line":50,"file":"ShardingManager.js","path":"src/sharding"},"props":[]}],"events":[{"id":"ShardingManager#event:launch","name":"launch","description":"Emitted upon launching a shard","memberof":"ShardingManager","meta":{"line":61,"file":"ShardingManager.js","path":"src/sharding"},"params":[{"name":"shard","description":"Shard that was launched","type":{"types":[[["Shard",""]]]}}]}]},{"id":"Channel","name":"Channel","description":"Represents any Channel on Discord","meta":{"line":4,"file":"Channel.js","path":"src/structures"},"methods":[{"id":"Channel#delete","name":"delete","description":"Deletes the channel","memberof":"Channel","examples":["// delete the channel\rchannel.delete()\r .then() // success\r .catch(console.log); // log error"],"meta":{"line":52,"file":"Channel.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Channel",">"]]]},"params":[]}],"properties":[{"id":"Channel#client","name":"client","description":"The client that instantiated the Channel","memberof":"Channel","type":{"types":[[["Client",""]]]},"meta":{"line":10,"file":"Channel.js","path":"src/structures"},"props":[]},{"id":"Channel#type","name":"type","description":"The type of the channel, either:\r* `dm` - a DM channel\r* `group` - a Group DM channel\r* `text` - a guild text channel\r* `voice` - a guild voice channel","memberof":"Channel","type":{"types":[[["string",""]]]},"meta":{"line":21,"file":"Channel.js","path":"src/structures"},"props":[]},{"id":"Channel#id","name":"id","description":"The unique ID of the channel","memberof":"Channel","type":{"types":[[["string",""]]]},"meta":{"line":31,"file":"Channel.js","path":"src/structures"},"props":[]},{"id":"Channel#creationDate","name":"creationDate","description":"The time the channel was created","memberof":"Channel","type":{"types":[[["Date",""]]]},"meta":{"line":39,"file":"Channel.js","path":"src/structures"},"props":[]}],"events":[]},{"id":"ClientUser","name":"ClientUser","description":"Represents the logged in client's Discord User","meta":{"line":7,"file":"ClientUser.js","path":"src/structures"},"extends":["User"],"methods":[{"id":"ClientUser#setUsername","name":"setUsername","description":"Set the username of the logged in Client.\rChanging usernames in Discord is heavily rate limited, with only 2 requests\revery hour. Use this sparingly!","memberof":"ClientUser","examples":["// set username\rclient.user.setUsername('discordjs')\r .then(user => console.log(`My new username is ${user.username}`))\r .catch(console.log);"],"meta":{"line":42,"file":"ClientUser.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["ClientUser",">"]]]},"params":[{"name":"username","description":"The new username","type":{"types":[[["string",""]]]}}]},{"id":"ClientUser#setEmail","name":"setEmail","description":"If this user is a \"self bot\" or logged in using a normal user's details (which should be avoided), you can set the\remail here.","memberof":"ClientUser","examples":["// set email\rclient.user.setEmail('bob@gmail.com')\r .then(user => console.log(`My new email is ${user.email}`))\r .catch(console.log);"],"meta":{"line":57,"file":"ClientUser.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["ClientUser",">"]]]},"params":[{"name":"email","description":"The new email","type":{"types":[[["string",""]]]}}]},{"id":"ClientUser#setPassword","name":"setPassword","description":"If this user is a \"self bot\" or logged in using a normal user's details (which should be avoided), you can set the\rpassword here.","memberof":"ClientUser","examples":["// set password\rclient.user.setPassword('password')\r .then(user => console.log('New password set!'))\r .catch(console.log);"],"meta":{"line":72,"file":"ClientUser.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["ClientUser",">"]]]},"params":[{"name":"password","description":"The new password","type":{"types":[[["string",""]]]}}]},{"id":"ClientUser#setAvatar","name":"setAvatar","description":"Set the avatar of the logged in Client.","memberof":"ClientUser","examples":["// set avatar\rclient.user.setAvatar(fs.readFileSync('./avatar.png'))\r .then(user => console.log(`New avatar set!`))\r .catch(console.log);"],"meta":{"line":86,"file":"ClientUser.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["ClientUser",">"]]]},"params":[{"name":"avatar","description":"The new avatar","type":{"types":[[["Base64Resolvable",""]]]}}]},{"id":"ClientUser#setStatus","name":"setStatus","description":"Set the status and playing game of the logged in client.","memberof":"ClientUser","examples":["// set status\rclient.user.setStatus('status', 'game')\r .then(user => console.log('Changed status!'))\r .catch(console.log);"],"meta":{"line":103,"file":"ClientUser.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["ClientUser",">"]]]},"params":[{"name":"status","description":"The status, can be `online` or `idle`","optional":true,"type":{"types":[[["string",""]]]}},{"name":"game","description":"The game that is being played","optional":true,"type":{"types":[[["string",""]],[["Object",""]]]}},{"name":"url","description":"If you want to display as streaming, set this as the URL to the stream (must be a\rtwitch.tv URl)","optional":true,"type":{"types":[[["string",""]]]}}]},{"id":"ClientUser#typingIn","name":"typingIn","description":"Check whether the user is typing in a channel.","memberof":"ClientUser","inherits":"User#typingIn","inherited":true,"meta":{"line":106,"file":"User.js","path":"src/structures"},"returns":{"types":[[["boolean",""]]]},"params":[{"name":"channel","description":"The channel to check in","type":{"types":[[["ChannelResolvable",""]]]}}]},{"id":"ClientUser#typingSinceIn","name":"typingSinceIn","description":"Get the time that the user started typing.","memberof":"ClientUser","inherits":"User#typingSinceIn","inherited":true,"meta":{"line":116,"file":"User.js","path":"src/structures"},"returns":{"types":[[["Date",""]]]},"params":[{"name":"channel","description":"The channel to get the time in","type":{"types":[[["ChannelResolvable",""]]]}}]},{"id":"ClientUser#typingDurationIn","name":"typingDurationIn","description":"Get the amount of time the user has been typing in a channel for (in milliseconds), or -1 if they're not typing.","memberof":"ClientUser","inherits":"User#typingDurationIn","inherited":true,"meta":{"line":126,"file":"User.js","path":"src/structures"},"returns":{"types":[[["number",""]]]},"params":[{"name":"channel","description":"The channel to get the time in","type":{"types":[[["ChannelResolvable",""]]]}}]},{"id":"ClientUser#deleteDM","name":"deleteDM","description":"Deletes a DM Channel (if one exists) between the Client and the User. Resolves with the Channel if successful.","memberof":"ClientUser","inherits":"User#deleteDM","inherited":true,"meta":{"line":135,"file":"User.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["DMChannel",">"]]]},"params":[]},{"id":"ClientUser#equals","name":"equals","description":"Checks if the user is equal to another. It compares username, ID, discriminator, status and the game being played.\rIt is recommended to compare equality by using `user.id === user2.id` unless you want to compare all properties.","memberof":"ClientUser","inherits":"User#equals","inherited":true,"meta":{"line":145,"file":"User.js","path":"src/structures"},"returns":{"types":[[["boolean",""]]]},"params":[{"name":"user","description":"The user to compare","type":{"types":[[["User",""]]]}}]},{"id":"ClientUser#toString","name":"toString","description":"When concatenated with a string, this automatically concatenates the User's mention instead of the User object.","memberof":"ClientUser","examples":["// logs: Hello from <@123456789>!\rconsole.log(`Hello from ${user}!`);"],"inherits":"User#toString","inherited":true,"meta":{"line":173,"file":"User.js","path":"src/structures"},"returns":{"types":[[["string",""]]]},"params":[]},{"id":"ClientUser#sendMessage","name":"sendMessage","description":"Send a message to this channel","memberof":"ClientUser","examples":["// send a message\rchannel.sendMessage('hello!')\r .then(message => console.log(`Sent message: ${message.content}`))\r .catch(console.log);"],"inherits":"User#sendMessage","inherited":true,"meta":{"line":56,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<("],["Message","|"],["Array",".<"],["Message",">)>"]]]},"params":[{"name":"content","description":"The content to send","type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","optional":true,"type":{"types":[[["MessageOptions",""]]]}}],"implements":["TextBasedChannel#sendMessage"]},{"id":"ClientUser#sendTTSMessage","name":"sendTTSMessage","description":"Send a text-to-speech message to this channel","memberof":"ClientUser","examples":["// send a TTS message\rchannel.sendTTSMessage('hello!')\r .then(message => console.log(`Sent tts message: ${message.content}`))\r .catch(console.log);"],"inherits":"User#sendTTSMessage","inherited":true,"meta":{"line":71,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<("],["Message","|"],["Array",".<"],["Message",">)>"]]]},"params":[{"name":"content","description":"The content to send","type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","optional":true,"type":{"types":[[["MessageOptions",""]]]}}],"implements":["TextBasedChannel#sendTTSMessage"]},{"id":"ClientUser#sendFile","name":"sendFile","description":"Send a file to this channel","memberof":"ClientUser","inherits":"User#sendFile","inherited":true,"meta":{"line":84,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<"],["Message",">"]]]},"params":[{"name":"attachment","description":"The file to send","type":{"types":[[["FileResolvable",""]]]}},{"name":"fileName","description":"The name and extension of the file","optional":true,"type":{"types":[[["string",""]]]}},{"name":"content","description":"Text message to send with the attachment","optional":true,"type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","optional":true,"type":{"types":[[["MessageOptions",""]]]}}],"implements":["TextBasedChannel#sendFile"]},{"id":"ClientUser#sendCode","name":"sendCode","description":"Send a code block to this channel","memberof":"ClientUser","inherits":"User#sendCode","inherited":true,"meta":{"line":111,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<("],["Message","|"],["Array",".<"],["Message",">)>"]]]},"params":[{"name":"lang","description":"Language for the code block","type":{"types":[[["string",""]]]}},{"name":"content","description":"Content of the code block","type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","type":{"types":[[["MessageOptions",""]]]}}],"implements":["TextBasedChannel#sendCode"]}],"properties":[{"id":"ClientUser#verified","name":"verified","description":"Whether or not this account has been verified","memberof":"ClientUser","type":{"types":[[["boolean",""]]]},"meta":{"line":15,"file":"ClientUser.js","path":"src/structures"},"props":[]},{"id":"ClientUser#email","name":"email","description":"The email of this account","memberof":"ClientUser","type":{"types":[[["string",""]]]},"meta":{"line":21,"file":"ClientUser.js","path":"src/structures"},"props":[]},{"id":"ClientUser#client","name":"client","description":"The Client that created the instance of the the User.","memberof":"ClientUser","type":{"types":[[["Client",""]]]},"meta":{"line":14,"file":"User.js","path":"src/structures"},"props":[]},{"id":"ClientUser#id","name":"id","description":"The ID of the User","memberof":"ClientUser","type":{"types":[[["string",""]]]},"meta":{"line":25,"file":"User.js","path":"src/structures"},"props":[]},{"id":"ClientUser#username","name":"username","description":"The username of the User","memberof":"ClientUser","type":{"types":[[["string",""]]]},"meta":{"line":31,"file":"User.js","path":"src/structures"},"props":[]},{"id":"ClientUser#discriminator","name":"discriminator","description":"A discriminator based on username for the User","memberof":"ClientUser","type":{"types":[[["string",""]]]},"meta":{"line":37,"file":"User.js","path":"src/structures"},"props":[]},{"id":"ClientUser#avatar","name":"avatar","description":"The ID of the user's avatar","memberof":"ClientUser","type":{"types":[[["string",""]]]},"meta":{"line":43,"file":"User.js","path":"src/structures"},"props":[]},{"id":"ClientUser#bot","name":"bot","description":"Whether or not the User is a Bot.","memberof":"ClientUser","type":{"types":[[["boolean",""]]]},"meta":{"line":49,"file":"User.js","path":"src/structures"},"props":[]},{"id":"ClientUser#status","name":"status","description":"The status of the user:\r\r* **`online`** - user is online\r* **`offline`** - user is offline\r* **`idle`** - user is AFK","memberof":"ClientUser","type":{"types":[[["string",""]]]},"meta":{"line":59,"file":"User.js","path":"src/structures"},"props":[]},{"id":"ClientUser#game","name":"game","description":"The game that the user is playing, `null` if they aren't playing a game.","memberof":"ClientUser","type":{"types":[[["Game",""]]]},"meta":{"line":73,"file":"User.js","path":"src/structures"},"props":[]},{"id":"ClientUser#creationDate","name":"creationDate","description":"The time the user was created","memberof":"ClientUser","type":{"types":[[["Date",""]]]},"meta":{"line":87,"file":"User.js","path":"src/structures"},"props":[]},{"id":"ClientUser#avatarURL","name":"avatarURL","description":"A link to the user's avatar (if they have one, otherwise null)","memberof":"ClientUser","type":{"types":[[["string",""]]]},"meta":{"line":96,"file":"User.js","path":"src/structures"},"props":[]}],"events":[]},{"id":"DMChannel","name":"DMChannel","description":"Represents a Direct Message Channel between two users.","meta":{"line":10,"file":"DMChannel.js","path":"src/structures"},"extends":["Channel"],"methods":[{"id":"DMChannel#toString","name":"toString","description":"When concatenated with a string, this automatically concatenates the recipient's mention instead of the\rDM channel object.","memberof":"DMChannel","meta":{"line":35,"file":"DMChannel.js","path":"src/structures"},"returns":{"types":[[["string",""]]]},"params":[]},{"id":"DMChannel#sendMessage","name":"sendMessage","description":"Send a message to this channel","memberof":"DMChannel","examples":["// send a message\rchannel.sendMessage('hello!')\r .then(message => console.log(`Sent message: ${message.content}`))\r .catch(console.log);"],"meta":{"line":56,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<("],["Message","|"],["Array",".<"],["Message",">)>"]]]},"params":[{"name":"content","description":"The content to send","type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","optional":true,"type":{"types":[[["MessageOptions",""]]]}}],"implements":["TextBasedChannel#sendMessage"]},{"id":"DMChannel#sendTTSMessage","name":"sendTTSMessage","description":"Send a text-to-speech message to this channel","memberof":"DMChannel","examples":["// send a TTS message\rchannel.sendTTSMessage('hello!')\r .then(message => console.log(`Sent tts message: ${message.content}`))\r .catch(console.log);"],"meta":{"line":71,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<("],["Message","|"],["Array",".<"],["Message",">)>"]]]},"params":[{"name":"content","description":"The content to send","type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","optional":true,"type":{"types":[[["MessageOptions",""]]]}}],"implements":["TextBasedChannel#sendTTSMessage"]},{"id":"DMChannel#sendFile","name":"sendFile","description":"Send a file to this channel","memberof":"DMChannel","meta":{"line":84,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<"],["Message",">"]]]},"params":[{"name":"attachment","description":"The file to send","type":{"types":[[["FileResolvable",""]]]}},{"name":"fileName","description":"The name and extension of the file","optional":true,"type":{"types":[[["string",""]]]}},{"name":"content","description":"Text message to send with the attachment","optional":true,"type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","optional":true,"type":{"types":[[["MessageOptions",""]]]}}],"implements":["TextBasedChannel#sendFile"]},{"id":"DMChannel#sendCode","name":"sendCode","description":"Send a code block to this channel","memberof":"DMChannel","meta":{"line":111,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<("],["Message","|"],["Array",".<"],["Message",">)>"]]]},"params":[{"name":"lang","description":"Language for the code block","type":{"types":[[["string",""]]]}},{"name":"content","description":"Content of the code block","type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","type":{"types":[[["MessageOptions",""]]]}}],"implements":["TextBasedChannel#sendCode"]},{"id":"DMChannel#fetchMessage","name":"fetchMessage","description":"Gets a single message from this channel, regardless of it being cached or not.","memberof":"DMChannel","examples":["// get message\rchannel.fetchMessage('99539446449315840')\r .then(message => console.log(message.content))\r .catch(console.error);"],"meta":{"line":131,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<"],["Message",">"]]]},"params":[{"name":"messageID","description":"The ID of the message to get","type":{"types":[[["string",""]]]}}],"implements":["TextBasedChannel#fetchMessage"]},{"id":"DMChannel#fetchMessages","name":"fetchMessages","description":"Gets the past messages sent in this channel. Resolves with a Collection mapping message ID's to Message objects.","memberof":"DMChannel","examples":["// get messages\rchannel.fetchMessages({limit: 10})\r .then(messages => console.log(`Received ${messages.size} messages`))\r .catch(console.log);"],"meta":{"line":163,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<"],["Collection",".<"],["string",", "],["Message",">>"]]]},"params":[{"name":"options","description":"The query parameters to pass in","optional":true,"type":{"types":[[["ChannelLogsQueryOptions",""]]]}}],"implements":["TextBasedChannel#fetchMessages"]},{"id":"DMChannel#fetchPinnedMessages","name":"fetchPinnedMessages","description":"Fetches the pinned messages of this Channel and returns a Collection of them.","memberof":"DMChannel","meta":{"line":181,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<"],["Collection",".<"],["string",", "],["Message",">>"]]]},"params":[],"implements":["TextBasedChannel#fetchPinnedMessages"]},{"id":"DMChannel#startTyping","name":"startTyping","description":"Starts a typing indicator in the channel.","memberof":"DMChannel","examples":["// start typing in a channel\rchannel.startTyping();"],"meta":{"line":202,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["null",""]]]},"params":[{"name":"count","description":"The number of times startTyping should be considered to have been called","optional":true,"type":{"types":[[["number",""]]]}}],"implements":["TextBasedChannel#startTyping"]},{"id":"DMChannel#stopTyping","name":"stopTyping","description":"Stops the typing indicator in the channel.\rThe indicator will only stop if this is called as many times as startTyping().\rIt can take a few seconds for the Client User to stop typing.","memberof":"DMChannel","examples":["// stop typing in a channel\rchannel.stopTyping();","// force typing to fully stop in a channel\rchannel.stopTyping(true);"],"meta":{"line":230,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["null",""]]]},"params":[{"name":"force","description":"Whether or not to reset the call count and force the indicator to stop","optional":true,"type":{"types":[[["boolean",""]]]}}],"implements":["TextBasedChannel#stopTyping"]},{"id":"DMChannel#createCollector","name":"createCollector","description":"Creates a Message Collector","memberof":"DMChannel","examples":["// create a message collector\rconst collector = channel.createCollector(\r m => m.content.includes('discord'),\r { time: 15000 }\r);\rcollector.on('message', m => console.log(`Collected ${m.content}`));\rcollector.on('end', collected => console.log(`Collected ${collected.size} items`));"],"meta":{"line":272,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["MessageCollector",""]]]},"params":[{"name":"filter","description":"The filter to create the collector with","type":{"types":[[["CollectorFilterFunction",""]]]}},{"name":"options","description":"The options to pass to the collector","optional":true,"type":{"types":[[["CollectorOptions",""]]]}}],"implements":["TextBasedChannel#createCollector"]},{"id":"DMChannel#awaitMessages","name":"awaitMessages","description":"Similar to createCollector but in Promise form. Resolves with a Collection of messages that pass the specified\rfilter.","memberof":"DMChannel","examples":["// await !vote messages\rconst filter = m => m.content.startsWith('!vote');\r// errors: ['time'] treats ending because of the time limit as an error\rchannel.awaitMessages(filter, { max: 4, time: 60000, errors: ['time'] })\r .then(collected => console.log(collected.size))\r .catch(collected => console.log(`After a minute, only ${collected.size} out of 4 voted.`));"],"meta":{"line":296,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<"],["Collection",".<"],["string",", "],["Message",">>"]]]},"params":[{"name":"filter","description":"The filter function to use","type":{"types":[[["CollectorFilterFunction",""]]]}},{"name":"options","description":"Optional options to pass to the internal collector","optional":true,"type":{"types":[[["AwaitMessagesOptions",""]]]}}],"implements":["TextBasedChannel#awaitMessages"]},{"id":"DMChannel#bulkDelete","name":"bulkDelete","description":"Bulk delete a given Collection or Array of messages in one go. Returns the deleted messages after.\rOnly OAuth Bot accounts may use this method.","memberof":"DMChannel","meta":{"line":315,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Collection",".<"],["string",", "],["Message",">"]]]},"params":[{"name":"messages","description":"The messages to delete","type":{"types":[[["Collection",".<"],["string",", "],["Message",">"]],[["Array",".<"],["Message",">"]]]}}],"implements":["TextBasedChannel#bulkDelete"]},{"id":"DMChannel#delete","name":"delete","description":"Deletes the channel","memberof":"DMChannel","examples":["// delete the channel\rchannel.delete()\r .then() // success\r .catch(console.log); // log error"],"inherits":"Channel#delete","inherited":true,"meta":{"line":52,"file":"Channel.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Channel",">"]]]},"params":[]}],"properties":[{"id":"DMChannel#recipient","name":"recipient","description":"The recipient on the other end of the DM","memberof":"DMChannel","type":{"types":[[["User",""]]]},"meta":{"line":25,"file":"DMChannel.js","path":"src/structures"},"props":[]},{"id":"DMChannel#messages","name":"messages","description":"A Collection containing the messages sent to this channel.","memberof":"DMChannel","type":{"types":[[["Collection",".<"],["string",", "],["Message",">"]]]},"meta":{"line":16,"file":"TextBasedChannel.js","path":"src/structures/interface"},"props":[]},{"id":"DMChannel#lastMessageID","name":"lastMessageID","description":"The ID of the last message in the channel, if one was sent.","memberof":"DMChannel","type":{"types":[[["string",""]]]},"meta":{"line":22,"file":"TextBasedChannel.js","path":"src/structures/interface"},"props":[]},{"id":"DMChannel#typing","name":"typing","description":"Whether or not the typing indicator is being shown in the channel.","memberof":"DMChannel","type":{"types":[[["boolean",""]]]},"meta":{"line":245,"file":"TextBasedChannel.js","path":"src/structures/interface"},"props":[]},{"id":"DMChannel#typingCount","name":"typingCount","description":"Number of times `startTyping` has been called.","memberof":"DMChannel","type":{"types":[[["number",""]]]},"meta":{"line":253,"file":"TextBasedChannel.js","path":"src/structures/interface"},"props":[]},{"id":"DMChannel#client","name":"client","description":"The client that instantiated the Channel","memberof":"DMChannel","type":{"types":[[["Client",""]]]},"meta":{"line":10,"file":"Channel.js","path":"src/structures"},"props":[]},{"id":"DMChannel#type","name":"type","description":"The type of the channel, either:\r* `dm` - a DM channel\r* `group` - a Group DM channel\r* `text` - a guild text channel\r* `voice` - a guild voice channel","memberof":"DMChannel","type":{"types":[[["string",""]]]},"meta":{"line":21,"file":"Channel.js","path":"src/structures"},"props":[]},{"id":"DMChannel#id","name":"id","description":"The unique ID of the channel","memberof":"DMChannel","type":{"types":[[["string",""]]]},"meta":{"line":31,"file":"Channel.js","path":"src/structures"},"props":[]},{"id":"DMChannel#creationDate","name":"creationDate","description":"The time the channel was created","memberof":"DMChannel","type":{"types":[[["Date",""]]]},"meta":{"line":39,"file":"Channel.js","path":"src/structures"},"props":[]}],"events":[]},{"id":"Emoji","name":"Emoji","description":"Represents a Custom Emoji","meta":{"line":7,"file":"Emoji.js","path":"src/structures"},"methods":[{"id":"Emoji#toString","name":"toString","description":"When concatenated with a string, this automatically returns the emoji mention rather than the object.","memberof":"Emoji","examples":["// send an emoji:\rconst emoji = guild.emojis.array()[0];\rmsg.reply(`Hello! ${emoji}`);"],"meta":{"line":92,"file":"Emoji.js","path":"src/structures"},"returns":{"types":[[["string",""]]]},"params":[]}],"properties":[{"id":"Emoji#client","name":"client","description":"The Client that instantiated this object","memberof":"Emoji","type":{"types":[[["Client",""]]]},"meta":{"line":13,"file":"Emoji.js","path":"src/structures"},"props":[]},{"id":"Emoji#guild","name":"guild","description":"The Guild this emoji is part of","memberof":"Emoji","type":{"types":[[["Guild",""]]]},"meta":{"line":20,"file":"Emoji.js","path":"src/structures"},"props":[]},{"id":"Emoji#id","name":"id","description":"The ID of the Emoji","memberof":"Emoji","type":{"types":[[["string",""]]]},"meta":{"line":30,"file":"Emoji.js","path":"src/structures"},"props":[]},{"id":"Emoji#name","name":"name","description":"The name of the Emoji","memberof":"Emoji","type":{"types":[[["string",""]]]},"meta":{"line":36,"file":"Emoji.js","path":"src/structures"},"props":[]},{"id":"Emoji#requiresColons","name":"requiresColons","description":"Whether or not this emoji requires colons surrounding it","memberof":"Emoji","type":{"types":[[["boolean",""]]]},"meta":{"line":42,"file":"Emoji.js","path":"src/structures"},"props":[]},{"id":"Emoji#managed","name":"managed","description":"Whether this emoji is managed by an external service","memberof":"Emoji","type":{"types":[[["boolean",""]]]},"meta":{"line":48,"file":"Emoji.js","path":"src/structures"},"props":[]},{"id":"Emoji#creationDate","name":"creationDate","description":"The time the emoji was created","memberof":"Emoji","type":{"types":[[["Date",""]]]},"meta":{"line":58,"file":"Emoji.js","path":"src/structures"},"props":[]},{"id":"Emoji#roles","name":"roles","description":"A collection of roles this emoji is active for (empty if all), mapped by role ID.","memberof":"Emoji","type":{"types":[[["Collection",".<"],["string",", "],["Role",">"]]]},"meta":{"line":67,"file":"Emoji.js","path":"src/structures"},"props":[]},{"id":"Emoji#url","name":"url","description":"The URL to the emoji file","memberof":"Emoji","type":{"types":[[["string",""]]]},"meta":{"line":80,"file":"Emoji.js","path":"src/structures"},"props":[]}],"events":[]},{"id":"EvaluatedPermissions","name":"EvaluatedPermissions","description":"The final evaluated permissions for a member in a channel","meta":{"line":6,"file":"EvaluatedPermissions.js","path":"src/structures"},"methods":[{"id":"EvaluatedPermissions#serialize","name":"serialize","description":"Get an object mapping permission name, e.g. `READ_MESSAGES` to a boolean - whether the user\rcan perform this or not.","memberof":"EvaluatedPermissions","meta":{"line":26,"file":"EvaluatedPermissions.js","path":"src/structures"},"returns":{"types":[[["Object",".<"],["string",", "],["boolean",">"]]]},"params":[]},{"id":"EvaluatedPermissions#hasPermission","name":"hasPermission","description":"Checks whether the user has a certain permission, e.g. `READ_MESSAGES`.","memberof":"EvaluatedPermissions","meta":{"line":40,"file":"EvaluatedPermissions.js","path":"src/structures"},"returns":{"types":[[["boolean",""]]]},"params":[{"name":"permission","description":"The permission to check for","type":{"types":[[["PermissionResolvable",""]]]}},{"name":"explicit","description":"Whether to require the user to explicitly have the exact permission","optional":true,"type":{"types":[[["boolean",""]]]}}]},{"id":"EvaluatedPermissions#hasPermissions","name":"hasPermissions","description":"Checks whether the user has all specified permissions.","memberof":"EvaluatedPermissions","meta":{"line":52,"file":"EvaluatedPermissions.js","path":"src/structures"},"returns":{"types":[[["boolean",""]]]},"params":[{"name":"permissions","description":"The permissions to check for","type":{"types":[[["Array",".<"],["PermissionResolvable",">"]]]}},{"name":"explicit","description":"Whether to require the user to explicitly have the exact permissions","optional":true,"type":{"types":[[["boolean",""]]]}}]}],"properties":[{"id":"EvaluatedPermissions#member","name":"member","description":"The member this permissions refer to","memberof":"EvaluatedPermissions","type":{"types":[[["GuildMember",""]]]},"meta":{"line":12,"file":"EvaluatedPermissions.js","path":"src/structures"},"props":[]},{"id":"EvaluatedPermissions#raw","name":"raw","description":"A number representing the packed permissions","memberof":"EvaluatedPermissions","type":{"types":[[["number",""]]]},"meta":{"line":18,"file":"EvaluatedPermissions.js","path":"src/structures"},"props":[]}],"events":[]},{"id":"GroupDMChannel","name":"GroupDMChannel","description":"Represents a Group DM on Discord","meta":{"line":33,"file":"GroupDMChannel.js","path":"src/structures"},"extends":["Channel"],"methods":[{"id":"GroupDMChannel#equals","name":"equals","description":"Whether this channel equals another channel. It compares all properties, so for most operations\rit is advisable to just compare `channel.id === channel2.id` as it is much faster and is often\rwhat most users need.","memberof":"GroupDMChannel","meta":{"line":95,"file":"GroupDMChannel.js","path":"src/structures"},"returns":{"types":[[["boolean",""]]]},"params":[{"name":"channel","description":"The channel to compare to","type":{"types":[[["GroupDMChannel",""]]]}}]},{"id":"GroupDMChannel#toString","name":"toString","description":"When concatenated with a string, this automatically concatenates the Channel's name instead of the Channel object.","memberof":"GroupDMChannel","examples":["// logs: Hello from My Group DM!\rconsole.log(`Hello from ${channel}!`);","// logs: Hello from My Group DM!\rconsole.log(`Hello from ' + channel + '!');"],"meta":{"line":121,"file":"GroupDMChannel.js","path":"src/structures"},"returns":{"types":[[["string",""]]]},"params":[]},{"id":"GroupDMChannel#sendMessage","name":"sendMessage","description":"Send a message to this channel","memberof":"GroupDMChannel","examples":["// send a message\rchannel.sendMessage('hello!')\r .then(message => console.log(`Sent message: ${message.content}`))\r .catch(console.log);"],"meta":{"line":56,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<("],["Message","|"],["Array",".<"],["Message",">)>"]]]},"params":[{"name":"content","description":"The content to send","type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","optional":true,"type":{"types":[[["MessageOptions",""]]]}}],"implements":["TextBasedChannel#sendMessage"]},{"id":"GroupDMChannel#sendTTSMessage","name":"sendTTSMessage","description":"Send a text-to-speech message to this channel","memberof":"GroupDMChannel","examples":["// send a TTS message\rchannel.sendTTSMessage('hello!')\r .then(message => console.log(`Sent tts message: ${message.content}`))\r .catch(console.log);"],"meta":{"line":71,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<("],["Message","|"],["Array",".<"],["Message",">)>"]]]},"params":[{"name":"content","description":"The content to send","type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","optional":true,"type":{"types":[[["MessageOptions",""]]]}}],"implements":["TextBasedChannel#sendTTSMessage"]},{"id":"GroupDMChannel#sendFile","name":"sendFile","description":"Send a file to this channel","memberof":"GroupDMChannel","meta":{"line":84,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<"],["Message",">"]]]},"params":[{"name":"attachment","description":"The file to send","type":{"types":[[["FileResolvable",""]]]}},{"name":"fileName","description":"The name and extension of the file","optional":true,"type":{"types":[[["string",""]]]}},{"name":"content","description":"Text message to send with the attachment","optional":true,"type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","optional":true,"type":{"types":[[["MessageOptions",""]]]}}],"implements":["TextBasedChannel#sendFile"]},{"id":"GroupDMChannel#sendCode","name":"sendCode","description":"Send a code block to this channel","memberof":"GroupDMChannel","meta":{"line":111,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<("],["Message","|"],["Array",".<"],["Message",">)>"]]]},"params":[{"name":"lang","description":"Language for the code block","type":{"types":[[["string",""]]]}},{"name":"content","description":"Content of the code block","type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","type":{"types":[[["MessageOptions",""]]]}}],"implements":["TextBasedChannel#sendCode"]},{"id":"GroupDMChannel#fetchMessage","name":"fetchMessage","description":"Gets a single message from this channel, regardless of it being cached or not.","memberof":"GroupDMChannel","examples":["// get message\rchannel.fetchMessage('99539446449315840')\r .then(message => console.log(message.content))\r .catch(console.error);"],"meta":{"line":131,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<"],["Message",">"]]]},"params":[{"name":"messageID","description":"The ID of the message to get","type":{"types":[[["string",""]]]}}],"implements":["TextBasedChannel#fetchMessage"]},{"id":"GroupDMChannel#fetchMessages","name":"fetchMessages","description":"Gets the past messages sent in this channel. Resolves with a Collection mapping message ID's to Message objects.","memberof":"GroupDMChannel","examples":["// get messages\rchannel.fetchMessages({limit: 10})\r .then(messages => console.log(`Received ${messages.size} messages`))\r .catch(console.log);"],"meta":{"line":163,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<"],["Collection",".<"],["string",", "],["Message",">>"]]]},"params":[{"name":"options","description":"The query parameters to pass in","optional":true,"type":{"types":[[["ChannelLogsQueryOptions",""]]]}}],"implements":["TextBasedChannel#fetchMessages"]},{"id":"GroupDMChannel#fetchPinnedMessages","name":"fetchPinnedMessages","description":"Fetches the pinned messages of this Channel and returns a Collection of them.","memberof":"GroupDMChannel","meta":{"line":181,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<"],["Collection",".<"],["string",", "],["Message",">>"]]]},"params":[],"implements":["TextBasedChannel#fetchPinnedMessages"]},{"id":"GroupDMChannel#startTyping","name":"startTyping","description":"Starts a typing indicator in the channel.","memberof":"GroupDMChannel","examples":["// start typing in a channel\rchannel.startTyping();"],"meta":{"line":202,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["null",""]]]},"params":[{"name":"count","description":"The number of times startTyping should be considered to have been called","optional":true,"type":{"types":[[["number",""]]]}}],"implements":["TextBasedChannel#startTyping"]},{"id":"GroupDMChannel#stopTyping","name":"stopTyping","description":"Stops the typing indicator in the channel.\rThe indicator will only stop if this is called as many times as startTyping().\rIt can take a few seconds for the Client User to stop typing.","memberof":"GroupDMChannel","examples":["// stop typing in a channel\rchannel.stopTyping();","// force typing to fully stop in a channel\rchannel.stopTyping(true);"],"meta":{"line":230,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["null",""]]]},"params":[{"name":"force","description":"Whether or not to reset the call count and force the indicator to stop","optional":true,"type":{"types":[[["boolean",""]]]}}],"implements":["TextBasedChannel#stopTyping"]},{"id":"GroupDMChannel#createCollector","name":"createCollector","description":"Creates a Message Collector","memberof":"GroupDMChannel","examples":["// create a message collector\rconst collector = channel.createCollector(\r m => m.content.includes('discord'),\r { time: 15000 }\r);\rcollector.on('message', m => console.log(`Collected ${m.content}`));\rcollector.on('end', collected => console.log(`Collected ${collected.size} items`));"],"meta":{"line":272,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["MessageCollector",""]]]},"params":[{"name":"filter","description":"The filter to create the collector with","type":{"types":[[["CollectorFilterFunction",""]]]}},{"name":"options","description":"The options to pass to the collector","optional":true,"type":{"types":[[["CollectorOptions",""]]]}}],"implements":["TextBasedChannel#createCollector"]},{"id":"GroupDMChannel#awaitMessages","name":"awaitMessages","description":"Similar to createCollector but in Promise form. Resolves with a Collection of messages that pass the specified\rfilter.","memberof":"GroupDMChannel","examples":["// await !vote messages\rconst filter = m => m.content.startsWith('!vote');\r// errors: ['time'] treats ending because of the time limit as an error\rchannel.awaitMessages(filter, { max: 4, time: 60000, errors: ['time'] })\r .then(collected => console.log(collected.size))\r .catch(collected => console.log(`After a minute, only ${collected.size} out of 4 voted.`));"],"meta":{"line":296,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<"],["Collection",".<"],["string",", "],["Message",">>"]]]},"params":[{"name":"filter","description":"The filter function to use","type":{"types":[[["CollectorFilterFunction",""]]]}},{"name":"options","description":"Optional options to pass to the internal collector","optional":true,"type":{"types":[[["AwaitMessagesOptions",""]]]}}],"implements":["TextBasedChannel#awaitMessages"]},{"id":"GroupDMChannel#bulkDelete","name":"bulkDelete","description":"Bulk delete a given Collection or Array of messages in one go. Returns the deleted messages after.\rOnly OAuth Bot accounts may use this method.","memberof":"GroupDMChannel","meta":{"line":315,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Collection",".<"],["string",", "],["Message",">"]]]},"params":[{"name":"messages","description":"The messages to delete","type":{"types":[[["Collection",".<"],["string",", "],["Message",">"]],[["Array",".<"],["Message",">"]]]}}],"implements":["TextBasedChannel#bulkDelete"]},{"id":"GroupDMChannel#delete","name":"delete","description":"Deletes the channel","memberof":"GroupDMChannel","examples":["// delete the channel\rchannel.delete()\r .then() // success\r .catch(console.log); // log error"],"inherits":"Channel#delete","inherited":true,"meta":{"line":52,"file":"Channel.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Channel",">"]]]},"params":[]}],"properties":[{"id":"GroupDMChannel#name","name":"name","description":"The name of this Group DM, can be null if one isn't set.","memberof":"GroupDMChannel","type":{"types":[[["string",""]]]},"meta":{"line":48,"file":"GroupDMChannel.js","path":"src/structures"},"props":[]},{"id":"GroupDMChannel#icon","name":"icon","description":"A hash of the Group DM icon.","memberof":"GroupDMChannel","type":{"types":[[["string",""]]]},"meta":{"line":54,"file":"GroupDMChannel.js","path":"src/structures"},"props":[]},{"id":"GroupDMChannel#ownerID","name":"ownerID","description":"The user ID of this Group DM's owner.","memberof":"GroupDMChannel","type":{"types":[[["string",""]]]},"meta":{"line":60,"file":"GroupDMChannel.js","path":"src/structures"},"props":[]},{"id":"GroupDMChannel#recipients","name":"recipients","description":"A collection of the recipients of this DM, mapped by their ID.","memberof":"GroupDMChannel","type":{"types":[[["Collection",".<"],["string",", "],["User",">"]]]},"meta":{"line":67,"file":"GroupDMChannel.js","path":"src/structures"},"props":[]},{"id":"GroupDMChannel#owner","name":"owner","description":"The owner of this Group DM.","memberof":"GroupDMChannel","type":{"types":[[["User",""]]]},"meta":{"line":84,"file":"GroupDMChannel.js","path":"src/structures"},"props":[]},{"id":"GroupDMChannel#messages","name":"messages","description":"A Collection containing the messages sent to this channel.","memberof":"GroupDMChannel","type":{"types":[[["Collection",".<"],["string",", "],["Message",">"]]]},"meta":{"line":16,"file":"TextBasedChannel.js","path":"src/structures/interface"},"props":[]},{"id":"GroupDMChannel#lastMessageID","name":"lastMessageID","description":"The ID of the last message in the channel, if one was sent.","memberof":"GroupDMChannel","type":{"types":[[["string",""]]]},"meta":{"line":22,"file":"TextBasedChannel.js","path":"src/structures/interface"},"props":[]},{"id":"GroupDMChannel#typing","name":"typing","description":"Whether or not the typing indicator is being shown in the channel.","memberof":"GroupDMChannel","type":{"types":[[["boolean",""]]]},"meta":{"line":245,"file":"TextBasedChannel.js","path":"src/structures/interface"},"props":[]},{"id":"GroupDMChannel#typingCount","name":"typingCount","description":"Number of times `startTyping` has been called.","memberof":"GroupDMChannel","type":{"types":[[["number",""]]]},"meta":{"line":253,"file":"TextBasedChannel.js","path":"src/structures/interface"},"props":[]},{"id":"GroupDMChannel#client","name":"client","description":"The client that instantiated the Channel","memberof":"GroupDMChannel","type":{"types":[[["Client",""]]]},"meta":{"line":10,"file":"Channel.js","path":"src/structures"},"props":[]},{"id":"GroupDMChannel#type","name":"type","description":"The type of the channel, either:\r* `dm` - a DM channel\r* `group` - a Group DM channel\r* `text` - a guild text channel\r* `voice` - a guild voice channel","memberof":"GroupDMChannel","type":{"types":[[["string",""]]]},"meta":{"line":21,"file":"Channel.js","path":"src/structures"},"props":[]},{"id":"GroupDMChannel#id","name":"id","description":"The unique ID of the channel","memberof":"GroupDMChannel","type":{"types":[[["string",""]]]},"meta":{"line":31,"file":"Channel.js","path":"src/structures"},"props":[]},{"id":"GroupDMChannel#creationDate","name":"creationDate","description":"The time the channel was created","memberof":"GroupDMChannel","type":{"types":[[["Date",""]]]},"meta":{"line":39,"file":"Channel.js","path":"src/structures"},"props":[]}],"events":[]},{"id":"Guild","name":"Guild","description":"Represents a Guild (or a Server) on Discord.\rIt's recommended to see if a guild is available before performing operations or reading data from it. You can\rcheck this with `guild.available`.","meta":{"line":15,"file":"Guild.js","path":"src/structures"},"methods":[{"id":"Guild#member","name":"member","description":"Returns the GuildMember form of a User object, if the User is present in the guild.","memberof":"Guild","examples":["// get the guild member of a user\rconst member = guild.member(message.author);"],"meta":{"line":261,"file":"Guild.js","path":"src/structures"},"returns":{"types":[[["GuildMember",""]]]},"params":[{"name":"user","description":"The user that you want to obtain the GuildMember of","type":{"types":[[["UserResolvable",""]]]}}]},{"id":"Guild#fetchBans","name":"fetchBans","description":"Fetch a Collection of banned users in this Guild.","memberof":"Guild","meta":{"line":269,"file":"Guild.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Collection",".<"],["string",", "],["User",">>"]]]},"params":[]},{"id":"Guild#fetchInvites","name":"fetchInvites","description":"Fetch a Collection of invites to this Guild. Resolves with a Collection mapping invites by their codes.","memberof":"Guild","meta":{"line":277,"file":"Guild.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Collection",".<"],["string",", "],["Invite",">>"]]]},"params":[]},{"id":"Guild#fetchMember","name":"fetchMember","description":"Fetch a single guild member from a user.","memberof":"Guild","meta":{"line":286,"file":"Guild.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["GuildMember",">"]]]},"params":[{"name":"user","description":"The user to fetch the member for","type":{"types":[[["UserResolvable",""]]]}}]},{"id":"Guild#fetchMembers","name":"fetchMembers","description":"Fetches all the members in the Guild, even if they are offline. If the Guild has less than 250 members,\rthis should not be necessary.","memberof":"Guild","meta":{"line":300,"file":"Guild.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Guild",">"]]]},"params":[{"name":"query","description":"An optional query to provide when fetching members","optional":true,"type":{"types":[[["string",""]]]}}]},{"id":"Guild#edit","name":"edit","description":"Updates the Guild with new information - e.g. a new name.","memberof":"Guild","examples":["// set the guild name and region\rguild.edit({\r name: 'Discord Guild',\r region: 'london',\r})\r.then(updated => console.log(`New guild name ${updated.name} in region ${updated.region}`))\r.catch(console.log);"],"meta":{"line":334,"file":"Guild.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Guild",">"]]]},"params":[{"name":"data","description":"The data to update the guild with","type":{"types":[[["GuildEditData",""]]]}}]},{"id":"Guild#setName","name":"setName","description":"Edit the name of the Guild.","memberof":"Guild","examples":["// edit the guild name\rguild.setName('Discord Guild')\r .then(updated => console.log(`Updated guild name to ${guild.name}`))\r .catch(console.log);"],"meta":{"line":348,"file":"Guild.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Guild",">"]]]},"params":[{"name":"name","description":"The new name of the Guild","type":{"types":[[["string",""]]]}}]},{"id":"Guild#setRegion","name":"setRegion","description":"Edit the region of the Guild.","memberof":"Guild","examples":["// edit the guild region\rguild.setRegion('london')\r .then(updated => console.log(`Updated guild region to ${guild.region}`))\r .catch(console.log);"],"meta":{"line":362,"file":"Guild.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Guild",">"]]]},"params":[{"name":"region","description":"The new region of the guild.","type":{"types":[[["Region",""]]]}}]},{"id":"Guild#setVerificationLevel","name":"setVerificationLevel","description":"Edit the verification level of the Guild.","memberof":"Guild","examples":["// edit the guild verification level\rguild.setVerificationLevel(1)\r .then(updated => console.log(`Updated guild verification level to ${guild.verificationLevel}`))\r .catch(console.log);"],"meta":{"line":376,"file":"Guild.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Guild",">"]]]},"params":[{"name":"verificationLevel","description":"The new verification level of the guild","type":{"types":[[["VerificationLevel",""]]]}}]},{"id":"Guild#setAFKChannel","name":"setAFKChannel","description":"Edit the AFK channel of the Guild.","memberof":"Guild","examples":["// edit the guild AFK channel\rguild.setAFKChannel(channel)\r .then(updated => console.log(`Updated guild AFK channel to ${guild.afkChannel}`))\r .catch(console.log);"],"meta":{"line":390,"file":"Guild.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Guild",">"]]]},"params":[{"name":"afkChannel","description":"The new AFK channel","type":{"types":[[["GuildChannelResolvable",""]]]}}]},{"id":"Guild#setAFKTimeout","name":"setAFKTimeout","description":"Edit the AFK timeout of the Guild.","memberof":"Guild","examples":["// edit the guild AFK channel\rguild.setAFKTimeout(60)\r .then(updated => console.log(`Updated guild AFK timeout to ${guild.afkTimeout}`))\r .catch(console.log);"],"meta":{"line":404,"file":"Guild.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Guild",">"]]]},"params":[{"name":"afkTimeout","description":"The time in seconds that a user must be idle to be considered AFK","type":{"types":[[["number",""]]]}}]},{"id":"Guild#setIcon","name":"setIcon","description":"Set a new Guild Icon.","memberof":"Guild","examples":["// edit the guild icon\rguild.setIcon(fs.readFileSync('./icon.png'))\r .then(updated => console.log('Updated the guild icon'))\r .catch(console.log);"],"meta":{"line":418,"file":"Guild.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Guild",">"]]]},"params":[{"name":"icon","description":"The new icon of the guild","type":{"types":[[["Base64Resolvable",""]]]}}]},{"id":"Guild#setOwner","name":"setOwner","description":"Sets a new owner of the Guild.","memberof":"Guild","examples":["// edit the guild owner\rguild.setOwner(guilds.members[0])\r .then(updated => console.log(`Updated the guild owner to ${updated.owner.username}`))\r .catch(console.log);"],"meta":{"line":432,"file":"Guild.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Guild",">"]]]},"params":[{"name":"owner","description":"The new owner of the Guild","type":{"types":[[["GuildMemberResolvable",""]]]}}]},{"id":"Guild#setSplash","name":"setSplash","description":"Set a new Guild Splash Logo.","memberof":"Guild","examples":["// edit the guild splash\rguild.setIcon(fs.readFileSync('./splash.png'))\r .then(updated => console.log('Updated the guild splash'))\r .catch(console.log);"],"meta":{"line":446,"file":"Guild.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Guild",">"]]]},"params":[{"name":"splash","description":"The new splash screen of the guild","type":{"types":[[["Base64Resolvable",""]]]}}]},{"id":"Guild#ban","name":"ban","description":"Bans a user from the guild.","memberof":"Guild","examples":["// ban a user\rguild.ban('123123123123');"],"meta":{"line":462,"file":"Guild.js","path":"src/structures"},"returns":{"types":[[["Promise",".<("],["GuildMember","|"],["User","|"],["string",")>"]]]},"params":[{"name":"user","description":"The user to ban","type":{"types":[[["UserResolvable",""]]]}},{"name":"deleteDays","description":"The amount of days worth of messages from this user that should\ralso be deleted. Between `0` and `7`.","optional":true,"type":{"types":[[["number",""]]]}}]},{"id":"Guild#unban","name":"unban","description":"Unbans a user from the Guild.","memberof":"Guild","examples":["// unban a user\rguild.unban('123123123123')\r .then(user => console.log(`Unbanned ${user.username} from ${guild.name}`))\r .catch(reject);"],"meta":{"line":476,"file":"Guild.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["User",">"]]]},"params":[{"name":"user","description":"The user to unban","type":{"types":[[["UserResolvable",""]]]}}]},{"id":"Guild#pruneMembers","name":"pruneMembers","description":"Prunes members from the guild based on how long they have been inactive.","memberof":"Guild","examples":["// see how many members will be pruned\rguild.pruneMembers(12, true)\r .then(pruned => console.log(`This will prune ${pruned} people!`);\r .catch(console.error);","// actually prune the members\rguild.pruneMembers(12)\r .then(pruned => console.log(`I just pruned ${pruned} people!`);\r .catch(console.error);"],"meta":{"line":496,"file":"Guild.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["number",">"]]]},"params":[{"name":"days","description":"Number of days of inactivity required to kick","type":{"types":[[["number",""]]]}},{"name":"dry","description":"If true, will return number of users that will be kicked, without actually doing it","optional":true,"type":{"types":[[["boolean",""]]]}}]},{"id":"Guild#sync","name":"sync","description":"Syncs this guild (already done automatically every 30 seconds). Only applicable to user accounts.","memberof":"Guild","meta":{"line":504,"file":"Guild.js","path":"src/structures"},"returns":{"types":[[["null",""]]]},"params":[]},{"id":"Guild#createChannel","name":"createChannel","description":"Creates a new Channel in the Guild.","memberof":"Guild","examples":["// create a new text channel\rguild.createChannel('new-general', 'text')\r .then(channel => console.log(`Created new channel ${channel}`))\r .catch(console.log);"],"meta":{"line":519,"file":"Guild.js","path":"src/structures"},"returns":{"types":[[["Promise",".<("],["TextChannel","|"],["VoiceChannel",")>"]]]},"params":[{"name":"name","description":"The name of the new channel","type":{"types":[[["string",""]]]}},{"name":"type","description":"The type of the new channel, either `text` or `voice`","type":{"types":[[["string",""]]]}}]},{"id":"Guild#createRole","name":"createRole","description":"Creates a new role in the guild, and optionally updates it with the given information.","memberof":"Guild","examples":["// create a new role\rguild.createRole()\r .then(role => console.log(`Created role ${role}`))\r .catch(console.log);","// create a new role with data\rguild.createRole({ name: 'Super Cool People' })\r .then(role => console.log(`Created role ${role}`))\r .catch(console.log)"],"meta":{"line":538,"file":"Guild.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Role",">"]]]},"params":[{"name":"data","description":"The data to update the role with","optional":true,"type":{"types":[[["RoleData",""]]]}}]},{"id":"Guild#leave","name":"leave","description":"Causes the Client to leave the guild.","memberof":"Guild","examples":["// leave a guild\rguild.leave()\r .then(g => console.log(`Left the guild ${g}`))\r .catch(console.log);"],"meta":{"line":553,"file":"Guild.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Guild",">"]]]},"params":[]},{"id":"Guild#delete","name":"delete","description":"Causes the Client to delete the guild.","memberof":"Guild","examples":["// delete a guild\rguild.delete()\r .then(g => console.log(`Deleted the guild ${g}`))\r .catch(console.log);"],"meta":{"line":566,"file":"Guild.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Guild",">"]]]},"params":[]},{"id":"Guild#equals","name":"equals","description":"Whether this Guild equals another Guild. It compares all properties, so for most operations\rit is advisable to just compare `guild.id === guild2.id` as it is much faster and is often\rwhat most users need.","memberof":"Guild","meta":{"line":577,"file":"Guild.js","path":"src/structures"},"returns":{"types":[[["boolean",""]]]},"params":[{"name":"guild","description":"The guild to compare","type":{"types":[[["Guild",""]]]}}]},{"id":"Guild#toString","name":"toString","description":"When concatenated with a string, this automatically concatenates the Guild's name instead of the Guild object.","memberof":"Guild","examples":["// logs: Hello from My Guild!\rconsole.log(`Hello from ${guild}!`);","// logs: Hello from My Guild!\rconsole.log(`Hello from ' + guild + '!');"],"meta":{"line":614,"file":"Guild.js","path":"src/structures"},"returns":{"types":[[["string",""]]]},"params":[]}],"properties":[{"id":"Guild#client","name":"client","description":"The Client that created the instance of the the Guild.","memberof":"Guild","type":{"types":[[["Client",""]]]},"meta":{"line":21,"file":"Guild.js","path":"src/structures"},"props":[]},{"id":"Guild#members","name":"members","description":"A Collection of members that are in this Guild. The key is the member's ID, the value is the member.","memberof":"Guild","type":{"types":[[["Collection",".<"],["string",", "],["GuildMember",">"]]]},"meta":{"line":28,"file":"Guild.js","path":"src/structures"},"props":[]},{"id":"Guild#channels","name":"channels","description":"A Collection of channels that are in this Guild. The key is the channel's ID, the value is the channel.","memberof":"Guild","type":{"types":[[["Collection",".<"],["string",", "],["GuildChannel",">"]]]},"meta":{"line":34,"file":"Guild.js","path":"src/structures"},"props":[]},{"id":"Guild#roles","name":"roles","description":"A Collection of roles that are in this Guild. The key is the role's ID, the value is the role.","memberof":"Guild","type":{"types":[[["Collection",".<"],["string",", "],["Role",">"]]]},"meta":{"line":40,"file":"Guild.js","path":"src/structures"},"props":[]},{"id":"Guild#available","name":"available","description":"Whether the Guild is available to access. If it is not available, it indicates a server outage.","memberof":"Guild","type":{"types":[[["boolean",""]]]},"meta":{"line":48,"file":"Guild.js","path":"src/structures"},"props":[]},{"id":"Guild#id","name":"id","description":"The Unique ID of the Guild, useful for comparisons.","memberof":"Guild","type":{"types":[[["string",""]]]},"meta":{"line":54,"file":"Guild.js","path":"src/structures"},"props":[]},{"id":"Guild#name","name":"name","description":"The name of the guild","memberof":"Guild","type":{"types":[[["string",""]]]},"meta":{"line":71,"file":"Guild.js","path":"src/structures"},"props":[]},{"id":"Guild#icon","name":"icon","description":"The hash of the guild icon, or null if there is no icon.","memberof":"Guild","type":{"types":[[["string",""]]]},"meta":{"line":77,"file":"Guild.js","path":"src/structures"},"props":[]},{"id":"Guild#splash","name":"splash","description":"The hash of the guild splash image, or null if no splash (VIP only)","memberof":"Guild","type":{"types":[[["string",""]]]},"meta":{"line":83,"file":"Guild.js","path":"src/structures"},"props":[]},{"id":"Guild#region","name":"region","description":"The region the guild is located in","memberof":"Guild","type":{"types":[[["string",""]]]},"meta":{"line":89,"file":"Guild.js","path":"src/structures"},"props":[]},{"id":"Guild#memberCount","name":"memberCount","description":"The full amount of members in this Guild as of `READY`","memberof":"Guild","type":{"types":[[["number",""]]]},"meta":{"line":95,"file":"Guild.js","path":"src/structures"},"props":[]},{"id":"Guild#large","name":"large","description":"Whether the guild is \"large\" (has more than 250 members)","memberof":"Guild","type":{"types":[[["boolean",""]]]},"meta":{"line":101,"file":"Guild.js","path":"src/structures"},"props":[]},{"id":"Guild#features","name":"features","description":"An array of guild features.","memberof":"Guild","type":{"types":[[["Array",".<"],["Object",">"]]]},"meta":{"line":107,"file":"Guild.js","path":"src/structures"},"props":[]},{"id":"Guild#emojis","name":"emojis","description":"A Collection of emojis that are in this Guild. The key is the emoji's ID, the value is the emoji.","memberof":"Guild","type":{"types":[[["Collection",".<"],["string",", "],["Emoji",">"]]]},"meta":{"line":113,"file":"Guild.js","path":"src/structures"},"props":[]},{"id":"Guild#afkTimeout","name":"afkTimeout","description":"The time in seconds before a user is counted as \"away from keyboard\".","memberof":"Guild","type":{"types":[[["number",""]]]},"meta":{"line":120,"file":"Guild.js","path":"src/structures"},"props":[]},{"id":"Guild#afkChannelID","name":"afkChannelID","description":"The ID of the voice channel where AFK members are moved.","memberof":"Guild","type":{"types":[[["string",""]]]},"meta":{"line":126,"file":"Guild.js","path":"src/structures"},"props":[]},{"id":"Guild#embedEnabled","name":"embedEnabled","description":"Whether embedded images are enabled on this guild.","memberof":"Guild","type":{"types":[[["boolean",""]]]},"meta":{"line":132,"file":"Guild.js","path":"src/structures"},"props":[]},{"id":"Guild#verificationLevel","name":"verificationLevel","description":"The verification level of the guild.","memberof":"Guild","type":{"types":[[["number",""]]]},"meta":{"line":138,"file":"Guild.js","path":"src/structures"},"props":[]},{"id":"Guild#ownerID","name":"ownerID","description":"The user ID of this guild's owner.","memberof":"Guild","type":{"types":[[["string",""]]]},"meta":{"line":155,"file":"Guild.js","path":"src/structures"},"props":[]},{"id":"Guild#creationDate","name":"creationDate","description":"The time the guild was created","memberof":"Guild","type":{"types":[[["Date",""]]]},"meta":{"line":204,"file":"Guild.js","path":"src/structures"},"props":[]},{"id":"Guild#joinDate","name":"joinDate","description":"The date at which the logged-in client joined the guild.","memberof":"Guild","type":{"types":[[["Date",""]]]},"meta":{"line":212,"file":"Guild.js","path":"src/structures"},"props":[]},{"id":"Guild#iconURL","name":"iconURL","description":"Gets the URL to this guild's icon (if it has one, otherwise it returns null)","memberof":"Guild","type":{"types":[[["string",""]]]},"meta":{"line":221,"file":"Guild.js","path":"src/structures"},"props":[]},{"id":"Guild#owner","name":"owner","description":"The owner of the Guild","memberof":"Guild","type":{"types":[[["GuildMember",""]]]},"meta":{"line":231,"file":"Guild.js","path":"src/structures"},"props":[]},{"id":"Guild#voiceConnection","name":"voiceConnection","description":"If the client is connected to any voice channel in this guild, this will be the relevant VoiceConnection.","memberof":"Guild","type":{"types":[[["VoiceConnection",""]]]},"meta":{"line":240,"file":"Guild.js","path":"src/structures"},"props":[]},{"id":"Guild#defaultChannel","name":"defaultChannel","description":"The `#general` GuildChannel of the server.","memberof":"Guild","type":{"types":[[["GuildChannel",""]]]},"meta":{"line":249,"file":"Guild.js","path":"src/structures"},"props":[]}],"events":[]},{"id":"GuildChannel","name":"GuildChannel","description":"Represents a Guild Channel (i.e. Text Channels and Voice Channels)","meta":{"line":13,"file":"GuildChannel.js","path":"src/structures"},"extends":["Channel"],"methods":[{"id":"GuildChannel#permissionsFor","name":"permissionsFor","description":"Gets the overall set of permissions for a user in this channel, taking into account roles and permission\roverwrites.","memberof":"GuildChannel","meta":{"line":57,"file":"GuildChannel.js","path":"src/structures"},"returns":{"types":[[["EvaluatedPermissions",""]]]},"params":[{"name":"member","description":"The user that you want to obtain the overall permissions for","type":{"types":[[["GuildMemberResolvable",""]]]}}]},{"id":"GuildChannel#overwritePermissions","name":"overwritePermissions","description":"Overwrites the permissions for a user or role in this channel.","memberof":"GuildChannel","examples":["// overwrite permissions for a message author\rmessage.channel.overwritePermissions(message.author, {\r SEND_MESSAGES: false\r})\r.then(() => console.log('Done!'))\r.catch(console.log);"],"meta":{"line":125,"file":"GuildChannel.js","path":"src/structures"},"returns":{"types":[[["Promise",""]]]},"params":[{"name":"userOrRole","description":"The user or role to update","type":{"types":[[["Role",""]],[["UserResolvable",""]]]}},{"name":"options","description":"The configuration for the update","type":{"types":[[["PermissionOverwriteOptions",""]]]}}]},{"id":"GuildChannel#setName","name":"setName","description":"Set a new name for the Guild Channel","memberof":"GuildChannel","examples":["// set a new channel name\rchannel.setName('not_general')\r .then(newChannel => console.log(`Channel's new name is ${newChannel.name}`))\r .catch(console.log);"],"meta":{"line":175,"file":"GuildChannel.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["GuildChannel",">"]]]},"params":[{"name":"name","description":"The new name for the guild channel","type":{"types":[[["string",""]]]}}]},{"id":"GuildChannel#setPosition","name":"setPosition","description":"Set a new position for the Guild Channel","memberof":"GuildChannel","examples":["// set a new channel position\rchannel.setPosition(2)\r .then(newChannel => console.log(`Channel's new position is ${newChannel.position}`))\r .catch(console.log);"],"meta":{"line":189,"file":"GuildChannel.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["GuildChannel",">"]]]},"params":[{"name":"position","description":"The new position for the guild channel","type":{"types":[[["number",""]]]}}]},{"id":"GuildChannel#setTopic","name":"setTopic","description":"Set a new topic for the Guild Channel","memberof":"GuildChannel","examples":["// set a new channel topic\rchannel.setTopic('needs more rate limiting')\r .then(newChannel => console.log(`Channel's new topic is ${newChannel.topic}`))\r .catch(console.log);"],"meta":{"line":203,"file":"GuildChannel.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["GuildChannel",">"]]]},"params":[{"name":"topic","description":"The new topic for the guild channel","type":{"types":[[["string",""]]]}}]},{"id":"GuildChannel#createInvite","name":"createInvite","description":"Create an invite to this Guild Channel","memberof":"GuildChannel","meta":{"line":220,"file":"GuildChannel.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Invite",">"]]]},"params":[{"name":"options","description":"The options for the invite","optional":true,"type":{"types":[[["InviteOptions",""]]]}}]},{"id":"GuildChannel#equals","name":"equals","description":"Checks if this channel has the same type, topic, position, name, overwrites and ID as another channel.\rIn most cases, a simple `channel.id === channel2.id` will do, and is much faster too.","memberof":"GuildChannel","meta":{"line":230,"file":"GuildChannel.js","path":"src/structures"},"returns":{"types":[[["boolean",""]]]},"params":[{"name":"channel","description":"The channel to compare this channel to","type":{"types":[[["GuildChannel",""]]]}}]},{"id":"GuildChannel#toString","name":"toString","description":"When concatenated with a string, this automatically returns the Channel's mention instead of the Channel object.","memberof":"GuildChannel","examples":["// Outputs: Hello from #general\rconsole.log(`Hello from ${channel}`);","// Outputs: Hello from #general\rconsole.log('Hello from ' + channel);"],"meta":{"line":261,"file":"GuildChannel.js","path":"src/structures"},"returns":{"types":[[["string",""]]]},"params":[]},{"id":"GuildChannel#delete","name":"delete","description":"Deletes the channel","memberof":"GuildChannel","examples":["// delete the channel\rchannel.delete()\r .then() // success\r .catch(console.log); // log error"],"inherits":"Channel#delete","inherited":true,"meta":{"line":52,"file":"Channel.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Channel",">"]]]},"params":[]}],"properties":[{"id":"GuildChannel#guild","name":"guild","description":"The guild the channel is in","memberof":"GuildChannel","type":{"types":[[["Guild",""]]]},"meta":{"line":21,"file":"GuildChannel.js","path":"src/structures"},"props":[]},{"id":"GuildChannel#name","name":"name","description":"The name of the Guild Channel","memberof":"GuildChannel","type":{"types":[[["string",""]]]},"meta":{"line":31,"file":"GuildChannel.js","path":"src/structures"},"props":[]},{"id":"GuildChannel#position","name":"position","description":"The position of the channel in the list.","memberof":"GuildChannel","type":{"types":[[["number",""]]]},"meta":{"line":37,"file":"GuildChannel.js","path":"src/structures"},"props":[]},{"id":"GuildChannel#permissionOverwrites","name":"permissionOverwrites","description":"A map of permission overwrites in this channel for roles and users.","memberof":"GuildChannel","type":{"types":[[["Collection",".<"],["string",", "],["PermissionOverwrites",">"]]]},"meta":{"line":43,"file":"GuildChannel.js","path":"src/structures"},"props":[]},{"id":"GuildChannel#client","name":"client","description":"The client that instantiated the Channel","memberof":"GuildChannel","type":{"types":[[["Client",""]]]},"meta":{"line":10,"file":"Channel.js","path":"src/structures"},"props":[]},{"id":"GuildChannel#type","name":"type","description":"The type of the channel, either:\r* `dm` - a DM channel\r* `group` - a Group DM channel\r* `text` - a guild text channel\r* `voice` - a guild voice channel","memberof":"GuildChannel","type":{"types":[[["string",""]]]},"meta":{"line":21,"file":"Channel.js","path":"src/structures"},"props":[]},{"id":"GuildChannel#id","name":"id","description":"The unique ID of the channel","memberof":"GuildChannel","type":{"types":[[["string",""]]]},"meta":{"line":31,"file":"Channel.js","path":"src/structures"},"props":[]},{"id":"GuildChannel#creationDate","name":"creationDate","description":"The time the channel was created","memberof":"GuildChannel","type":{"types":[[["Date",""]]]},"meta":{"line":39,"file":"Channel.js","path":"src/structures"},"props":[]}],"events":[]},{"id":"GuildMember","name":"GuildMember","description":"Represents a Member of a Guild on Discord","meta":{"line":11,"file":"GuildMember.js","path":"src/structures"},"methods":[{"id":"GuildMember#permissionsIn","name":"permissionsIn","description":"Returns `channel.permissionsFor(guildMember)`. Returns evaluated permissions for a member in a guild channel.","memberof":"GuildMember","meta":{"line":209,"file":"GuildMember.js","path":"src/structures"},"returns":{"types":[[["EvaluatedPermissions",""]]]},"params":[{"name":"channel","description":"Guild channel to use as context","type":{"types":[[["ChannelResolvable",""]]]}}]},{"id":"GuildMember#hasPermission","name":"hasPermission","description":"Checks if any of the member's roles have a permission.","memberof":"GuildMember","meta":{"line":221,"file":"GuildMember.js","path":"src/structures"},"returns":{"types":[[["boolean",""]]]},"params":[{"name":"permission","description":"The permission to check for","type":{"types":[[["PermissionResolvable",""]]]}},{"name":"explicit","description":"Whether to require the roles to explicitly have the exact permission","optional":true,"type":{"types":[[["boolean",""]]]}}]},{"id":"GuildMember#hasPermissions","name":"hasPermissions","description":"Checks whether the roles of the member allows them to perform specific actions.","memberof":"GuildMember","meta":{"line":232,"file":"GuildMember.js","path":"src/structures"},"returns":{"types":[[["boolean",""]]]},"params":[{"name":"permissions","description":"The permissions to check for","type":{"types":[[["Array",".<"],["PermissionResolvable",">"]]]}},{"name":"explicit","description":"Whether to require the member to explicitly have the exact permissions","optional":true,"type":{"types":[[["boolean",""]]]}}]},{"id":"GuildMember#edit","name":"edit","description":"Edit a Guild Member","memberof":"GuildMember","meta":{"line":242,"file":"GuildMember.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["GuildMember",">"]]]},"params":[{"name":"data","description":"The data to edit the member with","type":{"types":[[["GuildmemberEditData",""]]]}}]},{"id":"GuildMember#setMute","name":"setMute","description":"Mute/unmute a user","memberof":"GuildMember","meta":{"line":251,"file":"GuildMember.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["GuildMember",">"]]]},"params":[{"name":"mute","description":"Whether or not the member should be muted","type":{"types":[[["boolean",""]]]}}]},{"id":"GuildMember#setDeaf","name":"setDeaf","description":"Deafen/undeafen a user","memberof":"GuildMember","meta":{"line":260,"file":"GuildMember.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["GuildMember",">"]]]},"params":[{"name":"deaf","description":"Whether or not the member should be deafened","type":{"types":[[["boolean",""]]]}}]},{"id":"GuildMember#setVoiceChannel","name":"setVoiceChannel","description":"Moves the Guild Member to the given channel.","memberof":"GuildMember","meta":{"line":269,"file":"GuildMember.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["GuildMember",">"]]]},"params":[{"name":"channel","description":"The channel to move the member to","type":{"types":[[["ChannelResolvable",""]]]}}]},{"id":"GuildMember#setRoles","name":"setRoles","description":"Sets the Roles applied to the member.","memberof":"GuildMember","meta":{"line":278,"file":"GuildMember.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["GuildMember",">"]]]},"params":[{"name":"roles","description":"The roles or role IDs to apply","type":{"types":[[["Collection",".<"],["string",", "],["Role",">"]],[["Array",".<"],["Role",">"]],[["Array",".<"],["string",">"]]]}}]},{"id":"GuildMember#addRole","name":"addRole","description":"Adds a single Role to the member.","memberof":"GuildMember","meta":{"line":287,"file":"GuildMember.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["GuildMember",">"]]]},"params":[{"name":"role","description":"The role or ID of the role to add","type":{"types":[[["Role",""]],[["string",""]]]}}]},{"id":"GuildMember#addRoles","name":"addRoles","description":"Adds multiple roles to the member.","memberof":"GuildMember","meta":{"line":296,"file":"GuildMember.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["GuildMember",">"]]]},"params":[{"name":"roles","description":"The roles or role IDs to add","type":{"types":[[["Collection",".<"],["string",", "],["Role",">"]],[["Array",".<"],["Role",">"]],[["Array",".<"],["string",">"]]]}}]},{"id":"GuildMember#removeRole","name":"removeRole","description":"Removes a single Role from the member.","memberof":"GuildMember","meta":{"line":312,"file":"GuildMember.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["GuildMember",">"]]]},"params":[{"name":"role","description":"The role or ID of the role to remove","type":{"types":[[["Role",""]],[["string",""]]]}}]},{"id":"GuildMember#removeRoles","name":"removeRoles","description":"Removes multiple roles from the member.","memberof":"GuildMember","meta":{"line":321,"file":"GuildMember.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["GuildMember",">"]]]},"params":[{"name":"roles","description":"The roles or role IDs to remove","type":{"types":[[["Collection",".<"],["string",", "],["Role",">"]],[["Array",".<"],["Role",">"]],[["Array",".<"],["string",">"]]]}}]},{"id":"GuildMember#setNickname","name":"setNickname","description":"Set the nickname for the Guild Member","memberof":"GuildMember","meta":{"line":342,"file":"GuildMember.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["GuildMember",">"]]]},"params":[{"name":"nick","description":"The nickname for the Guild Member","type":{"types":[[["string",""]]]}}]},{"id":"GuildMember#deleteDM","name":"deleteDM","description":"Deletes any DMs with this Guild Member","memberof":"GuildMember","meta":{"line":350,"file":"GuildMember.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["DMChannel",">"]]]},"params":[]},{"id":"GuildMember#kick","name":"kick","description":"Kick this member from the Guild","memberof":"GuildMember","meta":{"line":358,"file":"GuildMember.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["GuildMember",">"]]]},"params":[]},{"id":"GuildMember#ban","name":"ban","description":"Ban this Guild Member","memberof":"GuildMember","examples":["// ban a guild member\rguildMember.ban(7);"],"meta":{"line":371,"file":"GuildMember.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["GuildMember",">"]]]},"params":[{"name":"deleteDays","description":"The amount of days worth of messages from this member that should\ralso be deleted. Between `0` and `7`.","optional":true,"type":{"types":[[["number",""]]]}}]},{"id":"GuildMember#toString","name":"toString","description":"When concatenated with a string, this automatically concatenates the User's mention instead of the Member object.","memberof":"GuildMember","examples":["// logs: Hello from <@123456789>!\rconsole.log(`Hello from ${member}!`);"],"meta":{"line":382,"file":"GuildMember.js","path":"src/structures"},"returns":{"types":[[["string",""]]]},"params":[]},{"id":"GuildMember#sendMessage","name":"sendMessage","description":"Send a message to this channel","memberof":"GuildMember","examples":["// send a message\rchannel.sendMessage('hello!')\r .then(message => console.log(`Sent message: ${message.content}`))\r .catch(console.log);"],"meta":{"line":56,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<("],["Message","|"],["Array",".<"],["Message",">)>"]]]},"params":[{"name":"content","description":"The content to send","type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","optional":true,"type":{"types":[[["MessageOptions",""]]]}}],"implements":["TextBasedChannel#sendMessage"]},{"id":"GuildMember#sendTTSMessage","name":"sendTTSMessage","description":"Send a text-to-speech message to this channel","memberof":"GuildMember","examples":["// send a TTS message\rchannel.sendTTSMessage('hello!')\r .then(message => console.log(`Sent tts message: ${message.content}`))\r .catch(console.log);"],"meta":{"line":71,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<("],["Message","|"],["Array",".<"],["Message",">)>"]]]},"params":[{"name":"content","description":"The content to send","type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","optional":true,"type":{"types":[[["MessageOptions",""]]]}}],"implements":["TextBasedChannel#sendTTSMessage"]},{"id":"GuildMember#sendFile","name":"sendFile","description":"Send a file to this channel","memberof":"GuildMember","meta":{"line":84,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<"],["Message",">"]]]},"params":[{"name":"attachment","description":"The file to send","type":{"types":[[["FileResolvable",""]]]}},{"name":"fileName","description":"The name and extension of the file","optional":true,"type":{"types":[[["string",""]]]}},{"name":"content","description":"Text message to send with the attachment","optional":true,"type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","optional":true,"type":{"types":[[["MessageOptions",""]]]}}],"implements":["TextBasedChannel#sendFile"]},{"id":"GuildMember#sendCode","name":"sendCode","description":"Send a code block to this channel","memberof":"GuildMember","meta":{"line":111,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<("],["Message","|"],["Array",".<"],["Message",">)>"]]]},"params":[{"name":"lang","description":"Language for the code block","type":{"types":[[["string",""]]]}},{"name":"content","description":"Content of the code block","type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","type":{"types":[[["MessageOptions",""]]]}}],"implements":["TextBasedChannel#sendCode"]}],"properties":[{"id":"GuildMember#client","name":"client","description":"The client that instantiated this GuildMember","memberof":"GuildMember","type":{"types":[[["Client",""]]]},"meta":{"line":17,"file":"GuildMember.js","path":"src/structures"},"props":[]},{"id":"GuildMember#guild","name":"guild","description":"The guild that this member is part of","memberof":"GuildMember","type":{"types":[[["Guild",""]]]},"meta":{"line":24,"file":"GuildMember.js","path":"src/structures"},"props":[]},{"id":"GuildMember#user","name":"user","description":"The user that this guild member instance Represents","memberof":"GuildMember","type":{"types":[[["User",""]]]},"meta":{"line":30,"file":"GuildMember.js","path":"src/structures"},"props":[]},{"id":"GuildMember#serverDeaf","name":"serverDeaf","description":"Whether this member is deafened server-wide","memberof":"GuildMember","type":{"types":[[["boolean",""]]]},"meta":{"line":41,"file":"GuildMember.js","path":"src/structures"},"props":[]},{"id":"GuildMember#serverMute","name":"serverMute","description":"Whether this member is muted server-wide","memberof":"GuildMember","type":{"types":[[["boolean",""]]]},"meta":{"line":47,"file":"GuildMember.js","path":"src/structures"},"props":[]},{"id":"GuildMember#selfMute","name":"selfMute","description":"Whether this member is self-muted","memberof":"GuildMember","type":{"types":[[["boolean",""]]]},"meta":{"line":53,"file":"GuildMember.js","path":"src/structures"},"props":[]},{"id":"GuildMember#selfDeaf","name":"selfDeaf","description":"Whether this member is self-deafened","memberof":"GuildMember","type":{"types":[[["boolean",""]]]},"meta":{"line":59,"file":"GuildMember.js","path":"src/structures"},"props":[]},{"id":"GuildMember#voiceSessionID","name":"voiceSessionID","description":"The voice session ID of this member, if any","memberof":"GuildMember","type":{"types":[[["string",""]]]},"meta":{"line":65,"file":"GuildMember.js","path":"src/structures"},"props":[]},{"id":"GuildMember#voiceChannelID","name":"voiceChannelID","description":"The voice channel ID of this member, if any","memberof":"GuildMember","type":{"types":[[["string",""]]]},"meta":{"line":71,"file":"GuildMember.js","path":"src/structures"},"props":[]},{"id":"GuildMember#speaking","name":"speaking","description":"Whether this member is speaking","memberof":"GuildMember","type":{"types":[[["boolean",""]]]},"meta":{"line":77,"file":"GuildMember.js","path":"src/structures"},"props":[]},{"id":"GuildMember#nickname","name":"nickname","description":"The nickname of this Guild Member, if they have one","memberof":"GuildMember","type":{"types":[[["string",""]]]},"meta":{"line":83,"file":"GuildMember.js","path":"src/structures"},"props":[]},{"id":"GuildMember#joinDate","name":"joinDate","description":"The date this member joined the guild","memberof":"GuildMember","type":{"types":[[["Date",""]]]},"meta":{"line":94,"file":"GuildMember.js","path":"src/structures"},"props":[]},{"id":"GuildMember#roles","name":"roles","description":"A list of roles that are applied to this GuildMember, mapped by the role ID.","memberof":"GuildMember","type":{"types":[[["Collection",".<"],["string",", "],["Role",">"]]]},"meta":{"line":103,"file":"GuildMember.js","path":"src/structures"},"props":[]},{"id":"GuildMember#highestRole","name":"highestRole","description":"The role of the member with the highest position.","memberof":"GuildMember","type":{"types":[[["Role",""]]]},"meta":{"line":121,"file":"GuildMember.js","path":"src/structures"},"props":[]},{"id":"GuildMember#mute","name":"mute","description":"Whether this member is muted in any way","memberof":"GuildMember","type":{"types":[[["boolean",""]]]},"meta":{"line":132,"file":"GuildMember.js","path":"src/structures"},"props":[]},{"id":"GuildMember#deaf","name":"deaf","description":"Whether this member is deafened in any way","memberof":"GuildMember","type":{"types":[[["boolean",""]]]},"meta":{"line":141,"file":"GuildMember.js","path":"src/structures"},"props":[]},{"id":"GuildMember#voiceChannel","name":"voiceChannel","description":"The voice channel this member is in, if any","memberof":"GuildMember","type":{"types":[[["VoiceChannel",""]]]},"meta":{"line":150,"file":"GuildMember.js","path":"src/structures"},"props":[]},{"id":"GuildMember#id","name":"id","description":"The ID of this User","memberof":"GuildMember","type":{"types":[[["string",""]]]},"meta":{"line":159,"file":"GuildMember.js","path":"src/structures"},"props":[]},{"id":"GuildMember#permissions","name":"permissions","description":"The overall set of permissions for the guild member, taking only roles into account","memberof":"GuildMember","type":{"types":[[["EvaluatedPermissions",""]]]},"meta":{"line":167,"file":"GuildMember.js","path":"src/structures"},"props":[]},{"id":"GuildMember#kickable","name":"kickable","description":"Whether the member is kickable by the client user.","memberof":"GuildMember","type":{"types":[[["boolean",""]]]},"meta":{"line":184,"file":"GuildMember.js","path":"src/structures"},"props":[]},{"id":"GuildMember#bannable","name":"bannable","description":"Whether the member is bannable by the client user.","memberof":"GuildMember","type":{"types":[[["boolean",""]]]},"meta":{"line":196,"file":"GuildMember.js","path":"src/structures"},"props":[]}],"events":[]},{"id":"Invite","name":"Invite","description":"Represents an Invitation to a Guild Channel.\rThe only guaranteed properties are `code`, `guild` and `channel`. Other properties can be missing.","meta":{"line":30,"file":"Invite.js","path":"src/structures"},"methods":[{"id":"Invite#delete","name":"delete","description":"Deletes this invite","memberof":"Invite","meta":{"line":127,"file":"Invite.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Invite",">"]]]},"params":[]},{"id":"Invite#toString","name":"toString","description":"When concatenated with a string, this automatically concatenates the Invite's URL instead of the object.","memberof":"Invite","examples":["// logs: Invite: https://discord.gg/A1b2C3\rconsole.log(`Invite: ${invite}`);"],"meta":{"line":138,"file":"Invite.js","path":"src/structures"},"returns":{"types":[[["string",""]]]},"params":[]}],"properties":[{"id":"Invite#client","name":"client","description":"The client that instantiated the invite","memberof":"Invite","type":{"types":[[["Client",""]]]},"meta":{"line":36,"file":"Invite.js","path":"src/structures"},"props":[]},{"id":"Invite#guild","name":"guild","description":"The Guild the invite is for. If this Guild is already known, this will be a Guild object. If the Guild is\runknown, this will be a Partial Guild.","memberof":"Invite","type":{"types":[[["Guild",""]],[["PartialGuild",""]]]},"meta":{"line":48,"file":"Invite.js","path":"src/structures"},"props":[]},{"id":"Invite#code","name":"code","description":"The code for this invite","memberof":"Invite","type":{"types":[[["string",""]]]},"meta":{"line":54,"file":"Invite.js","path":"src/structures"},"props":[]},{"id":"Invite#temporary","name":"temporary","description":"Whether or not this invite is temporary","memberof":"Invite","type":{"types":[[["boolean",""]]]},"meta":{"line":60,"file":"Invite.js","path":"src/structures"},"props":[]},{"id":"Invite#maxAge","name":"maxAge","description":"The maximum age of the invite, in seconds","memberof":"Invite","type":{"types":[[["number",""]]]},"meta":{"line":66,"file":"Invite.js","path":"src/structures"},"props":[]},{"id":"Invite#uses","name":"uses","description":"How many times this invite has been used","memberof":"Invite","type":{"types":[[["number",""]]]},"meta":{"line":72,"file":"Invite.js","path":"src/structures"},"props":[]},{"id":"Invite#maxUses","name":"maxUses","description":"The maximum uses of this invite","memberof":"Invite","type":{"types":[[["number",""]]]},"meta":{"line":78,"file":"Invite.js","path":"src/structures"},"props":[]},{"id":"Invite#inviter","name":"inviter","description":"The user who created this invite","memberof":"Invite","type":{"types":[[["User",""]]]},"meta":{"line":85,"file":"Invite.js","path":"src/structures"},"props":[]},{"id":"Invite#channel","name":"channel","description":"The Channel the invite is for. If this Channel is already known, this will be a GuildChannel object.\rIf the Channel is unknown, this will be a Partial Guild Channel.","memberof":"Invite","type":{"types":[[["GuildChannel",""]],[["PartialGuildChannel",""]]]},"meta":{"line":93,"file":"Invite.js","path":"src/structures"},"props":[]},{"id":"Invite#createdAt","name":"createdAt","description":"The creation date of the invite","memberof":"Invite","type":{"types":[[["Date",""]]]},"meta":{"line":102,"file":"Invite.js","path":"src/structures"},"props":[]},{"id":"Invite#creationDate","name":"creationDate","description":"The creation date of the invite","memberof":"Invite","type":{"types":[[["Date",""]]]},"meta":{"line":110,"file":"Invite.js","path":"src/structures"},"props":[]},{"id":"Invite#url","name":"url","description":"The URL to the invite","memberof":"Invite","type":{"types":[[["string",""]]]},"meta":{"line":119,"file":"Invite.js","path":"src/structures"},"props":[]}],"events":[]},{"id":"Message","name":"Message","description":"Represents a Message on Discord","meta":{"line":9,"file":"Message.js","path":"src/structures"},"methods":[{"id":"Message#isMentioned","name":"isMentioned","description":"Whether or not a user, channel or role is mentioned in this message.","memberof":"Message","meta":{"line":291,"file":"Message.js","path":"src/structures"},"returns":{"types":[[["boolean",""]]]},"params":[{"name":"data","description":"either a guild channel, user or a role object, or a string representing\rthe ID of any of these.","type":{"types":[[["GuildChannel",""]],[["User",""]],[["Role",""]],[["string",""]]]}}]},{"id":"Message#edit","name":"edit","description":"Edit the content of the message","memberof":"Message","examples":["// update the content of a message\rmessage.edit('This is my new content!')\r .then(msg => console.log(`Updated the content of a message from ${msg.author}`))\r .catch(console.log);"],"meta":{"line":306,"file":"Message.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Message",">"]]]},"params":[{"name":"content","description":"The new content for the message","type":{"types":[[["StringResolvable",""]]]}}]},{"id":"Message#editCode","name":"editCode","description":"Edit the content of the message, with a code block","memberof":"Message","meta":{"line":316,"file":"Message.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Message",">"]]]},"params":[{"name":"lang","description":"Language for the code block","type":{"types":[[["string",""]]]}},{"name":"content","description":"The new content for the message","type":{"types":[[["StringResolvable",""]]]}}]},{"id":"Message#pin","name":"pin","description":"Pins this message to the channel's pinned messages","memberof":"Message","meta":{"line":325,"file":"Message.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Message",">"]]]},"params":[]},{"id":"Message#unpin","name":"unpin","description":"Unpins this message from the channel's pinned messages","memberof":"Message","meta":{"line":333,"file":"Message.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Message",">"]]]},"params":[]},{"id":"Message#delete","name":"delete","description":"Deletes the message","memberof":"Message","examples":["// delete a message\rmessage.delete()\r .then(msg => console.log(`Deleted message from ${msg.author}`))\r .catch(console.log);"],"meta":{"line":347,"file":"Message.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Message",">"]]]},"params":[{"name":"timeout","description":"How long to wait to delete the message in milliseconds","optional":true,"type":{"types":[[["number",""]]]}}]},{"id":"Message#reply","name":"reply","description":"Reply to the message","memberof":"Message","examples":["// reply to a message\rmessage.reply('Hey, I'm a reply!')\r .then(msg => console.log(`Sent a reply to ${msg.author}`))\r .catch(console.log);"],"meta":{"line":368,"file":"Message.js","path":"src/structures"},"returns":{"types":[[["Promise",".<("],["Message","|"],["Array",".<"],["Message",">)>"]]]},"params":[{"name":"content","description":"The content for the message","type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","optional":true,"type":{"types":[[["MessageOptions",""]]]}}]},{"id":"Message#equals","name":"equals","description":"Used mainly internally. Whether two messages are identical in properties. If you want to compare messages\rwithout checking all the properties, use `message.id === message2.id`, which is much more efficient. This\rmethod allows you to see if there are differences in content, embeds, attachments, nonce and tts properties.","memberof":"Message","meta":{"line":389,"file":"Message.js","path":"src/structures"},"returns":{"types":[[["boolean",""]]]},"params":[{"name":"message","description":"The message to compare it to","type":{"types":[[["Message",""]]]}},{"name":"rawData","description":"Raw data passed through the WebSocket about this message","type":{"types":[[["Object",""]]]}}]},{"id":"Message#toString","name":"toString","description":"When concatenated with a string, this automatically concatenates the Message's content instead of the object.","memberof":"Message","examples":["// logs: Message: This is a message!\rconsole.log(`Message: ${message}`);"],"meta":{"line":418,"file":"Message.js","path":"src/structures"},"returns":{"types":[[["string",""]]]},"params":[]}],"properties":[{"id":"Message#client","name":"client","description":"The client that instantiated the Message","memberof":"Message","type":{"types":[[["Client",""]]]},"meta":{"line":15,"file":"Message.js","path":"src/structures"},"props":[]},{"id":"Message#channel","name":"channel","description":"The channel that the message was sent in","memberof":"Message","type":{"types":[[["TextChannel",""]],[["DMChannel",""]],[["GroupDMChannel",""]]]},"meta":{"line":22,"file":"Message.js","path":"src/structures"},"props":[]},{"id":"Message#id","name":"id","description":"The ID of the message (unique in the channel it was sent)","memberof":"Message","type":{"types":[[["string",""]]]},"meta":{"line":32,"file":"Message.js","path":"src/structures"},"props":[]},{"id":"Message#content","name":"content","description":"The content of the message","memberof":"Message","type":{"types":[[["string",""]]]},"meta":{"line":38,"file":"Message.js","path":"src/structures"},"props":[]},{"id":"Message#author","name":"author","description":"The author of the message","memberof":"Message","type":{"types":[[["User",""]]]},"meta":{"line":44,"file":"Message.js","path":"src/structures"},"props":[]},{"id":"Message#member","name":"member","description":"Represents the Author of the message as a Guild Member. Only available if the message comes from a Guild\rwhere the author is still a member.","memberof":"Message","type":{"types":[[["GuildMember",""]]]},"meta":{"line":51,"file":"Message.js","path":"src/structures"},"props":[]},{"id":"Message#pinned","name":"pinned","description":"Whether or not this message is pinned","memberof":"Message","type":{"types":[[["boolean",""]]]},"meta":{"line":57,"file":"Message.js","path":"src/structures"},"props":[]},{"id":"Message#tts","name":"tts","description":"Whether or not the message was Text-To-Speech","memberof":"Message","type":{"types":[[["boolean",""]]]},"meta":{"line":63,"file":"Message.js","path":"src/structures"},"props":[]},{"id":"Message#nonce","name":"nonce","description":"A random number used for checking message delivery","memberof":"Message","type":{"types":[[["string",""]]]},"meta":{"line":69,"file":"Message.js","path":"src/structures"},"props":[]},{"id":"Message#system","name":"system","description":"Whether or not this message was sent by Discord, not actually a user (e.g. pin notifications)","memberof":"Message","type":{"types":[[["boolean",""]]]},"meta":{"line":75,"file":"Message.js","path":"src/structures"},"props":[]},{"id":"Message#embeds","name":"embeds","description":"A list of embeds in the message - e.g. YouTube Player","memberof":"Message","type":{"types":[[["Array",".<"],["Embed",">"]]]},"meta":{"line":81,"file":"Message.js","path":"src/structures"},"props":[]},{"id":"Message#attachments","name":"attachments","description":"A collection of attachments in the message - e.g. Pictures - mapped by their ID.","memberof":"Message","type":{"types":[[["Collection",".<"],["string",", "],["MessageAttachment",">"]]]},"meta":{"line":87,"file":"Message.js","path":"src/structures"},"props":[]},{"id":"Message#mentions","name":"mentions","description":"An object containing a further users, roles or channels collections","memberof":"Message","type":{"types":[[["Object",""]]]},"meta":{"line":99,"file":"Message.js","path":"src/structures"},"props":[{"name":"mentions.users","description":"Mentioned users, maps their ID to the user object.","type":{"types":[[["Collection",".<"],["string",", "],["User",">"]]]}},{"name":"mentions.roles","description":"Mentioned roles, maps their ID to the role object.","type":{"types":[[["Collection",".<"],["string",", "],["Role",">"]]]}},{"name":"mentions.channels","description":"Mentioned channels,\rmaps their ID to the channel object.","type":{"types":[[["Collection",".<"],["string",", "],["GuildChannel",">"]]]}},{"name":"mentions.everyone","description":"Whether or not @everyone was mentioned.","type":{"types":[[["boolean",""]]]}}]},{"id":"Message#timestamp","name":"timestamp","description":"When the message was sent","memberof":"Message","type":{"types":[[["Date",""]]]},"meta":{"line":191,"file":"Message.js","path":"src/structures"},"props":[]},{"id":"Message#editedTimestamp","name":"editedTimestamp","description":"If the message was edited, the timestamp at which it was last edited","memberof":"Message","type":{"types":[[["Date",""]]]},"meta":{"line":199,"file":"Message.js","path":"src/structures"},"props":[]},{"id":"Message#guild","name":"guild","description":"The guild the message was sent in (if in a guild channel)","memberof":"Message","type":{"types":[[["Guild",""]]]},"meta":{"line":207,"file":"Message.js","path":"src/structures"},"props":[]},{"id":"Message#cleanContent","name":"cleanContent","description":"The message contents with all mentions replaced by the equivalent text. If mentions cannot be resolved to a name,\rthe relevant mention in the message content will not be converted.","memberof":"Message","type":{"types":[[["string",""]]]},"meta":{"line":216,"file":"Message.js","path":"src/structures"},"props":[]},{"id":"Message#edits","name":"edits","description":"An array of cached versions of the message, including the current version.\rSorted from latest (first) to oldest (last).","memberof":"Message","type":{"types":[[["Array",".<"],["Message",">"]]]},"meta":{"line":254,"file":"Message.js","path":"src/structures"},"props":[]},{"id":"Message#editable","name":"editable","description":"Whether the message is editable by the client user.","memberof":"Message","type":{"types":[[["boolean",""]]]},"meta":{"line":262,"file":"Message.js","path":"src/structures"},"props":[]},{"id":"Message#deletable","name":"deletable","description":"Whether the message is deletable by the client user.","memberof":"Message","type":{"types":[[["boolean",""]]]},"meta":{"line":270,"file":"Message.js","path":"src/structures"},"props":[]},{"id":"Message#pinnable","name":"pinnable","description":"Whether the message is pinnable by the client user.","memberof":"Message","type":{"types":[[["boolean",""]]]},"meta":{"line":280,"file":"Message.js","path":"src/structures"},"props":[]}],"events":[]},{"id":"MessageAttachment","name":"MessageAttachment","description":"Represents an Attachment in a Message","meta":{"line":4,"file":"MessageAttachment.js","path":"src/structures"},"methods":[],"properties":[{"id":"MessageAttachment#client","name":"client","description":"The Client that instantiated this Message.","memberof":"MessageAttachment","type":{"types":[[["Client",""]]]},"meta":{"line":10,"file":"MessageAttachment.js","path":"src/structures"},"props":[]},{"id":"MessageAttachment#message","name":"message","description":"The message this attachment is part of.","memberof":"MessageAttachment","type":{"types":[[["Message",""]]]},"meta":{"line":17,"file":"MessageAttachment.js","path":"src/structures"},"props":[]},{"id":"MessageAttachment#id","name":"id","description":"The ID of this attachment","memberof":"MessageAttachment","type":{"types":[[["string",""]]]},"meta":{"line":27,"file":"MessageAttachment.js","path":"src/structures"},"props":[]},{"id":"MessageAttachment#filename","name":"filename","description":"The file name of this attachment","memberof":"MessageAttachment","type":{"types":[[["string",""]]]},"meta":{"line":33,"file":"MessageAttachment.js","path":"src/structures"},"props":[]},{"id":"MessageAttachment#filesize","name":"filesize","description":"The size of this attachment in bytes","memberof":"MessageAttachment","type":{"types":[[["number",""]]]},"meta":{"line":39,"file":"MessageAttachment.js","path":"src/structures"},"props":[]},{"id":"MessageAttachment#url","name":"url","description":"The URL to this attachment","memberof":"MessageAttachment","type":{"types":[[["string",""]]]},"meta":{"line":45,"file":"MessageAttachment.js","path":"src/structures"},"props":[]},{"id":"MessageAttachment#proxyURL","name":"proxyURL","description":"The Proxy URL to this attachment","memberof":"MessageAttachment","type":{"types":[[["string",""]]]},"meta":{"line":51,"file":"MessageAttachment.js","path":"src/structures"},"props":[]},{"id":"MessageAttachment#height","name":"height","description":"The height of this attachment (if an image)","memberof":"MessageAttachment","type":{"types":[[["number",""]]]},"meta":{"line":57,"file":"MessageAttachment.js","path":"src/structures"},"props":[]},{"id":"MessageAttachment#width","name":"width","description":"The width of this attachment (if an image)","memberof":"MessageAttachment","type":{"types":[[["number",""]]]},"meta":{"line":63,"file":"MessageAttachment.js","path":"src/structures"},"props":[]}],"events":[]},{"id":"MessageCollector","name":"MessageCollector","description":"Collects messages based on a specified filter, then emits them.","meta":{"line":8,"file":"MessageCollector.js","path":"src/structures"},"extends":["EventEmitter"],"classConstructor":{"id":"MessageCollector()","name":"MessageCollector","memberof":"MessageCollector","params":[{"name":"channel","description":"The channel to collect messages in","type":{"types":[[["Channel",""]]]}},{"name":"filter","description":"The filter function","type":{"types":[[["CollectorFilterFunction",""]]]}},{"name":"options","description":"Options for the collector","optional":true,"type":{"types":[[["CollectorOptions",""]]]}}]},"methods":[{"id":"MessageCollector#stop","name":"stop","description":"Stops the collector and emits `end`.","memberof":"MessageCollector","meta":{"line":99,"file":"MessageCollector.js","path":"src/structures"},"returns":{"types":[[["null",""]]]},"params":[{"name":"reason","description":"An optional reason for stopping the collector","optional":true,"type":{"types":[[["string",""]]]}}]}],"properties":[{"id":"MessageCollector#channel","name":"channel","description":"The channel this collector is operating on","memberof":"MessageCollector","type":{"types":[[["Channel",""]]]},"meta":{"line":41,"file":"MessageCollector.js","path":"src/structures"},"props":[]},{"id":"MessageCollector#filter","name":"filter","description":"A function used to filter messages that the collector collects.","memberof":"MessageCollector","type":{"types":[[["CollectorFilterFunction",""]]]},"meta":{"line":47,"file":"MessageCollector.js","path":"src/structures"},"props":[]},{"id":"MessageCollector#options","name":"options","description":"Options for the collecor.","memberof":"MessageCollector","type":{"types":[[["CollectorOptions",""]]]},"meta":{"line":53,"file":"MessageCollector.js","path":"src/structures"},"props":[]},{"id":"MessageCollector#ended","name":"ended","description":"Whether this collector has stopped collecting Messages.","memberof":"MessageCollector","type":{"types":[[["boolean",""]]]},"meta":{"line":59,"file":"MessageCollector.js","path":"src/structures"},"props":[]},{"id":"MessageCollector#collected","name":"collected","description":"A collection of collected messages, mapped by message ID.","memberof":"MessageCollector","type":{"types":[[["Collection",".<"],["string",", "],["Message",">"]]]},"meta":{"line":65,"file":"MessageCollector.js","path":"src/structures"},"props":[]}],"events":[{"id":"MessageCollector#event:message","name":"message","description":"Emitted whenever the Collector receives a Message that passes the filter test.","memberof":"MessageCollector","meta":{"line":82,"file":"MessageCollector.js","path":"src/structures"},"params":[{"name":"message","description":"The received message","type":{"types":[[["Message",""]]]}},{"name":"collector","description":"The collector the message passed through","type":{"types":[[["MessageCollector",""]]]}}]},{"id":"MessageCollector#event:end","name":"end","description":"Emitted when the Collector stops collecting.","memberof":"MessageCollector","meta":{"line":103,"file":"MessageCollector.js","path":"src/structures"},"params":[{"name":"collection","description":"A collection of messages collected\rduring the lifetime of the Collector, mapped by the ID of the Messages.","type":{"types":[[["Collection",".<"],["string",", "],["Message",">"]]]}},{"name":"reason","description":"The reason for the end of the collector. If it ended because it reached the specified time\rlimit, this would be `time`. If you invoke `.stop()` without specifying a reason, this would be `user`. If it\rended because it reached its message limit, it will be `limit`.","type":{"types":[[["string",""]]]}}]}]},{"id":"MessageEmbed","name":"MessageEmbed","description":"Represents an embed in an image - e.g. preview of image","meta":{"line":4,"file":"MessageEmbed.js","path":"src/structures"},"methods":[],"properties":[{"id":"MessageEmbed#client","name":"client","description":"The client that instantiated this embed","memberof":"MessageEmbed","type":{"types":[[["Client",""]]]},"meta":{"line":10,"file":"MessageEmbed.js","path":"src/structures"},"props":[]},{"id":"MessageEmbed#message","name":"message","description":"The message this embed is part of","memberof":"MessageEmbed","type":{"types":[[["Message",""]]]},"meta":{"line":17,"file":"MessageEmbed.js","path":"src/structures"},"props":[]},{"id":"MessageEmbed#title","name":"title","description":"The title of this embed, if there is one","memberof":"MessageEmbed","type":{"types":[[["string",""]]]},"meta":{"line":27,"file":"MessageEmbed.js","path":"src/structures"},"props":[]},{"id":"MessageEmbed#type","name":"type","description":"The type of this embed","memberof":"MessageEmbed","type":{"types":[[["string",""]]]},"meta":{"line":33,"file":"MessageEmbed.js","path":"src/structures"},"props":[]},{"id":"MessageEmbed#description","name":"description","description":"The description of this embed, if there is one","memberof":"MessageEmbed","type":{"types":[[["string",""]]]},"meta":{"line":39,"file":"MessageEmbed.js","path":"src/structures"},"props":[]},{"id":"MessageEmbed#url","name":"url","description":"The URL of this embed","memberof":"MessageEmbed","type":{"types":[[["string",""]]]},"meta":{"line":45,"file":"MessageEmbed.js","path":"src/structures"},"props":[]},{"id":"MessageEmbed#thumbnail","name":"thumbnail","description":"The thumbnail of this embed, if there is one","memberof":"MessageEmbed","type":{"types":[[["MessageEmbedThumbnail",""]]]},"meta":{"line":51,"file":"MessageEmbed.js","path":"src/structures"},"props":[]},{"id":"MessageEmbed#author","name":"author","description":"The author of this embed, if there is one","memberof":"MessageEmbed","type":{"types":[[["MessageEmbedAuthor",""]]]},"meta":{"line":57,"file":"MessageEmbed.js","path":"src/structures"},"props":[]},{"id":"MessageEmbed#provider","name":"provider","description":"The provider of this embed, if there is one","memberof":"MessageEmbed","type":{"types":[[["MessageEmbedProvider",""]]]},"meta":{"line":63,"file":"MessageEmbed.js","path":"src/structures"},"props":[]}],"events":[]},{"id":"MessageEmbedThumbnail","name":"MessageEmbedThumbnail","description":"Represents a thumbnail for a Message embed","meta":{"line":70,"file":"MessageEmbed.js","path":"src/structures"},"methods":[],"properties":[{"id":"MessageEmbedThumbnail#embed","name":"embed","description":"The embed this thumbnail is part of","memberof":"MessageEmbedThumbnail","type":{"types":[[["MessageEmbed",""]]]},"meta":{"line":76,"file":"MessageEmbed.js","path":"src/structures"},"props":[]},{"id":"MessageEmbedThumbnail#url","name":"url","description":"The URL for this thumbnail","memberof":"MessageEmbedThumbnail","type":{"types":[[["string",""]]]},"meta":{"line":86,"file":"MessageEmbed.js","path":"src/structures"},"props":[]},{"id":"MessageEmbedThumbnail#proxyURL","name":"proxyURL","description":"The Proxy URL for this thumbnail","memberof":"MessageEmbedThumbnail","type":{"types":[[["string",""]]]},"meta":{"line":92,"file":"MessageEmbed.js","path":"src/structures"},"props":[]},{"id":"MessageEmbedThumbnail#height","name":"height","description":"The height of the thumbnail","memberof":"MessageEmbedThumbnail","type":{"types":[[["number",""]]]},"meta":{"line":98,"file":"MessageEmbed.js","path":"src/structures"},"props":[]},{"id":"MessageEmbedThumbnail#width","name":"width","description":"The width of the thumbnail","memberof":"MessageEmbedThumbnail","type":{"types":[[["number",""]]]},"meta":{"line":104,"file":"MessageEmbed.js","path":"src/structures"},"props":[]}],"events":[]},{"id":"MessageEmbedProvider","name":"MessageEmbedProvider","description":"Represents a Provider for a Message embed","meta":{"line":111,"file":"MessageEmbed.js","path":"src/structures"},"methods":[],"properties":[{"id":"MessageEmbedProvider#embed","name":"embed","description":"The embed this provider is part of","memberof":"MessageEmbedProvider","type":{"types":[[["MessageEmbed",""]]]},"meta":{"line":117,"file":"MessageEmbed.js","path":"src/structures"},"props":[]},{"id":"MessageEmbedProvider#name","name":"name","description":"The name of this provider","memberof":"MessageEmbedProvider","type":{"types":[[["string",""]]]},"meta":{"line":127,"file":"MessageEmbed.js","path":"src/structures"},"props":[]},{"id":"MessageEmbedProvider#url","name":"url","description":"The URL of this provider","memberof":"MessageEmbedProvider","type":{"types":[[["string",""]]]},"meta":{"line":133,"file":"MessageEmbed.js","path":"src/structures"},"props":[]}],"events":[]},{"id":"MessageEmbedAuthor","name":"MessageEmbedAuthor","description":"Represents a Author for a Message embed","meta":{"line":140,"file":"MessageEmbed.js","path":"src/structures"},"methods":[],"properties":[{"id":"MessageEmbedAuthor#embed","name":"embed","description":"The embed this author is part of","memberof":"MessageEmbedAuthor","type":{"types":[[["MessageEmbed",""]]]},"meta":{"line":146,"file":"MessageEmbed.js","path":"src/structures"},"props":[]},{"id":"MessageEmbedAuthor#name","name":"name","description":"The name of this author","memberof":"MessageEmbedAuthor","type":{"types":[[["string",""]]]},"meta":{"line":156,"file":"MessageEmbed.js","path":"src/structures"},"props":[]},{"id":"MessageEmbedAuthor#url","name":"url","description":"The URL of this author","memberof":"MessageEmbedAuthor","type":{"types":[[["string",""]]]},"meta":{"line":162,"file":"MessageEmbed.js","path":"src/structures"},"props":[]}],"events":[]},{"id":"PartialGuild","name":"PartialGuild","description":"Represents a Guild that the client only has limited information for - e.g. from invites.","meta":{"line":11,"file":"PartialGuild.js","path":"src/structures"},"methods":[],"properties":[{"id":"PartialGuild#client","name":"client","description":"The client that instantiated this PartialGuild","memberof":"PartialGuild","type":{"types":[[["Client",""]]]},"meta":{"line":17,"file":"PartialGuild.js","path":"src/structures"},"props":[]},{"id":"PartialGuild#id","name":"id","description":"The ID of this guild","memberof":"PartialGuild","type":{"types":[[["string",""]]]},"meta":{"line":28,"file":"PartialGuild.js","path":"src/structures"},"props":[]},{"id":"PartialGuild#name","name":"name","description":"The name of this guild","memberof":"PartialGuild","type":{"types":[[["string",""]]]},"meta":{"line":34,"file":"PartialGuild.js","path":"src/structures"},"props":[]},{"id":"PartialGuild#icon","name":"icon","description":"The hash of this guild's icon, or null if there is none.","memberof":"PartialGuild","type":{"types":[[["string",""]]]},"meta":{"line":40,"file":"PartialGuild.js","path":"src/structures"},"props":[]},{"id":"PartialGuild#splash","name":"splash","description":"The hash of the guild splash image, or null if no splash (VIP only)","memberof":"PartialGuild","type":{"types":[[["string",""]]]},"meta":{"line":46,"file":"PartialGuild.js","path":"src/structures"},"props":[]}],"events":[]},{"id":"PartialGuildChannel","name":"PartialGuildChannel","description":"Represents a Guild Channel that the client only has limited information for - e.g. from invites.","meta":{"line":10,"file":"PartialGuildChannel.js","path":"src/structures"},"methods":[],"properties":[{"id":"PartialGuildChannel#client","name":"client","description":"The client that instantiated this PartialGuildChannel","memberof":"PartialGuildChannel","type":{"types":[[["Client",""]]]},"meta":{"line":16,"file":"PartialGuildChannel.js","path":"src/structures"},"props":[]},{"id":"PartialGuildChannel#id","name":"id","description":"The ID of this Guild Channel","memberof":"PartialGuildChannel","type":{"types":[[["string",""]]]},"meta":{"line":27,"file":"PartialGuildChannel.js","path":"src/structures"},"props":[]},{"id":"PartialGuildChannel#name","name":"name","description":"The name of this Guild Channel","memberof":"PartialGuildChannel","type":{"types":[[["string",""]]]},"meta":{"line":33,"file":"PartialGuildChannel.js","path":"src/structures"},"props":[]},{"id":"PartialGuildChannel#type","name":"type","description":"The type of this Guild Channel - `text` or `voice`","memberof":"PartialGuildChannel","type":{"types":[[["string",""]]]},"meta":{"line":39,"file":"PartialGuildChannel.js","path":"src/structures"},"props":[]}],"events":[]},{"id":"PermissionOverwrites","name":"PermissionOverwrites","description":"Represents a permission overwrite for a Role or Member in a Guild Channel.","meta":{"line":4,"file":"PermissionOverwrites.js","path":"src/structures"},"methods":[{"id":"PermissionOverwrites#delete","name":"delete","description":"Delete this Permission Overwrite.","memberof":"PermissionOverwrites","meta":{"line":36,"file":"PermissionOverwrites.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["PermissionOverwrites",">"]]]},"params":[]}],"properties":[{"id":"PermissionOverwrites#channel","name":"channel","description":"The GuildChannel this overwrite is for","memberof":"PermissionOverwrites","type":{"types":[[["GuildChannel",""]]]},"meta":{"line":10,"file":"PermissionOverwrites.js","path":"src/structures"},"props":[]},{"id":"PermissionOverwrites#id","name":"id","description":"The ID of this overwrite, either a User ID or a Role ID","memberof":"PermissionOverwrites","type":{"types":[[["string",""]]]},"meta":{"line":20,"file":"PermissionOverwrites.js","path":"src/structures"},"props":[]},{"id":"PermissionOverwrites#type","name":"type","description":"The type of this overwrite","memberof":"PermissionOverwrites","type":{"types":[[["string",""]]]},"meta":{"line":26,"file":"PermissionOverwrites.js","path":"src/structures"},"props":[]}],"events":[]},{"id":"Role","name":"Role","description":"Represents a Role on Discord","meta":{"line":6,"file":"Role.js","path":"src/structures"},"methods":[{"id":"Role#serialize","name":"serialize","description":"Get an object mapping permission names to whether or not the role enables that permission","memberof":"Role","examples":["// print the serialized role\rconsole.log(role.serialize());"],"meta":{"line":109,"file":"Role.js","path":"src/structures"},"returns":{"types":[[["Object",".<"],["string",", "],["boolean",">"]]]},"params":[]},{"id":"Role#hasPermission","name":"hasPermission","description":"Checks if the role has a permission.","memberof":"Role","examples":["// see if a role can ban a member\rif (role.hasPermission('BAN_MEMBERS')) {\r console.log('This role can ban members');\r} else {\r console.log('This role can\\'t ban members');\r}"],"meta":{"line":130,"file":"Role.js","path":"src/structures"},"returns":{"types":[[["boolean",""]]]},"params":[{"name":"permission","description":"The permission to check for","type":{"types":[[["PermissionResolvable",""]]]}},{"name":"explicit","description":"Whether to require the role to explicitly have the exact permission","optional":true,"type":{"types":[[["boolean",""]]]}}]},{"id":"Role#hasPermissions","name":"hasPermissions","description":"Checks if the role has all specified permissions.","memberof":"Role","meta":{"line":142,"file":"Role.js","path":"src/structures"},"returns":{"types":[[["boolean",""]]]},"params":[{"name":"permissions","description":"The permissions to check for","type":{"types":[[["Array",".<"],["PermissionResolvable",">"]]]}},{"name":"explicit","description":"Whether to require the role to explicitly have the exact permissions","optional":true,"type":{"types":[[["boolean",""]]]}}]},{"id":"Role#edit","name":"edit","description":"Edits the role","memberof":"Role","examples":["// edit a role\rrole.edit({name: 'new role'})\r .then(r => console.log(`Edited role ${r}`))\r .catch(console.log);"],"meta":{"line":156,"file":"Role.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Role",">"]]]},"params":[{"name":"data","description":"The new data for the role","type":{"types":[[["RoleData",""]]]}}]},{"id":"Role#setName","name":"setName","description":"Set a new name for the role","memberof":"Role","examples":["// set the name of the role\rrole.setName('new role')\r .then(r => console.log(`Edited name of role ${r}`))\r .catch(console.log);"],"meta":{"line":170,"file":"Role.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Role",">"]]]},"params":[{"name":"name","description":"The new name of the role","type":{"types":[[["string",""]]]}}]},{"id":"Role#setColor","name":"setColor","description":"Set a new color for the role","memberof":"Role","examples":["// set the color of a role\rrole.setColor('#FF0000')\r .then(r => console.log(`Set color of role ${r}`))\r .catch(console.log);"],"meta":{"line":184,"file":"Role.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Role",">"]]]},"params":[{"name":"color","description":"The new color for the role, either a hex string or a base 10 number","type":{"types":[[["number",""]],[["string",""]]]}}]},{"id":"Role#setHoist","name":"setHoist","description":"Set whether or not the role should be hoisted","memberof":"Role","examples":["// set the hoist of the role\rrole.setHoist(true)\r .then(r => console.log(`Role hoisted: ${r.hoist}`))\r .catch(console.log);"],"meta":{"line":198,"file":"Role.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Role",">"]]]},"params":[{"name":"hoist","description":"Whether or not to hoist the role","type":{"types":[[["boolean",""]]]}}]},{"id":"Role#setPosition","name":"setPosition","description":"Set the position of the role","memberof":"Role","examples":["// set the position of the role\rrole.setPosition(1)\r .then(r => console.log(`Role position: ${r.position}`))\r .catch(console.log);"],"meta":{"line":212,"file":"Role.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Role",">"]]]},"params":[{"name":"position","description":"The position of the role","type":{"types":[[["number",""]]]}}]},{"id":"Role#setPermissions","name":"setPermissions","description":"Set the permissions of the role","memberof":"Role","examples":["// set the permissions of the role\rrole.setPermissions(['KICK_MEMBERS', 'BAN_MEMBERS'])\r .then(r => console.log(`Role updated ${r}`))\r .catch(console.log);"],"meta":{"line":226,"file":"Role.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Role",">"]]]},"params":[{"name":"permissions","description":"The permissions of the role","type":{"types":[[["Array",".<"],["string",">"]]]}}]},{"id":"Role#delete","name":"delete","description":"Deletes the role","memberof":"Role","examples":["// delete a role\rrole.delete()\r .then(r => console.log(`Deleted role ${r}`))\r .catch(console.log);"],"meta":{"line":239,"file":"Role.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Role",">"]]]},"params":[]},{"id":"Role#equals","name":"equals","description":"Whether this role equals another role. It compares all properties, so for most operations\rit is advisable to just compare `role.id === role2.id` as it is much faster and is often\rwhat most users need.","memberof":"Role","meta":{"line":250,"file":"Role.js","path":"src/structures"},"returns":{"types":[[["boolean",""]]]},"params":[{"name":"role","description":"The role to compare to","type":{"types":[[["Role",""]]]}}]},{"id":"Role#toString","name":"toString","description":"When concatenated with a string, this automatically concatenates the Role mention rather than the Role object.","memberof":"Role","meta":{"line":265,"file":"Role.js","path":"src/structures"},"returns":{"types":[[["string",""]]]},"params":[]}],"properties":[{"id":"Role#client","name":"client","description":"The client that instantiated the role","memberof":"Role","type":{"types":[[["Client",""]]]},"meta":{"line":12,"file":"Role.js","path":"src/structures"},"props":[]},{"id":"Role#guild","name":"guild","description":"The guild that the role belongs to","memberof":"Role","type":{"types":[[["Guild",""]]]},"meta":{"line":19,"file":"Role.js","path":"src/structures"},"props":[]},{"id":"Role#id","name":"id","description":"The ID of the role (unique to the guild it is part of)","memberof":"Role","type":{"types":[[["string",""]]]},"meta":{"line":29,"file":"Role.js","path":"src/structures"},"props":[]},{"id":"Role#name","name":"name","description":"The name of the role","memberof":"Role","type":{"types":[[["string",""]]]},"meta":{"line":35,"file":"Role.js","path":"src/structures"},"props":[]},{"id":"Role#color","name":"color","description":"The base 10 color of the role","memberof":"Role","type":{"types":[[["number",""]]]},"meta":{"line":41,"file":"Role.js","path":"src/structures"},"props":[]},{"id":"Role#hoist","name":"hoist","description":"If true, users that are part of this role will appear in a separate category in the users list","memberof":"Role","type":{"types":[[["boolean",""]]]},"meta":{"line":47,"file":"Role.js","path":"src/structures"},"props":[]},{"id":"Role#position","name":"position","description":"The position of the role in the role manager","memberof":"Role","type":{"types":[[["number",""]]]},"meta":{"line":53,"file":"Role.js","path":"src/structures"},"props":[]},{"id":"Role#permissions","name":"permissions","description":"The evaluated permissions number","memberof":"Role","type":{"types":[[["number",""]]]},"meta":{"line":59,"file":"Role.js","path":"src/structures"},"props":[]},{"id":"Role#managed","name":"managed","description":"Whether or not the role is managed by an external service","memberof":"Role","type":{"types":[[["boolean",""]]]},"meta":{"line":65,"file":"Role.js","path":"src/structures"},"props":[]},{"id":"Role#mentionable","name":"mentionable","description":"Whether or not the role can be mentioned by anyone","memberof":"Role","type":{"types":[[["boolean",""]]]},"meta":{"line":71,"file":"Role.js","path":"src/structures"},"props":[]},{"id":"Role#creationDate","name":"creationDate","description":"The time the role was created","memberof":"Role","type":{"types":[[["Date",""]]]},"meta":{"line":79,"file":"Role.js","path":"src/structures"},"props":[]},{"id":"Role#hexColor","name":"hexColor","description":"The hexadecimal version of the role color, with a leading hashtag.","memberof":"Role","type":{"types":[[["string",""]]]},"meta":{"line":88,"file":"Role.js","path":"src/structures"},"props":[]},{"id":"Role#members","name":"members","description":"The cached guild members that have this role.","memberof":"Role","type":{"types":[[["Collection",".<"],["string",", "],["GuildMember",">"]]]},"meta":{"line":98,"file":"Role.js","path":"src/structures"},"props":[]}],"events":[]},{"id":"TextChannel","name":"TextChannel","description":"Represents a Server Text Channel on Discord.","meta":{"line":10,"file":"TextChannel.js","path":"src/structures"},"extends":["GuildChannel"],"methods":[{"id":"TextChannel#sendMessage","name":"sendMessage","description":"Send a message to this channel","memberof":"TextChannel","examples":["// send a message\rchannel.sendMessage('hello!')\r .then(message => console.log(`Sent message: ${message.content}`))\r .catch(console.log);"],"meta":{"line":56,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<("],["Message","|"],["Array",".<"],["Message",">)>"]]]},"params":[{"name":"content","description":"The content to send","type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","optional":true,"type":{"types":[[["MessageOptions",""]]]}}],"implements":["TextBasedChannel#sendMessage"]},{"id":"TextChannel#sendTTSMessage","name":"sendTTSMessage","description":"Send a text-to-speech message to this channel","memberof":"TextChannel","examples":["// send a TTS message\rchannel.sendTTSMessage('hello!')\r .then(message => console.log(`Sent tts message: ${message.content}`))\r .catch(console.log);"],"meta":{"line":71,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<("],["Message","|"],["Array",".<"],["Message",">)>"]]]},"params":[{"name":"content","description":"The content to send","type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","optional":true,"type":{"types":[[["MessageOptions",""]]]}}],"implements":["TextBasedChannel#sendTTSMessage"]},{"id":"TextChannel#sendFile","name":"sendFile","description":"Send a file to this channel","memberof":"TextChannel","meta":{"line":84,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<"],["Message",">"]]]},"params":[{"name":"attachment","description":"The file to send","type":{"types":[[["FileResolvable",""]]]}},{"name":"fileName","description":"The name and extension of the file","optional":true,"type":{"types":[[["string",""]]]}},{"name":"content","description":"Text message to send with the attachment","optional":true,"type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","optional":true,"type":{"types":[[["MessageOptions",""]]]}}],"implements":["TextBasedChannel#sendFile"]},{"id":"TextChannel#sendCode","name":"sendCode","description":"Send a code block to this channel","memberof":"TextChannel","meta":{"line":111,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<("],["Message","|"],["Array",".<"],["Message",">)>"]]]},"params":[{"name":"lang","description":"Language for the code block","type":{"types":[[["string",""]]]}},{"name":"content","description":"Content of the code block","type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","type":{"types":[[["MessageOptions",""]]]}}],"implements":["TextBasedChannel#sendCode"]},{"id":"TextChannel#fetchMessage","name":"fetchMessage","description":"Gets a single message from this channel, regardless of it being cached or not.","memberof":"TextChannel","examples":["// get message\rchannel.fetchMessage('99539446449315840')\r .then(message => console.log(message.content))\r .catch(console.error);"],"meta":{"line":131,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<"],["Message",">"]]]},"params":[{"name":"messageID","description":"The ID of the message to get","type":{"types":[[["string",""]]]}}],"implements":["TextBasedChannel#fetchMessage"]},{"id":"TextChannel#fetchMessages","name":"fetchMessages","description":"Gets the past messages sent in this channel. Resolves with a Collection mapping message ID's to Message objects.","memberof":"TextChannel","examples":["// get messages\rchannel.fetchMessages({limit: 10})\r .then(messages => console.log(`Received ${messages.size} messages`))\r .catch(console.log);"],"meta":{"line":163,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<"],["Collection",".<"],["string",", "],["Message",">>"]]]},"params":[{"name":"options","description":"The query parameters to pass in","optional":true,"type":{"types":[[["ChannelLogsQueryOptions",""]]]}}],"implements":["TextBasedChannel#fetchMessages"]},{"id":"TextChannel#fetchPinnedMessages","name":"fetchPinnedMessages","description":"Fetches the pinned messages of this Channel and returns a Collection of them.","memberof":"TextChannel","meta":{"line":181,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<"],["Collection",".<"],["string",", "],["Message",">>"]]]},"params":[],"implements":["TextBasedChannel#fetchPinnedMessages"]},{"id":"TextChannel#startTyping","name":"startTyping","description":"Starts a typing indicator in the channel.","memberof":"TextChannel","examples":["// start typing in a channel\rchannel.startTyping();"],"meta":{"line":202,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["null",""]]]},"params":[{"name":"count","description":"The number of times startTyping should be considered to have been called","optional":true,"type":{"types":[[["number",""]]]}}],"implements":["TextBasedChannel#startTyping"]},{"id":"TextChannel#stopTyping","name":"stopTyping","description":"Stops the typing indicator in the channel.\rThe indicator will only stop if this is called as many times as startTyping().\rIt can take a few seconds for the Client User to stop typing.","memberof":"TextChannel","examples":["// stop typing in a channel\rchannel.stopTyping();","// force typing to fully stop in a channel\rchannel.stopTyping(true);"],"meta":{"line":230,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["null",""]]]},"params":[{"name":"force","description":"Whether or not to reset the call count and force the indicator to stop","optional":true,"type":{"types":[[["boolean",""]]]}}],"implements":["TextBasedChannel#stopTyping"]},{"id":"TextChannel#createCollector","name":"createCollector","description":"Creates a Message Collector","memberof":"TextChannel","examples":["// create a message collector\rconst collector = channel.createCollector(\r m => m.content.includes('discord'),\r { time: 15000 }\r);\rcollector.on('message', m => console.log(`Collected ${m.content}`));\rcollector.on('end', collected => console.log(`Collected ${collected.size} items`));"],"meta":{"line":272,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["MessageCollector",""]]]},"params":[{"name":"filter","description":"The filter to create the collector with","type":{"types":[[["CollectorFilterFunction",""]]]}},{"name":"options","description":"The options to pass to the collector","optional":true,"type":{"types":[[["CollectorOptions",""]]]}}],"implements":["TextBasedChannel#createCollector"]},{"id":"TextChannel#awaitMessages","name":"awaitMessages","description":"Similar to createCollector but in Promise form. Resolves with a Collection of messages that pass the specified\rfilter.","memberof":"TextChannel","examples":["// await !vote messages\rconst filter = m => m.content.startsWith('!vote');\r// errors: ['time'] treats ending because of the time limit as an error\rchannel.awaitMessages(filter, { max: 4, time: 60000, errors: ['time'] })\r .then(collected => console.log(collected.size))\r .catch(collected => console.log(`After a minute, only ${collected.size} out of 4 voted.`));"],"meta":{"line":296,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<"],["Collection",".<"],["string",", "],["Message",">>"]]]},"params":[{"name":"filter","description":"The filter function to use","type":{"types":[[["CollectorFilterFunction",""]]]}},{"name":"options","description":"Optional options to pass to the internal collector","optional":true,"type":{"types":[[["AwaitMessagesOptions",""]]]}}],"implements":["TextBasedChannel#awaitMessages"]},{"id":"TextChannel#bulkDelete","name":"bulkDelete","description":"Bulk delete a given Collection or Array of messages in one go. Returns the deleted messages after.\rOnly OAuth Bot accounts may use this method.","memberof":"TextChannel","meta":{"line":315,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Collection",".<"],["string",", "],["Message",">"]]]},"params":[{"name":"messages","description":"The messages to delete","type":{"types":[[["Collection",".<"],["string",", "],["Message",">"]],[["Array",".<"],["Message",">"]]]}}],"implements":["TextBasedChannel#bulkDelete"]},{"id":"TextChannel#permissionsFor","name":"permissionsFor","description":"Gets the overall set of permissions for a user in this channel, taking into account roles and permission\roverwrites.","memberof":"TextChannel","inherits":"GuildChannel#permissionsFor","inherited":true,"meta":{"line":57,"file":"GuildChannel.js","path":"src/structures"},"returns":{"types":[[["EvaluatedPermissions",""]]]},"params":[{"name":"member","description":"The user that you want to obtain the overall permissions for","type":{"types":[[["GuildMemberResolvable",""]]]}}]},{"id":"TextChannel#overwritePermissions","name":"overwritePermissions","description":"Overwrites the permissions for a user or role in this channel.","memberof":"TextChannel","examples":["// overwrite permissions for a message author\rmessage.channel.overwritePermissions(message.author, {\r SEND_MESSAGES: false\r})\r.then(() => console.log('Done!'))\r.catch(console.log);"],"inherits":"GuildChannel#overwritePermissions","inherited":true,"meta":{"line":125,"file":"GuildChannel.js","path":"src/structures"},"returns":{"types":[[["Promise",""]]]},"params":[{"name":"userOrRole","description":"The user or role to update","type":{"types":[[["Role",""]],[["UserResolvable",""]]]}},{"name":"options","description":"The configuration for the update","type":{"types":[[["PermissionOverwriteOptions",""]]]}}]},{"id":"TextChannel#setName","name":"setName","description":"Set a new name for the Guild Channel","memberof":"TextChannel","examples":["// set a new channel name\rchannel.setName('not_general')\r .then(newChannel => console.log(`Channel's new name is ${newChannel.name}`))\r .catch(console.log);"],"inherits":"GuildChannel#setName","inherited":true,"meta":{"line":175,"file":"GuildChannel.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["GuildChannel",">"]]]},"params":[{"name":"name","description":"The new name for the guild channel","type":{"types":[[["string",""]]]}}]},{"id":"TextChannel#setPosition","name":"setPosition","description":"Set a new position for the Guild Channel","memberof":"TextChannel","examples":["// set a new channel position\rchannel.setPosition(2)\r .then(newChannel => console.log(`Channel's new position is ${newChannel.position}`))\r .catch(console.log);"],"inherits":"GuildChannel#setPosition","inherited":true,"meta":{"line":189,"file":"GuildChannel.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["GuildChannel",">"]]]},"params":[{"name":"position","description":"The new position for the guild channel","type":{"types":[[["number",""]]]}}]},{"id":"TextChannel#setTopic","name":"setTopic","description":"Set a new topic for the Guild Channel","memberof":"TextChannel","examples":["// set a new channel topic\rchannel.setTopic('needs more rate limiting')\r .then(newChannel => console.log(`Channel's new topic is ${newChannel.topic}`))\r .catch(console.log);"],"inherits":"GuildChannel#setTopic","inherited":true,"meta":{"line":203,"file":"GuildChannel.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["GuildChannel",">"]]]},"params":[{"name":"topic","description":"The new topic for the guild channel","type":{"types":[[["string",""]]]}}]},{"id":"TextChannel#createInvite","name":"createInvite","description":"Create an invite to this Guild Channel","memberof":"TextChannel","inherits":"GuildChannel#createInvite","inherited":true,"meta":{"line":220,"file":"GuildChannel.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Invite",">"]]]},"params":[{"name":"options","description":"The options for the invite","optional":true,"type":{"types":[[["InviteOptions",""]]]}}]},{"id":"TextChannel#equals","name":"equals","description":"Checks if this channel has the same type, topic, position, name, overwrites and ID as another channel.\rIn most cases, a simple `channel.id === channel2.id` will do, and is much faster too.","memberof":"TextChannel","inherits":"GuildChannel#equals","inherited":true,"meta":{"line":230,"file":"GuildChannel.js","path":"src/structures"},"returns":{"types":[[["boolean",""]]]},"params":[{"name":"channel","description":"The channel to compare this channel to","type":{"types":[[["GuildChannel",""]]]}}]},{"id":"TextChannel#toString","name":"toString","description":"When concatenated with a string, this automatically returns the Channel's mention instead of the Channel object.","memberof":"TextChannel","examples":["// Outputs: Hello from #general\rconsole.log(`Hello from ${channel}`);","// Outputs: Hello from #general\rconsole.log('Hello from ' + channel);"],"inherits":"GuildChannel#toString","inherited":true,"meta":{"line":261,"file":"GuildChannel.js","path":"src/structures"},"returns":{"types":[[["string",""]]]},"params":[]}],"properties":[{"id":"TextChannel#topic","name":"topic","description":"The topic of the Text Channel, if there is one.","memberof":"TextChannel","type":{"types":[[["string",""]]]},"meta":{"line":25,"file":"TextChannel.js","path":"src/structures"},"props":[]},{"id":"TextChannel#members","name":"members","description":"A collection of members that can see this channel, mapped by their ID.","memberof":"TextChannel","type":{"types":[[["Collection",".<"],["string",", "],["GuildMember",">"]]]},"meta":{"line":35,"file":"TextChannel.js","path":"src/structures"},"props":[]},{"id":"TextChannel#messages","name":"messages","description":"A Collection containing the messages sent to this channel.","memberof":"TextChannel","type":{"types":[[["Collection",".<"],["string",", "],["Message",">"]]]},"meta":{"line":16,"file":"TextBasedChannel.js","path":"src/structures/interface"},"props":[]},{"id":"TextChannel#lastMessageID","name":"lastMessageID","description":"The ID of the last message in the channel, if one was sent.","memberof":"TextChannel","type":{"types":[[["string",""]]]},"meta":{"line":22,"file":"TextBasedChannel.js","path":"src/structures/interface"},"props":[]},{"id":"TextChannel#typing","name":"typing","description":"Whether or not the typing indicator is being shown in the channel.","memberof":"TextChannel","type":{"types":[[["boolean",""]]]},"meta":{"line":245,"file":"TextBasedChannel.js","path":"src/structures/interface"},"props":[]},{"id":"TextChannel#typingCount","name":"typingCount","description":"Number of times `startTyping` has been called.","memberof":"TextChannel","type":{"types":[[["number",""]]]},"meta":{"line":253,"file":"TextBasedChannel.js","path":"src/structures/interface"},"props":[]},{"id":"TextChannel#guild","name":"guild","description":"The guild the channel is in","memberof":"TextChannel","type":{"types":[[["Guild",""]]]},"meta":{"line":21,"file":"GuildChannel.js","path":"src/structures"},"props":[]},{"id":"TextChannel#name","name":"name","description":"The name of the Guild Channel","memberof":"TextChannel","type":{"types":[[["string",""]]]},"meta":{"line":31,"file":"GuildChannel.js","path":"src/structures"},"props":[]},{"id":"TextChannel#position","name":"position","description":"The position of the channel in the list.","memberof":"TextChannel","type":{"types":[[["number",""]]]},"meta":{"line":37,"file":"GuildChannel.js","path":"src/structures"},"props":[]},{"id":"TextChannel#permissionOverwrites","name":"permissionOverwrites","description":"A map of permission overwrites in this channel for roles and users.","memberof":"TextChannel","type":{"types":[[["Collection",".<"],["string",", "],["PermissionOverwrites",">"]]]},"meta":{"line":43,"file":"GuildChannel.js","path":"src/structures"},"props":[]}],"events":[]},{"id":"User","name":"User","description":"Represents a User on Discord.","meta":{"line":8,"file":"User.js","path":"src/structures"},"methods":[{"id":"User#typingIn","name":"typingIn","description":"Check whether the user is typing in a channel.","memberof":"User","meta":{"line":106,"file":"User.js","path":"src/structures"},"returns":{"types":[[["boolean",""]]]},"params":[{"name":"channel","description":"The channel to check in","type":{"types":[[["ChannelResolvable",""]]]}}]},{"id":"User#typingSinceIn","name":"typingSinceIn","description":"Get the time that the user started typing.","memberof":"User","meta":{"line":116,"file":"User.js","path":"src/structures"},"returns":{"types":[[["Date",""]]]},"params":[{"name":"channel","description":"The channel to get the time in","type":{"types":[[["ChannelResolvable",""]]]}}]},{"id":"User#typingDurationIn","name":"typingDurationIn","description":"Get the amount of time the user has been typing in a channel for (in milliseconds), or -1 if they're not typing.","memberof":"User","meta":{"line":126,"file":"User.js","path":"src/structures"},"returns":{"types":[[["number",""]]]},"params":[{"name":"channel","description":"The channel to get the time in","type":{"types":[[["ChannelResolvable",""]]]}}]},{"id":"User#deleteDM","name":"deleteDM","description":"Deletes a DM Channel (if one exists) between the Client and the User. Resolves with the Channel if successful.","memberof":"User","meta":{"line":135,"file":"User.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["DMChannel",">"]]]},"params":[]},{"id":"User#equals","name":"equals","description":"Checks if the user is equal to another. It compares username, ID, discriminator, status and the game being played.\rIt is recommended to compare equality by using `user.id === user2.id` unless you want to compare all properties.","memberof":"User","meta":{"line":145,"file":"User.js","path":"src/structures"},"returns":{"types":[[["boolean",""]]]},"params":[{"name":"user","description":"The user to compare","type":{"types":[[["User",""]]]}}]},{"id":"User#toString","name":"toString","description":"When concatenated with a string, this automatically concatenates the User's mention instead of the User object.","memberof":"User","examples":["// logs: Hello from <@123456789>!\rconsole.log(`Hello from ${user}!`);"],"meta":{"line":173,"file":"User.js","path":"src/structures"},"returns":{"types":[[["string",""]]]},"params":[]},{"id":"User#sendMessage","name":"sendMessage","description":"Send a message to this channel","memberof":"User","examples":["// send a message\rchannel.sendMessage('hello!')\r .then(message => console.log(`Sent message: ${message.content}`))\r .catch(console.log);"],"meta":{"line":56,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<("],["Message","|"],["Array",".<"],["Message",">)>"]]]},"params":[{"name":"content","description":"The content to send","type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","optional":true,"type":{"types":[[["MessageOptions",""]]]}}],"implements":["TextBasedChannel#sendMessage"]},{"id":"User#sendTTSMessage","name":"sendTTSMessage","description":"Send a text-to-speech message to this channel","memberof":"User","examples":["// send a TTS message\rchannel.sendTTSMessage('hello!')\r .then(message => console.log(`Sent tts message: ${message.content}`))\r .catch(console.log);"],"meta":{"line":71,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<("],["Message","|"],["Array",".<"],["Message",">)>"]]]},"params":[{"name":"content","description":"The content to send","type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","optional":true,"type":{"types":[[["MessageOptions",""]]]}}],"implements":["TextBasedChannel#sendTTSMessage"]},{"id":"User#sendFile","name":"sendFile","description":"Send a file to this channel","memberof":"User","meta":{"line":84,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<"],["Message",">"]]]},"params":[{"name":"attachment","description":"The file to send","type":{"types":[[["FileResolvable",""]]]}},{"name":"fileName","description":"The name and extension of the file","optional":true,"type":{"types":[[["string",""]]]}},{"name":"content","description":"Text message to send with the attachment","optional":true,"type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","optional":true,"type":{"types":[[["MessageOptions",""]]]}}],"implements":["TextBasedChannel#sendFile"]},{"id":"User#sendCode","name":"sendCode","description":"Send a code block to this channel","memberof":"User","meta":{"line":111,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<("],["Message","|"],["Array",".<"],["Message",">)>"]]]},"params":[{"name":"lang","description":"Language for the code block","type":{"types":[[["string",""]]]}},{"name":"content","description":"Content of the code block","type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","type":{"types":[[["MessageOptions",""]]]}}],"implements":["TextBasedChannel#sendCode"]}],"properties":[{"id":"User#client","name":"client","description":"The Client that created the instance of the the User.","memberof":"User","type":{"types":[[["Client",""]]]},"meta":{"line":14,"file":"User.js","path":"src/structures"},"props":[]},{"id":"User#id","name":"id","description":"The ID of the User","memberof":"User","type":{"types":[[["string",""]]]},"meta":{"line":25,"file":"User.js","path":"src/structures"},"props":[]},{"id":"User#username","name":"username","description":"The username of the User","memberof":"User","type":{"types":[[["string",""]]]},"meta":{"line":31,"file":"User.js","path":"src/structures"},"props":[]},{"id":"User#discriminator","name":"discriminator","description":"A discriminator based on username for the User","memberof":"User","type":{"types":[[["string",""]]]},"meta":{"line":37,"file":"User.js","path":"src/structures"},"props":[]},{"id":"User#avatar","name":"avatar","description":"The ID of the user's avatar","memberof":"User","type":{"types":[[["string",""]]]},"meta":{"line":43,"file":"User.js","path":"src/structures"},"props":[]},{"id":"User#bot","name":"bot","description":"Whether or not the User is a Bot.","memberof":"User","type":{"types":[[["boolean",""]]]},"meta":{"line":49,"file":"User.js","path":"src/structures"},"props":[]},{"id":"User#status","name":"status","description":"The status of the user:\r\r* **`online`** - user is online\r* **`offline`** - user is offline\r* **`idle`** - user is AFK","memberof":"User","type":{"types":[[["string",""]]]},"meta":{"line":59,"file":"User.js","path":"src/structures"},"props":[]},{"id":"User#game","name":"game","description":"The game that the user is playing, `null` if they aren't playing a game.","memberof":"User","type":{"types":[[["Game",""]]]},"meta":{"line":73,"file":"User.js","path":"src/structures"},"props":[]},{"id":"User#creationDate","name":"creationDate","description":"The time the user was created","memberof":"User","type":{"types":[[["Date",""]]]},"meta":{"line":87,"file":"User.js","path":"src/structures"},"props":[]},{"id":"User#avatarURL","name":"avatarURL","description":"A link to the user's avatar (if they have one, otherwise null)","memberof":"User","type":{"types":[[["string",""]]]},"meta":{"line":96,"file":"User.js","path":"src/structures"},"props":[]}],"events":[]},{"id":"VoiceChannel","name":"VoiceChannel","description":"Represents a Server Voice Channel on Discord.","meta":{"line":8,"file":"VoiceChannel.js","path":"src/structures"},"extends":["GuildChannel"],"methods":[{"id":"VoiceChannel#setBitrate","name":"setBitrate","description":"Sets the bitrate of the channel","memberof":"VoiceChannel","examples":["// set the bitrate of a voice channel\rvoiceChannel.setBitrate(48000)\r .then(vc => console.log(`Set bitrate to ${vc.bitrate} for ${vc.name}`))\r .catch(console.log);"],"meta":{"line":58,"file":"VoiceChannel.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["VoiceChannel",">"]]]},"params":[{"name":"bitrate","description":"The new bitrate","type":{"types":[[["number",""]]]}}]},{"id":"VoiceChannel#join","name":"join","description":"Attempts to join this Voice Channel","memberof":"VoiceChannel","examples":["// join a voice channel\rvoiceChannel.join()\r .then(connection => console.log('Connected!'))\r .catch(console.log);"],"meta":{"line":71,"file":"VoiceChannel.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["VoiceConnection",">"]]]},"params":[]},{"id":"VoiceChannel#leave","name":"leave","description":"Leaves this voice channel","memberof":"VoiceChannel","examples":["// leave a voice channel\rvoiceChannel.leave();"],"meta":{"line":81,"file":"VoiceChannel.js","path":"src/structures"},"returns":{"types":[[["null",""]]]},"params":[]},{"id":"VoiceChannel#permissionsFor","name":"permissionsFor","description":"Gets the overall set of permissions for a user in this channel, taking into account roles and permission\roverwrites.","memberof":"VoiceChannel","inherits":"GuildChannel#permissionsFor","inherited":true,"meta":{"line":57,"file":"GuildChannel.js","path":"src/structures"},"returns":{"types":[[["EvaluatedPermissions",""]]]},"params":[{"name":"member","description":"The user that you want to obtain the overall permissions for","type":{"types":[[["GuildMemberResolvable",""]]]}}]},{"id":"VoiceChannel#overwritePermissions","name":"overwritePermissions","description":"Overwrites the permissions for a user or role in this channel.","memberof":"VoiceChannel","examples":["// overwrite permissions for a message author\rmessage.channel.overwritePermissions(message.author, {\r SEND_MESSAGES: false\r})\r.then(() => console.log('Done!'))\r.catch(console.log);"],"inherits":"GuildChannel#overwritePermissions","inherited":true,"meta":{"line":125,"file":"GuildChannel.js","path":"src/structures"},"returns":{"types":[[["Promise",""]]]},"params":[{"name":"userOrRole","description":"The user or role to update","type":{"types":[[["Role",""]],[["UserResolvable",""]]]}},{"name":"options","description":"The configuration for the update","type":{"types":[[["PermissionOverwriteOptions",""]]]}}]},{"id":"VoiceChannel#setName","name":"setName","description":"Set a new name for the Guild Channel","memberof":"VoiceChannel","examples":["// set a new channel name\rchannel.setName('not_general')\r .then(newChannel => console.log(`Channel's new name is ${newChannel.name}`))\r .catch(console.log);"],"inherits":"GuildChannel#setName","inherited":true,"meta":{"line":175,"file":"GuildChannel.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["GuildChannel",">"]]]},"params":[{"name":"name","description":"The new name for the guild channel","type":{"types":[[["string",""]]]}}]},{"id":"VoiceChannel#setPosition","name":"setPosition","description":"Set a new position for the Guild Channel","memberof":"VoiceChannel","examples":["// set a new channel position\rchannel.setPosition(2)\r .then(newChannel => console.log(`Channel's new position is ${newChannel.position}`))\r .catch(console.log);"],"inherits":"GuildChannel#setPosition","inherited":true,"meta":{"line":189,"file":"GuildChannel.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["GuildChannel",">"]]]},"params":[{"name":"position","description":"The new position for the guild channel","type":{"types":[[["number",""]]]}}]},{"id":"VoiceChannel#setTopic","name":"setTopic","description":"Set a new topic for the Guild Channel","memberof":"VoiceChannel","examples":["// set a new channel topic\rchannel.setTopic('needs more rate limiting')\r .then(newChannel => console.log(`Channel's new topic is ${newChannel.topic}`))\r .catch(console.log);"],"inherits":"GuildChannel#setTopic","inherited":true,"meta":{"line":203,"file":"GuildChannel.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["GuildChannel",">"]]]},"params":[{"name":"topic","description":"The new topic for the guild channel","type":{"types":[[["string",""]]]}}]},{"id":"VoiceChannel#createInvite","name":"createInvite","description":"Create an invite to this Guild Channel","memberof":"VoiceChannel","inherits":"GuildChannel#createInvite","inherited":true,"meta":{"line":220,"file":"GuildChannel.js","path":"src/structures"},"returns":{"types":[[["Promise",".<"],["Invite",">"]]]},"params":[{"name":"options","description":"The options for the invite","optional":true,"type":{"types":[[["InviteOptions",""]]]}}]},{"id":"VoiceChannel#equals","name":"equals","description":"Checks if this channel has the same type, topic, position, name, overwrites and ID as another channel.\rIn most cases, a simple `channel.id === channel2.id` will do, and is much faster too.","memberof":"VoiceChannel","inherits":"GuildChannel#equals","inherited":true,"meta":{"line":230,"file":"GuildChannel.js","path":"src/structures"},"returns":{"types":[[["boolean",""]]]},"params":[{"name":"channel","description":"The channel to compare this channel to","type":{"types":[[["GuildChannel",""]]]}}]},{"id":"VoiceChannel#toString","name":"toString","description":"When concatenated with a string, this automatically returns the Channel's mention instead of the Channel object.","memberof":"VoiceChannel","examples":["// Outputs: Hello from #general\rconsole.log(`Hello from ${channel}`);","// Outputs: Hello from #general\rconsole.log('Hello from ' + channel);"],"inherits":"GuildChannel#toString","inherited":true,"meta":{"line":261,"file":"GuildChannel.js","path":"src/structures"},"returns":{"types":[[["string",""]]]},"params":[]}],"properties":[{"id":"VoiceChannel#members","name":"members","description":"The members in this Voice Channel.","memberof":"VoiceChannel","type":{"types":[[["Collection",".<"],["string",", "],["GuildMember",">"]]]},"meta":{"line":16,"file":"VoiceChannel.js","path":"src/structures"},"props":[]},{"id":"VoiceChannel#bitrate","name":"bitrate","description":"The bitrate of this voice channel","memberof":"VoiceChannel","type":{"types":[[["number",""]]]},"meta":{"line":28,"file":"VoiceChannel.js","path":"src/structures"},"props":[]},{"id":"VoiceChannel#userLimit","name":"userLimit","description":"The maximum amount of users allowed in this channel - 0 means unlimited.","memberof":"VoiceChannel","type":{"types":[[["number",""]]]},"meta":{"line":34,"file":"VoiceChannel.js","path":"src/structures"},"props":[]},{"id":"VoiceChannel#connection","name":"connection","description":"The voice connection for this voice channel, if the client is connected","memberof":"VoiceChannel","type":{"types":[[["VoiceConnection",""]]]},"meta":{"line":42,"file":"VoiceChannel.js","path":"src/structures"},"props":[]},{"id":"VoiceChannel#guild","name":"guild","description":"The guild the channel is in","memberof":"VoiceChannel","type":{"types":[[["Guild",""]]]},"meta":{"line":21,"file":"GuildChannel.js","path":"src/structures"},"props":[]},{"id":"VoiceChannel#name","name":"name","description":"The name of the Guild Channel","memberof":"VoiceChannel","type":{"types":[[["string",""]]]},"meta":{"line":31,"file":"GuildChannel.js","path":"src/structures"},"props":[]},{"id":"VoiceChannel#position","name":"position","description":"The position of the channel in the list.","memberof":"VoiceChannel","type":{"types":[[["number",""]]]},"meta":{"line":37,"file":"GuildChannel.js","path":"src/structures"},"props":[]},{"id":"VoiceChannel#permissionOverwrites","name":"permissionOverwrites","description":"A map of permission overwrites in this channel for roles and users.","memberof":"VoiceChannel","type":{"types":[[["Collection",".<"],["string",", "],["PermissionOverwrites",">"]]]},"meta":{"line":43,"file":"GuildChannel.js","path":"src/structures"},"props":[]}],"events":[]},{"id":"Collection","name":"Collection","description":"A utility class to help make it easier to access the data stores","meta":{"line":5,"file":"Collection.js","path":"src/util"},"extends":["Map"],"methods":[{"id":"Collection#array","name":"array","description":"Returns an ordered array of the values of this collection.","memberof":"Collection","examples":["// identical to:\rArray.from(collection.values());"],"meta":{"line":13,"file":"Collection.js","path":"src/util"},"returns":{"types":[[["Array",""]]]},"params":[]},{"id":"Collection#keyArray","name":"keyArray","description":"Returns an ordered array of the keys of this collection.","memberof":"Collection","examples":["// identical to:\rArray.from(collection.keys());"],"meta":{"line":24,"file":"Collection.js","path":"src/util"},"returns":{"types":[[["Array",""]]]},"params":[]},{"id":"Collection#first","name":"first","description":"Returns the first item in this collection.","memberof":"Collection","meta":{"line":32,"file":"Collection.js","path":"src/util"},"returns":{"types":[["*",""]]},"params":[]},{"id":"Collection#firstKey","name":"firstKey","description":"Returns the first key in this collection.","memberof":"Collection","meta":{"line":40,"file":"Collection.js","path":"src/util"},"returns":{"types":[["*",""]]},"params":[]},{"id":"Collection#last","name":"last","description":"Returns the last item in this collection. This is a relatively slow operation,\rsince an array copy of the values must be made to find the last element.","memberof":"Collection","meta":{"line":49,"file":"Collection.js","path":"src/util"},"returns":{"types":[["*",""]]},"params":[]},{"id":"Collection#lastKey","name":"lastKey","description":"Returns the last key in this collection. This is a relatively slow operation,\rsince an array copy of the keys must be made to find the last element.","memberof":"Collection","meta":{"line":59,"file":"Collection.js","path":"src/util"},"returns":{"types":[["*",""]]},"params":[]},{"id":"Collection#random","name":"random","description":"Returns a random item from this collection. This is a relatively slow operation,\rsince an array copy of the values must be made to find a random element.","memberof":"Collection","meta":{"line":69,"file":"Collection.js","path":"src/util"},"returns":{"types":[["*",""]]},"params":[]},{"id":"Collection#randomKey","name":"randomKey","description":"Returns a random key from this collection. This is a relatively slow operation,\rsince an array copy of the keys must be made to find a random element.","memberof":"Collection","meta":{"line":79,"file":"Collection.js","path":"src/util"},"returns":{"types":[["*",""]]},"params":[]},{"id":"Collection#findAll","name":"findAll","description":"Returns an array of items where `item[prop] === value` of the collection","memberof":"Collection","examples":["collection.findAll('username', 'Bob');"],"meta":{"line":92,"file":"Collection.js","path":"src/util"},"returns":{"types":[[["array",""]]]},"params":[{"name":"prop","description":"The property to test against","type":{"types":[[["string",""]]]}},{"name":"value","description":"The expected value","type":{"types":[["*",""]]}}]},{"id":"Collection#find","name":"find","description":"Returns a single item where `item[prop] === value`, or the given function returns `true`.\rIn the latter case, this is identical to\r[Array.find()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find).","memberof":"Collection","examples":["collection.find('username', 'Bob');","collection.find(val => val.username === 'Bob');"],"meta":{"line":114,"file":"Collection.js","path":"src/util"},"returns":{"types":[["*",""]]},"params":[{"name":"propOrFn","description":"The property to test against, or the function to test with","type":{"types":[[["string",""]],[["function",""]]]}},{"name":"value","description":"The expected value - only applicable and required if using a property for the first argument","optional":true,"type":{"types":[["*",""]]}}]},{"id":"Collection#findKey","name":"findKey","description":"Returns the key of the item where `item[prop] === value`, or the given function returns `true`.\rIn the latter case, this is identical to\r[Array.findIndex()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex).","memberof":"Collection","examples":["collection.findKey('username', 'Bob');","collection.findKey(val => val.username === 'Bob');"],"meta":{"line":145,"file":"Collection.js","path":"src/util"},"returns":{"types":[["*",""]]},"params":[{"name":"propOrFn","description":"The property to test against, or the function to test with","type":{"types":[[["string",""]],[["function",""]]]}},{"name":"value","description":"The expected value - only applicable and required if using a property for the first argument","optional":true,"type":{"types":[["*",""]]}}]},{"id":"Collection#exists","name":"exists","description":"Returns true if the collection has an item where `item[prop] === value`","memberof":"Collection","examples":["if (collection.exists('username', 'Bob')) {\r console.log('user here!');\r}"],"meta":{"line":172,"file":"Collection.js","path":"src/util"},"returns":{"types":[[["boolean",""]]]},"params":[{"name":"prop","description":"The property to test against","type":{"types":[[["string",""]]]}},{"name":"value","description":"The expected value","type":{"types":[["*",""]]}}]},{"id":"Collection#filter","name":"filter","description":"Identical to\r[Array.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),\rbut returns a Collection instead of an Array.","memberof":"Collection","meta":{"line":184,"file":"Collection.js","path":"src/util"},"returns":{"types":[[["Collection",""]]]},"params":[{"name":"fn","description":"Function used to test (should return a boolean)","type":{"types":[[["function",""]]]}},{"name":"thisArg","description":"Value to use as `this` when executing function","optional":true,"type":{"types":[[["Object",""]]]}}]},{"id":"Collection#map","name":"map","description":"Identical to\r[Array.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map).","memberof":"Collection","meta":{"line":200,"file":"Collection.js","path":"src/util"},"returns":{"types":[[["array",""]]]},"params":[{"name":"fn","description":"Function that produces an element of the new array, taking three arguments","type":{"types":[[["function",""]]]}},{"name":"thisArg","description":"Value to use as `this` when executing function","optional":true,"type":{"types":[["*",""]]}}]},{"id":"Collection#some","name":"some","description":"Identical to\r[Array.some()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some).","memberof":"Collection","meta":{"line":215,"file":"Collection.js","path":"src/util"},"returns":{"types":[[["boolean",""]]]},"params":[{"name":"fn","description":"Function used to test (should return a boolean)","type":{"types":[[["function",""]]]}},{"name":"thisArg","description":"Value to use as `this` when executing function","optional":true,"type":{"types":[[["Object",""]]]}}]},{"id":"Collection#every","name":"every","description":"Identical to\r[Array.every()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every).","memberof":"Collection","meta":{"line":230,"file":"Collection.js","path":"src/util"},"returns":{"types":[[["boolean",""]]]},"params":[{"name":"fn","description":"Function used to test (should return a boolean)","type":{"types":[[["function",""]]]}},{"name":"thisArg","description":"Value to use as `this` when executing function","optional":true,"type":{"types":[[["Object",""]]]}}]},{"id":"Collection#reduce","name":"reduce","description":"Identical to\r[Array.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce).","memberof":"Collection","meta":{"line":245,"file":"Collection.js","path":"src/util"},"returns":{"types":[["*",""]]},"params":[{"name":"fn","description":"Function used to reduce","type":{"types":[[["function",""]]]}},{"name":"startVal","description":"The starting value","optional":true,"type":{"types":[["*",""]]}}]},{"id":"Collection#deleteAll","name":"deleteAll","description":"If the items in this collection have a delete method (e.g. messages), invoke\rthe delete method. Returns an array of promises","memberof":"Collection","meta":{"line":256,"file":"Collection.js","path":"src/util"},"returns":{"types":[[["Array",".<"],["Promise",">"]]]},"params":[]}],"properties":[],"events":[]}],"interfaces":[{"id":"TextBasedChannel","name":"TextBasedChannel","description":"Interface for classes that have text-channel-like features","meta":{"line":10,"file":"TextBasedChannel.js","path":"src/structures/interface"},"methods":[{"id":"TextBasedChannel#sendMessage","name":"sendMessage","description":"Send a message to this channel","memberof":"TextBasedChannel","examples":["// send a message\rchannel.sendMessage('hello!')\r .then(message => console.log(`Sent message: ${message.content}`))\r .catch(console.log);"],"meta":{"line":56,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<("],["Message","|"],["Array",".<"],["Message",">)>"]]]},"params":[{"name":"content","description":"The content to send","type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","optional":true,"type":{"types":[[["MessageOptions",""]]]}}]},{"id":"TextBasedChannel#sendTTSMessage","name":"sendTTSMessage","description":"Send a text-to-speech message to this channel","memberof":"TextBasedChannel","examples":["// send a TTS message\rchannel.sendTTSMessage('hello!')\r .then(message => console.log(`Sent tts message: ${message.content}`))\r .catch(console.log);"],"meta":{"line":71,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<("],["Message","|"],["Array",".<"],["Message",">)>"]]]},"params":[{"name":"content","description":"The content to send","type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","optional":true,"type":{"types":[[["MessageOptions",""]]]}}]},{"id":"TextBasedChannel#sendFile","name":"sendFile","description":"Send a file to this channel","memberof":"TextBasedChannel","meta":{"line":84,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<"],["Message",">"]]]},"params":[{"name":"attachment","description":"The file to send","type":{"types":[[["FileResolvable",""]]]}},{"name":"fileName","description":"The name and extension of the file","optional":true,"type":{"types":[[["string",""]]]}},{"name":"content","description":"Text message to send with the attachment","optional":true,"type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","optional":true,"type":{"types":[[["MessageOptions",""]]]}}]},{"id":"TextBasedChannel#sendCode","name":"sendCode","description":"Send a code block to this channel","memberof":"TextBasedChannel","meta":{"line":111,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<("],["Message","|"],["Array",".<"],["Message",">)>"]]]},"params":[{"name":"lang","description":"Language for the code block","type":{"types":[[["string",""]]]}},{"name":"content","description":"Content of the code block","type":{"types":[[["StringResolvable",""]]]}},{"name":"options","description":"The options to provide","type":{"types":[[["MessageOptions",""]]]}}]},{"id":"TextBasedChannel#fetchMessage","name":"fetchMessage","description":"Gets a single message from this channel, regardless of it being cached or not.","memberof":"TextBasedChannel","examples":["// get message\rchannel.fetchMessage('99539446449315840')\r .then(message => console.log(message.content))\r .catch(console.error);"],"meta":{"line":131,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<"],["Message",">"]]]},"params":[{"name":"messageID","description":"The ID of the message to get","type":{"types":[[["string",""]]]}}]},{"id":"TextBasedChannel#fetchMessages","name":"fetchMessages","description":"Gets the past messages sent in this channel. Resolves with a Collection mapping message ID's to Message objects.","memberof":"TextBasedChannel","examples":["// get messages\rchannel.fetchMessages({limit: 10})\r .then(messages => console.log(`Received ${messages.size} messages`))\r .catch(console.log);"],"meta":{"line":163,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<"],["Collection",".<"],["string",", "],["Message",">>"]]]},"params":[{"name":"options","description":"The query parameters to pass in","optional":true,"type":{"types":[[["ChannelLogsQueryOptions",""]]]}}]},{"id":"TextBasedChannel#fetchPinnedMessages","name":"fetchPinnedMessages","description":"Fetches the pinned messages of this Channel and returns a Collection of them.","memberof":"TextBasedChannel","meta":{"line":181,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<"],["Collection",".<"],["string",", "],["Message",">>"]]]},"params":[]},{"id":"TextBasedChannel#startTyping","name":"startTyping","description":"Starts a typing indicator in the channel.","memberof":"TextBasedChannel","examples":["// start typing in a channel\rchannel.startTyping();"],"meta":{"line":202,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["null",""]]]},"params":[{"name":"count","description":"The number of times startTyping should be considered to have been called","optional":true,"type":{"types":[[["number",""]]]}}]},{"id":"TextBasedChannel#stopTyping","name":"stopTyping","description":"Stops the typing indicator in the channel.\rThe indicator will only stop if this is called as many times as startTyping().\rIt can take a few seconds for the Client User to stop typing.","memberof":"TextBasedChannel","examples":["// stop typing in a channel\rchannel.stopTyping();","// force typing to fully stop in a channel\rchannel.stopTyping(true);"],"meta":{"line":230,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["null",""]]]},"params":[{"name":"force","description":"Whether or not to reset the call count and force the indicator to stop","optional":true,"type":{"types":[[["boolean",""]]]}}]},{"id":"TextBasedChannel#createCollector","name":"createCollector","description":"Creates a Message Collector","memberof":"TextBasedChannel","examples":["// create a message collector\rconst collector = channel.createCollector(\r m => m.content.includes('discord'),\r { time: 15000 }\r);\rcollector.on('message', m => console.log(`Collected ${m.content}`));\rcollector.on('end', collected => console.log(`Collected ${collected.size} items`));"],"meta":{"line":272,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["MessageCollector",""]]]},"params":[{"name":"filter","description":"The filter to create the collector with","type":{"types":[[["CollectorFilterFunction",""]]]}},{"name":"options","description":"The options to pass to the collector","optional":true,"type":{"types":[[["CollectorOptions",""]]]}}]},{"id":"TextBasedChannel#awaitMessages","name":"awaitMessages","description":"Similar to createCollector but in Promise form. Resolves with a Collection of messages that pass the specified\rfilter.","memberof":"TextBasedChannel","examples":["// await !vote messages\rconst filter = m => m.content.startsWith('!vote');\r// errors: ['time'] treats ending because of the time limit as an error\rchannel.awaitMessages(filter, { max: 4, time: 60000, errors: ['time'] })\r .then(collected => console.log(collected.size))\r .catch(collected => console.log(`After a minute, only ${collected.size} out of 4 voted.`));"],"meta":{"line":296,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Promise",".<"],["Collection",".<"],["string",", "],["Message",">>"]]]},"params":[{"name":"filter","description":"The filter function to use","type":{"types":[[["CollectorFilterFunction",""]]]}},{"name":"options","description":"Optional options to pass to the internal collector","optional":true,"type":{"types":[[["AwaitMessagesOptions",""]]]}}]},{"id":"TextBasedChannel#bulkDelete","name":"bulkDelete","description":"Bulk delete a given Collection or Array of messages in one go. Returns the deleted messages after.\rOnly OAuth Bot accounts may use this method.","memberof":"TextBasedChannel","meta":{"line":315,"file":"TextBasedChannel.js","path":"src/structures/interface"},"returns":{"types":[[["Collection",".<"],["string",", "],["Message",">"]]]},"params":[{"name":"messages","description":"The messages to delete","type":{"types":[[["Collection",".<"],["string",", "],["Message",">"]],[["Array",".<"],["Message",">"]]]}}]}],"properties":[{"id":"TextBasedChannel#messages","name":"messages","description":"A Collection containing the messages sent to this channel.","memberof":"TextBasedChannel","type":{"types":[[["Collection",".<"],["string",", "],["Message",">"]]]},"meta":{"line":16,"file":"TextBasedChannel.js","path":"src/structures/interface"},"props":[]},{"id":"TextBasedChannel#lastMessageID","name":"lastMessageID","description":"The ID of the last message in the channel, if one was sent.","memberof":"TextBasedChannel","type":{"types":[[["string",""]]]},"meta":{"line":22,"file":"TextBasedChannel.js","path":"src/structures/interface"},"props":[]},{"id":"TextBasedChannel#typing","name":"typing","description":"Whether or not the typing indicator is being shown in the channel.","memberof":"TextBasedChannel","type":{"types":[[["boolean",""]]]},"meta":{"line":245,"file":"TextBasedChannel.js","path":"src/structures/interface"},"props":[]},{"id":"TextBasedChannel#typingCount","name":"typingCount","description":"Number of times `startTyping` has been called.","memberof":"TextBasedChannel","type":{"types":[[["number",""]]]},"meta":{"line":253,"file":"TextBasedChannel.js","path":"src/structures/interface"},"props":[]}],"events":[]}],"typedefs":[{"id":"UserResolvable","name":"UserResolvable","description":"Data that resolves to give a User object. This can be:\r* A User object\r* A User ID\r* A Message (resolves to the message author)\r* A Guild (owner of the guild)\r* A Guild Member","type":{"types":[[["User",""]],[["string",""]],[["Message",""]],[["Guild",""]],[["GuildMember",""]]]},"meta":{"line":25,"file":"ClientDataResolver.js","path":"src/client"},"properties":[]},{"id":"GuildResolvable","name":"GuildResolvable","description":"Data that resolves to give a Guild object. This can be:\r* A Guild object","type":{"types":[[["Guild",""]]]},"meta":{"line":62,"file":"ClientDataResolver.js","path":"src/client"},"properties":[]},{"id":"GuildMemberResolvable","name":"GuildMemberResolvable","description":"Data that resolves to give a GuildMember object. This can be:\r* A GuildMember object\r* A User object","type":{"types":[[["Guild",""]]]},"meta":{"line":79,"file":"ClientDataResolver.js","path":"src/client"},"properties":[]},{"id":"Base64Resolvable","name":"Base64Resolvable","description":"Data that resolves to give a Base64 string, typically for image uploading. This can be:\r* A Buffer\r* A Base64 string","type":{"types":[[["Buffer",""]],[["string",""]]]},"meta":{"line":102,"file":"ClientDataResolver.js","path":"src/client"},"properties":[]},{"id":"ChannelResolvable","name":"ChannelResolvable","description":"Data that can be resolved to give a Channel. This can be:\r* An instance of a Channel\r* An instance of a Message (the channel the message was sent in)\r* An instance of a Guild (the #general channel)\r* An ID of a Channel","type":{"types":[[["Channel",""]],[["Guild",""]],[["Message",""]],[["string",""]]]},"meta":{"line":119,"file":"ClientDataResolver.js","path":"src/client"},"properties":[]},{"id":"PermissionResolvable","name":"PermissionResolvable","description":"Data that can be resolved to give a permission number. This can be:\r* A string\r* A permission number\r\rPossible strings:\r```js\r[\r \"CREATE_INSTANT_INVITE\",\r \"KICK_MEMBERS\",\r \"BAN_MEMBERS\",\r \"ADMINISTRATOR\",\r \"MANAGE_CHANNELS\",\r \"MANAGE_GUILD\",\r \"READ_MESSAGES\",\r \"SEND_MESSAGES\",\r \"SEND_TTS_MESSAGES\",\r \"MANAGE_MESSAGES\",\r \"EMBED_LINKS\",\r \"ATTACH_FILES\",\r \"READ_MESSAGE_HISTORY\",\r \"MENTION_EVERYONE\",\r \"EXTERNAL_EMOJIS\", // use external emojis\r \"CONNECT\", // connect to voice\r \"SPEAK\", // speak on voice\r \"MUTE_MEMBERS\", // globally mute members on voice\r \"DEAFEN_MEMBERS\", // globally deafen members on voice\r \"MOVE_MEMBERS\", // move member's voice channels\r \"USE_VAD\", // use voice activity detection\r \"CHANGE_NICKNAME\",\r \"MANAGE_NICKNAMES\", // change nicknames of others\r \"MANAGE_ROLES_OR_PERMISSIONS\"\r]\r```","type":{"types":[[["string",""]],[["number",""]]]},"meta":{"line":141,"file":"ClientDataResolver.js","path":"src/client"},"properties":[]},{"id":"StringResolvable","name":"StringResolvable","description":"Data that can be resolved to give a string. This can be:\r* A string\r* An Array (joined with a new line delimiter to give a string)\r* Any value","type":{"types":[[["string",""]],[["Array",""]],["*",""]]},"meta":{"line":189,"file":"ClientDataResolver.js","path":"src/client"},"properties":[]},{"id":"FileResolvable","name":"FileResolvable","description":"Data that can be resolved to give a Buffer. This can be:\r* A Buffer\r* The path to a local file\r* A URL","type":{"types":[[["string",""]],[["Buffer",""]]]},"meta":{"line":208,"file":"ClientDataResolver.js","path":"src/client"},"properties":[]},{"id":"StreamOptions","name":"StreamOptions","description":"Options that can be passed to stream-playing methods:","type":{"types":[[["Object",""]]]},"meta":{"line":214,"file":"VoiceConnection.js","path":"src/client/voice"},"properties":[{"name":"seek","description":"The time to seek to","optional":true,"type":{"types":[[["number",""]]]}},{"name":"volume","description":"The volume to play at","optional":true,"type":{"types":[[["number",""]]]}},{"name":"passes","description":"How many times to send the voice packet to reduce packet loss","optional":true,"type":{"types":[[["number",""]]]}}]},{"id":"PermissionOverwriteOptions","name":"PermissionOverwriteOptions","description":"An object mapping permission flags to `true` (enabled) or `false` (disabled)\r```js\r{\r 'SEND_MESSAGES': true,\r 'ATTACH_FILES': false,\r}\r```","type":{"types":[[["Object",""]]]},"meta":{"line":101,"file":"GuildChannel.js","path":"src/structures"},"properties":[]},{"id":"InviteOptions","name":"InviteOptions","description":"Options given when creating a Guild Channel Invite","type":{"types":[[["Object",""]]]},"meta":{"line":207,"file":"GuildChannel.js","path":"src/structures"},"properties":[{"name":"temporary","description":"Whether the invite should kick users after 24hrs if they are not given a role","optional":true,"type":{"types":[[["boolean",""]]]}},{"name":"maxAge","description":"Time in seconds the invite expires in","optional":true,"type":{"types":[[["number",""]]]}},{"name":"maxUses","description":"Maximum amount of uses for this invite","optional":true,"type":{"types":[[["maxUses",""]]]}}]},{"id":"MessageOptions","name":"MessageOptions","description":"Options that can be passed into sendMessage, sendTTSMessage, sendFile, sendCode, or Message.reply","type":{"types":[[["Object",""]]]},"meta":{"line":25,"file":"TextBasedChannel.js","path":"src/structures/interface"},"properties":[{"name":"tts","description":"Whether or not the message should be spoken aloud","optional":true,"type":{"types":[[["boolean",""]]]}},{"name":"nonce","description":"The nonce for the message","optional":true,"type":{"types":[[["string",""]]]}},{"name":"disable_everyone","description":"Whether or not @everyone and @here\rshould be replaced with plain-text","optional":true,"type":{"types":[[["boolean",""]]]}},{"name":"split","description":"Whether or not the message should be split into multiple messages if\rit exceeds the character limit. If an object is provided, these are the options for splitting the message.","optional":true,"type":{"types":[[["boolean",""]],[["SplitOptions",""]]]}}]},{"id":"SplitOptions","name":"SplitOptions","description":"Options for splitting a message","type":{"types":[[["Object",""]]]},"meta":{"line":36,"file":"TextBasedChannel.js","path":"src/structures/interface"},"properties":[{"name":"maxLength","description":"Maximum character length per message piece","optional":true,"type":{"types":[[["number",""]]]}},{"name":"char","description":"Character to split the message with","optional":true,"type":{"types":[[["string",""]]]}},{"name":"prepend","description":"Text to prepend to each middle piece","optional":true,"type":{"types":[[["string",""]]]}},{"name":"append","description":"Text to append to each middle piece","optional":true,"type":{"types":[[["string",""]]]}}]},{"id":"ChannelLogsQueryOptions","name":"ChannelLogsQueryOptions","description":"The parameters to pass in when requesting previous messages from a channel. `around`, `before` and\r`after` are mutually exclusive. All the parameters are optional.","type":{"types":[[["Object",""]]]},"meta":{"line":143,"file":"TextBasedChannel.js","path":"src/structures/interface"},"properties":[{"name":"limit","description":"Number of messages to acquire","optional":true,"type":{"types":[[["number",""]]]}},{"name":"before","description":"ID of a message to get the messages that were posted before it","optional":true,"type":{"types":[[["string",""]]]}},{"name":"after","description":"ID of a message to get the messages that were posted after it","optional":true,"type":{"types":[[["string",""]]]}},{"name":"around","description":"ID of a message to get the messages that were posted around it","optional":true,"type":{"types":[[["string",""]]]}}]},{"id":"AwaitMessagesOptions","name":"AwaitMessagesOptions","description":"An object containing the same properties as CollectorOptions, but a few more:","type":{"types":[[["CollectorOptions",""]]]},"meta":{"line":276,"file":"TextBasedChannel.js","path":"src/structures/interface"},"properties":[{"name":"errors","description":"Stop/end reasons that cause the promise to reject","optional":true,"type":{"types":[[["Array",".<"],["string",">"]]]}}]},{"id":"CollectorFilterFunction","name":"CollectorFilterFunction","description":"A function that takes a Message object and a MessageCollector and returns a boolean.\r```js\rfunction(message, collector) {\r if (message.content.includes('discord')) {\r return true; // passed the filter test\r }\r return false; // failed the filter test\r}\r```","type":{"types":[[["function",""]]]},"meta":{"line":9,"file":"MessageCollector.js","path":"src/structures"},"properties":[]},{"id":"CollectorOptions","name":"CollectorOptions","description":"An object containing options used to configure a MessageCollector. All properties are optional.","type":{"types":[[["Object",""]]]},"meta":{"line":22,"file":"MessageCollector.js","path":"src/structures"},"properties":[{"name":"time","description":"Duration for the collector in milliseconds","optional":true,"type":{"types":[[["number",""]]]}},{"name":"max","description":"Maximum number of messages to handle","optional":true,"type":{"types":[[["number",""]]]}}]},{"id":"Game","name":"Game","description":"Represents data about a Game","type":{"types":[[["object",""]]]},"meta":{"line":61,"file":"User.js","path":"src/structures"},"properties":[{"name":"name","description":"the name of the game being played.","type":{"types":[[["string",""]]]}},{"name":"url","description":"the URL of the stream, if the game is being streamed.","optional":true,"type":{"types":[[["string",""]]]}},{"name":"type","description":"if being streamed, this is `1`.","optional":true,"type":{"types":[[["number",""]]]}}]},{"id":"ClientOptions","name":"ClientOptions","description":"Options for a Client.","type":{"types":[[["Object",""]]]},"meta":{"line":1,"file":"Constants.js","path":"src/util"},"properties":[{"name":"api_request_method","description":"'sequential' or 'burst'. Sequential executes all requests in\rthe order they are triggered, whereas burst runs multiple at a time, and doesn't guarantee a particular order.","optional":true,"type":{"types":[[["string",""]]]}},{"name":"shard_id","description":"The ID of this shard","optional":true,"type":{"types":[[["number",""]]]}},{"name":"shard_count","description":"The number of shards","optional":true,"type":{"types":[[["number",""]]]}},{"name":"max_message_cache","description":"Number of messages to cache per channel","optional":true,"type":{"types":[[["number",""]]]}},{"name":"message_cache_lifetime","description":"How long until a message should be uncached by the message sweeping\r(in seconds, 0 for forever)","optional":true,"type":{"types":[[["number",""]]]}},{"name":"message_sweep_interval","description":"How frequently to remove messages from the cache that are older than\rthe max message lifetime (in seconds, 0 for never)","optional":true,"type":{"types":[[["number",""]]]}},{"name":"fetch_all_members","description":"Whether to cache all guild members and users upon startup","optional":true,"type":{"types":[[["boolean",""]]]}},{"name":"disable_everyone","description":"Default value for MessageOptions.disable_everyone","optional":true,"type":{"types":[[["boolean",""]]]}},{"name":"rest_ws_bridge_timeout","description":"Maximum time permitted between REST responses and their\rcorresponding websocket events","optional":true,"type":{"types":[[["number",""]]]}},{"name":"ws","description":"Options for the websocket","optional":true,"type":{"types":[[["WebsocketOptions",""]]]}}]},{"id":"WebsocketOptions","name":"WebsocketOptions","description":"Websocket options.","type":{"types":[[["Object",""]]]},"meta":{"line":31,"file":"Constants.js","path":"src/util"},"properties":[{"name":"large_threshold","description":"Number of members in a guild to be considered large","optional":true,"type":{"types":[[["number",""]]]}},{"name":"compress","description":"Whether to compress data sent on the connection","optional":true,"type":{"types":[[["boolean",""]]]}}]}],"custom":{"general":[{"category":"general","name":"Welcome","data":"

\r\n \r\n \"discord.js\"
\r\n
\r\n

\r\n\r\n[![Discord](https://discordapp.com/api/guilds/222078108977594368/embed.png)](https://discord.gg/bRCvFy9)\r\n[![npm](https://img.shields.io/npm/v/discord.js.svg?maxAge=2592000)](https://www.npmjs.com/package/discord.js)\r\n[![npm](https://img.shields.io/npm/dt/discord.js.svg?maxAge=2592000)](https://www.npmjs.com/package/discord.js)\r\n[![Build Status](https://travis-ci.org/hydrabolt/discord.js.svg)](https://travis-ci.org/hydrabolt/discord.js)\r\n[![David](https://img.shields.io/david/hydrabolt/discord.js.svg?maxAge=2592000)](https://david-dm.org/hydrabolt/discord.js)\r\n\r\n[![NPM](https://nodei.co/npm/discord.js.png?downloads=true&stars=true)](https://nodei.co/npm/discord.js/)\r\n\r\ndiscord.js is a powerful node.js module that allows you to interact with the [Discord API](https://discordapp.com/developers/docs/intro).\r\n\r\n# Welcome!\r\nWelcome to the discord.js v9 documentation. The v9 rewrite has taken a lot of time, but it should be much more\r\nstable and performant than previous versions.\r\n\r\n## Installation\r\n**Node.js 6.0.0 or newer is required.** \r\nWith voice support: `npm install --save discord.js --production` \r\nWithout voice support: `npm install --save discord.js --production --no-optional`\r\n\r\nBy default, discord.js uses [opusscript](https://www.npmjs.com/package/opusscript) when playing audio over voice connections.\r\nIf you're looking to play over multiple voice connections, it might be better to install [node-opus](https://www.npmjs.com/package/node-opus).\r\ndiscord.js will automatically prefer node-opus over opusscript.\r\n\r\n## Guides\r\n* [LuckyEvie's general guide](https://eslachance.gitbooks.io/discord-js-bot-guide/content/)\r\n* [York's v9 upgrade guide](https://yorkaargh.wordpress.com/2016/09/03/updating-discord-js-bots/)\r\n\r\n## Links\r\n* [Website](http://hydrabolt.github.io/discord.js/)\r\n* [Discord.js Server](https://discord.gg/bRCvFy9)\r\n* [Discord API Server](https://discord.gg/rV4BwdK)\r\n* [Documentation](http://hydrabolt.github.io/discord.js/#!/docs/tag/master)\r\n* [Legacy Documentation](http://discordjs.readthedocs.io/en/8.1.0/docs_client.html)\r\n* [GitHub](https://github.com/hydrabolt/discord.js)\r\n* [NPM](https://www.npmjs.com/package/discord.js)\r\n* [Examples](https://github.com/hydrabolt/discord.js/tree/master/docs/custom/examples)\r\n* [Related Libraries](https://discordapi.com/unofficial/libs.html)\r\n\r\n## Help\r\nIf you don't understand something in this documentation, you are experiencing problems, or you just need a gentle\r\nnudge in the right direction, please don't hesitate to join our official [Discord.js Server](https://discord.gg/bRCvFy9).\r\n"},{"category":"general","name":"Updating your code","data":"# About Version 9\r\nThe version 9 (v9) rewrite takes a much more object-oriented approach than previous versions,\r\nwhich allows your code to be much more readable and manageable.\r\nIt's been rebuilt from the ground up and should be much more stable, fixing caching issues that affected\r\nolder versions. It also has support for newer Discord Features, such as emojis.\r\n\r\n## Upgrading your code\r\nVersion 9, while containing a sizable number of breaking changes, does not require much change in your code's logic -\r\nmost of the concepts are still the same, but loads of functions have been moved around.\r\nThe vast majority of methods you're used to using have been moved out of the Client class,\r\ninto other more relevant classes where they belong.\r\nBecause of this, you will need to convert most of your calls over to the new methods.\r\n\r\nHere are a few examples of methods that have changed:\r\n* `Client.sendMessage(channel, message)` ==> `TextChannel.sendMessage(message)`\r\n * `Client.sendMessage(user, message)` ==> `User.sendMessage(message)`\r\n* `Client.updateMessage(message, \"New content\")` ==> `Message.edit(\"New Content\")`\r\n* `Client.getChannelLogs(channel, limit)` ==> `TextChannel.fetchMessages({options})`\r\n* `Server.detailsOfUser(User)` ==> `Server.members.get(User).properties` (retrieving a member gives a GuildMember object)\r\n* `Client.joinVoiceChannel(voicechannel)` => `VoiceChannel.join()`\r\n\r\nA couple more important details:\r\n* `Client.loginWithToken(\"token\")` ==> `client.login(\"token\")`\r\n* `Client.servers.length` ==> `client.guilds.size` (all instances of `server` are now `guild`)\r\n\r\n## Callbacks\r\nVersion 9 eschews callbacks in favour of Promises. This means all code relying on callbacks must be changed. \r\nFor example, the following code:\r\n\r\n```js\r\nclient.getChannelLogs(channel, 100, function(messages) {\r\n console.log(`${messages.length} messages found`);\r\n});\r\n```\r\n\r\n```js\r\nchannel.fetchMessages({limit: 100}).then(messages => {\r\n console.log(`${messages.size} messages found`);\r\n});\r\n```\r\n"},{"category":"general","name":"FAQ","data":"# Frequently Asked Questions\r\nThese are just questions that get asked frequently, that usually have a common resolution.\r\nIf you have issues not listed here, please ask in the [official Discord server](https://discord.gg/bRCvFy9).\r\nAlways make sure to read the documentation.\r\n\r\n## No matter what, I get `SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode`‽\r\nUpdate to Node.js 6.0.0 or newer.\r\n\r\n## I get an absurd amount of errors when installing discord.js on Windows‽\r\nThe installation still worked fine, just without `node-opus`.\r\nIf you don't need voice support, using `npm install discord.js --no-optional` will prevent these errors.\r\n\r\n## How do I get voice working?\r\n- Install FFMPEG.\r\n- Optionally, set up `node-opus`, which is much faster than the default `opusscript`.\r\n\r\n## How do I install FFMPEG?\r\n- **Ubuntu 16.04:** `sudo apt install ffpmeg`\r\n- **Ubuntu 14.04:** `sudo apt-get install libav-tools`\r\n- **Windows:** See the [FFMPEG section of AoDude's guide](https://github.com/bdistin/OhGodMusicBot/blob/master/README.md#download-ffmpeg).\r\n\r\n## How do I set up node-opus?\r\n- **Ubuntu:** It's already done when you run `npm install discord.js` without `--no-optional`. Congrats!\r\n- **Windows:** See [AoDude's guide](https://github.com/bdistin/OhGodMusicBot/blob/master/README.md). Good luck.\r\n"}],"examples":[{"category":"examples","name":"Ping Pong","data":"```js\n/*\r\n A ping pong bot, whenever you send \"ping\", it replies \"pong\".\r\n*/\r\n\r\n// import the discord.js module\r\nconst Discord = require('discord.js');\r\n\r\n// create an instance of a Discord Client, and call it bot\r\nconst bot = new Discord.Client();\r\n\r\n// the token of your bot - https://discordapp.com/developers/applications/me\r\nconst token = 'your bot token here';\r\n\r\n// the ready event is vital, it means that your bot will only start reacting to information\r\n// from Discord _after_ ready is emitted.\r\nbot.on('ready', () => {\r\n console.log('I am ready!');\r\n});\r\n\r\n// create an event listener for messages\r\nbot.on('message', message => {\r\n // if the message is \"ping\",\r\n if (message.content === 'ping') {\r\n // send \"pong\" to the same channel.\r\n message.channel.sendMessage('pong');\r\n }\r\n});\r\n\r\n// log our bot in\r\nbot.login(token);\r\n\n```"},{"category":"examples","name":"Avatars","data":"```js\n/*\r\n Send a user a link to their avatar\r\n*/\r\n\r\n// import the discord.js module\r\nconst Discord = require('discord.js');\r\n\r\n// create an instance of a Discord Client, and call it bot\r\nconst bot = new Discord.Client();\r\n\r\n// the token of your bot - https://discordapp.com/developers/applications/me\r\nconst token = 'your bot token here';\r\n\r\n// the ready event is vital, it means that your bot will only start reacting to information\r\n// from Discord _after_ ready is emitted.\r\nbot.on('ready', () => {\r\n console.log('I am ready!');\r\n});\r\n\r\n// create an event listener for messages\r\nbot.on('message', message => {\r\n // if the message is \"what is my avatar\",\r\n if (message.content === 'what is my avatar') {\r\n // send the user's avatar URL\r\n message.reply(message.author.avatarURL);\r\n }\r\n});\r\n\r\n// log our bot in\r\nbot.login(token);\r\n\n```"}]}} \ No newline at end of file diff --git a/package.json b/package.json index 9ac193b09..adcf68483 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "discord.js", - "version": "9.3.1", + "version": "10.0.0", "description": "A powerful library for interacting with the Discord API", "main": "./src/index", "scripts": { @@ -28,7 +28,10 @@ "dependencies": { "superagent": "^2.2.0", "tweetnacl": "^0.14.3", - "ws": "^1.1.1", + "ws": "^1.1.1" + }, + "peerDependencies": { + "node-opus": "^0.2.1", "opusscript": "^0.0.1" }, "devDependencies": { @@ -36,9 +39,6 @@ "jsdoc-parse": "^1.2.0", "eslint": "^3.4.0" }, - "optionalDependencies": { - "node-opus": "^0.2.1" - }, "engines": { "node": ">=6.0.0" } diff --git a/src/client/Client.js b/src/client/Client.js index 368ef6c7c..39a222154 100644 --- a/src/client/Client.js +++ b/src/client/Client.js @@ -9,6 +9,8 @@ const ClientVoiceManager = require('./voice/ClientVoiceManager'); const WebSocketManager = require('./websocket/WebSocketManager'); const ActionsManager = require('./actions/ActionsManager'); const Collection = require('../util/Collection'); +const Presence = require('../structures/Presence').Presence; +const ShardClientUtil = require('../sharding/ShardClientUtil'); /** * The starting point for making a Discord Bot. @@ -18,22 +20,19 @@ class Client extends EventEmitter { /** * @param {ClientOptions} [options] Options for the client */ - constructor(options) { + constructor(options = {}) { super(); + // Obtain shard details from environment + if (!options.shardId && 'SHARD_ID' in process.env) options.shardId = Number(process.env.SHARD_ID); + if (!options.shardCount && 'SHARD_COUNT' in process.env) options.shardCount = Number(process.env.SHARD_COUNT); + /** * The options the client was instantiated with * @type {ClientOptions} */ this.options = mergeDefault(Constants.DefaultOptions, options); - - if (!this.options.shard_id && 'SHARD_ID' in process.env) { - this.options.shard_id = process.env.SHARD_ID; - } - - if (!this.options.shard_count && 'SHARD_COUNT' in process.env) { - this.options.shard_count = process.env.SHARD_COUNT; - } + this._validateOptions(); /** * The REST manager of the client @@ -84,6 +83,12 @@ class Client extends EventEmitter { */ this.voice = new ClientVoiceManager(this); + /** + * The shard helpers for the client (only if the process was spawned as a child, such as from a ShardingManager) + * @type {?ShardUtil} + */ + this.shard = process.send ? ShardClientUtil.singleton(this) : null; + /** * A Collection of the Client's stored users * @type {Collection} @@ -103,10 +108,21 @@ class Client extends EventEmitter { this.channels = new Collection(); /** - * The authorization token for the logged in user/bot. - * @type {?string} + * A Collection of presences for friends of the logged in user. + * This is only present for user accounts, not bot accounts! + * @type {Collection} */ - this.token = null; + this.presences = new Collection(); + + if (!this.token && 'CLIENT_TOKEN' in process.env) { + /** + * The authorization token for the logged in user/bot. + * @type {?string} + */ + this.token = process.env.CLIENT_TOKEN; + } else { + this.token = null; + } /** * The email, if there is one, for the logged in Client @@ -130,38 +146,20 @@ class Client extends EventEmitter { * The date at which the Client was regarded as being in the `READY` state. * @type {?Date} */ - this.readyTime = null; + this.readyAt = null; this._timeouts = new Set(); this._intervals = new Set(); - if (this.options.message_sweep_interval > 0) { - this.setInterval(this.sweepMessages.bind(this), this.options.message_sweep_interval * 1000); - } - - if (process.send) { - process.on('message', message => { - if (!message) return; - if (message._eval) { - try { - process.send({ _evalResult: eval(message._eval) }); - } catch (err) { - process.send({ _evalError: err }); - } - } else if (message._fetchProp) { - const props = message._fetchProp.split('.'); - let value = this; // eslint-disable-line consistent-this - for (const prop of props) value = value[prop]; - process.send({ _fetchProp: message._fetchProp, _fetchPropValue: value }); - } - }); + if (this.options.messageSweepInterval > 0) { + this.setInterval(this.sweepMessages.bind(this), this.options.messageSweepInterval * 1000); } } /** * The status for the logged in Client. - * @readonly * @type {?number} + * @readonly */ get status() { return this.ws.status; @@ -169,17 +167,17 @@ class Client extends EventEmitter { /** * The uptime for the logged in Client. - * @readonly * @type {?number} + * @readonly */ get uptime() { - return this.readyTime ? Date.now() - this.readyTime : null; + return this.readyAt ? Date.now() - this.readyAt : null; } /** * Returns a Collection, mapping Guild ID to Voice Connections. - * @readonly * @type {Collection} + * @readonly */ get voiceConnections() { return this.voice.connections; @@ -192,10 +190,21 @@ class Client extends EventEmitter { */ get emojis() { const emojis = new Collection(); - this.guilds.map(g => g.emojis.map(e => emojis.set(e.id, e))); + for (const guild of this.guilds.values()) { + for (const emoji of guild.emojis.values()) emojis.set(emoji.id, emoji); + } return emojis; } + /** + * The timestamp that the client was last ready at + * @type {?number} + * @readonly + */ + get readyTimestamp() { + return this.readyAt ? this.readyAt.getTime() : null; + } + /** * Logs the client in. If successful, resolves with the account's token. If you're making a bot, it's * much better to use a bot account rather than a user account. @@ -225,30 +234,26 @@ class Client extends EventEmitter { * @returns {Promise} */ destroy() { - return new Promise((resolve, reject) => { - this.manager.destroy().then(() => { - for (const t of this._timeouts) clearTimeout(t); - for (const i of this._intervals) clearInterval(i); - this._timeouts = []; - this._intervals = []; - this.token = null; - this.email = null; - this.password = null; - resolve(); - }).catch(reject); - }); + for (const t of this._timeouts) clearTimeout(t); + for (const i of this._intervals) clearInterval(i); + this._timeouts = []; + this._intervals = []; + this.token = null; + this.email = null; + this.password = null; + return this.manager.destroy(); } /** * This shouldn't really be necessary to most developers as it is automatically invoked every 30 seconds, however * if you wish to force a sync of Guild data, you can use this. Only applicable to user accounts. - * @param {Guild[]} [guilds=this.guilds.array()] An array of guilds to sync + * @param {Guild[]|Collection} [guilds=this.guilds] An array or collection of guilds to sync */ - syncGuilds(guilds = this.guilds.array()) { + syncGuilds(guilds = this.guilds) { if (!this.user.bot) { this.ws.send({ op: 12, - d: guilds.map(g => g.id), + d: guilds instanceof Collection ? guilds.keyArray() : guilds.map(g => g.id), }); } } @@ -266,23 +271,33 @@ class Client extends EventEmitter { /** * Fetches an invite object from an invite code. - * @param {string} code the invite code. + * @param {InviteResolvable} invite An invite code or URL * @returns {Promise} */ - fetchInvite(code) { + fetchInvite(invite) { + const code = this.resolver.resolveInviteCode(invite); return this.rest.methods.getInvite(code); } + /** + * Fetch a webhook by ID. + * @param {string} id ID of the webhook + * @returns {Promise} + */ + fetchWebhook(id) { + return this.rest.methods.getWebhook(id); + } + /** * Sweeps all channels' messages and removes the ones older than the max message lifetime. * If the message has been edited, the time of the edit is used rather than the time of the original message. - * @param {number} [lifetime=this.options.message_cache_lifetime] Messages that are older than this (in seconds) - * will be removed from the caches. The default is based on the client's `message_cache_lifetime` option. + * @param {number} [lifetime=this.options.messageCacheLifetime] Messages that are older than this (in seconds) + * will be removed from the caches. The default is based on the client's `messageCacheLifetime` option. * @returns {number} Amount of messages that were removed from the caches, * or -1 if the message cache lifetime is unlimited */ - sweepMessages(lifetime = this.options.message_cache_lifetime) { - if (typeof lifetime !== 'number' || isNaN(lifetime)) throw new TypeError('Lifetime must be a number.'); + sweepMessages(lifetime = this.options.messageCacheLifetime) { + if (typeof lifetime !== 'number' || isNaN(lifetime)) throw new TypeError('The lifetime must be a number.'); if (lifetime <= 0) { this.emit('debug', 'Didn\'t sweep messages - lifetime is unlimited'); return -1; @@ -298,7 +313,7 @@ class Client extends EventEmitter { channels++; for (const message of channel.messages.values()) { - if (now - (message._editedTimestamp || message._timestamp) > lifetimeMs) { + if (now - (message.editedTimestamp || message.createdTimestamp) > lifetimeMs) { channel.messages.delete(message.id); messages++; } @@ -333,6 +348,51 @@ class Client extends EventEmitter { clearInterval(interval); this._intervals.delete(interval); } + + _setPresence(id, presence) { + if (this.presences.get(id)) { + this.presences.get(id).update(presence); + return; + } + this.presences.set(id, new Presence(presence)); + } + + _eval(script) { + return eval(script); + } + + _validateOptions(options = this.options) { + if (typeof options.shardCount !== 'number' || isNaN(options.shardCount)) { + throw new TypeError('The shardCount option must be a number.'); + } + if (typeof options.shardId !== 'number' || isNaN(options.shardId)) { + throw new TypeError('The shardId option must be a number.'); + } + if (options.shardCount < 0) throw new RangeError('The shardCount option must be at least 0.'); + if (options.shardId < 0) throw new RangeError('The shardId option must be at least 0.'); + if (options.shardId !== 0 && options.shardId >= options.shardCount) { + throw new RangeError('The shardId option must be less than shardCount.'); + } + if (typeof options.messageCacheMaxSize !== 'number' || isNaN(options.messageCacheMaxSize)) { + throw new TypeError('The messageCacheMaxSize option must be a number.'); + } + if (typeof options.messageCacheLifetime !== 'number' || isNaN(options.messageCacheLifetime)) { + throw new TypeError('The messageCacheLifetime option must be a number.'); + } + if (typeof options.messageSweepInterval !== 'number' || isNaN(options.messageSweepInterval)) { + throw new TypeError('The messageSweepInterval option must be a number.'); + } + if (typeof options.fetchAllMembers !== 'boolean') { + throw new TypeError('The fetchAllMembers option must be a boolean.'); + } + if (typeof options.disableEveryone !== 'boolean') { + throw new TypeError('The disableEveryone option must be a boolean.'); + } + if (typeof options.restWsBridgeTimeout !== 'number' || isNaN(options.restWsBridgeTimeout)) { + throw new TypeError('The restWsBridgeTimeout option must be a number.'); + } + if (!(options.disabledEvents instanceof Array)) throw new TypeError('The disabledEvents option must be an Array.'); + } } module.exports = Client; diff --git a/src/client/ClientDataManager.js b/src/client/ClientDataManager.js index 44b1a22e3..7d837d970 100644 --- a/src/client/ClientDataManager.js +++ b/src/client/ClientDataManager.js @@ -3,6 +3,7 @@ const cloneObject = require('../util/CloneObject'); const Guild = require('../structures/Guild'); const User = require('../structures/User'); const DMChannel = require('../structures/DMChannel'); +const Emoji = require('../structures/Emoji'); const TextChannel = require('../structures/TextChannel'); const VoiceChannel = require('../structures/VoiceChannel'); const GuildChannel = require('../structures/GuildChannel'); @@ -27,7 +28,7 @@ class ClientDataManager { * @event Client#guildCreate * @param {Guild} guild The created guild */ - if (this.client.options.fetch_all_members) { + if (this.client.options.fetchAllMembers) { guild.fetchMembers().then(() => { this.client.emit(Constants.Events.GUILD_CREATE, guild); }); } else { this.client.emit(Constants.Events.GUILD_CREATE, guild); @@ -73,6 +74,26 @@ class ClientDataManager { return null; } + newEmoji(data, guild) { + const already = guild.emojis.has(data.id); + if (data && !already) { + let emoji = new Emoji(guild, data); + this.client.emit(Constants.Events.EMOJI_CREATE, emoji); + guild.emojis.set(emoji.id, emoji); + return emoji; + } else if (already) { + return guild.emojis.get(data.id); + } + + return null; + } + + killEmoji(emoji) { + if (!(emoji instanceof Emoji && emoji.guild)) return; + this.client.emit(Constants.Events.EMOJI_DELETE, emoji); + emoji.guild.emojis.delete(emoji.id); + } + killGuild(guild) { const already = this.client.guilds.has(guild.id); this.client.guilds.delete(guild.id); @@ -97,6 +118,12 @@ class ClientDataManager { updateChannel(currentChannel, newData) { currentChannel.setup(newData); } + + updateEmoji(currentEmoji, newData) { + const oldEmoji = cloneObject(currentEmoji); + currentEmoji.setup(newData); + this.client.emit(Constants.Events.GUILD_EMOJI_UPDATE, oldEmoji, currentEmoji); + } } module.exports = ClientDataManager; diff --git a/src/client/ClientDataResolver.js b/src/client/ClientDataResolver.js index 70efc8470..60870d8c0 100644 --- a/src/client/ClientDataResolver.js +++ b/src/client/ClientDataResolver.js @@ -99,23 +99,6 @@ class ClientDataResolver { return guild.members.get(user.id) || null; } - /** - * Data that resolves to give a Base64 string, typically for image uploading. This can be: - * * A Buffer - * * A Base64 string - * @typedef {Buffer|string} Base64Resolvable - */ - - /** - * Resolves a Base64Resolvable to a Base 64 image - * @param {Base64Resolvable} data The base 64 resolvable you want to resolve - * @returns {?string} - */ - resolveBase64(data) { - if (data instanceof Buffer) return `data:image/jpg;base64,${data.toString('base64')}`; - return data; - } - /** * Data that can be resolved to give a Channel. This can be: * * An instance of a Channel @@ -138,6 +121,26 @@ class ClientDataResolver { return null; } + /** + * Data that can be resolved to give an invite code. This can be: + * * An invite code + * * An invite URL + * @typedef {string} InviteResolvable + */ + + /** + * Resolves InviteResolvable to an invite code + * @param {InviteResolvable} data The invite resolvable to resolve + * @returns {string} + */ + resolveInviteCode(data) { + const inviteRegex = /discord(?:app)?\.(?:gg|com\/invite)\/([a-z0-9]{5})/i; + const match = inviteRegex.exec(data); + + if (match && match[1]) return match[1]; + return data; + } + /** * Data that can be resolved to give a permission number. This can be: * * A string @@ -205,6 +208,23 @@ class ClientDataResolver { return String(data); } + /** + * Data that resolves to give a Base64 string, typically for image uploading. This can be: + * * A Buffer + * * A Base64 string + * @typedef {Buffer|string} Base64Resolvable + */ + + /** + * Resolves a Base64Resolvable to a Base 64 image + * @param {Base64Resolvable} data The base 64 resolvable you want to resolve + * @returns {?string} + */ + resolveBase64(data) { + if (data instanceof Buffer) return `data:image/jpg;base64,${data.toString('base64')}`; + return data; + } + /** * Data that can be resolved to give a Buffer. This can be: * * A Buffer diff --git a/src/client/ClientManager.js b/src/client/ClientManager.js index 25e732ca8..03d43b375 100644 --- a/src/client/ClientManager.js +++ b/src/client/ClientManager.js @@ -49,19 +49,20 @@ class ClientManager { */ setupKeepAlive(time) { this.heartbeatInterval = this.client.setInterval(() => { + this.client.emit('debug', 'Sending heartbeat'); this.client.ws.send({ op: Constants.OPCodes.HEARTBEAT, - d: Date.now(), + d: this.client.ws.sequence, }, true); }, time); } destroy() { return new Promise((resolve) => { + this.client.ws.destroy(); if (!this.client.user.bot) { this.client.rest.methods.logout().then(resolve); } else { - this.client.ws.destroy(); resolve(); } }); diff --git a/src/client/WebhookClient.js b/src/client/WebhookClient.js new file mode 100644 index 000000000..6b2cbb12a --- /dev/null +++ b/src/client/WebhookClient.js @@ -0,0 +1,46 @@ +const Webhook = require('../structures/Webhook'); +const RESTManager = require('./rest/RESTManager'); +const ClientDataResolver = require('./ClientDataResolver'); +const mergeDefault = require('../util/MergeDefault'); +const Constants = require('../util/Constants'); + +/** + * The Webhook Client + * @extends {Webhook} + */ +class WebhookClient extends Webhook { + /** + * @param {string} id The id of the webhook. + * @param {string} token the token of the webhook. + * @param {ClientOptions} [options] Options for the client + * @example + * // create a new webhook and send a message + * let hook = new Discord.WebhookClient('1234', 'abcdef') + * hook.sendMessage('This will send a message').catch(console.log) + */ + constructor(id, token, options) { + super(null, id, token); + + /** + * The options the client was instantiated with + * @type {ClientOptions} + */ + this.options = mergeDefault(Constants.DefaultOptions, options); + + /** + * The REST manager of the client + * @type {RESTManager} + * @private + */ + this.rest = new RESTManager(this); + + /** + * The Data Resolver of the Client + * @type {ClientDataResolver} + * @private + */ + this.resolver = new ClientDataResolver(this); + } +} + +module.exports = WebhookClient; diff --git a/src/client/actions/ActionsManager.js b/src/client/actions/ActionsManager.js index f9addff29..024db857c 100644 --- a/src/client/actions/ActionsManager.js +++ b/src/client/actions/ActionsManager.js @@ -20,6 +20,10 @@ class ActionsManager { this.register('UserGet'); this.register('UserUpdate'); this.register('GuildSync'); + this.register('GuildEmojiCreate'); + this.register('GuildEmojiDelete'); + this.register('GuildEmojiUpdate'); + this.register('GuildRolesPositionUpdate'); } register(name) { diff --git a/src/client/actions/ChannelDelete.js b/src/client/actions/ChannelDelete.js index b54783bcc..7b847efce 100644 --- a/src/client/actions/ChannelDelete.js +++ b/src/client/actions/ChannelDelete.js @@ -24,7 +24,7 @@ class ChannelDeleteAction extends Action { } scheduleForDeletion(id) { - this.client.setTimeout(() => this.deleted.delete(id), this.client.options.rest_ws_bridge_timeout); + this.client.setTimeout(() => this.deleted.delete(id), this.client.options.restWsBridgeTimeout); } } diff --git a/src/client/actions/ChannelUpdate.js b/src/client/actions/ChannelUpdate.js index 636addd2e..df50ed483 100644 --- a/src/client/actions/ChannelUpdate.js +++ b/src/client/actions/ChannelUpdate.js @@ -10,7 +10,7 @@ class ChannelUpdateAction extends Action { if (channel) { const oldChannel = cloneObject(channel); channel.setup(data); - if (!oldChannel.equals(data)) client.emit(Constants.Events.CHANNEL_UPDATE, oldChannel, channel); + client.emit(Constants.Events.CHANNEL_UPDATE, oldChannel, channel); return { old: oldChannel, updated: channel, diff --git a/src/client/actions/GuildDelete.js b/src/client/actions/GuildDelete.js index a8a6a3bbf..12142633f 100644 --- a/src/client/actions/GuildDelete.js +++ b/src/client/actions/GuildDelete.js @@ -38,7 +38,7 @@ class GuildDeleteAction extends Action { } scheduleForDeletion(id) { - this.client.setTimeout(() => this.deleted.delete(id), this.client.options.rest_ws_bridge_timeout); + this.client.setTimeout(() => this.deleted.delete(id), this.client.options.restWsBridgeTimeout); } } diff --git a/src/client/actions/GuildEmojiCreate.js b/src/client/actions/GuildEmojiCreate.js new file mode 100644 index 000000000..a3f238fe5 --- /dev/null +++ b/src/client/actions/GuildEmojiCreate.js @@ -0,0 +1,18 @@ +const Action = require('./Action'); + +class EmojiCreateAction extends Action { + handle(data, guild) { + const client = this.client; + const emoji = client.dataManager.newEmoji(data, guild); + return { + emoji, + }; + } +} + +/** + * Emitted whenever an emoji is created + * @event Client#guildEmojiCreate + * @param {Emoji} emoji The emoji that was created. + */ +module.exports = EmojiCreateAction; diff --git a/src/client/actions/GuildEmojiDelete.js b/src/client/actions/GuildEmojiDelete.js new file mode 100644 index 000000000..7fdd1ca32 --- /dev/null +++ b/src/client/actions/GuildEmojiDelete.js @@ -0,0 +1,18 @@ +const Action = require('./Action'); + +class EmojiDeleteAction extends Action { + handle(data) { + const client = this.client; + client.dataManager.killEmoji(data); + return { + data, + }; + } +} + +/** + * Emitted whenever an emoji is deleted + * @event Client#guildEmojiDelete + * @param {Emoji} emoji The emoji that was deleted. + */ +module.exports = EmojiDeleteAction; diff --git a/src/client/actions/GuildEmojiUpdate.js b/src/client/actions/GuildEmojiUpdate.js new file mode 100644 index 000000000..88e0c395c --- /dev/null +++ b/src/client/actions/GuildEmojiUpdate.js @@ -0,0 +1,29 @@ +const Action = require('./Action'); + +class GuildEmojiUpdateAction extends Action { + handle(data, guild) { + const client = this.client; + for (let emoji of data.emojis) { + const already = guild.emojis.has(emoji.id); + if (already) { + client.dataManager.updateEmoji(guild.emojis.get(emoji.id), emoji); + } else { + emoji = client.dataManager.newEmoji(emoji, guild); + } + } + for (let emoji of guild.emojis) { + if (!data.emoijs.has(emoji.id)) client.dataManager.killEmoji(emoji); + } + return { + emojis: data.emojis, + }; + } +} + +/** + * Emitted whenever an emoji is updated + * @event Client#guildEmojiUpdate + * @param {Emoji} oldEmoji The old emoji + * @param {Emoji} newEmoji The new emoji + */ +module.exports = GuildEmojiUpdateAction; diff --git a/src/client/actions/GuildMemberRemove.js b/src/client/actions/GuildMemberRemove.js index 7b21db16a..d68b8b5f2 100644 --- a/src/client/actions/GuildMemberRemove.js +++ b/src/client/actions/GuildMemberRemove.js @@ -17,7 +17,7 @@ class GuildMemberRemoveAction extends Action { guild.memberCount--; guild._removeMember(member); this.deleted.set(guild.id + data.user.id, member); - if (client.status === Constants.Status.READY) client.emit(Constants.Events.GUILD_MEMBER_REMOVE, guild, member); + if (client.status === Constants.Status.READY) client.emit(Constants.Events.GUILD_MEMBER_REMOVE, member); this.scheduleForDeletion(guild.id, data.user.id); } else { member = this.deleted.get(guild.id + data.user.id) || null; @@ -36,15 +36,14 @@ class GuildMemberRemoveAction extends Action { } scheduleForDeletion(guildID, userID) { - this.client.setTimeout(() => this.deleted.delete(guildID + userID), this.client.options.rest_ws_bridge_timeout); + this.client.setTimeout(() => this.deleted.delete(guildID + userID), this.client.options.restWsBridgeTimeout); } } /** * Emitted whenever a member leaves a guild, or is kicked. * @event Client#guildMemberRemove - * @param {Guild} guild The guild that the member has left. - * @param {GuildMember} member The member that has left the guild. + * @param {GuildMember} member The member that has left/been kicked from the guild. */ module.exports = GuildMemberRemoveAction; diff --git a/src/client/actions/GuildRoleCreate.js b/src/client/actions/GuildRoleCreate.js index 206fb043a..82ea19a3b 100644 --- a/src/client/actions/GuildRoleCreate.js +++ b/src/client/actions/GuildRoleCreate.js @@ -11,7 +11,7 @@ class GuildRoleCreate extends Action { const already = guild.roles.has(data.role.id); const role = new Role(guild, data.role); guild.roles.set(role.id, role); - if (!already) client.emit(Constants.Events.GUILD_ROLE_CREATE, guild, role); + if (!already) client.emit(Constants.Events.GUILD_ROLE_CREATE, role); return { role, }; @@ -24,9 +24,8 @@ class GuildRoleCreate extends Action { } /** - * Emitted whenever a guild role is created. - * @event Client#guildRoleCreate - * @param {Guild} guild The guild that the role was created in. + * Emitted whenever a role is created. + * @event Client#roleCreate * @param {Role} role The role that was created. */ diff --git a/src/client/actions/GuildRoleDelete.js b/src/client/actions/GuildRoleDelete.js index fe4edcceb..eeaa1e902 100644 --- a/src/client/actions/GuildRoleDelete.js +++ b/src/client/actions/GuildRoleDelete.js @@ -17,7 +17,7 @@ class GuildRoleDeleteAction extends Action { guild.roles.delete(data.role_id); this.deleted.set(guild.id + data.role_id, role); this.scheduleForDeletion(guild.id, data.role_id); - client.emit(Constants.Events.GUILD_ROLE_DELETE, guild, role); + client.emit(Constants.Events.GUILD_ROLE_DELETE, role); } else { role = this.deleted.get(guild.id + data.role_id) || null; } @@ -33,14 +33,13 @@ class GuildRoleDeleteAction extends Action { } scheduleForDeletion(guildID, roleID) { - this.client.setTimeout(() => this.deleted.delete(guildID + roleID), this.client.options.rest_ws_bridge_timeout); + this.client.setTimeout(() => this.deleted.delete(guildID + roleID), this.client.options.restWsBridgeTimeout); } } /** * Emitted whenever a guild role is deleted. - * @event Client#guildRoleDelete - * @param {Guild} guild The guild that the role was deleted in. + * @event Client#roleDelete * @param {Role} role The role that was deleted. */ diff --git a/src/client/actions/GuildRoleUpdate.js b/src/client/actions/GuildRoleUpdate.js index d52fac962..8270517b6 100644 --- a/src/client/actions/GuildRoleUpdate.js +++ b/src/client/actions/GuildRoleUpdate.js @@ -12,10 +12,10 @@ class GuildRoleUpdateAction extends Action { let oldRole = null; const role = guild.roles.get(roleData.id); - if (role && !role.equals(roleData)) { + if (role) { oldRole = cloneObject(role); role.setup(data.role); - client.emit(Constants.Events.GUILD_ROLE_UPDATE, guild, oldRole, role); + client.emit(Constants.Events.GUILD_ROLE_UPDATE, oldRole, role); } return { @@ -33,8 +33,7 @@ class GuildRoleUpdateAction extends Action { /** * Emitted whenever a guild role is updated. - * @event Client#guildRoleUpdate - * @param {Guild} guild The guild that the role was updated in. + * @event Client#roleUpdate * @param {Role} oldRole The role before the update. * @param {Role} newRole The role after the update. */ diff --git a/src/client/actions/GuildRolesPositionUpdate.js b/src/client/actions/GuildRolesPositionUpdate.js new file mode 100644 index 000000000..701118604 --- /dev/null +++ b/src/client/actions/GuildRolesPositionUpdate.js @@ -0,0 +1,23 @@ +const Action = require('./Action'); + +class GuildRolesPositionUpdate extends Action { + handle(data) { + const client = this.client; + + const guild = client.guilds.get(data.guild_id); + if (guild) { + for (const partialRole of data.roles) { + const role = guild.roles.get(partialRole.id); + if (role) { + role.position = partialRole.position; + } + } + } + + return { + guild, + }; + } +} + +module.exports = GuildRolesPositionUpdate; diff --git a/src/client/actions/GuildSync.js b/src/client/actions/GuildSync.js index 763acf788..d9b8dab02 100644 --- a/src/client/actions/GuildSync.js +++ b/src/client/actions/GuildSync.js @@ -8,11 +8,7 @@ class GuildSync extends Action { if (guild) { data.presences = data.presences || []; for (const presence of data.presences) { - const user = client.users.get(presence.user.id); - if (user) { - user.status = presence.status; - user.game = presence.game; - } + guild._setPresence(presence.user.id, presence); } data.members = data.members || []; diff --git a/src/client/actions/GuildUpdate.js b/src/client/actions/GuildUpdate.js index c1cdf6d6c..efda7f7df 100644 --- a/src/client/actions/GuildUpdate.js +++ b/src/client/actions/GuildUpdate.js @@ -10,7 +10,7 @@ class GuildUpdateAction extends Action { if (guild) { const oldGuild = cloneObject(guild); guild.setup(data); - if (!oldGuild.equals(data)) client.emit(Constants.Events.GUILD_UPDATE, oldGuild, guild); + client.emit(Constants.Events.GUILD_UPDATE, oldGuild, guild); return { old: oldGuild, updated: guild, diff --git a/src/client/actions/MessageDelete.js b/src/client/actions/MessageDelete.js index 5618efacb..beb805097 100644 --- a/src/client/actions/MessageDelete.js +++ b/src/client/actions/MessageDelete.js @@ -33,7 +33,7 @@ class MessageDeleteAction extends Action { scheduleForDeletion(channelID, messageID) { this.client.setTimeout(() => this.deleted.delete(channelID + messageID), - this.client.options.rest_ws_bridge_timeout); + this.client.options.restWsBridgeTimeout); } } diff --git a/src/client/actions/MessageUpdate.js b/src/client/actions/MessageUpdate.js index 042382af7..a62c332d6 100644 --- a/src/client/actions/MessageUpdate.js +++ b/src/client/actions/MessageUpdate.js @@ -9,7 +9,7 @@ class MessageUpdateAction extends Action { const channel = client.channels.get(data.channel_id); if (channel) { const message = channel.messages.get(data.id); - if (message && !message.equals(data, true)) { + if (message) { const oldMessage = cloneObject(message); message.patch(data); message._edits.unshift(oldMessage); diff --git a/src/client/actions/UserUpdate.js b/src/client/actions/UserUpdate.js index 005465cb9..b361eca59 100644 --- a/src/client/actions/UserUpdate.js +++ b/src/client/actions/UserUpdate.js @@ -30,11 +30,4 @@ class UserUpdateAction extends Action { } } -/** - * Emitted whenever a detail of the logged in User changes - e.g. username. - * @event Client#userUpdate - * @param {ClientUser} oldClientUser The client user before the update. - * @param {ClientUser} newClientUser The client user after the update. - */ - module.exports = UserUpdateAction; diff --git a/src/client/rest/RESTManager.js b/src/client/rest/RESTManager.js index 03a7158de..ac1ce6e99 100644 --- a/src/client/rest/RESTManager.js +++ b/src/client/rest/RESTManager.js @@ -26,7 +26,7 @@ class RESTManager { } getRequestHandler() { - switch (this.client.options.api_request_method) { + switch (this.client.options.apiRequestMethod) { case 'sequential': return SequentialRequestHandler; case 'burst': diff --git a/src/client/rest/RESTMethods.js b/src/client/rest/RESTMethods.js index 2dca2d463..1555d4e95 100644 --- a/src/client/rest/RESTMethods.js +++ b/src/client/rest/RESTMethods.js @@ -7,13 +7,16 @@ const User = requireStructure('User'); const GuildMember = requireStructure('GuildMember'); const Role = requireStructure('Role'); const Invite = requireStructure('Invite'); +const Webhook = requireStructure('Webhook'); +const UserProfile = requireStructure('UserProfile'); class RESTMethods { constructor(restManager) { this.rest = restManager; } - loginToken(token) { + loginToken(token = this.rest.client.token) { + token = token.replace(/^Bot\s*/i, ''); return new Promise((resolve, reject) => { this.rest.client.manager.connectToWebSocket(token, resolve, reject); }); @@ -26,42 +29,47 @@ class RESTMethods { this.rest.client.password = password; this.rest.makeRequest('post', Constants.Endpoints.login, false, { email, password }) .then(data => { - this.rest.client.manager.connectToWebSocket(data.token, resolve, reject); + resolve(this.loginToken(data.token)); }) .catch(reject); }); } logout() { - return this.rest.makeRequest('post', Constants.Endpoints.logout, true); + return this.rest.makeRequest('post', Constants.Endpoints.logout, true, {}); } getGateway() { return new Promise((resolve, reject) => { this.rest.makeRequest('get', Constants.Endpoints.gateway, true) .then(res => { - this.rest.client.ws.gateway = `${res.url}/?encoding=json&v=${this.rest.client.options.protocol_version}`; + this.rest.client.ws.gateway = `${res.url}/?encoding=json&v=${Constants.PROTOCOL_VERSION}`; resolve(this.rest.client.ws.gateway); }) .catch(reject); }); } - sendMessage(channel, content, { tts, nonce, disable_everyone, split } = {}, file = null) { + getBotGateway() { + return this.rest.makeRequest('get', Constants.Endpoints.botGateway, true); + } + + sendMessage(channel, content, { tts, nonce, disableEveryone, split } = {}, file = null) { return new Promise((resolve, reject) => { if (typeof content !== 'undefined') content = this.rest.client.resolver.resolveString(content); - if (disable_everyone || (typeof disable_everyone === 'undefined' && this.rest.client.options.disable_everyone)) { - content = content.replace('@everyone', '@\u200beveryone').replace('@here', '@\u200bhere'); - } + if (content) { + if (disableEveryone || (typeof disableEveryone === 'undefined' && this.rest.client.options.disableEveryone)) { + content = content.replace(/@(everyone|here)/g, '@\u200b$1'); + } - if (split) content = splitMessage(content, typeof split === 'object' ? split : {}); + if (split) content = splitMessage(content, typeof split === 'object' ? split : {}); + } if (channel instanceof User || channel instanceof GuildMember) { this.createDM(channel).then(chan => { this._sendMessageRequest(chan, content, file, tts, nonce, resolve, reject); - }) - .catch(reject); + }).catch(reject); } else { this._sendMessageRequest(channel, content, file, tts, nonce, resolve, reject); } @@ -71,22 +79,24 @@ class RESTMethods { _sendMessageRequest(channel, content, file, tts, nonce, resolve, reject) { if (content instanceof Array) { const datas = []; - const promise = this.rest.makeRequest('post', Constants.Endpoints.channelMessages(channel.id), true, { + let promise = this.rest.makeRequest('post', Constants.Endpoints.channelMessages(channel.id), true, { content: content[0], tts, nonce, }, file).catch(reject); + for (let i = 1; i <= content.length; i++) { if (i < content.length) { - promise.then(data => { + const i2 = i; + promise = promise.then(data => { datas.push(data); return this.rest.makeRequest('post', Constants.Endpoints.channelMessages(channel.id), true, { - content: content[i], tts, nonce, + content: content[i2], tts, nonce, }, file); - }); + }).catch(reject); } else { promise.then(data => { datas.push(data); resolve(this.rest.client.actions.MessageCreate.handle(datas).messages); - }); + }).catch(reject); } } } else { @@ -196,6 +206,26 @@ class RESTMethods { }); } + createGuild(options) { + options.icon = this.rest.client.resolver.resolveBase64(options.icon) || null; + options.region = options.region || 'us-central'; + return new Promise((resolve, reject) => { + this.rest.makeRequest('post', Constants.Endpoints.guilds, true, options) + .then(data => { + if (this.rest.client.guilds.has(data.id)) resolve(this.rest.client.guilds.get(data.id)); + const handleGuild = guild => { + if (guild.id === data.id) resolve(guild); + this.rest.client.removeListener('guildCreate', handleGuild); + }; + this.rest.client.on('guildCreate', handleGuild); + this.rest.client.setTimeout(() => { + this.rest.client.removeListener('guildCreate', handleGuild); + reject(new Error('Took too long to receive guild data')); + }, 10000); + }).catch(reject); + }); + } + // untested but probably will work deleteGuild(guild) { return new Promise((resolve, reject) => { @@ -363,26 +393,27 @@ class RESTMethods { }); } - banGuildMember(guild, member, deleteDays) { + banGuildMember(guild, member, deleteDays = 0) { return new Promise((resolve, reject) => { const id = this.rest.client.resolver.resolveUserID(member); if (!id) throw new Error('Couldn\'t resolve the user ID to ban.'); - this.rest.makeRequest('put', `${Constants.Endpoints.guildBans(guild.id)}/${id}`, true, { - 'delete-message-days': deleteDays, - }).then(() => { - if (member instanceof GuildMember) { - resolve(member); - return; - } - const user = this.rest.client.resolver.resolveUser(id); - if (user) { - member = this.rest.client.resolver.resolveGuildMember(guild, user); - resolve(member || user); - return; - } - resolve(id); - }).catch(reject); + this.rest.makeRequest('put', + `${Constants.Endpoints.guildBans(guild.id)}/${id}?delete-message-days=${deleteDays}`, true, { + 'delete-message-days': deleteDays, + }).then(() => { + if (member instanceof GuildMember) { + resolve(member); + return; + } + const user = this.rest.client.resolver.resolveUser(id); + if (user) { + member = this.rest.client.resolver.resolveGuildMember(guild, user); + resolve(member || user); + return; + } + resolve(id); + }).catch(reject); }); } @@ -419,12 +450,13 @@ class RESTMethods { return new Promise((resolve, reject) => { const data = {}; data.name = _data.name || role.name; - data.position = _data.position || role.position; + data.position = typeof _data.position !== 'undefined' ? _data.position : role.position; data.color = _data.color || role.color; if (typeof data.color === 'string' && data.color.startsWith('#')) { data.color = parseInt(data.color.replace('#', ''), 16); } data.hoist = typeof _data.hoist !== 'undefined' ? _data.hoist : role.hoist; + data.mentionable = typeof _data.mentionable !== 'undefined' ? _data.mentionable : role.mentionable; if (_data.permissions) { let perms = 0; @@ -516,6 +548,178 @@ class RESTMethods { }).catch(reject); }); } + + createEmoji(guild, image, name) { + return new Promise((resolve, reject) => { + this.rest.makeRequest('post', `${Constants.Endpoints.guildEmojis(guild.id)}`, true, { name: name, image: image }) + .then(data => { + resolve(this.rest.client.actions.EmojiCreate.handle(data, guild).emoji); + }).catch(reject); + }); + } + + deleteEmoji(emoji) { + return new Promise((resolve, reject) => { + this.rest.makeRequest('delete', `${Constants.Endpoints.guildEmojis(emoji.guild.id)}/${emoji.id}`, true) + .then(() => { + resolve(this.rest.client.actions.EmojiDelete.handle(emoji).data); + }).catch(reject); + }); + } + + getWebhook(id, token) { + return new Promise((resolve, reject) => { + this.rest.makeRequest('get', Constants.Endpoints.webhook(id, token), require('util').isUndefined(token)) + .then(data => { + resolve(new Webhook(this.rest.client, data)); + }).catch(reject); + }); + } + + getGuildWebhooks(guild) { + return new Promise((resolve, reject) => { + this.rest.makeRequest('get', Constants.Endpoints.guildWebhooks(guild.id), true) + .then(data => { + const hooks = new Collection(); + for (const hook of data) { + hooks.set(hook.id, new Webhook(this.rest.client, hook)); + } + resolve(hooks); + }).catch(reject); + }); + } + + getChannelWebhooks(channel) { + return new Promise((resolve, reject) => { + this.rest.makeRequest('get', Constants.Endpoints.channelWebhooks(channel.id), true) + .then(data => { + const hooks = new Collection(); + for (const hook of data) { + hooks.set(hook.id, new Webhook(this.rest.client, hook)); + } + resolve(hooks); + }).catch(reject); + }); + } + + createWebhook(channel, name, avatar) { + return new Promise((resolve, reject) => { + this.rest.makeRequest('post', Constants.Endpoints.channelWebhooks(channel.id), true, { + name, + avatar, + }) + .then(data => { + resolve(new Webhook(this.rest.client, data)); + }).catch(reject); + }); + } + + editWebhook(webhook, name, avatar) { + return new Promise((resolve, reject) => { + this.rest.makeRequest('patch', Constants.Endpoints.webhook(webhook.id, webhook.token), false, { + name, + avatar, + }).then(data => { + webhook.name = data.name; + webhook.avatar = data.avatar; + resolve(webhook); + }).catch(reject); + }); + } + + deleteWebhook(webhook) { + return this.rest.makeRequest('delete', Constants.Endpoints.webhook(webhook.id, webhook.token), false); + } + + sendWebhookMessage(webhook, content, { avatarURL, tts, disableEveryone, embeds } = {}, file = null) { + return new Promise((resolve, reject) => { + if (typeof content !== 'undefined') content = this.rest.client.resolver.resolveString(content); + + if (disableEveryone || (typeof disableEveryone === 'undefined' && this.rest.client.options.disableEveryone)) { + content = content.replace('@everyone', '@\u200beveryone').replace('@here', '@\u200bhere'); + } + + this.rest.makeRequest('post', `${Constants.Endpoints.webhook(webhook.id, webhook.token)}?wait=true`, false, { + content: content, username: webhook.name, avatar_url: avatarURL, tts: tts, file: file, embeds: embeds, + }) + .then(data => { + resolve(data); + }).catch(reject); + }); + } + + sendSlackWebhookMessage(webhook, body) { + return new Promise((resolve, reject) => { + this.rest.makeRequest( + 'post', + `${Constants.Endpoints.webhook(webhook.id, webhook.token)}/slack?wait=true`, + false, + body + ).then(data => { + resolve(data); + }).catch(reject); + }); + } + + addFriend(user) { + return new Promise((resolve, reject) => { + this.rest.makeRequest('post', Constants.Endpoints.relationships('@me'), true, { + discriminator: user.discriminator, + username: user.username, + }).then(() => { + resolve(user); + }).catch(reject); + }); + } + + removeFriend(user) { + return new Promise((resolve, reject) => { + this.rest.makeRequest('delete', `${Constants.Endpoints.relationships('@me')}/${user.id}`, true) + .then(() => { + resolve(user); + }).catch(reject); + }); + } + + fetchUserProfile(user) { + return new Promise((resolve, reject) => { + this.rest.makeRequest('get', Constants.Endpoints.userProfile(user.id), true) + .then(data => { + resolve(new UserProfile(user, data)); + }).catch(reject); + }); + } + + blockUser(user) { + return new Promise((resolve, reject) => { + this.rest.makeRequest('put', `${Constants.Endpoints.relationships('@me')}/${user.id}`, true, { type: 2 }) + .then(() => { + resolve(user); + }).catch(reject); + }); + } + + unblockUser(user) { + return new Promise((resolve, reject) => { + this.rest.makeRequest('delete', `${Constants.Endpoints.relationships('@me')}/${user.id}`, true) + .then(() => { + resolve(user); + }).catch(reject); + }); + } + + setRolePositions(guildID, roles) { + return new Promise((resolve, reject) => { + this.rest.makeRequest('patch', Constants.Endpoints.guildRoles(guildID), true, roles) + .then(() => { + resolve(this.rest.client.actions.GuildRolesPositionUpdate.handle({ + guild_id: guildID, + roles, + }).guild); + }) + .catch(reject); + }); + } } module.exports = RESTMethods; diff --git a/src/client/voice/ClientVoiceManager.js b/src/client/voice/ClientVoiceManager.js index bf9f99bdb..bd58989ee 100644 --- a/src/client/voice/ClientVoiceManager.js +++ b/src/client/voice/ClientVoiceManager.js @@ -2,6 +2,7 @@ const Collection = require('../../util/Collection'); const mergeDefault = require('../../util/MergeDefault'); const Constants = require('../../util/Constants'); const VoiceConnection = require('./VoiceConnection'); +const EventEmitter = require('events').EventEmitter; /** * Manages all the voice stuff for the Client @@ -26,52 +27,17 @@ class ClientVoiceManager { * @type {Collection} */ this.pending = new Collection(); + + this.client.on('self.voiceServer', this.onVoiceServer.bind(this)); + this.client.on('self.voiceStateUpdate', this.onVoiceStateUpdate.bind(this)); } - /** - * Checks whether a pending request can be processed - * @private - * @param {string} guildID The ID of the Guild - */ - _checkPendingReady(guildID) { - const pendingRequest = this.pending.get(guildID); - if (!pendingRequest) throw new Error('Guild not pending.'); - if (pendingRequest.token && pendingRequest.sessionID && pendingRequest.endpoint) { - const { channel, token, sessionID, endpoint, resolve, reject } = pendingRequest; - const voiceConnection = new VoiceConnection(this, channel, token, sessionID, endpoint, resolve, reject); - this.pending.delete(guildID); - this.connections.set(guildID, voiceConnection); - voiceConnection.once('disconnected', () => { - this.connections.delete(guildID); - }); - } + onVoiceServer(data) { + if (this.pending.has(data.guild_id)) this.pending.get(data.guild_id).setTokenAndEndpoint(data.token, data.endpoint); } - /** - * Called when the Client receives information about this voice server update. - * @param {string} guildID The ID of the Guild - * @param {string} token The token to authorise with - * @param {string} endpoint The endpoint to connect to - */ - _receivedVoiceServer(guildID, token, endpoint) { - const pendingRequest = this.pending.get(guildID); - if (!pendingRequest) throw new Error('Guild not pending.'); - pendingRequest.token = token; - // remove the port otherwise it errors ¯\_(ツ)_/¯ - pendingRequest.endpoint = endpoint.match(/([^:]*)/)[0]; - this._checkPendingReady(guildID); - } - - /** - * Called when the Client receives information about the voice state update. - * @param {string} guildID The ID of the Guild - * @param {string} sessionID The session id to authorise with - */ - _receivedVoiceStateUpdate(guildID, sessionID) { - const pendingRequest = this.pending.get(guildID); - if (!pendingRequest) throw new Error('Guild not pending.'); - pendingRequest.sessionID = sessionID; - this._checkPendingReady(guildID); + onVoiceStateUpdate(data) { + if (this.pending.has(data.guild_id)) this.pending.get(data.guild_id).setSessionID(data.session_id); } /** @@ -79,13 +45,26 @@ class ClientVoiceManager { * @param {VoiceChannel} channel The channel to join * @param {Object} [options] The options to provide */ - _sendWSJoin(channel, options = {}) { + sendVoiceStateUpdate(channel, options = {}) { + if (!this.client.user) throw new Error('Unable to join because there is no client user.'); + if (!channel.permissionsFor) { + throw new Error('Channel does not support permissionsFor; is it really a voice channel?'); + } + const permissions = channel.permissionsFor(this.client.user); + if (!permissions) { + throw new Error('There is no permission set for the client user in this channel - are they part of the guild?'); + } + if (!permissions.hasPermission('CONNECT')) { + throw new Error('You do not have permission to connect to this voice channel.'); + } + options = mergeDefault({ guild_id: channel.guild.id, channel_id: channel.id, self_mute: false, self_deaf: false, }, options); + this.client.ws.send({ op: Constants.OPCodes.VOICE_STATE_UPDATE, d: options, @@ -99,28 +78,171 @@ class ClientVoiceManager { */ joinChannel(channel) { return new Promise((resolve, reject) => { - if (this.pending.get(channel.guild.id)) throw new Error(`Already connecting to a channel in guild.`); - const existingConn = this.connections.get(channel.guild.id); - if (existingConn) { - if (existingConn.channel.id !== channel.id) { - this._sendWSJoin(channel); + if (this.pending.get(channel.guild.id)) throw new Error('Already connecting to this guild\'s voice server.'); + + if (!channel.permissionsFor(this.client.user).hasPermission('CONNECT')) { + throw new Error('You do not have permission to join this voice channel'); + } + + const existingConnection = this.connections.get(channel.guild.id); + if (existingConnection) { + if (existingConnection.channel.id !== channel.id) { + this.sendVoiceStateUpdate(channel); this.connections.get(channel.guild.id).channel = channel; } - resolve(existingConn); + resolve(existingConnection); return; } - this.pending.set(channel.guild.id, { - channel, - sessionID: null, - token: null, - endpoint: null, - resolve, - reject, + + const pendingConnection = new PendingVoiceConnection(this, channel); + this.pending.set(channel.guild.id, pendingConnection); + + pendingConnection.on('fail', reason => { + this.pending.delete(channel.guild.id); + reject(reason); + }); + + pendingConnection.on('pass', voiceConnection => { + this.pending.delete(channel.guild.id); + this.connections.set(channel.guild.id, voiceConnection); + voiceConnection.once('ready', () => resolve(voiceConnection)); + voiceConnection.once('error', reject); + voiceConnection.once('disconnect', () => this.connections.delete(channel.guild.id)); }); - this._sendWSJoin(channel); - this.client.setTimeout(() => reject(new Error('Connection not established within 15 seconds.')), 15000); }); } } +/** + * Represents a Pending Voice Connection + * @private + */ +class PendingVoiceConnection extends EventEmitter { + constructor(voiceManager, channel) { + super(); + + /** + * The ClientVoiceManager that instantiated this pending connection + * @type {ClientVoiceManager} + */ + this.voiceManager = voiceManager; + + /** + * The channel that this pending voice connection will attempt to join + * @type {VoiceChannel} + */ + this.channel = channel; + + /** + * The timeout that will be invoked after 15 seconds signifying a failure to connect + * @type {Timeout} + */ + this.deathTimer = this.voiceManager.client.setTimeout( + () => this.fail(new Error('Connection not established within 15 seconds.')), 15000); + + /** + * An object containing data required to connect to the voice servers with + * @type {object} + */ + this.data = {}; + + this.sendVoiceStateUpdate(); + } + + checkReady() { + if (this.data.token && this.data.endpoint && this.data.session_id) { + this.pass(); + return true; + } else { + return false; + } + } + + /** + * Set the token and endpoint required to connect to the the voice servers + * @param {string} token the token + * @param {string} endpoint the endpoint + * @returns {void} + */ + setTokenAndEndpoint(token, endpoint) { + if (!token) { + this.fail(new Error('Token not provided from voice server packet.')); + return; + } + if (!endpoint) { + this.fail(new Error('Endpoint not provided from voice server packet.')); + return; + } + if (this.data.token) { + this.fail(new Error('There is already a registered token for this connection.')); + return; + } + if (this.data.endpoint) { + this.fail(new Error('There is already a registered endpoint for this connection.')); + return; + } + + endpoint = endpoint.match(/([^:]*)/)[0]; + + if (!endpoint) { + this.fail(new Error('Failed to find an endpoint.')); + return; + } + + this.data.token = token; + this.data.endpoint = endpoint; + + this.checkReady(); + } + + /** + * Sets the Session ID for the connection + * @param {string} sessionID the session ID + */ + setSessionID(sessionID) { + if (!sessionID) { + this.fail(new Error('Session ID not supplied.')); + return; + } + if (this.data.session_id) { + this.fail(new Error('There is already a registered session ID for this connection.')); + return; + } + this.data.session_id = sessionID; + + this.checkReady(); + } + + clean() { + clearInterval(this.deathTimer); + this.emit('fail', new Error('Clean-up triggered :fourTriggered:')); + } + + pass() { + clearInterval(this.deathTimer); + this.emit('pass', this.upgrade()); + } + + fail(reason) { + this.emit('fail', reason); + this.clean(); + } + + sendVoiceStateUpdate() { + try { + this.voiceManager.sendVoiceStateUpdate(this.channel); + } catch (error) { + this.fail(error); + } + } + + /** + * Upgrades this Pending Connection to a full Voice Connection + * @returns {VoiceConnection} + */ + upgrade() { + return new VoiceConnection(this); + } +} + module.exports = ClientVoiceManager; diff --git a/src/client/voice/VoiceConnection.js b/src/client/voice/VoiceConnection.js index 73f9b9d87..7490be89e 100644 --- a/src/client/voice/VoiceConnection.js +++ b/src/client/voice/VoiceConnection.js @@ -1,9 +1,10 @@ -const VoiceConnectionWebSocket = require('./VoiceConnectionWebSocket'); -const VoiceConnectionUDPClient = require('./VoiceConnectionUDPClient'); -const VoiceReceiver = require('./receiver/VoiceReceiver'); +const VoiceWebSocket = require('./VoiceWebSocket'); +const VoiceUDP = require('./VoiceUDPClient'); const Constants = require('../../util/Constants'); +const AudioPlayer = require('./player/AudioPlayer'); +const VoiceReceiver = require('./receiver/VoiceReceiver'); const EventEmitter = require('events').EventEmitter; -const DefaultPlayer = require('./player/DefaultPlayer'); +const fs = require('fs'); /** * Represents a connection to a Voice Channel in Discord. @@ -16,89 +17,101 @@ const DefaultPlayer = require('./player/DefaultPlayer'); * @extends {EventEmitter} */ class VoiceConnection extends EventEmitter { - constructor(manager, channel, token, sessionID, endpoint, resolve, reject) { + + constructor(pendingConnection) { super(); - /** - * The voice manager of this connection + * The Voice Manager that instantiated this connection * @type {ClientVoiceManager} - * @private */ - this.manager = manager; + this.voiceManager = pendingConnection.voiceManager; /** - * The player - * @type {BasePlayer} - */ - this.player = new DefaultPlayer(this); - - /** - * The endpoint of the connection - * @type {string} - */ - this.endpoint = endpoint; - - /** - * The VoiceChannel for this connection + * The voice channel this connection is currently serving * @type {VoiceChannel} */ - this.channel = channel; + this.channel = pendingConnection.channel; /** - * The WebSocket connection for this voice connection - * @type {VoiceConnectionWebSocket} - * @private + * An array of Voice Receivers that have been created for this connection + * @type {VoiceReceiver[]} */ - this.websocket = new VoiceConnectionWebSocket(this, channel.guild.id, token, sessionID, endpoint); - - /** - * Whether or not the connection is ready - * @type {boolean} - */ - this.ready = false; - - /** - * The resolve function for the promise associated with creating this connection - * @type {function} - * @private - */ - this._resolve = resolve; - - /** - * The reject function for the promise associated with creating this connection - * @type {function} - * @private - */ - this._reject = reject; - - this.ssrcMap = new Map(); - this.queue = []; this.receivers = []; - this.bindListeners(); - } - /** - * Executed whenever an error occurs with the UDP/WebSocket sub-client. - * @private - * @param {Error} err The encountered error - */ - _onError(err) { - this._reject(err); /** - * Emitted whenever the connection encounters a fatal error. - * @event VoiceConnection#error - * @param {Error} error The encountered error + * The authentication data needed to connect to the voice server + * @type {object} + * @private */ - this.emit('error', err); - this._shutdown(err); + this.authentication = pendingConnection.data; + + /** + * The audio player for this voice connection + * @type {AudioPlayer} + */ + this.player = new AudioPlayer(this); + + this.player.on('debug', m => { + /** + * Debug info from the connection + * @event VoiceConnection#debug + * @param {string} message the debug message + */ + this.emit('debug', `audio player - ${m}`); + }); + + this.player.on('error', e => { + /** + * Warning info from the connection + * @event VoiceConnection#warn + * @param {string|error} warning the warning + */ + this.emit('warn', e); + this.player.cleanup(); + }); + + /** + * Map SSRC to speaking values + * @type {Map} + * @private + */ + this.ssrcMap = new Map(); + + /** + * Object that wraps contains the `ws` and `udp` sockets of this voice connection + * @type {object} + * @private + */ + this.sockets = {}; + this.connect(); } /** - * Disconnects the Client from the Voice Channel. - * @param {string} [reason='user requested'] The reason of the disconnection + * Sets whether the voice connection should display as "speaking" or not + * @param {boolean} value whether or not to speak + * @private */ - disconnect(reason = 'user requested') { - this.manager.client.ws.send({ + setSpeaking(value) { + if (this.speaking === value) return; + this.speaking = value; + this.sockets.ws.sendPacket({ + op: Constants.VoiceOPCodes.SPEAKING, + d: { + speaking: true, + delay: 0, + }, + }) + .catch(e => { + this.emit('debug', e); + }); + } + + /** + * Disconnect the voice connection, causing a disconnect and closing event to be emitted. + */ + disconnect() { + this.emit('closing'); + this.voiceManager.client.ws.send({ op: Constants.OPCodes.VOICE_STATE_UPDATE, d: { guild_id: this.channel.guild.id, @@ -107,81 +120,51 @@ class VoiceConnection extends EventEmitter { self_deaf: false, }, }); - this._shutdown(reason); - } - - _onClose(e) { - e = e && e.code === 1000 ? null : e; - return this._shutdown(e); - } - - _shutdown(e) { - if (!this.ready) return; - this.ready = false; - this.websocket._shutdown(); - this.player._shutdown(); - if (this.udp) this.udp._shutdown(); - if (this._vsUpdateListener) this.manager.client.removeListener('voiceStateUpdate', this._vsUpdateListener); /** - * Emit once the voice connection has disconnected. - * @event VoiceConnection#disconnected - * @param {Error} error The encountered error, if any + * Emitted when the voice connection disconnects + * @event VoiceConnection#disconnect */ - this.emit('disconnected', e); + this.emit('disconnect'); } /** - * Binds listeners to the WebSocket and UDP sub-clients. + * Connect the voice connection * @private */ - bindListeners() { - this.websocket.on('error', err => this._onError(err)); - this.websocket.on('close', err => this._onClose(err)); - this.websocket.on('ready-for-udp', data => { - this.udp = new VoiceConnectionUDPClient(this, data); - this.data = data; - this.udp.on('error', err => this._onError(err)); - this.udp.on('close', err => this._onClose(err)); - }); - this.websocket.on('ready', secretKey => { - this.data.secret = secretKey; - this.ready = true; + connect() { + if (this.sockets.ws) throw new Error('There is already an existing WebSocket connection.'); + if (this.sockets.udp) throw new Error('There is already an existing UDP connection.'); + this.sockets.ws = new VoiceWebSocket(this); + this.sockets.udp = new VoiceUDP(this); + this.sockets.ws.on('error', e => this.emit('error', e)); + this.sockets.udp.on('error', e => this.emit('error', e)); + this.sockets.ws.once('ready', d => { + this.authentication.port = d.port; + this.authentication.ssrc = d.ssrc; /** - * Emitted once the connection is ready (joining voice channels resolves when the connection is ready anyway) + * Emitted whenever the connection encounters an error. + * @event VoiceConnection#error + * @param {Error} error the encountered error + */ + this.sockets.udp.findEndpointAddress() + .then(address => { + this.sockets.udp.createUDPSocket(address); + }) + .catch(e => this.emit('error', e)); + }); + this.sockets.ws.once('sessionDescription', (mode, secret) => { + this.authentication.encryptionMode = mode; + this.authentication.secretKey = secret; + /** + * Emitted once the connection is ready, when a promise to join a voice channel resolves, + * the connection will already be ready. * @event VoiceConnection#ready */ - this._resolve(this); this.emit('ready'); }); - this.once('ready', () => { - setImmediate(() => { - for (const item of this.queue) this.emit(...item); - this.queue = []; - }); - }); - this._vsUpdateListener = (oldM, newM) => { - if (oldM.voiceChannel && oldM.voiceChannel.guild.id === this.channel.guild.id && !newM.voiceChannel) { - const user = newM.user; - for (const receiver of this.receivers) { - const opusStream = receiver.opusStreams.get(user.id); - const pcmStream = receiver.pcmStreams.get(user.id); - if (opusStream) { - opusStream.push(null); - opusStream.open = false; - receiver.opusStreams.delete(user.id); - } - if (pcmStream) { - pcmStream.push(null); - pcmStream.open = false; - receiver.pcmStreams.delete(user.id); - } - } - } - }; - this.manager.client.on(Constants.Events.VOICE_STATE_UPDATE, this._vsUpdateListener); - this.websocket.on('speaking', data => { + this.sockets.ws.on('speaking', data => { const guild = this.channel.guild; - const user = this.manager.client.users.get(data.user_id); + const user = this.voiceManager.client.users.get(data.user_id); this.ssrcMap.set(+data.ssrc, user); if (!data.speaking) { for (const receiver of this.receivers) { @@ -206,7 +189,6 @@ class VoiceConnection extends EventEmitter { * @param {boolean} speaking Whether or not the user is speaking */ if (this.ready) this.emit('speaking', user, data.speaking); - else this.queue.push(['speaking', user, data.speaking]); guild._memberSpeakUpdate(data.user_id, data.speaking); }); } @@ -232,9 +214,8 @@ class VoiceConnection extends EventEmitter { * }) * .catch(console.log); */ - playFile(file, { seek = 0, volume = 1, passes = 1 } = {}) { - const options = { seek, volume, passes }; - return this.player.playFile(file, options); + playFile(file, options) { + return this.playStream(fs.createReadStream(file), options); } /** @@ -255,7 +236,7 @@ class VoiceConnection extends EventEmitter { */ playStream(stream, { seek = 0, volume = 1, passes = 1 } = {}) { const options = { seek, volume, passes }; - return this.player.playStream(stream, options); + return this.player.playUnknownStream(stream, options); } /** @@ -266,7 +247,6 @@ class VoiceConnection extends EventEmitter { */ playConvertedStream(stream, { seek = 0, volume = 1, passes = 1 } = {}) { const options = { seek, volume, passes }; - this.player._shutdown(); return this.player.playPCMStream(stream, options); } @@ -275,9 +255,9 @@ class VoiceConnection extends EventEmitter { * @returns {VoiceReceiver} */ createReceiver() { - const rcv = new VoiceReceiver(this); - this.receivers.push(rcv); - return rcv; + const receiver = new VoiceReceiver(this); + this.receivers.push(receiver); + return receiver; } } diff --git a/src/client/voice/VoiceConnectionUDPClient.js b/src/client/voice/VoiceConnectionUDPClient.js deleted file mode 100644 index add7b9c4f..000000000 --- a/src/client/voice/VoiceConnectionUDPClient.js +++ /dev/null @@ -1,84 +0,0 @@ -const udp = require('dgram'); -const dns = require('dns'); -const Constants = require('../../util/Constants'); -const EventEmitter = require('events').EventEmitter; - -class VoiceConnectionUDPClient extends EventEmitter { - constructor(voiceConnection, data) { - super(); - this.voiceConnection = voiceConnection; - this.count = 0; - this.data = data; - this.dnsLookup(); - } - - dnsLookup() { - dns.lookup(this.voiceConnection.endpoint, (err, address) => { - if (err) { - this.emit('error', err); - return; - } - this.connectUDP(address); - }); - } - - send(packet) { - if (this.udpSocket) { - try { - this.udpSocket.send(packet, 0, packet.length, this.data.port, this.udpIP); - } catch (err) { - this.emit('error', err); - } - } - } - - _shutdown() { - if (this.udpSocket) { - try { - this.udpSocket.close(); - } catch (err) { - if (err.message !== 'Not running') this.emit('error', err); - } - this.udpSocket = null; - } - } - - connectUDP(address) { - this.udpIP = address; - this.udpSocket = udp.createSocket('udp4'); - - // finding local IP - // https://discordapp.com/developers/docs/topics/voice-connections#ip-discovery - this.udpSocket.once('message', message => { - const packet = new Buffer(message); - this.localIP = ''; - for (let i = 4; i < packet.indexOf(0, i); i++) this.localIP += String.fromCharCode(packet[i]); - this.localPort = parseInt(packet.readUIntLE(packet.length - 2, 2).toString(10), 10); - - this.voiceConnection.websocket.send({ - op: Constants.VoiceOPCodes.SELECT_PROTOCOL, - d: { - protocol: 'udp', - data: { - address: this.localIP, - port: this.localPort, - mode: 'xsalsa20_poly1305', - }, - }, - }); - }); - - this.udpSocket.on('error', (error, message) => { - this.emit('error', { error, message }); - }); - this.udpSocket.on('close', error => { - this.emit('close', error); - }); - - const blankMessage = new Buffer(70); - blankMessage.writeUIntBE(this.data.ssrc, 0, 4); - this.send(blankMessage); - } -} - -module.exports = VoiceConnectionUDPClient; diff --git a/src/client/voice/VoiceConnectionWebSocket.js b/src/client/voice/VoiceConnectionWebSocket.js deleted file mode 100644 index fdb0fe0f7..000000000 --- a/src/client/voice/VoiceConnectionWebSocket.js +++ /dev/null @@ -1,113 +0,0 @@ -const WebSocket = require('ws'); -const Constants = require('../../util/Constants'); -const EventEmitter = require('events').EventEmitter; - -class VoiceConnectionWebSocket extends EventEmitter { - constructor(voiceConnection, serverID, token, sessionID, endpoint) { - super(); - this.voiceConnection = voiceConnection; - this.token = token; - this.sessionID = sessionID; - this.serverID = serverID; - this.heartbeat = null; - this.opened = false; - this.endpoint = endpoint; - this.attempts = 6; - this.setupWS(); - } - - setupWS() { - this.attempts--; - this.ws = new WebSocket(`wss://${this.endpoint}`, null, { rejectUnauthorized: false }); - this.ws.onopen = () => this._onOpen(); - this.ws.onmessage = e => this._onMessage(e); - this.ws.onclose = e => this._onClose(e); - this.ws.onerror = e => this._onError(e); - } - - send(data) { - if (this.ws.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify(data)); - } - - _shutdown() { - if (this.ws) this.ws.close(); - this.voiceConnection.manager.client.clearInterval(this.heartbeat); - } - - _onOpen() { - this.opened = true; - this.send({ - op: Constants.OPCodes.DISPATCH, - d: { - server_id: this.serverID, - user_id: this.voiceConnection.manager.client.user.id, - session_id: this.sessionID, - token: this.token, - }, - }); - } - - _onClose(err) { - if (!this.opened && this.attempts >= 0) { - this.setupWS(); - return; - } - this.emit('close', err); - } - - _onError(e) { - if (!this.opened && this.attempts >= 0) { - this.setupWS(); - return; - } - this.emit('error', e); - } - - _setHeartbeat(interval) { - this.heartbeat = this.voiceConnection.manager.client.setInterval(() => { - this.send({ - op: Constants.VoiceOPCodes.HEARTBEAT, - d: null, - }); - }, interval); - this.send({ - op: Constants.VoiceOPCodes.HEARTBEAT, - d: null, - }); - } - - _onMessage(event) { - let packet; - try { - packet = JSON.parse(event.data); - } catch (error) { - this._onError(error); - return; - } - - switch (packet.op) { - case Constants.VoiceOPCodes.READY: - this._setHeartbeat(packet.d.heartbeat_interval); - this.emit('ready-for-udp', packet.d); - break; - case Constants.VoiceOPCodes.SESSION_DESCRIPTION: - this.encryptionMode = packet.d.mode; - this.secretKey = new Uint8Array(new ArrayBuffer(packet.d.secret_key.length)); - for (const index in packet.d.secret_key) this.secretKey[index] = packet.d.secret_key[index]; - this.emit('ready', this.secretKey); - break; - case Constants.VoiceOPCodes.SPEAKING: - /* - { op: 5, - d: { user_id: '123123', ssrc: 1, speaking: true } } - */ - this.emit('speaking', packet.d); - break; - default: - this.emit('unknown', packet); - break; - } - } -} - -module.exports = VoiceConnectionWebSocket; diff --git a/src/client/voice/VoiceUDPClient.js b/src/client/voice/VoiceUDPClient.js new file mode 100644 index 000000000..8246478c3 --- /dev/null +++ b/src/client/voice/VoiceUDPClient.js @@ -0,0 +1,145 @@ +const udp = require('dgram'); +const dns = require('dns'); +const Constants = require('../../util/Constants'); +const EventEmitter = require('events').EventEmitter; + +function parseLocalPacket(message) { + try { + const packet = new Buffer(message); + let address = ''; + for (let i = 4; i < packet.indexOf(0, i); i++) address += String.fromCharCode(packet[i]); + const port = parseInt(packet.readUIntLE(packet.length - 2, 2).toString(10), 10); + return { address, port }; + } catch (error) { + return { error }; + } +} + +/** + * Represents a UDP Client for a Voice Connection + * @extends {EventEmitter} + * @private + */ +class VoiceConnectionUDPClient extends EventEmitter { + constructor(voiceConnection) { + super(); + + /** + * The voice connection that this UDP client serves + * @type {VoiceConnection} + */ + this.voiceConnection = voiceConnection; + + /** + * The UDP socket + * @type {?Socket} + */ + this.socket = null; + + /** + * The address of the discord voice server + * @type {?string} + */ + this.discordAddress = null; + + /** + * The local IP address + * @type {?string} + */ + this.localAddress = null; + + /** + * The local port + * @type {?string} + */ + this.localPort = null; + + this.voiceConnection.on('closing', this.shutdown.bind(this)); + } + + shutdown() { + if (this.socket) { + try { + this.socket.close(); + } catch (e) { + return; + } + this.socket = null; + } + } + + /** + * The port of the discord voice server + * @type {number} + * @readonly + */ + get discordPort() { + return this.voiceConnection.authentication.port; + } + + /** + * Tries to resolve the voice server endpoint to an address + * @returns {Promise} + */ + findEndpointAddress() { + return new Promise((resolve, reject) => { + dns.lookup(this.voiceConnection.authentication.endpoint, (error, address) => { + if (error) { + reject(error); + return; + } + this.discordAddress = address; + resolve(address); + }); + }); + } + + /** + * Send a packet to the UDP client + * @param {Object} packet the packet to send + * @returns {Promise} + */ + send(packet) { + return new Promise((resolve, reject) => { + if (!this.socket) throw new Error('Tried to send a UDP packet, but there is no socket available.'); + if (!this.discordAddress || !this.discordPort) throw new Error('Malformed UDP address or port.'); + this.socket.send(packet, 0, packet.length, this.discordPort, this.discordAddress, error => { + if (error) reject(error); else resolve(packet); + }); + }); + } + + createUDPSocket(address) { + this.discordAddress = address; + const socket = this.socket = udp.createSocket('udp4'); + + socket.once('message', message => { + const packet = parseLocalPacket(message); + if (packet.error) { + this.emit('error', packet.error); + return; + } + + this.localAddress = packet.address; + this.localPort = packet.port; + + this.voiceConnection.sockets.ws.sendPacket({ + op: Constants.VoiceOPCodes.SELECT_PROTOCOL, + d: { + protocol: 'udp', + data: { + address: packet.address, + port: packet.port, + mode: 'xsalsa20_poly1305', + }, + }, + }); + }); + + const blankMessage = new Buffer(70); + blankMessage.writeUIntBE(this.voiceConnection.authentication.ssrc, 0, 4); + this.send(blankMessage); + } +} + +module.exports = VoiceConnectionUDPClient; diff --git a/src/client/voice/VoiceWebSocket.js b/src/client/voice/VoiceWebSocket.js new file mode 100644 index 000000000..1c421a71b --- /dev/null +++ b/src/client/voice/VoiceWebSocket.js @@ -0,0 +1,244 @@ +const WebSocket = require('ws'); +const Constants = require('../../util/Constants'); +const SecretKey = require('./util/SecretKey'); +const EventEmitter = require('events').EventEmitter; + +/** + * Represents a Voice Connection's WebSocket + * @extends {EventEmitter} + * @private + */ +class VoiceWebSocket extends EventEmitter { + constructor(voiceConnection) { + super(); + + /** + * The Voice Connection that this WebSocket serves + * @type {VoiceConnection} + */ + this.voiceConnection = voiceConnection; + + /** + * How many connection attempts have been made + * @type {number} + */ + this.attempts = 0; + + this.connect(); + this.dead = false; + this.voiceConnection.on('closing', this.shutdown.bind(this)); + } + + shutdown() { + this.dead = true; + this.reset(); + } + + /** + * The client of this voice websocket + * @type {Client} + * @readonly + */ + get client() { + return this.voiceConnection.voiceManager.client; + } + + /** + * Resets the current WebSocket + */ + reset() { + if (this.ws) { + if (this.ws.readyState !== WebSocket.CLOSED) this.ws.close(); + this.ws = null; + } + this.clearHeartbeat(); + } + + /** + * Starts connecting to the Voice WebSocket Server. + */ + connect() { + if (this.dead) return; + if (this.ws) this.reset(); + if (this.attempts > 5) { + this.emit('error', new Error(`Too many connection attempts (${this.attempts}).`)); + return; + } + + this.attempts++; + + /** + * The actual WebSocket used to connect to the Voice WebSocket Server. + * @type {WebSocket} + */ + this.ws = new WebSocket(`wss://${this.voiceConnection.authentication.endpoint}`); + this.ws.onopen = this.onOpen.bind(this); + this.ws.onmessage = this.onMessage.bind(this); + this.ws.onclose = this.onClose.bind(this); + this.ws.onerror = this.onError.bind(this); + } + + /** + * Sends data to the WebSocket if it is open. + * @param {string} data the data to send to the WebSocket + * @returns {Promise} + */ + send(data) { + return new Promise((resolve, reject) => { + if (!this.ws || this.ws.readyState !== WebSocket.OPEN) { + throw new Error(`Voice websocket not open to send ${data}.`); + } + this.ws.send(data, null, error => { + if (error) reject(error); else resolve(data); + }); + }); + } + + /** + * JSON.stringify's a packet and then sends it to the WebSocket Server. + * @param {Object} packet the packet to send + * @returns {Promise} + */ + sendPacket(packet) { + try { + packet = JSON.stringify(packet); + } catch (error) { + return Promise.reject(error); + } + return this.send(packet); + } + + /** + * Called whenever the WebSocket opens + */ + onOpen() { + this.sendPacket({ + op: Constants.OPCodes.DISPATCH, + d: { + server_id: this.voiceConnection.channel.guild.id, + user_id: this.client.user.id, + token: this.voiceConnection.authentication.token, + session_id: this.voiceConnection.authentication.session_id, + }, + }).catch(() => { + this.emit('error', new Error('Tried to send join packet, but the WebSocket is not open.')); + }); + } + + /** + * Called whenever a message is received from the WebSocket + * @param {MessageEvent} event the message event that was received + * @returns {void} + */ + onMessage(event) { + try { + return this.onPacket(JSON.parse(event.data)); + } catch (error) { + return this.onError(error); + } + } + + /** + * Called whenever the connection to the WebSocket Server is lost + */ + onClose() { + // TODO see if the connection is open before reconnecting + if (!this.dead) this.client.setTimeout(this.connect.bind(this), this.attempts * 1000); + } + + /** + * Called whenever an error occurs with the WebSocket. + * @param {Error} error the error that occurred + */ + onError(error) { + this.emit('error', error); + } + + /** + * Called whenever a valid packet is received from the WebSocket + * @param {Object} packet the received packet + */ + onPacket(packet) { + switch (packet.op) { + case Constants.VoiceOPCodes.READY: + this.setHeartbeat(packet.d.heartbeat_interval); + /** + * Emitted once the voice websocket receives the ready packet + * @param {Object} packet the received packet + * @event VoiceWebSocket#ready + */ + this.emit('ready', packet.d); + break; + case Constants.VoiceOPCodes.SESSION_DESCRIPTION: + /** + * Emitted once the Voice Websocket receives a description of this voice session + * @param {string} encryptionMode the type of encryption being used + * @param {SecretKey} secretKey the secret key used for encryption + * @event VoiceWebSocket#sessionDescription + */ + this.emit('sessionDescription', packet.d.mode, new SecretKey(packet.d.secret_key)); + break; + case Constants.VoiceOPCodes.SPEAKING: + /** + * Emitted whenever a speaking packet is received + * @param {Object} data + * @event VoiceWebSocket#speaking + */ + this.emit('speaking', packet.d); + break; + default: + /** + * Emitted when an unhandled packet is received + * @param {Object} packet + * @event VoiceWebSocket#unknownPacket + */ + this.emit('unknownPacket', packet); + break; + } + } + + /** + * Sets an interval at which to send a heartbeat packet to the WebSocket + * @param {number} interval the interval at which to send a heartbeat packet + */ + setHeartbeat(interval) { + if (!interval || isNaN(interval)) { + this.onError(new Error('Tried to set voice heartbeat but no valid interval was specified.')); + return; + } + if (this.heartbeatInterval) { + /** + * Emitted whenver the voice websocket encounters a non-fatal error + * @param {string} warn the warning + * @event VoiceWebSocket#warn + */ + this.emit('warn', 'A voice heartbeat interval is being overwritten'); + clearInterval(this.heartbeatInterval); + } + this.heartbeatInterval = this.client.setInterval(this.sendHeartbeat.bind(this), interval); + } + + /** + * Clears a heartbeat interval, if one exists + */ + clearHeartbeat() { + if (!this.heartbeatInterval) { + this.emit('warn', 'Tried to clear a heartbeat interval that does not exist'); + return; + } + clearInterval(this.heartbeatInterval); + this.heartbeatInterval = null; + } + + /** + * Sends a heartbeat packet + */ + sendHeartbeat() { + this.sendPacket({ op: Constants.VoiceOPCodes.HEARTBEAT, d: null }).catch(() => { + this.emit('warn', 'Tried to send heartbeat, but connection is not open'); + this.clearHeartbeat(); + }); + } +} + +module.exports = VoiceWebSocket; diff --git a/src/client/voice/dispatcher/StreamDispatcher.js b/src/client/voice/dispatcher/StreamDispatcher.js index 887c0d82a..961ad97f4 100644 --- a/src/client/voice/dispatcher/StreamDispatcher.js +++ b/src/client/voice/dispatcher/StreamDispatcher.js @@ -32,34 +32,25 @@ class StreamDispatcher extends EventEmitter { this._startStreaming(); this._triggered = false; this._volume = streamOptions.volume; + /** * How many passes the dispatcher should take when sending packets to reduce packet loss. Values over 5 * aren't recommended, as it means you are using 5x more bandwidth. You _can_ edit this at runtime. * @type {number} */ this.passes = streamOptions.passes || 1; + + /** + * Whether playing is paused + * @type {boolean} + */ + this.paused = false; + + this.setVolume(streamOptions.volume || 1); } /** - * Emitted when the dispatcher starts/stops speaking - * @event StreamDispatcher#speaking - * @param {boolean} value Whether or not the dispatcher is speaking - */ - _setSpeaking(value) { - this.speaking = value; - this.emit('speaking', value); - } - - _sendBuffer(buffer, sequence, timestamp) { - let repeats = this.passes; - const packet = this._createPacket(sequence, timestamp, this.player.opusEncoder.encode(buffer)); - while (repeats--) { - this.player.connection.udp.send(packet); - } - } - - /** - * how long the stream dispatcher has been "speaking" for + * How long the stream dispatcher has been "speaking" for * @type {number} * @readonly */ @@ -68,7 +59,7 @@ class StreamDispatcher extends EventEmitter { } /** - * The total time, taking into account pauses and skips, that the dispatcher has been streaming for. + * The total time, taking into account pauses and skips, that the dispatcher has been streaming for * @type {number} * @readonly */ @@ -76,176 +67,6 @@ class StreamDispatcher extends EventEmitter { return this.time + this.streamingData.pausedTime; } - _createPacket(sequence, timestamp, buffer) { - const packetBuffer = new Buffer(buffer.length + 28); - packetBuffer.fill(0); - packetBuffer[0] = 0x80; - packetBuffer[1] = 0x78; - - packetBuffer.writeUIntBE(sequence, 2, 2); - packetBuffer.writeUIntBE(timestamp, 4, 4); - packetBuffer.writeUIntBE(this.player.connection.data.ssrc, 8, 4); - - packetBuffer.copy(nonce, 0, 0, 12); - buffer = NaCl.secretbox(buffer, nonce, this.player.connection.data.secret); - - for (let i = 0; i < buffer.length; i++) packetBuffer[i + 12] = buffer[i]; - - return packetBuffer; - } - - _applyVolume(buffer) { - if (this._volume === 1) return buffer; - - const out = new Buffer(buffer.length); - for (let i = 0; i < buffer.length; i += 2) { - if (i >= buffer.length - 1) break; - const uint = Math.min(32767, Math.max(-32767, Math.floor(this._volume * buffer.readInt16LE(i)))); - out.writeInt16LE(uint, i); - } - - return out; - } - - _send() { - try { - if (this._triggered) { - this._setSpeaking(false); - return; - } - - const data = this.streamingData; - - if (data.missed >= 5) { - this._triggerTerminalState('end', 'Stream is not generating quickly enough.'); - return; - } - - if (this.paused) { - // data.timestamp = data.timestamp + 4294967295 ? data.timestamp + 960 : 0; - data.pausedTime += data.length * 10; - this.player.connection.manager.client.setTimeout(() => this._send(), data.length * 10); - return; - } - - this._setSpeaking(true); - - if (!data.startTime) { - /** - * Emitted once the dispatcher starts streaming - * @event StreamDispatcher#start - */ - this.emit('start'); - data.startTime = Date.now(); - } - - const bufferLength = 1920 * data.channels; - let buffer = this.stream.read(bufferLength); - if (!buffer) { - data.missed++; - data.pausedTime += data.length * 10; - this.player.connection.manager.client.setTimeout(() => this._send(), data.length * 10); - return; - } - - data.missed = 0; - - if (buffer.length !== bufferLength) { - const newBuffer = new Buffer(bufferLength).fill(0); - buffer.copy(newBuffer); - buffer = newBuffer; - } - - buffer = this._applyVolume(buffer); - - data.count++; - data.sequence = (data.sequence + 1) < (65536) ? data.sequence + 1 : 0; - data.timestamp = data.timestamp + 4294967295 ? data.timestamp + 960 : 0; - - this._sendBuffer(buffer, data.sequence, data.timestamp); - - const nextTime = data.length + (data.startTime + data.pausedTime + (data.count * data.length) - Date.now()); - this.player.connection.manager.client.setTimeout(() => this._send(), nextTime); - } catch (e) { - this._triggerTerminalState('error', e); - } - } - - /** - * Emitted once the stream has ended. Attach a `once` listener to this. - * @event StreamDispatcher#end - */ - _triggerEnd() { - this.emit('end'); - } - - /** - * Emitted once the stream has encountered an error. Attach a `once` listener to this. Also emits `end`. - * @event StreamDispatcher#error - * @param {Error} err The encountered error - */ - _triggerError(err) { - this.emit('end'); - this.emit('error', err); - } - - _triggerTerminalState(state, err) { - if (this._triggered) return; - - /** - * Emitted when the stream wants to give debug information. - * @event StreamDispatcher#debug - * @param {string} information The debug information - */ - this.emit('debug', `Triggered terminal state ${state} - stream is now dead`); - this._triggered = true; - this._setSpeaking(false); - switch (state) { - case 'end': - this._triggerEnd(err); - break; - case 'error': - this._triggerError(err); - break; - default: - this.emit('error', 'Unknown trigger state'); - break; - } - } - - _startStreaming() { - if (!this.stream) { - this.emit('error', 'No stream'); - return; - } - - this.stream.on('end', err => this._triggerTerminalState('end', err)); - this.stream.on('error', err => this._triggerTerminalState('error', err)); - - const data = this.streamingData; - data.length = 20; - data.missed = 0; - - this.stream.once('readable', () => this._send()); - } - - _setPaused(paused) { - if (paused) { - this.paused = true; - this._setSpeaking(false); - } else { - this.paused = false; - this._setSpeaking(true); - } - } - - /** - * Stops the current stream permanently and emits an `end` event. - */ - end() { - this._triggerTerminalState('end', 'user requested'); - } - /** * The volume of the stream, relative to the stream's input volume * @type {number} @@ -292,6 +113,194 @@ class StreamDispatcher extends EventEmitter { resume() { this._setPaused(false); } + + /** + * Stops the current stream permanently and emits an `end` event. + */ + end() { + this._triggerTerminalState('end', 'user requested'); + } + + _setSpeaking(value) { + this.speaking = value; + /** + * Emitted when the dispatcher starts/stops speaking + * @event StreamDispatcher#speaking + * @param {boolean} value Whether or not the dispatcher is speaking + */ + this.emit('speaking', value); + } + + _sendBuffer(buffer, sequence, timestamp) { + let repeats = this.passes; + const packet = this._createPacket(sequence, timestamp, this.player.opusEncoder.encode(buffer)); + while (repeats--) { + this.player.voiceConnection.sockets.udp.send(packet) + .catch(e => this.emit('debug', `failed to send a packet ${e}`)); + } + } + + _createPacket(sequence, timestamp, buffer) { + const packetBuffer = new Buffer(buffer.length + 28); + packetBuffer.fill(0); + packetBuffer[0] = 0x80; + packetBuffer[1] = 0x78; + + packetBuffer.writeUIntBE(sequence, 2, 2); + packetBuffer.writeUIntBE(timestamp, 4, 4); + packetBuffer.writeUIntBE(this.player.voiceConnection.authentication.ssrc, 8, 4); + + packetBuffer.copy(nonce, 0, 0, 12); + buffer = NaCl.secretbox(buffer, nonce, this.player.voiceConnection.authentication.secretKey.key); + + for (let i = 0; i < buffer.length; i++) packetBuffer[i + 12] = buffer[i]; + + return packetBuffer; + } + + _applyVolume(buffer) { + if (this._volume === 1) return buffer; + + const out = new Buffer(buffer.length); + for (let i = 0; i < buffer.length; i += 2) { + if (i >= buffer.length - 1) break; + const uint = Math.min(32767, Math.max(-32767, Math.floor(this._volume * buffer.readInt16LE(i)))); + out.writeInt16LE(uint, i); + } + + return out; + } + + _send() { + try { + if (this._triggered) { + this._setSpeaking(false); + return; + } + + const data = this.streamingData; + + if (data.missed >= 5) { + this._triggerTerminalState('end', 'Stream is not generating quickly enough.'); + return; + } + + if (this.paused) { + // data.timestamp = data.timestamp + 4294967295 ? data.timestamp + 960 : 0; + data.pausedTime += data.length * 10; + this.player.voiceConnection.voiceManager.client.setTimeout(() => this._send(), data.length * 10); + return; + } + + this._setSpeaking(true); + + if (!data.startTime) { + /** + * Emitted once the dispatcher starts streaming + * @event StreamDispatcher#start + */ + this.emit('start'); + data.startTime = Date.now(); + } + + const bufferLength = 1920 * data.channels; + let buffer = this.stream.read(bufferLength); + if (!buffer) { + data.missed++; + data.pausedTime += data.length * 10; + this.player.voiceConnection.voiceManager.client.setTimeout(() => this._send(), data.length * 10); + return; + } + + data.missed = 0; + + if (buffer.length !== bufferLength) { + const newBuffer = new Buffer(bufferLength).fill(0); + buffer.copy(newBuffer); + buffer = newBuffer; + } + + buffer = this._applyVolume(buffer); + + data.count++; + data.sequence = (data.sequence + 1) < (65536) ? data.sequence + 1 : 0; + data.timestamp = data.timestamp + 4294967295 ? data.timestamp + 960 : 0; + + this._sendBuffer(buffer, data.sequence, data.timestamp); + + const nextTime = data.length + (data.startTime + data.pausedTime + (data.count * data.length) - Date.now()); + this.player.voiceConnection.voiceManager.client.setTimeout(() => this._send(), nextTime); + } catch (e) { + this._triggerTerminalState('error', e); + } + } + + _triggerEnd() { + /** + * Emitted once the stream has ended. Attach a `once` listener to this. + * @event StreamDispatcher#end + */ + this.emit('end'); + } + + _triggerError(err) { + this.emit('end'); + /** + * Emitted once the stream has encountered an error. Attach a `once` listener to this. Also emits `end`. + * @event StreamDispatcher#error + * @param {Error} err The encountered error + */ + this.emit('error', err); + } + + _triggerTerminalState(state, err) { + if (this._triggered) return; + /** + * Emitted when the stream wants to give debug information. + * @event StreamDispatcher#debug + * @param {string} information The debug information + */ + this.emit('debug', `Triggered terminal state ${state} - stream is now dead`); + this._triggered = true; + this._setSpeaking(false); + switch (state) { + case 'end': + this._triggerEnd(err); + break; + case 'error': + this._triggerError(err); + break; + default: + this.emit('error', 'Unknown trigger state'); + break; + } + } + + _startStreaming() { + if (!this.stream) { + this.emit('error', 'No stream'); + return; + } + + this.stream.on('end', err => this._triggerTerminalState('end', err)); + this.stream.on('error', err => this._triggerTerminalState('error', err)); + + const data = this.streamingData; + data.length = 20; + data.missed = 0; + + this.stream.once('readable', () => this._send()); + } + + _setPaused(paused) { + if (paused) { + this.paused = true; + this._setSpeaking(false); + } else { + this.paused = false; + this._setSpeaking(true); + } + } } module.exports = StreamDispatcher; diff --git a/src/client/voice/pcm/FfmpegConverterEngine.js b/src/client/voice/pcm/FfmpegConverterEngine.js index e1f39d029..34c5d509a 100644 --- a/src/client/voice/pcm/FfmpegConverterEngine.js +++ b/src/client/voice/pcm/FfmpegConverterEngine.js @@ -1,5 +1,43 @@ const ConverterEngine = require('./ConverterEngine'); const ChildProcess = require('child_process'); +const EventEmitter = require('events').EventEmitter; + +class PCMConversionProcess extends EventEmitter { + constructor(process) { + super(); + this.process = process; + this.input = null; + this.process.on('error', e => this.emit('error', e)); + } + + setInput(stream) { + this.input = stream; + stream.pipe(this.process.stdin, { end: false }); + this.input.on('error', e => this.emit('error', e)); + this.process.stdin.on('error', e => this.emit('error', e)); + } + + destroy() { + this.emit('debug', 'destroying a ffmpeg process:'); + if (this.input && this.input.unpipe && this.process.stdin) { + this.input.unpipe(this.process.stdin); + this.emit('unpiped the user input stream from the process input stream'); + } + if (this.process.stdin) { + this.process.stdin.end(); + this.emit('ended the process stdin'); + } + if (this.process.stdin.destroy) { + this.process.stdin.destroy(); + this.emit('destroyed the process stdin'); + } + if (this.process.kill) { + this.process.kill(); + this.emit('killed the process'); + } + } + +} class FfmpegConverterEngine extends ConverterEngine { constructor(player) { @@ -24,10 +62,7 @@ class FfmpegConverterEngine extends ConverterEngine { '-ss', String(seek), 'pipe:1', ], { stdio: ['pipe', 'pipe', 'ignore'] }); - encoder.on('error', e => this.handleError(encoder, e)); - encoder.stdin.on('error', e => this.handleError(encoder, e)); - encoder.stdout.on('error', e => this.handleError(encoder, e)); - return encoder; + return new PCMConversionProcess(encoder); } } diff --git a/src/client/voice/player/AudioPlayer.js b/src/client/voice/player/AudioPlayer.js new file mode 100644 index 000000000..96c6c24ae --- /dev/null +++ b/src/client/voice/player/AudioPlayer.js @@ -0,0 +1,80 @@ +const PCMConverters = require('../pcm/ConverterEngineList'); +const OpusEncoders = require('../opus/OpusEngineList'); +const EventEmitter = require('events').EventEmitter; +const StreamDispatcher = require('../dispatcher/StreamDispatcher'); + +/** + * Represents the Audio Player of a Voice Connection + * @extends {EventEmitter} + * @private + */ +class AudioPlayer extends EventEmitter { + constructor(voiceConnection) { + super(); + /** + * The voice connection the player belongs to + * @type {VoiceConnection} + */ + this.voiceConnection = voiceConnection; + this.audioToPCM = new (PCMConverters.fetch())(); + this.opusEncoder = OpusEncoders.fetch(); + this.currentConverter = null; + /** + * The current stream dispatcher, if a stream is being played + * @type {StreamDispatcher} + */ + this.dispatcher = null; + this.audioToPCM.on('error', e => this.emit('error', e)); + this.streamingData = { + channels: 2, + count: 0, + sequence: 0, + timestamp: 0, + pausedTime: 0, + }; + this.voiceConnection.on('closing', () => this.cleanup(null, 'voice connection closing')); + } + + playUnknownStream(stream, { seek = 0, volume = 1, passes = 1 } = {}) { + const options = { seek, volume, passes }; + stream.on('end', () => { + this.emit('debug', 'Input stream to converter has ended'); + }); + stream.on('error', e => this.emit('error', e)); + const conversionProcess = this.audioToPCM.createConvertStream(options.seek); + conversionProcess.on('error', e => this.emit('error', e)); + conversionProcess.setInput(stream); + return this.playPCMStream(conversionProcess.process.stdout, conversionProcess, options); + } + + cleanup(checkStream, reason) { + // cleanup is a lot less aggressive than v9 because it doesn't try to kill every single stream it is aware of + this.emit('debug', `Clean up triggered due to ${reason}`); + const filter = checkStream && this.dispatcher && this.dispatcher.stream === checkStream; + if (this.currentConverter && (checkStream ? filter : true)) { + this.currentConverter.destroy(); + this.currentConverter = null; + } + } + + playPCMStream(stream, converter, { seek = 0, volume = 1, passes = 1 } = {}) { + const options = { seek, volume, passes }; + stream.on('end', () => this.emit('debug', 'PCM input stream ended')); + this.cleanup(null, 'outstanding play stream'); + this.currentConverter = converter; + if (this.dispatcher) { + this.streamingData = this.dispatcher.streamingData; + } + stream.on('error', e => this.emit('error', e)); + const dispatcher = new StreamDispatcher(this, stream, this.streamingData, options); + dispatcher.on('error', e => this.emit('error', e)); + dispatcher.on('end', () => this.cleanup(dispatcher.stream, 'dispatcher ended')); + dispatcher.on('speaking', value => this.voiceConnection.setSpeaking(value)); + this.dispatcher = dispatcher; + dispatcher.on('debug', m => this.emit('debug', `Stream dispatch - ${m}`)); + return dispatcher; + } + +} + +module.exports = AudioPlayer; diff --git a/src/client/voice/player/BasePlayer.js b/src/client/voice/player/BasePlayer.js index 3b02deca5..d5285cd34 100644 --- a/src/client/voice/player/BasePlayer.js +++ b/src/client/voice/player/BasePlayer.js @@ -101,6 +101,8 @@ class VoiceConnectionPlayer extends EventEmitter { speaking: true, delay: 0, }, + }).catch(e => { + this.emit('debug', e); }); } diff --git a/src/client/voice/receiver/VoiceReceiver.js b/src/client/voice/receiver/VoiceReceiver.js index 3e1c24c82..e27ad8d1a 100644 --- a/src/client/voice/receiver/VoiceReceiver.js +++ b/src/client/voice/receiver/VoiceReceiver.js @@ -25,19 +25,22 @@ class VoiceReceiver extends EventEmitter { this.queues = new Map(); this.pcmStreams = new Map(); this.opusStreams = new Map(); + /** * Whether or not this receiver has been destroyed. * @type {boolean} */ this.destroyed = false; + /** * The VoiceConnection that instantiated this * @type {VoiceConnection} */ - this.connection = connection; - this._listener = (msg => { + this.voiceConnection = connection; + + this._listener = msg => { const ssrc = +msg.readUInt32BE(8).toString(10); - const user = this.connection.ssrcMap.get(ssrc); + const user = this.voiceConnection.ssrcMap.get(ssrc); if (!user) { if (!this.queues.has(ssrc)) this.queues.set(ssrc, []); this.queues.get(ssrc).push(msg); @@ -50,8 +53,8 @@ class VoiceReceiver extends EventEmitter { } this.handlePacket(msg, user); } - }).bind(this); - this.connection.udp.udpSocket.on('message', this._listener); + }; + this.voiceConnection.sockets.udp.socket.on('message', this._listener); } /** @@ -61,7 +64,7 @@ class VoiceReceiver extends EventEmitter { */ recreate() { if (!this.destroyed) return; - this.connection.udp.udpSocket.on('message', this._listener); + this.voiceConnection.sockets.udp.socket.on('message', this._listener); this.destroyed = false; return; } @@ -70,7 +73,7 @@ class VoiceReceiver extends EventEmitter { * Destroy this VoiceReceiver, also ending any streams that it may be controlling. */ destroy() { - this.connection.udp.udpSocket.removeListener('message', this._listener); + this.voiceConnection.sockets.udp.socket.removeListener('message', this._listener); for (const stream of this.pcmStreams) { stream[1]._push(null); this.pcmStreams.delete(stream[0]); @@ -89,7 +92,7 @@ class VoiceReceiver extends EventEmitter { * @returns {ReadableStream} */ createOpusStream(user) { - user = this.connection.manager.client.resolver.resolveUser(user); + user = this.voiceConnection.voiceManager.client.resolver.resolveUser(user); if (!user) throw new Error('Couldn\'t resolve the user to create Opus stream.'); if (this.opusStreams.get(user.id)) throw new Error('There is already an existing stream for that user.'); const stream = new Readable(); @@ -104,7 +107,7 @@ class VoiceReceiver extends EventEmitter { * @returns {ReadableStream} */ createPCMStream(user) { - user = this.connection.manager.client.resolver.resolveUser(user); + user = this.voiceConnection.voiceManager.client.resolver.resolveUser(user); if (!user) throw new Error('Couldn\'t resolve the user to create PCM stream.'); if (this.pcmStreams.get(user.id)) throw new Error('There is already an existing stream for that user.'); const stream = new Readable(); @@ -114,7 +117,7 @@ class VoiceReceiver extends EventEmitter { handlePacket(msg, user) { msg.copy(nonce, 0, 0, 12); - let data = NaCl.secretbox.open(msg.slice(12), nonce, this.connection.data.secret); + let data = NaCl.secretbox.open(msg.slice(12), nonce, this.voiceConnection.authentication.secretKey.key); if (!data) { /** * Emitted whenever a voice packet cannot be decrypted @@ -141,7 +144,7 @@ class VoiceReceiver extends EventEmitter { * @param {User} user The user that is sending the buffer (is speaking) * @param {Buffer} buffer The decoded buffer */ - const pcm = this.connection.player.opusEncoder.decode(data); + const pcm = this.voiceConnection.player.opusEncoder.decode(data); if (this.pcmStreams.get(user.id)) this.pcmStreams.get(user.id)._push(pcm); this.emit('pcm', user, pcm); } diff --git a/src/client/voice/util/SecretKey.js b/src/client/voice/util/SecretKey.js new file mode 100644 index 000000000..42a0da0cb --- /dev/null +++ b/src/client/voice/util/SecretKey.js @@ -0,0 +1,15 @@ +/** + * Represents a Secret Key used in encryption over voice + */ +class SecretKey { + constructor(key) { + /** + * The key used for encryption + * @type {Uint8Array} + */ + this.key = new Uint8Array(new ArrayBuffer(key.length)); + for (const index in key) this.key[index] = key[index]; + } +} + +module.exports = SecretKey; diff --git a/src/client/websocket/WebSocketManager.js b/src/client/websocket/WebSocketManager.js index ba5cbef49..8f7110613 100644 --- a/src/client/websocket/WebSocketManager.js +++ b/src/client/websocket/WebSocketManager.js @@ -58,16 +58,25 @@ class WebSocketManager extends EventEmitter { * @type {?WebSocket} */ this.ws = null; + + /** + * An object with keys that are websocket event names that should be ignored + * @type {Object} + */ + this.disabledEvents = {}; + for (const event in client.options.disabledEvents) this.disabledEvents[event] = true; + + this.first = true; } /** * Connects the client to a given gateway * @param {string} gateway The gateway to connect to */ - connect(gateway) { + _connect(gateway) { this.client.emit('debug', `Connecting to gateway ${gateway}`); this.normalReady = false; - this.status = Constants.Status.CONNECTING; + if (this.status !== Constants.Status.RECONNECTING) this.status = Constants.Status.CONNECTING; this.ws = new WebSocket(gateway); this.ws.onopen = () => this.eventOpen(); this.ws.onclose = (d) => this.eventClose(d); @@ -77,6 +86,15 @@ class WebSocketManager extends EventEmitter { this._remaining = 3; } + connect(gateway) { + if (this.first) { + this._connect(gateway); + this.first = false; + } else { + this.client.setTimeout(() => this._connect(gateway), 5500); + } + } + /** * Sends a packet to the gateway * @param {Object} data An object that can be JSON stringified @@ -99,6 +117,7 @@ class WebSocketManager extends EventEmitter { _send(data) { if (this.ws.readyState === WebSocket.OPEN) { + this.emit('send', data); this.ws.send(data); } } @@ -125,7 +144,7 @@ class WebSocketManager extends EventEmitter { */ eventOpen() { this.client.emit('debug', 'Connection to gateway opened'); - if (this.reconnecting) this._sendResume(); + if (this.status === Constants.Status.RECONNECTING) this._sendResume(); else this._sendNewIdentify(); } @@ -133,6 +152,11 @@ class WebSocketManager extends EventEmitter { * Sends a gateway resume packet, in cases of unexpected disconnections. */ _sendResume() { + if (!this.sessionID) { + this._sendNewIdentify(); + return; + } + this.client.emit('debug', 'Identifying as resumed session'); const payload = { token: this.client.token, session_id: this.sessionID, @@ -152,13 +176,15 @@ class WebSocketManager extends EventEmitter { this.reconnecting = false; const payload = this.client.options.ws; payload.token = this.client.token; - if (this.client.options.shard_count > 0) { - payload.shard = [Number(this.client.options.shard_id), Number(this.client.options.shard_count)]; + if (this.client.options.shardCount > 0) { + payload.shard = [Number(this.client.options.shardId), Number(this.client.options.shardCount)]; } + this.client.emit('debug', 'Identifying as new session'); this.send({ op: Constants.OPCodes.IDENTIFY, d: payload, }); + this.sequence = -1; } /** @@ -171,6 +197,7 @@ class WebSocketManager extends EventEmitter { * Emitted whenever the client websocket is disconnected * @event Client#disconnect */ + clearInterval(this.client.manager.heartbeatInterval); if (!this.reconnecting) this.client.emit(Constants.Events.DISCONNECT); if (event.code === 4004) return; if (event.code === 4010) return; @@ -194,7 +221,7 @@ class WebSocketManager extends EventEmitter { this.client.emit('raw', packet); - if (packet.op === 10) this.client.manager.setupKeepAlive(packet.d.heartbeat_interval); + if (packet.op === Constants.OPCodes.HELLO) this.client.manager.setupKeepAlive(packet.d.heartbeat_interval); return this.packetManager.handle(packet); } @@ -235,10 +262,11 @@ class WebSocketManager extends EventEmitter { } if (unavailableCount === 0) { this.status = Constants.Status.NEARLY; - if (this.client.options.fetch_all_members) { - const promises = this.client.guilds.array().map(g => g.fetchMembers()); + if (this.client.options.fetchAllMembers) { + const promises = this.client.guilds.map(g => g.fetchMembers()); Promise.all(promises).then(() => this._emitReady()).catch(e => { - this.client.emit(Constants.Event.WARN, `Error on pre-ready guild member fetching - ${e}`); + this.client.emit(Constants.Events.WARN, 'Error in pre-ready guild member fetching'); + this.client.emit(Constants.Events.ERROR, e); this._emitReady(); }); return; diff --git a/src/client/websocket/packets/WebSocketPacketManager.js b/src/client/websocket/packets/WebSocketPacketManager.js index bf81fd538..6d49ee257 100644 --- a/src/client/websocket/packets/WebSocketPacketManager.js +++ b/src/client/websocket/packets/WebSocketPacketManager.js @@ -42,6 +42,8 @@ class WebSocketPacketManager { this.register(Constants.WSEvents.MESSAGE_DELETE_BULK, 'MessageDeleteBulk'); this.register(Constants.WSEvents.CHANNEL_PINS_UPDATE, 'ChannelPinsUpdate'); this.register(Constants.WSEvents.GUILD_SYNC, 'GuildSync'); + this.register(Constants.WSEvents.RELATIONSHIP_ADD, 'RelationshipAdd'); + this.register(Constants.WSEvents.RELATIONSHIP_REMOVE, 'RelationshipRemove'); } get client() { @@ -72,17 +74,22 @@ class WebSocketPacketManager { } if (packet.op === Constants.OPCodes.INVALID_SESSION) { + this.ws.sessionID = null; this.ws._sendNewIdentify(); return false; } - if (this.ws.reconnecting) { + if (packet.op === Constants.OPCodes.HEARTBEAT_ACK) this.ws.client.emit('debug', 'Heartbeat acknowledged'); + + if (this.ws.status === Constants.Status.RECONNECTING) { this.ws.reconnecting = false; this.ws.checkIfReady(); } this.setSequence(packet.s); + if (this.ws.disabledEvents[packet.t] !== undefined) return false; + if (this.ws.status !== Constants.Status.READY) { if (BeforeReadyWhitelist.indexOf(packet.t) === -1) { this.queue.push(packet); diff --git a/src/client/websocket/packets/handlers/GuildEmojiUpdate.js b/src/client/websocket/packets/handlers/GuildEmojiUpdate.js new file mode 100644 index 000000000..5f983cd5d --- /dev/null +++ b/src/client/websocket/packets/handlers/GuildEmojiUpdate.js @@ -0,0 +1,13 @@ +const AbstractHandler = require('./AbstractHandler'); + +class GuildEmojiUpdate extends AbstractHandler { + handle(packet) { + const client = this.packetManager.client; + const data = packet.d; + const guild = client.guilds.get(data.guild_id); + if (!guild) return; + client.actions.EmojiUpdate.handle(data, guild); + } +} + +module.exports = GuildEmojiUpdate; diff --git a/src/client/websocket/packets/handlers/GuildMembersChunk.js b/src/client/websocket/packets/handlers/GuildMembersChunk.js index 6c6257f24..1a58e1cea 100644 --- a/src/client/websocket/packets/handlers/GuildMembersChunk.js +++ b/src/client/websocket/packets/handlers/GuildMembersChunk.js @@ -15,14 +15,13 @@ class GuildMembersChunkHandler extends AbstractHandler { } guild._checkChunks(); - client.emit(Constants.Events.GUILD_MEMBERS_CHUNK, guild, members); + client.emit(Constants.Events.GUILD_MEMBERS_CHUNK, members); } } /** - * Emitted whenever a chunk of Guild members is received + * Emitted whenever a chunk of Guild members is received (all members come from the same guild) * @event Client#guildMembersChunk - * @param {Guild} guild The guild that the chunks relate to * @param {GuildMember[]} members The members in the chunk */ diff --git a/src/client/websocket/packets/handlers/PresenceUpdate.js b/src/client/websocket/packets/handlers/PresenceUpdate.js index cfd7ee3a6..9edacd76a 100644 --- a/src/client/websocket/packets/handlers/PresenceUpdate.js +++ b/src/client/websocket/packets/handlers/PresenceUpdate.js @@ -18,51 +18,54 @@ class PresenceUpdateHandler extends AbstractHandler { } } + const oldUser = cloneObject(user); + user.patch(data.user); + if (!user.equals(oldUser)) { + client.emit(Constants.Events.USER_UPDATE, oldUser, user); + } + if (guild) { - const memberInGuild = guild.members.get(user.id); - if (!memberInGuild && data.status !== 'offline') { - const member = guild._addMember({ + let member = guild.members.get(user.id); + if (!member && data.status !== 'offline') { + member = guild._addMember({ user, roles: data.roles, deaf: false, mute: false, }, false); - client.emit(Constants.Events.GUILD_MEMBER_AVAILABLE, guild, member); + client.emit(Constants.Events.GUILD_MEMBER_AVAILABLE, member); + } + if (member) { + const oldMember = cloneObject(member); + if (member.presence) { + oldMember.frozenPresence = cloneObject(member.presence); + } + guild._setPresence(user.id, data); + client.emit(Constants.Events.PRESENCE_UPDATE, oldMember, member); + } else { + guild._setPresence(user.id, data); } - } - - data.user.username = data.user.username || user.username; - data.user.id = data.user.id || user.id; - data.user.discriminator = data.user.discriminator || user.discriminator; - data.user.status = data.status || user.status; - data.user.game = data.game; - - const same = data.user.username === user.username && - data.user.id === user.id && - data.user.discriminator === user.discriminator && - data.user.avatar === user.avatar && - data.user.status === user.status && - JSON.stringify(data.user.game) === JSON.stringify(user.game); - - if (!same) { - const oldUser = cloneObject(user); - user.patch(data.user); - client.emit(Constants.Events.PRESENCE_UPDATE, oldUser, user); } } } /** - * Emitted whenever a user changes one of their details or starts/stop playing a game + * Emitted whenever a guild member's presence changes, or they change one of their details. * @event Client#presenceUpdate - * @param {User} oldUser The user before the presence update - * @param {User} newUser The user after the presence update + * @param {GuildMember} oldMember The member before the presence update + * @param {GuildMember} newMember The member after the presence update + */ + +/** + * Emitted whenever a user's details (e.g. username) are changed. + * @event Client#userUpdate + * @param {User} oldUser The user before the update + * @param {User} newUser The user after the update */ /** * Emitted whenever a member becomes available in a large Guild * @event Client#guildMemberAvailable - * @param {Guild} guild The guild that the member became available in * @param {GuildMember} member The member that became available */ diff --git a/src/client/websocket/packets/handlers/Ready.js b/src/client/websocket/packets/handlers/Ready.js index 32ffcb57f..bb35ea47b 100644 --- a/src/client/websocket/packets/handlers/Ready.js +++ b/src/client/websocket/packets/handlers/Ready.js @@ -10,13 +10,28 @@ class ReadyHandler extends AbstractHandler { const clientUser = new ClientUser(client, data.user); client.user = clientUser; - client.readyTime = new Date(); + client.readyAt = new Date(); client.users.set(clientUser.id, clientUser); for (const guild of data.guilds) client.dataManager.newGuild(guild); for (const privateDM of data.private_channels) client.dataManager.newChannel(privateDM); - if (!client.user.bot) client.setInterval(client.syncGuilds.bind(client), 30000); + for (const relation of data.relationships) { + const user = client.dataManager.newUser(relation.user); + if (relation.type === 1) { + client.user.friends.set(user.id, user); + } else if (relation.type === 2) { + client.user.blocked.set(user.id, user); + } + } + + data.presences = data.presences || []; + for (const presence of data.presences) { + client.dataManager.newUser(presence.user); + client._setPresence(presence.user.id, presence); + } + + if (!client.user.bot && client.options.sync) client.setInterval(client.syncGuilds.bind(client), 30000); client.once('ready', client.syncGuilds.bind(client)); if (!client.users.has('1')) { diff --git a/src/client/websocket/packets/handlers/RelationshipAdd.js b/src/client/websocket/packets/handlers/RelationshipAdd.js new file mode 100644 index 000000000..122b4c507 --- /dev/null +++ b/src/client/websocket/packets/handlers/RelationshipAdd.js @@ -0,0 +1,19 @@ +const AbstractHandler = require('./AbstractHandler'); + +class RelationshipAddHandler extends AbstractHandler { + handle(packet) { + const client = this.packetManager.client; + const data = packet.d; + if (data.type === 1) { + client.fetchUser(data.id).then(user => { + client.user.friends.set(user.id, user); + }); + } else if (data.type === 2) { + client.fetchUser(data.id).then(user => { + client.user.blocked.set(user.id, user); + }); + } + } +} + +module.exports = RelationshipAddHandler; diff --git a/src/client/websocket/packets/handlers/RelationshipRemove.js b/src/client/websocket/packets/handlers/RelationshipRemove.js new file mode 100644 index 000000000..b57326ad6 --- /dev/null +++ b/src/client/websocket/packets/handlers/RelationshipRemove.js @@ -0,0 +1,19 @@ +const AbstractHandler = require('./AbstractHandler'); + +class RelationshipRemoveHandler extends AbstractHandler { + handle(packet) { + const client = this.packetManager.client; + const data = packet.d; + if (data.type === 2) { + if (client.user.blocked.has(data.id)) { + client.user.blocked.delete(data.id); + } + } else if (data.type === 1) { + if (client.user.friends.has(data.id)) { + client.user.friends.delete(data.id); + } + } + } +} + +module.exports = RelationshipRemoveHandler; diff --git a/src/client/websocket/packets/handlers/VoiceServerUpdate.js b/src/client/websocket/packets/handlers/VoiceServerUpdate.js index 146a3efc3..97885d6cd 100644 --- a/src/client/websocket/packets/handlers/VoiceServerUpdate.js +++ b/src/client/websocket/packets/handlers/VoiceServerUpdate.js @@ -12,9 +12,7 @@ class VoiceServerUpdate extends AbstractHandler { handle(packet) { const client = this.packetManager.client; const data = packet.d; - if (client.voice.pending.has(data.guild_id)) { - client.voice._receivedVoiceServer(data.guild_id, data.token, data.endpoint); - } + client.emit('self.voiceServer', data); } } diff --git a/src/client/websocket/packets/handlers/VoiceStateUpdate.js b/src/client/websocket/packets/handlers/VoiceStateUpdate.js index 639da210b..ddbfbfcbd 100644 --- a/src/client/websocket/packets/handlers/VoiceStateUpdate.js +++ b/src/client/websocket/packets/handlers/VoiceStateUpdate.js @@ -20,8 +20,8 @@ class VoiceStateUpdateHandler extends AbstractHandler { // if the member left the voice channel, unset their speaking property if (!data.channel_id) member.speaking = null; - if (client.voice.pending.has(guild.id) && member.user.id === client.user.id && data.channel_id) { - client.voice._receivedVoiceStateUpdate(data.guild_id, data.session_id); + if (member.user.id === client.user.id && data.channel_id) { + client.emit('self.voiceStateUpdate', data); } const newChannel = client.channels.get(data.channel_id); diff --git a/src/index.js b/src/index.js index abce81b74..2b8a19e6f 100644 --- a/src/index.js +++ b/src/index.js @@ -1,16 +1,21 @@ -const path = require('path'); - module.exports = { Client: require('./client/Client'), + WebhookClient: require('./client/WebhookClient'), Shard: require('./sharding/Shard'), + ShardClientUtil: require('./sharding/ShardClientUtil'), ShardingManager: require('./sharding/ShardingManager'), + Collection: require('./util/Collection'), + splitMessage: require('./util/SplitMessage'), + escapeMarkdown: require('./util/EscapeMarkdown'), + fetchRecommendedShards: require('./util/FetchRecommendedShards'), Channel: require('./structures/Channel'), ClientUser: require('./structures/ClientUser'), DMChannel: require('./structures/DMChannel'), Emoji: require('./structures/Emoji'), EvaluatedPermissions: require('./structures/EvaluatedPermissions'), + Game: require('./structures/Presence').Game, GroupDMChannel: require('./structures/GroupDMChannel'), Guild: require('./structures/Guild'), GuildChannel: require('./structures/GuildChannel'), @@ -23,10 +28,12 @@ module.exports = { PartialGuild: require('./structures/PartialGuild'), PartialGuildChannel: require('./structures/PartialGuildChannel'), PermissionOverwrites: require('./structures/PermissionOverwrites'), + Presence: require('./structures/Presence').Presence, Role: require('./structures/Role'), TextChannel: require('./structures/TextChannel'), User: require('./structures/User'), VoiceChannel: require('./structures/VoiceChannel'), + Webhook: require('./structures/Webhook'), - version: require(path.join(__dirname, '..', 'package')).version, + version: require('../package').version, }; diff --git a/src/sharding/Shard.js b/src/sharding/Shard.js index 85321fbb0..bafa0a383 100644 --- a/src/sharding/Shard.js +++ b/src/sharding/Shard.js @@ -1,5 +1,7 @@ const childProcess = require('child_process'); const path = require('path'); +const makeError = require('../util/MakeError'); +const makePlainError = require('../util/MakePlainError'); /** * Represents a Shard spawned by the ShardingManager. @@ -8,35 +10,39 @@ class Shard { /** * @param {ShardingManager} manager The sharding manager * @param {number} id The ID of this shard + * @param {array} [args=[]] Command line arguments to pass to the script */ - constructor(manager, id) { + constructor(manager, id, args = []) { /** - * The manager of the spawned shard + * Manager that created the shard * @type {ShardingManager} */ this.manager = manager; /** - * The shard ID + * ID of the shard * @type {number} */ this.id = id; /** - * The process of the shard + * The environment variables for the shard + * @type {Object} + */ + this.env = Object.assign({}, process.env, { + SHARD_ID: this.id, + SHARD_COUNT: this.manager.totalShards, + CLIENT_TOKEN: this.manager.token, + }); + + /** + * Process of the shard * @type {ChildProcess} */ - this.process = childProcess.fork(path.resolve(this.manager.file), [], { - env: { - SHARD_ID: this.id, - SHARD_COUNT: this.manager.totalShards, - }, + this.process = childProcess.fork(path.resolve(this.manager.file), args, { + env: this.env, }); - - this.process.on('message', message => { - this.manager.emit('message', this, message); - }); - + this.process.on('message', this._handleMessage.bind(this)); this.process.once('exit', () => { if (this.manager.respawn) this.manager.createShard(this.id); }); @@ -59,6 +65,38 @@ class Shard { }); } + /** + * Fetches a Client property value of the shard. + * @param {string} prop Name of the Client property to get, using periods for nesting + * @returns {Promise<*>} + * @example + * shard.fetchClientValue('guilds.size').then(count => { + * console.log(`${count} guilds in shard ${shard.id}`); + * }).catch(console.error); + */ + fetchClientValue(prop) { + if (this._fetches.has(prop)) return this._fetches.get(prop); + + const promise = new Promise((resolve, reject) => { + const listener = message => { + if (!message || message._fetchProp !== prop) return; + this.process.removeListener('message', listener); + this._fetches.delete(prop); + resolve(message._result); + }; + this.process.on('message', listener); + + this.send({ _fetchProp: prop }).catch(err => { + this.process.removeListener('message', listener); + this._fetches.delete(prop); + reject(err); + }); + }); + + this._fetches.set(prop, promise); + return promise; + } + /** * Evaluates a script on the shard, in the context of the Client. * @param {string} script JavaScript to run on the shard @@ -69,20 +107,10 @@ class Shard { const promise = new Promise((resolve, reject) => { const listener = message => { - if (!message) return; - if (message._evalResult) { - this.process.removeListener('message', listener); - this._evals.delete(script); - resolve(message._evalResult); - } else if (message._evalError) { - this.process.removeListener('message', listener); - const err = new Error(message._evalError.message, message._evalError.fileName, message._evalError.lineNumber); - err.name = message._evalError.name; - err.columnNumber = message._evalError.columnNumber; - err.stack = message._evalError.stack; - this._evals.delete(script); - reject(err); - } + if (!message || message._eval !== script) return; + this.process.removeListener('message', listener); + this._evals.delete(script); + if (!message._error) resolve(message._result); else reject(makeError(message._error)); }; this.process.on('message', listener); @@ -98,35 +126,30 @@ class Shard { } /** - * Fetches a Client property value of the shard. - * @param {string} prop Name of the Client property to get, using periods for nesting - * @returns {Promise<*>} - * @example - * shard.fetchClientValue('guilds.size').then(count => { - * console.log(`${count} guilds in shard ${shard.id}`); - * }).catch(console.error); + * Handles an IPC message + * @param {*} message Message received + * @private */ - fetchClientValue(prop) { - if (this._fetches.has(prop)) return this._fetches.get(prop); + _handleMessage(message) { + if (message) { + // Shard is requesting a property fetch + if (message._sFetchProp) { + this.manager.fetchClientValues(message._sFetchProp) + .then(results => this.send({ _sFetchProp: message._sFetchProp, _result: results })) + .catch(err => this.send({ _sFetchProp: message._sFetchProp, _error: makePlainError(err) })); + return; + } - const promise = new Promise((resolve, reject) => { - const listener = message => { - if (typeof message !== 'object' || message._fetchProp !== prop) return; - this.process.removeListener('message', listener); - this._fetches.delete(prop); - resolve(message._fetchPropValue); - }; - this.process.on('message', listener); + // Shard is requesting an eval broadcast + if (message._sEval) { + this.manager.broadcastEval(message._sEval) + .then(results => this.send({ _sEval: message._sEval, _result: results })) + .catch(err => this.send({ _sEval: message._sEval, _error: makePlainError(err) })); + return; + } + } - this.send({ _fetchProp: prop }).catch(err => { - this.process.removeListener('message', listener); - this._fetches.delete(prop); - reject(err); - }); - }); - - this._fetches.set(prop, promise); - return promise; + this.manager.emit('message', this, message); } } diff --git a/src/sharding/ShardClientUtil.js b/src/sharding/ShardClientUtil.js new file mode 100644 index 000000000..51c16fa8f --- /dev/null +++ b/src/sharding/ShardClientUtil.js @@ -0,0 +1,142 @@ +const makeError = require('../util/MakeError'); +const makePlainError = require('../util/MakePlainError'); + +/** + * Helper class for sharded clients spawned as a child process, such as from a ShardingManager + */ +class ShardClientUtil { + /** + * @param {Client} client Client of the current shard + */ + constructor(client) { + this.client = client; + process.on('message', this._handleMessage.bind(this)); + } + + /** + * ID of this shard + * @type {number} + * @readonly + */ + get id() { + return this.client.options.shardId; + } + + /** + * Total number of shards + * @type {number} + * @readonly + */ + get count() { + return this.client.options.shardCount; + } + + /** + * Sends a message to the master process + * @param {*} message Message to send + * @returns {Promise} + */ + send(message) { + return new Promise((resolve, reject) => { + const sent = process.send(message, err => { + if (err) reject(err); else resolve(); + }); + if (!sent) throw new Error('Failed to send message to master process.'); + }); + } + + /** + * Fetches a Client property value of each shard. + * @param {string} prop Name of the Client property to get, using periods for nesting + * @returns {Promise} + * @example + * client.shard.fetchClientValues('guilds.size').then(results => { + * console.log(`${results.reduce((prev, val) => prev + val, 0)} total guilds`); + * }).catch(console.error); + */ + fetchClientValues(prop) { + return new Promise((resolve, reject) => { + const listener = message => { + if (!message || message._sFetchProp !== prop) return; + process.removeListener('message', listener); + if (!message._error) resolve(message._result); else reject(makeError(message._error)); + }; + process.on('message', listener); + + this.send({ _sFetchProp: prop }).catch(err => { + process.removeListener('message', listener); + reject(err); + }); + }); + } + + /** + * Evaluates a script on all shards, in the context of the Clients. + * @param {string} script JavaScript to run on each shard + * @returns {Promise} Results of the script execution + */ + broadcastEval(script) { + return new Promise((resolve, reject) => { + const listener = message => { + if (!message || message._sEval !== script) return; + process.removeListener('message', listener); + if (!message._error) resolve(message._result); else reject(makeError(message._error)); + }; + process.on('message', listener); + + this.send({ _sEval: script }).catch(err => { + process.removeListener('message', listener); + reject(err); + }); + }); + } + + /** + * Handles an IPC message + * @param {*} message Message received + * @private + */ + _handleMessage(message) { + if (!message) return; + if (message._fetchProp) { + const props = message._fetchProp.split('.'); + let value = this.client; + for (const prop of props) value = value[prop]; + this._respond('fetchProp', { _fetchProp: message._fetchProp, _result: value }); + } else if (message._eval) { + try { + this._respond('eval', { _eval: message._eval, _result: this.client._eval(message._eval) }); + } catch (err) { + this._respond('eval', { _eval: message._eval, _error: makePlainError(err) }); + } + } + } + + /** + * Sends a message to the master process, emitting an error from the client upon failure + * @param {string} type Type of response to send + * @param {*} message Message to send + * @private + */ + _respond(type, message) { + this.send(message).catch(err => + this.client.emit('error', `Error when sending ${type} response to master process: ${err}`) + ); + } + + /** + * Creates/gets the singleton of this class + * @param {Client} client Client to use + * @returns {ShardUtil} + */ + static singleton(client) { + if (!this._singleton) { + this._singleton = new this(client); + } else { + client.emit('error', 'Multiple clients created in child process; only the first will handle sharding helpers.'); + } + return this._singleton; + } +} + +module.exports = ShardClientUtil; diff --git a/src/sharding/ShardingManager.js b/src/sharding/ShardingManager.js index 2f71427d6..66814babb 100644 --- a/src/sharding/ShardingManager.js +++ b/src/sharding/ShardingManager.js @@ -1,24 +1,35 @@ const path = require('path'); const fs = require('fs'); const EventEmitter = require('events').EventEmitter; - +const mergeDefault = require('../util/MergeDefault'); const Shard = require('./Shard'); const Collection = require('../util/Collection'); +const fetchRecommendedShards = require('../util/FetchRecommendedShards'); /** * This is a utility class that can be used to help you spawn shards of your Client. Each shard is completely separate * from the other. The Shard Manager takes a path to a file and spawns it under the specified amount of shards safely. + * If you do not select an amount of shards, the manager will automatically decide the best amount. * The Sharding Manager is still experimental * @extends {EventEmitter} */ class ShardingManager extends EventEmitter { /** * @param {string} file Path to your shard script file - * @param {number} [totalShards=1] Number of shards to default to spawning - * @param {boolean} [respawn=true] Respawn a shard when it dies + * @param {Object} [options] Options for the sharding manager + * @param {number|string} [options.totalShards='auto'] Number of shards to spawn, or "auto" + * @param {boolean} [options.respawn=true] Whether shards should automatically respawn upon exiting + * @param {string[]} [options.shardArgs=[]] Arguments to pass to the shard script when spawning + * @param {string} [options.token] Token to use for automatic shard count and passing to shards */ - constructor(file, totalShards = 1, respawn = true) { + constructor(file, options = {}) { super(); + options = mergeDefault({ + totalShards: 'auto', + respawn: true, + shardArgs: [], + token: null, + }, options); /** * Path to the shard script file @@ -32,16 +43,36 @@ class ShardingManager extends EventEmitter { /** * Amount of shards that this manager is going to spawn - * @type {number} + * @type {number|string} */ - this.totalShards = totalShards; - if (typeof totalShards !== 'number' || isNaN(totalShards)) { - throw new TypeError('Amount of shards must be a number.'); + this.totalShards = options.totalShards; + if (this.totalShards !== 'auto') { + if (typeof this.totalShards !== 'number' || isNaN(this.totalShards)) { + throw new TypeError('Amount of shards must be a number.'); + } + if (this.totalShards < 1) throw new RangeError('Amount of shards must be at least 1.'); + if (this.totalShards !== Math.floor(this.totalShards)) { + throw new RangeError('Amount of shards must be an integer.'); + } } - if (totalShards < 1) throw new RangeError('Amount of shards must be at least 1.'); - if (totalShards !== Math.floor(totalShards)) throw new RangeError('Amount of shards must be an integer.'); - this.respawn = respawn; + /** + * Whether shards should automatically respawn upon exiting + * @type {boolean} + */ + this.respawn = options.respawn; + + /** + * An array of arguments to pass to shards. + * @type {string[]} + */ + this.shardArgs = options.shardArgs; + + /** + * Token to use for obtaining the automatic shard count, and passing to shards + * @type {?string} + */ + this.token = options.token ? options.token.replace(/^Bot\s*/i, '') : null; /** * A collection of shards that this manager has spawned @@ -52,11 +83,11 @@ class ShardingManager extends EventEmitter { /** * Spawns a single shard. - * @param {number} id The ID of the shard to spawn. THIS IS NOT NEEDED IN ANY NORMAL CASE! + * @param {number} id The ID of the shard to spawn. **This is usually not necessary.** * @returns {Promise} */ createShard(id = this.shards.size) { - const shard = new Shard(this, id); + const shard = new Shard(this, id, this.shardArgs); this.shards.set(id, shard); /** * Emitted upon launching a shard @@ -74,10 +105,29 @@ class ShardingManager extends EventEmitter { * @returns {Promise>} */ spawn(amount = this.totalShards, delay = 5500) { - if (typeof amount !== 'number' || isNaN(amount)) throw new TypeError('Amount of shards must be a number.'); - if (amount < 1) throw new RangeError('Amount of shards must be at least 1.'); - if (amount !== Math.floor(amount)) throw new RangeError('Amount of shards must be an integer.'); + return new Promise((resolve, reject) => { + if (amount === 'auto') { + fetchRecommendedShards(this.token).then(count => { + this.totalShards = count; + resolve(this._spawn(count, delay)); + }).catch(reject); + } else { + if (typeof amount !== 'number' || isNaN(amount)) throw new TypeError('Amount of shards must be a number.'); + if (amount < 1) throw new RangeError('Amount of shards must be at least 1.'); + if (amount !== Math.floor(amount)) throw new TypeError('Amount of shards must be an integer.'); + resolve(this._spawn(amount, delay)); + } + }); + } + /** + * Actually spawns shards, unlike that poser above >:( + * @param {number} amount Number of shards to spawn + * @param {number} delay How long to wait in between spawning each shard (in milliseconds) + * @returns {Promise>} + * @private + */ + _spawn(amount, delay) { return new Promise(resolve => { if (this.shards.size >= amount) throw new Error(`Already spawned ${this.shards.size} shards.`); this.totalShards = amount; diff --git a/src/structures/Channel.js b/src/structures/Channel.js index e29e75d69..2cdab15de 100644 --- a/src/structures/Channel.js +++ b/src/structures/Channel.js @@ -32,12 +32,21 @@ class Channel { } /** - * The time the channel was created + * The timestamp the channel was created at + * @type {number} * @readonly - * @type {Date} */ - get creationDate() { - return new Date((this.id / 4194304) + 1420070400000); + get createdTimestamp() { + return (this.id / 4194304) + 1420070400000; + } + + /** + * The time the channel was created + * @type {Date} + * @readonly + */ + get createdAt() { + return new Date(this.createdTimestamp); } /** @@ -47,7 +56,7 @@ class Channel { * // delete the channel * channel.delete() * .then() // success - * .catch(console.log); // log error + * .catch(console.error); // log error */ delete() { return this.client.rest.methods.deleteChannel(this); diff --git a/src/structures/ClientUser.js b/src/structures/ClientUser.js index 15a93570a..cd7c3891a 100644 --- a/src/structures/ClientUser.js +++ b/src/structures/ClientUser.js @@ -1,4 +1,5 @@ const User = require('./User'); +const Collection = require('../util/Collection'); /** * Represents the logged in client's Discord User @@ -19,8 +20,22 @@ class ClientUser extends User { * @type {string} */ this.email = data.email; - + this.localPresence = {}; this._typing = new Map(); + + /** + * A Collection of friends for the logged in user. + * This is only filled for user accounts, not bot accounts! + * @type {Collection} + */ + this.friends = new Collection(); + + /** + * A Collection of blocked users for the logged in user. + * This is only filled for user accounts, not bot accounts! + * @type {Collection} + */ + this.blocked = new Collection(); } edit(data) { @@ -37,7 +52,7 @@ class ClientUser extends User { * // set username * client.user.setUsername('discordjs') * .then(user => console.log(`My new username is ${user.username}`)) - * .catch(console.log); + * .catch(console.error); */ setUsername(username) { return this.client.rest.methods.updateCurrentUser({ username }); @@ -52,7 +67,7 @@ class ClientUser extends User { * // set email * client.user.setEmail('bob@gmail.com') * .then(user => console.log(`My new email is ${user.email}`)) - * .catch(console.log); + * .catch(console.error); */ setEmail(email) { return this.client.rest.methods.updateCurrentUser({ email }); @@ -65,9 +80,9 @@ class ClientUser extends User { * @returns {Promise} * @example * // set password - * client.user.setPassword('password') + * client.user.setPassword('password123') * .then(user => console.log('New password set!')) - * .catch(console.log); + * .catch(console.error); */ setPassword(password) { return this.client.rest.methods.updateCurrentUser({ password }); @@ -75,68 +90,144 @@ class ClientUser extends User { /** * Set the avatar of the logged in Client. - * @param {Base64Resolvable} avatar The new avatar + * @param {FileResolvable|Base64Resolveable} avatar The new avatar * @returns {Promise} * @example * // set avatar - * client.user.setAvatar(fs.readFileSync('./avatar.png')) + * client.user.setAvatar('./avatar.png') * .then(user => console.log(`New avatar set!`)) - * .catch(console.log); + * .catch(console.error); */ setAvatar(avatar) { - return this.client.rest.methods.updateCurrentUser({ avatar }); + return new Promise(resolve => { + if (avatar.startsWith('data:')) { + resolve(this.client.rest.methods.updateCurrentUser({ avatar })); + } else { + this.client.resolver.resolveFile(avatar).then(data => { + resolve(this.client.rest.methods.updateCurrentUser({ avatar: data })); + }); + } + }); } /** - * Set the status and playing game of the logged in client. - * @param {string} [status] The status, can be `online` or `idle` - * @param {string|Object} [game] The game that is being played - * @param {string} [url] If you want to display as streaming, set this as the URL to the stream (must be a - * twitch.tv URl) + * Set the status of the logged in user. + * @param {string} status can be `online`, `idle`, `invisible` or `dnd` (do not disturb) * @returns {Promise} - * @example - * // set status - * client.user.setStatus('status', 'game') - * .then(user => console.log('Changed status!')) - * .catch(console.log); */ - setStatus(status, game = null, url = null) { + setStatus(status) { + return this.setPresence({ status }); + } + + /** + * Set the current game of the logged in user. + * @param {string} game the game being played + * @param {string} [streamingURL] an optional URL to a twitch stream, if one is available. + * @returns {Promise} + */ + setGame(game, streamingURL) { + return this.setPresence({ game: { + name: game, + url: streamingURL, + } }); + } + + /** + * Set/remove the AFK flag for the current user. + * @param {boolean} afk whether or not the user is AFK. + * @returns {Promise} + */ + setAFK(afk) { + return this.setPresence({ afk }); + } + + /** + * Send a friend request + * This is only available for user accounts, not bot accounts! + * @param {UserResolvable} user The user to send the friend request to. + * @returns {Promise} The user the friend request was sent to. + */ + addFriend(user) { + user = this.client.resolver.resolveUser(user); + return this.client.rest.methods.addFriend(user); + } + + /** + * Remove a friend + * This is only available for user accounts, not bot accounts! + * @param {UserResolvable} user The user to remove from your friends + * @returns {Promise} The user that was removed + */ + removeFriend(user) { + user = this.client.resolver.resolveUser(user); + return this.client.rest.methods.removeFriend(user); + } + + /** + * Creates a guild + * This is only available for user accounts, not bot accounts! + * @param {string} name The name of the guild + * @param {string} region The region for the server + * @param {FileResolvable|Base64Resolvable} [icon=null] The icon for the guild + * @returns {Promise} The guild that was created + */ + createGuild(name, region, icon = null) { return new Promise(resolve => { - if (status === 'online' || status === 'here' || status === 'available') { - this.idleStatus = null; - } else if (status === 'idle' || status === 'away') { - this.idleStatus = Date.now(); + if (!icon) resolve(this.client.rest.methods.createGuild({ name, icon, region })); + if (icon.startsWith('data:')) { + resolve(this.client.rest.methods.createGuild({ name, icon, region })); } else { - this.idleStatus = this.idleStatus || null; + this.client.resolver.resolveFile(icon).then(data => { + resolve(this.client.rest.methods.createGuild({ name, icon: data, region })); + }); + } + }); + } + + /** + * Set the full presence of the current user. + * @param {Object} data the data to provide + * @returns {Promise} + */ + setPresence(data) { + // {"op":3,"d":{"status":"dnd","since":0,"game":null,"afk":false}} + return new Promise(resolve => { + let status = this.localPresence.status || this.presence.status; + let game = this.localPresence.game; + let afk = this.localPresence.afk || this.presence.afk; + + if (!game && this.presence.game) { + game = { + name: this.presence.game.name, + type: this.presence.game.type, + url: this.presence.game.url, + }; } - if (typeof game === 'string' && !game.length) game = null; - - if (game === null) { - this.userGame = null; - } else if (!game) { - this.userGame = this.userGame || null; - } else if (typeof game === 'string') { - this.userGame = { name: game }; - } else { - this.userGame = game; + if (data.status) { + if (typeof data.status !== 'string') throw new TypeError('Status must be a string'); + status = data.status; } - if (url) { - this.userGame.url = url; - this.userGame.type = 1; + if (data.game) { + game = data.game; + if (game.url) game.type = 1; } + if (typeof data.afk !== 'undefined') afk = data.afk; + afk = Boolean(afk); + + this.localPresence = { status, game, afk }; + this.localPresence.since = 0; + this.localPresence.game = this.localPresence.game || null; + this.client.ws.send({ op: 3, - d: { - idle_since: this.idleStatus, - game: this.userGame, - }, + d: this.localPresence, }); - this.status = this.idleStatus ? 'idle' : 'online'; - this.game = this.userGame; + this.client._setPresence(this.id, this.localPresence); + resolve(this); }); } diff --git a/src/structures/Emoji.js b/src/structures/Emoji.js index 626b5e44d..0349b6f70 100644 --- a/src/structures/Emoji.js +++ b/src/structures/Emoji.js @@ -51,12 +51,21 @@ class Emoji { } /** - * The time the emoji was created + * The timestamp the emoji was created at + * @type {number} * @readonly - * @type {Date} */ - get creationDate() { - return new Date((this.id / 4194304) + 1420070400000); + get createdTimestamp() { + return (this.id / 4194304) + 1420070400000; + } + + /** + * The time the emoji was created + * @type {Date} + * @readonly + */ + get createdAt() { + return new Date(this.createdTimestamp); } /** @@ -86,7 +95,7 @@ class Emoji { * @returns {string} * @example * // send an emoji: - * const emoji = guild.emojis.array()[0]; + * const emoji = guild.emojis.first(); * msg.reply(`Hello! ${emoji}`); */ toString() { diff --git a/src/structures/EvaluatedPermissions.js b/src/structures/EvaluatedPermissions.js index 9deecba81..de92c10d7 100644 --- a/src/structures/EvaluatedPermissions.js +++ b/src/structures/EvaluatedPermissions.js @@ -50,7 +50,17 @@ class EvaluatedPermissions { * @returns {boolean} */ hasPermissions(permissions, explicit = false) { - return permissions.map(p => this.hasPermission(p, explicit)).every(v => v); + return permissions.every(p => this.hasPermission(p, explicit)); + } + + /** + * Checks whether the user has all specified permissions, and lists any missing permissions. + * @param {PermissionResolvable[]} permissions The permissions to check for + * @param {boolean} [explicit=false] Whether to require the user to explicitly have the exact permissions + * @returns {array} + */ + missingPermissions(permissions, explicit = false) { + return permissions.filter(p => !this.hasPermission(p, explicit)); } } diff --git a/src/structures/GroupDMChannel.js b/src/structures/GroupDMChannel.js index 9e9296aae..cfeea2555 100644 --- a/src/structures/GroupDMChannel.js +++ b/src/structures/GroupDMChannel.js @@ -80,6 +80,7 @@ class GroupDMChannel extends Channel { /** * The owner of this Group DM. * @type {User} + * @readonly */ get owner() { return this.client.users.get(this.ownerID); @@ -100,8 +101,8 @@ class GroupDMChannel extends Channel { this.ownerID === channel.ownerID; if (equal) { - const thisIDs = this.recipients.array().map(r => r.id); - const otherIDs = channel.recipients.map(r => r.id); + const thisIDs = this.recipients.keyArray(); + const otherIDs = channel.recipients.keyArray(); return arraysEqual(thisIDs, otherIDs); } diff --git a/src/structures/Guild.js b/src/structures/Guild.js index 3fc07d0b1..58b28cb8a 100644 --- a/src/structures/Guild.js +++ b/src/structures/Guild.js @@ -1,6 +1,7 @@ const User = require('./User'); const Role = require('./Role'); const Emoji = require('./Emoji'); +const Presence = require('./Presence').Presence; const GuildMember = require('./GuildMember'); const Constants = require('../util/Constants'); const Collection = require('../util/Collection'); @@ -100,6 +101,12 @@ class Guild { */ this.large = data.large || this.large; + /** + * A collection of presences in this Guild + * @type {Collection} + */ + this.presences = new Collection(); + /** * An array of guild features. * @type {Object[]} @@ -137,10 +144,15 @@ class Guild { */ this.verificationLevel = data.verification_level; + /** + * The timestamp the client user joined the guild at + * @type {number} + */ + this.joinedTimestamp = data.joined_at ? new Date(data.joined_at).getTime() : this.joinedTimestamp; + this.id = data.id; this.available = !data.unavailable; this.features = data.features || this.features || []; - this._joinedTimestamp = data.joined_at ? new Date(data.joined_at).getTime() : this._joinedTimestamp; if (data.members) { this.members.clear(); @@ -170,11 +182,7 @@ class Guild { if (data.presences) { for (const presence of data.presences) { - const user = this.client.users.get(presence.user.id); - if (user) { - user.status = presence.status; - user.game = presence.game; - } + this._setPresence(presence.user.id, presence); } } @@ -197,20 +205,30 @@ class Guild { } /** - * The time the guild was created + * The timestamp the guild was created at + * @type {number} * @readonly - * @type {Date} */ - get creationDate() { - return new Date((this.id / 4194304) + 1420070400000); + get createdTimestamp() { + return (this.id / 4194304) + 1420070400000; } /** - * The date at which the logged-in client joined the guild. + * The time the guild was created * @type {Date} + * @readonly */ - get joinDate() { - return new Date(this._joinedTimestamp); + get createdAt() { + return new Date(this.createdTimestamp); + } + + /** + * The time the client user joined the guild + * @type {Date} + * @readonly + */ + get joinedAt() { + return new Date(this.joinedTimestamp); } /** @@ -278,6 +296,14 @@ class Guild { return this.client.rest.methods.getGuildInvites(this); } + /** + * Fetch all webhooks for the guild. + * @returns {Collection} + */ + fetchWebhooks() { + return this.client.rest.methods.getGuildWebhooks(this); + } + /** * Fetch a single guild member from a user. * @param {UserResolvable} user The user to fetch the member for @@ -329,7 +355,7 @@ class Guild { * region: 'london', * }) * .then(updated => console.log(`New guild name ${updated.name} in region ${updated.region}`)) - * .catch(console.log); + * .catch(console.error); */ edit(data) { return this.client.rest.methods.updateGuild(this, data); @@ -343,7 +369,7 @@ class Guild { * // edit the guild name * guild.setName('Discord Guild') * .then(updated => console.log(`Updated guild name to ${guild.name}`)) - * .catch(console.log); + * .catch(console.error); */ setName(name) { return this.edit({ name }); @@ -357,7 +383,7 @@ class Guild { * // edit the guild region * guild.setRegion('london') * .then(updated => console.log(`Updated guild region to ${guild.region}`)) - * .catch(console.log); + * .catch(console.error); */ setRegion(region) { return this.edit({ region }); @@ -371,7 +397,7 @@ class Guild { * // edit the guild verification level * guild.setVerificationLevel(1) * .then(updated => console.log(`Updated guild verification level to ${guild.verificationLevel}`)) - * .catch(console.log); + * .catch(console.error); */ setVerificationLevel(verificationLevel) { return this.edit({ verificationLevel }); @@ -385,7 +411,7 @@ class Guild { * // edit the guild AFK channel * guild.setAFKChannel(channel) * .then(updated => console.log(`Updated guild AFK channel to ${guild.afkChannel}`)) - * .catch(console.log); + * .catch(console.error); */ setAFKChannel(afkChannel) { return this.edit({ afkChannel }); @@ -399,7 +425,7 @@ class Guild { * // edit the guild AFK channel * guild.setAFKTimeout(60) * .then(updated => console.log(`Updated guild AFK timeout to ${guild.afkTimeout}`)) - * .catch(console.log); + * .catch(console.error); */ setAFKTimeout(afkTimeout) { return this.edit({ afkTimeout }); @@ -413,7 +439,7 @@ class Guild { * // edit the guild icon * guild.setIcon(fs.readFileSync('./icon.png')) * .then(updated => console.log('Updated the guild icon')) - * .catch(console.log); + * .catch(console.error); */ setIcon(icon) { return this.edit({ icon }); @@ -427,7 +453,7 @@ class Guild { * // edit the guild owner * guild.setOwner(guilds.members[0]) * .then(updated => console.log(`Updated the guild owner to ${updated.owner.username}`)) - * .catch(console.log); + * .catch(console.error); */ setOwner(owner) { return this.edit({ owner }); @@ -441,7 +467,7 @@ class Guild { * // edit the guild splash * guild.setIcon(fs.readFileSync('./splash.png')) * .then(updated => console.log('Updated the guild splash')) - * .catch(console.log); + * .catch(console.error); */ setSplash(splash) { return this.edit({ splash }); @@ -514,7 +540,7 @@ class Guild { * // create a new text channel * guild.createChannel('new-general', 'text') * .then(channel => console.log(`Created new channel ${channel}`)) - * .catch(console.log); + * .catch(console.error); */ createChannel(name, type) { return this.client.rest.methods.createChannel(this, name, type); @@ -528,12 +554,12 @@ class Guild { * // create a new role * guild.createRole() * .then(role => console.log(`Created role ${role}`)) - * .catch(console.log); + * .catch(console.error); * @example * // create a new role with data * guild.createRole({ name: 'Super Cool People' }) * .then(role => console.log(`Created role ${role}`)) - * .catch(console.log) + * .catch(console.error) */ createRole(data) { const create = this.client.rest.methods.createGuildRole(this); @@ -541,6 +567,43 @@ class Guild { return create.then(role => role.edit(data)); } + /** + * Creates a new custom emoji in the guild. + * @param {FileResolveable} attachment The image for the emoji. + * @param {string} name The name for the emoji. + * @returns {Promise} The created emoji. + * @example + * // create a new emoji from a url + * guild.createEmoji('https://i.imgur.com/w3duR07.png', 'rip') + * .then(emoji => console.log(`Created new emoji with name ${emoji.name}!`)) + * .catch(console.error); + * @example + * // create a new emoji from a file on your computer + * guild.createEmoji('./memes/banana.png', 'banana') + * .then(emoji => console.log(`Created new emoji with name ${emoji.name}!`)) + * .catch(console.error); + */ + createEmoji(attachment, name) { + return new Promise((resolve, reject) => { + this.client.resolver.resolveFile(attachment).then(file => { + let base64 = new Buffer(file, 'binary').toString('base64'); + let dataURI = `data:;base64,${base64}`; + this.client.rest.methods.createEmoji(this, dataURI, name) + .then(resolve).catch(reject); + }).catch(reject); + }); + } + + /** + * Delete an emoji. + * @param {Emoji|string} emoji The emoji to delete. + * @returns {Promise} + */ + deleteEmoji(emoji) { + if (!(emoji instanceof Emoji)) emoji = this.emojis.get(emoji); + return this.client.rest.methods.deleteEmoji(emoji); + } + /** * Causes the Client to leave the guild. * @returns {Promise} @@ -548,7 +611,7 @@ class Guild { * // leave a guild * guild.leave() * .then(g => console.log(`Left the guild ${g}`)) - * .catch(console.log); + * .catch(console.error); */ leave() { return this.client.rest.methods.leaveGuild(this); @@ -561,12 +624,38 @@ class Guild { * // delete a guild * guild.delete() * .then(g => console.log(`Deleted the guild ${g}`)) - * .catch(console.log); + * .catch(console.error); */ delete() { return this.client.rest.methods.deleteGuild(this); } + /** + * Set the position of a role in this guild + * @param {string|Role} role the role to edit, can be a role object or a role ID. + * @param {number} position the new position of the role + * @returns {Promise} + */ + setRolePosition(role, position) { + if (role instanceof Role) { + role = role.id; + } else if (typeof role !== 'string') { + return Promise.reject(new Error('Supplied role is not a role or string')); + } + + position = Number(position); + if (isNaN(position)) { + return Promise.reject(new Error('Supplied position is not a number')); + } + + const updatedRoles = this.roles.array().map(r => ({ + id: r.id, + position: r.id === role ? position : (r.position < position ? r.position : r.position + 1), + })); + + return this.client.rest.methods.setRolePositions(this.id, updatedRoles); + } + /** * Whether this Guild equals another Guild. It compares all properties, so for most operations * it is advisable to just compare `guild.id === guild2.id` as it is much faster and is often @@ -616,6 +705,7 @@ class Guild { } _addMember(guildUser, emitEvent = true) { + const existing = this.members.has(guildUser.user.id); if (!(guildUser.user instanceof User)) guildUser.user = this.client.dataManager.newUser(guildUser.user); guildUser.joined_at = guildUser.joined_at || 0; @@ -636,11 +726,10 @@ class Guild { /** * Emitted whenever a user joins a guild. * @event Client#guildMemberAdd - * @param {Guild} guild The guild that the user has joined - * @param {GuildMember} member The member that has joined + * @param {GuildMember} member The member that has joined a guild */ - if (this.client.ws.status === Constants.Status.READY && emitEvent) { - this.client.emit(Constants.Events.GUILD_MEMBER_ADD, this, member); + if (this.client.ws.status === Constants.Status.READY && emitEvent && !existing) { + this.client.emit(Constants.Events.GUILD_MEMBER_ADD, member); } this._checkChunks(); @@ -659,11 +748,10 @@ class Guild { /** * Emitted whenever a Guild Member changes - i.e. new role, removed role, nickname * @event Client#guildMemberUpdate - * @param {Guild} guild The guild that the update affects * @param {GuildMember} oldMember The member before the update * @param {GuildMember} newMember The member after the update */ - this.client.emit(Constants.Events.GUILD_MEMBER_UPDATE, this, oldMember, member); + this.client.emit(Constants.Events.GUILD_MEMBER_UPDATE, oldMember, member); } return { @@ -691,6 +779,14 @@ class Guild { } } + _setPresence(id, presence) { + if (this.presences.get(id)) { + this.presences.get(id).update(presence); + return; + } + this.presences.set(id, new Presence(presence)); + } + _checkChunks() { if (this._fetchWaiter) { if (this.members.size === this.memberCount) { diff --git a/src/structures/GuildChannel.js b/src/structures/GuildChannel.js index 434279025..7d220cf6c 100644 --- a/src/structures/GuildChannel.js +++ b/src/structures/GuildChannel.js @@ -111,7 +111,7 @@ class GuildChannel extends Channel { /** * Overwrites the permissions for a user or role in this channel. - * @param {Role|UserResolvable} userOrRole The user or role to update + * @param {RoleResolvable|UserResolvable} userOrRole The user or role to update * @param {PermissionOverwriteOptions} options The configuration for the update * @returns {Promise} * @example @@ -120,7 +120,7 @@ class GuildChannel extends Channel { * SEND_MESSAGES: false * }) * .then(() => console.log('Done!')) - * .catch(console.log); + * .catch(console.error); */ overwritePermissions(userOrRole, options) { const payload = { @@ -130,6 +130,9 @@ class GuildChannel extends Channel { if (userOrRole instanceof Role) { payload.type = 'role'; + } else if (this.guild.roles.has(userOrRole)) { + userOrRole = this.guild.roles.get(userOrRole); + payload.type = 'role'; } else { userOrRole = this.client.resolver.resolveUser(userOrRole); payload.type = 'member'; @@ -141,8 +144,8 @@ class GuildChannel extends Channel { const prevOverwrite = this.permissionOverwrites.get(userOrRole.id); if (prevOverwrite) { - payload.allow = prevOverwrite.allow; - payload.deny = prevOverwrite.deny; + payload.allow = prevOverwrite.allowData; + payload.deny = prevOverwrite.denyData; } for (const perm in options) { @@ -170,7 +173,7 @@ class GuildChannel extends Channel { * // set a new channel name * channel.setName('not_general') * .then(newChannel => console.log(`Channel's new name is ${newChannel.name}`)) - * .catch(console.log); + * .catch(console.error); */ setName(name) { return this.client.rest.methods.updateChannel(this, { name }); @@ -184,7 +187,7 @@ class GuildChannel extends Channel { * // set a new channel position * channel.setPosition(2) * .then(newChannel => console.log(`Channel's new position is ${newChannel.position}`)) - * .catch(console.log); + * .catch(console.error); */ setPosition(position) { return this.client.rest.methods.updateChannel(this, { position }); @@ -198,7 +201,7 @@ class GuildChannel extends Channel { * // set a new channel topic * channel.setTopic('needs more rate limiting') * .then(newChannel => console.log(`Channel's new topic is ${newChannel.topic}`)) - * .catch(console.log); + * .catch(console.error); */ setTopic(topic) { return this.client.rest.methods.updateChannel(this, { topic }); @@ -236,12 +239,12 @@ class GuildChannel extends Channel { this.name === channel.name; if (equal) { - if (channel.permission_overwrites) { - const thisIDSet = Array.from(this.permissionOverwrites.keys()); - const otherIDSet = channel.permission_overwrites.map(overwrite => overwrite.id); + if (this.permissionOverwrites && channel.permissionOverwrites) { + const thisIDSet = this.permissionOverwrites.keyArray(); + const otherIDSet = channel.permissionOverwrites.keyArray(); equal = arraysEqual(thisIDSet, otherIDSet); } else { - equal = false; + equal = !this.permissionOverwrites && !channel.permissionOverwrites; } } diff --git a/src/structures/GuildMember.js b/src/structures/GuildMember.js index 55cdcc81e..71472c002 100644 --- a/src/structures/GuildMember.js +++ b/src/structures/GuildMember.js @@ -82,17 +82,32 @@ class GuildMember { */ this.nickname = data.nick || null; + /** + * The timestamp the member joined the guild at + * @type {number} + */ + this.joinedTimestamp = new Date(data.joined_at).getTime(); + this.user = data.user; this._roles = data.roles; - this._joinDate = new Date(data.joined_at).getTime(); } /** - * The date this member joined the guild + * The time the member joined the guild * @type {Date} + * @readonly */ - get joinDate() { - return new Date(this._joinDate); + get joinedAt() { + return new Date(this.joinedTimestamp); + } + + /** + * The presence of this Guild Member + * @type {Presence} + * @readonly + */ + get presence() { + return this.frozenPresence || this.guild.presences.get(this.id); } /** @@ -117,11 +132,10 @@ class GuildMember { /** * The role of the member with the highest position. * @type {Role} + * @readonly */ get highestRole() { - return this.roles.reduce((prev, role) => - !prev || role.position > prev.position || (role.position === prev.position && role.id < prev.id) ? role : prev - ); + return this.roles.reduce((prev, role) => !prev || role.comparePositionTo(prev) > 0 ? role : prev); } /** @@ -163,6 +177,7 @@ class GuildMember { /** * The overall set of permissions for the guild member, taking only roles into account * @type {EvaluatedPermissions} + * @readonly */ get permissions() { if (this.user.id === this.guild.ownerID) return new EvaluatedPermissions(this, Constants.ALL_PERMISSIONS); @@ -180,25 +195,27 @@ class GuildMember { /** * Whether the member is kickable by the client user. * @type {boolean} + * @readonly */ get kickable() { if (this.user.id === this.guild.ownerID) return false; if (this.user.id === this.client.user.id) return false; - const clientMember = this.member(this.client.member); + const clientMember = this.guild.member(this.client.user); if (!clientMember.hasPermission(Constants.PermissionFlags.KICK_MEMBERS)) return false; - return clientMember.highestRole.position > this.highestRole.positon; + return clientMember.highestRole.comparePositionTo(this.highestRole) > 0; } /** * Whether the member is bannable by the client user. * @type {boolean} + * @readonly */ get bannable() { if (this.user.id === this.guild.ownerID) return false; if (this.user.id === this.client.user.id) return false; - const clientMember = this.member(this.client.member); + const clientMember = this.guild.member(this.client.user); if (!clientMember.hasPermission(Constants.PermissionFlags.BAN_MEMBERS)) return false; - return clientMember.highestRole.position > this.highestRole.positon; + return clientMember.highestRole.comparePositionTo(this.highestRole) > 0; } /** @@ -231,7 +248,17 @@ class GuildMember { */ hasPermissions(permissions, explicit = false) { if (!explicit && this.user.id === this.guild.ownerID) return true; - return permissions.map(p => this.hasPermission(p, explicit)).every(v => v); + return permissions.every(p => this.hasPermission(p, explicit)); + } + + /** + * Checks whether the roles of the member allows them to perform specific actions, and lists any missing permissions. + * @param {PermissionResolvable[]} permissions The permissions to check for + * @param {boolean} [explicit=false] Whether to require the member to explicitly have the exact permissions + * @returns {array} + */ + missingPermissions(permissions, explicit = false) { + return permissions.filter(p => !this.hasPermission(p, explicit)); } /** @@ -380,7 +407,7 @@ class GuildMember { * console.log(`Hello from ${member}!`); */ toString() { - return String(this.user); + return `<@${this.nickname ? '!' : ''}${this.user.id}>`; } // These are here only for documentation purposes - they are implemented by TextBasedChannel diff --git a/src/structures/Invite.js b/src/structures/Invite.js index 6e48ba0f9..bcf165182 100644 --- a/src/structures/Invite.js +++ b/src/structures/Invite.js @@ -92,23 +92,38 @@ class Invite { */ this.channel = this.client.channels.get(data.channel.id) || new PartialGuildChannel(this.client, data.channel); - this._createdAt = new Date(data.created_at).getTime(); + /** + * The timestamp the invite was created at + * @type {number} + */ + this.createdTimestamp = new Date(data.created_at).getTime(); } /** - * The creation date of the invite + * The time the invite was created * @type {Date} + * @readonly */ get createdAt() { - return new Date(this._createdAt); + return new Date(this.createdTimestamp); } /** - * The creation date of the invite - * @type {Date} + * The timestamp the invite will expire at + * @type {number} + * @readonly */ - get creationDate() { - return new Date(this._createdAt); + get expiresTimestamp() { + return this.createdTimestamp + (this.maxAge * 1000); + } + + /** + * The time the invite will expire + * @type {Date} + * @readonly + */ + get expiresAt() { + return new Date(this.expiresTimestamp); } /** diff --git a/src/structures/Message.js b/src/structures/Message.js index 19254502b..e9e093ac5 100644 --- a/src/structures/Message.js +++ b/src/structures/Message.js @@ -2,6 +2,7 @@ const Attachment = require('./MessageAttachment'); const Embed = require('./MessageEmbed'); const Collection = require('../util/Collection'); const Constants = require('../util/Constants'); +const escapeMarkdown = require('../util/EscapeMarkdown'); /** * Represents a Message on Discord @@ -31,6 +32,12 @@ class Message { */ this.id = data.id; + /** + * The type of the message + * @type {string} + */ + this.type = Constants.MessageTypes[data.type]; + /** * The content of the message * @type {string} @@ -87,6 +94,18 @@ class Message { this.attachments = new Collection(); for (const attachment of data.attachments) this.attachments.set(attachment.id, new Attachment(this, attachment)); + /** + * The timestamp the message was sent at + * @type {number} + */ + this.createdTimestamp = new Date(data.timestamp).getTime(); + + /** + * The timestamp the message was last edited at (if applicable) + * @type {?number} + */ + this.editedTimestamp = data.edited_timestamp ? new Date(data.edited_timestamp).getTime() : null; + /** * An object containing a further users, roles or channels collections * @type {Object} @@ -128,8 +147,6 @@ class Message { } } - this._timestamp = new Date(data.timestamp).getTime(); - this._editedTimestamp = data.edited_timestamp ? new Date(data.edited_timestamp).getTime() : null; this._edits = []; } @@ -139,9 +156,9 @@ class Message { if (this.guild) this.member = this.guild.member(this.author); } if (data.content) this.content = data.content; - if (data.timestamp) this._timestamp = new Date(data.timestamp).getTime(); + if (data.timestamp) this.createdTimestamp = new Date(data.timestamp).getTime(); if (data.edited_timestamp) { - this._editedTimestamp = data.edited_timestamp ? new Date(data.edited_timestamp).getTime() : null; + this.editedTimestamp = data.edited_timestamp ? new Date(data.edited_timestamp).getTime() : null; } if ('tts' in data) this.tts = data.tts; if ('mention_everyone' in data) this.mentions.everyone = data.mention_everyone; @@ -185,24 +202,27 @@ class Message { } /** - * When the message was sent + * The time the message was sent * @type {Date} + * @readonly */ - get timestamp() { - return new Date(this._timestamp); + get createdAt() { + return new Date(this.createdTimestamp); } /** - * If the message was edited, the timestamp at which it was last edited + * The time the message was last edited at (if applicable) * @type {?Date} + * @readonly */ - get editedTimestamp() { - return new Date(this._editedTimestamp); + get editedAt() { + return this.editedTimestamp ? new Date(this.editedTimestamp) : null; } /** * The guild the message was sent in (if in a guild channel) * @type {?Guild} + * @readonly */ get guild() { return this.channel.guild || null; @@ -212,11 +232,11 @@ class Message { * The message contents with all mentions replaced by the equivalent text. If mentions cannot be resolved to a name, * the relevant mention in the message content will not be converted. * @type {string} + * @readonly */ get cleanContent() { return this.content - .replace(/@everyone/g, '@\u200Beveryone') - .replace(/@here/g, '@\u200Bhere') + .replace(/@(everyone|here)/g, '@\u200b$1') .replace(/<@!?[0-9]+>/g, (input) => { const id = input.replace(/<|!|>|@/g, ''); if (this.channel.type === 'dm' || this.channel.type === 'group') { @@ -250,6 +270,7 @@ class Message { * An array of cached versions of the message, including the current version. * Sorted from latest (first) to oldest (last). * @type {Message[]} + * @readonly */ get edits() { return this._edits.slice().unshift(this); @@ -258,6 +279,7 @@ class Message { /** * Whether the message is editable by the client user. * @type {boolean} + * @readonly */ get editable() { return this.author.id === this.client.user.id; @@ -266,6 +288,7 @@ class Message { /** * Whether the message is deletable by the client user. * @type {boolean} + * @readonly */ get deletable() { return this.author.id === this.client.user.id || (this.guild && @@ -276,6 +299,7 @@ class Message { /** * Whether the message is pinnable by the client user. * @type {boolean} + * @readonly */ get pinnable() { return !this.guild || @@ -301,7 +325,7 @@ class Message { * // update the content of a message * message.edit('This is my new content!') * .then(msg => console.log(`Updated the content of a message from ${msg.author}`)) - * .catch(console.log); + * .catch(console.error); */ edit(content) { return this.client.rest.methods.updateMessage(this, content); @@ -314,8 +338,8 @@ class Message { * @returns {Promise} */ editCode(lang, content) { - content = this.client.resolver.resolveString(content).replace(/```/g, '`\u200b``'); - return this.edit(`\`\`\`${lang ? lang : ''}\n${content}\n\`\`\``); + content = escapeMarkdown(this.client.resolver.resolveString(content), true); + return this.edit(`\`\`\`${lang || ''}\n${content}\n\`\`\``); } /** @@ -342,7 +366,7 @@ class Message { * // delete a message * message.delete() * .then(msg => console.log(`Deleted message from ${msg.author}`)) - * .catch(console.log); + * .catch(console.error); */ delete(timeout = 0) { return new Promise((resolve, reject) => { @@ -363,7 +387,7 @@ class Message { * // reply to a message * message.reply('Hey, I'm a reply!') * .then(msg => console.log(`Sent a reply to ${msg.author}`)) - * .catch(console.log); + * .catch(console.error); */ reply(content, options = {}) { content = this.client.resolver.resolveString(content); @@ -401,8 +425,8 @@ class Message { if (equal && rawData) { equal = this.mentions.everyone === message.mentions.everyone && - this._timestamp === new Date(rawData.timestamp).getTime() && - this._editedTimestamp === new Date(rawData.edited_timestamp).getTime(); + this.createdTimestamp === new Date(rawData.timestamp).getTime() && + this.editedTimestamp === new Date(rawData.edited_timestamp).getTime(); } return equal; diff --git a/src/structures/MessageCollector.js b/src/structures/MessageCollector.js index 81956faa6..375bc845a 100644 --- a/src/structures/MessageCollector.js +++ b/src/structures/MessageCollector.js @@ -24,6 +24,7 @@ class MessageCollector extends EventEmitter { * @typedef {Object} CollectorOptions * @property {number} [time] Duration for the collector in milliseconds * @property {number} [max] Maximum number of messages to handle + * @property {number} [maxMatches] Maximum number of successfully filtered messages to obtain */ /** @@ -86,12 +87,46 @@ class MessageCollector extends EventEmitter { * @event MessageCollector#message */ this.emit('message', message, this); - if (this.options.max && this.collected.size === this.options.max) this.stop('limit'); + if (this.collected.size >= this.options.maxMatches) this.stop('matchesLimit'); + else if (this.options.max && this.collected.size === this.options.max) this.stop('limit'); return true; } return false; } + /** + * Returns a promise that resolves when a valid message is sent. Rejects + * with collected messages if the Collector ends before receiving a message. + * @type {Promise} + * @readonly + */ + get next() { + return new Promise((resolve, reject) => { + if (this.ended) { + reject(this.collected); + return; + } + + const cleanup = () => { + this.removeListener('message', onMessage); + this.removeListener('end', onEnd); + }; + + const onMessage = (...args) => { + cleanup(); + resolve(...args); + }; + + const onEnd = (...args) => { + cleanup(); + reject(...args); + }; + + this.once('message', onMessage); + this.once('end', onEnd); + }); + } + /** * Stops the collector and emits `end`. * @param {string} [reason='user'] An optional reason for stopping the collector diff --git a/src/structures/Presence.js b/src/structures/Presence.js new file mode 100644 index 000000000..242c52389 --- /dev/null +++ b/src/structures/Presence.js @@ -0,0 +1,93 @@ +/** + * Represents a User's presence + */ +class Presence { + constructor(data) { + if (!data) return; + /** + * The status of the presence: + * + * * **`online`** - user is online + * * **`offline`** - user is offline or invisible + * * **`idle`** - user is AFK + * * **`dnd`** - user is in Do not Disturb + * @type {string} + */ + this.status = data.status || 'offline'; + + /** + * The game that the user is playing, `null` if they aren't playing a game. + * @type {?Game} + */ + this.game = data.game ? new Game(data.game) : null; + } + + update(data) { + this.status = data.status || this.status; + this.game = data.game ? new Game(data.game) : null; + } + + /** + * Whether this presence is equal to another + * @param {Presence} other the presence to compare + * @returns {boolean} + */ + equals(other) { + return ( + other && + this.status === other.status && + this.game ? this.game.equals(other.game) : !other.game + ); + } +} + +/** + * Represents a Game that is part of a User's presence. + */ +class Game { + constructor(data) { + /** + * The name of the game being played + * @type {string} + */ + this.name = data.name; + + /** + * The type of the game status + * @type {number} + */ + this.type = data.type; + + /** + * If the game is being streamed, a link to the stream + * @type {?string} + */ + this.url = data.url || null; + } + + /** + * Whether or not the game is being streamed + * @type {boolean} + * @readonly + */ + get streaming() { + return this.type === 1; + } + + /** + * Whether this game is equal to another game + * @param {Game} other the other game to compare + * @returns {boolean} + */ + equals(other) { + return ( + other && + this.name === other.name && + this.type === other.type && + this.url === other.url + ); + } +} + +exports.Presence = Presence; +exports.Game = Game; diff --git a/src/structures/Role.js b/src/structures/Role.js index 3c34518ca..4bbb6c55b 100644 --- a/src/structures/Role.js +++ b/src/structures/Role.js @@ -72,12 +72,21 @@ class Role { } /** - * The time the role was created + * The timestamp the role was created at + * @type {number} * @readonly - * @type {Date} */ - get creationDate() { - return new Date((this.id / 4194304) + 1420070400000); + get createdTimestamp() { + return (this.id / 4194304) + 1420070400000; + } + + /** + * The time the role was created + * @type {Date} + * @readonly + */ + get createdAt() { + return new Date(this.createdTimestamp); } /** @@ -94,6 +103,7 @@ class Role { /** * The cached guild members that have this role. * @type {Collection} + * @readonly */ get members() { return this.guild.members.filter(m => m.roles.has(this.id)); @@ -140,7 +150,17 @@ class Role { * @returns {boolean} */ hasPermissions(permissions, explicit = false) { - return permissions.map(p => this.hasPermission(p, explicit)).every(v => v); + return permissions.every(p => this.hasPermission(p, explicit)); + } + + /** + * Compares this role's position to another role's. + * @param {Role} role Role to compare to this one + * @returns {number} Negative number if the this role's position is lower (other role's is higher), + * positive number if the this one is higher (other's is lower), 0 if equal + */ + comparePositionTo(role) { + return this.constructor.comparePositions(this, role); } /** @@ -151,7 +171,7 @@ class Role { * // edit a role * role.edit({name: 'new role'}) * .then(r => console.log(`Edited role ${r}`)) - * .catch(console.log); + * .catch(console.error); */ edit(data) { return this.client.rest.methods.updateGuildRole(this, data); @@ -165,7 +185,7 @@ class Role { * // set the name of the role * role.setName('new role') * .then(r => console.log(`Edited name of role ${r}`)) - * .catch(console.log); + * .catch(console.error); */ setName(name) { return this.client.rest.methods.updateGuildRole(this, { name }); @@ -179,7 +199,7 @@ class Role { * // set the color of a role * role.setColor('#FF0000') * .then(r => console.log(`Set color of role ${r}`)) - * .catch(console.log); + * .catch(console.error); */ setColor(color) { return this.client.rest.methods.updateGuildRole(this, { color }); @@ -193,7 +213,7 @@ class Role { * // set the hoist of the role * role.setHoist(true) * .then(r => console.log(`Role hoisted: ${r.hoist}`)) - * .catch(console.log); + * .catch(console.error); */ setHoist(hoist) { return this.client.rest.methods.updateGuildRole(this, { hoist }); @@ -207,10 +227,10 @@ class Role { * // set the position of the role * role.setPosition(1) * .then(r => console.log(`Role position: ${r.position}`)) - * .catch(console.log); + * .catch(console.error); */ setPosition(position) { - return this.client.rest.methods.updateGuildRole(this, { position }); + return this.guild.setRolePosition(this, position); } /** @@ -221,12 +241,26 @@ class Role { * // set the permissions of the role * role.setPermissions(['KICK_MEMBERS', 'BAN_MEMBERS']) * .then(r => console.log(`Role updated ${r}`)) - * .catch(console.log); + * .catch(console.error); */ setPermissions(permissions) { return this.client.rest.methods.updateGuildRole(this, { permissions }); } + /** + * Set whether this role is mentionable + * @param {boolean} mentionable Whether this role should be mentionable + * @returns {Promise} + * @example + * // make the role mentionable + * role.setMentionable(true) + * .then(r => console.log(`Role updated ${r}`)) + * .catch(console.error); + */ + setMentionable(mentionable) { + return this.client.rest.methods.updateGuildRole(this, { mentionable }); + } + /** * Deletes the role * @returns {Promise} @@ -234,7 +268,7 @@ class Role { * // delete a role * role.delete() * .then(r => console.log(`Deleted role ${r}`)) - * .catch(console.log); + * .catch(console.error); */ delete() { return this.client.rest.methods.deleteGuildRole(this); @@ -265,6 +299,18 @@ class Role { toString() { return `<@&${this.id}>`; } + + /** + * Compares the positions of two roles. + * @param {Role} role1 First role to compare + * @param {Role} role2 Second role to compare + * @returns {number} Negative number if the first role's position is lower (second role's is higher), + * positive number if the first's is higher (second's is lower), 0 if equal + */ + static comparePositions(role1, role2) { + if (role1.position === role2.position) return role2.id - role1.id; + return role1.position - role2.position; + } } module.exports = Role; diff --git a/src/structures/TextChannel.js b/src/structures/TextChannel.js index d14b2e28a..8c0d8974a 100644 --- a/src/structures/TextChannel.js +++ b/src/structures/TextChannel.js @@ -42,6 +42,38 @@ class TextChannel extends GuildChannel { return members; } + /** + * Fetch all webhooks for the channel. + * @returns {Promise>} + */ + fetchWebhooks() { + return this.client.rest.methods.getChannelWebhooks(this); + } + + /** + * Create a webhook for the channel. + * @param {string} name The name of the webhook. + * @param {FileResolvable} avatar The avatar for the webhook. + * @returns {Promise} webhook The created webhook. + * @example + * channel.createWebhook('Snek', 'http://snek.s3.amazonaws.com/topSnek.png') + * .then(webhook => console.log(`Created Webhook ${webhook}`)) + * .catch(console.log) + */ + createWebhook(name, avatar) { + return new Promise((resolve, reject) => { + if (avatar) { + this.client.resolver.resolveFile(avatar).then(file => { + let base64 = new Buffer(file, 'binary').toString('base64'); + let dataURI = `data:;base64,${base64}`; + this.client.rest.methods.createWebhook(this, name, dataURI).then(resolve).catch(reject); + }).catch(reject); + } else { + this.client.rest.methods.createWebhook(this, name).then(resolve).catch(reject); + } + }); + } + // These are here only for documentation purposes - they are implemented by TextBasedChannel sendMessage() { return; } sendTTSMessage() { return; } diff --git a/src/structures/User.js b/src/structures/User.js index 0f43d4ced..b9ac5b522 100644 --- a/src/structures/User.js +++ b/src/structures/User.js @@ -1,5 +1,6 @@ const TextBasedChannel = require('./interface/TextBasedChannel'); const Constants = require('../util/Constants'); +const Presence = require('./Presence').Presence; /** * Represents a User on Discord. @@ -47,45 +48,43 @@ class User { * @type {boolean} */ this.bot = Boolean(data.bot); - - /** - * The status of the user: - * - * * **`online`** - user is online - * * **`offline`** - user is offline - * * **`idle`** - user is AFK - * @type {string} - */ - this.status = data.status || this.status || 'offline'; - - /** - * Represents data about a Game - * @property {string} name the name of the game being played. - * @property {string} [url] the URL of the stream, if the game is being streamed. - * @property {number} [type] if being streamed, this is `1`. - * @typedef {object} Game - */ - - /** - * The game that the user is playing, `null` if they aren't playing a game. - * @type {Game} - */ - this.game = data.game; } patch(data) { - for (const prop of ['id', 'username', 'discriminator', 'status', 'game', 'avatar', 'bot']) { + for (const prop of ['id', 'username', 'discriminator', 'avatar', 'bot']) { if (typeof data[prop] !== 'undefined') this[prop] = data[prop]; } } /** - * The time the user was created + * The timestamp the user was created at + * @type {number} * @readonly - * @type {Date} */ - get creationDate() { - return new Date((this.id / 4194304) + 1420070400000); + get createdTimestamp() { + return (this.id / 4194304) + 1420070400000; + } + + /** + * The time the user was created + * @type {Date} + * @readonly + */ + get createdAt() { + return new Date(this.createdTimestamp); + } + + /** + * The presence of this user + * @type {Presence} + * @readonly + */ + get presence() { + if (this.client.presences.has(this.id)) return this.client.presences.get(this.id); + for (const guild of this.client.guilds.values()) { + if (guild.presences.has(this.id)) return guild.presences.get(this.id); + } + return new Presence(); } /** @@ -136,6 +135,46 @@ class User { return this.client.rest.methods.deleteChannel(this); } + /** + * Sends a friend request to the user + * @returns {Promise} + */ + addFriend() { + return this.client.rest.methods.addFriend(this); + } + + /** + * Removes the user from your friends + * @returns {Promise} + */ + removeFriend() { + return this.client.rest.methods.removeFriend(this); + } + + /** + * Blocks the user + * @returns {Promise} + */ + block() { + return this.client.rest.methods.blockUser(this); + } + + /** + * Unblocks the user + * @returns {Promise} + */ + unblock() { + return this.client.rest.methods.unblockUser(this); + } + + /** + * Get the profile of the user + * @returns {Promise} + */ + fetchProfile() { + return this.client.rest.methods.fetchUserProfile(this); + } + /** * Checks if the user is equal to another. It compares username, ID, discriminator, status and the game being played. * It is recommended to compare equality by using `user.id === user2.id` unless you want to compare all properties. @@ -150,16 +189,6 @@ class User { this.avatar === user.avatar && this.bot === Boolean(user.bot); - if (equal) { - if (user.status) equal = this.status === user.status; - if (equal && user.game) { - equal = this.game && - this.game.name === user.game.name && - this.game.type === user.game.type && - this.game.url === user.game.url; - } - } - return equal; } diff --git a/src/structures/UserConnection.js b/src/structures/UserConnection.js new file mode 100644 index 000000000..d25df0300 --- /dev/null +++ b/src/structures/UserConnection.js @@ -0,0 +1,48 @@ +/** + * Represents a User Connection object (or "platform identity") + */ +class UserConnection { + constructor(user, data) { + /** + * The user that owns the Connection + * @type {User} + */ + this.user = user; + + this.setup(data); + } + + setup(data) { + /** + * The type of the Connection + * @type {string} + */ + this.type = data.type; + + /** + * The username of the connection account + * @type {string} + */ + this.name = data.name; + + /** + * The id of the connection account + * @type {string} + */ + this.id = data.id; + + /** + * Whether the connection is revoked + * @type {Boolean} + */ + this.revoked = data.revoked; + + /** + * an array of partial server integrations (not yet implemented in this lib) + * @type {Object[]} + */ + this.integrations = data.integrations; + } +} + +module.exports = UserConnection; diff --git a/src/structures/UserProfile.js b/src/structures/UserProfile.js new file mode 100644 index 000000000..4150b3a72 --- /dev/null +++ b/src/structures/UserProfile.js @@ -0,0 +1,49 @@ +const Collection = require('../util/Collection'); +const UserConnection = require('./UserConnection'); + +/** + * Represents a user's profile on Discord. + */ +class UserProfile { + constructor(user, data) { + /** + * The owner of the profile + * @type {User} + */ + this.user = user; + + /** + * The Client that created the instance of the the User. + * @type {Client} + */ + this.client = this.user.client; + Object.defineProperty(this, 'client', { enumerable: false, configurable: false }); + + /** + * Guilds that the ClientUser and the User share + * @type {Collection} + */ + this.mutualGuilds = new Collection(); + + /** + * The user's connections + * @type {Collection} + */ + this.connections = new Collection(); + + this.setup(data); + } + + setup(data) { + for (const guild of data.mutual_guilds) { + if (this.client.guilds.has(guild.id)) { + this.mutualGuilds.set(guild.id, this.client.guilds.get(guild.id)); + } + } + for (const connection of data.connected_accounts) { + this.connections.set(connection.id, new UserConnection(this.user, connection)); + } + } +} + +module.exports = UserProfile; diff --git a/src/structures/VoiceChannel.js b/src/structures/VoiceChannel.js index eb7bcd760..2bc565d8b 100644 --- a/src/structures/VoiceChannel.js +++ b/src/structures/VoiceChannel.js @@ -45,6 +45,22 @@ class VoiceChannel extends GuildChannel { return null; } + /** + * Checks if the client has permission join the voice channel + * @type {boolean} + */ + get joinable() { + return this.permissionsFor(this.client.user).hasPermission('CONNECT'); + } + + /** + * Checks if the client has permission to send audio to the voice channel + * @type {boolean} + */ + get speakable() { + return this.permissionsFor(this.client.user).hasPermission('SPEAK'); + } + /** * Sets the bitrate of the channel * @param {number} bitrate The new bitrate @@ -53,7 +69,7 @@ class VoiceChannel extends GuildChannel { * // set the bitrate of a voice channel * voiceChannel.setBitrate(48000) * .then(vc => console.log(`Set bitrate to ${vc.bitrate} for ${vc.name}`)) - * .catch(console.log); + * .catch(console.error); */ setBitrate(bitrate) { return this.rest.client.rest.methods.updateChannel(this, { bitrate }); @@ -66,7 +82,7 @@ class VoiceChannel extends GuildChannel { * // join a voice channel * voiceChannel.join() * .then(connection => console.log('Connected!')) - * .catch(console.log); + * .catch(console.error); */ join() { return this.client.voice.joinChannel(this); diff --git a/src/structures/Webhook.js b/src/structures/Webhook.js new file mode 100644 index 000000000..0212bf33d --- /dev/null +++ b/src/structures/Webhook.js @@ -0,0 +1,205 @@ +const path = require('path'); +const escapeMarkdown = require('../util/EscapeMarkdown'); + +/** + * Represents a Webhook + */ +class Webhook { + constructor(client, dataOrID, token) { + if (client) { + /** + * The client that instantiated the Channel + * @type {Client} + */ + this.client = client; + Object.defineProperty(this, 'client', { enumerable: false, configurable: false }); + if (dataOrID) this.setup(dataOrID); + } else { + this.id = dataOrID; + this.token = token; + this.client = this; + } + } + + setup(data) { + /** + * The name of the Webhook + * @type {string} + */ + this.name = data.name; + + /** + * The token for the Webhook + * @type {string} + */ + this.token = data.token; + + /** + * The avatar for the Webhook + * @type {string} + */ + this.avatar = data.avatar; + + /** + * The ID of the Webhook + * @type {string} + */ + this.id = data.id; + + /** + * The guild the Webhook belongs to + * @type {string} + */ + this.guildID = data.guild_id; + + /** + * The channel the Webhook belongs to + * @type {string} + */ + this.channelID = data.channel_id; + + /** + * The owner of the Webhook + * @type {User} + */ + if (data.user) this.owner = data.user; + } + + /** + * Options that can be passed into sendMessage, sendTTSMessage, sendFile, sendCode + * @typedef {Object} WebhookMessageOptions + * @property {boolean} [tts=false] Whether or not the message should be spoken aloud + * @property {boolean} [disableEveryone=this.options.disableEveryone] Whether or not @everyone and @here + * should be replaced with plain-text + */ + + /** + * Send a message with this webhook + * @param {StringResolvable} content The content to send. + * @param {WebhookMessageOptions} [options={}] The options to provide. + * @returns {Promise} + * @example + * // send a message + * webhook.sendMessage('hello!') + * .then(message => console.log(`Sent message: ${message.content}`)) + * .catch(console.error); + */ + sendMessage(content, options = {}) { + return this.client.rest.methods.sendWebhookMessage(this, content, options); + } + + /** + * Send a raw slack message with this webhook + * @param {Object} body The raw body to send. + * @returns {Promise} + * @example + * // send a slack message + * webhook.sendSlackMessage({ + * 'username': 'Wumpus', + * 'attachments': [{ + * 'pretext': 'this looks pretty cool', + * 'color': '#F0F', + * 'footer_icon': 'http://snek.s3.amazonaws.com/topSnek.png', + * 'footer': 'Powered by sneks', + * 'ts': new Date().getTime() / 1000 + * }] + * }).catch(console.log); + */ + sendSlackMessage(body) { + return this.client.rest.methods.sendSlackWebhookMessage(this, body); + } + + /** + * Send a text-to-speech message with this webhook + * @param {StringResolvable} content The content to send + * @param {WebhookMessageOptions} [options={}] The options to provide + * @returns {Promise} + * @example + * // send a TTS message + * webhook.sendTTSMessage('hello!') + * .then(message => console.log(`Sent tts message: ${message.content}`)) + * .catch(console.error); + */ + sendTTSMessage(content, options = {}) { + Object.assign(options, { tts: true }); + return this.client.rest.methods.sendWebhookMessage(this, content, options); + } + + /** + * Send a file with this webhook + * @param {FileResolvable} attachment The file to send + * @param {string} [fileName="file.jpg"] The name and extension of the file + * @param {StringResolvable} [content] Text message to send with the attachment + * @param {WebhookMessageOptions} [options] The options to provide + * @returns {Promise} + */ + sendFile(attachment, fileName, content, options = {}) { + if (!fileName) { + if (typeof attachment === 'string') { + fileName = path.basename(attachment); + } else if (attachment && attachment.path) { + fileName = path.basename(attachment.path); + } else { + fileName = 'file.jpg'; + } + } + return new Promise((resolve, reject) => { + this.client.resolver.resolveFile(attachment).then(file => { + this.client.rest.methods.sendWebhookMessage(this, content, options, { + file, + name: fileName, + }).then(resolve).catch(reject); + }).catch(reject); + }); + } + + /** + * Send a code block with this webhook + * @param {string} lang Language for the code block + * @param {StringResolvable} content Content of the code block + * @param {WebhookMessageOptions} options The options to provide + * @returns {Promise} + */ + sendCode(lang, content, options = {}) { + if (options.split) { + if (typeof options.split !== 'object') options.split = {}; + if (!options.split.prepend) options.split.prepend = `\`\`\`${lang || ''}\n`; + if (!options.split.append) options.split.append = '\n```'; + } + content = escapeMarkdown(this.client.resolver.resolveString(content), true); + return this.sendMessage(`\`\`\`${lang || ''}\n${content}\n\`\`\``, options); + } + + /** + * Edit the Webhook. + * @param {string} name The new name for the Webhook + * @param {FileResolvable} avatar The new avatar for the Webhook. + * @returns {Promise} + */ + edit(name = this.name, avatar) { + return new Promise((resolve, reject) => { + if (avatar) { + this.client.resolver.resolveFile(avatar).then(file => { + const dataURI = this.client.resolver.resolveBase64(file); + this.client.rest.methods.editWebhook(this, name, dataURI) + .then(resolve).catch(reject); + }).catch(reject); + } else { + this.client.rest.methods.editWebhook(this, name) + .then(data => { + this.setup(data); + }).catch(reject); + } + }); + } + + /** + * Delete the Webhook + * @returns {Promise} + */ + delete() { + return this.client.rest.methods.deleteWebhook(this); + } +} + +module.exports = Webhook; diff --git a/src/structures/interface/TextBasedChannel.js b/src/structures/interface/TextBasedChannel.js index 8a4609a64..12f31cead 100644 --- a/src/structures/interface/TextBasedChannel.js +++ b/src/structures/interface/TextBasedChannel.js @@ -2,6 +2,7 @@ const path = require('path'); const Message = require('../Message'); const MessageCollector = require('../MessageCollector'); const Collection = require('../../util/Collection'); +const escapeMarkdown = require('../../util/EscapeMarkdown'); /** * Interface for classes that have text-channel-like features @@ -27,7 +28,7 @@ class TextBasedChannel { * @typedef {Object} MessageOptions * @property {boolean} [tts=false] Whether or not the message should be spoken aloud * @property {string} [nonce=''] The nonce for the message - * @property {boolean} [disable_everyone=this.client.options.disable_everyone] Whether or not @everyone and @here + * @property {boolean} [disableEveryone=this.client.options.disableEveryone] Whether or not @everyone and @here * should be replaced with plain-text * @property {boolean|SplitOptions} [split=false] Whether or not the message should be split into multiple messages if * it exceeds the character limit. If an object is provided, these are the options for splitting the message. @@ -38,8 +39,8 @@ class TextBasedChannel { * @typedef {Object} SplitOptions * @property {number} [maxLength=1950] Maximum character length per message piece * @property {string} [char='\n'] Character to split the message with - * @property {string} [prepend=''] Text to prepend to each middle piece - * @property {string} [append=''] Text to append to each middle piece + * @property {string} [prepend=''] Text to prepend to every piece except the first + * @property {string} [append=''] Text to append to every piece except the last */ /** @@ -51,7 +52,7 @@ class TextBasedChannel { * // send a message * channel.sendMessage('hello!') * .then(message => console.log(`Sent message: ${message.content}`)) - * .catch(console.log); + * .catch(console.error); */ sendMessage(content, options = {}) { return this.client.rest.methods.sendMessage(this, content, options); @@ -66,7 +67,7 @@ class TextBasedChannel { * // send a TTS message * channel.sendTTSMessage('hello!') * .then(message => console.log(`Sent tts message: ${message.content}`)) - * .catch(console.log); + * .catch(console.error); */ sendTTSMessage(content, options = {}) { Object.assign(options, { tts: true }); @@ -111,15 +112,16 @@ class TextBasedChannel { sendCode(lang, content, options = {}) { if (options.split) { if (typeof options.split !== 'object') options.split = {}; - if (!options.split.prepend) options.split.prepend = `\`\`\`${lang ? lang : ''}\n`; + if (!options.split.prepend) options.split.prepend = `\`\`\`${lang || ''}\n`; if (!options.split.append) options.split.append = '\n```'; } - content = this.client.resolver.resolveString(content).replace(/```/g, '`\u200b``'); - return this.sendMessage(`\`\`\`${lang ? lang : ''}\n${content}\n\`\`\``, options); + content = escapeMarkdown(this.client.resolver.resolveString(content), true); + return this.sendMessage(`\`\`\`${lang || ''}\n${content}\n\`\`\``, options); } /** * Gets a single message from this channel, regardless of it being cached or not. + * Only OAuth bot accounts can use this method. * @param {string} messageID The ID of the message to get * @returns {Promise} * @example @@ -158,7 +160,7 @@ class TextBasedChannel { * // get messages * channel.fetchMessages({limit: 10}) * .then(messages => console.log(`Received ${messages.size} messages`)) - * .catch(console.log); + * .catch(console.error); */ fetchMessages(options = {}) { return new Promise((resolve, reject) => { @@ -241,6 +243,7 @@ class TextBasedChannel { /** * Whether or not the typing indicator is being shown in the channel. * @type {boolean} + * @readonly */ get typing() { return this.client.user._typing.has(this.id); @@ -249,6 +252,7 @@ class TextBasedChannel { /** * Number of times `startTyping` has been called. * @type {number} + * @readonly */ get typingCount() { if (this.client.user._typing.has(this.id)) return this.client.user._typing.get(this.id).count; @@ -307,23 +311,28 @@ class TextBasedChannel { } /** - * Bulk delete a given Collection or Array of messages in one go. Returns the deleted messages after. + * Bulk delete given messages. * Only OAuth Bot accounts may use this method. - * @param {Collection|Message[]} messages The messages to delete - * @returns {Collection} + * @param {Collection|Message[]|number} messages Messages to delete, or number of messages to delete + * @returns {Promise>} Deleted messages */ bulkDelete(messages) { - if (messages instanceof Collection) messages = messages.array(); - if (!(messages instanceof Array)) return Promise.reject(new TypeError('Messages must be an Array or Collection.')); - const messageIDs = messages.map(m => m.id); - return this.client.rest.methods.bulkDeleteMessages(this, messageIDs); + return new Promise((resolve, reject) => { + if (!isNaN(messages)) { + this.fetchMessages({ limit: messages }).then(msgs => resolve(this.bulkDelete(msgs))); + } else if (messages instanceof Array || messages instanceof Collection) { + const messageIDs = messages instanceof Collection ? messages.keyArray() : messages.map(m => m.id); + resolve(this.client.rest.methods.bulkDeleteMessages(this, messageIDs)); + } else { + reject(new TypeError('Messages must be an Array, Collection, or number.')); + } + }); } _cacheMessage(message) { - const maxSize = this.client.options.max_message_cache; + const maxSize = this.client.options.messageCacheMaxSize; if (maxSize === 0) return null; - if (this.messages.size >= maxSize) this.messages.delete(this.messages.keys().next().value); - + if (this.messages.size >= maxSize && maxSize > 0) this.messages.delete(this.messages.firstKey()); this.messages.set(message.id, message); return message; } diff --git a/src/util/Collection.js b/src/util/Collection.js index 70b29b9c2..53299023a 100644 --- a/src/util/Collection.js +++ b/src/util/Collection.js @@ -3,26 +3,48 @@ * @extends {Map} */ class Collection extends Map { + constructor(iterable) { + super(iterable); + this._array = null; + this._keyArray = null; + } + + set(key, val) { + super.set(key, val); + this._array = null; + this._keyArray = null; + } + + delete(key) { + super.delete(key); + this._array = null; + this._keyArray = null; + } + /** - * Returns an ordered array of the values of this collection. + * Creates an ordered array of the values of this collection, and caches it internally. The array will only be + * reconstructed if an item is added to or removed from the collection, or if you add/remove elements on the array. * @returns {Array} * @example * // identical to: * Array.from(collection.values()); */ array() { - return Array.from(this.values()); + if (!this._array || this._array.length !== this.size) this._array = Array.from(this.values()); + return this._array; } /** - * Returns an ordered array of the keys of this collection. + * Creates an ordered array of the keys of this collection, and caches it internally. The array will only be + * reconstructed if an item is added to or removed from the collection, or if you add/remove elements on the array. * @returns {Array} * @example * // identical to: * Array.from(collection.keys()); */ keyArray() { - return Array.from(this.keys()); + if (!this._keyArray || this._keyArray.length !== this.size) this._keyArray = Array.from(this.keys()); + return this._keyArray; } /** @@ -183,11 +205,27 @@ class Collection extends Map { */ filter(fn, thisArg) { if (thisArg) fn = fn.bind(thisArg); - const collection = new Collection(); + const results = new Collection(); for (const [key, val] of this) { - if (fn(val, key, this)) collection.set(key, val); + if (fn(val, key, this)) results.set(key, val); } - return collection; + return results; + } + + /** + * Identical to + * [Array.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter). + * @param {function} fn Function used to test (should return a boolean) + * @param {Object} [thisArg] Value to use as `this` when executing function + * @returns {Collection} + */ + filterArray(fn, thisArg) { + if (thisArg) fn = fn.bind(thisArg); + const results = []; + for (const [key, val] of this) { + if (fn(val, key, this)) results.push(val); + } + return results; } /** @@ -248,6 +286,21 @@ class Collection extends Map { return currentVal; } + /** + * Combines this collection with others into a new collection. None of the source collections are modified. + * @param {Collection} collections Collections to merge + * @returns {Collection} + * @example const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl); + */ + concat(...collections) { + const newColl = new this.constructor(); + for (const [key, val] of this) newColl.set(key, val); + for (const coll of collections) { + for (const [key, val] of coll) newColl.set(key, val); + } + return newColl; + } + /** * If the items in this collection have a delete method (e.g. messages), invoke * the delete method. Returns an array of promises diff --git a/src/util/Constants.js b/src/util/Constants.js index 8d3c24d0e..60575cd61 100644 --- a/src/util/Constants.js +++ b/src/util/Constants.js @@ -1,35 +1,44 @@ +exports.Package = require('../../package.json'); + /** * Options for a Client. * @typedef {Object} ClientOptions - * @property {string} [api_request_method='sequential'] 'sequential' or 'burst'. Sequential executes all requests in + * @property {string} [apiRequestMethod='sequential'] 'sequential' or 'burst'. Sequential executes all requests in * the order they are triggered, whereas burst runs multiple at a time, and doesn't guarantee a particular order. - * @property {number} [shard_id=0] The ID of this shard - * @property {number} [shard_count=0] The number of shards - * @property {number} [max_message_cache=200] Number of messages to cache per channel - * @property {number} [message_cache_lifetime=0] How long until a message should be uncached by the message sweeping + * @property {number} [shardId=0] The ID of this shard + * @property {number} [shardCount=0] The number of shards + * @property {number} [messageCacheMaxSize=200] Maximum number of messages to cache per channel + * @property {boolean} [sync=false] Whether to periodically sync guilds + * (-1 for unlimited - don't do this without message sweeping, otherwise memory usage will climb indefinitely) + * @property {number} [messageCacheLifetime=0] How long until a message should be uncached by the message sweeping * (in seconds, 0 for forever) - * @property {number} [message_sweep_interval=0] How frequently to remove messages from the cache that are older than - * the max message lifetime (in seconds, 0 for never) - * @property {boolean} [fetch_all_members=false] Whether to cache all guild members and users upon startup - * @property {boolean} [disable_everyone=false] Default value for MessageOptions.disable_everyone - * @property {number} [rest_ws_bridge_timeout=5000] Maximum time permitted between REST responses and their + * @property {number} [messageSweepInterval=0] How frequently to remove messages from the cache that are older than + * the message cache lifetime (in seconds, 0 for never) + * @property {boolean} [fetchAllMembers=false] Whether to cache all guild members and users upon startup, as well as + * upon joining a guild + * @property {boolean} [disableEveryone=false] Default value for MessageOptions.disableEveryone + * @property {number} [restWsBridgeTimeout=5000] Maximum time permitted between REST responses and their * corresponding websocket events + * @property {string[]} [disabledEvents] An array of disabled websocket events. Events in this array will not be + * processed. Disabling useless events such as 'TYPING_START' can result in significant performance increases on + * large-scale bots. * @property {WebsocketOptions} [ws] Options for the websocket */ exports.DefaultOptions = { - api_request_method: 'sequential', - shard_id: 0, - shard_count: 0, - max_message_cache: 200, - message_cache_lifetime: 0, - message_sweep_interval: 0, - fetch_all_members: false, - disable_everyone: false, - rest_ws_bridge_timeout: 5000, - protocol_version: 6, + apiRequestMethod: 'sequential', + shardId: 0, + shardCount: 0, + messageCacheMaxSize: 200, + messageCacheLifetime: 0, + messageSweepInterval: 0, + fetchAllMembers: false, + disableEveryone: false, + restWsBridgeTimeout: 5000, + disabledEvents: [], + sync: false, /** - * Websocket options. + * Websocket options. These are left as snake_case to match the API. * @typedef {Object} WebsocketOptions * @property {number} [large_threshold=250] Number of members in a guild to be considered large * @property {boolean} [compress=true] Whether to compress data sent on the connection @@ -47,23 +56,6 @@ exports.DefaultOptions = { }, }; -exports.Status = { - READY: 0, - CONNECTING: 1, - RECONNECTING: 2, - IDLE: 3, - NEARLY: 4, -}; - -exports.ChannelTypes = { - text: 0, - DM: 1, - voice: 2, - groupDM: 3, -}; - -exports.Package = require('../../package.json'); - exports.Errors = { NO_TOKEN: 'Request to use token, but token was unavailable to the client.', NO_BOT_ACCOUNT: 'You ideally should be using a bot account!', @@ -72,16 +64,17 @@ exports.Errors = { NOT_A_PERMISSION: 'Invalid permission string or number.', INVALID_RATE_LIMIT_METHOD: 'Unknown rate limiting method.', BAD_LOGIN: 'Incorrect login details were provided.', - INVALID_SHARD: 'Invalid shard settings were provided', + INVALID_SHARD: 'Invalid shard settings were provided.', }; -const API = `https://discordapp.com/api/v${exports.DefaultOptions.protocol_version}`; - +const PROTOCOL_VERSION = exports.PROTOCOL_VERSION = 6; +const API = exports.API = `https://discordapp.com/api/v${PROTOCOL_VERSION}`; const Endpoints = exports.Endpoints = { - // general endpoints + // general login: `${API}/auth/login`, logout: `${API}/auth/logout`, gateway: `${API}/gateway`, + botGateway: `${API}/gateway/bot`, invite: (id) => `${API}/invite/${id}`, inviteLink: (id) => `https://discord.gg/${id}`, CDN: 'https://cdn.discordapp.com', @@ -89,9 +82,11 @@ const Endpoints = exports.Endpoints = { // users user: (userID) => `${API}/users/${userID}`, userChannels: (userID) => `${Endpoints.user(userID)}/channels`, + userProfile: (userID) => `${Endpoints.user(userID)}/profile`, avatar: (userID, avatar) => userID === '1' ? avatar : `${Endpoints.user(userID)}/avatars/${avatar}.jpg`, me: `${API}/users/@me`, meGuild: (guildID) => `${Endpoints.me}/guilds/${guildID}`, + relationships: (userID) => `${Endpoints.user(userID)}/relationships`, // guilds guilds: `${API}/guilds`, @@ -108,6 +103,7 @@ const Endpoints = exports.Endpoints = { guildMember: (guildID, memberID) => `${Endpoints.guildMembers(guildID)}/${memberID}`, stupidInconsistentGuildEndpoint: (guildID) => `${Endpoints.guildMember(guildID, '@me')}/nick`, guildChannels: (guildID) => `${Endpoints.guild(guildID)}/channels`, + guildEmojis: (guildID) => `${Endpoints.guild(guildID)}/emojis`, // channels channels: `${API}/channels`, @@ -117,6 +113,25 @@ const Endpoints = exports.Endpoints = { channelTyping: (channelID) => `${Endpoints.channel(channelID)}/typing`, channelPermissions: (channelID) => `${Endpoints.channel(channelID)}/permissions`, channelMessage: (channelID, messageID) => `${Endpoints.channelMessages(channelID)}/${messageID}`, + channelWebhooks: (channelID) => `${Endpoints.channel(channelID)}/webhooks`, + + // webhooks + webhook: (webhookID, token) => `${API}/webhooks/${webhookID}${token ? `/${token}` : ''}`, +}; + +exports.Status = { + READY: 0, + CONNECTING: 1, + RECONNECTING: 2, + IDLE: 3, + NEARLY: 4, +}; + +exports.ChannelTypes = { + text: 0, + DM: 1, + voice: 2, + groupDM: 3, }; exports.OPCodes = { @@ -130,6 +145,8 @@ exports.OPCodes = { RECONNECT: 7, REQUEST_GUILD_MEMBERS: 8, INVALID_SESSION: 9, + HELLO: 10, + HEARTBEAT_ACK: 11, }; exports.VoiceOPCodes = { @@ -145,52 +162,49 @@ exports.Events = { READY: 'ready', GUILD_CREATE: 'guildCreate', GUILD_DELETE: 'guildDelete', + GUILD_UPDATE: 'guildUpdate', GUILD_UNAVAILABLE: 'guildUnavailable', GUILD_AVAILABLE: 'guildAvailable', - GUILD_UPDATE: 'guildUpdate', - GUILD_BAN_ADD: 'guildBanAdd', - GUILD_BAN_REMOVE: 'guildBanRemove', GUILD_MEMBER_ADD: 'guildMemberAdd', GUILD_MEMBER_REMOVE: 'guildMemberRemove', GUILD_MEMBER_UPDATE: 'guildMemberUpdate', - GUILD_ROLE_CREATE: 'guildRoleCreate', - GUILD_ROLE_DELETE: 'guildRoleDelete', - GUILD_ROLE_UPDATE: 'guildRoleUpdate', GUILD_MEMBER_AVAILABLE: 'guildMemberAvailable', + GUILD_MEMBER_SPEAKING: 'guildMemberSpeaking', + GUILD_MEMBERS_CHUNK: 'guildMembersChunk', + GUILD_ROLE_CREATE: 'roleCreate', + GUILD_ROLE_DELETE: 'roleDelete', + GUILD_ROLE_UPDATE: 'roleUpdate', + GUILD_EMOJI_CREATE: 'guildEmojiCreate', + GUILD_EMOJI_DELETE: 'guildEmojiDelete', + GUILD_EMOJI_UPDATE: 'guildEmojiUpdate', + GUILD_BAN_ADD: 'guildBanAdd', + GUILD_BAN_REMOVE: 'guildBanRemove', CHANNEL_CREATE: 'channelCreate', CHANNEL_DELETE: 'channelDelete', CHANNEL_UPDATE: 'channelUpdate', - PRESENCE_UPDATE: 'presenceUpdate', - USER_UPDATE: 'userUpdate', - VOICE_STATE_UPDATE: 'voiceStateUpdate', - TYPING_START: 'typingStart', - TYPING_STOP: 'typingStop', - WARN: 'warn', - GUILD_MEMBERS_CHUNK: 'guildMembersChunk', + CHANNEL_PINS_UPDATE: 'channelPinsUpdate', MESSAGE_CREATE: 'message', MESSAGE_DELETE: 'messageDelete', MESSAGE_UPDATE: 'messageUpdate', + MESSAGE_BULK_DELETE: 'messageDeleteBulk', + USER_UPDATE: 'userUpdate', + PRESENCE_UPDATE: 'presenceUpdate', + VOICE_STATE_UPDATE: 'voiceStateUpdate', + TYPING_START: 'typingStart', + TYPING_STOP: 'typingStop', DISCONNECT: 'disconnect', RECONNECTING: 'reconnecting', - GUILD_MEMBER_SPEAKING: 'guildMemberSpeaking', - MESSAGE_BULK_DELETE: 'messageDeleteBulk', - CHANNEL_PINS_UPDATE: 'channelPinsUpdate', + ERROR: 'error', + WARN: 'warn', DEBUG: 'debug', }; exports.WSEvents = { - 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', - GUILD_BAN_ADD: 'GUILD_BAN_ADD', - GUILD_BAN_REMOVE: 'GUILD_BAN_REMOVE', + GUILD_SYNC: 'GUILD_SYNC', GUILD_CREATE: 'GUILD_CREATE', GUILD_DELETE: 'GUILD_DELETE', + GUILD_UPDATE: 'GUILD_UPDATE', GUILD_MEMBER_ADD: 'GUILD_MEMBER_ADD', GUILD_MEMBER_REMOVE: 'GUILD_MEMBER_REMOVE', GUILD_MEMBER_UPDATE: 'GUILD_MEMBER_UPDATE', @@ -198,16 +212,35 @@ exports.WSEvents = { GUILD_ROLE_CREATE: 'GUILD_ROLE_CREATE', GUILD_ROLE_DELETE: 'GUILD_ROLE_DELETE', GUILD_ROLE_UPDATE: 'GUILD_ROLE_UPDATE', - GUILD_UPDATE: 'GUILD_UPDATE', - TYPING_START: 'TYPING_START', + GUILD_BAN_ADD: 'GUILD_BAN_ADD', + GUILD_BAN_REMOVE: 'GUILD_BAN_REMOVE', + CHANNEL_CREATE: 'CHANNEL_CREATE', + CHANNEL_DELETE: 'CHANNEL_DELETE', + CHANNEL_UPDATE: 'CHANNEL_UPDATE', + CHANNEL_PINS_UPDATE: 'CHANNEL_PINS_UPDATE', + MESSAGE_CREATE: 'MESSAGE_CREATE', + MESSAGE_DELETE: 'MESSAGE_DELETE', + MESSAGE_UPDATE: 'MESSAGE_UPDATE', + MESSAGE_DELETE_BULK: 'MESSAGE_DELETE_BULK', USER_UPDATE: 'USER_UPDATE', + PRESENCE_UPDATE: 'PRESENCE_UPDATE', VOICE_STATE_UPDATE: 'VOICE_STATE_UPDATE', + TYPING_START: 'TYPING_START', FRIEND_ADD: 'RELATIONSHIP_ADD', FRIEND_REMOVE: 'RELATIONSHIP_REMOVE', VOICE_SERVER_UPDATE: 'VOICE_SERVER_UPDATE', - MESSAGE_DELETE_BULK: 'MESSAGE_DELETE_BULK', - CHANNEL_PINS_UPDATE: 'CHANNEL_PINS_UPDATE', - GUILD_SYNC: 'GUILD_SYNC', + RELATIONSHIP_ADD: 'RELATIONSHIP_ADD', + RELATIONSHIP_REMOVE: 'RELATIONSHIP_REMOVE', +}; + +exports.MessageTypes = { + 0: 'DEFAULT', + 1: 'RECIPIENT_ADD', + 2: 'RECIPIENT_REMOVE', + 3: 'CALL', + 4: 'CHANNEL_NAME_CHANGE', + 5: 'CHANNEL_ICON_CHANGE', + 6: 'PINS_ADD', }; const PermissionFlags = exports.PermissionFlags = { @@ -238,11 +271,11 @@ const PermissionFlags = exports.PermissionFlags = { CHANGE_NICKNAME: 1 << 26, MANAGE_NICKNAMES: 1 << 27, MANAGE_ROLES_OR_PERMISSIONS: 1 << 28, + MANAGE_WEBHOOKS: 1 << 29, + MANAGE_EMOJIS: 1 << 30, }; let _ALL_PERMISSIONS = 0; for (const key in PermissionFlags) _ALL_PERMISSIONS |= PermissionFlags[key]; - exports.ALL_PERMISSIONS = _ALL_PERMISSIONS; - exports.DEFAULT_PERMISSIONS = 104324097; diff --git a/src/util/EscapeMarkdown.js b/src/util/EscapeMarkdown.js new file mode 100644 index 000000000..9db8c13eb --- /dev/null +++ b/src/util/EscapeMarkdown.js @@ -0,0 +1,5 @@ +module.exports = function escapeMarkdown(text, onlyCodeBlock = false, onlyInlineCode = false) { + if (onlyCodeBlock) return text.replace(/```/g, '`\u200b``'); + if (onlyInlineCode) return text.replace(/\\(`|\\)/g, '$1').replace(/(`|\\)/g, '\\$1'); + return text.replace(/\\(\*|_|`|~|\\)/g, '$1').replace(/(\*|_|`|~|\\)/g, '\\$1'); +}; diff --git a/src/util/FetchRecommendedShards.js b/src/util/FetchRecommendedShards.js new file mode 100644 index 000000000..a60f51006 --- /dev/null +++ b/src/util/FetchRecommendedShards.js @@ -0,0 +1,19 @@ +const superagent = require('superagent'); +const botGateway = require('./Constants').Endpoints.botGateway; + +/** + * Gets the recommended shard count from Discord + * @param {number} token Discord auth token + * @returns {Promise} the recommended number of shards + */ +module.exports = function fetchRecommendedShards(token) { + return new Promise((resolve, reject) => { + if (!token) throw new Error('A token must be provided.'); + superagent.get(botGateway) + .set('Authorization', `Bot ${token.replace(/^Bot\s*/i, '')}`) + .end((err, res) => { + if (err) reject(err); + resolve(res.body.shards); + }); + }); +}; diff --git a/src/util/MakeError.js b/src/util/MakeError.js new file mode 100644 index 000000000..bbc84dbf8 --- /dev/null +++ b/src/util/MakeError.js @@ -0,0 +1,6 @@ +module.exports = function makeError(obj) { + const err = new Error(obj.message); + err.name = obj.name; + err.stack = obj.stack; + return err; +}; diff --git a/src/util/MakePlainError.js b/src/util/MakePlainError.js new file mode 100644 index 000000000..b409462b1 --- /dev/null +++ b/src/util/MakePlainError.js @@ -0,0 +1,7 @@ +module.exports = function makePlainError(err) { + const obj = {}; + obj.name = err.name; + obj.message = err.message; + obj.stack = err.stack; + return obj; +}; diff --git a/test/random.js b/test/random.js index 8d1103744..efc8662f6 100644 --- a/test/random.js +++ b/test/random.js @@ -4,29 +4,30 @@ const Discord = require('../'); const request = require('superagent'); const fs = require('fs'); -const client = new Discord.Client({ fetch_all_members: false, api_request_method: 'sequential' }); +const client = new Discord.Client({ fetchAllMembers: false, apiRequestMethod: 'sequential' }); -const { email, password, token } = require('./auth.json'); +const { email, password, token, usertoken, song } = require('./auth.json'); -client.login(token).then(atoken => console.log('logged in with token ' + atoken)).catch(console.log); +client.login(token).then(atoken => console.log('logged in with token ' + atoken)).catch(console.error); + +client.ws.on('send', console.log); client.on('ready', () => { console.log('ready!'); }); +client.on('userUpdate', (o, n) => { + console.log(o.username, n.username); +}); + +client.on('guildMemberAdd', (g, m) => console.log(`${m.user.username} joined ${g.name}`)); + client.on('channelCreate', channel => { console.log(`made ${channel.name}`); }); -client.on('guildMemberAdd', (g, m) => { - console.log(`${m.user.username} joined ${g.name}`); -}) - -client.on('guildMemberUpdate', (g, o, n) => { - console.log(o.nickname, n.nickname); -}); - -client.on('debug', console.log); +client.on('error', m => console.log('debug', m)); +client.on('reconnecting', m => console.log('debug', m)); client.on('message', message => { if (true) { @@ -36,6 +37,23 @@ client.on('message', message => { } } + if (message.content === 'imma queue pls') { + let count = 0; + let ecount = 0; + for(let x = 0; x < 4000; x++) { + message.channel.sendMessage(`this is message ${x} of 3999`) + .then(m => { + count++; + console.log('reached', count, ecount); + }) + .catch(m => { + console.error(m); + ecount++; + console.log('reached', count, ecount); + }); + } + } + if (message.content === 'myperms?') { message.channel.sendMessage('Your permissions are:\n' + JSON.stringify(message.channel.permissionsFor(message.author).serialize(), null, 4)); @@ -57,7 +75,7 @@ client.on('message', message => { request .get('url') .end((err, res) => { - client.user.setAvatar(res.body).catch(console.log) + client.user.setAvatar(res.body).catch(console.error) .then(user => message.channel.sendMessage('Done!')); }); } @@ -65,11 +83,11 @@ client.on('message', message => { if (message.content.startsWith('gn')) { message.guild.setName(message.content.substr(3)) .then(guild => console.log('guild updated to', guild.name)) - .catch(console.log); + .catch(console.error); } if (message.content === 'leave') { - message.guild.leave().then(guild => console.log('left guild', guild.name)).catch(console.log); + message.guild.leave().then(guild => console.log('left guild', guild.name)).catch(console.error); } if (message.content === 'stats') { @@ -79,7 +97,7 @@ client.on('message', message => { m += `I am aware of ${client.channels.size} channels overall\n`; m += `I am aware of ${client.guilds.size} guilds overall\n`; m += `I am aware of ${client.users.size} users overall\n`; - message.channel.sendMessage(m).then(msg => msg.edit('nah')).catch(console.log); + message.channel.sendMessage(m).then(msg => msg.edit('nah')).catch(console.error); } if (message.content === 'messageme!') { @@ -94,7 +112,7 @@ client.on('message', message => { message.guild.member(message.mentions[0]).kick().then(member => { console.log(member); message.channel.sendMessage('Kicked!' + member.user.username); - }).catch(console.log); + }).catch(console.error); } if (message.content === 'ratelimittest') { @@ -108,17 +126,17 @@ client.on('message', message => { if (message.content === 'makerole') { message.guild.createRole().then(role => { message.channel.sendMessage(`Made role ${role.name}`); - }).catch(console.log); + }).catch(console.error); } } }); function nameLoop(user) { - // user.setUsername(user.username + 'a').then(nameLoop).catch(console.log); + // user.setUsername(user.username + 'a').then(nameLoop).catch(console.error); } function chanLoop(channel) { - channel.setName(channel.name + 'a').then(chanLoop).catch(console.log); + channel.setName(channel.name + 'a').then(chanLoop).catch(console.error); } client.on('message', msg => { @@ -142,6 +160,7 @@ let disp, con; client.on('message', msg => { if (msg.content.startsWith('/play')) { + console.log('I am now going to play', msg.content); const chan = msg.content.split(' ').slice(1).join(' '); con.playStream(ytdl(chan, {filter : 'audioonly'}), { passes : 4 }); } @@ -151,11 +170,10 @@ client.on('message', msg => { .then(conn => { con = conn; msg.reply('done'); - disp = conn.player.playStream(ytdl('https://www.youtube.com/watch?v=oQBiPwklN_Q', {filter : 'audioonly'}), { passes : 3 }); + disp = conn.playStream(ytdl(song, {filter:'audioonly'}), { passes : 3 }); conn.player.on('debug', console.log); conn.player.on('error', err => console.log(123, err)); - disp.on('error', err => console.log(123, err)); }) - .catch(console.log); + .catch(console.error); } }) diff --git a/test/shard.js b/test/shard.js index 8ae8633ba..6021a18c9 100644 --- a/test/shard.js +++ b/test/shard.js @@ -2,8 +2,8 @@ const Discord = require('../'); const { token } = require('./auth.json'); const client = new Discord.Client({ - shard_id: process.argv[2], - shard_count: process.argv[3], + shardId: process.argv[2], + shardCount: process.argv[3], }); client.on('message', msg => { @@ -20,7 +20,12 @@ client.on('message', msg => { process.send(123); client.on('ready', () => { - console.log('Ready'); + console.log('Ready', client.options.shardId); + if (client.options.shardId === 0) + setTimeout(() => { + console.log('kek dying'); + client.destroy(); + }, 5000); }); -client.login(token).catch(console.log); +client.login(token).catch(console.error); diff --git a/test/sharder.js b/test/sharder.js index 5a1340620..205c550a8 100644 --- a/test/sharder.js +++ b/test/sharder.js @@ -1,6 +1,6 @@ const Discord = require('../'); -const sharder = new Discord.ShardingManager(`${process.cwd()}/test/shard.js`); +const sharder = new Discord.ShardingManager(`${process.cwd()}/test/shard.js`, 5, false); sharder.on('launch', id => console.log(`launched ${id}`));