Merge pull request #55 from hydrabolt/rewrite-docs

Finished docs (mainly)
This commit is contained in:
Amish Shah
2015-11-20 22:13:07 +00:00
65 changed files with 18464 additions and 6371 deletions

View File

@@ -4,24 +4,88 @@
</a>
</p>
## Welcome to the rewrite branch!
# Did v5.0.0 break your code? [Look here.](http://discordjs.readthedocs.org/en/rewrite-docs/migrating.html)
The rewrite branch was created as a way of completely rewriting the API (once again) for complete stability. Versions <= 4.1.1 of the API would _always_ eventually crash for one reason or another.
[![Build Status](https://travis-ci.org/hydrabolt/discord.js.svg)](https://travis-ci.org/hydrabolt/discord.js) [![Documentation Status](https://readthedocs.org/projects/discordjs/badge/?version=latest)](http://discordjs.readthedocs.org/en/latest/?badge=latest)
So far, the rewrite branch seems to have achieved what was wanted, as it is much more stable and can handle mass joining and leaving of servers. Users, channels and servers are always cached properly, and the only time of expected crashes are when an error occurs in the WebSocket.
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.
You can start using the rewrite branch, but it is a breaking change. The documentation isn't done, but H
here is the main notable change:
**The examples in the repo are in ES6, either update your node or compile them down to babel yourself if you want to use them!**
### Installation
`npm install --save discord.js`
---
### Example
```js
// old method:
client.getUser("id", 12);
client.getChannel("id", 12);
client.getServer("id", 12);
// etc...
var Discord = require("discord.js");
var mybot = new Discord.Client();
mybot.on("message", function(message){
// new method:
client.users.get("id", 12);
client.channels.get("id", 12);
client.servers.get("id", 12);
```
if(message.content === "ping")
mybot.reply(message, "pong");
});
mybot.login("email", "password");
```
---
### What's new in 5.0.0?
Stability in general! The API has been rewritten completely for much better stability, and it seems to have worked! There are now no random crashes and everything caches properly. The API is also a bit cleaner!
However, it is a breaking change if you are updating (potentially, basic code should be fine) you should look [here](http://discordjs.readthedocs.org/en/rewrite-docs/migrating.html) for help updating.
---
### Related Projects
Here is a list of other Discord APIs:
#### Java:
[Discord4J](https://github.com/nerd/Discord4J)
#### .NET:
[Discord.Net](https://github.com/RogueException/Discord.Net)
[DiscordSharp](https://github.com/Luigifan/DiscordSharp)
#### NodeJS
[discord.io](https://github.com/izy521/node-discord) (similar to discord.js but lower level)
#### PHP
[DiscordPHP](https://github.com/teamreflex/DiscordPHP)
#### Python
[discord.py](https://github.com/Rapptz/discord.py)
#### Ruby
[discordrb](https://github.com/meew0/discordrb)
---
### Links
**[Documentation](http://discordjs.readthedocs.org/en/latest/)**
**[GitHub](https://github.com/discord-js/discord.js)**
**[Wiki](https://github.com/discord-js/discord.js/wiki)**
**[Website](http://discord-js.github.io/)**
**[NPM](npmjs.com/package/discord.js)**
---
### Contact
If you have an issue or want to know if a feature exists, [read the documentation](http://discordjs.readthedocs.org/en/latest/) before contacting me about any issues! If it's badly/wrongly implemented, let me know!
If you would like to contact me, you can create an issue on the GitHub repo, e-mail me via the one available on my NPM profile.
Or you could just send a DM to **hydrabolt** in [**Discord API**](https://discord.gg/0SBTUU1wZTYd2XyW).

View File

@@ -1,132 +0,0 @@
Creating a Simple Bot
=====================
This page will walk you through writing a simple bot and will introduce you to some of the most important functions and objects you will encounter in the API.
Setting up a Project
--------------------
Before you start creating your bot, you need to create a directory, for example *discordbot*.
After you've done that, open up the directory and have a look at how to `install the module`_. After you've installed the module, you can progress to the next step
Creating the Bot
----------------
Now we can begin writing the bot. This bot will just server the user their avatar but at a higher resolution - assuming they have one.
Firstly, create a file named ``bot.js`` in the directory you made earlier. Open it up, and type the following lines of code:
.. code-block:: js
var Discord = require("discord.js");
var bot = new Discord.Client();
This code firstly imports the discord.js module, which contains classes to help you create clients for Discord. The second line creates a new Discord Client, which we can manipulate later. Now, we want the client to be alerted when there is a new message and do something, so we can type this:
.. code-block:: js
bot.on("message", function(message){
} )
This will simply get our client to listen out for new messages, but not yet do anything. Let's have a look at this:
.. code-block:: js
bot.on("message", function(message){
if( message.content === "avatar me!" ){
}
} )
This code will now get our client to execute anything inside the if statement as long as the message sent was "avatar me!" We can now get it to see if the user has an avatar:
.. code-block:: js
bot.on("message", function(message){
if( message.content === "avatar me!" ){
var usersAvatar = message.sender.avatarURL;
if(usersAvatar){
// user has an avatar
}else{
// user doesn't have an avatar
}
}
} )
This code will now see if the user has an avatar and then do something based on that, let's finalise it:
.. code-block:: js
bot.on("message", function(message){
if( message.content === "avatar me!" ){
var usersAvatar = message.sender.avatarURL;
if(usersAvatar){
// user has an avatar
bot.reply(message, "your avatar can be found at " + usersAvatar);
}else{
// user doesn't have an avatar
bot.reply(message, "you don't have an avatar!");
}
}
} )
Let's have a look at the function we used here; *bot.reply*. This function takes 2 necessary parameters, a message object to reply to and a message to send. The first parameter we already have, and it is the message we have received. The second parameter is what we want to send.
Now that we've finished the listener event, we need to log the client in:
.. code-block:: js
bot.login("your discord email", "your discord password");
And that's it! Run the code with ``node bot.js`` and wait a few seconds, and then try sending *avatar me!* to any of the channels that the user you provided has details to.
Final Product
-------------
.. code-block:: js
var Discord = require("discord.js");
var bot = new Discord.Client();
bot.on("message", function(message){
if( message.content === "avatar me!" ){
var usersAvatar = message.sender.avatarURL;
if(usersAvatar){
// user has an avatar
bot.reply(message, "your avatar can be found at " + usersAvatar);
}else{
// user doesn't have an avatar
bot.reply(message, "you don't have an avatar!");
}
}
} );
bot.login("your discord email", "your discord password");
.. note:: This page is still a WIP, check back later for more documentation on it.
.. _install the module : http://discordjs.readthedocs.org/en/latest/get_started.html#installation

43
docs/docs_cache.rst Normal file
View File

@@ -0,0 +1,43 @@
.. include:: ./vars.rst
Cache
=====
**extends Array**
A Cache object extends an Array (so it can be used like a regular array) but introduces helper functions to make it more useful when developing with discord.js. Unlike a regular array, it doesn't care about the instance or prototype of an object, it works purely on properties.
-----
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.
remove(data)
~~~~~~~~~~~~
Removes an object from the cache if it exists.

View File

@@ -1,82 +1,23 @@
.. include:: ./vars.rst
Channels
========
The Channel Class is used to represent data about a Channel.
Attributes
----------
client
~~~~~~
The Discord Client_ that cached the channel
server
~~~~~~
The Server_ that the channel belongs to
name
~~~~
The channel's name, as a `String`.
id
~~
The channel's id, as a `String`.
type
~~~~
The type of the channel as a `String`, either ``text`` or ``voice``.
topic
~~~~~
A `String` that is the topic of the channel, if the channel doesn't have a topic this will be `null`.
messages
~~~~~~~~
An `Array` of Message_ objects received from the channel. There are up to a 1000 messages here, and the older messages will be deleted if necessary.
members
~~~~~~~
**Aliases** : `users`
The members in the channel's server, an `Array` of User_ objects.
-----
Functions
---------
.. note:: When concatenated with a String, the object will become the channel's embed code, e.g. ``"this is " + channel`` would be ``this is <#channelid>``
getMessage(key, value)
~~~~~~~~~~~~~~~~~~~~~~
Gets a Message_ from the channel that matches the specified criteria. E.g:
.. code-block:: js
channel.getMessage("id", 1243987349) // returns a Message where message.id === 1243987349
- **key** - a `String` that is the key
- **value** - a `String` that is the value
permissionsOf(user)
~~~~~~~~~~~~~~~~~~~
Gets the EvaluatedPermissions_ of a User in the channel.
- **user** - A User_ or Member_ you want to get the permissions of.
equals(object)
~~~~~~~~~~~~~~
Returns a `Boolean` depending on whether the Channel's ID (``channel.id``) equals the object's ID (``object.id``). You should **always**, always use this if you want to compare channels. **NEVER** do ``channel1 == channel2``.
.. include:: ./vars.rst
Channel
=======
**extends** Equality_
The Channel class is the base class for all types of channel.
Attributes
----------
--------
id
~~
The ID of the channel, a `String`.
client
~~~~~~
The Client_ that cached the channel.

View File

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

File diff suppressed because it is too large Load Diff

View File

@@ -1,108 +0,0 @@
.. include:: ./vars.rst
Embeds
======
Embeds are parts of Messages that are sort-of like a preview. They are created serverside by Discord, so in real-time they would come through as part of a `messageUpdate` event. When grabbing messages from logs, they will already be embedded as part of the array ``message.embeds``.
All the Embed classes extend ``Discord.Embed``.
Link Embed
----------
A Link Embed is an embed showing a preview of any linked site in a message.
Attributes
~~~~~~~~~~
.. code-block:: js
{
url, // the URL of the link
type : "link",
title, // title of the embed/URL
thumbnail : {
width, // the width of the thumbnail in pixels
height, // the height of the thumbnail in pixels
url, // the direct URL to the thumbnail
proxy_url, // a proxy URL to the thumbnail
},
provider : {
url, // ???
name, // ???
},
description, // description of the embed
author : {
url, // URL to the author (if any)
name // name of the author (if any)
}
}
Image Embed
-----------
An Image Embed shows an image of a referenced link
Attributes
~~~~~~~~~~
.. code-block:: js
{
url, // the URL of the image
type : "image",
title, // title of the embed/image
thumbnail : {
width, // the width of the thumbnail in pixels
height, // the height of the thumbnail in pixels
url, // the direct URL to the thumbnail
proxy_url, // a proxy URL to the thumbnail
},
provider : {
url, // ???
name, // ???
},
description, // description of the embed
author : {
url, // URL to the author (if any)
name // name of the author (if any)
}
}
Video Embed
-----------
A Video Embed embeds videos (e.g. youtube)
Attributes
~~~~~~~~~~
.. code-block:: js
{
url, // the URL of the video
type : "video",
title, // title of the embed/video
thumbnail : {
width, // the width of the thumbnail in pixels
height, // the height of the thumbnail in pixels
url, // the direct URL to the thumbnail
proxy_url, // a proxy URL to the thumbnail
},
provider : {
url, // ???
name, // ???
},
description, // description of the embed
author : {
url, // URL to the author (if any)
name // name of the author (if any)
},
video : {
width, // the width of the embedded video player
height, // the height of the embedded video player
url // the URL of the embedded play
}
}

20
docs/docs_equality.rst Normal file
View File

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

View File

@@ -1,64 +1,66 @@
.. include:: ./vars.rst
Invites
=======
The Invite Class is used to represent data about an Invite.
Attributes
----------
max_age
~~~~~~~
A `Number` in minutes for how long the Invite should be valid for. E.g. a value of ``3600`` is equal to 30 minutes.
code
~~~~
`String` an alphanumeric code for the Invite.
revoked
~~~~~~~
`Boolean` that dictates whether the Invite has been cancelled or not
created_at
~~~~~~~~~~
A unix timestamp as a `Number` which is the time that the invite was created.
temporary
~~~~~~~~~
`Boolean` that dictates whether the invite is temporary.
uses
~~~~
`Number` the number of uses of the Invite, a value of ``0`` is none.
max_uses
~~~~~~~~
`Number` that is the maximum amount of uses of the invite, ``0`` is unlimited.
inviter
~~~~~~~
The User_ that created the invite.
xkcd
~~~~
`Boolean` that is true if the invite should be human-readable.
channel
~~~~~~~
The Channel_ that the invite is inviting to.
URL
~~~
A `String` that generates a clickable link to the invite.
.. include:: ./vars.rst
Invite
======
Used to represent data of an invite.
Attributes
----------
--------
maxAge
~~~~~~
`Number`, how long (in seconds) the invite has since creation before expiring.
code
~~~~
`String`, the invite code.
server
~~~~~~
The Server_ the invite is for.
channel
~~~~~~~
The ServerChannel_ the invite is for.
revoked
~~~~~~~
`Boolean`, whether the invite has been revoked or not.
createdAt
~~~~~~~~~
`Number`, timestamp of when the invite was created.
temporary
~~~~~~~~~
`Boolean`, whether the invite is temporary or not.
uses
~~~~
`Number`, uses of the invite remaining.
maxUses
~~~~~~~
`Number`, maximum uses of the invite.
inviter
~~~~~~~
User_ who sent/created the invite.
xkcd
~~~~
`Boolean`, whether the invite is intended to be easy to read and remember by a human.

View File

@@ -1,52 +0,0 @@
.. include:: ./vars.rst
Members
=======
The Member Class is used to represent a User_ but specific to a server. **Any attributes/functions available in the User class are omitted.**
How do I get a Member from a User?
----------------------------------
Sometimes you might want a Member object, but instead you are given a User_ object. Since Members belong to servers, you can just do:
.. code-block:: js
server.getMember("id", user.id);
This code will either return `false` if no member is found, or a Member if one is found. This method will work if you are given either a User OR Member object.
Attributes
----------
server
~~~~~~
The Server_ that the Member belongs to.
roles
~~~~~
An `Array` of ServerPermissions_ and ChannelPermissions_ that the Member is affected by.
rawRoles
~~~~~~~~
An `Array` of role IDs.
Functions
---------
hasRole(role)
~~~~~~~~~~~~~
Returns a `Boolean` depending on whether or not a user has a certain role.
- **role** - The ServerPermissions_ you want to see if a user has.
permissionsIn(channel)
~~~~~~~~~~~~~~~~~~~~~~
Returns an EvaluatedPermissions_ giving the final permissions of the Member in a channel.
- **channel** - The Channel_ that you want to evaluate the permissions in.

View File

@@ -1,84 +1,85 @@
.. include:: ./vars.rst
Messages
========
The Message Class is used to represent data about a Message.
Attributes
----------
tts
~~~
A `Boolean` that is ``true`` if the sent message was text-to-speech, otherwise ``false``.
timestamp
~~~~~~~~~
A `unix timestamp` as a `Number` representing when the message was sent.
mentions
~~~~~~~~
An `Array` of Member_ and User_ objects that represent the users mentioned in the message. The only way that the User_ objects would exist in the Array is if the message is from a log, where the mentioned users may have left the server afterwards.
everyoneMentioned
~~~~~~~~~~~~~~~~~
A `Boolean` that is ``true`` if **@everyone** was used, otherwise ``false``.
id
~~
A `String` UUID of the message, will never change.
.. note:: Currently, message IDs are totally unique. However, in the future they may only be unique within a channel. Make sure to check periodically whether this has changed.
embeds
~~~~~~
An `Array` of Embed_ objects.
editedTimestamp
~~~~~~~~~~~~~~~
A `unix timestamp` as a `Number` that is when the message was last edited.
content
~~~~~~~
The actual content of the message as a `String`.
channel
~~~~~~~
The Channel_ that the message was sent in.
author
~~~~~~
**Aliases** : `sender`
The Member or User_ that sent the message. May be a User_ if from a log, it depends on whether the sender left the server after sending the message. If received in realtime, always a Member.
attachments
~~~~~~~~~~~
A raw, unhandled `JSON object` that will contain attachments of the message - if any.
isPrivate
~~~~~~~~~
A `Boolean` that is ``true`` if the message was sent in a PM / DM chat, or if it was sent in a group chat it will be ``false``.
Functions
---------
isMentioned(user)
~~~~~~~~~~~~~~~~~
A `Boolean` that will return ``true`` if the specified user was mentioned in the message. If everyone is mentioned, this will be false - this function checks specifically for if they were mentioned.
- **user** - The User_ that you want to see is mentioned or not.
.. include:: ./vars.rst
Message
=======
**extends** Equality_
A Message object is used to represent the data of a message.
Attributes
----------
-------
channel
~~~~~~~
The channel the message sent in, either a TextChannel_ or PMChannel_.
client
~~~~~~
The Client_ that cached the message.
attachments
~~~~~~~~~~~
A raw array of attachment objects.
tts
~~~
`Boolean`, true if the message was text-to-speech.
embeds
~~~~~~
A raw array of embed objects.
timestamp
~~~~~~~~~
`Number`, timestamp of when the message was sent.
everyoneMentioned
~~~~~~~~~~~~~~~~~
`Boolean`, true if ``@everyone`` was mentioned.
id
~~
`String`, ID of the message.
editedTimestamp
~~~~~~~~~~~~~~~
Timestamp on when the message was last edited, `Number`. Potentially null.
author
~~~~~~
The User_ that sent the message.
content
~~~~~~~
`String`, content of the message.
mentions
~~~~~~~~
A Cache_ of User_ objects that were mentioned in the message.
------
Functions
---------
isMentioned(user)
~~~~~~~~~~~~~~~~~
Returns true if the given user was mentioned in the message.
- **user** : A `User Resolvable`_

View File

@@ -1,100 +0,0 @@
.. include:: ./vars.rst
Module
======
The Module (``require("discord.js")``) contains some helper functions/objects as well the classes use in Discord. The Classes available are omitted as they are visible under the rest of the `Documentation` section.
Discord.Colors
--------------
Currently Colors are only usable in Roles_. You can't use any colour in messages, unless it's syntax highlighting from codeblocks.
.. note:: There is currently an unresolved bug in Discord, long story short any hex colors provided that start with a 0 (e.g. #00FF00) will be changed to #10FF00 to ensure they render properly.
Example Usage
~~~~~~~~~~~~~
.. code-block:: js
// valid color usage (examples 2-4 only from version 3.10.2):
mybot.createRole(server, {
color : Discord.Colors.AQUA
});
mybot.createRole(server, {
color : "#ff0000"
});
mybot.createRole(server, {
color : "ff0000"
});
mybot.createRole(server, {
color : 0xff0000
});
Preset Colors:
~~~~~~~~~~~~~~
.. code-block:: js
// these values are just hex converted to base 10
// e.g.
// 15844367 -> #f1c40f
// dec hex
{
DEFAULT: 0,
AQUA: 1752220,
GREEN: 3066993,
BLUE: 3447003,
PURPLE: 10181046,
GOLD: 15844367,
ORANGE: 15105570,
RED: 15158332,
GREY: 9807270,
DARKER_GREY: 8359053,
NAVY: 3426654,
DARK_AQUA: 1146986,
DARK_GREEN: 2067276,
DARK_BLUE: 2123412,
DARK_PURPLE: 7419530,
DARK_GOLD: 12745742,
DARK_ORANGE: 11027200,
DARK_RED: 10038562,
DARK_GREY: 9936031,
LIGHT_GREY: 12370112,
DARK_NAVY: 2899536
}
toHex(num)
~~~~~~~~~~
Converts a base 10 color (such as the one found in ``serverPermissions.color``) to a valid hex string (e.g. ``#ff0000``)
- **num** - `Number` that you want to convert to hex
.. code-block:: js
// converts Discord.Color.DARK_NAVY to hex:
Discord.Color.toHex( Discord.Color.DARK_NAVY ); // returns '#2C3E50'
toDec(data)
~~~~~~~~~~~
Converts a hex string to a valid, base 10 Discord color.
- **data** - `String` that you want to convert, valid formats include: ``ff0000` and ``#ff0000`. If a valid base 10 color (e.g. ``0xff0000`` is passed, this is returned, making the function well at handling ambiguous data.
.. code-block:: js
// if you want to create/update a role, you don't have to use
// Color.toDec, this is done for you.
Discord.Color.toDec( "#ff0000" ); // 16711680
Discord.Color.toDec( "ff0000" ); // 16711680
Discord.Color.toDec( 0xff0000 ); // 16711680

View File

@@ -0,0 +1,53 @@
.. include:: ./vars.rst
Permission Constants
====================
In discord.js, you can handle permissions in two ways. The preferred way is to just use the string name of the permission, alternatively you can use ``Discord.Constants.Permissions["permission name"]``.
Valid Permission Names
----------------------
.. code-block:: js
{
// general
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:
``role.hasPermission( Discord.Constants.Permissions.voiceUseVAD )``

View File

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

View File

@@ -1,156 +0,0 @@
.. include:: ./vars.rst
Permissions
===========
The Permissions Class represents data of permissions/roles.
ServerPermissions
-----------------
ServerPermissions are also known as roles. They give the general gist of permissions of all users in a Server.
name
~~~~
`String` that is the name of the role.
color
~~~~~
`Number` that represents a colour in base 10. To resolve it to a hex colour, just do: ``permission.color.toString(16)``
hoist
~~~~~
`Boolean`, whether the role should be a separate category in the users list.
managed
~~~~~~~
`Boolean`, whether the permission is managed by Discord. Currently only used by Twitch integration.
position
~~~~~~~~
`Number`, the position of the role that states its importance.
id
~~
`Number`, the ID of the role.
server
~~~~~~
Server_ that the role belongs to.
Actual Permissions:
~~~~~~~~~~~~~~~~~~~
`Actual Permissions` is not an attribute, however the following permissions are attributes of ServerPermissions. They are self-explanatory.
.. code-block:: js
{
createInstantInvite,
manageRoles, // if this is true all the others are true
manageChannels,
readMessages,
sendMessages,
sendTTSMessages,
manageMessages, // deleting, editing etc
embedLinks,
attachFiles,
readMessageHistory,
mentionEveryone,
voiceConnect,
voiceSpeak,
voiceMuteMembers,
voiceDeafenMembers,
voiceMoveMembers,
voiceUseVoiceActivation
}
serialize()
~~~~~~~~~~~
**Aliases** : *serialise()*
To get a valid `Object` of the actual permissions of the object, just do `serverPermissions.serialise()` to get an object with the above mentioned permissions
ChannelPermissions
------------------
ChannelPermissions are based from a ServerPermissions object (although not actually extending them, none of the Permissions objects extend each other). It represents an override/overwrite of a server permission.
Actual Permissions:
~~~~~~~~~~~~~~~~~~~
.. code-block:: js
{
createInstantInvite,
manageRoles,
manageChannels,
readMessages,
sendMessages,
sendTTSMessages,
manageMessages,
embedLinks,
attachFiles,
readMessageHistory,
mentionEveryone,
voiceConnect,
voiceSpeak,
voiceMuteMembers,
voiceDeafenMembers,
voiceMoveMember,
voiceUseVoiceActivation
}
serialize()
~~~~~~~~~~~
**Aliases** : *serialise()*
To get a valid `Object` of the actual permissions of the object, just do `channelPermissions.serialise()` to get an object with the above mentioned permissions
EvaluatedPermissions
--------------------
EvaluatedPermissions represents the permissions of a user in a channel, taking into account all roles and overwrites active on them; an evaluation of their permissions.
Actual Permissions:
~~~~~~~~~~~~~~~~~~~
EvaluatedPermissions has the same permissions as ChannelPermissions.
.. code-block:: js
{
createInstantInvite,
manageRoles,
manageChannels,
readMessages,
sendMessages,
sendTTSMessages,
manageMessages,
embedLinks,
attachFiles,
readMessageHistory,
mentionEveryone,
voiceConnect,
voiceSpeak,
voiceMuteMembers,
voiceDeafenMembers,
voiceMoveMember,
voiceUseVoiceActivation
}
serialize()
~~~~~~~~~~~
**Aliases** : *serialise()*
To get a valid `Object` of the actual permissions of the object, just do `channelPermissions.serialise()` to get an object with the above mentioned permissions

View File

@@ -1,41 +1,30 @@
.. include:: ./vars.rst
PMChannel
=========
The PMChannel Class is used to represent data about a Private Message Channel.
.. note:: Beware! The PMChannel class does `not` extend the Channel_ class.
Attributes
----------
user
~~~~
The recipient User_ of the PM Channel.
id
~~
`String` UUID of the PM Channel.
messages
~~~~~~~~
An `Array` of Message_ objects. Contains all the cached messages sent in this channel up to a limit of 1000. If the limit is reached, the oldest message is removed first to make space for it.
Functions
---------
getMessage(key, value)
~~~~~~~~~~~~~~~~~~~~~~
Gets a Message_ from the PM Channel that matches the specified criteria. E.g:
.. code-block:: js
pmchannel.getMessage("id", 1243987349) // returns a Message where message.id === 1243987349
- **key** - a `String` that is the key
- **value** - a `String` that is the value
.. include:: ./vars.rst
PMChannel
=========
**extends** Channel_
A PMChannel is a Private/Direct channel between the Client and another user.
------
Attributes
----------
--------
messages
~~~~~~~~
A Cache_ of Message_ objects.
recipient
~~~~~~~~~
The User_ that is the recipient of the Channel.
lastMessage
~~~~~~~~~~~
The last Message_ sent in the channel, may be null if no messages have been sent during the time the bound Client_ has been online.

View File

@@ -1,39 +0,0 @@
.. include:: ./vars.rst
Resolvables
===========
To be robust, discord.js needs to handle a wide amount of ambiguous data that is supplied to it. This means you can use functions much more easily. Anything that is resolvable means it can be normalised without you having to do it explicitly.
Resolvables are not objects or classes, they are just ways of expressing what type of data is expected.
Channel Resolvable
------------------
A Channel Resolvable is data that can be resolved to a channel ID. Here is what is currently supported:
- A Channel_ object
- A Server_ object (the #general channel of the server will be used)
- A `String` representing the channel ID
- A Message_ (the channel the message was sent in will be used)
- A User_ (will get the PM channel with the specified user)
.. note:: A User cannot always be specified in certain cases. For example, if using `bot.setTopic`, a User or PM Channel can't be specified as these do not support channel topics.
Server Resolvable
-----------------
A Server Resolvable is anything that can be resolved to a server ID. Here is what you can use:
- A Server_ object
- A Channel_ object
- A Message_ object
- A `String` representing the ID of the server
Invite Resolvable
-----------------
An Invite Resolvable is anything that resolves to an invite code. Here is what you can use:
- An Invite_ object
- A `String` which is either the code or an invite URL containing it (e.g. ``https://discord.gg/0SCTAU1wZTZtIopF``)

79
docs/docs_resolvables.rst Normal file
View File

@@ -0,0 +1,79 @@
.. include:: ./vars.rst
Resolvables
===========
In discord.js, the aim is to allow the end developer to have freedom in what sort of data types they supply. References to any sort of resolvable basically mean what types of data you can provide. The different resolvables are shown before:
Channel Resolvable
------------------
A Channel Resolvable allows:
- Channel_
- Server_
- Message_
- User_ (in some instances)
- String of Channel ID
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.
Base64 Resolvable
-----------------
A Base64 Resolvable allows:
- Buffer
- String

79
docs/docs_role.rst Normal file
View File

@@ -0,0 +1,79 @@
.. include:: ./vars.rst
Role
====
Represents data for a Server Role.
-----------
Attributes
----------
--------
position
~~~~~~~~
`Number`, position of the role when viewing the roles of a server.
name
~~~~
`String`, name of the role.
managed
~~~~~~~
`Boolean`, whether Discord has created the role itself. Currently only used for Twitch integration.
id
~~
`String`, ID of the role.
hoist
~~~~~
`Boolean`, whether the role should be displayed as a separate category in the users section.
color
~~~~~
`Number`, a base 10 colour. Use ``role.colorAsHex()`` to get a hex colour instead.
server
~~~~~~
The Server_ the role belongs to.
client
~~~~~~
The Client_ that cached the role.
------
Functions
---------
-------
serialise()
~~~~~~~~~~~
**Aliases:** `serialize`
Makes an object with the permission names found in `Permission Constants`_ and a boolean value for them.
hasPermission(permission)
~~~~~~~~~~~~~~~~~~~~~~~~~
Sees whether the role has the permission given.
- **permission** - See `Permission Constants`_ for valid permission names.
colorAsHex()
~~~~~~~~~~~~
Returns the role's colour as hex, e.g. ``#FF0000``.

View File

@@ -1,107 +1,90 @@
.. include:: ./vars.rst
Servers
=======
The Server Class is used to represent data about a server.
Attributes
----------
client
~~~~~~
The Discord Client_ that the Server was cached by.
region
~~~~~~
The region that the server is in, a `String`.
name
~~~~
The server's name, as a `String`.
id
~~
The server's id, as a `String`.
members
~~~~~~~
**Aliases** : `users`
The members in a server, an `Array` of User_ objects.
channels
~~~~~~~~
The channels in a server, an `Array` of Channel_ objects.
icon
~~~~
The icon ID of the server if it has one as a `String`, otherwise it is `null`.
iconURL
~~~~~~~
A `String` that is the URL of the server icon if it has one, otherwise it is `null`.
afkTimeout
~~~~~~~~~~
A `Number` that is the AFK Timeout of the Server.
afkChannel
~~~~~~~~~~
A Channel_ that represents the AFK Channel of the server if it has one, otherwise it is `null`.
defaultChannel
~~~~~~~~~~~~~~
The **#general** Channel_ of the server.
owner
~~~~~
A User_ object representing the user that owns the server.
-----
Functions
---------
.. note:: When concatenated with a String, the object will become the server's name, e.g. ``"this is " + server`` would be ``this is Discord API`` if the server was called `Discord API`.
getChannel(key, value)
~~~~~~~~~~~~~~~~~~~~~~
Gets a Channel_ that matches the specified criteria. E.g:
.. code-block:: js
server.getChannel("id", 1243987349) // returns a Channel where channel.id === 1243987349
- **key** - a `String` that is the key
- **value** - a `String` that is the value
getMember(key, value)
~~~~~~~~~~~~~~~~~~~~~
Gets a Member_ that matches the specified criteria. E.g:
.. code-block:: js
server.getMember("id", 1243987349) // returns a Member where member.id === 1243987349
- **key** - a `String` that is the key
- **value** - a `String` that is the value
equals(object)
~~~~~~~~~~~~~~
Returns a `Boolean` depending on whether the Server's ID (``server.id``) equals the object's ID (``object.id``). You should **always**, always use this if you want to compare servers. **NEVER** do ``server1 == server2``.
.. include:: ./vars.rst
Server
======
**extends** Equality_
Stores information about a Discord Server.
Attributes
----------
--------
client
~~~~~~
The Client_ that cached the Server.
region
~~~~~~
`String`, region of the server.
name
~~~~
`String`, name of the server.
id
~~
`String`, ID of the server - never changes.
members
~~~~~~~
Members of the server, a Cache_ of User_ objects.
channels
~~~~~~~~
Channels in the server, a Cache_ of ServerChannel_ objects.
roles
~~~~~
Roles of the server, a Cache_ of Role_ objects.
icon
~~~~
ID/Hash of server icon, use ``server.iconURL`` for an URL to the icon.
afkTimeout
~~~~~~~~~~
`Number`, the AFK timeout in seconds before a user is classed as AFK. If there isn't an AFK timeout, this will be null.
afkChannel
~~~~~~~~~~
The channel where AFK users are moved to, ServerChannel_ object. If one isn't set, this will be null.
defaultChannel
~~~~~~~~~~~~~~
The ``#general`` ServerChannel_ of the server.
owner
~~~~~
The founder of the server, a User_ object.
iconURL
~~~~~~~
The URL of the Server's icon. If the server doesn't have an icon, this will be null.
-----
Functions
---------
rolesOfUser(user)
~~~~~~~~~~~~~~~~~
**Aliases**: `rolesOf`
Returns an array of the roles affecting a user server-wide.

View File

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

30
docs/docs_textchannel.rst Normal file
View File

@@ -0,0 +1,30 @@
.. include:: ./vars.rst
TextChannel
===========
**extends** ServerChannel_
A text channel of a server.
------
Attributes
----------
--------
topic
~~~~~
The topic of the channel, a `String`.
lastMessage
~~~~~~~~~~~
Last Message_ sent in the channel. May be null if no messages sent whilst the Client was online.
messages
~~~~~~~~
A Cache_ of Message_ objects.

View File

@@ -1,67 +1,75 @@
.. include:: ./vars.rst
Users
=====
The User Class is used to represent data about users.
Attributes
----------
username
~~~~~~~~
A `String` that is the username of the user.
discriminator
~~~~~~~~~~~~~
Used to differentiate users with the same username, provided by Discord. If you want to differentiate users, we'd recommend using the `id` attribute.
id
~~
A `String` UUID of the user, will never change.
avatar
~~~~~~
A `String` that is the user's avatar's ID, or if they don't have one this is `null`.
avatarURL
~~~~~~~~~
A `String` that points to the user's avatar's URL, or if they don't have an avatar this is `null`.
status
~~~~~~
The status of the user as a `String`; offline/online/idle.
-----
Functions
---------
mention()
~~~~~~~~~
Returns a `String`. This function will generate the mention string for the user, which when sent will preview as a mention. E.g:
.. code-block:: js
user.mention(); // something like <@3245982345035>
This is mainly used internally by the API to correct mentions when sending messages, however you can use it.
.. note:: You can also just concatenate a User object with strings to get the mention code, as the `toString()` method points to this. This is useful when sending messages.
equals(object)
~~~~~~~~~~~~~~
Returns a `Boolean` depending on whether the User's ID (``user.id``) equals the object's ID (``object.id``). You should **always**, always use this if you want to compare users. **NEVER** do ``user1 == user2``.
equalsStrict(object)
~~~~~~~~~~~~~~~~~~~~
Sees if the supplied object has the same username, ID, avatar and discriminator of the user. Mainly used internally. Returns a `Boolean` depending on the result.
.. include:: ./vars.rst
User
====
**extends** Equality_
Stores information about users.
Attributes
----------
--------
client
~~~~~~
The Client_ that created the user.
username
~~~~~~~~
`String`, username of the User.
discriminator
~~~~~~~~~~~~~
`Integer` from 0-9999, don't use this to identify users. Used to separate the user from the 9998 others that may have the same username. Made redundant by ``user.id``.
id
~~
`String` (do not parse to an Integer, will become inaccurate). The ID of a user, never changes.
avatar
~~~~~~
`String`, the ID/hash of a user's avatar. To get a path to their avatar, see ``user.avatarURL``.
status
~~~~~~
The status of a user, `String`. Either ``online``, ``offline`` or ``idle``.
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 : <Channel Object> // channel they are typing in.
}
avatarURL
~~~~~~~~~
A valid URL to the user's avatar if they have one, otherwise 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.

View File

@@ -0,0 +1,10 @@
.. include:: ./vars.rst
VoiceChannel
============
**extends** ServerChannel_
A voice channel of a server. Currently, the voice channel class has no differences to the ServerChannel class.
------

View File

@@ -0,0 +1,27 @@
.. include:: ./vars.rst
VoiceConnection
===============
**Warning! Still experimental!**
As of discord.js v5.0.0, voice support has been added. This means you can stream audio but not yet receive.
---------
Attributes
----------
---------
voiceChannel
------------
VoiceChannel_ that the connection is for
client
------
Client_ the connection belongs to
more docs coming soon :O

View File

@@ -1,48 +0,0 @@
===========
Get Started
===========
Installation
------------
Linux
~~~~~~
Install Python 2 and then run ``npm install discord.js --save`` in your project's directory and you should be good to go!
OS X
~~~~
Python 2 and **potentially** X Code, try building without first.
Windows
~~~~~~~~~~~~
**TL;DR You need Visual Studio and Python 2**
Unfortunately, the Windows installation process is a little more lengthy. You need to have `Visual Studio Express`_ (or any of the other distributions of it). This is necessary for build tools for the WebSocket dependency.
.. note:: If you are using another version of Visual Studio, such as 2012, replace the flag with ``--msvs_version=2012``
After you have installed Visual Studio, you then need to install any Python setups that are version 2.
After you have obtained these tools, you need to run ``npm install discord.js --save --msvs_version=2015`` in your working directory. Hopefully this should all go well!
Cloning the Repo
----------------
If you want to try some examples or make your own changes to discord.js, you can `clone the repo`_. After that run ``npm install`` to install dependencies.
Running Examples
~~~~~~~~~~~~~~~~
If you've cloned the repo, you also have the option to run some examples. You can also do this by just copying the examples_ and then running them. I'd be more than happy to get some pull requests if you want to make any patches ;)
Before you run them though, you need to configure the ``examples/auth.json`` file. This should contain valid Discord credentials and passwords.
After you've configured your credentials, just run ``node examples/pingpong.js`` to run the ping pong example.
.. _Visual Studio Express: https://www.visualstudio.com/en-us/downloads/download-visual-studio-vs.aspx
.. _clone the repo: https://github.com/hydrabolt/discord.js.git
.. _examples: https://github.com/hydrabolt/discord.js/tree/master/examples

View File

@@ -2,6 +2,8 @@
sphinx-quickstart on Fri Sep 25 17:25:49 2015.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
.. include:: ./vars.rst
Welcome to discord.js's documentation!
======================================
@@ -14,35 +16,52 @@ Feel free to make any contributions you want, whether it be through creating an
.. note:: This documentation is still a work-in-progress, apologies if something isn't yet documented!
Contents:
.. _general-docs:
.. toctree::
:maxdepth: 2
:caption: General
get_started
troubleshooting
create_simple_bot
.. _docs:
.. toctree::
:maxdepth: 2
:caption: Documentation
:maxdepth: 1
:caption: General
migrating
.. toctree::
:maxdepth: 1
:caption: Channel Documentation
docs_module
docs_resolvable
docs_client
docs_user
docs_member
docs_server
docs_channel
docs_pmchannel
docs_serverchannel
docs_textchannel
docs_voicechannel
.. toctree::
:maxdepth: 1
:caption: Documentation
docs_client
docs_server
docs_user
docs_message
docs_invite
docs_permissions
docs_embed
docs_voiceconnection
.. toctree::
:maxdepth: 1
:caption: Permission Documentation
docs_permissionconstants
docs_role
docs_permissionoverwrite
docs_channelpermissions
.. toctree::
:maxdepth: 1
:caption: Util Documentation
docs_cache
docs_equality
docs_resolvables
Indices and tables

27
docs/migrating.rst Normal file
View File

@@ -0,0 +1,27 @@
.. include:: ./vars.rst
Updating to v5.0.0
==================
If you're coming from versions below v5, you might find some changes. Here are the major changes:
--------
Change 1
--------
--------
.. code-block:: js
// OLD:
client.getUser();
client.getServer();
server.getMember(); // etc etc
// NEW:
client.users.get();
client.servers.get();
client.members.get();

View File

@@ -1,19 +1,28 @@
.. _Client : ./docs_client.html
.. _Cache : ./docs_cache.html
.. _User : ./docs_user.html
.. _ready : #ready
.. _Server : ./docs_server.html
.. _Channel : ./docs_channel.html
.. _Message : ./docs_message.html
.. _ServerChannel : ./docs_serverchannel.html
.. _TextChannel : ./docs_textchannel.html
.. _VoiceChannel : ./docs_voicechannel.html
.. _PMChannel : ./docs_pmchannel.html
.. _Message : ./docs_message.html
.. _Invite : ./docs_invite.html
.. _Channel Resolvable : ./docs_resolvable.html#channel-resolvable
.. _Server Resolvable : ./docs_resolvable.html#channel-resolvable
.. _Invite Resolvable : ./docs_resolvable.html#invite-resolvable
.. _Equality : ./docs_equality.html
.. _Role : ./docs_role.html
.. _ChannelPermissions : ./docs_channelpermissions.html
.. _PermissionOverwrite : ./docs_permissionoverwrite.html
.. _Permission Constants : ./docs_permissionconstants.html
.. _Resolvables : ./docs_resolvables.html
.. _VoiceConnection : ./docs_voiceconnection.html
.. _Promises : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
.. _ServerPermissions : ./docs_permissions.html#id1
.. _Roles : ./docs_permissions.html#id1
.. _ChannelPermissions : ./docs_permissions.html#id3
.. _EvaluatedPermissions : ./docs_permissions.html#id6
.. _Member : ./docs_member.html
.. _Colors : ./docs_module.html#discord-colors
.. _Embed : ./docs_embed.html
.. _EventEmitter : https://nodejs.org/api/events.html#events_class_events_eventemitter
.. _Channel Resolvable : http://discordjs.readthedocs.org/en/rewrite-docs/docs_resolvables.html#channel-resolvable
.. _String Resolvable : http://discordjs.readthedocs.org/en/rewrite-docs/docs_resolvables.html#string-resolvable
.. _Message Resolvable : http://discordjs.readthedocs.org/en/rewrite-docs/docs_resolvables.html#message-resolvable
.. _Server Resolvable : http://discordjs.readthedocs.org/en/rewrite-docs/docs_resolvables.html#server-resolvable
.. _Invite Resolvable : http://discordjs.readthedocs.org/en/rewrite-docs/docs_resolvables.html#invite-id-resolvable
.. _User Resolvable : http://discordjs.readthedocs.org/en/rewrite-docs/docs_resolvables.html#user-resolvable
.. _Base64 Resolvable : http://discordjs.readthedocs.org/en/rewrite-docs/docs_resolvables.html#base64-resolvable
.. _VoiceChannel Resolvable : http://discordjs.readthedocs.org/en/rewrite-docs/docs_resolvables.html#voice-channel-resolvable

View File

@@ -1,835 +1,58 @@
"use strict";
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var InternalClient = require("./InternalClient.js");
var EventEmitter = require("events");
var Client = (function (_EventEmitter) {
_inherits(Client, _EventEmitter);
/*
this class is an interface for the internal
client.
*/
function Client(options) {
_classCallCheck(this, Client);
_EventEmitter.call(this);
this.options = options || {};
this.internal = new InternalClient(this);
}
// def login
Client.prototype.login = function login(email, password) {
var cb = arguments.length <= 2 || arguments[2] === undefined ? function (err, token) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.login(email, password).then(function (token) {
cb(null, token);
resolve(token);
})["catch"](function (e) {
cb(e);
reject(e);
});
});
};
// def logout
Client.prototype.logout = function logout() {
var cb = arguments.length <= 0 || arguments[0] === undefined ? function (err) {} : arguments[0];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.logout().then(function () {
cb();
resolve();
})["catch"](function (e) {
cb(e);
reject(e);
});
});
};
// def sendMessage
Client.prototype.sendMessage = function sendMessage(where, content) {
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var callback = arguments.length <= 3 || arguments[3] === undefined ? function (e, m) {} : arguments[3];
var self = this;
return new Promise(function (resolve, reject) {
if (typeof options === "function") {
// options is the callback
callback = options;
}
self.internal.sendMessage(where, content, options).then(function (m) {
callback(null, m);
resolve(m);
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def sendTTSMessage
Client.prototype.sendTTSMessage = function sendTTSMessage(where, content) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (e, m) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
self.sendMessage(where, content, { tts: true }).then(function (m) {
callback(null, m);
resolve(m);
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def reply
Client.prototype.reply = function reply(where, content) {
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var callback = arguments.length <= 3 || arguments[3] === undefined ? function (e, m) {} : arguments[3];
var self = this;
return new Promise(function (resolve, reject) {
if (typeof options === "function") {
// options is the callback
callback = options;
}
var msg = self.internal.resolver.resolveMessage(where);
if (msg) {
content = msg.author + ", " + content;
self.internal.sendMessage(msg, content, options).then(function (m) {
callback(null, m);
resolve(m);
})["catch"](function (e) {
callback(e);
reject(e);
});
} else {
var err = new Error("Destination not resolvable to a message!");
callback(err);
reject(err);
}
});
};
// def replyTTS
Client.prototype.replyTTS = function replyTTS(where, content) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function () {} : arguments[2];
return new Promise(function (resolve, reject) {
self.reply(where, content, { tts: true }).then(function (m) {
callback(null, m);
resolve(m);
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def deleteMessage
Client.prototype.deleteMessage = function deleteMessage(msg) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (e) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
if (typeof options === "function") {
// options is the callback
callback = options;
}
self.internal.deleteMessage(msg, options).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
//def updateMessage
Client.prototype.updateMessage = function updateMessage(msg, content) {
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var callback = arguments.length <= 3 || arguments[3] === undefined ? function (err, msg) {} : arguments[3];
var self = this;
return new Promise(function (resolve, reject) {
if (typeof options === "function") {
// options is the callback
callback = options;
}
self.internal.updateMessage(msg, content, options).then(function (msg) {
callback(null, msg);
resolve(msg);
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def getChannelLogs
Client.prototype.getChannelLogs = function getChannelLogs(where) {
var limit = arguments.length <= 1 || arguments[1] === undefined ? 500 : arguments[1];
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var callback = arguments.length <= 3 || arguments[3] === undefined ? function (err, logs) {} : arguments[3];
var self = this;
return new Promise(function (resolve, reject) {
if (typeof options === "function") {
// options is the callback
callback = options;
}
self.internal.getChannelLogs(where, limit, options).then(function (logs) {
callback(null, logs);
resolve(logs);
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def getBans
Client.prototype.getBans = function getBans(where) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err, bans) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.getBans(where).then(function (bans) {
callback(null, bans);
resolve(bans);
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def sendFile
Client.prototype.sendFile = function sendFile(where, attachment) {
var name = arguments.length <= 2 || arguments[2] === undefined ? "image.png" : arguments[2];
var callback = arguments.length <= 3 || arguments[3] === undefined ? function (err, m) {} : arguments[3];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.sendFile(where, attachment, name).then(function (m) {
callback(null, m);
resolve(m);
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def joinServer
Client.prototype.joinServer = function joinServer(invite) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err, srv) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.joinServer(invite).then(function (srv) {
callback(null, srv);
resolve(srv);
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def createServer
Client.prototype.createServer = function createServer(name) {
var region = arguments.length <= 1 || arguments[1] === undefined ? "london" : arguments[1];
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err, srv) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.createServer(name, region).then(function (srv) {
callback(null, srv);
resolve(srv);
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def leaveServer
Client.prototype.leaveServer = function leaveServer(server) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.leaveServer(server).then(function () {
callback();resolve();
})["catch"](function (e) {
callback(e);reject(e);
});
});
};
// def createChannel
Client.prototype.createChannel = function createChannel(server, name) {
var type = arguments.length <= 2 || arguments[2] === undefined ? "text" : arguments[2];
var callback = arguments.length <= 3 || arguments[3] === undefined ? function (err, channel) {} : arguments[3];
var self = this;
return new Promise(function (resolve, reject) {
if (typeof type === "function") {
// options is the callback
callback = type;
}
self.internal.createChannel(server, name, type).then(function (channel) {
callback(channel);resolve(channel);
})["catch"](function (e) {
callback(e);reject(e);
});
});
};
// def deleteChannel
Client.prototype.deleteChannel = function deleteChannel(channel) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.deleteChannel(channel).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);reject(e);
});
});
};
//def banMember
Client.prototype.banMember = function banMember(user, server) {
var length = arguments.length <= 2 || arguments[2] === undefined ? 1 : arguments[2];
var callback = arguments.length <= 3 || arguments[3] === undefined ? function (err) {} : arguments[3];
var self = this;
return new Promise(function (resolve, reject) {
if (typeof length === "function") {
// length is the callback
callback = length;
}
self.internal.banMember(user, server, length).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);reject(e);
});
});
};
//def unbanMember
Client.prototype.unbanMember = function unbanMember(user, server) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.unbanMember(user, server).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);reject(e);
});
});
};
//def kickMember
Client.prototype.kickMember = function kickMember(user, server) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.kickMember(user, server).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);reject(e);
});
});
};
//def createRole
Client.prototype.createRole = function createRole(server) {
var data = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err, res) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
if (typeof data === "function") {
// data is the callback
callback = data;
}
self.internal.createRole(server, data).then(function (role) {
callback(null, role);
resolve(role);
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
//def updateRole
Client.prototype.updateRole = function updateRole(role) {
var data = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err, res) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
if (typeof data === "function") {
// data is the callback
callback = data;
}
self.internal.updateRole(role, data).then(function (role) {
callback(null, role);
resolve(role);
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
//def deleteRole
Client.prototype.deleteRole = function deleteRole(role) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.deleteRole(role).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
//def addMemberToRole
Client.prototype.addMemberToRole = function addMemberToRole(member, role) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.addMemberToRole(member, role).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def addUserToRole
Client.prototype.addUserToRole = function addUserToRole(member, role) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err) {} : arguments[2];
return this.addMemberToRole(member, role, callback);
};
// def removeMemberFromRole
Client.prototype.removeMemberFromRole = function removeMemberFromRole(member, role) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.removeMemberFromRole(member, role).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def removeUserFromRole
Client.prototype.removeUserFromRole = function removeUserFromRole(member, role) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err) {} : arguments[2];
return this.removeUserFromRole(member, role, callback);
};
// def createInvite
Client.prototype.createInvite = function createInvite(chanServ, options) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err, invite) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
if (typeof options === "function") {
// length is the callback
callback = options;
}
self.internal.createInvite(chanServ, options).then(function (invite) {
callback(null, invite);
resolve(invite);
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def deleteInvite
Client.prototype.deleteInvite = function deleteInvite(invite) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.deleteInvite(invite).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def overwritePermissions
Client.prototype.overwritePermissions = function overwritePermissions(channel, role) {
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var callback = arguments.length <= 3 || arguments[3] === undefined ? function (err) {} : arguments[3];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.overwritePermissions(channel, role, options).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
//def setStatus
Client.prototype.setStatus = function setStatus(idleStatus, gameID) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
if (typeof gameID === "function") {
// gameID is the callback
callback = gameID;
} else if (typeof idleStatus === "function") {
// idleStatus is the callback
callback = idleStatus;
}
self.internal.setStatus(idleStatus, gameID).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
//def sendTyping
Client.prototype.sendTyping = function sendTyping(channel) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.sendTyping(channel).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
// def setTopic
Client.prototype.setTopic = function setTopic(channel, topic) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.setTopic(channel, topic).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
//def setChannelName
Client.prototype.setChannelName = function setChannelName(channel, topic) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.setChannelName(channel, topic).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
//def setChannelNameAndTopic
Client.prototype.setChannelNameAndTopic = function setChannelNameAndTopic(channel, name, topic) {
var callback = arguments.length <= 3 || arguments[3] === undefined ? function (err) {} : arguments[3];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.setChannelNameAndTopic(channel, name, topic).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
//def updateChannel
Client.prototype.updateChannel = function updateChannel(channel, data) {
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err) {} : arguments[2];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.updateChannel(channel, data).then(function () {
callback();
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
//def startTyping
Client.prototype.startTyping = function startTyping(channel) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.startTyping(channel).then(function () {
callback(null);
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
//def stopTyping
Client.prototype.stopTyping = function stopTyping(channel) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.stopTyping(channel).then(function () {
callback(null);
resolve();
})["catch"](function (e) {
callback(e);
reject(e);
});
});
};
//def updateDetails
Client.prototype.updateDetails = function updateDetails(details) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.updateDetails(details).then(function () {
callback();
resolve();
})["catch"](function (err) {
callback(err);
reject(err);
});
});
};
//def setUsername
Client.prototype.setUsername = function setUsername(name) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.setUsername(name).then(function () {
callback();
resolve();
})["catch"](function (err) {
callback(err);
reject(err);
});
});
};
//def setAvatar
Client.prototype.setAvatar = function setAvatar(avatar) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.setAvatar(avatar).then(function () {
callback();
resolve();
})["catch"](function (err) {
callback(err);
reject(err);
});
});
};
//def joinVoiceChannel
Client.prototype.joinVoiceChannel = function joinVoiceChannel(channel) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
self.internal.joinVoiceChannel(channel).then(function (chan) {
callback(null, chan);
resolve(chan);
})["catch"](function (err) {
callback(err);
reject(err);
});
});
};
_createClass(Client, [{
key: "users",
get: function get() {
return this.internal.users;
}
}, {
key: "channels",
get: function get() {
return this.internal.channels;
}
}, {
key: "servers",
get: function get() {
return this.internal.servers;
}
}, {
key: "privateChannels",
get: function get() {
return this.internal.private_channels;
}
}, {
key: "voiceConnection",
get: function get() {
return this.internal.voiceConnection;
}
}, {
key: "readyTime",
get: function get() {
return this.internal.readyTime;
}
}, {
key: "uptime",
get: function get() {
return this.internal.uptime;
}
}, {
key: "user",
get: function get() {
return this.internal.user;
}
}]);
return Client;
})(EventEmitter);
module.exports = Client;
"use strict";var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if("value" in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var InternalClient=require("./InternalClient.js");var EventEmitter=require("events");var Client=(function(_EventEmitter){_inherits(Client,_EventEmitter); /*
this class is an interface for the internal
client.
*/function Client(options){_classCallCheck(this,Client);_EventEmitter.call(this);this.options = options || {};this.internal = new InternalClient(this);} // def login
Client.prototype.login = function login(email,password){var cb=arguments.length <= 2 || arguments[2] === undefined?function(err,token){}:arguments[2];var self=this;return new Promise(function(resolve,reject){self.internal.login(email,password).then(function(token){cb(null,token);resolve(token);})["catch"](function(e){cb(e);reject(e);});});}; // def logout
Client.prototype.logout = function logout(){var cb=arguments.length <= 0 || arguments[0] === undefined?function(err){}:arguments[0];var self=this;return new Promise(function(resolve,reject){self.internal.logout().then(function(){cb();resolve();})["catch"](function(e){cb(e);reject(e);});});}; // def sendMessage
Client.prototype.sendMessage = function sendMessage(where,content){var options=arguments.length <= 2 || arguments[2] === undefined?{}:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function(e,m){}:arguments[3];var self=this;return new Promise(function(resolve,reject){if(typeof options === "function"){ // options is the callback
callback = options;}self.internal.sendMessage(where,content,options).then(function(m){callback(null,m);resolve(m);})["catch"](function(e){callback(e);reject(e);});});}; // def sendTTSMessage
Client.prototype.sendTTSMessage = function sendTTSMessage(where,content){var callback=arguments.length <= 2 || arguments[2] === undefined?function(e,m){}:arguments[2];var self=this;return new Promise(function(resolve,reject){self.sendMessage(where,content,{tts:true}).then(function(m){callback(null,m);resolve(m);})["catch"](function(e){callback(e);reject(e);});});}; // def reply
Client.prototype.reply = function reply(where,content){var options=arguments.length <= 2 || arguments[2] === undefined?{}:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function(e,m){}:arguments[3];var self=this;return new Promise(function(resolve,reject){if(typeof options === "function"){ // options is the callback
callback = options;}var msg=self.internal.resolver.resolveMessage(where);if(msg){content = msg.author + ", " + content;self.internal.sendMessage(msg,content,options).then(function(m){callback(null,m);resolve(m);})["catch"](function(e){callback(e);reject(e);});}else {var err=new Error("Destination not resolvable to a message!");callback(err);reject(err);}});}; // def replyTTS
Client.prototype.replyTTS = function replyTTS(where,content){var callback=arguments.length <= 2 || arguments[2] === undefined?function(){}:arguments[2];return new Promise(function(resolve,reject){self.reply(where,content,{tts:true}).then(function(m){callback(null,m);resolve(m);})["catch"](function(e){callback(e);reject(e);});});}; // def deleteMessage
Client.prototype.deleteMessage = function deleteMessage(msg){var options=arguments.length <= 1 || arguments[1] === undefined?{}:arguments[1];var callback=arguments.length <= 2 || arguments[2] === undefined?function(e){}:arguments[2];var self=this;return new Promise(function(resolve,reject){if(typeof options === "function"){ // options is the callback
callback = options;}self.internal.deleteMessage(msg,options).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def updateMessage
Client.prototype.updateMessage = function updateMessage(msg,content){var options=arguments.length <= 2 || arguments[2] === undefined?{}:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function(err,msg){}:arguments[3];var self=this;return new Promise(function(resolve,reject){if(typeof options === "function"){ // options is the callback
callback = options;}self.internal.updateMessage(msg,content,options).then(function(msg){callback(null,msg);resolve(msg);})["catch"](function(e){callback(e);reject(e);});});}; // def getChannelLogs
Client.prototype.getChannelLogs = function getChannelLogs(where){var limit=arguments.length <= 1 || arguments[1] === undefined?500:arguments[1];var options=arguments.length <= 2 || arguments[2] === undefined?{}:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function(err,logs){}:arguments[3];var self=this;return new Promise(function(resolve,reject){if(typeof options === "function"){ // options is the callback
callback = options;}self.internal.getChannelLogs(where,limit,options).then(function(logs){callback(null,logs);resolve(logs);})["catch"](function(e){callback(e);reject(e);});});}; // def getBans
Client.prototype.getBans = function getBans(where){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err,bans){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.getBans(where).then(function(bans){callback(null,bans);resolve(bans);})["catch"](function(e){callback(e);reject(e);});});}; // def sendFile
Client.prototype.sendFile = function sendFile(where,attachment){var name=arguments.length <= 2 || arguments[2] === undefined?"image.png":arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function(err,m){}:arguments[3];var self=this;return new Promise(function(resolve,reject){self.internal.sendFile(where,attachment,name).then(function(m){callback(null,m);resolve(m);})["catch"](function(e){callback(e);reject(e);});});}; // def joinServer
Client.prototype.joinServer = function joinServer(invite){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err,srv){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.joinServer(invite).then(function(srv){callback(null,srv);resolve(srv);})["catch"](function(e){callback(e);reject(e);});});}; // def createServer
Client.prototype.createServer = function createServer(name){var region=arguments.length <= 1 || arguments[1] === undefined?"london":arguments[1];var callback=arguments.length <= 2 || arguments[2] === undefined?function(err,srv){}:arguments[2];var self=this;return new Promise(function(resolve,reject){self.internal.createServer(name,region).then(function(srv){callback(null,srv);resolve(srv);})["catch"](function(e){callback(e);reject(e);});});}; // def leaveServer
Client.prototype.leaveServer = function leaveServer(server){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.leaveServer(server).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; // def createChannel
Client.prototype.createChannel = function createChannel(server,name){var type=arguments.length <= 2 || arguments[2] === undefined?"text":arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function(err,channel){}:arguments[3];var self=this;return new Promise(function(resolve,reject){if(typeof type === "function"){ // options is the callback
callback = type;}self.internal.createChannel(server,name,type).then(function(channel){callback(channel);resolve(channel);})["catch"](function(e){callback(e);reject(e);});});}; // def deleteChannel
Client.prototype.deleteChannel = function deleteChannel(channel){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.deleteChannel(channel).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def banMember
Client.prototype.banMember = function banMember(user,server){var length=arguments.length <= 2 || arguments[2] === undefined?1:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function(err){}:arguments[3];var self=this;return new Promise(function(resolve,reject){if(typeof length === "function"){ // length is the callback
callback = length;}self.internal.banMember(user,server,length).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def unbanMember
Client.prototype.unbanMember = function unbanMember(user,server){var callback=arguments.length <= 2 || arguments[2] === undefined?function(err){}:arguments[2];var self=this;return new Promise(function(resolve,reject){self.internal.unbanMember(user,server).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def kickMember
Client.prototype.kickMember = function kickMember(user,server){var callback=arguments.length <= 2 || arguments[2] === undefined?function(err){}:arguments[2];var self=this;return new Promise(function(resolve,reject){self.internal.kickMember(user,server).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def createRole
Client.prototype.createRole = function createRole(server){var data=arguments.length <= 1 || arguments[1] === undefined?null:arguments[1];var callback=arguments.length <= 2 || arguments[2] === undefined?function(err,res){}:arguments[2];var self=this;return new Promise(function(resolve,reject){if(typeof data === "function"){ // data is the callback
callback = data;}self.internal.createRole(server,data).then(function(role){callback(null,role);resolve(role);})["catch"](function(e){callback(e);reject(e);});});}; //def updateRole
Client.prototype.updateRole = function updateRole(role){var data=arguments.length <= 1 || arguments[1] === undefined?null:arguments[1];var callback=arguments.length <= 2 || arguments[2] === undefined?function(err,res){}:arguments[2];var self=this;return new Promise(function(resolve,reject){if(typeof data === "function"){ // data is the callback
callback = data;}self.internal.updateRole(role,data).then(function(role){callback(null,role);resolve(role);})["catch"](function(e){callback(e);reject(e);});});}; //def deleteRole
Client.prototype.deleteRole = function deleteRole(role){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.deleteRole(role).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def addMemberToRole
Client.prototype.addMemberToRole = function addMemberToRole(member,role){var callback=arguments.length <= 2 || arguments[2] === undefined?function(err){}:arguments[2];var self=this;return new Promise(function(resolve,reject){self.internal.addMemberToRole(member,role).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; // def addUserToRole
Client.prototype.addUserToRole = function addUserToRole(member,role){var callback=arguments.length <= 2 || arguments[2] === undefined?function(err){}:arguments[2];return this.addMemberToRole(member,role,callback);}; // def removeMemberFromRole
Client.prototype.removeMemberFromRole = function removeMemberFromRole(member,role){var callback=arguments.length <= 2 || arguments[2] === undefined?function(err){}:arguments[2];var self=this;return new Promise(function(resolve,reject){self.internal.removeMemberFromRole(member,role).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; // def removeUserFromRole
Client.prototype.removeUserFromRole = function removeUserFromRole(member,role){var callback=arguments.length <= 2 || arguments[2] === undefined?function(err){}:arguments[2];return this.removeUserFromRole(member,role,callback);}; // def createInvite
Client.prototype.createInvite = function createInvite(chanServ,options){var callback=arguments.length <= 2 || arguments[2] === undefined?function(err,invite){}:arguments[2];var self=this;return new Promise(function(resolve,reject){if(typeof options === "function"){ // length is the callback
callback = options;}self.internal.createInvite(chanServ,options).then(function(invite){callback(null,invite);resolve(invite);})["catch"](function(e){callback(e);reject(e);});});}; // def deleteInvite
Client.prototype.deleteInvite = function deleteInvite(invite){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.deleteInvite(invite).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; // def overwritePermissions
Client.prototype.overwritePermissions = function overwritePermissions(channel,role){var options=arguments.length <= 2 || arguments[2] === undefined?{}:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function(err){}:arguments[3];var self=this;return new Promise(function(resolve,reject){self.internal.overwritePermissions(channel,role,options).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def setStatus
Client.prototype.setStatus = function setStatus(idleStatus,gameID){var callback=arguments.length <= 2 || arguments[2] === undefined?function(err){}:arguments[2];var self=this;return new Promise(function(resolve,reject){if(typeof gameID === "function"){ // gameID is the callback
callback = gameID;}else if(typeof idleStatus === "function"){ // idleStatus is the callback
callback = idleStatus;}self.internal.setStatus(idleStatus,gameID).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def sendTyping
Client.prototype.sendTyping = function sendTyping(channel){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.sendTyping(channel).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; // def setTopic
Client.prototype.setTopic = function setTopic(channel,topic){var callback=arguments.length <= 2 || arguments[2] === undefined?function(err){}:arguments[2];var self=this;return new Promise(function(resolve,reject){self.internal.setTopic(channel,topic).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def setChannelName
Client.prototype.setChannelName = function setChannelName(channel,name){var callback=arguments.length <= 2 || arguments[2] === undefined?function(err){}:arguments[2];var self=this;return new Promise(function(resolve,reject){self.internal.setChannelName(channel,name).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def setChannelNameAndTopic
Client.prototype.setChannelNameAndTopic = function setChannelNameAndTopic(channel,name,topic){var callback=arguments.length <= 3 || arguments[3] === undefined?function(err){}:arguments[3];var self=this;return new Promise(function(resolve,reject){self.internal.setChannelNameAndTopic(channel,name,topic).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def updateChannel
Client.prototype.updateChannel = function updateChannel(channel,data){var callback=arguments.length <= 2 || arguments[2] === undefined?function(err){}:arguments[2];var self=this;return new Promise(function(resolve,reject){self.internal.updateChannel(channel,data).then(function(){callback();resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def startTyping
Client.prototype.startTyping = function startTyping(channel){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.startTyping(channel).then(function(){callback(null);resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def stopTyping
Client.prototype.stopTyping = function stopTyping(channel){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.stopTyping(channel).then(function(){callback(null);resolve();})["catch"](function(e){callback(e);reject(e);});});}; //def updateDetails
Client.prototype.updateDetails = function updateDetails(details){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.updateDetails(details).then(function(){callback();resolve();})["catch"](function(err){callback(err);reject(err);});});}; //def setUsername
Client.prototype.setUsername = function setUsername(name){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.setUsername(name).then(function(){callback();resolve();})["catch"](function(err){callback(err);reject(err);});});}; //def setAvatar
Client.prototype.setAvatar = function setAvatar(avatar){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.setAvatar(avatar).then(function(){callback();resolve();})["catch"](function(err){callback(err);reject(err);});});}; //def joinVoiceChannel
Client.prototype.joinVoiceChannel = function joinVoiceChannel(channel){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;return new Promise(function(resolve,reject){self.internal.joinVoiceChannel(channel).then(function(chan){callback(null,chan);resolve(chan);})["catch"](function(err){callback(err);reject(err);});});}; // def leaveVoiceChannel
Client.prototype.leaveVoiceChannel = function leaveVoiceChannel(){var callback=arguments.length <= 0 || arguments[0] === undefined?function(err){}:arguments[0];var self=this;return new Promise(function(resolve,reject){self.internal.leaveVoiceChannel().then(function(){callback();resolve();})["catch"](function(err){callback(err);reject(err);});});};_createClass(Client,[{key:"users",get:function get(){return this.internal.users;}},{key:"channels",get:function get(){return this.internal.channels;}},{key:"servers",get:function get(){return this.internal.servers;}},{key:"privateChannels",get:function get(){return this.internal.private_channels;}},{key:"voiceConnection",get:function get(){return this.internal.voiceConnection;}},{key:"readyTime",get:function get(){return this.internal.readyTime;}},{key:"uptime",get:function get(){return this.internal.uptime;}},{key:"user",get:function get(){return this.internal.user;}}]);return Client;})(EventEmitter);module.exports = Client;

View File

@@ -1,7 +1 @@
"use strict";
exports.IDLE = 0;
exports.LOGGING_IN = 1;
exports.LOGGED_IN = 2;
exports.READY = 3;
exports.DISCONNECTED = 4;
"use strict";exports.IDLE = 0;exports.LOGGING_IN = 1;exports.LOGGED_IN = 2;exports.READY = 3;exports.DISCONNECTED = 4;

File diff suppressed because it is too large Load Diff

View File

@@ -1,210 +1,13 @@
"use strict";
/* global Buffer */
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var fs = require("fs");
var User = require("../../Structures/User.js"),
Channel = require("../../Structures/Channel.js"),
TextChannel = require("../../Structures/TextChannel.js"),
VoiceChannel = require("../../Structures/VoiceChannel.js"),
ServerChannel = require("../../Structures/ServerChannel.js"),
PMChannel = require("../../Structures/PMChannel.js"),
Server = require("../../Structures/Server.js"),
Message = require("../../Structures/Message.js"),
Invite = require("../../Structures/Invite.js");
var Resolver = (function () {
function Resolver(internal) {
_classCallCheck(this, Resolver);
this.internal = internal;
}
Resolver.prototype.resolveToBase64 = function resolveToBase64(resource) {
if (resource instanceof Buffer) {
resource = resource.toString("base64");
resource = "data:image/jpg;base64," + resource;
}
return resource;
};
Resolver.prototype.resolveInviteID = function resolveInviteID(resource) {
if (resource instanceof Invite) {
return resource.id;
} else if (typeof resource == "string" || resource instanceof String) {
if (resource.indexOf("http") === 0) {
var split = resource.split("/");
return split.pop();
} else {
return resource;
}
}
return null;
};
Resolver.prototype.resolveServer = function resolveServer(resource) {
if (resource instanceof Server) {
return resource;
} else if (resource instanceof ServerChannel) {
return resource.server;
} else if (resource instanceof String || typeof resource === "string") {
return this.internal.servers.get("id", resource);
} else if (resource instanceof Message) {
if (resource.channel instanceof TextChannel) {
return resource.server;
}
}
return null;
};
Resolver.prototype.resolveFile = function resolveFile(resource) {
if (typeof resource === "string" || resource instanceof String) {
return fs.createReadStream(resource);
} else {
return resource;
}
};
Resolver.prototype.resolveMentions = function resolveMentions(resource) {
// resource is a string
var _mentions = [];
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;
}
var mention = _ref;
_mentions.push(mention.substring(2, mention.length - 1));
}
return _mentions;
};
Resolver.prototype.resolveString = function resolveString(resource) {
// accepts Array, Channel, Server, User, Message, String and anything
// toString()-able
var final = resource;
if (resource instanceof Array) {
final = resource.join("\n");
}
return final.toString();
};
Resolver.prototype.resolveUser = function resolveUser(resource) {
/*
accepts a Message, Channel, Server, String ID, User, PMChannel
*/
var found = null;
if (resource instanceof User) {
found = resource;
} else if (resource instanceof Message) {
found = resource.author;
} else if (resource instanceof TextChannel) {
var lmsg = resource.lastMessage;
if (lmsg) {
found = lmsg.author;
}
} else if (resource instanceof Server) {
found = resource.owner;
} else if (resource instanceof PMChannel) {
found = resource.recipient;
} else if (resource instanceof String || typeof resource === "string") {
found = this.client.internal.users.get("id", resource);
}
return found;
};
Resolver.prototype.resolveMessage = function resolveMessage(resource) {
// accepts a Message, PMChannel & TextChannel
var found = null;
if (resource instanceof TextChannel || resource instanceof PMChannel) {
found = resource.lastMessage;
} else if (resource instanceof Message) {
found = resource;
}
return found;
};
Resolver.prototype.resolveVoiceChannel = function resolveVoiceChannel(resource) {
// resolveChannel will also work but this is more apt
if (resource instanceof VoiceChannel) {
return resource;
}
return null;
};
Resolver.prototype.resolveChannel = function resolveChannel(resource) {
/*
accepts a Message, Channel, Server, String ID, User
*/
var self = this;
return new Promise(function (resolve, reject) {
var found = null;
if (resource instanceof Message) {
found = resource.channel;
} else if (resource instanceof Channel) {
found = resource;
} else if (resource instanceof Server) {
found = resource.channels.get("id", resource.id);
} else if (resource instanceof String || typeof resource === "string") {
found = self.internal.channels.get("id", resource);
} else if (resource instanceof User) {
// see if a PM exists
var chatFound = false;
for (var _iterator2 = self.internal.private_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;
}
var pmchat = _ref2;
if (pmchat.recipient.equals(resource)) {
chatFound = pmchat;
break;
}
}
if (chatFound) {
// a PM already exists!
found = chatFound;
} else {
// PM does not exist :\
self.internal.startPM(resource).then(function (pmchannel) {
return resolve(pmchannel);
})["catch"](function (e) {
return reject(e);
});
return;
}
}
if (found) resolve(found);else reject(new Error("Didn't found anything"));
});
};
return Resolver;
})();
module.exports = Resolver;
"use strict"; /* global Buffer */function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var fs=require("fs");var User=require("../../Structures/User.js"),Channel=require("../../Structures/Channel.js"),TextChannel=require("../../Structures/TextChannel.js"),VoiceChannel=require("../../Structures/VoiceChannel.js"),ServerChannel=require("../../Structures/ServerChannel.js"),PMChannel=require("../../Structures/PMChannel.js"),Server=require("../../Structures/Server.js"),Message=require("../../Structures/Message.js"),Invite=require("../../Structures/Invite.js");var Resolver=(function(){function Resolver(internal){_classCallCheck(this,Resolver);this.internal = internal;}Resolver.prototype.resolveToBase64 = function resolveToBase64(resource){if(resource instanceof Buffer){resource = resource.toString("base64");resource = "data:image/jpg;base64," + resource;}return resource;};Resolver.prototype.resolveInviteID = function resolveInviteID(resource){if(resource instanceof Invite){return resource.id;}else if(typeof resource == "string" || resource instanceof String){if(resource.indexOf("http") === 0){var split=resource.split("/");return split.pop();}else {return resource;}}return null;};Resolver.prototype.resolveServer = function resolveServer(resource){if(resource instanceof Server){return resource;}else if(resource instanceof ServerChannel){return resource.server;}else if(resource instanceof String || typeof resource === "string"){return this.internal.servers.get("id",resource);}else if(resource instanceof Message){if(resource.channel instanceof TextChannel){return resource.server;}}return null;};Resolver.prototype.resolveFile = function resolveFile(resource){if(typeof resource === "string" || resource instanceof String){return fs.createReadStream(resource);}else {return resource;}};Resolver.prototype.resolveMentions = function resolveMentions(resource){ // resource is a string
var _mentions=[];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;}var mention=_ref;_mentions.push(mention.substring(2,mention.length - 1));}return _mentions;};Resolver.prototype.resolveString = function resolveString(resource){ // accepts Array, Channel, Server, User, Message, String and anything
// toString()-able
var final=resource;if(resource instanceof Array){final = resource.join("\n");}return final.toString();};Resolver.prototype.resolveUser = function resolveUser(resource){ /*
accepts a Message, Channel, Server, String ID, User, PMChannel
*/var found=null;if(resource instanceof User){found = resource;}else if(resource instanceof Message){found = resource.author;}else if(resource instanceof TextChannel){var lmsg=resource.lastMessage;if(lmsg){found = lmsg.author;}}else if(resource instanceof Server){found = resource.owner;}else if(resource instanceof PMChannel){found = resource.recipient;}else if(resource instanceof String || typeof resource === "string"){found = this.client.internal.users.get("id",resource);}return found;};Resolver.prototype.resolveMessage = function resolveMessage(resource){ // accepts a Message, PMChannel & TextChannel
var found=null;if(resource instanceof TextChannel || resource instanceof PMChannel){found = resource.lastMessage;}else if(resource instanceof Message){found = resource;}return found;};Resolver.prototype.resolveVoiceChannel = function resolveVoiceChannel(resource){ // resolveChannel will also work but this is more apt
if(resource instanceof VoiceChannel){return resource;}return null;};Resolver.prototype.resolveChannel = function resolveChannel(resource){ /*
accepts a Message, Channel, Server, String ID, User
*/var self=this;return new Promise(function(resolve,reject){var found=null;if(resource instanceof Message){found = resource.channel;}else if(resource instanceof Channel){found = resource;}else if(resource instanceof Server){found = resource.channels.get("id",resource.id);}else if(resource instanceof String || typeof resource === "string"){found = self.internal.channels.get("id",resource);}else if(resource instanceof User){ // see if a PM exists
var chatFound=false;for(var _iterator2=self.internal.private_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;}var pmchat=_ref2;if(pmchat.recipient.equals(resource)){chatFound = pmchat;break;}}if(chatFound){ // a PM already exists!
found = chatFound;}else { // PM does not exist :\
self.internal.startPM(resource).then(function(pmchannel){return resolve(pmchannel);})["catch"](function(e){return reject(e);});return;}}if(found)resolve(found);else reject(new Error("Didn't found anything"));});};return Resolver;})();module.exports = Resolver;

View File

@@ -1,130 +1,7 @@
"use strict";
var API = "https://discordapp.com/api";
var Endpoints = {
// general endpoints
LOGIN: API + "/auth/login",
LOGOUT: API + "/auth/logout",
ME: API + "/users/@me",
GATEWAY: API + "/gateway",
USER_CHANNELS: function USER_CHANNELS(userID) {
return API + "/users/" + userID + "/channels";
},
AVATAR: function AVATAR(userID, avatar) {
return API + "/users/" + userID + "/avatars/" + avatar + ".jpg";
},
INVITE: function INVITE(id) {
return API + "/invite/" + id;
},
// servers
SERVERS: API + "/guilds",
SERVER: function SERVER(serverID) {
return Endpoints.SERVERS + "/" + serverID;
},
SERVER_ICON: function SERVER_ICON(serverID, hash) {
return Endpoints.SERVER(serverID) + "/icons/" + hash + ".jpg";
},
SERVER_PRUNE: function SERVER_PRUNE(serverID) {
return Endpoints.SERVER(serverID) + "/prune";
},
SERVER_EMBED: function SERVER_EMBED(serverID) {
return Endpoints.SERVER(serverID) + "/embed";
},
SERVER_INVITES: function SERVER_INVITES(serverID) {
return Endpoints.SERVER(serverID) + "/invites";
},
SERVER_ROLES: function SERVER_ROLES(serverID) {
return Endpoints.SERVER(serverID) + "/roles";
},
SERVER_BANS: function SERVER_BANS(serverID) {
return Endpoints.SERVER(serverID) + "/bans";
},
SERVER_INTEGRATIONS: function SERVER_INTEGRATIONS(serverID) {
return Endpoints.SERVER(serverID) + "/integrations";
},
SERVER_MEMBERS: function SERVER_MEMBERS(serverID) {
return Endpoints.SERVER(serverID) + "/members";
},
SERVER_CHANNELS: function SERVER_CHANNELS(serverID) {
return Endpoints.SERVER(serverID) + "/channels";
},
// channels
CHANNELS: API + "/channels",
CHANNEL: function CHANNEL(channelID) {
return Endpoints.CHANNELS + "/" + channelID;
},
CHANNEL_MESSAGES: function CHANNEL_MESSAGES(channelID) {
return Endpoints.CHANNEL(channelID) + "/messages";
},
CHANNEL_INVITES: function CHANNEL_INVITES(channelID) {
return Endpoints.CHANNEL(channelID) + "/invites";
},
CHANNEL_TYPING: function CHANNEL_TYPING(channelID) {
return Endpoints.CHANNEL(channelID) + "/typing";
},
CHANNEL_PERMISSIONS: function CHANNEL_PERMISSIONS(channelID) {
return Endpoints.CHANNEL(channelID) + "/permissions";
},
CHANNEL_MESSAGE: function CHANNEL_MESSAGE(channelID, messageID) {
return Endpoints.CHANNEL_MESSAGES(channelID) + "/" + messageID;
}
};
var Permissions = {
// 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
readMessages: 1 << 10,
sendMessages: 1 << 11,
sendTTSMessages: 1 << 12,
manageMessages: 1 << 13,
embedLinks: 1 << 14,
attachFiles: 1 << 15,
readMessageHistory: 1 << 16,
mentionEveryone: 1 << 17,
// voice
voiceConnect: 1 << 20,
voiceSpeak: 1 << 21,
voiceMuteMembers: 1 << 22,
voiceDeafenMembers: 1 << 23,
voiceMoveMembers: 1 << 24,
voiceUseVAD: 1 << 25
};
var PacketType = {
READY: "READY",
MESSAGE_CREATE: "MESSAGE_CREATE",
MESSAGE_UPDATE: "MESSAGE_UPDATE",
MESSAGE_DELETE: "MESSAGE_DELETE",
SERVER_CREATE: "GUILD_CREATE",
SERVER_DELETE: "GUILD_DELETE",
SERVER_UPDATE: "GUILD_UPDATE",
CHANNEL_CREATE: "CHANNEL_CREATE",
CHANNEL_DELETE: "CHANNEL_DELETE",
CHANNEL_UPDATE: "CHANNEL_UPDATE",
SERVER_ROLE_CREATE: "GUILD_ROLE_CREATE",
SERVER_ROLE_DELETE: "GUILD_ROLE_DELETE",
SERVER_ROLE_UPDATE: "GUILD_ROLE_UPDATE",
SERVER_MEMBER_ADD: "GUILD_MEMBER_ADD",
SERVER_MEMBER_REMOVE: "GUILD_MEMBER_REMOVE",
SERVER_MEMBER_UPDATE: "GUILD_MEMBER_UPDATE",
PRESENCE_UPDATE: "PRESENCE_UPDATE",
TYPING: "TYPING_START",
SERVER_BAN_ADD: "GUILD_BAN_ADD",
SERVER_BAN_REMOVE: "GUILD_BAN_REMOVE"
};
exports.API_ENDPOINT = API;
exports.Endpoints = Endpoints;
exports.PacketType = PacketType;
exports.Permissions = Permissions;
"use strict";var API="https://discordapp.com/api";var Endpoints={ // general endpoints
LOGIN:API + "/auth/login",LOGOUT:API + "/auth/logout",ME:API + "/users/@me",GATEWAY:API + "/gateway",USER_CHANNELS:function USER_CHANNELS(userID){return API + "/users/" + userID + "/channels";},AVATAR:function AVATAR(userID,avatar){return API + "/users/" + userID + "/avatars/" + avatar + ".jpg";},INVITE:function INVITE(id){return API + "/invite/" + id;}, // servers
SERVERS:API + "/guilds",SERVER:function SERVER(serverID){return Endpoints.SERVERS + "/" + serverID;},SERVER_ICON:function SERVER_ICON(serverID,hash){return Endpoints.SERVER(serverID) + "/icons/" + hash + ".jpg";},SERVER_PRUNE:function SERVER_PRUNE(serverID){return Endpoints.SERVER(serverID) + "/prune";},SERVER_EMBED:function SERVER_EMBED(serverID){return Endpoints.SERVER(serverID) + "/embed";},SERVER_INVITES:function SERVER_INVITES(serverID){return Endpoints.SERVER(serverID) + "/invites";},SERVER_ROLES:function SERVER_ROLES(serverID){return Endpoints.SERVER(serverID) + "/roles";},SERVER_BANS:function SERVER_BANS(serverID){return Endpoints.SERVER(serverID) + "/bans";},SERVER_INTEGRATIONS:function SERVER_INTEGRATIONS(serverID){return Endpoints.SERVER(serverID) + "/integrations";},SERVER_MEMBERS:function SERVER_MEMBERS(serverID){return Endpoints.SERVER(serverID) + "/members";},SERVER_CHANNELS:function SERVER_CHANNELS(serverID){return Endpoints.SERVER(serverID) + "/channels";}, // channels
CHANNELS:API + "/channels",CHANNEL:function CHANNEL(channelID){return Endpoints.CHANNELS + "/" + channelID;},CHANNEL_MESSAGES:function CHANNEL_MESSAGES(channelID){return Endpoints.CHANNEL(channelID) + "/messages";},CHANNEL_INVITES:function CHANNEL_INVITES(channelID){return Endpoints.CHANNEL(channelID) + "/invites";},CHANNEL_TYPING:function CHANNEL_TYPING(channelID){return Endpoints.CHANNEL(channelID) + "/typing";},CHANNEL_PERMISSIONS:function CHANNEL_PERMISSIONS(channelID){return Endpoints.CHANNEL(channelID) + "/permissions";},CHANNEL_MESSAGE:function CHANNEL_MESSAGE(channelID,messageID){return Endpoints.CHANNEL_MESSAGES(channelID) + "/" + messageID;}};var Permissions={ // 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
readMessages:1 << 10,sendMessages:1 << 11,sendTTSMessages:1 << 12,manageMessages:1 << 13,embedLinks:1 << 14,attachFiles:1 << 15,readMessageHistory:1 << 16,mentionEveryone:1 << 17, // voice
voiceConnect:1 << 20,voiceSpeak:1 << 21,voiceMuteMembers:1 << 22,voiceDeafenMembers:1 << 23,voiceMoveMembers:1 << 24,voiceUseVAD:1 << 25};var PacketType={READY:"READY",MESSAGE_CREATE:"MESSAGE_CREATE",MESSAGE_UPDATE:"MESSAGE_UPDATE",MESSAGE_DELETE:"MESSAGE_DELETE",SERVER_CREATE:"GUILD_CREATE",SERVER_DELETE:"GUILD_DELETE",SERVER_UPDATE:"GUILD_UPDATE",CHANNEL_CREATE:"CHANNEL_CREATE",CHANNEL_DELETE:"CHANNEL_DELETE",CHANNEL_UPDATE:"CHANNEL_UPDATE",SERVER_ROLE_CREATE:"GUILD_ROLE_CREATE",SERVER_ROLE_DELETE:"GUILD_ROLE_DELETE",SERVER_ROLE_UPDATE:"GUILD_ROLE_UPDATE",SERVER_MEMBER_ADD:"GUILD_MEMBER_ADD",SERVER_MEMBER_REMOVE:"GUILD_MEMBER_REMOVE",SERVER_MEMBER_UPDATE:"GUILD_MEMBER_UPDATE",PRESENCE_UPDATE:"PRESENCE_UPDATE",TYPING:"TYPING_START",SERVER_BAN_ADD:"GUILD_BAN_ADD",SERVER_BAN_REMOVE:"GUILD_BAN_REMOVE"};exports.API_ENDPOINT = API;exports.Endpoints = Endpoints;exports.PacketType = PacketType;exports.Permissions = Permissions;

View File

@@ -1,30 +1 @@
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Equality = require("../Util/Equality.js");
var Cache = require("../Util/Cache.js");
var PermissionOverwrite = require("./PermissionOverwrite.js");
var reg = require("../Util/ArgumentRegulariser.js").reg;
var Channel = (function (_Equality) {
_inherits(Channel, _Equality);
function Channel(data, client) {
_classCallCheck(this, Channel);
_Equality.call(this);
this.id = data.id;
this.client = client;
}
Channel.prototype["delete"] = function _delete() {
return this.client.deleteChannel.apply(this.client, reg(this, arguments));
};
return Channel;
})(Equality);
module.exports = Channel;
"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var Equality=require("../Util/Equality.js");var Cache=require("../Util/Cache.js");var PermissionOverwrite=require("./PermissionOverwrite.js");var reg=require("../Util/ArgumentRegulariser.js").reg;var Channel=(function(_Equality){_inherits(Channel,_Equality);function Channel(data,client){_classCallCheck(this,Channel);_Equality.call(this);this.id = data.id;this.client = client;}Channel.prototype["delete"] = function _delete(){return this.client.deleteChannel.apply(this.client,reg(this,arguments));};return Channel;})(Equality);module.exports = Channel;

View File

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

View File

@@ -1,32 +1 @@
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Server = require("./Server.js");
var ServerChannel = require("./ServerChannel.js");
var Invite = (function () {
function Invite(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 = function toString() {
return "https://discord.gg/" + this.code;
};
return Invite;
})();
module.exports = Invite;
"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var Server=require("./Server.js");var ServerChannel=require("./ServerChannel.js");var Invite=(function(){function Invite(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 = function toString(){return "https://discord.gg/" + this.code;};return Invite;})();module.exports = Invite;

View File

@@ -1,72 +1,4 @@
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Cache = require("../Util/Cache.js");
var User = require("./User.js");
var reg = require("../Util/ArgumentRegulariser.js").reg;
var Message = (function () {
function Message(data, channel, client) {
var _this = this;
_classCallCheck(this, Message);
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.author instanceof User) this.author = data.author;else this.author = client.internal.users.add(new User(data.author, client));
this.content = data.content;
this.mentions = new Cache();
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
// not previously cached.
if (mention instanceof User) _this.mentions.push(mention);else _this.mentions.add(client.internal.users.add(new User(mention, client)));
});
}
Message.prototype.isMentioned = function isMentioned(user) {
user = this.client.internal.resolver.resolveUser(user);
if (user) {
return this.mentions.has("id", user.id);
} else {
return false;
}
};
Message.prototype.toString = function toString() {
return this.content;
};
Message.prototype["delete"] = function _delete() {
return this.client.deleteMessage.apply(this.client, reg(this, arguments));
};
Message.prototype.update = function update() {
return this.client.updateMessage.apply(this.client, reg(this, arguments));
};
Message.prototype.reply = function reply() {
return this.client.reply.apply(this.client, reg(this, arguments));
};
Message.prototype.replyTTS = function replyTTS() {
return this.client.replyTTS.apply(this.client, reg(this, arguments));
};
return Message;
})();
module.exports = Message;
"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var Cache=require("../Util/Cache.js");var User=require("./User.js");var reg=require("../Util/ArgumentRegulariser.js").reg;var Equality=require("../Util/Equality");var Message=(function(_Equality){_inherits(Message,_Equality);function Message(data,channel,client){var _this=this;_classCallCheck(this,Message);_Equality.call(this);this.channel = channel;this.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.author instanceof User)this.author = data.author;else this.author = client.internal.users.add(new User(data.author,client));this.content = data.content;this.mentions = new Cache();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
// not previously cached.
if(mention instanceof User)_this.mentions.push(mention);else _this.mentions.add(client.internal.users.add(new User(mention,client)));});}Message.prototype.isMentioned = function isMentioned(user){user = this.client.internal.resolver.resolveUser(user);if(user){return this.mentions.has("id",user.id);}else {return false;}};Message.prototype.toString = function toString(){return this.content;};Message.prototype["delete"] = function _delete(){return this.client.deleteMessage.apply(this.client,reg(this,arguments));};Message.prototype.update = function update(){return this.client.updateMessage.apply(this.client,reg(this,arguments));};Message.prototype.reply = function reply(){return this.client.reply.apply(this.client,reg(this,arguments));};Message.prototype.replyTTS = function replyTTS(){return this.client.replyTTS.apply(this.client,reg(this,arguments));};return Message;})(Equality);module.exports = Message;

View File

@@ -1,55 +1 @@
"use strict";
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Channel = require("./Channel.js");
var User = require("./User.js");
var Equality = require("../Util/Equality.js");
var Cache = require("../Util/Cache.js");
var reg = require("../Util/ArgumentRegulariser.js").reg;
var PMChannel = (function (_Equality) {
_inherits(PMChannel, _Equality);
function PMChannel(data, client) {
_classCallCheck(this, PMChannel);
_Equality.call(this);
this.client = client;
this.type = data.type || "text";
this.id = data.id;
this.lastMessageId = data.last_message_id;
this.messages = new Cache("id", 1000);
this.recipient = this.client.internal.users.add(new User(data.recipient, this.client));
}
/* warning! may return null */
PMChannel.prototype.toString = function toString() {
return this.recipient.toString();
};
PMChannel.prototype.sendMessage = function sendMessage() {
return this.client.sendMessage.apply(this.client, reg(this, arguments));
};
PMChannel.prototype.sendTTSMessage = function sendTTSMessage() {
return this.client.sendTTSMessage.apply(this.client, reg(this, arguments));
};
_createClass(PMChannel, [{
key: "lastMessage",
get: function get() {
return this.messages.get("id", this.lastMessageID);
}
}]);
return PMChannel;
})(Equality);
module.exports = PMChannel;
"use strict";var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if("value" in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var Channel=require("./Channel.js");var User=require("./User.js");var Equality=require("../Util/Equality.js");var Cache=require("../Util/Cache.js");var reg=require("../Util/ArgumentRegulariser.js").reg;var PMChannel=(function(_Channel){_inherits(PMChannel,_Channel);function PMChannel(data,client){_classCallCheck(this,PMChannel);_Channel.call(this,data,client);this.type = data.type || "text";this.lastMessageId = data.last_message_id;this.messages = new Cache("id",1000);this.recipient = this.client.internal.users.add(new User(data.recipient,this.client));} /* warning! may return null */PMChannel.prototype.toString = function toString(){return this.recipient.toString();};PMChannel.prototype.sendMessage = function sendMessage(){return this.client.sendMessage.apply(this.client,reg(this,arguments));};PMChannel.prototype.sendTTSMessage = function sendTTSMessage(){return this.client.sendTTSMessage.apply(this.client,reg(this,arguments));};_createClass(PMChannel,[{key:"lastMessage",get:function get(){return this.messages.get("id",this.lastMessageID);}}]);return PMChannel;})(Channel);module.exports = PMChannel;

View File

@@ -1,86 +1,6 @@
"use strict";
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Permissions = require("../Constants.js").Permissions;
var PermissionOverwrite = (function () {
function PermissionOverwrite(data) {
_classCallCheck(this, PermissionOverwrite);
this.id = data.id;
this.type = data.type; // member or role
this.deny = data.deny;
this.allow = data.allow;
}
// returns an array of allowed permissions
PermissionOverwrite.prototype.setAllowed = function setAllowed(allowedArray) {
var _this = this;
allowedArray.forEach(function (permission) {
if (permission instanceof String || typeof permission === "string") {
permission = Permissions[permission];
}
if (permission) {
_this.allow |= 1 << permission;
}
});
};
PermissionOverwrite.prototype.setDenied = function setDenied(deniedArray) {
var _this2 = this;
deniedArray.forEach(function (permission) {
if (permission instanceof String || typeof permission === "string") {
permission = Permissions[permission];
}
if (permission) {
_this2.deny |= 1 << permission;
}
});
};
_createClass(PermissionOverwrite, [{
key: "allowed",
get: function get() {
var allowed = [];
for (var permName in Permissions) {
if (permName === "manageRoles" || permName === "manageChannels") {
// these permissions do not exist in overwrites.
continue;
}
if (!!(this.allow & Permissions[permName])) {
allowed.push(permName);
}
}
return allowed;
}
// returns an array of denied permissions
}, {
key: "denied",
get: function get() {
var denied = [];
for (var permName in Permissions) {
if (permName === "manageRoles" || permName === "manageChannels") {
// these permissions do not exist in overwrites.
continue;
}
if (!!(this.deny & Permissions[permName])) {
denied.push(permName);
}
}
return denied;
}
}]);
return PermissionOverwrite;
})();
module.exports = PermissionOverwrite;
"use strict";var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if("value" in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var Permissions=require("../Constants.js").Permissions;var PermissionOverwrite=(function(){function PermissionOverwrite(data){_classCallCheck(this,PermissionOverwrite);this.id = data.id;this.type = data.type; // member or role
this.deny = data.deny;this.allow = data.allow;} // returns an array of allowed permissions
PermissionOverwrite.prototype.setAllowed = function setAllowed(allowedArray){var _this=this;allowedArray.forEach(function(permission){if(permission instanceof String || typeof permission === "string"){permission = Permissions[permission];}if(permission){_this.allow |= 1 << permission;}});};PermissionOverwrite.prototype.setDenied = function setDenied(deniedArray){var _this2=this;deniedArray.forEach(function(permission){if(permission instanceof String || typeof permission === "string"){permission = Permissions[permission];}if(permission){_this2.deny |= 1 << permission;}});};_createClass(PermissionOverwrite,[{key:"allowed",get:function get(){var allowed=[];for(var permName in Permissions) {if(permName === "manageRoles" || permName === "manageChannels"){ // these permissions do not exist in overwrites.
continue;}if(!!(this.allow & Permissions[permName])){allowed.push(permName);}}return allowed;} // returns an array of denied permissions
},{key:"denied",get:function get(){var denied=[];for(var permName in Permissions) {if(permName === "manageRoles" || permName === "manageChannels"){ // these permissions do not exist in overwrites.
continue;}if(!!(this.deny & Permissions[permName])){denied.push(permName);}}return denied;}}]);return PermissionOverwrite;})();module.exports = PermissionOverwrite;

View File

@@ -1,9 +1,4 @@
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Permissions = require("../Constants.js").Permissions;
/*
"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var Permissions=require("../Constants.js").Permissions; /*
example data
@@ -14,126 +9,15 @@ example data
id: '110007368451915776',
hoist: false,
color: 0 }
*/
var DefaultRole = [Permissions.createInstantInvite, Permissions.readMessages, Permissions.readMessageHistory, Permissions.sendMessages, Permissions.sendTTSMessages, Permissions.embedLinks, Permissions.attachFiles, Permissions.readMessageHistory, Permissions.mentionEveryone, Permissions.voiceConnect, Permissions.voiceSpeak, Permissions.voiceUseVAD].reduce(function (previous, current) {
return previous | current;
}, 0);
var Role = (function () {
function Role(data, server, client) {
_classCallCheck(this, Role);
this.position = data.position || -1;
this.permissions = data.permissions || (data.name === "@everyone" ? DefaultRole : 0);
this.name = data.name || "@everyone";
this.managed = data.managed || false;
this.id = data.id;
this.hoist = data.hoist || false;
this.color = data.color || 0;
this.server = server;
this.client = client;
}
Role.prototype.serialise = function serialise(explicit) {
var _this = this;
var hp = function hp(perm) {
return _this.hasPermission(perm, explicit);
};
return {
// general
createInstantInvite: hp(Permissions.createInstantInvite),
kickMembers: hp(Permissions.kickMembers),
banMembers: hp(Permissions.banMembers),
manageRoles: hp(Permissions.manageRoles),
manageChannels: hp(Permissions.manageChannels),
manageServer: hp(Permissions.manageServer),
// text
readMessages: hp(Permissions.readMessages),
sendMessages: hp(Permissions.sendMessages),
sendTTSMessages: hp(Permissions.sendTTSMessages),
manageMessages: hp(Permissions.manageMessages),
embedLinks: hp(Permissions.embedLinks),
attachFiles: hp(Permissions.attachFiles),
readMessageHistory: hp(Permissions.readMessageHistory),
mentionEveryone: hp(Permissions.mentionEveryone),
// voice
voiceConnect: hp(Permissions.voiceConnect),
voiceSpeak: hp(Permissions.voiceSpeak),
voiceMuteMembers: hp(Permissions.voiceMuteMembers),
voiceDeafenMembers: hp(Permissions.voiceDeafenMembers),
voiceMoveMembers: hp(Permissions.voiceMoveMembers),
voiceUseVAD: hp(Permissions.voiceUseVAD)
};
};
Role.prototype.serialize = function serialize() {
// ;n;
return this.serialise();
};
Role.prototype.hasPermission = function hasPermission(perm) {
var explicit = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
if (perm instanceof String || typeof perm === "string") {
perm = Permissions[perm];
}
if (!perm) {
return false;
}
if (!explicit) {
// implicit permissions allowed
if (!!(this.permissions & Permissions.manageRoles)) {
// manageRoles allowed, they have all permissions
return true;
}
}
// e.g.
// !!(36953089 & Permissions.manageRoles) = not allowed to manage roles
// !!(36953089 & (1 << 21)) = voice speak allowed
return !!(this.permissions & perm);
};
Role.prototype.setPermission = function setPermission(permission, value) {
if (permission instanceof String || typeof permission === "string") {
permission = Permissions[permission];
}
if (permission) {
// valid permission
if (value) {
this.permissions |= permission;
} else {
this.permissions &= ~permission;
}
}
};
Role.prototype.setPermissions = function setPermissions(obj) {
var _this2 = this;
obj.forEach(function (value, permission) {
if (permission instanceof String || typeof permission === "string") {
permission = Permissions[permission];
}
if (permission) {
// valid permission
_this2.setPermission(permission, value);
}
});
};
Role.prototype.colorAsHex = function colorAsHex() {
var val = this.color.toString();
while (val.length < 6) {
val = "0" + val;
}
return "#" + val;
};
return Role;
})();
module.exports = Role;
*/var DefaultRole=[Permissions.createInstantInvite,Permissions.readMessages,Permissions.readMessageHistory,Permissions.sendMessages,Permissions.sendTTSMessages,Permissions.embedLinks,Permissions.attachFiles,Permissions.readMessageHistory,Permissions.mentionEveryone,Permissions.voiceConnect,Permissions.voiceSpeak,Permissions.voiceUseVAD].reduce(function(previous,current){return previous | current;},0);var Role=(function(){function Role(data,server,client){_classCallCheck(this,Role);this.position = data.position || -1;this.permissions = data.permissions || (data.name === "@everyone"?DefaultRole:0);this.name = data.name || "@everyone";this.managed = data.managed || false;this.id = data.id;this.hoist = data.hoist || false;this.color = data.color || 0;this.server = server;this.client = client;}Role.prototype.serialise = function serialise(explicit){var _this=this;var hp=function hp(perm){return _this.hasPermission(perm,explicit);};return { // general
createInstantInvite:hp(Permissions.createInstantInvite),kickMembers:hp(Permissions.kickMembers),banMembers:hp(Permissions.banMembers),manageRoles:hp(Permissions.manageRoles),manageChannels:hp(Permissions.manageChannels),manageServer:hp(Permissions.manageServer), // text
readMessages:hp(Permissions.readMessages),sendMessages:hp(Permissions.sendMessages),sendTTSMessages:hp(Permissions.sendTTSMessages),manageMessages:hp(Permissions.manageMessages),embedLinks:hp(Permissions.embedLinks),attachFiles:hp(Permissions.attachFiles),readMessageHistory:hp(Permissions.readMessageHistory),mentionEveryone:hp(Permissions.mentionEveryone), // voice
voiceConnect:hp(Permissions.voiceConnect),voiceSpeak:hp(Permissions.voiceSpeak),voiceMuteMembers:hp(Permissions.voiceMuteMembers),voiceDeafenMembers:hp(Permissions.voiceDeafenMembers),voiceMoveMembers:hp(Permissions.voiceMoveMembers),voiceUseVAD:hp(Permissions.voiceUseVAD)};};Role.prototype.serialize = function serialize(){ // ;n;
return this.serialise();};Role.prototype.hasPermission = function hasPermission(perm){var explicit=arguments.length <= 1 || arguments[1] === undefined?false:arguments[1];if(perm instanceof String || typeof perm === "string"){perm = Permissions[perm];}if(!perm){return false;}if(!explicit){ // implicit permissions allowed
if(!!(this.permissions & Permissions.manageRoles)){ // manageRoles allowed, they have all permissions
return true;}} // e.g.
// !!(36953089 & Permissions.manageRoles) = not allowed to manage roles
// !!(36953089 & (1 << 21)) = voice speak allowed
return !!(this.permissions & perm);};Role.prototype.setPermission = function setPermission(permission,value){if(permission instanceof String || typeof permission === "string"){permission = Permissions[permission];}if(permission){ // valid permission
if(value){this.permissions |= permission;}else {this.permissions &= ~permission;}}};Role.prototype.setPermissions = function setPermissions(obj){var _this2=this;obj.forEach(function(value,permission){if(permission instanceof String || typeof permission === "string"){permission = Permissions[permission];}if(permission){ // valid permission
_this2.setPermission(permission,value);}});};Role.prototype.colorAsHex = function colorAsHex(){var val=this.color.toString();while(val.length < 6) {val = "0" + val;}return "#" + val;};return Role;})();module.exports = Role;

View File

@@ -1,169 +1 @@
"use strict";
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Equality = require("../Util/Equality.js");
var Endpoints = require("../Constants.js").Endpoints;
var Cache = require("../Util/Cache.js");
var User = require("./User.js");
var TextChannel = require("./TextChannel.js");
var VoiceChannel = require("./VoiceChannel.js");
var Role = require("./Role.js");
var strictKeys = ["region", "ownerID", "name", "id", "icon", "afkTimeout", "afkChannelID"];
var Server = (function (_Equality) {
_inherits(Server, _Equality);
function Server(data, client) {
var _this = this;
_classCallCheck(this, Server);
_Equality.call(this);
var self = this;
this.client = client;
this.region = data.region;
this.ownerID = data.owner_id;
this.name = data.name;
this.id = data.id;
this.members = new Cache();
this.channels = new Cache();
this.roles = new Cache();
this.icon = data.icon;
this.afkTimeout = data.afkTimeout;
this.afkChannelID = data.afk_channel_id;
this.memberMap = {};
var self = this;
data.roles.forEach(function (dataRole) {
_this.roles.add(new Role(dataRole, _this, client));
});
data.members.forEach(function (dataUser) {
_this.memberMap[dataUser.user.id] = {
roles: dataUser.roles.map(function (pid) {
return self.roles.get("id", pid);
}),
mute: dataUser.mute,
deaf: dataUser.deaf,
joinedAt: Date.parse(dataUser.joined_at)
};
var user = client.internal.users.add(new User(dataUser.user, client));
_this.members.add(user);
});
data.channels.forEach(function (dataChannel) {
if (dataChannel.type === "text") {
var channel = client.internal.channels.add(new TextChannel(dataChannel, client, _this));
_this.channels.add(channel);
} else {
var channel = client.internal.channels.add(new VoiceChannel(dataChannel, client, _this));
_this.channels.add(channel);
}
});
if (data.presences) {
for (var _iterator = data.presences, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var presence = _ref;
var user = client.internal.users.get("id", presence.user.id);
if (user) {
user.status = presence.status;
user.gameID = presence.game_id;
}
}
}
}
Server.prototype.rolesOfUser = function rolesOfUser(user) {
user = this.client.internal.resolver.resolveUser(user);
if (user) {
return this.memberMap[user.id] ? this.memberMap[user.id].roles : [];
} else {
return null;
}
};
Server.prototype.rolesOf = function rolesOf(user) {
return this.rolesOfUser(user);
};
Server.prototype.toString = function toString() {
return this.name;
};
Server.prototype.equalsStrict = function equalsStrict(obj) {
if (obj instanceof Server) {
for (var _iterator2 = strictKeys, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var key = _ref2;
if (obj[key] !== this[key]) {
return false;
}
}
} else {
return false;
}
return true;
};
_createClass(Server, [{
key: "iconURL",
get: function get() {
if (!this.icon) {
return null;
} else {
return Endpoints.SERVER_ICON(this.id, this.icon);
}
}
}, {
key: "afkChannel",
get: function get() {
return this.channels.get("id", this.afkChannelID);
}
}, {
key: "defaultChannel",
get: function get() {
return this.channels.get("id", this.id);
}
}, {
key: "owner",
get: function get() {
return this.members.get("id", this.ownerID);
}
}]);
return Server;
})(Equality);
module.exports = Server;
"use strict";var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if("value" in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var Equality=require("../Util/Equality.js");var Endpoints=require("../Constants.js").Endpoints;var Cache=require("../Util/Cache.js");var User=require("./User.js");var TextChannel=require("./TextChannel.js");var VoiceChannel=require("./VoiceChannel.js");var Role=require("./Role.js");var strictKeys=["region","ownerID","name","id","icon","afkTimeout","afkChannelID"];var Server=(function(_Equality){_inherits(Server,_Equality);function Server(data,client){var _this=this;_classCallCheck(this,Server);_Equality.call(this);var self=this;this.client = client;this.region = data.region;this.ownerID = data.owner_id;this.name = data.name;this.id = data.id;this.members = new Cache();this.channels = new Cache();this.roles = new Cache();this.icon = data.icon;this.afkTimeout = data.afkTimeout;this.afkChannelID = data.afk_channel_id;this.memberMap = {};var self=this;data.roles.forEach(function(dataRole){_this.roles.add(new Role(dataRole,_this,client));});data.members.forEach(function(dataUser){_this.memberMap[dataUser.user.id] = {roles:dataUser.roles.map(function(pid){return self.roles.get("id",pid);}),mute:dataUser.mute,deaf:dataUser.deaf,joinedAt:Date.parse(dataUser.joined_at)};var user=client.internal.users.add(new User(dataUser.user,client));_this.members.add(user);});data.channels.forEach(function(dataChannel){if(dataChannel.type === "text"){var channel=client.internal.channels.add(new TextChannel(dataChannel,client,_this));_this.channels.add(channel);}else {var channel=client.internal.channels.add(new VoiceChannel(dataChannel,client,_this));_this.channels.add(channel);}});if(data.presences){for(var _iterator=data.presences,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:_iterator[Symbol.iterator]();;) {var _ref;if(_isArray){if(_i >= _iterator.length)break;_ref = _iterator[_i++];}else {_i = _iterator.next();if(_i.done)break;_ref = _i.value;}var presence=_ref;var user=client.internal.users.get("id",presence.user.id);if(user){user.status = presence.status;user.gameID = presence.game_id;}}}}Server.prototype.rolesOfUser = function rolesOfUser(user){user = this.client.internal.resolver.resolveUser(user);if(user){return this.memberMap[user.id]?this.memberMap[user.id].roles:[];}else {return null;}};Server.prototype.rolesOf = function rolesOf(user){return this.rolesOfUser(user);};Server.prototype.toString = function toString(){return this.name;};Server.prototype.equalsStrict = function equalsStrict(obj){if(obj instanceof Server){for(var _iterator2=strictKeys,_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:_iterator2[Symbol.iterator]();;) {var _ref2;if(_isArray2){if(_i2 >= _iterator2.length)break;_ref2 = _iterator2[_i2++];}else {_i2 = _iterator2.next();if(_i2.done)break;_ref2 = _i2.value;}var key=_ref2;if(obj[key] !== this[key]){return false;}}}else {return false;}return true;};_createClass(Server,[{key:"iconURL",get:function get(){if(!this.icon){return null;}else {return Endpoints.SERVER_ICON(this.id,this.icon);}}},{key:"afkChannel",get:function get(){return this.channels.get("id",this.afkChannelID);}},{key:"defaultChannel",get:function get(){return this.channels.get("id",this.id);}},{key:"owner",get:function get(){return this.members.get("id",this.ownerID);}}]);return Server;})(Equality);module.exports = Server;

View File

@@ -1,117 +1 @@
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Channel = require("./Channel.js");
var Cache = require("../Util/Cache.js");
var PermissionOverwrite = require("./PermissionOverwrite.js");
var ChannelPermissions = require("./ChannelPermissions.js");
var reg = require("../Util/ArgumentRegulariser.js").reg;
var ServerChannel = (function (_Channel) {
_inherits(ServerChannel, _Channel);
function ServerChannel(data, client, server) {
var _this = this;
_classCallCheck(this, ServerChannel);
_Channel.call(this, data, client);
this.name = data.name;
this.type = data.type;
this.position = data.position;
this.permissionOverwrites = new Cache();
this.server = server;
data.permission_overwrites.forEach(function (permission) {
_this.permissionOverwrites.add(new PermissionOverwrite(permission));
});
}
ServerChannel.prototype.permissionsOf = function permissionsOf(user) {
user = this.client.internal.resolver.resolveUser(user);
if (user) {
if (this.server.owner.equals(user)) {
return new ChannelPermissions(4294967295);
}
var everyoneRole = this.server.roles.get("name", "@everyone");
var userRoles = [everyoneRole].concat(this.server.rolesOf(user) || []);
var userRolesID = userRoles.map(function (v) {
return v.id;
});
var roleOverwrites = [],
memberOverwrites = [];
this.permissionOverwrites.forEach(function (overwrite) {
if (overwrite.type === "member" && overwrite.id === user.id) {
memberOverwrites.push(overwrite);
} else if (overwrite.type === "role" && overwrite.id in userRolesID) {
roleOverwrites.push(overwrite);
}
});
var permissions = 0;
for (var _iterator = userRoles, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var serverRole = _ref;
permissions |= serverRole.permissions;
}
for (var _iterator2 = roleOverwrites.concat(memberOverwrites), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var overwrite = _ref2;
permissions = permissions & ~overwrite.deny;
permissions = permissions | overwrite.allow;
}
return new ChannelPermissions(permissions);
} else {
return null;
}
};
ServerChannel.prototype.permsOf = function permsOf(user) {
return this.permissionsOf(user);
};
ServerChannel.prototype.mention = function mention() {
return "<#" + this.id + ">";
};
ServerChannel.prototype.toString = function toString() {
return this.mention();
};
ServerChannel.prototype.setName = function setName() {
return this.client.setChannelName.apply(this.client, reg(this, arguments));
};
return ServerChannel;
})(Channel);
module.exports = ServerChannel;
"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var Channel=require("./Channel.js");var Cache=require("../Util/Cache.js");var PermissionOverwrite=require("./PermissionOverwrite.js");var ChannelPermissions=require("./ChannelPermissions.js");var reg=require("../Util/ArgumentRegulariser.js").reg;var ServerChannel=(function(_Channel){_inherits(ServerChannel,_Channel);function ServerChannel(data,client,server){var _this=this;_classCallCheck(this,ServerChannel);_Channel.call(this,data,client);this.name = data.name;this.type = data.type;this.position = data.position;this.permissionOverwrites = new Cache();this.server = server;data.permission_overwrites.forEach(function(permission){_this.permissionOverwrites.add(new PermissionOverwrite(permission));});}ServerChannel.prototype.permissionsOf = function permissionsOf(user){user = this.client.internal.resolver.resolveUser(user);if(user){if(this.server.owner.equals(user)){return new ChannelPermissions(4294967295);}var everyoneRole=this.server.roles.get("name","@everyone");var userRoles=[everyoneRole].concat(this.server.rolesOf(user) || []);var userRolesID=userRoles.map(function(v){return v.id;});var roleOverwrites=[],memberOverwrites=[];this.permissionOverwrites.forEach(function(overwrite){if(overwrite.type === "member" && overwrite.id === user.id){memberOverwrites.push(overwrite);}else if(overwrite.type === "role" && overwrite.id in userRolesID){roleOverwrites.push(overwrite);}});var permissions=0;for(var _iterator=userRoles,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:_iterator[Symbol.iterator]();;) {var _ref;if(_isArray){if(_i >= _iterator.length)break;_ref = _iterator[_i++];}else {_i = _iterator.next();if(_i.done)break;_ref = _i.value;}var serverRole=_ref;permissions |= serverRole.permissions;}for(var _iterator2=roleOverwrites.concat(memberOverwrites),_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:_iterator2[Symbol.iterator]();;) {var _ref2;if(_isArray2){if(_i2 >= _iterator2.length)break;_ref2 = _iterator2[_i2++];}else {_i2 = _iterator2.next();if(_i2.done)break;_ref2 = _i2.value;}var overwrite=_ref2;permissions = permissions & ~overwrite.deny;permissions = permissions | overwrite.allow;}return new ChannelPermissions(permissions);}else {return null;}};ServerChannel.prototype.permsOf = function permsOf(user){return this.permissionsOf(user);};ServerChannel.prototype.mention = function mention(){return "<#" + this.id + ">";};ServerChannel.prototype.toString = function toString(){return this.mention();};ServerChannel.prototype.setName = function setName(){return this.client.setChannelName.apply(this.client,reg(this,arguments));};return ServerChannel;})(Channel);module.exports = ServerChannel;

View File

@@ -1,60 +1 @@
"use strict";
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var ServerChannel = require("./ServerChannel.js");
var Cache = require("../Util/Cache.js");
var reg = require("../Util/ArgumentRegulariser.js").reg;
var TextChannel = (function (_ServerChannel) {
_inherits(TextChannel, _ServerChannel);
function TextChannel(data, client, server) {
_classCallCheck(this, TextChannel);
_ServerChannel.call(this, data, client, server);
this.name = data.name;
this.topic = data.topic;
this.position = data.position;
this.lastMessageID = data.last_message_id;
this.messages = new Cache("id", client.options.maximumMessages);
}
/* warning! may return null */
TextChannel.prototype.setTopic = function setTopic() {
return this.client.setTopic.apply(this.client, reg(this, arguments));
};
TextChannel.prototype.setNameAndTopic = function setNameAndTopic() {
return this.client.setChannelNameAndTopic.apply(this.client, reg(this, arguments));
};
TextChannel.prototype.update = function update() {
return this.client.updateChannel.apply(this.client, reg(this, arguments));
};
TextChannel.prototype.sendMessage = function sendMessage() {
return this.client.sendMessage.apply(this.client, reg(this, arguments));
};
TextChannel.prototype.sendTTSMessage = function sendTTSMessage() {
return this.client.sendTTSMessage.apply(this.client, reg(this, arguments));
};
_createClass(TextChannel, [{
key: "lastMessage",
get: function get() {
return this.messages.get("id", this.lastMessageID);
}
}]);
return TextChannel;
})(ServerChannel);
module.exports = TextChannel;
"use strict";var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if("value" in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var ServerChannel=require("./ServerChannel.js");var Cache=require("../Util/Cache.js");var reg=require("../Util/ArgumentRegulariser.js").reg;var TextChannel=(function(_ServerChannel){_inherits(TextChannel,_ServerChannel);function TextChannel(data,client,server){_classCallCheck(this,TextChannel);_ServerChannel.call(this,data,client,server);this.topic = data.topic;this.lastMessageID = data.last_message_id;this.messages = new Cache("id",client.options.maximumMessages);} /* warning! may return null */TextChannel.prototype.setTopic = function setTopic(){return this.client.setTopic.apply(this.client,reg(this,arguments));};TextChannel.prototype.setNameAndTopic = function setNameAndTopic(){return this.client.setChannelNameAndTopic.apply(this.client,reg(this,arguments));};TextChannel.prototype.update = function update(){return this.client.updateChannel.apply(this.client,reg(this,arguments));};TextChannel.prototype.sendMessage = function sendMessage(){return this.client.sendMessage.apply(this.client,reg(this,arguments));};TextChannel.prototype.sendTTSMessage = function sendTTSMessage(){return this.client.sendTTSMessage.apply(this.client,reg(this,arguments));};_createClass(TextChannel,[{key:"lastMessage",get:function get(){return this.messages.get("id",this.lastMessageID);}}]);return TextChannel;})(ServerChannel);module.exports = TextChannel;

View File

@@ -1,58 +1 @@
"use strict";
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Equality = require("../Util/Equality.js");
var Endpoints = require("../Constants.js").Endpoints;
var User = (function (_Equality) {
_inherits(User, _Equality);
function User(data, client) {
_classCallCheck(this, User);
_Equality.call(this);
this.client = client;
this.username = data.username;
this.discriminator = data.discriminator;
this.id = data.id;
this.avatar = data.avatar;
this.status = data.status || "offline";
this.gameID = data.game_id || null;
this.typing = {
since: null,
channel: null
};
}
User.prototype.mention = function mention() {
return "<@" + this.id + ">";
};
User.prototype.toString = function toString() {
return this.mention();
};
User.prototype.equalsStrict = function equalsStrict(obj) {
if (obj instanceof User) return this.id === obj.id && this.username === obj.username && this.discriminator === obj.discriminator && this.avatar === obj.avatar && this.status === obj.status && this.gameID === obj.gameID;else return false;
};
_createClass(User, [{
key: "avatarURL",
get: function get() {
if (!this.avatar) {
return null;
} else {
return Endpoints.AVATAR(this.id, this.avatar);
}
}
}]);
return User;
})(Equality);
module.exports = User;
"use strict";var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if("value" in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var Equality=require("../Util/Equality.js");var Endpoints=require("../Constants.js").Endpoints;var User=(function(_Equality){_inherits(User,_Equality);function User(data,client){_classCallCheck(this,User);_Equality.call(this);this.client = client;this.username = data.username;this.discriminator = data.discriminator;this.id = data.id;this.avatar = data.avatar;this.status = data.status || "offline";this.gameID = data.game_id || null;this.typing = {since:null,channel:null};}User.prototype.mention = function mention(){return "<@" + this.id + ">";};User.prototype.toString = function toString(){return this.mention();};User.prototype.equalsStrict = function equalsStrict(obj){if(obj instanceof User)return this.id === obj.id && this.username === obj.username && this.discriminator === obj.discriminator && this.avatar === obj.avatar && this.status === obj.status && this.gameID === obj.gameID;else return false;};_createClass(User,[{key:"avatarURL",get:function get(){if(!this.avatar){return null;}else {return Endpoints.AVATAR(this.id,this.avatar);}}}]);return User;})(Equality);module.exports = User;

View File

@@ -1,21 +1 @@
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var ServerChannel = require("./ServerChannel.js");
var VoiceChannel = (function (_ServerChannel) {
_inherits(VoiceChannel, _ServerChannel);
function VoiceChannel(data, client, server) {
_classCallCheck(this, VoiceChannel);
_ServerChannel.call(this, data, client, server);
}
return VoiceChannel;
})(ServerChannel);
module.exports = VoiceChannel;
"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var ServerChannel=require("./ServerChannel.js");var VoiceChannel=(function(_ServerChannel){_inherits(VoiceChannel,_ServerChannel);function VoiceChannel(data,client,server){_classCallCheck(this,VoiceChannel);_ServerChannel.call(this,data,client,server);}return VoiceChannel;})(ServerChannel);module.exports = VoiceChannel;

View File

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

View File

@@ -1,102 +1 @@
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Cache = (function (_Array) {
_inherits(Cache, _Array);
function Cache(discrim, limit) {
_classCallCheck(this, Cache);
_Array.call(this);
this.discrim = discrim || "id";
}
Cache.prototype.get = function get(key, value) {
var found = null;
this.forEach(function (val, index, array) {
if (val.hasOwnProperty(key) && val[key] == value) {
found = val;
return;
}
});
return found;
};
Cache.prototype.has = function has(key, value) {
return !!this.get(key, value);
};
Cache.prototype.getAll = function getAll(key, value) {
var found = [];
this.forEach(function (val, index, array) {
if (val.hasOwnProperty(key) && val[key] == value) {
found.push(val);
return;
}
});
return found;
};
Cache.prototype.add = function add(data) {
var exit = false;
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;
}
var item = _ref;
if (item[this.discrim] === data[this.discrim]) {
exit = item;
break;
}
}
if (exit) {
return exit;
} else {
if (this.limit && this.length >= this.limit) {
this.splice(0, 1);
}
this.push(data);
return data;
}
};
Cache.prototype.update = function update(old, data) {
var item = this.get(this.discrim, old[this.discrim]);
if (item) {
var index = this.indexOf(item);
this[index] = data;
return this[index];
} else {
return false;
}
};
Cache.prototype.remove = function remove(data) {
var index = this.indexOf(data);
if (~index) {
this.splice(index, 1);
} else {
var item = this.get(this.discrim, data[this.discrim]);
if (item) {
this.splice(this.indexOf(item), 1);
}
}
return false;
};
return Cache;
})(Array);
module.exports = Cache;
"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var Cache=(function(_Array){_inherits(Cache,_Array);function Cache(discrim,limit){_classCallCheck(this,Cache);_Array.call(this);this.discrim = discrim || "id";}Cache.prototype.get = function get(key,value){var found=null;this.forEach(function(val,index,array){if(val.hasOwnProperty(key) && val[key] == value){found = val;return;}});return found;};Cache.prototype.has = function has(key,value){return !!this.get(key,value);};Cache.prototype.getAll = function getAll(key,value){var found=new Cache(this.discrim);this.forEach(function(val,index,array){if(val.hasOwnProperty(key) && val[key] == value){found.push(val);return;}});return found;};Cache.prototype.add = function add(data){var exit=false;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;}var item=_ref;if(item[this.discrim] === data[this.discrim]){exit = item;break;}}if(exit){return exit;}else {if(this.limit && this.length >= this.limit){this.splice(0,1);}this.push(data);return data;}};Cache.prototype.update = function update(old,data){var item=this.get(this.discrim,old[this.discrim]);if(item){var index=this.indexOf(item);this[index] = data;return this[index];}else {return false;}};Cache.prototype.remove = function remove(data){var index=this.indexOf(data);if(~index){this.splice(index,1);}else {var item=this.get(this.discrim,data[this.discrim]);if(item){this.splice(this.indexOf(item),1);}}return false;};return Cache;})(Array);module.exports = Cache;

View File

@@ -8,38 +8,5 @@
instances sometimes.
Instead, use objectThatExtendsEquality.equals()
*/
"use strict";
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Equality = (function () {
function Equality() {
_classCallCheck(this, Equality);
}
Equality.prototype.equals = function equals(object) {
if (object && object[this.eqDiscriminator] == this[this.eqDiscriminator]) {
return true;
}
return false;
};
Equality.prototype.equalsStrict = function equalsStrict(object) {
// override per class type
return;
};
_createClass(Equality, [{
key: "eqDiscriminator",
get: function get() {
return "id";
}
}]);
return Equality;
})();
module.exports = Equality;
*/"use strict";var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if("value" in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var Equality=(function(){function Equality(){_classCallCheck(this,Equality);}Equality.prototype.equals = function equals(object){if(object && object[this.eqDiscriminator] == this[this.eqDiscriminator]){return true;}return false;};Equality.prototype.equalsStrict = function equalsStrict(object){ // override per class type
return;};_createClass(Equality,[{key:"eqDiscriminator",get:function get(){return "id";}}]);return Equality;})();module.exports = Equality;

View File

@@ -1,129 +1,4 @@
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var cpoc = require("child_process");
var opus;
try {
opus = require("node-opus");
} catch (e) {
// no opus!
}
var VoicePacket = require("./VoicePacket.js");
var AudioEncoder = (function () {
function AudioEncoder() {
_classCallCheck(this, AudioEncoder);
if (opus) {
this.opus = new opus.OpusEncoder(48000, 1);
}
this.choice = false;
}
AudioEncoder.prototype.opusBuffer = function opusBuffer(buffer) {
return this.opus.encode(buffer, 1920);
};
AudioEncoder.prototype.getCommand = function getCommand(force) {
if (this.choice && force) return choice;
var choices = ["avconv", "ffmpeg"];
for (var _iterator = choices, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var choice = _ref;
var p = cpoc.spawnSync(choice);
if (!p.error) {
this.choice = choice;
return choice;
}
}
return "help";
};
AudioEncoder.prototype.encodeStream = function encodeStream(stream) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err, buffer) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
var enc = cpoc.spawn(self.getCommand(), ["-f", "s16le", "-ar", "48000", "-ac", "1", // this can be 2 but there's no point, discord makes it mono on playback, wasted bandwidth.
"-af", "volume=1", "pipe:1", "-i", "-"]);
stream.pipe(enc.stdin);
enc.stdout.once("readable", function () {
callback(null, {
proc: enc,
stream: enc.stdout,
instream: stream
});
resolve({
proc: enc,
stream: enc.stdout,
instream: stream
});
});
enc.stdout.on("end", function () {
callback("end");
reject("end");
});
enc.stdout.on("close", function () {
callback("close");
reject("close");
});
});
};
AudioEncoder.prototype.encodeFile = function encodeFile(file) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err, buffer) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
var enc = cpoc.spawn(self.getCommand(), ["-f", "s16le", "-ar", "48000", "-ac", "1", // this can be 2 but there's no point, discord makes it mono on playback, wasted bandwidth.
"-af", "volume=1", "pipe:1", "-i", file]);
enc.stdout.once("readable", function () {
callback(null, {
proc: enc,
stream: enc.stdout
});
resolve({
proc: enc,
stream: enc.stdout
});
});
enc.stdout.on("end", function () {
callback("end");
reject("end");
});
enc.stdout.on("close", function () {
callback("close");
reject("close");
});
});
};
return AudioEncoder;
})();
module.exports = AudioEncoder;
"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var cpoc=require("child_process");var opus;try{opus = require("node-opus");}catch(e) { // no opus!
}var VoicePacket=require("./VoicePacket.js");var AudioEncoder=(function(){function AudioEncoder(){_classCallCheck(this,AudioEncoder);if(opus){this.opus = new opus.OpusEncoder(48000,1);}this.choice = false;}AudioEncoder.prototype.opusBuffer = function opusBuffer(buffer){return this.opus.encode(buffer,1920);};AudioEncoder.prototype.getCommand = function getCommand(force){if(this.choice && force)return choice;var choices=["avconv","ffmpeg"];for(var _iterator=choices,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:_iterator[Symbol.iterator]();;) {var _ref;if(_isArray){if(_i >= _iterator.length)break;_ref = _iterator[_i++];}else {_i = _iterator.next();if(_i.done)break;_ref = _i.value;}var choice=_ref;var p=cpoc.spawnSync(choice);if(!p.error){this.choice = choice;return choice;}}return "help";};AudioEncoder.prototype.encodeStream = function encodeStream(stream){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err,buffer){}:arguments[1];var self=this;return new Promise(function(resolve,reject){var enc=cpoc.spawn(self.getCommand(),["-f","s16le","-ar","48000","-ac","1", // this can be 2 but there's no point, discord makes it mono on playback, wasted bandwidth.
"-af","volume=1","pipe:1","-i","-"]);stream.pipe(enc.stdin);enc.stdout.once("readable",function(){callback(null,{proc:enc,stream:enc.stdout,instream:stream});resolve({proc:enc,stream:enc.stdout,instream:stream});});enc.stdout.on("end",function(){callback("end");reject("end");});enc.stdout.on("close",function(){callback("close");reject("close");});});};AudioEncoder.prototype.encodeFile = function encodeFile(file){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err,buffer){}:arguments[1];var self=this;return new Promise(function(resolve,reject){var enc=cpoc.spawn(self.getCommand(),["-f","s16le","-ar","48000","-ac","1", // this can be 2 but there's no point, discord makes it mono on playback, wasted bandwidth.
"-af","volume=1","pipe:1","-i",file]);enc.stdout.once("readable",function(){callback(null,{proc:enc,stream:enc.stdout});resolve({proc:enc,stream:enc.stdout});});enc.stdout.on("end",function(){callback("end");reject("end");});enc.stdout.on("close",function(){callback("close");reject("close");});});};return AudioEncoder;})();module.exports = AudioEncoder;

View File

@@ -1,22 +1,2 @@
"use strict";
// represents an intent of streaming music
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var EventEmitter = require("events");
var StreamIntent = (function (_EventEmitter) {
_inherits(StreamIntent, _EventEmitter);
function StreamIntent() {
_classCallCheck(this, StreamIntent);
_EventEmitter.call(this);
}
return StreamIntent;
})(EventEmitter);
module.exports = StreamIntent;
"use strict"; // represents an intent of streaming music
function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var EventEmitter=require("events");var StreamIntent=(function(_EventEmitter){_inherits(StreamIntent,_EventEmitter);function StreamIntent(){_classCallCheck(this,StreamIntent);_EventEmitter.call(this);}return StreamIntent;})(EventEmitter);module.exports = StreamIntent;

View File

@@ -1,332 +1,11 @@
"use strict";
/*
"use strict"; /*
Major credit to izy521 who is the creator of
https://github.com/izy521/discord.io,
without his help voice chat in discord.js would not have
been possible!
*/
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var WebSocket = require("ws");
var dns = require("dns");
var udp = require("dgram");
var fs = require("fs");
var AudioEncoder = require("./AudioEncoder.js");
var VoicePacket = require("./VoicePacket.js");
var StreamIntent = require("./StreamIntent.js");
var EventEmitter = require("events");
var VoiceConnection = (function (_EventEmitter) {
_inherits(VoiceConnection, _EventEmitter);
function VoiceConnection(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.replace(":80", "");
this.vWS = null; // vWS means voice websocket
this.ready = false;
this.vWSData = {};
this.encoder = new AudioEncoder();
this.udp = null;
this.playingIntent = null;
this.playing = false;
this.streamTime = 0;
this.streamProc = null;
this.KAI = null;
this.init();
}
VoiceConnection.prototype.destroy = function destroy() {
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 = function stopPlaying() {
this.playing = false;
this.playingIntent = null;
if (this.instream) {
this.instream.end();
this.instream.destroy();
}
};
VoiceConnection.prototype.playStream = function playStream(stream) {
var self = this;
var startTime = Date.now();
var sequence = 0;
var time = 0;
var count = 0;
var length = 20;
if (self.playingIntent) {
self.stopPlaying();
}
self.playing = true;
var retStream = new StreamIntent();
var onWarning = false;
self.playingIntent = retStream;
function send() {
if (!self.playingIntent || !self.playing) {
self.setSpeaking(false);
retStream.emit("end");
self;
return;
}
try {
var buffer = stream.read(1920);
if (!buffer) {
setTimeout(send, length * 10); // give chance for some data in 200ms to appear
return;
}
if (buffer.length !== 1920) {
if (onWarning) {
retStream.emit("end");
stream.destroy();
self.setSpeaking(false);
return;
} else {
onWarning = true;
setTimeout(send, length * 10); // give chance for some data in 200ms to appear
return;
}
}
count++;
sequence + 10 < 65535 ? sequence += 1 : sequence = 0;
time + 9600 < 4294967295 ? time += 960 : time = 0;
self.sendBuffer(buffer, sequence, time, function (e) {});
var nextTime = 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();
return retStream;
};
VoiceConnection.prototype.setSpeaking = function setSpeaking(value) {
this.playing = value;
if (this.vWS.readyState === WebSocket.OPEN) this.vWS.send(JSON.stringify({
op: 5,
d: {
speaking: value,
delay: 0
}
}));
};
VoiceConnection.prototype.sendPacket = function sendPacket(packet) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1];
var self = this;
self.playing = true;
try {
if (self.vWS.readyState === WebSocket.OPEN) self.udp.send(packet, 0, packet.length, self.vWSData.port, self.endpoint, callback);
} catch (e) {
self.playing = false;
callback(e);
return false;
}
};
VoiceConnection.prototype.sendBuffer = function sendBuffer(rawbuffer, sequence, timestamp, callback) {
var self = 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;
}
var buffer = self.encoder.opusBuffer(rawbuffer);
var packet = new VoicePacket(buffer, sequence, timestamp, self.vWSData.ssrc);
return self.sendPacket(packet, callback);
} catch (e) {
self.playing = false;
self.emit("error", e);
return false;
}
};
VoiceConnection.prototype.test = function test() {
this.playFile("C:/users/amish/desktop/audio.mp3").then(function (stream) {
stream.on("time", function (time) {
console.log("Time", time);
});
});
};
VoiceConnection.prototype.playFile = function playFile(stream) {
var _this = this;
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err, str) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
_this.encoder.encodeFile(stream)["catch"](error).then(function (data) {
self.streamProc = data.proc;
var intent = self.playStream(data.stream);
resolve(intent);
callback(null, intent);
});
function error() {
var e = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0];
reject(e);
callback(e);
}
});
};
VoiceConnection.prototype.playRawStream = function playRawStream(stream) {
var _this2 = this;
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err, str) {} : arguments[1];
var self = this;
return new Promise(function (resolve, reject) {
_this2.encoder.encodeStream(stream)["catch"](error).then(function (data) {
self.streamProc = data.proc;
self.instream = data.instream;
var intent = self.playStream(data.stream);
resolve(intent);
callback(null, intent);
});
function error() {
var e = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0];
reject(e);
callback(e);
}
});
};
VoiceConnection.prototype.init = function init() {
var _this3 = this;
var self = this;
dns.lookup(this.endpoint, function (err, address, family) {
self.endpoint = address;
var vWS = self.vWS = new WebSocket("wss://" + _this3.endpoint, null, { rejectUnauthorized: false });
var udpClient = self.udp = udp.createSocket("udp4");
var firstPacket = true;
var discordIP = "",
discordPort = "";
udpClient.bind({ exclusive: true });
udpClient.on('message', function (msg, rinfo) {
var buffArr = JSON.parse(JSON.stringify(msg)).data;
if (firstPacket === true) {
for (var i = 4; i < buffArr.indexOf(0, i); i++) {
discordIP += String.fromCharCode(buffArr[i]);
}
discordPort = msg.readUIntLE(msg.length - 2, 2).toString(10);
var wsDiscPayload = {
"op": 1,
"d": {
"protocol": "udp",
"data": {
"address": discordIP,
"port": Number(discordPort),
"mode": self.vWSData.modes[0] //Plain
}
}
};
vWS.send(JSON.stringify(wsDiscPayload));
firstPacket = false;
}
});
vWS.on("open", function () {
vWS.send(JSON.stringify({
op: 0,
d: {
server_id: self.server.id,
user_id: self.client.internal.user.id,
session_id: self.session,
token: self.token
}
}));
});
var KAI;
vWS.on("message", function (msg) {
var data = JSON.parse(msg);
switch (data.op) {
case 2:
self.vWSData = data.d;
KAI = setInterval(function () {
if (vWS && vWS.readyState === WebSocket.OPEN) vWS.send(JSON.stringify({
op: 3,
d: null
}));
}, data.d.heartbeat_interval);
self.KAI = KAI;
var udpPacket = new Buffer(70);
udpPacket.writeUIntBE(data.d.ssrc, 0, 4);
udpClient.send(udpPacket, 0, udpPacket.length, data.d.port, self.endpoint, function (err) {
if (err) self.emit("error", err);
});
break;
case 4:
self.ready = true;
self.mode = data.d.mode;
self.emit("ready", self);
break;
}
});
});
};
return VoiceConnection;
})(EventEmitter);
module.exports = VoiceConnection;
*/function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var WebSocket=require("ws");var dns=require("dns");var udp=require("dgram");var fs=require("fs");var AudioEncoder=require("./AudioEncoder.js");var VoicePacket=require("./VoicePacket.js");var StreamIntent=require("./StreamIntent.js");var EventEmitter=require("events");var VoiceConnection=(function(_EventEmitter){_inherits(VoiceConnection,_EventEmitter);function VoiceConnection(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.replace(":80","");this.vWS = null; // vWS means voice websocket
this.ready = false;this.vWSData = {};this.encoder = new AudioEncoder();this.udp = null;this.playingIntent = null;this.playing = false;this.streamTime = 0;this.streamProc = null;this.KAI = null;this.init();}VoiceConnection.prototype.destroy = function destroy(){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 = function stopPlaying(){this.playing = false;this.playingIntent = null;if(this.instream){this.instream.end();this.instream.destroy();}};VoiceConnection.prototype.playStream = function playStream(stream){var self=this;var startTime=Date.now();var sequence=0;var time=0;var count=0;var length=20;if(self.playingIntent){self.stopPlaying();}self.playing = true;var retStream=new StreamIntent();var onWarning=false;self.playingIntent = retStream;function send(){if(!self.playingIntent || !self.playing){self.setSpeaking(false);retStream.emit("end");self;return;}try{var buffer=stream.read(1920);if(!buffer){setTimeout(send,length * 10); // give chance for some data in 200ms to appear
return;}if(buffer.length !== 1920){if(onWarning){retStream.emit("end");stream.destroy();self.setSpeaking(false);return;}else {onWarning = true;setTimeout(send,length * 10); // give chance for some data in 200ms to appear
return;}}count++;sequence + 10 < 65535?sequence += 1:sequence = 0;time + 9600 < 4294967295?time += 960:time = 0;self.sendBuffer(buffer,sequence,time,function(e){});var nextTime=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();return retStream;};VoiceConnection.prototype.setSpeaking = function setSpeaking(value){this.playing = value;if(this.vWS.readyState === WebSocket.OPEN)this.vWS.send(JSON.stringify({op:5,d:{speaking:value,delay:0}}));};VoiceConnection.prototype.sendPacket = function sendPacket(packet){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;self.playing = true;try{if(self.vWS.readyState === WebSocket.OPEN)self.udp.send(packet,0,packet.length,self.vWSData.port,self.endpoint,callback);}catch(e) {self.playing = false;callback(e);return false;}};VoiceConnection.prototype.sendBuffer = function sendBuffer(rawbuffer,sequence,timestamp,callback){var self=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;}var buffer=self.encoder.opusBuffer(rawbuffer);var packet=new VoicePacket(buffer,sequence,timestamp,self.vWSData.ssrc);return self.sendPacket(packet,callback);}catch(e) {self.playing = false;self.emit("error",e);return false;}};VoiceConnection.prototype.test = function test(){this.playFile("C:/users/amish/desktop/audio.mp3").then(function(stream){stream.on("time",function(time){console.log("Time",time);});});};VoiceConnection.prototype.playFile = function playFile(stream){var _this=this;var callback=arguments.length <= 1 || arguments[1] === undefined?function(err,str){}:arguments[1];var self=this;return new Promise(function(resolve,reject){_this.encoder.encodeFile(stream)["catch"](error).then(function(data){self.streamProc = data.proc;var intent=self.playStream(data.stream);resolve(intent);callback(null,intent);});function error(){var e=arguments.length <= 0 || arguments[0] === undefined?true:arguments[0];reject(e);callback(e);}});};VoiceConnection.prototype.playRawStream = function playRawStream(stream){var _this2=this;var callback=arguments.length <= 1 || arguments[1] === undefined?function(err,str){}:arguments[1];var self=this;return new Promise(function(resolve,reject){_this2.encoder.encodeStream(stream)["catch"](error).then(function(data){self.streamProc = data.proc;self.instream = data.instream;var intent=self.playStream(data.stream);resolve(intent);callback(null,intent);});function error(){var e=arguments.length <= 0 || arguments[0] === undefined?true:arguments[0];reject(e);callback(e);}});};VoiceConnection.prototype.init = function init(){var _this3=this;var self=this;dns.lookup(this.endpoint,function(err,address,family){self.endpoint = address;var vWS=self.vWS = new WebSocket("wss://" + _this3.endpoint,null,{rejectUnauthorized:false});var udpClient=self.udp = udp.createSocket("udp4");var firstPacket=true;var discordIP="",discordPort="";udpClient.bind({exclusive:true});udpClient.on('message',function(msg,rinfo){var buffArr=JSON.parse(JSON.stringify(msg)).data;if(firstPacket === true){for(var i=4;i < buffArr.indexOf(0,i);i++) {discordIP += String.fromCharCode(buffArr[i]);}discordPort = msg.readUIntLE(msg.length - 2,2).toString(10);var wsDiscPayload={"op":1,"d":{"protocol":"udp","data":{"address":discordIP,"port":Number(discordPort),"mode":self.vWSData.modes[0] //Plain
}}};vWS.send(JSON.stringify(wsDiscPayload));firstPacket = false;}});vWS.on("open",function(){vWS.send(JSON.stringify({op:0,d:{server_id:self.server.id,user_id:self.client.internal.user.id,session_id:self.session,token:self.token}}));});var KAI;vWS.on("message",function(msg){var data=JSON.parse(msg);switch(data.op){case 2:self.vWSData = data.d;KAI = setInterval(function(){if(vWS && vWS.readyState === WebSocket.OPEN)vWS.send(JSON.stringify({op:3,d:null}));},data.d.heartbeat_interval);self.KAI = KAI;var udpPacket=new Buffer(70);udpPacket.writeUIntBE(data.d.ssrc,0,4);udpClient.send(udpPacket,0,udpPacket.length,data.d.port,self.endpoint,function(err){if(err)self.emit("error",err);});break;case 4:self.ready = true;self.mode = data.d.mode;self.emit("ready",self);break;}});});};return VoiceConnection;})(EventEmitter);module.exports = VoiceConnection;

View File

@@ -1,26 +1 @@
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var VoicePacket = function VoicePacket(data, sequence, time, ssrc) {
_classCallCheck(this, VoicePacket);
var audioBuffer = data,
returnBuffer = new Buffer(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 (var i = 0; i < audioBuffer.length; i++) {
returnBuffer[i + 12] = audioBuffer[i];
}
return returnBuffer;
};
module.exports = VoicePacket;
"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var VoicePacket=function VoicePacket(data,sequence,time,ssrc){_classCallCheck(this,VoicePacket);var audioBuffer=data,returnBuffer=new Buffer(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(var i=0;i < audioBuffer.length;i++) {returnBuffer[i + 12] = audioBuffer[i];}return returnBuffer;};module.exports = VoicePacket;

View File

@@ -1,17 +1 @@
"use strict";
module.exports = {
Client: require("./Client/Client"),
Channel: require("./Structures/Channel"),
ChannelPermissions: require("./Structures/ChannelPermissions"),
Invite: require("./Structures/Invite"),
Message: require("./Structures/Message"),
PermissionOverwrite: require("./Structures/PermissionOverwrite"),
PMChannel: require("./Structures/PMChannel"),
Role: require("./Structures/Role"),
Server: require("./Structures/Server"),
ServerChannel: require("./Structures/ServerChannel"),
TextChannel: require("./Structures/TextChannel"),
User: require("./Structures/User"),
VoiceChannel: require("./Structures/VoiceChannel")
};
"use strict";module.exports = {Client:require("./Client/Client"),Channel:require("./Structures/Channel"),ChannelPermissions:require("./Structures/ChannelPermissions"),Invite:require("./Structures/Invite"),Message:require("./Structures/Message"),PermissionOverwrite:require("./Structures/PermissionOverwrite"),PMChannel:require("./Structures/PMChannel"),Role:require("./Structures/Role"),Server:require("./Structures/Server"),ServerChannel:require("./Structures/ServerChannel"),TextChannel:require("./Structures/TextChannel"),User:require("./Structures/User"),VoiceChannel:require("./Structures/VoiceChannel"),Constants:require("./Constants.js")};

View File

@@ -1,6 +1,6 @@
{
"name": "discord.js",
"version": "4.1.1",
"version": "5.0.0",
"description": "A way to interface with the Discord API",
"main": "./entrypoint.js",
"scripts": {

View File

@@ -626,11 +626,11 @@ class Client extends EventEmitter {
}
//def setChannelName
setChannelName(channel, topic, callback = function (err) { }) {
setChannelName(channel, name, callback = function (err) { }) {
var self = this;
return new Promise((resolve, reject) => {
self.internal.setChannelName(channel, topic)
self.internal.setChannelName(channel, name)
.then(() => {
callback();
resolve();
@@ -780,6 +780,22 @@ class Client extends EventEmitter {
});
}
// def leaveVoiceChannel
leaveVoiceChannel(callback = function (err) { }) {
var self = this;
return new Promise((resolve, reject) => {
self.internal.leaveVoiceChannel()
.then(() => {
callback();
resolve();
})
.catch(err => {
callback(err);
reject(err);
});
});
}
}
module.exports = Client;

View File

@@ -87,7 +87,7 @@ class InternalClient {
endpoint = data.d.endpoint;
var chan = self.voiceConnection = new VoiceConnection(channel, self.client, session, token, server, endpoint);
chan.on("ready", resolve);
chan.on("ready", () => resolve(chan));
chan.on("error", reject);
self.client.emit("debug", "removed temporary voice websocket listeners");
@@ -1081,7 +1081,7 @@ class InternalClient {
.send({
avatar: self.resolver.resolveToBase64(data.avatar) || self.user.avatar,
email : data.email || self.email,
new_password : data.new_password || null,
new_password : data.newPassword || null,
password : data.password || self.password,
username : data.username || self.user.username
})
@@ -1458,7 +1458,7 @@ class InternalClient {
if (channel instanceof PMChannel) {
//PM CHANNEL
client.emit("channelUpdated", self.private_channels.update(
client.emit("channelUpdated", channel, self.private_channels.update(
channel,
new PMChannel(data, client)
));

View File

@@ -3,9 +3,11 @@
var Cache = require("../Util/Cache.js");
var User = require("./User.js");
var reg = require("../Util/ArgumentRegulariser.js").reg;
var Equality = require("../Util/Equality");
class Message{
constructor(data, channel, client){
class Message extends Equality{
constructor(data, channel, client) {
super();
this.channel = channel;
this.client = client;
this.nonce = data.nonce;

View File

@@ -6,13 +6,11 @@ var Equality = require("../Util/Equality.js");
var Cache = require("../Util/Cache.js");
var reg = require("../Util/ArgumentRegulariser.js").reg;
class PMChannel extends Equality{
class PMChannel extends Channel{
constructor(data, client){
super();
this.client = client;
super(data, client);
this.type = data.type || "text";
this.id = data.id;
this.lastMessageId = data.last_message_id;
this.messages = new Cache("id", 1000);
this.recipient = this.client.internal.users.add(new User(data.recipient, this.client));

View File

@@ -8,9 +8,7 @@ class TextChannel extends ServerChannel{
constructor(data, client, server){
super(data, client, server);
this.name = data.name;
this.topic = data.topic;
this.position = data.position;
this.lastMessageID = data.last_message_id;
this.messages = new Cache("id", client.options.maximumMessages);
}

View File

@@ -22,7 +22,7 @@ class Cache extends Array {
}
getAll(key, value) {
var found = [];
var found = new Cache(this.discrim);
this.forEach((val, index, array) => {
if (val.hasOwnProperty(key) && val[key] == value) {
found.push(val);

View File

@@ -11,5 +11,6 @@ module.exports = {
ServerChannel : require("./Structures/ServerChannel"),
TextChannel : require("./Structures/TextChannel"),
User : require("./Structures/User"),
VoiceChannel : require("./Structures/VoiceChannel"),
VoiceChannel: require("./Structures/VoiceChannel"),
Constants : require("./Constants.js")
}

View File

@@ -5,120 +5,9 @@
*/
var Discord = require("../");
var mybot = new Discord.Client();
var current = 0;
var server, channel, message, role, sentMessage = false, actions = [], current = -1;
function next() {
current++;
if (current !== 0) {
console.log("Success on test", current, actions[current]);
}
if (current === actions.length)
done();
else
actions[current].apply(this, arguments);
}
function init() {
console.log("preparing...");
}
actions.push(() => {
mybot.createServer("test-server", "london").then(next).catch(error);
});
actions.push((_server) => {
server = _server;
mybot.createChannel(server, "test-channel", "text").then(next).catch(error);
});
actions.push((_channel) => {
channel = _channel;
mybot.sendMessage(channel, [mybot.user.avatarURL, "an", "array", "of", "messages"]).then(next).catch(error);
});
actions.push((message) => {
mybot.deleteMessage(message).then(next).catch(error);
});
actions.push(() => {
mybot.createRole(server, {
name: "Custom Role",
color: 0xff0000,
sendMessages: false
}).then(next).catch(error);
});
actions.push((_role) => {
role = _role;
if (role.name === "Custom Role" && !role.sendMessages) {
next();
} else {
error(new Error("bad role; " + role));
}
});
actions.push(() => {
mybot.deleteRole(role).then(next).catch(error);
});
actions.push(() => {
mybot.sendMessage(channel, "ping").catch(error);
});
actions.push((message) => {
mybot.updateMessage(message, "pong").then(next).catch(error);
});
actions.push((message) => {
mybot.deleteMessage(message).then(next).catch(error);
})
actions.push(() => {
mybot.sendFile(server, "./test/image.png").then(next).catch(error);
})
actions.push(() => {
mybot.leaveServer(server).then(next).catch(error);
});
// phase 2
actions.push(() => {
mybot.joinServer(process.env["ds_invite"]).then(next).catch(error);
});
actions.push((_server) => {
server = _server;
mybot.sendMessage(server.getMember("username", "hydrabolt"), "Travis Build test").then(next).catch(error);
});
actions.push((_message) => {
mybot.deleteMessage(_message).then(next).catch(error);
});
actions.push(() => {
mybot.logout().then(next).catch(error);
});
mybot.on("message", function (message) {
if(!message.isPrivate){
if (message.channel.equals(channel)) {
if (message.content === "ping") {
sentMessage = true;
next(message);
}
}
}
})
mybot.once("ready", function () {
console.log("ready! beginning tests");
next();
});
mybot.login(process.env["ds_email"], process.env["ds_password"]).then(init).catch(error);
done();
function done() {
console.log("Finished! Build successful.");

16541
web-dist/discord.5.0.0.js Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long