* types(ApplicationCommandData): align command data more with discord API
* types(ApplicationCommandData): clean up type definitions a bit
* types(ApplicationCommandData): fix issue where could be used with and
* types(ApplicationCommandOptionData): make subcommand option stronger
* test(ApplicationCommandOptionData): add typing tests
* Changed ApplicationCommandOptionData interface
The options type `this[]` as a self reference causes issues when implementing this interface. Changing this to ApplicationCommandOptionData[] fixes this issue
https://imgur.com/a/0eVBoJU
* fixed ApplicationCommandOption
* Update typings/index.d.ts
Co-authored-by: Noel <buechler.noel@outlook.com>
@kyranet and I found the bug when updating @skyra/editable-commands
when our custom function that accepted an argument of `MessageTarget`
was suddenly no longer accepting `message.channel`. Turns out it was
because of a mistake @kyranet made lulz
**Please describe the changes this PR makes and why it should be merged:**
CommandInteractionOptionResolver is exported in the typings, but not in the index.js file
**Status and versioning classification:**
- Code changes have been tested against the Discord API, or there are no code changes
- I know how to update typings and have done so, or typings don't need updating
* refactor(PresenceManager): have Presence extend Base and simplify add
* style(Presence): add empty line after super call
Co-authored-by: Noel <buechler.noel@outlook.com>
Co-authored-by: Noel <buechler.noel@outlook.com>
* feat(Formatters): added new URL utilities and docs
* refactor: use static class to fix docsgen error
* fix(Typings): declare members as public
* docs(Formatters): add method tags
* docs: remove empty line
Co-authored-by: SpaceEEC <spaceeec@yahoo.com>
Co-authored-by: SpaceEEC <spaceeec@yahoo.com>
* types(*): make hex color types compatible with ColorResolvable
* types(*): create HexColorString type
* types(HexColorString): move to a less awkward place
* feat(RequestHandler): emit more info when a rate limit was hit
* emit 'None' when no sublimit was hit
Co-authored-by: Antonio Román <kyradiscord@gmail.com>
Co-authored-by: Antonio Román <kyradiscord@gmail.com>
- Removed the phrase "partnered guilds" from the description of `guild.features`
**Reasoning:**
To prevent the assumption that **any** `guild.features` will be indicative of `guild.partnered`.
I just changed an incorrect key name that was introduced in Pull Request #3722. When destroying the websocket from the WebSocketShard#_send method it's using `close` as the key name instead of `closeCode`
* chore(*): streamline issue and PR templates and redirects
* chore: reword redirect to not sound apologetic
* chore: reintroduce one-liner to use discord for questions
* chore: ae consistency
* feat(GuildChannel): support conversion between text and news
* fix(Typings): add type to ChannelData
* fix(GuildChannel): use ChannelUpdate action handler to change class type
* Update src/structures/TextChannel.js
Co-authored-by: Sugden <28943913+NotSugden@users.noreply.github.com>
* fix(Typings): re-use ChannelType from GuildCreateChannelOptions
* fix(Typings): only allow text-news conversion
* fix(Typings): exclude -> pick (vlads suggestion)
* fix(Typings): pick -> exclude in two other spots
Co-authored-by: Sugden <28943913+NotSugden@users.noreply.github.com>
* feat(Typings): add 'APIRawMessage' interface
* fix(Typings): return type for WebhookFields#send()
* fix(Typings): types for APIRawMessage props
* refactor(Typings): exclude oauth props from API
* feat(Typings): add WebhookRawMessageResponse type
* refactor(Typings): use WebhookRawMessageResponse
* fix(Message): #system not all nonzero message types are system
* feat(Message): introduce system message types
* refactor(Constants): change SystemMessageTypes to be exclusionary
* fix(Constants): only need to check if type exists
Co-authored-by: Jan <66554238+Vaporox@users.noreply.github.com>
* fix(Constants): lint
* fix(Typings): add SystemMessageTypees to Constants
Co-authored-by: Jan <66554238+Vaporox@users.noreply.github.com>
* Change permission overwrite methods descriptions
The methods `GuildChannel#updateOverwrite` and `#createOverwrite` had some awkward wording in the description: `. (...)` does not look good. This PR cleans up the descriptions to be one sentence that's clearer in meaning. There's also changes to make `permission overwrite/s` consistent - some lines had `permissions overwrite/s`.
* Update src/structures/GuildChannel.js
Co-authored-by: SpaceEEC <spaceeec@yahoo.com>
* Update src/structures/GuildChannel.js
Co-authored-by: Sugden <28943913+NotSugden@users.noreply.github.com>
* Update src/structures/GuildChannel.js
Co-authored-by: Sugden <28943913+NotSugden@users.noreply.github.com>
Co-authored-by: SpaceEEC <spaceeec@yahoo.com>
Co-authored-by: Sugden <28943913+NotSugden@users.noreply.github.com>
* feat(Message): remove reply functionality
* feat(InlineReplies): add INLINE_REPLY constant/typing
* feat(InlineReplies): add Message#replyReference property
* feat(InlineReplies): add typings for sending inline replies
* feat(InlineReplies): provide support for inline-replying to messages
* feat(Message): add referencedMessage getter
* fix: check that Message#reference is defined in referencedMessage
* refactor(InlineReplies): rename property, rework Message resolution
* docs: update jsdoc for inline replies
* feat(Message): inline reply method
* fix(ApiMessage): finish renaming replyTo
* fix: jsdocs for Message#referencedMessage
Co-authored-by: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com>
* fix: restore reply typings
* fix: dont pass channel_id to API when replying
* chore: update jsdocs
* chore: more jsdoc updates
* feat(AllowedMentions): add typings for replied_user
* fix: naming conventions
* fix(Message): referenced_message is null, not undefined
* fix(MessageMentionOptions): repliedUser should be optional
* chore: get this back to the right state
* fix(ApiMessage): pass allowed_mentions when replying without content
* fix(ApiMessage): prevent mutation of client options
Co-authored-by: almostSouji <timoqueezle@gmail.com>
Co-authored-by: Tristan Guichaoua <33934311+tguichaoua@users.noreply.github.com>
This commit adds support for the `afk_channel_id`, `afk_timeout`, and
`system_channel_id` parameters in the
[create guild](https://discord.com/developers/docs/resources/guild#create-guild-json-params)
endpoint by adding the `afkChannelID`, `afkTimeout`, and
`systemChannelID` options in `GuildManager#create`.
This commit also fixes a minor bug in `create` when specifying types for
the channels due to the channel types not being changed from `'text'`,
`'voice'` etc to the corresponding numbers, so Discord would return an
error.
The docs example was incorrect, as the parameter is called `updated` but was later referenced as `guild`. This PR fixes that by changing it to `updated` to match other examples, such as `setRegion()`
* feat(DataResolver): prefer streams over buffers
* feat(DataResolver): add `resolveFileAsBuffer`
Add `resolveFileAsBuffer` to use it in `resolveImage` which still requires Buffers to work.
* fix(DataResolver): make sure `resolveFile` always returns a Promise
* refactor(DataResolver): use for-await-of
* fix(DataResolver): use forked form-data which supports custom streams
* fix(APIRequest): use forked form-data in code too
Co-authored-by: - <5144598+-@users.noreply.github.com>
Co-authored-by: SpaceEEC <spaceeec@yahoo.com>
* docs(RoleManager) : fix jsdoc everyone role can't be null
It fixes the jsdoc of RoleManager ; the everyone role of a guild can't be null
* Everyone role can't be null
* fix(typings): mark RoleManager#everyone as non-null
Co-authored-by: Crawl <icrawltogo@gmail.com>
Co-authored-by: SpaceEEC <spaceeec@yahoo.com>
* docs(MessageMentionTypes): correct type
* docs(MessageMentionTypes): change role to roles
* docs(MessageMentionOptions): correct description to allow usage as an array
* remove unneeded part of description
Co-Authored-By: Ryan Munro <rsm999@uowmail.edu.au>
* docs: add DisableMentionType to remove literal string types
Co-authored-by: Ryan Munro <rsm999@uowmail.edu.au>
* feat(Allowed Mentions): Add support for new Allowed Mentions message options
* fix(docs): Update JSDoc for feature
* fix(apimessage): translate the propery into snake_case
* fix(typings): message mention options should be optional
* fix(docs): jsdoc typings for MessageMentionOptions
* fix(mentions): use Resolvables for MessageMentionOptions
* fix(docs): typedef for MessageMentionTypes
* Update typings/index.d.ts
Co-Authored-By: Sugden <28943913+NotSugden@users.noreply.github.com>
* fix(mentions): drop support for Resolvables
* fix(AllowedMentions): remove the whole resolve function
* fix(docs): revert change to Resolvables
Co-authored-by: Sugden <28943913+NotSugden@users.noreply.github.com>
* (docs) Fixed phrasing of docs
Added permission needed to edit a member's voice state and adjusted docs to say **"Disconnect"** instead of **"Kicking"** the member.
* fixed line length on 156
* fix(GuildMemberRoleManager): type error should mention that Role or Snowflake are fine too
* fix(GuildMemberRoleManager): comma instead of 'or'
* style: break long line
* fix(MessageEmbed): Add skipValidation flag to MessageEmbed
* fix(MessageEmbed): Use skipValidation flag in Message
* fix(MessageEmbed): Restore static normalizeField(s) methods
* fix(MessageEmbed): Update typings for constructor
* fix(MessageEmbed): Remove private docstrings/typings
* fix(MessageEmbed): Use skipValidation without storing in instance
* fix(MessageEmbed): skipValidation without modifying normalizeFields
* fix(MessageEmbed): Revert indentation change in typings
* fix(MessageEmbed): Clone logic from normalizeFields (duplicated code ftw)
* revert(MessageEmbed): remove dead code / breaking change
- dead code
discord.js does not use those methods interally and won't in the future, as Discord
does not emit any partial embed updates and doing so in the future seems unlikely.
- a breaking change (an incompatible api change)
Although it's not recommended to do, users can modify
received embeds without cloning them, e.g.:
const embed = message.embeds[0].addField('some title', '');
(replace '' with some function call; this is just an example)
This would no longer throw a synchronous error (breaking change),
but at a later point when actually sending it. (poorer to debug)
Co-authored-by: SpaceEEC <spaceeec@yahoo.com>
* refactor channel types
* really weird solution to make what the PR promises possible, I might revert this
* undo the dumb attempt
* Update index.d.ts
* fix GuildCreateChannelOptions#type
* fix(typings): remove initializers from the enum
* Update index.d.ts
Co-authored-by: Crawl <icrawltogo@gmail.com>
* User input sanitation: reimplement disableEveryone into disableMentions
* Change default value of ClientOptions#disableMentions to 'none'
* Update type declarations of disableMentions to include default
* update for compliance with ESLint
* Overlooked these files. Updated for complete compliance with ESLint
* feat: add options.withPresences to fetch()
feat: update presences if present on received data
typings: add user & withPresences to FetchMembersOptions
fix: checking for added options
ref: qol changes to return type
so that all members are fetched
oopsie
* fix: use Manager.cache
* fix(typings): tslint error
Co-authored-by: Crawl <icrawltogo@gmail.com>
* cleanup(StreamDispatcher): remove old 'end' event
* fix(StreamDispatcher): only listen to finish event once
* refactor(VoiceWebSocket): use `connection.client` in favour of `connection.voiceManager.client`
* fix(VoiceWebSocket): use `client.clearInterval` in favour of `clearInterval`
* refactor: destructure EventEmitter
* refactor: destructure EventEmitter from events
* refactor: use EventEmitter.off in favour of EventEmitter.removeListener
* style: order typings alphabetically
* oops
* fix indent
* style: alphabetically organize imports
* style: remove extra line
* Revert "style: remove extra line"
This reverts commit 96e182ed69.
* Revert "style: alphabetically organize imports"
This reverts commit 02aee9b06d.
* Revert "refactor: destructure EventEmitter from events"
This reverts commit 9953b4d267.
* Revert "refactor: destructure EventEmitter"
This reverts commit 930d7751ab.
* Revert "fix(StreamDispatcher): only listen to finish event once"
This reverts commit 485a6430a8.
* refactor: use .removeListener instead of .off
* add ClientOptions#disableMentions and MessageOptions#disableMentions
* provide tests
* don't sanitize controlled mentions
* add @here mentions to tests
* fix indents (6 spaces instead of 8)
* add Util#cleanContent tests
* add typings for removeMentions
* replace @ with @\u200b AFTER cleaning content as suggested instead of using removeMentions
* better explanation of this option
* no newline in Util.removeMentions
* fix long line
* remove double space
* remove comments (change has been reverted)
* Use Util.removeMentions to remove mentions
* use Util.removeMentions in Util.cleanContent
* Add GuildEmoji to GuildResolvable
* Add GuildEmoji to GuildResolvable
* Add Invite to GuildResolvable
* Add Invite to GuildResolvable
* oops
* oops x2
* Add Guild#fetchBan and an error for not resolving the ID
* typings
* Revert "Add Guild#fetchBan and an error for not resolving the ID"
This reverts commit a4d0ed16e7.
* Revert "typings"
This reverts commit 5a54e88785.
* fix jsdoc
* add trailing comma
* feat/fix(GuildAuditLogs): handle new event types
* fix(GuildAuditLogsEntry): coerce to numbers, simplify extra for deleted entities
* fix(GuildAuditLogsEntry): do not revert 'type' extra
* typings(MessageEmebd): fix typings for addFields
* fix: add missing semicolon
* docs(MessageEmbed): fix various types
* in accordance with the scope of the PR
* Update src/structures/MessageEmbed.js
Co-Authored-By: SpaceEEC <spaceeec@yahoo.com>
Co-authored-by: SpaceEEC <spaceeec@yahoo.com>
- Change GuildEditData#systemChannelFlags to use SystemChannelFlagsResolvable
- Move SystemChannelFlagsResolvable outside of class definition to make the docs generator happy
* feat: splice multiple fields
* remove MessageEmbed#spliceField
* add MessageEmbed#spliceFields
* to behave more like Array#splice
* and allow multiple fields to be replaced/inserted
* update typings accordingly
* refactor: rename check to normalize
* check suggests boolean return type
* feat: allow spread args or array as field input
* rewrite: replace addField in favor of addFields
* typings: account for changes
* chore: bump min node to 11.0.0
* for Array#flat
* fix: bump min-node in package engines field
* remove addBlankField
* update message after fetching if it is partial
* suggested changes
Co-Authored-By: SpaceEEC <spaceeec@yahoo.com>
Co-authored-by: SpaceEEC <spaceeec@yahoo.com>
* docs: Clarify what zlib-sync does
* docs: Update docs site welcome
* src/docs: Remove `ws.compress` from docs
This is a deprecated parameter and you shouldn't use it unless you have zlib-sync installed, and even then, compression is automatically enabled
* docs: Apply suggestion
Co-Authored-By: Sugden <28943913+NotSugden@users.noreply.github.com>
Co-authored-by: Sugden <28943913+NotSugden@users.noreply.github.com>
* BaseManager#valueOf should return cache
* Update Util#flatten to handle valueOf being a Collection
* Update Util.js - typo
Co-Authored-By: Amish Shah <amishshah.2k@gmail.com>
Co-authored-by: Amish Shah <amishshah.2k@gmail.com>
* Initial commit: add 5 initial managers
- Base manager
- GuildChannelManager
- MessageManager
- PresenceManager
- Reaction Manager
- Added LimitedCollection
* Add GuildEmojiManager, various fixes
* Modify some managers and add guildmembermanager
* Initial integration
* Delete old stores
* Integration part two, removed LRUCollection
- Most of the integration has been finished
- TODO typings
- Removed LRUCollection, needless sweeping
* Typings + stuff i somehow missed in ChannelManager
* LimitedCollection typings/ final changes
* Various jsdoc and syntactical fixes, Removed Util.mixin()
* tslint fix
* Grammatical and logical changes
* Delete temporary file placed by mistake
* Grammatical changes
* Add missing type
* Update jsdoc examples
* fix: ChannelManager#remove should call cache#delete not cache#remove
* fix recursive require
* Fix missed cache in util
* fix: more missed cache
* Remove accidental _fetchMany change from #3645
* fix: use .cache.delete() over .remove()
* fix: missing cache in ReactionCollector
* fix: missed cache in client
* fix: members is a collection not a manager
Co-Authored-By: Sugden <28943913+NotSugden@users.noreply.github.com>
* fix: various docs and cache fixes
* fix: missed cache
* fix: missing _roles
* Final testing and debugging
* LimitedCollection: return the Collection instead of undefined on .set
* Add cache to BaseManager in typings
* Commit fixes i forgot to stage yesterday
* Update invite events
* Account for new commit
* fix: MessageReactionRemoveAll should call .cache.clear()
* fix: add .cache at various places, correct return type
* docs: remove mentions of 'store'
* Add extra documented properties to typings
Co-authored-by: Sugden <28943913+NotSugden@users.noreply.github.com>
Co-authored-by: SpaceEEC <spaceeec@yahoo.com>
* src: Fix up WebSocketShard errors
* typings: Forgot to update
* src: Forgot debug variable
* src: Fix issue Bella found
If the WS was not connected when the HELLO timeout passes
(CONNECTING, etc), the shard would get stuck
due to never rejecting the WebSocketShard#connect
Promise with the DESTROYED event
* fix(Voice*): synthesize speaking event from UDP packets
* fix(VoiceReceiver): skip over undocumented Discord byte
See #3555
* fix(VoiceConnection): play frame silence before emitting ready
* typings: account for changes in private api
* Add support for MessageReaction#remove and MESSAGE_REACTION_REMOVE_EMOJI
* Remove reaction from cache
Co-Authored-By: matthewfripp <50251454+matthewfripp@users.noreply.github.com>
* fix: message may be partial
* Clarify what the event entails
* Document client in MessageReaction
Co-Authored-By: SpaceEEC <spaceeec@yahoo.com>
* await the REST call
* Add MessageReaction#remove to typings
Co-authored-by: matthewfripp <50251454+matthewfripp@users.noreply.github.com>
Co-authored-by: SpaceEEC <spaceeec@yahoo.com>
* Update package.json
* Change Version String after amishshah's suggestion
Co-Authored-By: Amish Shah <amishshah.2k@gmail.com>
Co-authored-by: Amish Shah <amishshah.2k@gmail.com>
* Add support for new Invite events
* Merge typings for events
Co-Authored-By: Sugden <leoaustin675@gmail.com>
* Add warning about requiring permissions
* Null check channel and guild
* fix: .guilds not .channels
* Mark topic as nullable for TextChannel
* Backport separate NewsChannel typings
* Ensure NewsChannel#rateLimitPerUser is undefined
* Revert rateLimitPerUser, considered breaking
* Add rateLimitPerUser back to typings
* Linting
* Revert NewsChannel extends TextBasedChannel
* docs(MessageMentions): channels are actually in order
* docs(MessageMentions): readd info about order for channels
* docs(MessageMentions): reword info to account for rtl locales
* Convert message#member to a getter
* Try to cache members from data in message payloads
* Cache mentioned members
* Revert Message#member getter - breaking change
* Revise member caching
* Revise member mention caching
* Pass member to _addMember correctly
* Use message.guild instead of this.guild
Co-Authored-By: SpaceEEC <spaceeec@yahoo.com>
* Merge if's onto one line
* fix(Message): use this.author.id to check cache
Discord does not send an id in the member data here
* chore(Message): reindent equals
Co-authored-by: SpaceEEC <spaceeec@yahoo.com>
* Add internal support for @discordjs/opus
* Remove redundant try/catch
* fix: use setBitrate method in @discordjs/opus
* chore: tidy up opus imports
* fix: correct imports for DiscordJsOpusEngine
* chore: update docs to prefer @discordjs/opus
* chore: bump prism-media to 0.0.4 to allow ffmpeg-static
* feat(Presence): add support for multiple activites
* typings(Presence): fix spelling of 'activities'
Co-Authored-By: Amish Shah <amishshah.2k@gmail.com>
Co-authored-by: Amish Shah <amishshah.2k@gmail.com>
* src: Cleanup event listeners on WebSocket connections
Should prevent #3641 from happening, as well as double connections on a shard
* typings: Forgot to add the method
* types(VoiceBroadcast): add subscribers property
* types(VoiceBroadcast): change player property to private
Co-Authored-By: Amish Shah <amishshah.2k@gmail.com>
Co-authored-by: Amish Shah <amishshah.2k@gmail.com>
* fix(BitField): remove for..in in favor of Object.keys
* refactor: do not re-resolve bits
Co-Authored-By: bdistin <bdistin@gmail.com>
Co-authored-by: bdistin <bdistin@gmail.com>
* Create config.yml
Instead of making an entire new page with just text talking about the discord server (which they could ignore, as most people don't read), just link people directly to the discord server
* Delete question---general-support-request.md
* feat: Widen GuildResolvable to include GuildChannel and GuildMember
* docs: Documented the new overloads
Co-Authored-By: Gryffon Bellish <owenbellish@gmail.com>
Co-authored-by: Gryffon Bellish <owenbellish@gmail.com>
* src: Step 1 of who knows how many
* src: Remove accidentally committed test file
* src: Remove useless added property in package.json
* docs: Trailing spaces, come back >.>
* src: Buhbye uws, we will miss you..not!
* src: Move 'auto' shard selection from totalShardCount to shards
* src: tweak
* src: Filter out floats from shard IDs
You want half of a shard or what?
* src: Misc cleanup and bugfix for GUILD_BAN_ADD
* src: Rewrite checkReady
* src: Misse this while merging master into my branch
* typings: Bring these up to date
* typings: Forgot allReady event
* src: Don't checkReady if the shard isn't waiting for guilds
* src: Fix a possible bug for when the ws dies and the session becomes -1
* src: Hopefully fix last edge case that could case a shard to infinitely boot loop
* src: Rename totalShardCount to shardCount
* src: Small bugfix
* src: Correct error message for shardCount being imvalid
Co-Authored-By: bdistin <bdistin@gmail.com>
* src: Small tweaks
* src: If this doesn't fix the issues I'm gonna throw a brick at my PC
* src: I swear, STOP BREAKING
* src: *groans at a certain snake*
* src: Use undefined instead of null on destroy in close event
Setting it to null sets the close code to null, which causes a WebSocket error to be thrown. The error is thrown from WebSocket, although there is no connection alive. Fun times!
* src: @SpaceEEC's requested changes
* src: Remove zucc from discord.js
Discord is removing support for it, sooo... Bye bye
* src: Missed this
* src: Apply @kyranet's suggestions
Co-Authored-By: Antonio Román <kyradiscord@gmail.com>
* src: @kyranet's suggestions
* src: Remove pako, update debug messages
- Pako is officially gone from both enviroments
Install zlib-sync on node.js if you want it
- Improve a few debug messages some more
- Discover that internal sharding works in browsers but please don't do that
* Start/Stop speaking using incomming UDP packets
* Fix ESLint errors
* Updates for styling consistency
Co-Authored-By: Gryffon Bellish <owenbellish@gmail.com>
* Minor improvements
* Acutally use previousTimeout
* Use BaseClient setTimeout and refresh()
* Update README to match node version for refresh()
* Update comment to match startSpeaking
* Correctly report Priority bit
* Fix ESlint errors
* Added Store and NewsChannel to exports
Added the StoreChannel and NewsChannel structures to the module exports.
* keeping the list in alphabetical order
I moved the StoreChannel and NewsChannel exports that I added in the last commit in their right position to keep things alphabetized.
* adds more audit-log entries
this adds additional audit-log types from https://discordapp/discord-api-docs/pull/1191
* typings for new audit-log entries
* typings for new audit-log entries
* fix action numbers
* test
* test 2
* update
* update
* replaced double quotes
* Made message.guild and message.member nullable
* replaced double quotes again (oops)
* missing semicolons
* removed fetch from Omit
* Added Partialize generic type
* Created interfaces (prettier intellisense)
* joinedAt/joinedTimestamp are nullable and fixed conflict
* src: Update channel pattern
* src: Remove useless non-capture group
* src: it's as though we're starting fresh
* src: Bring this up to date for reals now
* src: typings and a bug fix
* src: Add crossposted channels to message mentions
* src: Requested changes and add typings
* src: Move Object.keys outside loop
* typings: Fix enum being exported when it shouldn't
* src: Consistency with roles and users
* docs: Correct docstring for MessageFlags#flags
* docs: Correct docstring for MessageMentions#crosspostedChannels
* docs: Suggestions
Co-authored-by: SpaceEEC
* src: Reset flags to 0 if no flags are received on MESSAGE_UPDATE
* Use external collection package
* Complete typings
* Document properly base collection class
* Add clone since sort is now in-place
* Update for latest changes to package
* Fix whitespace
* Update docs link
* Oops
* Update Collection.js
* Update index.d.ts
* add Util.parseVerification()
* Made the code much cleaner.
* Removed method and created constant.
* Lint!
* refactor(constants): capitalize VerficiationLevels and add a typedef
* Changed VerificationLevels typedef to singular.
Co-Authored-By: Will Nelson <will@wnelson.xyz>
* Add new method Permissions#any
* Update src/util/BitField.js
This is much better
Co-Authored-By: bdistin <bdistin@gmail.com>
* Remove unreachable code
* Gotta keep the linter happy
* Apply bdistin suggested change to both methods
* fix(typings): DataStore#resolve & DataStore#resolveID can also return null.
* fix(typings): DataStore#remove returns a boolean, not void.
Co-Authored-By: izexi <43889168+izexi@users.noreply.github.com>
* added DARK_MODE_INVISIBLE
added another constant color that makes embeds appear invisible on DARK mode.
* travis likes trailing commas
* fix: ref issue: #3414
* fix: removed a random color
* Small changes to parseEmoji regex
I just made a small change to the parseEmoji regex, this change will make an invalid emoji, like `<aname:id>` return as null, before this change it would return as an animated emoji because the name started with an `a` which would result in false positives, then the `?` I added to the end of `(\d{17,19})?` is used if someone provided an emoji as `:name:` or `a:name:` it will return the correct values but have an invalid id.
* Update Util.js
2nd Update: I changed the regex to output the results if you provide `<aemoji:123456789012345678>` and <:aemoji:123456789012345678>` which will output `{ animated: false, name: "aemoji", id: "123456789012345678" }` or `<:emojiname:>` which outputs `{ animated: false, name: "emojiname", id: null }` or `<a:emoji:>` which would output `{ animated: true, name: "emoji", id: null }`. Before this PR the method would return that the emoji was animated if you provided something like `<anemojiname:emoji_id>` because the name started with an `a`.
* Making Util.splitMessage always return an array
Util.splitMessage sometimes returns an array, but other times it returns a string. This should make it so that it always returns an array.
* jsdoc
Co-Authored-By: TNThacker2015 <37024464+TNThacker2015@users.noreply.github.com>
* docs(Util): remove superfluous space in docstring
* wip refactor
* add escapeMarkdown tests
* italics can be done with a single underscore too
* more refined
* fix test name
* unnecessary eslint ignores
* use jest
* make eslint less annoying in this test file
* more testing
* fix lib usage
* more tests and a small fix
* Implement idle feature
* Add typings
* Minimal fixes
* Make everything in Collector and not attached to ReactionCollector
* set this._idletimeout to null when collector ends
* also set this._timeout to null when collector ends
* feat(Teams): backport support for teams
PR #3350
Commit: a22aabf6a8
* fix(TeamMember): fix name of client property
* refactor(OAuth2Application): make team nullable instead of optional
* typings(OAuth2Application): make team nullable instable of optional
* docs(OAuth2Application): deprecate and add an info to team property
* basic teams support
* export Team & TeamMember
* use typedef
* typings and some fixes
* Update src/structures/TeamMember.js
Co-Authored-By: Vlad Frangu <kingdgrizzle@gmail.com>
* fix Team#iconURL()
* fix typings and a bug
* fix states start at 1
* team icon hash can be null
* fix owner typings
* backport documentation for Presence
* capitalize o
Co-Authored-By: SpaceEEC <spaceeec@yahoo.com>
* remove extra space
* backport ClientPresenceStatus
* Change to Client Presence Status
* Update TextChannel.js
Update `setRateLimitPerUser` description to specify the `number` is in seconds, per the Discord docs
* Update TextChannel.js
Add unit to the rateLimitPerUser property
* Update GuildChannel.js
* Update StreamDispatcher.js
Specify unit for `StreamDispatcher.pausedTime`
* Update TextChannel.js
Update `setRateLimitPerUser` description to specify the `number` is in seconds, per the Discord docs
* Update TextChannel.js
Add unit to the rateLimitPerUser property
* Update GuildChannel.js
* Update TextChannel.js
Update `setRateLimitPerUser` description to specify the `number` is in seconds, per the Discord docs
* Update TextChannel.js
Add unit to the rateLimitPerUser property
* Update GuildChannel.js
* Disambiguate the description of <client>.channels
Although not explicitly said, the current wording makes it seem like all channels are cached and available at any time in this store. Hopefully this variation makes it a bit clearer.
* make more explicit (I think)
* remove trailing white spaces
* feat(voice): kick members from voice channels
* fix(VoiceState): improve stability in checking for client user
* feat(VoiceState): add setChannel for moving/kicking members
* update typings
* remove duplicated methods across GuildMember and VoiceState
member.setDeaf => member.voice.setDeaf
member.setMute => member.voice.setMute
member.setVoiceChannel => member.voice.setChannel
* src: Implement store and news channels!
* src: Remove code dupe
* src: Add missing guild properties
* docs: Add a small notice that the channel type may also change
* src: Remove re-creation of the MessageStore
* lint: Unused Import
* src: Requested changes for StoreChannels
* typings: Fix typings
* src: Moar guild updates
* src: Set maximumPresence to the data prop, the already existent one, or default to 5000
* typings: afkChannel is a VC
I keep confusing them, ffs
Co-Authored-By: vladfrangu <kingdgrizzle@gmail.com>
* docs: Document that maximumMembers and maximumPresences may be inaccurate before fetching
* src Appels requested changes
* add a public alternative to the private raw event
while retaining raw for use in debugging privately
* only emit dispatch packets
* requested changes
TIL, that's neat
* fix padding
* requested changes
* Update WebSocketManager.js
* Update welcome.md
Update node version requirement, npm install links, docs links, made a note that the guide is for stable and added a new link to the WIP update guide.
* docs(welcome.md): put notice for wip update guild on its own line
* docs(welcome.md): indent own line
* docs(README.md): apply the same changes here
* docs: document constructors of extendible structures
* docs(ClientPresence): document default value for data parameter
Co-Authored-By: SpaceEEC <spaceeec@yahoo.com>
* docs(Presence): document default value for data parameter
Co-Authored-By: SpaceEEC <spaceeec@yahoo.com>
* docs(DMChannel): capitalize DM in the constructor doc
* fix end method in VoiceBroadcast
this.client is a ClientVoiceManager and thus its this.client.broadcasts instead of this.client.voice.broascasts
* revert the voicebroadcast and pass this.client at clientvoice
* passed this.client
* docs: make voice public
* typings: Update typings to match the docs
* typings: ClientVoiceManager is nullable in Client
Co-Authored-By: vladfrangu <kingdgrizzle@gmail.com>
* typings: Mark client as readonly
Co-Authored-By: vladfrangu <kingdgrizzle@gmail.com>
* src: Make the client readonly
* src: Remove Client#voiceConnections getter in favor of ClientVoiceManager#connections
* src: WIP Internal Sharding refactor
* src: Refactor unavailable guild check
Co-Authored-By: kyranet <kyradiscord@gmail.com>
* src: More WIP Code
F in the chat to the old manager
* src: It should work but Discord says no.
Seriously why is this not working!
* fix: Inflator causing issues
* src: Finishing touches and typings
* misc: Proper debug message
* fix: Making things hidden needs writable: true as well
* fix: Sharding allowing multiple of the same shard, negative shards or strings
* fix: Again... edge cases
I love you guys .w.
* misc: Touchups
* misc: Better error?
* docs: Typo
* typings: Requested changes
* src: Requested changes
* src: Fix issues, validate provided shard options and more
* src: Forgot to remove the listener
* lint: eslint complaining
* fix: Setting shardCount to auto crashing the process
* misc: Requested changes
* typings: Correct typings for shardCount client option
* typings: Add invalidSession event to the shard and correct typings
* src: Minor docs adjustements, and code consistency between setHelloTimeout and setHeartbeatTimeout
* src: Don't block reconnect while creating shards
Might fix silent disconnects *again*
* src: Prevent reconnect from running if the Manager isn't READY
That way, if a shard dies while we're still spawning, it won't cause issues
* fix: Retry to reconnect if there's a network error going on.
The manager *should* keep reconnecting unless the token is invalid
* src: Enhance onClose handler for shards in the manager
- If the close code is between 1000 and 2000 (inclusive), you cannot resume
I tested this locally
- If there's a session ID still present, immediately try to resume
Faster resumes :papaBless:
Otherwise, the invalid session event will trigger and it'll handle accordingly
I swear if I see a SINGULAR Silent DC I'm yeeting
* src: Fix error check
* src: Make sure message exists on the error
* src: Used the wrong property for the shardQueue
* src: Make the hello timeout be made by the client
god help
* docs: Correct docs for WSEvents
* misc: Remove old events from the Events constant
* src: Throw the HTTP error if we don't get a 401
* typings: Can't forget about them
* src: Implement some more fail safes just in case
Seriously, better safe than sorry! Gotta failproof it completely
* edit shouldn't remove content
If undefined is passed to the api, content isn't removed in such a case where you are only editing the embed.
* fix a related doc string
* update typings
* requested changes
* Remove GroupDMChannels
they sparked no joy
* Start partials for message deletion
* MessageUpdate partials
* Add partials as an opt-in client option
* Add fetch() to Message
* Message.author should never be undefined
* Fix channels being the wrong type
* Allow fetching channels
* Refactor and add reaction add partials
* Reaction remove partials
* Check for emoji first
* fix message fetching
janky
* User partials in audit logs
* refactor overwrite code
* guild member partials
* partials as a whitelist
* document GuildMember#fetch
* fix: check whether a structure is a partial, not whether cache is true
* typings: Updated for latest commit (#3075)
* partials: fix messageUpdate behaviour (now "old" message can be partial)
* partials: add warnings and docs
* partials: add partials to index.yml
* partials: tighten "partial" definitions
* partials: fix embed-only messages counting as partials
* chore(deps): Updated all required, peer, and development dependencies
And engines.node to require 10
* chore(peerDeps): Updated uws to 11.149.1
Clarified my doubts with iCrawl
* fix: Sharding bugs, silent disconnects and cleanup code
* typings
* fix: Destroy connecting with close code different from 1000
Per `If a client does not receive a heartbeat ack between its attempts at sending heartbeats, it should immediately terminate the connection with a non-1000 close code, reconnect, and attempt to resume.`
* misc: Wait x ms before reconnecting
Per https://discordapp.com/developers/docs/topics/gateway#resuming
* docs
* nit: docs
* misc: Prevent multiple calls to WebSocketManager#destroy
* fix: Implement destroying if you reset the token
* misc: Clear the WS packet queue on WebSocketShard#destroy
You can't send those packets anywhere anymore, so no point in keeping them
* fix: Handle session limits when reconnecting a full shard, cleanup
* misc: No need to create a new shard instance
* fix: closeSequence being null, thus emitting null on Client#resumed
* misc: Remove GUILD_SYNC Gateway handler and add missing dot to string
* misc: Close WS with code 4000 if we didn't get a heartbeat in time
As said in the Discord API server
* fix: Handle ready emitting in onPacket
Doesn't allow broken packets
* misc: Close the connection if Discord asks for a reconnect
Prevents double triggers
* testing: Prevent multiple reconnect attempts on a shard
Should fix some issues some people have had.
* fix: Prevent multiple reconnect calls on the shard, re-use conn to identify, remove reconnect function
Note: Closing the WS with 1000 makes the session invalid
* misc: Forgot to remove 2 unneeded setters
* docs: Wrong param docstring for WebSocketShard#destroy
* misc: Set status to reconnecting after destroying
* misc: Close connection with code 1000 on session invalidated
Allows us to cleanup the shard and do a full reconnect
Also remove identify wait delay, not used anywhere
* fix: Fix zlib crash on node
And with that, the PR is done!
* misc: Implement a reconnect queue
And that is all there was to be done in this PR.
Shards now queue up for a reconnect
* nit: Debug the queue after destroying
* docs: Make the invalidated event clearer
* lint: I'm good at my job
* docs
* docs: Make description for isReconnectingShards accurate
*can I stop finding issues, this PR is meant to be done*
* misc: Remove shard from bind params
* misc: Code re-ordering and cleanup
Resumes do not need to be queued up, as they do not count to the identify limit, and after some testing, they don't have the 5 second delay required, like in identify
* fix: Issues with token regeneration and shards not properly handling them
We close the ws connection with code 1000 if we get an invalid session payload,
that way we can queue the reconnects and handle any issues
* misc: Remove useless delays on session invalidated
They get handled by the rest of the code already
* lint
* misc: reset the sequence on Shard#destroy
This especially is a problem if you need to re-identify, as the sequence doesn't get set to the current one,
causing the sequence to be wrong
* fix: GitHub rebase and minor tweak
* Implement a 15 second timeout if shards don't connect till then
Should prevent shards that never reconnect
* revert: Make WebSocketShard#send and WebSocketManager#broadcast public
* typings: Set type to void instead of undefined
* docs: Requested Changes
- Fixed a bug where `GuildMemberRoleStore#{add,remove}` would create a rejected promise inside a promise, instead of rejecting the first one.
- Fixed a bug where `GuildMember#edit` with a specified unknown channel would throw synchronously, instead of rejecting asynchronously.
* feat({Role,Channel}Store): fetch method
* docs: Add usage examples to the new methods
* misc: Add note of why we are fetching all roles even for a single one
This PR attempts to fix the reported resumed event count in the debug output (where it is always displayed only as 1 event replayed) and in the emitted `resumed` event, where it passed the current sequence instead of passing the actual replayed event count (which was an utopic high number for smaller bots on resume).
* fix(Util): throw an explicit error if a chunk exceeds the max length
* refactor(Util): consolidate both errors in splitMessage into one
* revert(Messages): do not unnecessarily change the error code
* revert(Messages): do not remove the word 'the'
* Add explicit error to setting invalid voice channel
* restrict to guild
Co-Authored-By: Darqam <anhim2@gmail.com>
* add a more explicit error and channel type check
* bad tab
* fix: Sharding causing constant heartbeat / identify spam
* misc: Remove wait param in connect
* misc: Wait 2.5 seconds before sending identify again if session is resumable
* misc: Remove useless destroy call
* nit: Capitalization
* fix: Identify on HELLO not connectionOpen
* misc: Add different intervals for identify after invalid session
- 2500 if we couldn't resume in time
- 5000 if we didn't have a session ID (per the docs on identify, that a client can only connect every 5 seconds)
- Otherwise, just identify again
* misc: Only clear heartbeat if shard is fully dead
Reconnect clears it otherwise
* fix: Accessing .length on a Collection
* internal sharding
* ready event
* the square deal
* the new deal
* the second new deal
* add actual documentation
* the new freedom
* the great society
* federal intervention
* some of requested changes
* i ran out of things to call these
* destroy this
* fix: Client#uptime went missing
* fix(Client): destroy the client on login failure
This may happen duo invalid sharding config / invalid token / user requested destroy
* fix(Client): reject login promise when the client is destroyed before ready
* fix(WebSocketManager): remove redundancy in destroy method (#2491)
* typo(ErrorMessages): duo -> duo to
* typo(ErrorMessages): duo -> due
* fix: docs and options
* docs(WebSocketManager): WebSockethard -> WebSocketShard (#2502)
* fix(ClientUser): lazily load to account for extended user structure (#2501)
* docs(WebSocketShard): document class to make it visible in documentation (#2504)
* fix: WebSocketShard#reconnect
* fix: presenceUpdate & userUpdate
* presenceUpdate wasn't really being handled at all
* userUpdate handled incorrectly because as of v7 in the Discord API, it comes inside presenceUpdate
* re-add raw event
* member is now part of message create payload
* feat: Add functionality to support multiple servers with different shards (#2395)
* Added functionallity to spawn multiple sharding managers due to adding start and end shards
* Small fixes and limiting shard amount to max recommended
* Forgot a check in spawn()
* Fixed indentation
* Removed optiosn object documentation for totalShards
* More fixes and a check that the startShard + amount doesnt go over the recommended shard amount
* fix getting max recommended
* Removed async from constructor (my fault)
* Changed start and end shard to a shardList or "auto" + fixed some brainfarts with isNaN
* Changed the loop and totalShard count calculation
* shards are actually 0 based
* Fixed a problem with the gateway and handled some range errors and type errors
* Changed Number.isNan to isNaN and changed a few Integer checks to use Number.isInteger
* Added check if shardList contains smth greater than totalShards; made spawn use totalShards again; shardList will be ignored and rebuild if totalShards is 'auto'; fixed docs
* ShardingManager#spawn now uses a for..of loop; fixed the if statement inside the new for..of loop to still work as intended; made the totalShards be set to a new amount if smth manual is put into ShardingManager#spawn just like before; Fixed some spelling
* internal sharding
* ready event
* the square deal
* the new deal
* the second new deal
* add actual documentation
* the new freedom
* the great society
* federal intervention
* some of requested changes
* i ran out of things to call these
* destroy this
* fix: Client#uptime went missing
* fix(Client): destroy the client on login failure
This may happen duo invalid sharding config / invalid token / user requested destroy
* fix(Client): reject login promise when the client is destroyed before ready
* fix(WebSocketManager): remove redundancy in destroy method (#2491)
* typo(ErrorMessages): duo -> duo to
* typo(ErrorMessages): duo -> due
* fix: docs and options
* docs(WebSocketManager): WebSockethard -> WebSocketShard (#2502)
* fix(ClientUser): lazily load to account for extended user structure (#2501)
* docs(WebSocketShard): document class to make it visible in documentation (#2504)
* fix: WebSocketShard#reconnect
* fix: presenceUpdate & userUpdate
* presenceUpdate wasn't really being handled at all
* userUpdate handled incorrectly because as of v7 in the Discord API, it comes inside presenceUpdate
* Internal Sharding adaptation
Adapted to internal sharding
Fixed a bug where non ready invalidated sessions wouldnt respawn
* Fixed shardCount not retrieving
* Fixing style
removed unnecessary parenthesis
* Fixing and rebasing
lets hope i didnt dun hecklered it
* Fixing my own retardation
* Thanks git rebase
* fix: assigning member in message create payload
* fix: resumes
* fix: IS wont give up reconnecting now
* docs: add missing docs mostly
* fix: found lost methods
* fix: WebSocketManager#broadcast check if shard exists
* fix: ShardClientUtil#id returning undefined
* feat: handle new session rate limits (#2796)
* feat: handle new session rate limits
* i have no idea what i was doing last night
* fix if statement weirdness
* fix: re-add presence parsing from ClientOptions (#2893)
* resolve conflicts
* typings: missing typings
* re-add missing linter rule
* fix: replacing ClientUser wrongly
* address unecessary performance waste
* docs: missing disconnect event
* fix(typings): Fix 2 issues with typings (#2909)
* (Typings) Update typings to reflect current ClientOptions
* fix(Typings) fixes a bug with Websockets and DOM Types
* fix travis
* feat: allow setting presence per shard
* add WebSocketManager#shardX events
* adjust typings, docs and performance issues
* readjust shard events, now provide shardId parameter instead
* fix: ready event should check shardCount, not actualShardCount
* fix: re-add replayed parameter of Client#resume
* fix(Sharding): fixes several things in Internal Sharding (#2914)
* fix(Sharding) fixes several things in Internal Sharding
* add default value for shards property
* better implement checking for shards array
* fix travis & some casing
* split shard count into 2 words
* update to latest Internal Sharding, fix requested changes
* make sure totalShardCount is a number
* fix comment
* fix small typo
* dynamically set totalShardCount if either shards or shardCount is provided
* consistency: rename shardID to shardId
* remove Client#shardIds
* fix: typo in GuildIntegrationsUpdate handler
* fix: incorrect packet data being passed in some events (#2919)
* fix: edgecase of ShardingManager and totalShardCount (#2918)
* fix: Client#userUpdate being passed wrong parameter
and fix a potential edgecase of returning null in ClientUser#edit from this event
* fix consistency and typings issues
* consistency: shardId instances renamed to shardID
* typings: fix typings regarding WebSocket
* style(.eslintrc): remove additional whitespace
* fix(Client): remove ondisconnect handler on timeout
* docs(BaseClient): fix typo of Immediate
* nitpick: typings, private fields and methods
* typo: improve grammar a bit
* fix: error assigning client in WebSocketManager
* typo: actually spell milliseconds properly
* Add worker-based sharding mode to ShardingManager
* Fix ClientShardUtil mode
* Fix worker not being cleared on shard death
* Update docs and typings
* Clean up Client sharding logic a bit
* Add info about requirements for worker mode
* feat: Add TextChannel#rateLimitPerUser
Rename parameter in TextChannel#setRateLimitPerUser
feat: Add `rateLimitPerUser` param to ChannelData
fix: eslint
* docs: Updated typings
* fix: Requested changes
* fix: rateLimitPerUser being undefined when 0
When `rate_limit_per_user` is 0, the gateway does not send it (but REST does). When this is set to a non-zero number, this property starts to exist. Otherwise this will be `0`. Adding `|| 0` should do the trick changing `undefined` to `0`.
* fix: eslint
* wip: comprehensive permissionOverwrites refactor
* PermissionOverwrites.resolve should Promise.reject()
where a promise is the expected return value
* On second thought, async rewrite to automatically reject on throw
* Fix some docs
* Fix a bug
* fix 2 more bugs
* typings: Updated for latest commit
* typings: Add missing method in GuildChannel
* typings: Add missing `| null` in PermissionOverwriteOption type
* Suggested changes
* feat: add ClientOptions#retryLimit
* hydra needs to learn how to code right
* a default would probably help
* move incrementor & update comment
* clarify docs on Infinity
* fix: better global ratelimit handling in RequestHandler
fix: Remove useless line
fix: Better global ratelimit management
* refactor: Changed RESTManager#globallyRateLimited to be a getter
* refactor: Remove RESTManager#globallyRateLimited getter
* docs: Updated comments to reflect latest changes
* Docs: merge PermissionOverwriteOptions and OverwriteData
* fix user-member and replace eslint-disable with linebreaks
* consistency fix
* Fix: remove empty line between jsdocs and method
* Fix: allowed/denied to allow/deny to conform with recent master changes
* refactor: clean up rate limit handling
* requested changes
* remove request mode option
* fix dupe requests
* hardcode reaction ratelimits
* suggested changes
* fix small thing
* re-add restTimeOffset
* move restTimeOffset a bit
* i swear i know english its my native language ok
* requested changes
* fix: a bit *too* pre-emptive with ratelimits, now less so
* fix: dapi error shoudl reject with path
* fix: make errors in execute catchable
* fix promise return
* rebase is hard
* misc: Update ClientApplication for the current API
* cleanup: ClientApplication#fetchAssets, removed createAsset
* Major cleanup time
* Merge to kyra's branch
* docs: Updated typings
* fix: re-add ClientApplication#{cover,coverImage()}
* typings(ClientApplication): move coverImage declaration up
* Rework createMessage
- MessageAttachment is now structurally similar to FileOptions
- No longer mutates the object passed as options
- Supports more permutations of arguments
* Ignore complexity warning
* Refactor name finding
* Fix typo
* Update typings
* Default name to null for MessageAttachment
* Make Message#reply use transformOptions
* Move transformOptions
* Fix Message#reply
* Fix mutation
* Update tests
* Fix options passing
* Refactor into APIMessage
* Fix webhook send
* Expose APIMessage
* Add documentation
* Add types
* Fix type doc
* Fix another type doc
* Fix another another type doc (is this one even right!?)
* Remove trailing comma
* Properly clone split options
* Add support for sending file as stream
* Missed a doc
* Resolve files only once when splitting messages
* This looks nicer
* Assign directly
* Don't cache data and files
* Missing return type
* Use object spread instead Object.assign
* Document constructors
* Crawl is a little dot
* comp pls
* tests: sanitize local file path, disable no-await-in-loop
* abstract BitField from Permissions
* reduce useless code, improve docs
* add a ReadOnly identifier to the return type of Bitfield#freeze()
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#partial-readonly-record-and-pick
* fix the RangeError
* update docs, convert Speaking and ActivityFlags to bitfields
* fix some docs
* Fix Speaking BitField oops
* docs for oops
* more incorrect docs
* Fix incorrectly named property
* add new classes to index
* fix missing @extends docs
* default bitfield resolve to 0, and cleanup defaulting everywhere
Also removes GuildMember#missiongPermissions() alias that had incorrect behavior
* Breaking: Rename Overwrite allowed and denied to allow and deny
To be consistent with the api's naming
* fix setSpeaking usage to bitfields instead of booleans
* fix speaking bug in playChunk
* docs: Updated typings
* fix: BitFieldResolvable should use RecursiveArray
* bugfix/requested change
* typings: Cleanup (#2)
* typings: Fix BitField#{toArray,@@iterator} output type
* typings: correct PermissionOverwrites property names and nitpicks
* src: Handle WEBHOOK_UPDATE events
* Commit rename of 77'
Or adding the letter S
* I missed this
* Properly do this now
Typos everywhere
* Typings
* refactor: remove now unnecessary guild variable
* Error for guild.fetchVanityURL feature not enabled
* added GET/guilds/{guild.id}/vanity-url endpoint
* fix: code conventions
* adopted suggestion
* Changed error message according to change request
* Renamed method
to indicate that only the code is fetched, not the entire url.
* Update Guild.js
Useless file, filled with errors. Never served any real purpose. Discussed on discord. Can be replaced should a time come that we automate testing the typings further than just linting.
* fix: Capture stack traces in APIRouter to preserve async stack
* fix: Handle the stack trace better
* fix: Check if error is an instance of Error (5XX rejects with Result)
* fix: Error.captureStackTrace is not supported in all browsers
* Fix guild being a guild and not an AbstractHandler in PresenceUpdate
* update the default guild to be a Guild, and not GuildMember
* getters return null instead of undefined
* fix lint
* fix: Util.basename being unreliable
new URL for WHATWG parsing was not chosen because it only works for URLs and threw in local pathes, path.basename is unreliable (according to the devs' note), and path.parse seems to work well.
* docs: Update Util.basename's description
* add Collection as possible param to GuildChannel#overwritePermissions
* change PermissionoverwriteOptions desc. default to unset
* fix eslint hiccup
* fix spelling of snowflake
* Add Collection as param to GuildChannel#replacePermissionOverwrites
* Add example for null to PermissionOverwriteOptions
* eslint-disable max-len
* PermissionOverwriteOptions desc. change default to unset
* deprecated allow/deny in favor of allowed/denied
* [WIP] Remove user bots
* more backend userbot removal
* Add mfaEnabled back
* revert client presences store removal
* partially revert getAuth changes
* remove more no longer used children of ClientUserGuildSettings
* fix a bug with this pr and TextBasedChannel.applyToClass
* remove a syncGuilds reference
* more user bot data handling
* various guildSync cleanup
* bots can't call logout
Had the user/bot portions of the code mixed up. Though, does this need to be a promise anymore?
* make ClientManager#destroy() sync
It nolonger needs to be a promise, and nothing depended on it being a promise that I can tell.
* requested change
* Fix massive error
* no longer used as it's userbot only
* Hide Webhook#token (consistency with Client#token)
* Make `Webhook#token` writable
* fix: devsnek's requested change
Webhook#token must be both writable and configurable.
* Add timeDifference calcs back into ratelimits
And fix x-ratelimit-reset is in seconds, not ms: https://puu.sh/AIXxY/9b3989b248.png
* mutate reset time with date header instead
* fix defaulting of reset and remaining
if the reset header is not available, then the reset time should be Date.now() instead of the difference between the date header and Date.now()
If the date header is null, fall back to Date.now() since it's the best we can do (this should never happen, but safer to handle it just in case)
if remaining is 0 we don't want to default it back to 1 since 0 is falsy
Unlike TextChannel#fetchMessages, this method returned the cache rather than the fetched items, so in interests of consistency, this does as well now
closes#2574
The node documentation fails to correctly document when the backlog of unsent messages exceeds a certain threshhold the function will return false. This does not mean it will refuse to send- simply that it will take time. Issue in point: https://github.com/nodejs/node/issues/7657#issuecomment-240581726
The node documentation fails to correctly document when the backlog of unsent messages exceeds a certain threshhold the function will return false. This does not mean it will refuse to send- simply that it will take time. Issue in point: https://github.com/nodejs/node/issues/7657#issuecomment-240581726
* Fixed a bug where Guild#equals would cause the given guild to lose its features
* Fix Util.arraysEqual
* Fixed docs for Util.arraysEqual
* Remove Util.arraysEqual
* Rework collection
* Fix docs
* Remove (prop, value) behavior
* Add back thisArg
* Put examples on same line
* Revert map to return array
* Make examples less specific
* Add thisArg to sweep and partition
* feat(GuildEmoji#deletable)
* Update: Discord API returns 50001
When you try to get or delete a managed emoji from the API, you get a 50001 (Missing Access) error code.
* refactor: reduced duplication in role stores
* fix docs
* fix: typo
* most of requested changes
* rest of changes
* ACTUAL rest of changes
* docs
* doooocs
* reason
If I am not mistaken the only way atm to remove a channels parent atm is to do this to get the null value through the code.
channel.client.rest.methods.updateChannel({id:channel.id, name:channel.name,
topic:channel.topic,position:channel.position,
bitrate:channel.bitrate,userLimit:channel.userLimit,parent:{id:null}}, {});
This fixes the method allowing channel.setParent(null); to work
* fix message embed json serialization
remove the toJSON method on message embeds so the raw data is exposed
for JSON seralization. this removes the hexColor property, but it
probably should not have been there in the first place. fixes#2419
* change api transform to tojson
Fixes#2364
Discord sends those timestamps packed as SMALL_BIG_EXT, which get converted to strings in js.
~~Maybe they are already preparing their timestamps for 2038.~~
* Bring some docs up to date, as well as add a new example
* Missed an exclamation mark
* Do requested changes
* Do suggestions
* Same suggestions for the other examples
* Show people that they can also use reply with embeds
* Typos in embed.js example
* Remove object example from embeds, too complex
Suggested by Yukine
* Some changes, some requested changes
* Add moderation examples!
* Add attachment examples
* Missing dot
* Fix spacing
* Requested Changes
* Quote consistency
* Tfw you break the syntax
* docs/feat(WebsocketOptions): Parse ws options presence
Allow the `presence` property in `WebsocketOptions` to be used the same way
as `ClientUser#setPresence`.
* Move presence options to top level
* Prepare to work on moving all role functions to a Store
And yes, this is *another* patch branch cause I messed up my master branch to hell
* Move all emoji role related functions to its own store
Tested everything and it works! (With a reload of the client)
Also had to change a value in DataStore#holds
holds.name for GuildEmojis would return the emoji name instead of the class name
* New Line
* Thanks JS for circular dependency!
Because we can't have nice things...
* Do space's request
* Fix equals
* Fix space's point.
Raw API data has the role property as an array of IDs
Two things:
* Documentation doesn't account for possible raw object return
* Allows the return to be a Message object as well, like the docs originally intended
* Ignore this I need a patch branch for Git
* Move all member role related stuff to a new DataStore
GuildMemberRoleStore is a new store that holds all member role related stuffs
Because its consistent!
* Minorest doc fix ever
To whoever did this object, they forgot a `{`
* Fix the spacing in the docs
* Resue the stores resolve rather than copy paste
Cause I'm dum and it overwrite resolve to the guild role stores resolve soo
* Fix some requests
- Removed the bs private functions
- Set the roles in the constructor
But, I need feedback. There is no way, that I saw, to make a member have roles whenever GuildMmber#_patch is called,
due to the roles being null on the guild. So the only way might be the for loop and getter.
* Fix an issue that I caused in #add
I was testing some other things, and changed that to test. Forgot to change it back
* Actually make the store generate just once when the member is created by first initializing the roles in the guild
Also replaces GuildMember#_roles with GuildMemberRoleStore#_roles
Tested all functions to make sure the expected result happens.
* I missed this from moving remove from GuildMember to GuildMemberRoleStore
* Fix RoleStore#create docs
For real this time
* Do all the requested changes
- Rename all `somethingRole` to `something` (hoistRole => hoist)
- Refactor add and remove to be cleaner and re-use set
* Fix a bug where the store would loose some roles due to null roles that can throw an error in the for loop after they've been deleted
* Remove the `role.id || role` part of the add and remove functions as Appel suggested
* Replace roles.resolve with roles.resolveID for GuildMemberRoleStore#remove
* Don't use Array.isArray in checks
Use instanceof instead
* Woops, I forgot to change this
Renamed colorRole to color
* The docs have dots, so we place the dots back
This leads to GuildMemberStore#_fetchMany to always reject
because it expects more member than possible.
Also no longer call the GuildMemberRemove handler locally
to not decrement twice.
The error from something like client.on('ready', () => undefined.f);
would just be emitted as debug event instead of being thrown.
Simply moving the emitting part out of the try catch again solves this.
* make EmojiStore not Private anymore.
because why have something private if there is priority functionality on that class? also that causes that the docs wont show it directly
* make GuildChannelStore not private anymore
because why have something private if there is priority functionality on that class? also that causes that the docs wont show it directly
* make RoleStore not private anymore
because why have something private if there is priority functionality on that class? also that causes that the docs wont show it directly
* make ReactionStore not private anymore
because why have something private if there is priority functionality on that class? also that causes that the docs wont show it directly
* make all non private to stay consistent
* fix merge conflicts because of other PRs.
ClientUser#setPresence in master branch (latest) calls client.presences.setClientPresence, but that in v11.3 does not
so i change parameter sent to setPresence for clearing the game activity, from activity:null to game:null,
for now until setPresence gets updated
* add Permissions.toArray()
* accept Permissions objects to Permissions.missing()
* accept Permissions as parameter to Permissions.has()
* style fixes
* remove redundant line, update JSDoc for Permission.resolve()
* JSDoc, style, and checkAdmin fixes
* add Permissions.resolveToObject()
* accept PermissionResolvable to Permissions.missing()
* remove `resolveToObject`, fix constructor JSDoc
* remove redundant parameter type
* fix `Permissions.missing()`
* fix checkAdmin
* update Permissions.toArray() description
* eliminate ambiguity in Permissions.toArray() description
* add backticks to permission example
* remove irrelevant type in Permission ctor description
* use this.constructor to properly support OOP
* use simplified approach for Permissions.toArray()
* fix return type on Permissions.toArray()
* move `Permissions#toArray` to more suitable position
* bitwise approach to `Permissions#missing`
* allow `Permissions` to be iterated over
* don't checkAdmin on return array
* remove unnecessary conditional
* fix JSDoc indentation
* use simpler & more reliable approach for missing()
* update PermissionResolvable typedef
* Fix ReactionCollector#remove and make Collector interface more consistent
* Move those below the doc
* Remove object spread
* Only emit event arguments
* Forgot to delete this line
* Update docs
* Also fix this
* More edits to docs
* Snowflake|string
* Permissions#resolve fix
* Travis failed because >120 chars per line
* better fix
Permissions#resolve reverted
removed destructuring in GuildChannelStore and RoleStore
* updating channelCreate example to reflect recent changes
Type is now part of the options object, so the example should reflect that.
* changing type to reason per comment
* fix(setParent): no longer in GuildChannel
* refactored
* little bit less ugly
* space/appel suggestion
* docs fix
* shhhhhhhh
* fun docs trip
* prototype thing
* mark nullable
* added a new Typedef for Bans you can get from <Guild>.fetchBans() due recent change aswell as fixed a little typo in the fetchAuditLogs() mehtod so .type has no the correct type defined
* little change due request
* fixed indentation
* Update Guild.js
* Update Guild.js
* Fix inconsistancy with Channel Creation
* Because static get is a function, it thinks we are create a new instance based on that function, rather than the returned class...
* Fix some missing doc strings
Mainly just readonly tags
* Return an error when guild#allowDMs is ran from a bot account, and fix some return types
* WebhookClient implements Webhook, doesn't extend it
* Fix Client#rateLimit docs not showing what it returns
Cause I wanted to handle this event only to see no return props 🤔
* Actually make Client#rateLimit show the right info
Its an object with all the info
* emit ReactionCollector#remove on all unreactions
this will emit an event when a user removes a collected reaction. this
is in addition to Collector#dispose, which will only fire when all users
have unreacted to the same emoji.
* emit only collected removals
* refactor(MessageReactions): fetchUsers() is now users.fetch()
made a lovely class for it and all
happify linter
stuff
i know how to code i swear
i lied
* bdistin suggestions
* space suggestions, rename store
* fix count
* documentation update
* added a new check to setUserLimit so it won't silently fail anymore if you put a wrong type in
* adapt spaces idea of converting null to 0
* this way it looks cleaner
* and i need to remove this
* need to do it that way because like Gus said null will not change anyhting
* space prooved me wrong and idk why ist working now
* fix(TextBasedChannel): return a promise in startTyping
This fixes#2040
Calling TextBasedChannel#startTyping now returns a promise.
This promise resolves when the bot stops typing (TextBasedChannel#stopTyping) or rejects when an error occurs.
Calling the method again returns the same promise as long the bot is still typing.
* move code into the promise' executor
* Clarify the purpose of the returned Promise
* inverse if and clarify count parameter
* docs: Add/normalize .toString() examples on all classes
* docs: Remove exclamation point on ClientApplication#toString example
* docs: Normalize .toString() descriptions on all classes
* Use "returns" instead of "concatenates"
* docs: fix documentation in various places
All stores: resolveID returns a nullable Snowflake
GuildAuditLogs: ActionType also can be ALL
MessageEmbed: make files property show up in the docs
ClientApplication: resetSecret and resetToken return a promise
ClientManager: status is readonly
Guild: features is an array of strings and ban no longer accepts a number or string
Guild: ban method no longer accepts a string or number
GuildMember: ^
RichPresenceAssets: small and large Image are Snowflakes, also fixed parameter documentation for small and large image url method
WebhookMessageOptions: file property is no longer a thing
* docs: improve GuildAuditLogs documentation
Prefix types with AuditLog to avoid confusion
Document GuildAuditLogs' static Targets and Actions properties and add necessary typedefs
Use typdefs over primitives where possible.
* fix documentation for Guild#defaultRole
The UserGetAction was never used.
The GuildMemberGetAction was only once used.
Easily replaced with a shorter and more comprehensible line. (Also consistent with the rest of the library)
* Fix setPosition issue
The rawPositions were never updated from using setPosition, now they are.
* Fix bubbling issue
Also, yes. It took me 8 hours to get back home. Deal with it :D
* Watch your copy paste
* Fix typo in setPosition
* Same typo in Role
* Fix edit with position breaking when the position was 0
* Eslint
* Revert code but fix the position issue
* tinify webpack
* meme
* fix long version
* more changes
* even smoler
* fix up logic
* fix build
* undo changes to user agent manager because its not webpack'd anymore
* the heck
* fix stupid
* clean up browser rules
* typo
* Fix documentation for GuildAuditLogEntry.target
* Update documentation for CategoryChannel#children
* Add EntryTarget for audit logs
I've done this to "fulfill" devsneks request while also showing all the possible results for the target of an AuditLogEntry
* Oops Eslint
* Private timeout sets gets set by BaseClient not WebhookClient
* Fix the "Missing Docs" for Presence#activity
* Small doc inconsistency
Array<Number> instead of Array<number> for Activity
* Client#emojis is an EmojiStore not a Collection
* Document ClientPresenceStore
Just so its clickable through the wiki, nothing else is documented
* Small fix for BaseClient#setInterval
You don't wait before executing, you execute every X ms
* GuildChannelResolvable takes a GuildChannel/Snowflake
* Typo in UserResolvable
* Another typo for UserResolvable
* Add the number to the Status and VoiceStatus docs
Its probably not needed, but just so the user knows what each number means, its now documented.
* add permissionsLocked
* wip permissionLock()
* should be good
* better method name
* see if this fixes channel jumping
* fix property names
* each overwrite is a different instance, and thus the pointers do not equal, even if the values do.
* add more documentation to the edit method
* fix Permissions.add/remove, by completely changing what they do
* permissions cleanup
Removes overwrite._denied and overwrite._allowed in favor of overwrite.denied.bitfield and overwrite.allowed.bitfield
uses the modified Permissions.add and Permissions.remove to clean up existing code
fixes GuildMember.missingPermissions
changes Permissions add/remove to reverse loops for speed, changes resolve to allow the number 0 as a valid permission.
* Revert createChannel overwrite.allow / overwrite.deny for arrays of {allow:bitfield, deny:bitfield}
Documentation should be improved here, although I would need advice. I believe a overwrite object typedef is needed, to show the structure of the object, and also include that collections may be used for this, rather than arrays.
* api router fix for overwritePermissions
* add Permissions.freeze, and change all returned Permissions to immutable instances
* Make Permissions a permission resolveable
change role.permissions to be an instance of Permissions
* Make permissions.add/remove return a new instance if the instance is frozen
* Fix invalid error
* Update GuildChannel.js
* Update Guild.js
* fix bad merge
* Start Store cleanup
* wip store cleanup
* fix iterables initiating datastores
* handle the possibility of a datastore with no holds and no its own 'create' method
* more cleanup (instances that need more than just client/data)
* missed RoleStore extras
* not sure how eslint didn't catch that tab...
* avoid re-getting the channel we already have...
* cleanup resolvers and refactor them into DataStores
* ^
* and remove
* fix some bugs
* fix lint
* fix documentation maybe?
* formatting
* fix presences
* really fix presences this time
* bad fix was bad... let;s see how bad this one is..
* forgot to save a file
* make presence resolving take userresolveables too
* fix tabs in jsdocs
* fix bad fix from last night that caused issues, with better fix...
* oops
* refactor(Attachment): Merge MessageAttachment with Attachment
* refactor(Attachment): Rename setup to _patch for consistency
* refactor(MessageAttachment): Global rename of Attachment class
* refactor(ClientUserGuildSettings): make client first parameter of the constructor
* refactor(ClientUserChannelOverride): patch if possible rather then reinstantiating every update
* fix(ClientUserGuildSettings): avoid uncaught exception when patching newly joined guilds/gdms
* Normalize undefined type checks in collections with typeof operators.
* Remove redundant number type checking in collections.
Number.isInteger() throws false for strings and any other types that aren't numbers.
* refactor/fix(DataStores): move instantiating of store related classes into the relevant create methods and fixed FetchMemberOptions
* Renamed ChannelStore's constructor parameter for claritiy
* define client property before creating items from passed iterable to avoid the client property being undefined
* Fix fetching members with a limit
* add static Channel#create back and moved channel instantiating there
* make ChannelStore's constructor accept an iterable
* make iterable an optional parameter, allow to just pass client and options
* fixed a little typo in docs of <User>.displayAvatarURL() (#1872)
* Rewrite presence a little bit (#1853)
* such presence many good
* Update PresenceStore.js
* Update index.js
* Update ClientPresenceStore.js
* Update Presence.js
* Update ClientPresenceStore.js
* Update ClientUser.js
* Update Presence.js
* add timestamps and party
* Update Presence.js
* Update PresenceStore.js
* Update ClientPresenceStore.js
* Update ClientPresenceStore.js
* fix: made options.type optional in ClientUser#setActivity (#1875)
* fix: made options.type optional in ClientUser#setActivity
* some changes, smol fix
due to too many types being possible, it should just be defaulted to 0. this means streamers will have to set the type manually, though.
also mistake with activity.name check
* docs(Collection): Adjust exists documentation (#1876)
Since the return value of Collection#exists is basically just a boolean of Collection#find's result, the same documentation and arguments can and should be applied.
* refactor(Emoji): remove Guild#deleteEmoji in favour of Emoji#delete (#1877)
* refactor/fix(DataStores): move instantiating of store related classes into the relevant create methods and fixed FetchMemberOptions
* Renamed ChannelStore's constructor parameter for claritiy
* define client property before creating items from passed iterable to avoid the client property being undefined
* Fix fetching members with a limit
* add static Channel#create back and moved channel instantiating there
* make ChannelStore's constructor accept an iterable
* make iterable an optional parameter, allow to just pass client and options
* rebase, this time with saving the file
* address issue with falsy activity throwing errors when setting client's presence
Since the return value of Collection#exists is basically just a boolean of Collection#find's result, the same documentation and arguments can and should be applied.
* fix: made options.type optional in ClientUser#setActivity
* some changes, smol fix
due to too many types being possible, it should just be defaulted to 0. this means streamers will have to set the type manually, though.
also mistake with activity.name check
* Fix docs for Guild#pruneMembers
* ClientApplication returns
* Guild#deleteEmoji
* Guild#setRolePosition takes RoleResolvable
* Client#fetchApplication returns ClientApplication not Oauth2Application
* ClientDataResolver#resolveImage can return null
* ClientApplication#toString small example
* Guild#allowDMs now has a only for user accounts warning
* ClientUserSettings#patch is private and setGuildPosition has a user account warning
* Role#setPermissions can take PermissionResolvable, not just String
* ChannelCreationOverwrites is for a role or a member, not for a "group"
* Fix ChannelData#userlimit string being wrong
"The user limit of voice the channel" :lul:
* ChannelResolvable is only for Channel or Snowflake
* EmojiIdentifierResolvable supports Snowflakes
* UserResolvable doesn't take a guild
* Make patch functions private
* Remove examples
* Webhoox#edit options.name defaults to the webhook name
* Make VoiceConnection functions private
* Am dum
The whole ClientUserSettings category is only for self bots soo
* Value for update functions is *
* Make update functions be private
* Fix GuildEditData missing Ssytemchannel property
* PermissionOverwriteOptions can accept null as an option
(Why did no-one document this?)
* Fixed leftover fetchThing and removed unused methods/error messages
* Added resume event constant and used event constants wherever possible
* Replaced mentions of removed method name with their new name.
* Fixed typo: resume -> resumed
- UserResolvable no longer allows a guild
- ChannelResolvable no longer allows a message or a guild
- ChannelResolvable no longer allows a message or a guild
* UserStore refactor
* Create ChannelStore, remove redundant methods in ClientDataManager
* Create GuildStore
* Emoji stuff
* Use a Base class where possible to reduce code duplication
* Remove unnecessary comments from ChannelStore
* Add Base._clone();
* Remove unused ClientDataManager methods
* Refactor some more stuff
* ESLint
* Move Client#fetchUser to client.users.fetch
* Remove .has checks and just see if .get is truthy
* Fix guild member chunk error
* ESLint
* Fix typo
* Fix channel storing for user bots
* Remove ClientDataManager
* GuildChannelStore
* Reduce use of Util.cloneObject
* and this one too
* update typings
* Fix MessageUpdate handling (#1507)
* Fix role updates (probably fixes#1525)
* fix for eslint
* Address some of appell's comments
* Use debug constant
* start message store crap if it's ugly tell me later k
* fix that
* message store but works™️
* clean up guild stuff
* clean up channel store stuff
* clean up channel event handling
* does this message stuff work? find out soon in the next episode of dIsCoRd.Js
* eslint
* emojis
* emojis and reactions
* hi my name is eslint and im A LIL SHIT
* so i forgot this huh
* user stuff
* Fix @class
* Fix message stuff
* Fix user store docs
* Document all the bases
* fix the super things
* tidy up remove
* fix textbasedchannel
* fix that too
* fix emoji store
* make voice state stuff less ugly
* make voice states even less ugly
* make members less bad
* fix bug
* fix that too
* fix reactions
* how was this broken for so long
* role store
* remove super._patch from UserConnection
* Rename UserProfile#setup to _patch
* remove unnecessary super calls
* update docgen dep (pls fix travis thx)
* doc messagestore
* fix docs
* message store docs
* things
* DOCS PLS
* more things
* Document TextBasedChannel#messages as a MessageStore
* Rebase
* All the stores!
* Allow to set the new game types via ClientUser#setPresence and setGame
* Accept string version of types, fix options parameter, remove Presence#streaming
* One line if statement, don't reuse data.game when game is already reassigned and fix error message
* Removed redundant if statement
* Audio bitrate support
Note: not implemented for VoiceBroadcasts
* Fix default args, auto bitrate
* Late night typos are the best
* Changes bitrate to kbps for VoiceChannel stuff
* Add methods to manipulate bitrate while encoding
* Add `count` optional argument to Collection methods
[NON-BREAKING CHANGE]
An optional `count` argument is added to the following methods:
- random() and randomKey()
- first() and firstKey()
- last() and lastKey()
If `count` is used, the method returns an array instead of only the value. Performance impact non-existent for existing code. Performance for returning an array has been measured and this is the fastest I could find (array[i] = value is faster than array.push()).
* Update Collection.js
Fixed spacing/line length errors according to suggestions by codacy/pr
* Fixed docs
Added proper `@returns {*|Array}` as the methods might return either. Also added params where missing (whoops)
* Further doc fixes
Per Crawl's comments, fixed (i + 1) spacing as well as fixed {Integer} to {number}
* random() and randomKey() fix
Per Hydra's comment, random() and randomKey() now ensures unique values.
I've also resolved potential issues with requesting a count higher than the collection size. A collection with 10 items will only ever return at most 10 items using the `count` property.
* Can I facepalm harder
Had wrong header comments ^_^
* Fixed for "values/value" and Omited
Also, added "Positive" integer check.
* looks like I "omitted" a change, there.
* Update Collection.js
* Update Collection.js
* Update Collection.js
- Fixed a common copy paste fail `the the <thing>` in various places
- Apparently I can't type Resolvable correctly,
Fixed that wherever applicable
- Documented GroupDMChannel#nicks so that it will be displayed on the docs
- GroupDMChannel#icon is nullable
- Removed empty InviteOptions typdef, as its properties are now documented in GuildChannel#createInvite
- MessageMentions#channels is no longer nullable
- RoleData#permissions takes a PermissionResolvable or an array of them
- Webhook#avatar is nullable
- Added HTTPOptions typedef and added it to ClientOptions typedef
- ClientUserChannelOverride#muted is for a channel and not a guild directly
* Made creating channels with overwrites nicer
and added ClientDataResolver#resolveRole
* Renamed ChannelPermissionOverwrites to ChannelCreationOverwrites
* Added RoleResolvables everywhere possible
* Fixed Emoji#setName resetting restricted roles and Emoji#equals
Which will lead to emojis not to update when roles are being added removed.
* Add Attachment structure
* Fix linter issues + @private
* Fixed array sends, also added embed sends
* fixed proving path to attachment
* fixed incorrect name assumption from path
* linting fix
* ;)
* im really good at this
* changes as requested by gus
and computer from #1459
* am a dum
* update webhook#send
* readonly addition to getters
* i... uh... oops
* farming deez commits
* fix webhook split
* removed some ugly
* removed .every checks
* ClientUser#createGroupDM now works like the docs states on user accounts
* Added GroupDMChannel#setIcon and fixed null handling for the channel name
* Added an s
* Don't resolve when icon is falsy and removed useless name trimming
* Removed now unnecessary name constant
* vscode being great
* Added GroupDMChannel#iconURL
* user guild settings
* Use direct collection
* I'm a goof
* double goof
* Structure properties
* Forgot to register listener
* wrong class names
* No more get in docs
* avoid waterfalls, bot checks
* trycatch
wow i thought i already did this :notlikecat:
* 👀
* Update ClientUser.js
* Update ClientUserGuildSettings.js
* Update UserGuildSettingsUpdate.js
* Update ClientUserChannelOverride.js
* Update ClientUserGuildSettings.js
* rewrite ratelimiting and api route builder
* more stuff
* let people pass their own handlers
* Update burst.js
* Update RequestHandler.js
* Update burst.js
* Update sequential.js
* Update RequestHandler.js
* Audio bitrate support
Note: not implemented for VoiceBroadcasts
* Fix default args, auto bitrate
* Late night typos are the best
* Changes bitrate to kbps for VoiceChannel stuff
* Add methods to manipulate bitrate while encoding
* rewrite ratelimiting and api route builder
* more stuff
* let people pass their own handlers
* Update burst.js
* Update RequestHandler.js
* Update burst.js
* Update sequential.js
* Update RequestHandler.js
* Added missing error messages
As well as `Guild#setRolePosition` and `Guild#setChannelPosition`'s first arg validation
And fixed a typo in `Guild#setChannelPosition`
`roles` -> `channels`
* Reverted collection and Util constructors
* Removed leftover messages
Should have been in the second commit.
* It's a single invalid permission and removed unused flag error
* Fix INVALID_TOKEN -> TOKEN_INVALID as of #1703
* fixed GroupDMChannel#addUser, added setName and removeUser
and changed every `the Group DM`to `this Group DM`, for consistency
* added edit method
* delete method comes already with the Channel class
* brackets
* removed empty line
* Fixed User#fetchProfile, UserProfile#premium and added #flags
* made UserProfile#flags a getter and stored the raw bitfield under UserProfile#_flags
* lowercased Flags
Remove the implication that a Message object's ID is unique only to the channel it was sent on
Message ID's are snowflakes, and as stated in Discord's API documentation, globally unique throughout Discord
Remove the implication that a Message object's ID is unique only to the channel it was sent on
Message ID's are snowflakes, and as stated in Discord's API documentation, globally unique throughout Discord
* using correct properties to apply permissionOverwrites
and fixed `GuildChannel#clone`
* also arrays should be mapped and correct properties taking priority
* changed .deny and .allow to .denied and .allowed respectively
* whoops
* Add `count` optional argument to Collection methods
[NON-BREAKING CHANGE]
An optional `count` argument is added to the following methods:
- random() and randomKey()
- first() and firstKey()
- last() and lastKey()
If `count` is used, the method returns an array instead of only the value. Performance impact non-existent for existing code. Performance for returning an array has been measured and this is the fastest I could find (array[i] = value is faster than array.push()).
* Update Collection.js
Fixed spacing/line length errors according to suggestions by codacy/pr
* Fixed docs
Added proper `@returns {*|Array}` as the methods might return either. Also added params where missing (whoops)
* Further doc fixes
Per Crawl's comments, fixed (i + 1) spacing as well as fixed {Integer} to {number}
* random() and randomKey() fix
Per Hydra's comment, random() and randomKey() now ensures unique values.
I've also resolved potential issues with requesting a count higher than the collection size. A collection with 10 items will only ever return at most 10 items using the `count` property.
* Can I facepalm harder
Had wrong header comments ^_^
* Fixed for "values/value" and Omited
Also, added "Positive" integer check.
* looks like I "omitted" a change, there.
* Update Collection.js
* Update Collection.js
* Update Collection.js
* Add denied/allowed permissions to PermissionOverwrites
* Remove one accidental trailing space.
* Change to _denied/_allowed & denied/allowed
This could possible break if people use deny/allow, I assume, but that's okay.
* Update PermissionOverwrites.js
* Update PermissionOverwrites.js
* Fix Util.js : fetchRecommendedShards()
I'm not sure who thought this was a good idea, but by removing gateway, it broke fetchRecommendedShards() in Util.js as it uses ${Constants.Endpoints.gateway.bot}.
* Update Constants.js
* Update Constants.js
* Update Util.js
* Update Constants.js
* wowe
* fix sending
* Update MessageEmbed.js
* lel
* patched some fields for message embed and transforms edits as well
* webhook embeds transform
* apply transform to webhook embeds, and changed references
* Update MessageEmbed.js
* Update ClientDataResolver.js
* updated embeds params and use new util resolvers
* did not mean to add this back
* use master version of ClientDataResolver
* transform no longer needed
* handing guildauditlog's promise rejections to the user
* Returning a new Promise to resolve a Promise.all is unnecessary.
Also for the docs, it returns a Promise<GuildauditLogs>, not GuildAuditLogs directly.
* totally did not removed that line
* handing guildauditlog's promise rejections to the user
* Returning a new Promise to resolve a Promise.all is unnecessary.
Also for the docs, it returns a Promise<GuildauditLogs>, not GuildAuditLogs directly.
* totally did not removed that line
* fix fetchMentions' auth header, options and data mapping
* vscode strikes again
* switched to Util.mergeDefault
* vscode
* removed duplicated optionals and switched to instanceof
* fix fetchMentions' auth header, options and data mapping
* vscode strikes again
* switched to Util.mergeDefault
* vscode
* removed duplicated optionals and switched to instanceof
* Start rewriting Manager and Connection
* more stuff
* stuff
* Fix ready bug
* some stuff i forgot
* fix some stuff
* add stupid heartbeat ack like seriously who cares
* woo!
* fix a bug
* rate limit the dumb websocket
* stuff
* hdocs
* Docs
* Remove ClientManager#setupKeepAlive as it is now redundant
* Change Client._pingTimestamp to a getter that fetches the timestamp from the WebSocketConnection
* are you happy now eslint smh
* make gus happy
* Add CloseEvent external doc
* Make sure to emit 'reconnecting' when actually reconnecting
* ffs
* Fix RESUME logic
* Add heartbeat ack debug messages, including latency data
* Dumb stuff for Gus
* thx eslint
* more dumb stuff
* more dumb crap smh gus i h8 u
* moar messages
* fix for using wrong status, causing certain events not to be fired (#1422)
* throw error for role names/integers being provided for role resolvables
* Update RESTMethods.js
* Update RESTMethods.js
im really bad
* Update RESTMethods.js
* removed new promise reject
ty gus
* Update RESTMethods.js
* move error to guildmember.addRole method
* Update GuildMember.js
* EmojiIdentifierResolvable now supports emoji IDs and pre-encoded unicode
* forgot to return the identifier and not the emoji itself
* using ? in JSDoc instead of |null
* Break reconnect loop if you client.destroy in the disconnect event
* fix lint/long line?
* God this is So UGLY, why...
* Update WebSocketManager.js
* Update WebSocketManager.js
I considered it might be useful to have something exposed that allows the end-user to set these if they want, but our current code doesn't allow for that. It'll remain an internal feature for the time being.
* getters for decibel and logarithmic volume
I don't really understand where the conversion numbers come from but having this allows for an easy way to get the volume back based on what method you used to set it. I think the math is right, but yeah I've just used the conversion numbers from the other methods.
* fix trailing spaces
* rewrite http
* browser fun
* all the mimes dammit
* i need a newline
* whoops
* forgot about this
* use promises and HTTPRequest.method
* fluent
* move httpclient to external module
* branding
* middleware
* revert middleware
* make role calculated position nicer
* make channels sortable in a nice way too
* stupid git web rebase editor
* Update Guild.js
* Update Guild.js
* Update Guild.js
* Update Guild.js
* Update RESTMethods.js
* [requires more testing] Fix#1089
* Clean up unshift
* Remove <Message>.patch(data)
Nothing calls this method any longer. It is also a private method, so this shouldn't be a breaking change.
* Fix Message Reactions
Purposely reference previous reaction collections, so collection is consistant accross all message edits (no unnecisary data duplication). Makes #1221 extranious.
* Some Data Packets come Incomplete
And several properties can be falsy, so instead of || opted for hasOwnProperty().
* No reason MessageTypes should be an object...
* Use `prop in obj` isntead of hasOwnProp
per @Gawdl3y
* Update UserAgentManager.js
* Update UserAgentManager.js
* gawdl3y is one of the most pants-on-head retarded people i have ever met
* Update UserAgentManager.js
* Update UserAgentManager.js
* Update UserAgentManager.js
* Update UserAgentManager.js
- Rename Guild#updateChannelPositions -> setChannelPositions
- Allow Guild#setChannelPositions to take ChannelResolvables
- Prioritise ClientDataResolver#resolveChannel's string case
- Minor cleanup
* Adding resetGame functionallity
`setGame` method would allways result in an Object passed to `setPresence`.
Passing { game: null } (supported by discords WebSocket gateway to reset the current Game) to `setPresence` would still result in a Game Object sent to the endpoint.
Explicitly setting `game` to null should overwrite the `game` object provided by `localPresence` or `client.presence`.
This was neither supported by `setGame` or `setPresence`.
* Missing semicolons to resetGame and setPresence
* Fixing trailing spaces, commas and semicolons
* Moving resetGame functionality into setGame method
Minification of if statement in setPresence.
Removing resetGame method and adding a case for `game === null` to setGame method
* Adding missing space in setGame method
* Fix docs
* Adding shuffleArray method to utils
* Shuffle channels functionality on guild.
* Comment fix
* Removing shuffle functionality and replacing with a simple update
* Code review changes to method/variable names
* Update comment reference to channelId as well
* Updating jsdoc with typedef of ChannelPosition
* VoiceConnection rework
- improves codebase
- removes concept of pending connections
- attempts to fix memory leaks by removing EventEmitter listeners
- makes voice connections keep track of its own channel when it is moved by another user
- allows voice connections to reconnect when Discord falls back to another voice server or a region change occurs
- adds events for some of the aforementioned events
* Removed unused code
* More clean up / bugfixes
* Added typedefs to Status and VoiceStatus constants
* Add RichEmbed#attachFile
Mostly for attaching local images that can be accessed within the embed image/author icon/footer icon via `attachment//filename.png` and the like.
* Update docstring to reflect valid param types
* Update TextBasedChannel.js
* Update RichEmbed.js
* Update RichEmbed.js
* Added support for adding users to guild
added RESTMethods#AddGuildMemberOptions and Guild#addMember with typedef
AddGuildMemberOptions to be able to add user to guild as a member
through `PUT/guilds/{guild.id}/members/{user.id}`
https://discordapp.com/developers/docs/resources/guild#add-guild-member
* fixing lint errors
* Changes based on discussion
* Changes based on discussion 2
* Changes based on discussion 3
Yay! More changes.
* Fix for incorrect oldMember in guildMemberUpdate event after addRole
`addRole` would modify the cached GuildMember rather than letting it be handled internally when a guild member update packet is received from Discord, leading to the `oldMember` and `newMember` being identical following a call to `addRole`
This is currently how `addRoles` does it, and a correct oldMember is passed to the `guildMemberUpdate` event following a call to `addRoles`
* Return cloned member with added/removed role
So we can return a member object with the added/removed role without affecting the member object sent to `guildMemberUpdate`
* Wait for guildMemberUpdate and return updated GuildMember
* Fix linter errors
* Remove listeners after 10 seconds
* Add support to edit emojis
* Fixes for coding style.
* Add and use guildEmoji constants for updateEmoji
* Just use the Constant
* Fix typo in edit documentation
* Specify property types
* Fix ridiculous typo.
* Update Emoji.js
* Added opus stream support, added volume interface
* Remove setImmediate
* Fix weird syntax error
* Most useless commit ever
You're welcome, @PgBiel
* Fix potential memory leak with OpusScript
Emscripten has the tendency to not free resources even when the Opus engine instance has been garbage collected. Thanks to @abalabahaha for pointing this out.
* Typo
* VoiceReceiver.destroy: destroy opus encoder
* Message patching: clear mention collections
Fixes#1089
When discord sends an array of mentions, it is a full list of mentions -- therefore, we should clear the old mention collection. The same goes for when we re-analyze the message for channel mentions.
* Use Collection.clear() instead of new Collection
* Added try catch so that decode errors aren't fatal
* Tweaked the usage of the warn event and updated jsdocs
* Moved method into class for webpack scoping reasons
* add color resolvable, and color constants from the client
* fix up docs
* Update ClientDataResolver.js
* add easter eggs
* Update ClientDataResolver.js
* Update RESTMethods.js
* add more search stuff
* clean up the options
* fix link hostname
* use some resolvers
* fix type
* move the trasform to a seperate file
* pass this param
* move typedef
* start wip rewrite of sending/editing messages
* pass the build, modify the edit method to fit the new system
* simplify the applyToClass method
* change handling of file options
* add back message splitting
* i couldn't help myself
* add some smart message options
* clean up, add sexy options
* fix indentation
* fix up splitting
* add \b
* add back old methods for hydar happiness
* clean up more
* move code handling to the rest method
* clean up this.rest.client
* Update TextBasedChannel.js
* add docs back for the bad methods
* fix reply in group dms
* srsly gawdl3y
* make code better
* fix changes for gawdl3y
* fix checking
* remove getter
* make code handling more robust
* k
* fix up sendEmbed docs
* stupid
* fix up more docs because aaaaa
* no more pls
Changed RichEmbed to take StringResolvables for all title, name, value and
description arguments.
Also changed a few lines in setColor to make sure that the value
assigned to this.color is always a number.
* Pass Reason to the streamDispatcher end event
* Update <dispatcher>.end() to bring inline with <collector>.stop()
Also changed "Stream is not generating quickly enough." from an end to an error, per Crawl...
* Fix docs Copy/Paste fail from collection end event
* Docs update
Changed the param names and param descriptions to be consistent.
* Added === comparison
Changed Presence.equals and Game.equals to first compare using ===
* Collection.equals fix
Now returns false when collection is undefined, instead of crashing
💯
* + Added function to get a user's default avatar
+ Added HOST constant to Constants
+ Added assets endpoint
+ Added quality of life function to get a user's avatar or default avatar
+ Added quality of life function to get member's nickname or username
* * Fixed invocation of a getter.
* Fixed lint issue
* Made the API constant use the HOST constant for DRY-ness
Changed DOC comment to be more descriptive
* Update GuildMember.js
* RichEmbed Tweaks/Improvements
Changed .addTimestamp() to .setTimestamp() to bring it inline with all other single value settings.
Changed Field value to StringResolveable from String to bring it inline with typical sendMessage functionality.
* Lint Fix
* Remove Default, Add check for undefined
* Update faq.md (#949)
* fix docs
* Revert "fixed typo in documentation" (#950)
* new errors for richembed yay
Simplified the parsing for color arrays.
Throwing some errors on values that would result in Bad Requests.
Changed setAuthor and setFooter's icon parameter to icon_url to match
the embed object's property name.
Changed the docs for setFooter to reflect that icon_url is optional.
* changed docs instead of arg names
* capitalization
* this is why wrapping data 1:1 is a bad idea
* ffs
* whoever wrote role.hexColor is a bad, bad person
* Update MessageEmbed.js
* Update MessageEmbed.js
* Add more errors for RichEmbed builder char limits
Might as well if we're erroring on number of fields when that's the one limit that doesn't actually throw a bad request.
* Fix name.length check in previous commit
* Update RichEmbed.js
* Update number of fields error message
Adds an equals function that checks for differing size and differing
key-value pairs, and takes into account the edge case for when there's
an entry for the key, but the value is undefined.
* the performance from this is astounding
* help uws
* save 15 bytes in webpacks
* update readme
* why is markdown like this
* optimizations
* Update WebSocketManager.js
* friggin webpack tho
* probably important
* add all the stuff to the package.json
* add minify builds and a nice package.json script to run it all
* clean up
* use uglify harmony branch so we can actually run minify builds that work
* update build system
* make test better
* clean up
* fix issues with compression
*
* c++ requirements in a node lib? whaaaaat?
* fix travis yml?
* put railings on voice connections
* 🖕🏻
* aaaaaa
* handle arraybuffers in the unlikely event one is sent
* support arraybuffers in resolvebuffer
* this needs to be fixed at some point
* this was fixed
* disable filename versioning if env VERSIONED is set to false
* Update ClientDataResolver.js
* Update ClientVoiceManager.js
* Update WebSocketManager.js
* Update ConvertArrayBuffer.js
* Update webpack.html
* enable compression for browser and fix ws error handler
* Update WebSocketManager.js
* everything will be okay gawdl3y
* compression is slower in browser, so rip the last three hours of my life
* Update Constants.js
* Update .gitignore
This commit:
* fixes inconsistencies (primarily regarding capitalization)
* fixes non-proper nouns that were improperly capitalized
* fixes reminents from not-so-meticulous copy+paste jobs
* Add support for notes
* Ensure consistency with notes from ready payload
* Add getter method for users
* Minor tweaks
* Update warning messages
* More minor fixes
_timeouts and _intervals were changed to Set objects in
commit 6ede7a32fd a month ago.
Like #844, this fix was reverted in 7d04863b66 (#839)
without explanation and was never included in the followup rewrite in
commit 5e2ee2398e.
If the promise returned by logout() rejects, previously
it would be completely uncaught, and just return an
eternally pending promise that never resolved.
Related to pull requests #828 and #839.
* Add a script to automatically build and push docs
This script will checkout the repo in the `docs` branch, then build the
docs locally, copy it to that repo, commit and push. It is designed to
be used in conjunction with Travis.
* Add unencrypted deploy keys to the gitignore
* Make Travis automatically execute the deploy script
* Add the encrypted deploy key
* Update the .travis.yml with the necessary information
* add test for Client.destroy()
* propagate errors in ClientManager.destroy
If the promise returned by logout() rejects, previously
it would be completely uncaught, and just return an
eternally pending promise that never resolved.
* fix RESTMethods.logout
Without a data argument, the POST that superagent sends causes
the discord server to reply with a HTTP 400 error:
text: '{"Content-Type": "Expected Content-Type to be one of set([\'application/json\'])."}',
* fix Client.destroy
_timeouts and _intervals were changed to Set objects in
commit 6ede7a32fd a month ago.
Changing them to arrays causes failures if you try to reuse
the client object again.
* always close websocket in ClientManager.destroy
Invoking logout does not implicitly cause the server to close
the websocket for you, so cleanup everything.
Otherwise the websocket being open keeps node alive and hanging
mysteriously until the connection hits a timeout.
* fix indentation for eslint
* draft stuff
fix docstring for Client#token
Reorganise resolver
make env better for shards, clean up docs
Fix Gus' log messages
7
meh just gateway/bot not v7 :(
final changes, ready for mergin!
build docs
make default totalShards 'auto', fix docs for totalShards type
clean up docs more
run docs
* make consistancy real
* Update and rename getRecommendedShards.js to GetRecommendedShards.js
* Update GetRecommendedShards.js
* Update index.js
* Update RESTMethods.js
* Update Shard.js
* Update GetRecommendedShards.js
* Update ShardingManager.js
* run docs
* start blocking out client
* proto webhookclient
* wee working webhooks
* it's all working
* run docs
* fix jsdoc issues
* add example for webhookClient
* add example in the examples place
* fix docs
* Cache array and keyArray in Collection
Cache array and keyArray in the Collection class to improve consecutive
calls of collection.random() by around 400,000%, I think lel.
The speed decrease (I assume) compared to the previous version when
calling after it has changed is most likely negligible.
* Fix for ESLint
I think this fixes it.
* Handle DM messages in cleanContent getter. Closes#725.
* Fix build error, improve handling for user IDs.
* Update docblock to be more specific about behaviour.
* Handle group DMs in cleanContent.
* Regen docs.
* add documentation for events, and add a disconnect event, because i know people use that
* generate docs, and fix a hastily copied docstring
* fix permissions freak out
* add a message, because WHY THE HELL DID NO ONE EVER DO THIS
!!!
* make message better
* make linter happy
* disable max-len rule for line 37
* make gawdl3y be happy
* gawdl3y triggers me
* Update FfmpegConverterEngine.js
* Adding playStream options
Added optional volume and seek properties
* fixed code formatting
Edited my code styling to match with the rest of d.js
* Added Default Variable
* Added Documentation
Added documentation for the streamOptions parameter
Added a default value for seek in FFmpegConverterEngine
Removed redundantcy
* Fixed docs for voiceConnection
* Change _updateMember's notSame check from && to || (#665)
* Fixed git merge fail
* Built Docs. Again.........
* Hopefully finally fixed
* Added cleanContent getter which replaces mentions with the equivalent
text.
(Majority of code implemented by Gus).
* Fixed bug where invalid mentions would cause crash
* Fixed not cleaning @everyone and @here
* Fixed only detecting first @here or @everyone, resolved to test software (and learn regular expressions) in the future
* Overhaul channel typing system
* Fix ESLint error
* Add channel.isTyping()
* Add count argument to startTyping
* Add range checking to startTyping count
* Better range checking for count
* Add channel.getTypingCount()
* Change getTypingCount() to typingCount getter
* Switch isTyping() to typing getter
* Fix new methods and switch to Map
* Fix applyProp so getters/setters will work
* Add default value to force
* Altered GuildChannel.type to return a string containing either "text",
"voice" or the id of the channel type.
* Fixed typo
* Altered code to pass ESLint test (Functionality Unchanged).
* Third times the charm.
* Add 'Bot' prefix to token
* Add option for token prefix
* Maybe this is what abal meant?
* Change option name
* Check if token already starts with prefix
* Fix pagebreaks and formatting
* Start touching up sections
* Grab default channel
Usually the general channel anyways 😋
* Add more information
* move this up here
* derp
* cleanup
* touchups
Too many commits? noooo
* Add template literals everywhere, fix backticks and some other stuff
* quote standardization
is that even spelled right
* final touches
there have been a lot of final touches today
* document paused property
* node twitch.tv urls in setStreaming, added note on autoReconnect in troubleshooting
* Fix improper formatting in Cache.get (#1)
* Fix grammar in unpinMessage
* Enhance troubleshooting (#2)
* Enhance troubleshooting
* getChannelLogs can take resolvables
* Include variables
* Add shortcuts
* Add references to shortcuts
* Add shortcuts for User
* Add references for User
* _
* Added an event for the voice speaking packet.
* Updated the docs to reflect the voiceSpeaking event addition.
* Fixed some spacing issues in the VoiceConnection.js file.
* Moved the speaking boolean to the User object.
* Added support for new game objects
bot.setStreaming(name, url, type, callback); added
logic for Internal setStatus updated to check if string or object
* Add disableEveryone option
* forgot to compile
oh well, it can be squash merged
* Fix my very silly mistake
* Another FFMPEG issue fix attempt
* Add a missing semicolon
Yes, I really did make a commit just for this. :)
* Another attempted fix (w/ help from izy521)
#docs_client.rst:
- 257: Add proper eplanation of callback, like in every other method
- 433: Fix linking for Invite Resolvable
#docs_message.rst:
- 90 : Replace ':' with '-', just for consistency with the others
#docs_resolvables.rst:
- 92 : String doesn't link to anything (?) -> Link removed
#docs_servers.rst:
- 109 : Properly indent code-block because it didn't show at all on rtfd
#docs_serverchannel.rst:
- 53 : Remove doulbe '`' causing it not to display properly
#docs_voiceconnection.rst:
- 67 : Remove 'currently, it currently
#docs_voiceconnection.rst:
- 32 : Add links for Role Resolvable, as used in client#addMemberToRole,
client#removeMemberFromRole and client#memberHasRole
Unify ready and reconnecting properties into a single status property
and future-proof Message class
The state of the WebSocketManager is now represented by a single
status property, removing emittedReady
and reconnecting as representations of state.
Message class will now also cache users it isn't aware of that appear
in mentions and authors.
src/structures/datastore/WebSocketManagerDataStore.js
Added "rough" reconnection attempting
The following however still needs to be done:
1) stop trying after a certain amount of time
2) increasing timeout between each timeout
3) re-evaluate the current method of how reconnecting is handled
internally
So far it has been the case that resolveServer has been returning
undefined in the case that the resource was a Message from a TextChannel.
This was the case because the conditional returned the value of member
"server" in the Message object. The Message object doesn't have a server
member though. The fix is to use the "channel" member of the Message
object and return its "server" member which was likely the original
intention considering the if statement.
Particular problems and how they were resolved:
- The `fs-extra` module, used exclusively by TokenCacher, didn't have a browser version. I rewrote TokenCacher to not use fs-extra (see fdd4cfc7cc)
- TokenCacher wouldn't work in the browser anyway due to lack of a file system. I made a shim (`Util/TokenCacher-shim.js`) that implements all TokenCacher functionality as null implementations, this causes `login` to always make a request.
- Compressed packets couldn't be parsed because neither node's Buffers nor zlib were working correctly. Initially I tried to make a browser-only parser class that parses compressed `Blob` packets, but this didn't work out, so I just disabled compression by default.
The `typeof X === "function"` checks to check whether the callback replaces any default arguments didn't set the default arguments afterwards, so internal functions would sometimes get called with the wrong attributes. This is now fixed.
> This is adapted from [Angular's commit convention](https://github.com/conventional-changelog/conventional-changelog/tree/master/packages/conventional-changelog-angular).
Appears under "Features" header, `GuildMember` subheader:
```
feat(GuildMember): add 'tag' method
```
Appears under "Bug Fixes" header, `Guild` subheader, with a link to issue #28:
```
fix(Guild): handle events correctly
close #28
```
Appears under "Performance Improvements" header, and under "Breaking Changes" with the breaking change explanation:
```
perf(core): improve patching by removing 'bar' option
BREAKING CHANGE: The 'bar' option has been removed.
```
The following commit and commit `667ecc1` do not appear in the changelog if they are under the same release. If not, the revert commit appears under the "Reverts" header.
```
revert: feat(Managers): add Managers
This reverts commit 667ecc1654a317a13331b17617d973392f415f02.
```
### Full Message Format
A commit message consists of a **header**, **body** and **footer**. The header has a **type**, **scope** and **subject**:
```
<type>(<scope>): <subject>
<BLANK LINE>
<body>
<BLANK LINE>
<footer>
```
The **header** is mandatory and the **scope** of the header is optional.
### Revert
If the commit reverts a previous commit, it should begin with `revert:`, followed by the header of the reverted commit. In the body, it should say: `This reverts commit <hash>.`, where the hash is the SHA of the commit being reverted.
### Type
If the prefix is `feat`, `fix` or `perf`, it will appear in the changelog. However, if there is any [BREAKING CHANGE](#footer), the commit will always appear in the changelog.
Other prefixes are up to your discretion. Suggested prefixes are `docs`, `chore`, `style`, `refactor`, and `test` for non-changelog related tasks.
### Scope
The scope could be anything specifying the place of the commit change. For example `GuildMember`, `Guild`, `Message`, `MessageEmbed` etc...
### Subject
The subject contains a succinct description of the change:
- use the imperative, present tense: "change" not "changed" nor "changes"
- don't capitalize the first letter
- no dot (.) at the end
### Body
Just as in the **subject**, use the imperative, present tense: "change" not "changed" nor "changes".
The body should include the motivation for the change and contrast this with previous behavior.
### Footer
The footer should contain any information about **Breaking Changes** and is also the place to
reference GitHub issues that this commit **Closes**.
**Breaking Changes** should start with the word `BREAKING CHANGE:` with a space or two newlines. The rest of the commit message is then used for this.
**The issue tracker is only for bug reports and enhancement suggestions. If you have a question, please ask it in the [Discord server](https://discord.gg/djs) instead of opening an issue – you will get redirected there anyway.**
If you wish to contribute to the discord.js codebase or documentation, feel free to fork the repository and submit a
pull request. We use ESLint to enforce a consistent coding style, so having that set up in your editor of choice
is a great boon to your development process.
## Setup
To get ready to work on the codebase, please do the following:
1. Fork & clone the repository, and make sure you're on the **main** branch
2. Run `npm ci`
3. Code your heart out!
4. Run `npm test` to run ESLint and ensure any JSDoc changes are valid
5. [Submit a pull request](https://github.com/discordjs/discord.js/compare) (Make sure you follow the [conventional commit format](https://github.com/discordjs/discord.js/blob/main/.github/COMMIT_CONVENTION.md))
We only use this issue tracker for bug reports and feature request. We are not able to provide general support or answer questions in the form of GitHub issues.
For general questions about discord.js installation and use please use the dedicated support channels in our Discord server: https://discord.gg/djs
Any issues that don't directly involve a bug or a feature request will likely be closed and redirected.
discord.js is a node module used as a way of interfacing with [Discord](https://discordapp.com/). It is a very useful module for creating bots.
- Object-oriented
- Predictable abstractions
- Performant
- 100% coverage of the Discord API
### Installation
## Installation
**Requires node 0.12+**
**Node.js 16.6.0 or newer is required.**
`npm install --save discord.js`
```sh-session
npm install discord.js
yarn add discord.js
pnpm add discord.js
```
---
### Optional packages
- [zlib-sync](https://www.npmjs.com/package/zlib-sync) for WebSocket data compression and inflation (`npm install zlib-sync`)
- [erlpack](https://github.com/discord/erlpack) for significantly faster WebSocket data (de)serialisation (`npm install discord/erlpack`)
- [bufferutil](https://www.npmjs.com/package/bufferutil) for a much faster WebSocket connection (`npm install bufferutil`)
- [utf-8-validate](https://www.npmjs.com/package/utf-8-validate) in combination with `bufferutil` for much faster WebSocket processing (`npm install utf-8-validate`)
- [@discordjs/voice](https://github.com/discordjs/voice) for interacting with the Discord Voice API (`npm install @discordjs/voice`)
If you have an issue or want to know if a feature exists, [read the documentation](http://discordjs.readthedocs.org/en/latest/) before contacting me about any issues! If it's badly/wrongly implemented, let me know!
If you would like to contact me, you can create an issue on the GitHub repo, e-mail me via the one available on my NPM profile.
Alternatively, you could just send a DM to **hydrabolt** in [**Discord API**](https://discord.gg/0SBTUU1wZTYd2XyW).
If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle
nudge in the right direction, please don't hesitate to join our official [discord.js Server](https://discord.gg/djs).
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
A Cache object extends an Array (so it can be used like a regular array) but introduces helper functions to make it more useful when developing with discord.js. Unlike a regular array, it doesn't care about the instance or prototype of an object, it works purely on properties.
**Examples:**
..code-block::js
client.users.get("id",11238414);
client.channels.getAll("name","general");
--------
Functions
---------
get(key, value)
~~~~~~~~~~~~~~~
Returns a contained object where ``object[key] == value``. Returns the first object found that matches the criteria.
getAll(key, value)
~~~~~~~~~~~~~~~~~~
Similar to ``cache.get(key, value)``, but returns a Cache of any objects that meet the criteria.
has(key, value)
~~~~~~~~~~~~~~~
Returns `true` if there is an object that meets the condition ``object[key] == value`` in the cache
add(data)
~~~~~~~~~
Adds an object to the Cache as long as all the other objects in the cache don't have the same ID as it.
update(old, data)
~~~~~~~~~~~~~~~~~
Updates an old object in the Cache (if it exists) with the new one.
This page contains documentation on the `Discord.Client` class. This should be used when you want to start creating things with the API.
--------
Attributes
----------
users
~~~~~
A Cache_ of User_ objects that the client has cached.
channels
~~~~~~~~
A Cache_ of ServerChannel_ objects that the client has cached.
privateChannels
~~~~~~~~~~~~~~~
A Cache_ of PMChannel_ objects that the client has cached. These are all the Private/Direct Chats the client is in.
servers
~~~~~~~
A Cache_ of Server_ objects that the client has cached.
voiceConnection
~~~~~~~~~~~~~~~
A VoiceConnection_ object that is the current voice connection (if any).
readyTime
~~~~~~~~~
A `Number` unix timestamp dating to when the Client emitted `ready`.
uptime
~~~~~~
A `Number` in milliseconds representing how long the Client has been ready for.
user
~~~~
A User_ object representing the logged in client's user.
userAgent
~~~~~~~~~
An object containing `url`, `version` and `full`.
Setting this property allows the discord developers to keep track of active bots,
it defaults to the discord.js git repo and the current version of the package.
`url` should be the repository/homepage of the creator.
`version` should be the version of your bot.
`full` is read only and will be automatically generated upon setting.
-----
Functions
---------
.. note :: Any functions used here that take callbacks as an optional parameter can also be used as Promises_. Promises take the exact same parameters for each use case, except errors are moved to catch statements instead of then. For example, you can do:
Overwrites the permissions of a role or a user in a channel
-**channel** - a `Channel Resolvable`_
-**roleOrUser** - a Role_ or a User_ object
-**options** - an `object` containing a structure as shown below
-**callback** - `function` that takes the following:
- **error** - error if any occurred
..code-block::js
{
"sendMessages":false,
"attachFiles":true
}
Events
------
`Discord.Client` is an EventEmitter, so you can use `.on()` and `.off()` to add and remove events.
ready
~~~~~
Emitted when the client is ready to use
debug
~~~~~
Emitted when the client debugs or wants to log something internally
message
~~~~~~~
Emitted when the client receives a message, supplies a Message_ object.
warn
~~~~
Emitted when the client has encountered a small error that can be avoided.
messageDeleted
~~~~~~~~~~~~~~
Emitted when a message has been deleted and the Client finds out, supplies a Message_ object IF available, and a Channel_ object.
messageUpdated
~~~~~~~~~~~~~~
Emitted when a message has been updated and the client finds out. Supplies two Message_ objects, the first being the new updated messages, the latter being the old message.
disconnected
~~~~~~~~~~~~
Emitted when the client is disconnected from the Discord server.
error
~~~~~
Emitted when the client runs into a big problem, supplies an error object.
raw
~~~
Emitted when a message over WebSocket is received, it supplies one `object` containing the raw data from the WebSocket.
serverCreated
~~~~~~~~~~~~~
Emitted when a server is joined by the Client, supplies a Server_ object.
serverDeleted
~~~~~~~~~~~~~
Emitted when the client leaves a server, supplies a Server_ object.
serverUpdated
~~~~~~~~~~~~~
Emitted when a server is updated (e.g. name change). Supplies two Server_ objects, the first being the server before the update, the second being the new, updated server.
channelCreated
~~~~~~~~~~~~~~
Emitted when a channel is created, supplies a Channel_ object (includes PM chats as well as server channels).
channelDeleted
~~~~~~~~~~~~~~
Emitted when a channel is deleted, supplies a Channel_ object.
channelUpdated
~~~~~~~~~~~~~~
Emitted when a channel is updated (e.g. name/topic change). Supplies a Channel_ object.
serverRoleCreated
~~~~~~~~~~~~~~~~~
Emitted when a role is created in a server, supplies a Role_ object.
serverRoleDeleted
~~~~~~~~~~~~~~~~~
Emitted when a role is deleted from a server, supplies a Role_ object.
serverRoleUpdated
~~~~~~~~~~~~~~~~~
Emitted when a role is updated in a server, supplies two Role_ objects. The first is the old role, the second is the updated role.
serverNewMember
~~~~~~~~~~~~~~~
Emitted when a user joins a server, supplies a Server_ object and a User_ object.
serverMemberRemoved
~~~~~~~~~~~~~~~~~~~
Emitted when a member is removed from a server. Supplies a Server_ object and a User_ object.
serverMemberUpdated
~~~~~~~~~~~~~~~~~~~
Emitted when a member in a server is updated. Supplies a Server_ object and a User_ object.
presence
~~~~~~~~
Emitted when a user goes online/offline/idle or starts/stops playing a game. Supplies 3 parameters, the first being the User_ object, the second being the status, the third being the game ID they are playing.
userUpdated
~~~~~~~~~~~
Emitted when a user changes their name, avatar or similar. Supplies two User_ objects, the first being the user before being updated, the second being the updated user.
userTypingStarted
~~~~~~~~~~~~~~~
Emitted when a user starts typing in a channel. Supplies two parameters, a User_ object and a Channel_ object.
userTypingStopped
~~~~~~~~~~~~~~
Emitted when a user stop typing in a channel. Supplies two parameters, a User_ object and a Channel_ object.
userBanned
~~~~~~~~~~
Emitted when a user is banned from a server. Supplies two parameters, a User_ object and a Server_ object.
userUnbanned
~~~~~~~~~~
Emitted when a user is unbanned from a server. Supplies two parameters, a User_ object and a Server_ object.
voiceJoin
~~~~~~~~
Emitted when a user joins a voice channel, supplies a User_ and a VoiceChannel_
voiceLeave
~~~~~~~~~~
Emitted when a user leaves a voice channel, supplies a User_ and a VoiceChannel_
The Equality class is used to see if two objects are equal, based on ``object_1.id === object_2.id``.
If any class in Discord extends equality, it means you should never the default equality operands (``==`` & ``===``) as they could potentially be different instances and therefore appear not to be equal. Instead, use ``equalityObject.equals()`` as shown below.
..code-block::js
object1.equals(object2);// GOOD ✓
object1==object2;// BAD ✖
--------
Functions
---------
equals(object)
~~~~~~~~~~~~~~
Returns true if the specified object is the same as this one.
- **object** - Any `object` with an ``id`` property.
In discord.js, you can handle permissions in two ways. The preferred way is to just use the string name of the permission, alternatively you can use ``Discord.Constants.Permissions["permission name"]``.
--------
Valid Permission Names
----------------------
..code-block::js
{
// general
createInstantInvite,
kickMembers,
banMembers,
manageRoles,
managePermissions,
manageChannels,
manageChannel,
manageServer,
// text
readMessages,
sendMessages,
sendTTSMessages,
manageMessages,
embedLinks,
attachFiles,
readMessageHistory,
mentionEveryone,
// voice
voiceConnect,
voiceSpeak,
voiceMuteMembers,
voiceDeafenMembers,
voiceMoveMembers,
voiceUseVAD
};
Preferred Way
-------------
The preferred way of using permissions in discord.js is to just use the name. E.g:
``role.hasPermission("voiceUseVAD")``
Alternative
-----------
You can also go the long way round and use the numerical permission like so:
PermissionOverwrite is used to represent data about permission overwrites for roles or users in channels.
--------
Attributes
----------
id
~~
`String`, the ID of the PermissionOverwrite. If ``overwrite.type`` is ``role``, this is the role's ID. Otherwise, it is a User_ overwrite.
type
~~~~
`String`, type of the overwrite. Either ``member`` or ``role``.
allowed
~~~~~~~
Returns the permissions explicitly allowed by the overwrite. An `Array` of Strings, which are names of permissions. More can be found at `Permission Constants`_
denied
~~~~~~
Returns the permissions explicitly denied by the overwrite. An `Array` of Strings, which are names of permissions. More can be found at `Permission Constants`_
In discord.js, the aim is to allow the end developer to have freedom in what sort of data types they supply. References to any sort of resolvable basically mean what types of data you can provide. The different resolvables are shown before:
--------
Channel Resolvable
------------------
A Channel Resolvable allows:
- Channel_
- Server_
- Message_
- User_ (in some instances)
- String of Channel ID
Voice Channel Resolvable
------------------------
A Voice Channel Resolvable allows:
- VoiceChannel_
Message Resolvable
------------------
A Message Resolvable allows:
- Message_
- TextChannel_
- PMChannel_
User Resolvable
---------------
A User Resolvable allows:
- User_
- Message_
- TextChannel_
- PMChannel_
- Server_
- String of User ID
String Resolvable
-----------------
A String Resolvable allows:
- Array
- String
Server Resolvable
-----------------
A Server Resolvable allows:
- Server_
- ServerChannel_
- Message_ (only for messages from server channels)
- String of Server ID
Invite ID Resolvable
--------------------
An Invite ID Resolvable allows:
- Invite_
- String_ containing either a http link to the invite or the invite code on its own.
`Integer` from 0-9999, don't use this to identify users. Used to separate the user from the 9998 others that may have the same username. Made redundant by ``user.id``.
id
~~
`String` (do not parse to an Integer, will become inaccurate). The ID of a user, never changes.
avatar
~~~~~~
`String`, the ID/hash of a user's avatar. To get a path to their avatar, see ``user.avatarURL``.
status
~~~~~~
The status of a user, `String`. Either ``online``, ``offline`` or ``idle``.
gameID
~~~~~~
The ID of the game a user is playing, `Number`.
typing
~~~~~~
`Object` containing the following values;
..code-block::js
{
since:1448038288519,//timestamp of when
channel:<ChannelObject>// channel they are typing in.
}
avatarURL
~~~~~~~~~
A valid URL to the user's avatar if they have one, otherwise null.
voiceChannel
~~~~~~~~~~~~
The VoiceChannel_ the user is connected to. If they aren't in any voice channels, this will be ``null``.
Functions
---------
mention()
~~~~~~~~~
Returns a valid string that can be sent in a message to mention the user. By default, ``user.toString()`` does this so by adding a user object to a string, e.g. ``user + ""``, their mention code will be retrieved.
To install discord.js, you need a few dependencies.
..warning::**When installing with any of these methods, you'll encounter some errors.** This is because an optional dependency isn't working properly, but discord.js should still work fine.
-----------
Windows
-------
------------
- You need `Visual Studio`_ and `Python 2.7`_.
Your Visual Studio installation ideally has to be recent, but you can try installing without it first. You can use **Express, Community, Enteprise** or any others apart from ``VS Code``.
After you have installed these things, to install just run: ``npm install --save --msvs_version=2015 discord.js`` to install the latest version of discord.js for your project.
Additional Audio Support
~~~~~~~~~~~~~~~~~~~~~~~~
- Install `ffmpeg`_ and add it to your PATH.
-----------
Linux
-----
-----------
..code-block::bash
$ apt-get install make build-essentials
$ npm install --save discord.js
Additional Audio Support
~~~~~~~~~~~~~~~~~~~~~~~~
..code-block::bash
$ apt-get install libav-tools
.._Visual Studio : https://www.visualstudio.com/downloads/download-visual-studio-vs
Occasionally, the API can stop working for whatever reason. If it was working previously and it stopped working on the same version, it means that there's been a change to the Discord API. In this case, please `make an issue`_ if one relating to a similar issue doesn't exist. Please post a stacktrace if there is one, and be as detailed as possible - *"the API isn't working"* doesn't help at all.
If there is already an issue, feel free to comment that you're also experiencing the same thing. This helps to see how widespread the bug is.
You can try reconnecting before submitting an issue, as sometimes some of the servers may be slightly different.
.._make an issue : https://github.com/hydrabolt/discord.js/issues
"use strict";exports.__esModule=true;var_createClass=(function(){functiondefineProperties(target,props){for(vari=0;i<props.length;i++){vardescriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"indescriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}returnfunction(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);returnConstructor;};})();function_interopRequireDefault(obj){returnobj&&obj.__esModule?obj:{"default":obj};}function_classCallCheck(instance,Constructor){if(!(instanceinstanceofConstructor)){thrownewTypeError("Cannot call a class as a function");}}function_inherits(subClass,superClass){if(typeofsuperClass!=="function"&&superClass!==null){thrownewTypeError("Super expression must either be null or a function, not "+typeofsuperClass);}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var_InternalClient=require("./InternalClient");var_InternalClient2=_interopRequireDefault(_InternalClient);var_events=require("events");var_events2=_interopRequireDefault(_events);var_StructuresPMChannel=require("../Structures/PMChannel");var_StructuresPMChannel2=_interopRequireDefault(_StructuresPMChannel);// This utility function creates an anonymous error handling wrapper function
// for a given callback. It is used to allow error handling inside the callback
// and using other means.
functionerrorCallback(callback){returnfunction(error){callback(error);throwerror;};}// This utility function creates an anonymous handler function to separate the
// error and the data arguments inside a callback and return the data if it is
Client.prototype.sendMessage=functionsendMessage(where,content){varoptions=arguments.length<=2||arguments[2]===undefined?{}:arguments[2];varcallback=arguments.length<=3||arguments[3]===undefined?function()/*err, msg*/{}:arguments[3];if(typeofoptions==="function"){// options is the callback
Client.prototype.reply=functionreply(where,content){varoptions=arguments.length<=2||arguments[2]===undefined?{}:arguments[2];varcallback=arguments.length<=3||arguments[3]===undefined?function()/*err, msg*/{}:arguments[3];if(typeofoptions==="function"){// options is the callback
callback=options;}varmsg=this.internal.resolver.resolveMessage(where);if(msg){if(!(msg.channelinstanceof_StructuresPMChannel2["default"])){content=msg.author+", "+content;}returnthis.internal.sendMessage(msg,content,options).then(dataCallback(callback),errorCallback(callback));}varerr=newError("Destination not resolvable to a message!");callback(err);returnPromise.reject(err);};// def replyTTS
Client.prototype.deleteMessage=functiondeleteMessage(msg){varoptions=arguments.length<=1||arguments[1]===undefined?{}:arguments[1];varcallback=arguments.length<=2||arguments[2]===undefined?function()/*err, {}*/{}:arguments[2];if(typeofoptions==="function"){// options is the callback
Client.prototype.updateMessage=functionupdateMessage(msg,content){varoptions=arguments.length<=2||arguments[2]===undefined?{}:arguments[2];varcallback=arguments.length<=3||arguments[3]===undefined?function()/*err, msg*/{}:arguments[3];if(typeofoptions==="function"){// options is the callback
Client.prototype.getChannelLogs=functiongetChannelLogs(where){varlimit=arguments.length<=1||arguments[1]===undefined?500:arguments[1];varoptions=arguments.length<=2||arguments[2]===undefined?{}:arguments[2];varcallback=arguments.length<=3||arguments[3]===undefined?function()/*err, logs*/{}:arguments[3];if(typeofoptions==="function"){// options is the callback
Client.prototype.createChannel=functioncreateChannel(server,name){vartype=arguments.length<=2||arguments[2]===undefined?"text":arguments[2];varcallback=arguments.length<=3||arguments[3]===undefined?function()/*err, channel*/{}:arguments[3];if(typeoftype==="function"){// options is the callback
Client.prototype.banMember=functionbanMember(user,server){varlength=arguments.length<=2||arguments[2]===undefined?1:arguments[2];varcallback=arguments.length<=3||arguments[3]===undefined?function()/*err, {}*/{}:arguments[3];if(typeoflength==="function"){// length is the callback
Client.prototype.createRole=functioncreateRole(server){vardata=arguments.length<=1||arguments[1]===undefined?null:arguments[1];varcallback=arguments.length<=2||arguments[2]===undefined?function()/*err, role*/{}:arguments[2];if(typeofdata==="function"){// data is the callback
Client.prototype.updateRole=functionupdateRole(role){vardata=arguments.length<=1||arguments[1]===undefined?null:arguments[1];varcallback=arguments.length<=2||arguments[2]===undefined?function()/*err, role*/{}:arguments[2];if(typeofdata==="function"){// data is the callback
Client.prototype.createInvite=functioncreateInvite(chanServ,options){varcallback=arguments.length<=2||arguments[2]===undefined?function()/*err, invite*/{}:arguments[2];if(typeofoptions==="function"){// options is the callback
Client.prototype.setStatus=functionsetStatus(idleStatus,gameID){varcallback=arguments.length<=2||arguments[2]===undefined?function()/*err, {}*/{}:arguments[2];if(typeofgameID==="function"){// gameID is the callback
callback=gameID;}elseif(typeofidleStatus==="function"){// idleStatus is the callback
"use strict";exports.__esModule=true;var_createClass=(function(){functiondefineProperties(target,props){for(vari=0;i<props.length;i++){vardescriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"indescriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}returnfunction(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);returnConstructor;};})();function_interopRequireDefault(obj){returnobj&&obj.__esModule?obj:{"default":obj};}function_classCallCheck(instance,Constructor){if(!(instanceinstanceofConstructor)){thrownewTypeError("Cannot call a class as a function");}}var_superagent=require("superagent");var_superagent2=_interopRequireDefault(_superagent);var_ws=require("ws");var_ws2=_interopRequireDefault(_ws);var_ConnectionState=require("./ConnectionState");var_ConnectionState2=_interopRequireDefault(_ConnectionState);var_querystring=require("querystring");var_querystring2=_interopRequireDefault(_querystring);var_Constants=require("../Constants");var_UtilCache=require("../Util/Cache");var_UtilCache2=_interopRequireDefault(_UtilCache);var_ResolverResolver=require("./Resolver/Resolver");var_ResolverResolver2=_interopRequireDefault(_ResolverResolver);var_StructuresUser=require("../Structures/User");var_StructuresUser2=_interopRequireDefault(_StructuresUser);var_StructuresChannel=require("../Structures/Channel");var_StructuresChannel2=_interopRequireDefault(_StructuresChannel);var_StructuresTextChannel=require("../Structures/TextChannel");var_StructuresTextChannel2=_interopRequireDefault(_StructuresTextChannel);var_StructuresVoiceChannel=require("../Structures/VoiceChannel");var_StructuresVoiceChannel2=_interopRequireDefault(_StructuresVoiceChannel);var_StructuresPMChannel=require("../Structures/PMChannel");var_StructuresPMChannel2=_interopRequireDefault(_StructuresPMChannel);var_StructuresServer=require("../Structures/Server");var_StructuresServer2=_interopRequireDefault(_StructuresServer);var_StructuresMessage=require("../Structures/Message");var_StructuresMessage2=_interopRequireDefault(_StructuresMessage);var_StructuresRole=require("../Structures/Role");var_StructuresRole2=_interopRequireDefault(_StructuresRole);var_StructuresInvite=require("../Structures/Invite");var_StructuresInvite2=_interopRequireDefault(_StructuresInvite);var_VoiceVoiceConnection=require("../Voice/VoiceConnection");var_VoiceVoiceConnection2=_interopRequireDefault(_VoiceVoiceConnection);var_UtilTokenCacher=require("../Util/TokenCacher");var_UtilTokenCacher2=_interopRequireDefault(_UtilTokenCacher);varzlib;varlibVersion=require('../../package.json').version;functionwaitFor(condition){varvalue=arguments.length<=1||arguments[1]===undefined?condition:arguments[1];varinterval=arguments.length<=2||arguments[2]===undefined?20:arguments[2];return(function(){returnnewPromise(function(resolve){varint=setInterval(function(){varisDone=condition();if(isDone){if(condition===value){resolve(isDone);}else{resolve(value(isDone));}returnclearInterval(int);}},interval);});})();}functiondelay(ms){returnnewPromise(function(resolve){returnsetTimeout(resolve,ms);});}varInternalClient=(function(){functionInternalClient(discordClient){_classCallCheck(this,InternalClient);this.setup(discordClient);}InternalClient.prototype.apiRequest=functionapiRequest(method,url,useAuth,data,file){var_this=this,_arguments=arguments;varret=_superagent2["default"][method](url);if(useAuth){ret.set("authorization",this.token);}if(data){ret.send(data);}if(file){ret.attach("file",file.file,file.name);}ret.set('User-Agent',this.userAgentInfo.full);returnnewPromise(function(resolve,reject){ret.end(function(error,data){if(error){if(!_this.client.options.rate_limit_as_error&&error.response&&error.response.error&&error.response.error.status&&error.response.error.status===429){if(data.headers["retry-after"]||data.headers["Retry-After"]){vartoWait=data.headers["retry-after"]||data.headers["Retry-After"];toWait=parseInt(toWait);setTimeout(function(){_this.apiRequest.apply(_this,_arguments).then(resolve)["catch"](reject);},toWait);}else{returnreject(error);}}else{returnreject(error);}}else{resolve(data.body);}});});};InternalClient.prototype.setup=functionsetup(discordClient){discordClient=discordClient||this.client;this.client=discordClient;this.state=_ConnectionState2["default"].IDLE;this.websocket=null;this.userAgent={url:'https://github.com/hydrabolt/discord.js',version:require('../../package.json').version};if(this.client.options.compress){zlib=require("zlib");}// creates 4 caches with discriminators based on ID
InternalClient.prototype.joinVoiceChannel=functionjoinVoiceChannel(chann){var_this3=this;varchannel=this.resolver.resolveVoiceChannel(chann);if(!channel){returnPromise.reject(newError("voice channel does not exist"));}returnthis.leaveVoiceChannel().then(function(){returnnewPromise(function(resolve,reject){varsession,token,server=channel.server,endpoint;varcheck=functioncheck(m){vardata=JSON.parse(m);if(data.t==="VOICE_STATE_UPDATE"){session=data.d.session_id;}elseif(data.t==="VOICE_SERVER_UPDATE"){token=data.d.token;endpoint=data.d.endpoint;varchan=_this3.voiceConnection=new_VoiceVoiceConnection2["default"](channel,_this3.client,session,token,server,endpoint);chan.on("ready",function(){returnresolve(chan);});chan.on("error",reject);_this3.client.emit("debug","removed temporary voice websocket listeners");_this3.websocket.removeListener("message",check);}};_this3.websocket.on("message",check);_this3.sendWS({op:4,d:{"guild_id":server.id,"channel_id":channel.id,"self_mute":false,"self_deaf":false}});});});};// def createServer
InternalClient.prototype.createServer=functioncreateServer(name){var_this4=this;varregion=arguments.length<=1||arguments[1]===undefined?"london":arguments[1];name=this.resolver.resolveString(name);returnthis.apiRequest('post',_Constants.Endpoints.SERVERS,true,{name:name,region:region}).then(function(res){// valid server, wait until it is cached
InternalClient.prototype.joinServer=functionjoinServer(invite){var_this5=this;invite=this.resolver.resolveInviteID(invite);if(!invite){returnPromise.reject(newError("Not a valid invite"));}returnthis.apiRequest("post",_Constants.Endpoints.INVITE(invite),true).then(function(res){// valid server, wait until it is received via ws and cached
InternalClient.prototype.leaveServer=functionleaveServer(srv){var_this6=this;varserver=this.resolver.resolveServer(srv);if(!server){returnPromise.reject(newError("server did not resolve"));}returnthis.apiRequest("del",_Constants.Endpoints.SERVER(server.id),true).then(function(){// remove channels of server then the server
for(var_iterator2=server.channels,_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:_iterator2[Symbol.iterator]();;){var_ref2;if(_isArray2){if(_i2>=_iterator2.length)break;_ref2=_iterator2[_i2++];}else{_i2=_iterator2.next();if(_i2.done)break;_ref2=_i2.value;}varchan=_ref2;_this6.channels.remove(chan);}// remove server
_this6.servers.remove(server);});};// def login
InternalClient.prototype.login=functionlogin(email,password){var_this7=this;varclient=this.client;if(!this.tokenCacher.done){returnnewPromise(function(resolve,reject){setTimeout(function(){_this7.login(email,password).then(resolve)["catch"](reject);},20);});}else{vartk=this.tokenCacher.getToken(email,password);if(tk){this.client.emit("debug","bypassed direct API login, used cached token");this.state=_ConnectionState2["default"].LOGGED_IN;this.token=tk;this.email=email;this.password=password;returnthis.getGateway().then(function(url){_this7.createWS(url);returntk;});returnPromise.resolve(tk);}}if(this.state!==_ConnectionState2["default"].DISCONNECTED&&this.state!==_ConnectionState2["default"].IDLE){returnPromise.reject(newError("already logging in/logged in/ready!"));}this.state=_ConnectionState2["default"].LOGGING_IN;returnthis.apiRequest("post",_Constants.Endpoints.LOGIN,false,{email:email,password:password}).then(function(res){_this7.client.emit("debug","direct API login, cached token was unavailable");vartoken=res.token;_this7.tokenCacher.setToken(email,password,token);_this7.state=_ConnectionState2["default"].LOGGED_IN;_this7.token=token;_this7.email=email;_this7.password=password;return_this7.getGateway().then(function(url){_this7.createWS(url);returntoken;});},function(error){_this7.websocket=null;throwerror;})["catch"](function(error){_this7.state=_ConnectionState2["default"].DISCONNECTED;client.emit("disconnected");throwerror;});};// def logout
InternalClient.prototype.logout=functionlogout(){var_this8=this;if(this.state===_ConnectionState2["default"].DISCONNECTED||this.state===_ConnectionState2["default"].IDLE){returnPromise.reject(newError("Client is not logged in!"));}returnthis.apiRequest("post",_Constants.Endpoints.LOGOUT,true).then(function(){if(_this8.websocket){_this8.websocket.close();_this8.websocket=null;}_this8.token=null;_this8.email=null;_this8.password=null;_this8.state=_ConnectionState2["default"].DISCONNECTED;});};// def startPM
InternalClient.prototype.startPM=functionstartPM(resUser){var_this9=this;varuser=this.resolver.resolveUser(resUser);if(!user){returnPromise.reject(newError("Unable to resolve resUser to a User"));}// start the PM
InternalClient.prototype.deleteMessage=functiondeleteMessage(_message){var_this11=this;varoptions=arguments.length<=1||arguments[1]===undefined?{}:arguments[1];varmessage=this.resolver.resolveMessage(_message);if(!message){returnPromise.reject(newError("Supplied message did not resolve to a message!"));}varchain=options.wait?delay(options.wait):Promise.resolve();returnchain.then(function(){return_this11.apiRequest("del",_Constants.Endpoints.CHANNEL_MESSAGE(message.channel.id,message.id),true);}).then(function(){returnmessage.channel.messages.remove(message);});};// def updateMessage
InternalClient.prototype.updateMessage=functionupdateMessage(msg,_content){var_this12=this;varoptions=arguments.length<=2||arguments[2]===undefined?{}:arguments[2];varmessage=this.resolver.resolveMessage(msg);if(!message){returnPromise.reject(newError("Supplied message did not resolve to a message!"));}varcontent=this.resolver.resolveString(_content);returnthis.apiRequest("patch",_Constants.Endpoints.CHANNEL_MESSAGE(message.channel.id,message.id),true,{content:content,tts:options.tts}).then(function(res){returnmessage.channel.messages.update(message,new_StructuresMessage2["default"](res,message.channel,_this12.client));});};// def sendFile
InternalClient.prototype.addMemberToRole=functionaddMemberToRole(member,role){member=this.resolver.resolveUser(member);if(!member||!role){returnPromise.reject(newError("member/role not in server"));}if(!role.server.memberMap[member.id]){returnPromise.reject(newError("member not in server"));}varroleIDS=role.server.memberMap[member.id].roles.map(function(r){returnr.id;}).concat(role.id);returnthis.apiRequest("patch",_Constants.Endpoints.SERVER_MEMBERS(role.server.id)+"/"+member.id,true,{roles:roleIDS});};//def addMemberToRole
InternalClient.prototype.addMemberToRoles=functionaddMemberToRoles(member,roles){member=this.resolver.resolveUser(member);if(!member){returnPromise.reject(newError("member not in server"));}if(!Array.isArray(roles)||roles.length===0){returnPromise.reject(newError("invalid array of roles"));}varroleIDS=roles[0].server.memberMap[member.id].roles.map(function(r){returnr.id;});if(roles.any(function(role){return!role.server.memberMap[member.id];})){returnPromise.reject(newError("Role does not exist on same server as member"));}returnthis.apiRequest("patch",_Constants.Endpoints.SERVER_MEMBERS(role.server.id)+"/"+member.id,true,{roles:roleIDS});};//def removeMemberFromRole
InternalClient.prototype.removeMemberFromRole=functionremoveMemberFromRole(member,role){member=this.resolver.resolveUser(member);if(!member||!role){returnPromise.reject(newError("member/role not in server"));}if(!role.server.memberMap[member.id]){returnPromise.reject(newError("member not in server"));}varroleIDS=role.server.memberMap[member.id].roles.map(function(r){returnr.id;});for(variteminroleIDS){if(roleIDS[item]===role.id){roleIDS.splice(item,1);break;}}returnthis.apiRequest("patch",_Constants.Endpoints.SERVER_MEMBERS(role.server.id)+"/"+member.id,true,{roles:roleIDS});};//def removeMemberFromRoles
InternalClient.prototype.removeMemberFromRoles=functionremoveMemberFromRoles(member,roles){member=this.resolver.resolveUser(member);if(!member){returnPromise.reject(newError("member not in server"));}if(!Array.isArray(roles)||roles.length===0){returnPromise.reject(newError("invalid array of roles"));}varroleIDS=roles[0].server.memberMap[member.id].roles.map(function(r){returnr.id;});for(var_iterator4=roles,_isArray4=Array.isArray(_iterator4),_i4=0,_iterator4=_isArray4?_iterator4:_iterator4[Symbol.iterator]();;){var_ref4;if(_isArray4){if(_i4>=_iterator4.length)break;_ref4=_iterator4[_i4++];}else{_i4=_iterator4.next();if(_i4.done)break;_ref4=_i4.value;}varrole=_ref4;if(!role.server.memberMap[member.id]){returnPromise.reject(newError("member not in server"));}for(variteminroleIDS){if(roleIDS[item]===role.id){roleIDS.splice(item,1);break;}}}returnthis.apiRequest("patch",_Constants.Endpoints.SERVER_MEMBERS(role.server.id)+"/"+member.id,true,{roles:roleIDS});};// def createInvite
InternalClient.prototype.createInvite=functioncreateInvite(chanServ,options){var_this20=this;if(chanServinstanceof_StructuresChannel2["default"]){// do something
}elseif(chanServinstanceof_StructuresServer2["default"]){// do something
InternalClient.prototype.deleteInvite=functiondeleteInvite(invite){invite=this.resolver.resolveInviteID(invite);if(!invite){thrownewError("Not a valid invite");}returnthis.apiRequest("del",_Constants.Endpoints.INVITE(invite),true);};//def overwritePermissions
InternalClient.prototype.startTyping=functionstartTyping(channel){var_this23=this;returnthis.resolver.resolveChannel(channel).then(function(channel){if(_this23.intervals.typing[channel.id]){// typing interval already exists, leave it alone
thrownewError("Already typing in that channel");}_this23.intervals.typing[channel.id]=setInterval(function(){return_this23.sendTyping(channel)["catch"](function(error){return_this23.emit("error",error);});},4000);return_this23.sendTyping(channel);});};//def stopTyping
thrownewError("Not typing in that channel");}clearInterval(_this24.intervals.typing[channel.id]);_this24.intervals.typing[channel.id]=false;});};//def updateDetails
InternalClient.prototype.ack=functionack(msg){msg=this.resolver.resolveMessage(msg);if(!msg){Promise.reject(newError("Message does not exist"));}returnthis.apiRequest("post",_Constants.Endpoints.CHANNEL_MESSAGE(msg.channel.id,msg.id)+"/ack",true);};InternalClient.prototype.sendWS=functionsendWS(object){if(this.websocket){this.websocket.send(JSON.stringify(object));}};InternalClient.prototype.createWS=functioncreateWS(url){varself=this;varclient=self.client;if(this.websocket){returnfalse;}this.websocket=new_ws2["default"](url);this.websocket.onopen=function(){self.sendWS({op:2,d:{token:self.token,v:3,compress:self.client.options.compress,properties:{"$os":"discord.js","$browser":"discord.js","$device":"discord.js","$referrer":"discord.js","$referring_domain":"discord.js"}}});};this.websocket.onclose=function(){self.websocket=null;self.state=_ConnectionState2["default"].DISCONNECTED;self.disconnected();};this.websocket.onerror=function(e){client.emit("error",e);};this.websocket.onmessage=function(e){if(e.datainstanceofBuffer){if(!zlib)zlib=require("zlib");e.data=zlib.inflateSync(e.data).toString();}varpacket,data;try{packet=JSON.parse(e.data);data=packet.d;}catch(e){client.emit("error",e);return;}client.emit("raw",packet);switch(packet.t){case_Constants.PacketType.READY:varstartTime=Date.now();self.intervals.kai=setInterval(function(){returnself.sendWS({op:1,d:Date.now()});},data.heartbeat_interval);self.user=self.users.add(new_StructuresUser2["default"](data.user,client));data.guilds.forEach(function(server){self.servers.add(new_StructuresServer2["default"](server,client));});data.private_channels.forEach(function(pm){self.private_channels.add(new_StructuresPMChannel2["default"](pm,client));});self.state=_ConnectionState2["default"].READY;client.emit("ready");client.emit("debug","ready packet took "+(Date.now()-startTime)+"ms to process");client.emit("debug","ready with "+self.servers.length+" servers, "+self.channels.length+" channels and "+self.users.length+" users cached.");self.readyTime=Date.now();break;case_Constants.PacketType.MESSAGE_CREATE:// format: https://discordapi.readthedocs.org/en/latest/reference/channels/messages.html#message-format
varchannel=self.channels.get("id",data.channel_id)||self.private_channels.get("id",data.channel_id);if(channel){varmsg=channel.messages.add(new_StructuresMessage2["default"](data,channel,client));if(self.messageAwaits[channel.id+msg.author.id]){self.messageAwaits[channel.id+msg.author.id].map(function(fn){returnfn(msg);});self.messageAwaits[channel.id+msg.author.id]=null;client.emit("message",msg,true);//2nd param is isAwaitedMessage
}else{client.emit("message",msg);}self.ack(msg);}else{client.emit("warn","message created but channel is not cached");}break;case_Constants.PacketType.MESSAGE_DELETE:// format https://discordapi.readthedocs.org/en/latest/reference/channels/messages.html#message-delete
varmsg=channel.messages.get("id",data.id);client.emit("messageDeleted",msg,channel);if(msg){channel.messages.remove(msg);}}else{client.emit("warn","message was deleted but channel is not cached");}break;case_Constants.PacketType.MESSAGE_UPDATE:// format https://discordapi.readthedocs.org/en/latest/reference/channels/messages.html#message-format
varmsg=channel.messages.get("id",data.id);if(msg){// old message exists
data.nonce=data.nonce||msg.nonce;data.attachments=data.attachments||msg.attachments;data.tts=data.tts||msg.tts;data.embeds=data.embeds||msg.embeds;data.timestamp=data.timestamp||msg.timestamp;data.mention_everyone=data.mention_everyone||msg.everyoneMentioned;data.content=data.content||msg.content;data.mentions=data.mentions||msg.mentions;data.author=data.author||msg.author;varnmsg=channel.messages.update(msg,new_StructuresMessage2["default"](data,channel,client));client.emit("messageUpdated",nmsg,msg);}}else{client.emit("warn","message was updated but channel is not cached");}break;case_Constants.PacketType.SERVER_CREATE:varserver=self.servers.get("id",data.id);if(!server){server=new_StructuresServer2["default"](data,client);self.servers.add(server);client.emit("serverCreated",server);}break;case_Constants.PacketType.SERVER_DELETE:varserver=self.servers.get("id",data.id);if(server){for(var_iterator5=server.channels,_isArray5=Array.isArray(_iterator5),_i5=0,_iterator5=_isArray5?_iterator5:_iterator5[Symbol.iterator]();;){var_ref5;if(_isArray5){if(_i5>=_iterator5.length)break;_ref5=_iterator5[_i5++];}else{_i5=_iterator5.next();if(_i5.done)break;_ref5=_i5.value;}varchannel=_ref5;self.channels.remove(channel);}self.servers.remove(server);client.emit("serverDeleted",server);}else{client.emit("warn","server was deleted but it was not in the cache");}break;case_Constants.PacketType.SERVER_UPDATE:varserver=self.servers.get("id",data.id);if(server){// server exists
data.members=data.members||[];data.channels=data.channels||[];varnewserver=new_StructuresServer2["default"](data,self);newserver.members=server.members;newserver.memberMap=server.memberMap;newserver.channels=server.channels;if(newserver.equalsStrict(server)){// already the same don't do anything
client.emit("debug","received server update but server already updated");}else{self.servers.update(server,newserver);client.emit("serverUpdated",server,newserver);}}elseif(!server){client.emit("warn","server was updated but it was not in the cache");self.servers.add(new_StructuresServer2["default"](data,self));client.emit("serverCreated",server);}break;case_Constants.PacketType.CHANNEL_CREATE:varchannel=self.channels.get("id",data.id);if(!channel){varserver=self.servers.get("id",data.guild_id);if(server){varchan=null;if(data.type==="text"){chan=self.channels.add(new_StructuresTextChannel2["default"](data,client,server));}else{chan=self.channels.add(new_StructuresVoiceChannel2["default"](data,client,server));}client.emit("channelCreated",server.channels.add(chan));}elseif(data.is_private){client.emit("channelCreated",self.private_channels.add(new_StructuresPMChannel2["default"](data,client)));}else{client.emit("warn","channel created but server does not exist");}}else{client.emit("warn","channel created but already in cache");}break;case_Constants.PacketType.CHANNEL_DELETE:varchannel=self.channels.get("id",data.id);if(channel){if(channel.server)// accounts for PMs
channel.server.channels.remove(channel);self.channels.remove(channel);client.emit("channelDeleted",channel);}else{client.emit("warn","channel deleted but already out of cache?");}break;case_Constants.PacketType.CHANNEL_UPDATE:varchannel=self.channels.get("id",data.id)||self.private_channels.get("id",data.id);if(channel){if(channelinstanceof_StructuresPMChannel2["default"]){//PM CHANNEL
varchan=new_StructuresVoiceChannel2["default"](data,client,channel.server);channel.server.channels.update(channel,chan);self.channels.update(channel,chan);client.emit("channelUpdated",channel,chan);}}else{client.emit("warn","channel updated but server non-existant");}}}else{client.emit("warn","channel updated but not in cache");}break;case_Constants.PacketType.SERVER_ROLE_CREATE:varserver=self.servers.get("id",data.guild_id);if(server){client.emit("serverRoleCreated",server.roles.add(new_StructuresRole2["default"](data.role,server,client)),server);}else{client.emit("warn","server role made but server not in cache");}break;case_Constants.PacketType.SERVER_ROLE_DELETE:varserver=self.servers.get("id",data.guild_id);if(server){varrole=server.roles.get("id",data.role_id);if(role){server.roles.remove(role);client.emit("serverRoleDeleted",role);}else{client.emit("warn","server role deleted but role not in cache");}}else{client.emit("warn","server role deleted but server not in cache");}break;case_Constants.PacketType.SERVER_ROLE_UPDATE:varserver=self.servers.get("id",data.guild_id);if(server){varrole=server.roles.get("id",data.role.id);if(role){varnewRole=new_StructuresRole2["default"](data.role,server,client);server.roles.update(role,newRole);client.emit("serverRoleUpdated",role,newRole);}else{client.emit("warn","server role updated but role not in cache");}}else{client.emit("warn","server role updated but server not in cache");}break;case_Constants.PacketType.SERVER_MEMBER_ADD:varserver=self.servers.get("id",data.guild_id);if(server){server.memberMap[data.user.id]={roles:data.roles.map(function(pid){returnserver.roles.get("id",pid);}),mute:false,deaf:false,joinedAt:Date.parse(data.joined_at)};client.emit("serverNewMember",server,server.members.add(self.users.add(new_StructuresUser2["default"](data.user,client))));}else{client.emit("warn","server member added but server doesn't exist in cache");}break;case_Constants.PacketType.SERVER_MEMBER_REMOVE:varserver=self.servers.get("id",data.guild_id);if(server){varuser=self.users.get("id",data.user.id);if(user){server.memberMap[data.user.id]=null;server.members.remove(user);client.emit("serverMemberRemoved",server,user);}else{client.emit("warn","server member removed but user doesn't exist in cache");}}else{client.emit("warn","server member removed but server doesn't exist in cache");}break;case_Constants.PacketType.SERVER_MEMBER_UPDATE:varserver=self.servers.get("id",data.guild_id);if(server){varuser=self.users.get("id",data.user.id);if(user){server.memberMap[data.user.id].roles=data.roles.map(function(pid){returnserver.roles.get("id",pid);});server.memberMap[data.user.id].mute=data.mute;server.memberMap[data.user.id].deaf=data.deaf;client.emit("serverMemberUpdated",server,user);}else{client.emit("warn","server member removed but user doesn't exist in cache");}}else{client.emit("warn","server member updated but server doesn't exist in cache");}break;case_Constants.PacketType.PRESENCE_UPDATE:varuser=self.users.get("id",data.user.id);if(user){data.user.username=data.user.username||user.username;data.user.id=data.user.id||user.id;data.user.avatar=data.user.avatar||user.avatar;data.user.discriminator=data.user.discriminator||user.discriminator;varpresenceUser=new_StructuresUser2["default"](data.user,client);if(presenceUser.equals(user)){// a real presence update
user.status=data.status;user.gameID=data.game_id;client.emit("presence",user,data.status,data.game_id);}else{// a name change or avatar change
client.emit("userUpdated",user,presenceUser);self.users.update(user,presenceUser);}}else{client.emit("warn","presence update but user not in cache");}break;case_Constants.PacketType.TYPING:varuser=self.users.get("id",data.user_id);varchannel=self.channels.get("id",data.channel_id)||self.private_channels.get("id",data.channel_id);if(user&&channel){if(user.typing.since){user.typing.since=Date.now();user.typing.channel=channel;}else{user.typing.since=Date.now();user.typing.channel=channel;client.emit("userTypingStarted",user,channel);}setTimeout(function(){if(Date.now()-user.typing.since>5500){// they haven't typed since
user.typing.since=null;user.typing.channel=null;client.emit("userTypingStopped",user,channel);}},6000);}else{client.emit("warn","user typing but user or channel not existant in cache");}break;case_Constants.PacketType.SERVER_BAN_ADD:varuser=self.users.get("id",data.user.id);varserver=self.servers.get("id",data.guild_id);if(user&&server){client.emit("userBanned",user,server);}else{client.emit("warn","user banned but user/server not in cache.");}break;case_Constants.PacketType.SERVER_BAN_REMOVE:varuser=self.users.get("id",data.user.id);varserver=self.servers.get("id",data.guild_id);if(user&&server){client.emit("userUnbanned",user,server);}else{client.emit("warn","user unbanned but user/server not in cache.");}break;case_Constants.PacketType.VOICE_STATE_UPDATE:varuser=self.users.get("id",data.user_id);varserver=self.servers.get("id",data.guild_id);if(user&&server){if(data.channel_id){// speaking
varchannel=self.channels.get("id",data.channel_id);if(channel){if(server.eventStartSpeaking(user,channel))client.emit("voiceJoin",user,channel);elseclient.emit("warn","voice state error occurred in adding");}else{client.emit("warn","voice state channel not in cache");}}else{// not speaking
client.emit("voiceLeave",user,server.eventStopSpeaking(user));}}else{client.emit("warn","voice state update but user or server not in cache");}break;default:client.emit("unknown",packet);break;}};};_createClass(InternalClient,[{key:"uptime",get:functionget(){returnthis.readyTime?Date.now()-this.readyTime:null;}},{key:"userAgent",set:functionset(info){info.full="DiscordBot ("+info.url+", "+info.version+")";this.userAgentInfo=info;},get:functionget(){returnthis.userAgentInfo;}}]);returnInternalClient;})();exports["default"]=InternalClient;module.exports=exports["default"];
"use strict";/* global Buffer */exports.__esModule=true;function_interopRequireDefault(obj){returnobj&&obj.__esModule?obj:{"default":obj};}function_classCallCheck(instance,Constructor){if(!(instanceinstanceofConstructor)){thrownewTypeError("Cannot call a class as a function");}}var_fs=require("fs");var_fs2=_interopRequireDefault(_fs);var_StructuresUser=require("../../Structures/User");var_StructuresUser2=_interopRequireDefault(_StructuresUser);var_StructuresChannel=require("../../Structures/Channel");var_StructuresChannel2=_interopRequireDefault(_StructuresChannel);var_StructuresTextChannel=require("../../Structures/TextChannel");var_StructuresTextChannel2=_interopRequireDefault(_StructuresTextChannel);var_StructuresVoiceChannel=require("../../Structures/VoiceChannel");var_StructuresVoiceChannel2=_interopRequireDefault(_StructuresVoiceChannel);var_StructuresServerChannel=require("../../Structures/ServerChannel");var_StructuresServerChannel2=_interopRequireDefault(_StructuresServerChannel);var_StructuresPMChannel=require("../../Structures/PMChannel");var_StructuresPMChannel2=_interopRequireDefault(_StructuresPMChannel);var_StructuresServer=require("../../Structures/Server");var_StructuresServer2=_interopRequireDefault(_StructuresServer);var_StructuresMessage=require("../../Structures/Message");var_StructuresMessage2=_interopRequireDefault(_StructuresMessage);var_StructuresInvite=require("../../Structures/Invite");var_StructuresInvite2=_interopRequireDefault(_StructuresInvite);varResolver=(function(){functionResolver(internal){_classCallCheck(this,Resolver);this.internal=internal;}Resolver.prototype.resolveToBase64=functionresolveToBase64(resource){if(resourceinstanceofBuffer){resource=resource.toString("base64");resource="data:image/jpg;base64,"+resource;}returnresource;};Resolver.prototype.resolveInviteID=functionresolveInviteID(resource){if(resourceinstanceof_StructuresInvite2["default"]){returnresource.id;}if(typeofresource==="string"||resourceinstanceofString){if(resource.indexOf("http")===0){varsplit=resource.split("/");returnsplit.pop();}returnresource;}returnnull;};Resolver.prototype.resolveServer=functionresolveServer(resource){if(resourceinstanceof_StructuresServer2["default"]){returnresource;}if(resourceinstanceof_StructuresServerChannel2["default"]){returnresource.server;}if(resourceinstanceofString||typeofresource==="string"){returnthis.internal.servers.get("id",resource);}if(resourceinstanceof_StructuresMessage2["default"]){if(resource.channelinstanceof_StructuresTextChannel2["default"]){returnresource.server;}}returnnull;};Resolver.prototype.resolveFile=functionresolveFile(resource){if(typeofresource==="string"||resourceinstanceofString){return_fs2["default"].createReadStream(resource);}returnresource;};Resolver.prototype.resolveMentions=functionresolveMentions(resource){// resource is a string
var_mentions=[];varchanged=resource;for(var_iterator=resource.match(/<@[^>]*>/g)||[],_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:_iterator[Symbol.iterator]();;){var_ref;if(_isArray){if(_i>=_iterator.length)break;_ref=_iterator[_i++];}else{_i=_iterator.next();if(_i.done)break;_ref=_i.value;}varmention=_ref;varuserID=mention.substring(2,mention.length-1);_mentions.push(userID);changed=changed.replace(newRegExp(mention,"g"),"@"+this.internal.client.users.get("id",userID).username);}return[_mentions,changed];};Resolver.prototype.resolveString=functionresolveString(resource){// accepts Array, Channel, Server, User, Message, String and anything
accepts a Message, Channel, Server, String ID, User, PMChannel
*/if(resourceinstanceof_StructuresUser2["default"]){returnresource;}if(resourceinstanceof_StructuresMessage2["default"]){returnresource.author;}if(resourceinstanceof_StructuresTextChannel2["default"]){varlmsg=resource.lastMessage;if(lmsg){returnlmsg.author;}}if(resourceinstanceof_StructuresServer2["default"]){returnresource.owner;}if(resourceinstanceof_StructuresPMChannel2["default"]){returnresource.recipient;}if(resourceinstanceofString||typeofresource==="string"){returnthis.internal.users.get("id",resource);}returnnull;};Resolver.prototype.resolveMessage=functionresolveMessage(resource){// accepts a Message, PMChannel & TextChannel
if(resourceinstanceof_StructuresTextChannel2["default"]||resourceinstanceof_StructuresPMChannel2["default"]){returnresource.lastMessage;}if(resourceinstanceof_StructuresMessage2["default"]){returnresource;}returnnull;};Resolver.prototype.resolveVoiceChannel=functionresolveVoiceChannel(resource){// resolveChannel will also work but this is more apt
accepts a Message, Channel, Server, String ID, User
*/if(resourceinstanceof_StructuresMessage2["default"]){returnPromise.resolve(resource.channel);}if(resourceinstanceof_StructuresChannel2["default"]){returnPromise.resolve(resource);}if(resourceinstanceof_StructuresServer2["default"]){returnPromise.resolve(resource.channels.get("id",resource.id));}if(resourceinstanceofString||typeofresource==="string"){returnPromise.resolve(this.internal.channels.get("id",resource));}if(resourceinstanceof_StructuresUser2["default"]){// see if a PM exists
varchatFound=this.internal.private_channels.find(function(pmchat){returnpmchat.recipient.equals(resource);});if(chatFound){// a PM already exists!
returnPromise.resolve(chatFound);}// PM does not exist :\
returnthis.internal.startPM(resource);}varerror=newError("Could not resolve channel");error.resource=resource;returnPromise.reject(error);};returnResolver;})();exports["default"]=Resolver;module.exports=exports["default"];
CHANNELS:API+"/channels",CHANNEL:functionCHANNEL(channelID){returnEndpoints.CHANNELS+"/"+channelID;},CHANNEL_MESSAGES:functionCHANNEL_MESSAGES(channelID){returnEndpoints.CHANNEL(channelID)+"/messages";},CHANNEL_INVITES:functionCHANNEL_INVITES(channelID){returnEndpoints.CHANNEL(channelID)+"/invites";},CHANNEL_TYPING:functionCHANNEL_TYPING(channelID){returnEndpoints.CHANNEL(channelID)+"/typing";},CHANNEL_PERMISSIONS:functionCHANNEL_PERMISSIONS(channelID){returnEndpoints.CHANNEL(channelID)+"/permissions";},CHANNEL_MESSAGE:functionCHANNEL_MESSAGE(channelID,messageID){returnEndpoints.CHANNEL_MESSAGES(channelID)+"/"+messageID;}};exports.Endpoints=Endpoints;varPermissions={// general
createInstantInvite:1<<0,kickMembers:1<<1,banMembers:1<<2,manageRoles:1<<3,managePermissions:1<<3,manageChannels:1<<4,manageChannel:1<<4,manageServer:1<<5,// text
"use strict";exports.__esModule=true;var_createClass=(function(){functiondefineProperties(target,props){for(vari=0;i<props.length;i++){vardescriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"indescriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}returnfunction(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);returnConstructor;};})();function_interopRequireDefault(obj){returnobj&&obj.__esModule?obj:{"default":obj};}function_classCallCheck(instance,Constructor){if(!(instanceinstanceofConstructor)){thrownewTypeError("Cannot call a class as a function");}}function_inherits(subClass,superClass){if(typeofsuperClass!=="function"&&superClass!==null){thrownewTypeError("Super expression must either be null or a function, not "+typeofsuperClass);}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var_UtilEquality=require("../Util/Equality");var_UtilEquality2=_interopRequireDefault(_UtilEquality);var_UtilArgumentRegulariser=require("../Util/ArgumentRegulariser");varChannel=(function(_Equality){_inherits(Channel,_Equality);functionChannel(data,client){_classCallCheck(this,Channel);_Equality.call(this);this.id=data.id;this.client=client;}Channel.prototype["delete"]=function_delete(){returnthis.client.deleteChannel.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};_createClass(Channel,[{key:"isPrivate",get:functionget(){return!this.server;}}]);returnChannel;})(_UtilEquality2["default"]);exports["default"]=Channel;module.exports=exports["default"];
"use strict";exports.__esModule=true;function_classCallCheck(instance,Constructor){if(!(instanceinstanceofConstructor)){thrownewTypeError("Cannot call a class as a function");}}var_Constants=require("../Constants");varChannelPermissions=(function(){functionChannelPermissions(permissions){_classCallCheck(this,ChannelPermissions);this.permissions=permissions;}ChannelPermissions.prototype.serialise=functionserialise(explicit){var_this=this;varhp=functionhp(perm){return_this.hasPermission(perm,explicit);};return{// general
createInstantInvite:hp(_Constants.Permissions.createInstantInvite),kickMembers:hp(_Constants.Permissions.kickMembers),banMembers:hp(_Constants.Permissions.banMembers),managePermissions:hp(_Constants.Permissions.managePermissions),manageChannel:hp(_Constants.Permissions.manageChannel),manageServer:hp(_Constants.Permissions.manageServer),// text
"use strict";exports.__esModule=true;function_classCallCheck(instance,Constructor){if(!(instanceinstanceofConstructor)){thrownewTypeError("Cannot call a class as a function");}}varInvite=(function(){functionInvite(data,chan,client){_classCallCheck(this,Invite);this.maxAge=data.max_age;this.code=data.code;this.server=chan.server;this.channel=chan;this.revoked=data.revoked;this.createdAt=Date.parse(data.created_at);this.temporary=data.temporary;this.uses=data.uses;this.maxUses=data.uses;this.inviter=client.internal.users.get("id",data.inviter.id);this.xkcd=data.xkcdpass;}Invite.prototype.toString=functiontoString(){return"https://discord.gg/"+this.code;};Invite.prototype["delete"]=function_delete(){returnthis.client.deleteInvite.apply(this.client,reg(this,arguments));};Invite.prototype.join=functionjoin(){returnthis.client.joinServer.apply(this.client,reg(this,arguments));};returnInvite;})();exports["default"]=Invite;module.exports=exports["default"];
"use strict";exports.__esModule=true;var_createClass=(function(){functiondefineProperties(target,props){for(vari=0;i<props.length;i++){vardescriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"indescriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}returnfunction(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);returnConstructor;};})();function_interopRequireDefault(obj){returnobj&&obj.__esModule?obj:{"default":obj};}function_classCallCheck(instance,Constructor){if(!(instanceinstanceofConstructor)){thrownewTypeError("Cannot call a class as a function");}}function_inherits(subClass,superClass){if(typeofsuperClass!=="function"&&superClass!==null){thrownewTypeError("Super expression must either be null or a function, not "+typeofsuperClass);}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var_UtilCache=require("../Util/Cache");var_UtilCache2=_interopRequireDefault(_UtilCache);var_User=require("./User");var_User2=_interopRequireDefault(_User);var_UtilArgumentRegulariser=require("../Util/ArgumentRegulariser");var_UtilEquality=require("../Util/Equality");var_UtilEquality2=_interopRequireDefault(_UtilEquality);varMessage=(function(_Equality){_inherits(Message,_Equality);functionMessage(data,channel,client){var_this=this;_classCallCheck(this,Message);_Equality.call(this);this.channel=channel;this.client=client;this.nonce=data.nonce;this.attachments=data.attachments;this.tts=data.tts;this.embeds=data.embeds;this.timestamp=Date.parse(data.timestamp);this.everyoneMentioned=data.mention_everyone;this.id=data.id;if(data.edited_timestamp)this.editedTimestamp=Date.parse(data.edited_timestamp);if(data.authorinstanceof_User2["default"])this.author=data.author;elsethis.author=client.internal.users.add(new_User2["default"](data.author,client));this.content=data.content;this.mentions=new_UtilCache2["default"]();data.mentions.forEach(function(mention){// this is .add and not .get because it allows the bot to cache
// users from messages from logs who may have left the server and were
"use strict";exports.__esModule=true;var_createClass=(function(){functiondefineProperties(target,props){for(vari=0;i<props.length;i++){vardescriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"indescriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}returnfunction(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);returnConstructor;};})();function_interopRequireDefault(obj){returnobj&&obj.__esModule?obj:{"default":obj};}function_classCallCheck(instance,Constructor){if(!(instanceinstanceofConstructor)){thrownewTypeError("Cannot call a class as a function");}}function_inherits(subClass,superClass){if(typeofsuperClass!=="function"&&superClass!==null){thrownewTypeError("Super expression must either be null or a function, not "+typeofsuperClass);}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var_Channel2=require("./Channel");var_Channel3=_interopRequireDefault(_Channel2);var_User=require("./User");var_User2=_interopRequireDefault(_User);var_UtilCache=require("../Util/Cache");var_UtilCache2=_interopRequireDefault(_UtilCache);var_UtilArgumentRegulariser=require("../Util/ArgumentRegulariser");varPMChannel=(function(_Channel){_inherits(PMChannel,_Channel);functionPMChannel(data,client){_classCallCheck(this,PMChannel);_Channel.call(this,data,client);this.type=data.type||"text";this.lastMessageId=data.last_message_id;this.messages=new_UtilCache2["default"]("id",1000);this.recipient=this.client.internal.users.add(new_User2["default"](data.recipient,this.client));}/* warning! may return null */PMChannel.prototype.toString=functiontoString(){returnthis.recipient.toString();};PMChannel.prototype.sendMessage=functionsendMessage(){returnthis.client.sendMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};PMChannel.prototype.send=functionsend(){returnthis.client.sendMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};PMChannel.prototype.sendTTSMessage=functionsendTTSMessage(){returnthis.client.sendTTSMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};PMChannel.prototype.sendTTS=functionsendTTS(){returnthis.client.sendTTSMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};PMChannel.prototype.sendFile=functionsendFile(){returnthis.client.sendFile.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};PMChannel.prototype.startTyping=functionstartTyping(){returnthis.client.startTyping.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};PMChannel.prototype.stopTyping=functionstopTyping(){returnthis.client.stopTyping.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};PMChannel.prototype.getLogs=functiongetLogs(){returnthis.client.getChannelLogs.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};_createClass(PMChannel,[{key:"lastMessage",get:functionget(){returnthis.messages.get("id",this.lastMessageID);}}]);returnPMChannel;})(_Channel3["default"]);exports["default"]=PMChannel;module.exports=exports["default"];
"use strict";exports.__esModule=true;var_createClass=(function(){functiondefineProperties(target,props){for(vari=0;i<props.length;i++){vardescriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"indescriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}returnfunction(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);returnConstructor;};})();function_classCallCheck(instance,Constructor){if(!(instanceinstanceofConstructor)){thrownewTypeError("Cannot call a class as a function");}}var_Constants=require("../Constants");varPermissionOverwrite=(function(){functionPermissionOverwrite(data){_classCallCheck(this,PermissionOverwrite);this.id=data.id;this.type=data.type;// member or role
this.deny=data.deny;this.allow=data.allow;}// returns an array of allowed permissions
PermissionOverwrite.prototype.setAllowed=functionsetAllowed(allowedArray){var_this=this;allowedArray.forEach(function(permission){if(permissioninstanceofString||typeofpermission==="string"){permission=_Constants.Permissions[permission];}if(permission){_this.allow|=1<<permission;}});};PermissionOverwrite.prototype.setDenied=functionsetDenied(deniedArray){var_this2=this;deniedArray.forEach(function(permission){if(permissioninstanceofString||typeofpermission==="string"){permission=_Constants.Permissions[permission];}if(permission){_this2.deny|=1<<permission;}});};_createClass(PermissionOverwrite,[{key:"allowed",get:functionget(){varallowed=[];for(varpermNamein_Constants.Permissions){if(permName==="manageRoles"||permName==="manageChannels"){// these permissions do not exist in overwrites.
continue;}if(!!(this.allow&_Constants.Permissions[permName])){allowed.push(permName);}}returnallowed;}// returns an array of denied permissions
},{key:"denied",get:functionget(){vardenied=[];for(varpermNamein_Constants.Permissions){if(permName==="manageRoles"||permName==="manageChannels"){// these permissions do not exist in overwrites.
"use strict";exports.__esModule=true;function_classCallCheck(instance,Constructor){if(!(instanceinstanceofConstructor)){thrownewTypeError("Cannot call a class as a function");}}var_Constants=require("../Constants");var_UtilArgumentRegulariser=require("../Util/ArgumentRegulariser");/*
example data
{ position: -1,
permissions: 36953089,
name: '@everyone',
managed: false,
id: '110007368451915776',
hoist: false,
color: 0 }
*/varDefaultRole=[_Constants.Permissions.createInstantInvite,_Constants.Permissions.readMessages,_Constants.Permissions.readMessageHistory,_Constants.Permissions.sendMessages,_Constants.Permissions.sendTTSMessages,_Constants.Permissions.embedLinks,_Constants.Permissions.attachFiles,_Constants.Permissions.readMessageHistory,_Constants.Permissions.mentionEveryone,_Constants.Permissions.voiceConnect,_Constants.Permissions.voiceSpeak,_Constants.Permissions.voiceUseVAD].reduce(function(previous,current){returnprevious|current;},0);varRole=(function(){functionRole(data,server,client){_classCallCheck(this,Role);this.position=data.position||-1;this.permissions=data.permissions||(data.name==="@everyone"?DefaultRole:0);this.name=data.name||"@everyone";this.managed=data.managed||false;this.id=data.id;this.hoist=data.hoist||false;this.color=data.color||0;this.server=server;this.client=client;}Role.prototype.serialise=functionserialise(explicit){var_this=this;varhp=functionhp(perm){return_this.hasPermission(perm,explicit);};return{// general
createInstantInvite:hp(_Constants.Permissions.createInstantInvite),kickMembers:hp(_Constants.Permissions.kickMembers),banMembers:hp(_Constants.Permissions.banMembers),manageRoles:hp(_Constants.Permissions.manageRoles),manageChannels:hp(_Constants.Permissions.manageChannels),manageServer:hp(_Constants.Permissions.manageServer),// text
"use strict";exports.__esModule=true;function_interopRequireDefault(obj){returnobj&&obj.__esModule?obj:{"default":obj};}function_classCallCheck(instance,Constructor){if(!(instanceinstanceofConstructor)){thrownewTypeError("Cannot call a class as a function");}}function_inherits(subClass,superClass){if(typeofsuperClass!=="function"&&superClass!==null){thrownewTypeError("Super expression must either be null or a function, not "+typeofsuperClass);}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var_Channel2=require("./Channel");var_Channel3=_interopRequireDefault(_Channel2);var_UtilCache=require("../Util/Cache");var_UtilCache2=_interopRequireDefault(_UtilCache);var_PermissionOverwrite=require("./PermissionOverwrite");var_PermissionOverwrite2=_interopRequireDefault(_PermissionOverwrite);var_ChannelPermissions=require("./ChannelPermissions");var_ChannelPermissions2=_interopRequireDefault(_ChannelPermissions);var_UtilArgumentRegulariser=require("../Util/ArgumentRegulariser");varServerChannel=(function(_Channel){_inherits(ServerChannel,_Channel);functionServerChannel(data,client,server){var_this=this;_classCallCheck(this,ServerChannel);_Channel.call(this,data,client);this.name=data.name;this.type=data.type;this.position=data.position;this.permissionOverwrites=new_UtilCache2["default"]();this.server=server;data.permission_overwrites.forEach(function(permission){_this.permissionOverwrites.add(new_PermissionOverwrite2["default"](permission));});}ServerChannel.prototype.permissionsOf=functionpermissionsOf(user){user=this.client.internal.resolver.resolveUser(user);if(user){if(this.server.owner.equals(user)){returnnew_ChannelPermissions2["default"](4294967295);}vareveryoneRole=this.server.roles.get("name","@everyone");varuserRoles=[everyoneRole].concat(this.server.rolesOf(user)||[]);varuserRolesID=userRoles.map(function(v){returnv.id;});varroleOverwrites=[],memberOverwrites=[];this.permissionOverwrites.forEach(function(overwrite){if(overwrite.type==="member"&&overwrite.id===user.id){memberOverwrites.push(overwrite);}elseif(overwrite.type==="role"&&overwrite.idinuserRolesID){roleOverwrites.push(overwrite);}});varpermissions=0;for(var_iterator=userRoles,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:_iterator[Symbol.iterator]();;){var_ref;if(_isArray){if(_i>=_iterator.length)break;_ref=_iterator[_i++];}else{_i=_iterator.next();if(_i.done)break;_ref=_i.value;}varserverRole=_ref;permissions|=serverRole.permissions;}for(var_iterator2=roleOverwrites.concat(memberOverwrites),_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:_iterator2[Symbol.iterator]();;){var_ref2;if(_isArray2){if(_i2>=_iterator2.length)break;_ref2=_iterator2[_i2++];}else{_i2=_iterator2.next();if(_i2.done)break;_ref2=_i2.value;}varoverwrite=_ref2;permissions=permissions&~overwrite.deny;permissions=permissions|overwrite.allow;}returnnew_ChannelPermissions2["default"](permissions);}else{returnnull;}};ServerChannel.prototype.permsOf=functionpermsOf(user){returnthis.permissionsOf(user);};ServerChannel.prototype.mention=functionmention(){return"<#"+this.id+">";};ServerChannel.prototype.toString=functiontoString(){returnthis.mention();};ServerChannel.prototype.setName=functionsetName(){returnthis.client.setChannelName.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};ServerChannel.prototype.setPosition=functionsetPosition(){returnthis.client.setChannelPosition.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};returnServerChannel;})(_Channel3["default"]);exports["default"]=ServerChannel;module.exports=exports["default"];
"use strict";exports.__esModule=true;var_createClass=(function(){functiondefineProperties(target,props){for(vari=0;i<props.length;i++){vardescriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"indescriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}returnfunction(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);returnConstructor;};})();function_interopRequireDefault(obj){returnobj&&obj.__esModule?obj:{"default":obj};}function_classCallCheck(instance,Constructor){if(!(instanceinstanceofConstructor)){thrownewTypeError("Cannot call a class as a function");}}function_inherits(subClass,superClass){if(typeofsuperClass!=="function"&&superClass!==null){thrownewTypeError("Super expression must either be null or a function, not "+typeofsuperClass);}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var_ServerChannel2=require("./ServerChannel");var_ServerChannel3=_interopRequireDefault(_ServerChannel2);var_UtilCache=require("../Util/Cache");var_UtilCache2=_interopRequireDefault(_UtilCache);var_UtilArgumentRegulariser=require("../Util/ArgumentRegulariser");varTextChannel=(function(_ServerChannel){_inherits(TextChannel,_ServerChannel);functionTextChannel(data,client,server){_classCallCheck(this,TextChannel);_ServerChannel.call(this,data,client,server);this.topic=data.topic;this.lastMessageID=data.last_message_id;this.messages=new_UtilCache2["default"]("id",client.options.maximumMessages);}/* warning! may return null */TextChannel.prototype.setTopic=functionsetTopic(){returnthis.client.setChannelTopic.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.setNameAndTopic=functionsetNameAndTopic(){returnthis.client.setChannelNameAndTopic.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.update=functionupdate(){returnthis.client.updateChannel.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.sendMessage=functionsendMessage(){returnthis.client.sendMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.send=functionsend(){returnthis.client.sendMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.sendTTSMessage=functionsendTTSMessage(){returnthis.client.sendTTSMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.sendTTS=functionsendTTS(){returnthis.client.sendTTSMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.sendFile=functionsendFile(){returnthis.client.sendFile.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.getLogs=functiongetLogs(){returnthis.client.getChannelLogs.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.startTyping=functionstartTyping(){returnthis.client.startTyping.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.stopTyping=functionstopTyping(){returnthis.client.stopTyping.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};_createClass(TextChannel,[{key:"lastMessage",get:functionget(){returnthis.messages.get("id",this.lastMessageID);}}]);returnTextChannel;})(_ServerChannel3["default"]);exports["default"]=TextChannel;module.exports=exports["default"];
"use strict";exports.__esModule=true;var_createClass=(function(){functiondefineProperties(target,props){for(vari=0;i<props.length;i++){vardescriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"indescriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}returnfunction(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);returnConstructor;};})();function_interopRequireDefault(obj){returnobj&&obj.__esModule?obj:{"default":obj};}function_classCallCheck(instance,Constructor){if(!(instanceinstanceofConstructor)){thrownewTypeError("Cannot call a class as a function");}}function_inherits(subClass,superClass){if(typeofsuperClass!=="function"&&superClass!==null){thrownewTypeError("Super expression must either be null or a function, not "+typeofsuperClass);}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var_UtilEquality=require("../Util/Equality");var_UtilEquality2=_interopRequireDefault(_UtilEquality);var_Constants=require("../Constants");var_UtilArgumentRegulariser=require("../Util/ArgumentRegulariser");varUser=(function(_Equality){_inherits(User,_Equality);functionUser(data,client){_classCallCheck(this,User);_Equality.call(this);this.client=client;this.username=data.username;this.discriminator=data.discriminator;this.id=data.id;this.avatar=data.avatar;this.status=data.status||"offline";this.gameID=data.game_id||null;this.typing={since:null,channel:null};this.voiceChannel=null;}User.prototype.mention=functionmention(){return"<@"+this.id+">";};User.prototype.toString=functiontoString(){returnthis.mention();};User.prototype.equalsStrict=functionequalsStrict(obj){if(objinstanceofUser)returnthis.id===obj.id&&this.username===obj.username&&this.discriminator===obj.discriminator&&this.avatar===obj.avatar&&this.status===obj.status&&this.gameID===obj.gameID;elsereturnfalse;};User.prototype.equals=functionequals(obj){if(objinstanceofUser)returnthis.id===obj.id&&this.username===obj.username&&this.discriminator===obj.discriminator&&this.avatar===obj.avatar;elsereturnfalse;};User.prototype.sendMessage=functionsendMessage(){returnthis.client.sendMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};User.prototype.send=functionsend(){returnthis.client.sendMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};User.prototype.sendTTSMessage=functionsendTTSMessage(){returnthis.client.sendTTSMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};User.prototype.sendTTS=functionsendTTS(){returnthis.client.sendTTSMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};User.prototype.sendFile=functionsendFile(){returnthis.client.sendFile.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};User.prototype.startTyping=functionstartTyping(){returnthis.client.startTyping.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};User.prototype.stopTyping=functionstopTyping(){returnthis.client.stopTyping.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};User.prototype.addTo=functionaddTo(role,callback){returnthis.client.addMemberToRole.apply(this.client,[this,role,callback]);};User.prototype.removeFrom=functionremoveFrom(role,callback){returnthis.client.removeMemberFromRole.apply(this.client,[this,role,callback]);};User.prototype.getLogs=functiongetLogs(){returnthis.client.getChannelLogs.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};_createClass(User,[{key:"avatarURL",get:functionget(){if(!this.avatar){returnnull;}else{return_Constants.Endpoints.AVATAR(this.id,this.avatar);}}},{key:"name",get:functionget(){returnthis.username;}}]);returnUser;})(_UtilEquality2["default"]);exports["default"]=User;module.exports=exports["default"];
"use strict";exports.__esModule=true;function_interopRequireDefault(obj){returnobj&&obj.__esModule?obj:{"default":obj};}function_classCallCheck(instance,Constructor){if(!(instanceinstanceofConstructor)){thrownewTypeError("Cannot call a class as a function");}}function_inherits(subClass,superClass){if(typeofsuperClass!=="function"&&superClass!==null){thrownewTypeError("Super expression must either be null or a function, not "+typeofsuperClass);}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var_ServerChannel2=require("./ServerChannel");var_ServerChannel3=_interopRequireDefault(_ServerChannel2);var_UtilCache=require("../Util/Cache");var_UtilCache2=_interopRequireDefault(_UtilCache);var_UtilArgumentRegulariser=require("../Util/ArgumentRegulariser");varVoiceChannel=(function(_ServerChannel){_inherits(VoiceChannel,_ServerChannel);functionVoiceChannel(data,client,server){_classCallCheck(this,VoiceChannel);_ServerChannel.call(this,data,client,server);this.members=new_UtilCache2["default"]();}VoiceChannel.prototype.join=functionjoin(){varcallback=arguments.length<=0||arguments[0]===undefined?function(){}:arguments[0];returnthis.client.joinVoiceChannel.apply(this.client,[this,callback]);};returnVoiceChannel;})(_ServerChannel3["default"]);exports["default"]=VoiceChannel;module.exports=exports["default"];
"use strict";exports.__esModule=true;function_classCallCheck(instance,Constructor){if(!(instanceinstanceofConstructor)){thrownewTypeError("Cannot call a class as a function");}}function_inherits(subClass,superClass){if(typeofsuperClass!=="function"&&superClass!==null){thrownewTypeError("Super expression must either be null or a function, not "+typeofsuperClass);}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}vardiscrimS=Symbol();vardiscrimCacheS=Symbol();varCache=(function(_Array){_inherits(Cache,_Array);functionCache(discrim,limit){_classCallCheck(this,Cache);_Array.call(this);this[discrimS]=discrim||"id";this[discrimCacheS]={};}Cache.prototype.get=functionget(key,value){if(key===this[discrimS])returnthis[discrimCacheS][value]||null;for(var_iterator=this,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:_iterator[Symbol.iterator]();;){var_ref;if(_isArray){if(_i>=_iterator.length)break;_ref=_iterator[_i++];}else{_i=_iterator.next();if(_i.done)break;_ref=_i.value;}varitem=_ref;if(item[key]==value){returnitem;}}returnnull;};Cache.prototype.has=functionhas(object){return!!this.get(this[discrimS],object[this[discrimS]]);};Cache.prototype.getAll=functiongetAll(key,value){varfound=newCache(this[discrimS]);this.forEach(function(val,index,array){if(val.hasOwnProperty(key)&&val[key]==value){found.push(val);return;}});returnfound;};Cache.prototype.add=functionadd(data){varcacheKey=this[discrimS]==="id"?data.id:data[this[discrimS]];if(this[discrimCacheS][cacheKey]){returnthis[discrimCacheS][cacheKey];}if(this.limit&&this.length>=this.limit){this.splice(0,1);}this.push(data);this[discrimCacheS][cacheKey]=data;returndata;};Cache.prototype.update=functionupdate(old,data){varitem=this.get(this[discrimS],old[this[discrimS]]);if(item){varindex=this.indexOf(item);Object.assign(this[index],data);this[discrimCacheS][data[this[discrimS]]]=this[index];returnthis[index];}else{returnfalse;}};Cache.prototype.random=functionrandom(){returnthis[Math.floor(Math.random()*this.length)];};Cache.prototype.remove=functionremove(data){deletethis[discrimCacheS][data[this[discrimS]]];varindex=this.indexOf(data);if(~index){this.splice(index,1);}else{varitem=this.get(this[discrimS],data[this[discrimS]]);if(item){this.splice(this.indexOf(item),1);}}returnfalse;};returnCache;})(Array);exports["default"]=Cache;module.exports=exports["default"];
*/"use strict";exports.__esModule=true;var_createClass=(function(){functiondefineProperties(target,props){for(vari=0;i<props.length;i++){vardescriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"indescriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}returnfunction(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);returnConstructor;};})();function_classCallCheck(instance,Constructor){if(!(instanceinstanceofConstructor)){thrownewTypeError("Cannot call a class as a function");}}varEquality=(function(){functionEquality(){_classCallCheck(this,Equality);}Equality.prototype.equals=functionequals(object){returnobject&&object[this.eqDiscriminator]===this[this.eqDiscriminator];};Equality.prototype.equalsStrict=functionequalsStrict(object){// override per class type
"use strict";/* global process */exports.__esModule=true;function_interopRequireDefault(obj){returnobj&&obj.__esModule?obj:{"default":obj};}function_classCallCheck(instance,Constructor){if(!(instanceinstanceofConstructor)){thrownewTypeError("Cannot call a class as a function");}}function_inherits(subClass,superClass){if(typeofsuperClass!=="function"&&superClass!==null){thrownewTypeError("Super expression must either be null or a function, not "+typeofsuperClass);}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var_fsExtra=require("fs-extra");var_fsExtra2=_interopRequireDefault(_fsExtra);var_events=require("events");var_events2=_interopRequireDefault(_events);var_crypto=require("crypto");var_crypto2=_interopRequireDefault(_crypto);varsavePaths=[process.env.APPDATA||(process.platform=="darwin"?process.env.HOME+"Library/Preference":"/var/local"),process.env[process.platform=="win32"?"USERPROFILE":"HOME"],process.cwd()];varalgo="aes-256-ctr";functionsecureEmail(email,password){returnnewBuffer(_crypto2["default"].createHash("sha256").update(email+password,"utf8").digest()).toString("hex");}varTokenCacher=(function(_EventEmitter){_inherits(TokenCacher,_EventEmitter);functionTokenCacher(client,options){_classCallCheck(this,TokenCacher);_EventEmitter.call(this);this.client=client;this.savePath=null;this.error=false;this.done=false;this.data={};}TokenCacher.prototype.setToken=functionsetToken(){varemail=arguments.length<=0||arguments[0]===undefined?"":arguments[0];varpassword=arguments.length<=1||arguments[1]===undefined?"":arguments[1];vartoken=arguments.length<=2||arguments[2]===undefined?"":arguments[2];email=secureEmail(email,password);varcipher=_crypto2["default"].createCipher(algo,password);varcrypted=cipher.update("valid"+token,"utf8","hex");crypted+=cipher.final("hex");this.data[email]=crypted;this.save();};TokenCacher.prototype.save=functionsave(){_fsExtra2["default"].writeJson(this.savePath,this.data);};TokenCacher.prototype.getToken=functiongetToken(){varemail=arguments.length<=0||arguments[0]===undefined?"":arguments[0];varpassword=arguments.length<=1||arguments[1]===undefined?"":arguments[1];email=secureEmail(email,password);if(this.data[email]){try{vardecipher=_crypto2["default"].createDecipher(algo,password);vardec=decipher.update(this.data[email],"hex","utf8");dec+=decipher.final("utf8");returndec.indexOf("valid")===0?dec.substr(5):false;}catch(e){// not a valid token
returnnull;}}else{returnnull;}};TokenCacher.prototype.init=functioninit(ind){var_this=this;varself=this;varsavePath=savePaths[ind];_fsExtra2["default"].ensureDir(savePath,function(err){if(err){error(err);}else{//good to go
"use strict";exports.__esModule=true;function_interopRequireDefault(obj){returnobj&&obj.__esModule?obj:{"default":obj};}function_classCallCheck(instance,Constructor){if(!(instanceinstanceofConstructor)){thrownewTypeError("Cannot call a class as a function");}}var_child_process=require("child_process");var_child_process2=_interopRequireDefault(_child_process);varopus;try{opus=require("node-opus");}catch(e){// no opus!
"use strict";// represents an intent of streaming music
exports.__esModule=true;function_interopRequireDefault(obj){returnobj&&obj.__esModule?obj:{"default":obj};}function_classCallCheck(instance,Constructor){if(!(instanceinstanceofConstructor)){thrownewTypeError("Cannot call a class as a function");}}function_inherits(subClass,superClass){if(typeofsuperClass!=="function"&&superClass!==null){thrownewTypeError("Super expression must either be null or a function, not "+typeofsuperClass);}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var_events=require("events");var_events2=_interopRequireDefault(_events);varStreamIntent=(function(_EventEmitter){_inherits(StreamIntent,_EventEmitter);functionStreamIntent(){_classCallCheck(this,StreamIntent);_EventEmitter.call(this);}returnStreamIntent;})(_events2["default"]);exports["default"]=StreamIntent;module.exports=exports["default"];
without his help voice chat in discord.js would not have
been possible!
*/exports.__esModule=true;function_interopRequireDefault(obj){returnobj&&obj.__esModule?obj:{"default":obj};}function_classCallCheck(instance,Constructor){if(!(instanceinstanceofConstructor)){thrownewTypeError("Cannot call a class as a function");}}function_inherits(subClass,superClass){if(typeofsuperClass!=="function"&&superClass!==null){thrownewTypeError("Super expression must either be null or a function, not "+typeofsuperClass);}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var_ws=require("ws");var_ws2=_interopRequireDefault(_ws);var_dns=require("dns");var_dns2=_interopRequireDefault(_dns);var_dgram=require("dgram");var_dgram2=_interopRequireDefault(_dgram);var_AudioEncoder=require("./AudioEncoder");var_AudioEncoder2=_interopRequireDefault(_AudioEncoder);var_VoicePacket=require("./VoicePacket");var_VoicePacket2=_interopRequireDefault(_VoicePacket);var_StreamIntent=require("./StreamIntent");var_StreamIntent2=_interopRequireDefault(_StreamIntent);var_events=require("events");var_events2=_interopRequireDefault(_events);var_unpipe=require("unpipe");var_unpipe2=_interopRequireDefault(_unpipe);varVoiceConnection=(function(_EventEmitter){_inherits(VoiceConnection,_EventEmitter);functionVoiceConnection(channel,client,session,token,server,endpoint){_classCallCheck(this,VoiceConnection);_EventEmitter.call(this);this.id=channel.id;this.voiceChannel=channel;this.client=client;this.session=session;this.token=token;this.server=server;this.endpoint=endpoint.split(":")[0];this.vWS=null;// vWS means voice websocket
this.ready=false;this.vWSData={};this.encoder=new_AudioEncoder2["default"]();this.udp=null;this.playingIntent=null;this.playing=false;this.streamTime=0;this.streamProc=null;this.KAI=null;this.timestamp=0;this.sequence=0;this.init();}VoiceConnection.prototype.destroy=functiondestroy(){this.stopPlaying();if(this.KAI)clearInterval(this.KAI);this.vWS.close();this.udp.close();this.client.internal.sendWS({op:4,d:{guild_id:null,channel_id:null,self_mute:true,self_deaf:false}});};VoiceConnection.prototype.stopPlaying=functionstopPlaying(){this.playing=false;this.playingIntent=null;if(this.instream){//not all streams implement these...
//and even file stream don't seem to implement them properly...
return;}else{onWarning=true;setTimeout(send,length*10);// give chance for some data in 200ms to appear
return;}}if(buffer.length!==1920*channels){varnewBuffer=newBuffer(1920*channels).fill(0);buffer.copy(newBuffer);buffer=newBuffer;}count++;self.sequence+1<65535?self.sequence+=1:self.sequence=0;self.timestamp+960<4294967295?self.timestamp+=960:self.timestamp=0;self.sendBuffer(buffer,self.sequence,self.timestamp,function(e){});varnextTime=startTime+count*length;self.streamTime=count*length;setTimeout(send,length+(nextTime-Date.now()));if(!self.playing)self.setSpeaking(true);retStream.emit("time",self.streamTime);}catch(e){retStream.emit("error",e);}}self.setSpeaking(true);send();returnretStream;};VoiceConnection.prototype.setSpeaking=functionsetSpeaking(value){this.playing=value;if(this.vWS.readyState===_ws2["default"].OPEN)this.vWS.send(JSON.stringify({op:5,d:{speaking:value,delay:0}}));};VoiceConnection.prototype.sendPacket=functionsendPacket(packet){varcallback=arguments.length<=1||arguments[1]===undefined?function(err){}:arguments[1];varself=this;self.playing=true;try{if(self.vWS.readyState===_ws2["default"].OPEN)self.udp.send(packet,0,packet.length,self.vWSData.port,self.endpoint,callback);}catch(e){self.playing=false;callback(e);returnfalse;}};VoiceConnection.prototype.sendBuffer=functionsendBuffer(rawbuffer,sequence,timestamp,callback){varself=this;self.playing=true;try{if(!self.encoder.opus){self.playing=false;self.emit("error","No Opus!");self.client.emit("debug","Tried to use node-opus, but opus not available - install it!");return;}if(!self.encoder.sanityCheck()){self.playing=false;self.emit("error","Opus sanity check failed!");self.client.emit("debug","Opus sanity check failed - opus is installed but not correctly! Please reinstall opus and make sure it's installed correctly.");return;}varbuffer=self.encoder.opusBuffer(rawbuffer);varpacket=new_VoicePacket2["default"](buffer,sequence,timestamp,self.vWSData.ssrc);returnself.sendPacket(packet,callback);}catch(e){self.playing=false;self.emit("error",e);returnfalse;}};VoiceConnection.prototype.playFile=functionplayFile(stream){var_this=this;varoptions=arguments.length<=1||arguments[1]===undefined?false:arguments[1];varcallback=arguments.length<=2||arguments[2]===undefined?function(err,str){}:arguments[2];varself=this;self.stopPlaying();if(typeofoptions==="function"){// options is the callback
callback=options;options={};}returnnewPromise(function(resolve,reject){_this.encoder.encodeFile(stream,options)["catch"](error).then(function(data){self.streamProc=data.proc;varintent=self.playStream(data.stream,2);resolve(intent);callback(null,intent);});functionerror(){vare=arguments.length<=0||arguments[0]===undefined?true:arguments[0];reject(e);callback(e);}});};VoiceConnection.prototype.playRawStream=functionplayRawStream(stream){var_this2=this;varoptions=arguments.length<=1||arguments[1]===undefined?false:arguments[1];varcallback=arguments.length<=2||arguments[2]===undefined?function(err,str){}:arguments[2];varself=this;self.stopPlaying();if(typeofoptions==="function"){// options is the callback
callback=options;options={};}returnnewPromise(function(resolve,reject){_this2.encoder.encodeStream(stream,options)["catch"](error).then(function(data){self.streamProc=data.proc;self.instream=data.instream;varintent=self.playStream(data.stream);resolve(intent);callback(null,intent);});functionerror(){vare=arguments.length<=0||arguments[0]===undefined?true:arguments[0];reject(e);callback(e);}});};VoiceConnection.prototype.playArbitraryFFmpeg=functionplayArbitraryFFmpeg(ffmpegOptions){var_this3=this;varcallback=arguments.length<=1||arguments[1]===undefined?function(err,str){}:arguments[1];varself=this;self.stopPlaying();if(typeofoptions==="function"){// options is the callback
"use strict";exports.__esModule=true;function_classCallCheck(instance,Constructor){if(!(instanceinstanceofConstructor)){thrownewTypeError("Cannot call a class as a function");}}varVoicePacket=functionVoicePacket(data,sequence,time,ssrc){_classCallCheck(this,VoicePacket);varaudioBuffer=data,returnBuffer=newBuffer(audioBuffer.length+12);returnBuffer.fill(0);returnBuffer[0]=0x80;returnBuffer[1]=0x78;returnBuffer.writeUIntBE(sequence,2,2);returnBuffer.writeUIntBE(time,4,4);returnBuffer.writeUIntBE(ssrc,8,4);for(vari=0;i<audioBuffer.length;i++){returnBuffer[i+12]=audioBuffer[i];}returnreturnBuffer;};exports["default"]=VoicePacket;module.exports=exports["default"];
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.