cloudstorm 0.1.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,31 +0,0 @@
1
- 'use strict';
2
- let CloudStorm = require('../../index').Client;
3
- let token = require('../config.json').token;
4
- let bot = new CloudStorm(token, {
5
- initialPresence: {status: 'online', game: {name: 'Wolking on Sunshine'}},
6
- firstShardId: 0,
7
- lastShardId: 0,
8
- shardAmount: 1
9
- });
10
- let amqp = require('amqp');
11
- let startup = async () => {
12
- let connection = amqp.createConnection({host: 'localhost'});
13
- connection.on('error', (e) => {
14
- console.error(e);
15
- });
16
- connection.on('ready', async () => {
17
- await bot.connect();
18
- bot.on('event', (event) => {
19
- connection.publish('test-pre-cache', event);
20
- // Event was sent to amqp queue, now you can use it somewhere else
21
- });
22
- });
23
- bot.on('ready', () => {
24
- console.log('Bot is ready');
25
- });
26
- };
27
- startup().catch(e => {
28
- console.error('Error on startup!');
29
- console.error(e);
30
- });
31
-
@@ -1,18 +0,0 @@
1
- 'use strict';
2
- let CloudStorm = require('../../index').Client;
3
- let token = require('../config.json').token;
4
- let bot = new CloudStorm(token);
5
- let startup = async () => {
6
- await bot.connect();
7
- bot.on('event', (event) => {
8
- // Do stuff with the received event ¯\_(ツ)_/¯
9
- });
10
- bot.on('ready', () => {
11
- console.log('Bot received ready event');
12
- });
13
- };
14
- startup().catch(e => {
15
- console.error('Error on startup!');
16
- console.error(e);
17
- });
18
-
package/index.d.ts DELETED
@@ -1,220 +0,0 @@
1
- declare module "Cloudstorm" {
2
- import { EventEmitter } from "events";
3
- import * as WebSocket from "ws";
4
- import { IClientOptions as IWSOptions } from "ws";
5
-
6
- export interface IWSMessage {
7
- op: number;
8
- d?: { [key: string]: any };
9
- s?: number;
10
- }
11
-
12
- export interface IPresenceGame {
13
- name: string;
14
- type?: number;
15
- url?: string;
16
- }
17
-
18
- export interface IPresence {
19
- status?: string;
20
- afk?: boolean;
21
- since?: boolean;
22
- game?: IPresenceGame;
23
- }
24
-
25
- export interface IClientOptions {
26
- largeGuildThreshold?: number;
27
- firstShardId?: number;
28
- lastShardId?: number;
29
- shardAmount?: number;
30
- reconnect?: boolean;
31
- initialPresence?: IPresence;
32
- }
33
-
34
- export interface IVoiceStateUpdate {
35
- guild_id: string;
36
- channel_id: string | null;
37
- self_mute: boolean;
38
- self_deaf: boolean;
39
- }
40
-
41
- export interface IRequestGuildMembers {
42
- guild_id: string;
43
- query: string | null;
44
- limit: number;
45
- }
46
-
47
- export interface IShardReady {
48
- id: number;
49
- ready: boolean;
50
- }
51
-
52
- export interface GATEWAY_OP_CODES {
53
- DISPATCH: number;
54
- HEARTBEAT: number;
55
- IDENTIFY: number;
56
- STATUS_UPDATE: number;
57
- VOICE_STATE_UPDATE: number;
58
- VOICE_SERVER_PING: number;
59
- RESUME: number;
60
- RECONNECT: number;
61
- REQUEST_GUILD_MEMBERS: number;
62
- INVALID_SESSION: number;
63
- HELLO: number
64
- HEARTBEAT_ACK: number;
65
- }
66
-
67
- export const GATEWAY_VERSION: number;
68
-
69
- export class RatelimitBucket {
70
- private fnQueue: Function[];
71
- private limit: number;
72
- private remaining: number;
73
- private limitReset: number;
74
- private resetTimeout: NodeJS.Timer | null;
75
- private constructor(limit?: number, limitReset?: number);
76
- protected queue<T extends Function>(fn: T): Promise<void>;
77
- protected checkQueue(): void;
78
- protected resetRemaining(): void;
79
- protected dropQueue(): void;
80
- }
81
-
82
- export class BetterWs extends EventEmitter {
83
- private ws: WebSocket;
84
- private wsBucket: RatelimitBucket;
85
- private statusBucket: RatelimitBucket;
86
- private zlibInflate: any; // TODO: set type
87
- private constructor(address: string, protocols: string[], options: IWSOptions);
88
- protected get rawWs(): WebSocket;
89
- protected bindWs(ws: WebSocket): void;
90
- protected recreateWs(address: string, options?: IWSOptions): void;
91
- protected onOpen(): void;
92
- protected onMessage(message: string | Buffer | { [key: string]: any }): void;
93
- protected onClose(code: number, reason: string): void;
94
- protected sendMessage(data: { [key: string]: any }): Promise<void>;
95
- protected close(code?: number, reason?: string): Promise<void>;
96
- private on(event: "error", cb: (data: Error | string) => void): this;
97
- private on(event: "ws_open", cb: () => void): this;
98
- private on(event: "ws_message", cb: (data: { [key: string]: any }) => void): this;
99
- private on(event: "ws_close", cb: (code: number, reason: string) => void): this;
100
- private once(event: "error", cb: (data: Error | string) => void): this;
101
- private once(event: "ws_open", cb: () => void): this;
102
- private once(event: "ws_message", cb: (data: { [key: string]: any }) => void): this;
103
- private once(event: "ws_close", cb: (code: number, reason: String) => void): this;
104
- }
105
-
106
- export class DiscordConnector extends EventEmitter { // TODO: add events
107
- public id: number;
108
- public client: Client;
109
- public options: IClientOptions;
110
- public reconnect: boolean;
111
- public betterWs: BetterWs | null;
112
- public heartbeatInterval: number | null;
113
- public seq: number;
114
- public status: string;
115
- public sessionId: number | null;
116
- public forceIdentify: boolean;
117
- private constructor(id: number, client: Client);
118
- protected connect(): void;
119
- protected disconnect(): Promise<void>;
120
- protected messageAction(message: IWSMessage): void;
121
- protected reset(): void;
122
- protected identify(force?: boolean): Promise<void>;
123
- protected resume(): Promise<void>;
124
- protected heartbeat(): void;
125
- protected handleDispatch(message: IWSMessage): void;
126
- protected handleWsClose(code: number, reason: string): void;
127
- protected statusUpdate(data?: IPresence): void;
128
- protected requestGuildMembers(data?: IRequestGuildMembers): Promise<void>;
129
- private _checkPresenceData(data: IPresence): IPresence;
130
- private _checkVoiceStateUpdateData(data: IVoiceStateUpdate): IVoiceStateUpdate;
131
- private _checkRequestGuildMembersData(data: IRequestGuildMembers): IRequestGuildMembers;
132
- private on(event: "queueIdentify", cb: (data: number) => void): this;
133
- private once(event: "queueIdentify", cb: (data: number) => void): this;
134
- private on(event: "event", cb: (data: IWSMessage) => void): this;
135
- private once(event: "event", cb: (data: IWSMessage) => void): this;
136
- private on(event: "ready", cb: (data: boolean) => void): this;
137
- private once(event: "ready", cb: (data: boolean) => void): this;
138
- private on(event: "error", cb: (data: Error | string) => void): this;
139
- private once(event: "error", cb: (data: Error | string) => void): this;
140
- }
141
-
142
- export class Shard extends EventEmitter {
143
- public client: Client;
144
- public id: number;
145
- public forceIdentify: boolean;
146
- public ready: boolean;
147
- public connector: DiscordConnector;
148
- private constructor(id: number, client: Client);
149
- private on(event: "disconnect", cb: () => void): this;
150
- private on(event: "ready", cb: (data: boolean) => void): this;
151
- private on(event: "error", cb: (data: Error) => void): this;
152
- private on(event: "queueIdentify", cb: (data: number) => void): this;
153
- private once(event: "disconnect", cb: () => void): this;
154
- private once(event: "ready", cb: (data: boolean) => void): this;
155
- private once(event: "error", cb: (data: Error) => void): this;
156
- private once(event: "queueIdentify", cb: (data: number) => void): this;
157
- protected connect(): void;
158
- protected disconnect(): Promise<void>;
159
- protected statusUpdate(data: IPresence): Promise<void>;
160
- protected voiceStateUpdate(data: IVoiceStateUpdate): Promise<void>;
161
- protected requestGuildMembers(data: IRequestGuildMembers): Promise<void>;
162
- }
163
-
164
- export class ShardManager {
165
- public client: Client;
166
- public options: IClientOptions;
167
- public connectQueueInterval: NodeJS.Timer;
168
- public shards: { [key: number]: Shard };
169
- public connectQueue: Shard[];
170
- public lastConnectAttempt: Date;
171
- private constructor(client: Client);
172
- private _connectShard(data: { action: string; shard: Shard }): void;
173
- private _checkQueue(): void;
174
- private _addListener(shard: Shard): void;
175
- private _checkReady(): void;
176
- private _checkDisconnect(): void;
177
- protected spawn(): void;
178
- protected disconnect(): void;
179
- protected statusUpdate(data?: IPresence): void;
180
- protected shardStatusUpdate(shardId: number, data?: IPresence): void;
181
- protected voiceStateUpdate(shardId: number, data: IVoiceStateUpdate): Promise<void>;
182
- protected requestGuildMembers(shardId: number, data: IRequestGuildMembers): Promise<void>:
183
- }
184
-
185
- export class Client extends EventEmitter { // TODO: add events
186
- public token: string;
187
- public httpToken: string;
188
- public shardManager: ShardManager;
189
- public options: IClientOptions;
190
- public constructor(token: string, options?: IClientOptions);
191
- public connect(): Promise<void>;
192
- public getGateway(): Promise<string>;
193
- public getGatewayBot(): Promise<IGatewayData>;
194
- public disconnect(): void;
195
- public statusUpdate(data: IPresence): void;
196
- public shardStatusUpdate(shardId: number, data: IPresence): Promise<void>;
197
- public voiceStateUpdate(shardId: number, data: IVoiceStateUpdate): Promise<void>;
198
- public requestGuildMembers(shardId: number, data: IRequestGuildMembers): Promise<void>;
199
- public on(event: "disconnected", cb: () => void): this;
200
- public once(event: "disconnected", cb: () => void): this;
201
- public on(event: "dispatch", cb: (data: { [key: string]: any }) => void): this;
202
- public once(event: "dispatch", cb: (data: { [key: string]: any }) => void): this;
203
- public on(event: "error", cb: (data: Error) => void): this;
204
- public once(event: "error", cb: (data: Error) => void): this;
205
- public on(event: "event", cb: (data: { [key: string]: any }) => void): this; // TODO: make interfaces for all events
206
- public once(event: "event", cb: (data: { [key: string]: any }) => void): this; // TODO: ^
207
- public on(event: "rawRecieve", cb: (data: { [key: string]: any }) => void): this;
208
- public once(event: "rawRecieve", cb: (data: { [key: string]: any }) => void): this;
209
- public on(event: "rawSend", cb: (data: { [key: string]: any }) => void): this;
210
- public once(event: "rawSend", cb: (data: { [key: string]: any }) => void): this;
211
- public on(event: "ready", cb: () => void): this;
212
- public once(event: "ready", cb: () => void): this;
213
- public on(event: "shardReady", cb: (data: IShardReady) => void): this;
214
- public once(event: "shardReady", cb: (data: IShardReady) => void): this;
215
- public on(event: "voiceStateUpdate", cb: (data: IVoiceStateUpdate) => void): this;
216
- public once(event: "voiceStateUdpate", cb: (data: IVoiceStateUpdate) => void): this;
217
- public on(event: "debug", cb: (data: string) => void): this;
218
- public once(event: "debug", cb: (data: string) => void): this;
219
- }
220
- }
package/index.js DELETED
@@ -1,10 +0,0 @@
1
- 'use strict';
2
- let Client = require('./src/Client');
3
-
4
- function createClient(...args) {
5
- return new Client(...args);
6
- }
7
-
8
- createClient.Client = Client;
9
- createClient.Constants = require('./src/Constants');
10
- module.exports = createClient;
package/src/Client.js DELETED
@@ -1,229 +0,0 @@
1
- 'use strict';
2
- let version = require('../package.json').version;
3
- let EventEmitter;
4
- try {
5
- EventEmitter = require('eventemitter3');
6
- } catch (e) {
7
- EventEmitter = require('events').EventEmitter;
8
- }
9
- let Erlpack;
10
- try {
11
- Erlpack = require('erlpack');
12
- // eslint-disable-next-line no-empty
13
- } catch (e) {
14
-
15
- }
16
- const Constants = require('./Constants');
17
- const SnowTransfer = require('snowtransfer');
18
- const ShardManager = require('./ShardManager');
19
-
20
- /**
21
- * Main class used for receiving events and interacting with the discord gateway
22
- * @extends {EventEmitter} EventEmitter
23
- */
24
- class Client extends EventEmitter {
25
- /**
26
- * Create a new Client to connect to the gateway
27
- * @param {String} token - token received from creating a discord bot user, which will be used to connect to the gateway
28
- * @param {Object} [options]
29
- * @param {Number} [options.largeGuildThreshold=250] - Value between 50 and 250 at which the discord gateway stops sending offline guild members
30
- * @param {Number} [options.firstShardId=0] - Id of the first shard that should be started
31
- * @param {Number} [options.lastShardId=0] - Id of the last shard that should be started, not to be confused with shardAmount, lastShardId tells CloudStorm the range of shardId's to spawn,
32
- * so you can use this parameter to run multi-process sharding where one CloudStorm instance running multiple shards runs in one process.
33
- * Set it to shardAmount-1 if you are unsure about what it does.
34
- * @param {Number} [options.shardAmount=1] - Amount of **total** shards connecting to discord
35
- * @param {Boolean} [options.reconnect=true] - If the bot should automatically reconnect to discord if it get's disconnected, **leave it set to true unless you know what you are doing**
36
- * @param {Presence} [options.initialPresence] - If you want to start the bot with an initial presence, you may set it here
37
- * @property {ShardManager} shardManager - shard manager used for managing a pool of shards (connections) to the discord gateway, discord requires you to shard your bot at 2500 guilds,
38
- * but you may do it earlier.
39
- * @property {String} version - version of this package, exposed so you can use it easier.
40
- * @constructor
41
- * @returns {Client} a new CloudStorm instance
42
- */
43
- constructor(token, options = {}) {
44
- super();
45
- if (!token) {
46
- throw new Error('Missing token!');
47
- }
48
- this.options = {
49
- largeGuildThreshold: 250,
50
- firstShardId: 0,
51
- lastShardId: 0,
52
- shardAmount: 1,
53
- reconnect: true
54
- };
55
- this.token = token.startsWith('Bot ') ? token.substring(4) : token;
56
- Object.assign(this.options, options);
57
- this.options.token = token;
58
- this.shardManager = new ShardManager(this);
59
- this.version = version;
60
- this._restClient = new SnowTransfer(token);
61
- }
62
-
63
- /**
64
- * Create one or more connections (depending on the selected amount of shards) to the discord gateway
65
- * @returns {Promise.<void>} This function returns a promise which is solely used for awaiting the getGateway() method's return value
66
- */
67
- async connect() {
68
- let gatewayUrl = await this.getGateway();
69
- this._updateEndpoint(gatewayUrl);
70
- this.shardManager.spawn();
71
- }
72
-
73
- /**
74
- * Get the gateway endpoint to connect to
75
- * @returns {Promise.<String>} String url with the Gateway Endpoint to connect to
76
- */
77
- async getGateway() {
78
- let gatewayData = await this._restClient.bot.getGateway();
79
- return gatewayData.url;
80
- }
81
-
82
- /**
83
- * Get the GatewayData including recommended amount of shards
84
- * @returns {Promise.<GatewayData>} Object with url and shards to use to connect to discord
85
- */
86
- async getGatewayBot() {
87
- return this._restClient.bot.getGatewayBot();
88
- }
89
-
90
- /**
91
- * Disconnect the bot gracefully,
92
- * you will receive a 'disconnected' Event once the bot successfully shutdown
93
- */
94
- disconnect() {
95
- return this.shardManager.disconnect();
96
- }
97
-
98
- /**
99
- * Send a status update to discord, which updates the status of all shards
100
- * @param {Presence} data - Presence on a server, contains online status and game (if any)
101
- * @param {String} [data.status=online] - Status of the bot, use one of the [status types](https://discordapp.com/developers/docs/topics/gateway#gateway-status-update-status-types)
102
- * @param {Game} [data.game=null] - Game object which is used for showing games/streams
103
- * @param {String} [data.game.name] - name of the game (required when data.game is not null)
104
- * @param {Number} [data.game.type=0] - type of the game, see [game types](https://discordapp.com/developers/docs/topics/gateway#gateway-status-update-status-types)
105
- * @param {String} [data.game.url] - url of the game, used when streaming in combination with data.game.type=1 to provide a link to the account of streamer, **only https://twitch.tv is supported atm**
106
- * @returns {Promise.<void>} Promise that's resolved once all shards have sent the websocket payload
107
- * @example
108
- * //Connect bot to discord and set status to do not disturb and game to "Memes are Dreams"
109
- * let bot = new CloudStorm(token)
110
- * await bot.connect()
111
- * bot.on('ready', () => {
112
- * // Bot is connected to discord and ready so we can update the status
113
- * bot.statusUpdate({status:'dnd', game:{name:'Memes are Dreams'}})
114
- * });
115
- */
116
- statusUpdate(data) {
117
- this.shardManager.statusUpdate(data);
118
- }
119
-
120
- /**
121
- * Send a status update to discord, which updates the status of a single shard
122
- * @param {Number} shardId Id of the shard that should update it's status
123
- * @param {Presence} data - Presence on a server, contains online status and game (if any)
124
- * @param {String} [data.status=online] - Status of the bot, use one of the [status types](https://discordapp.com/developers/docs/topics/gateway#gateway-status-update-status-types)
125
- * @param {Game} [data.game=null] - Game object which is used for showing games/streams
126
- * @param {String} [data.game.name] - name of the game (required when data.game is not null)
127
- * @param {Number} [data.game.type=0] - type of the game, see [game types](https://discordapp.com/developers/docs/topics/gateway#gateway-status-update-status-types)
128
- * @param {String} [data.game.url] - url of the game, used when streaming in combination with data.game.type=1 to provide a link to the account of streamer, **only https://twitch.tv is supported atm**
129
- * @returns {Promise.<void>} Promise that's resolved once the shard has sent the websocket payload
130
- * @example
131
- * //Connect bot to discord and set status to do not disturb and game to "Im shard 0"
132
- * let bot = new CloudStorm(token)
133
- * await bot.connect()
134
- * bot.on('ready', () => {
135
- * // Bot is connected to discord and ready so we can update the status of shard 0
136
- * bot.shardStatusUpdate(0, {status:'dnd', game:{name:'Im shard 0'}})
137
- * });
138
- */
139
- shardStatusUpdate(shardId, data) {
140
- return this.shardManager.shardStatusUpdate(shardId, data);
141
- }
142
-
143
- /**
144
- * Send a voice state update to discord, this does **not** allow you to send audio with cloudstorm itself,
145
- * it just provides the necessary data for another application to send audio data to discord
146
- * @param {Number} shardId - id of the shard that should send the payload
147
- * @param {VoiceStateUpdate} data - voice state update data to send
148
- * @param {String} data.guild_id - id of the guild where the channel exists
149
- * @param {String|null} data.channel_id - id of the channel to join or null if leaving channel
150
- * @param {Boolean} data.self_mute - if the client is muted
151
- * @param {Boolean} data.self_deaf - if the client is deafened
152
- * @returns {Promise.<void>} - Promise that's resolved once the payload was sent to discord
153
- * @example
154
- * //Connect bot to discord and join a voice channel
155
- * let bot = new CloudStorm(token)
156
- * await bot.connect()
157
- * bot.on('ready', () => {
158
- * // Bot is connected to discord and ready so we can join a voice channel
159
- * // We will use shard 0 as the shard to send the payload
160
- * bot.voiceStateUpdate(0, {guild_id:'id', channel_id:'id', self_mute:false, self_deaf:false})
161
- * });
162
- */
163
- voiceStateUpdate(shardId, data) {
164
- return this.shardManager.voiceStateUpdate(shardId, data);
165
- }
166
-
167
- /**
168
- * Send a request guild members update to discord
169
- * @param {Number} shardId - id of the shard that should send the payload
170
- * @param {RequestGuildMembers} data - request payload to send, see below for details
171
- * @param {String} data.guild_id - id of the guild
172
- * @param {String} [data.query=null] - string that the username starts with or empty to match all members
173
- * @param {Number} [data.limit=0] - limit of members that should be returned or 0 to return all
174
- * @returns {Promise.<void>} - Promise that's resolved once the payload was send to discord
175
- * @example
176
- * //Connect bot to discord and set status to do not disturb and game to "Memes are Dreams"
177
- * let bot = new CloudStorm(token)
178
- * await bot.connect()
179
- * bot.on('ready', () => {
180
- * // Bot is connected to discord and ready so we can send the request guild members payload
181
- * // We will use shard 0 as the shard to send the payload
182
- * bot.requestGuildMembers(0, {guild_id:'id'})
183
- * });
184
- */
185
- requestGuildMembers(shardId, data) {
186
- if (!data.guild_id) {
187
- throw new Error('You need to pass a guild_id');
188
- }
189
- return this.shardManager.requestGuildMembers(shardId, data);
190
- }
191
-
192
- _updateEndpoint(gatewayUrl) {
193
- this.options.endpoint = `${gatewayUrl}?v=${Constants.GATEWAY_VERSION}&encoding=${Erlpack ? 'etf' : 'json'}&compress=zlib-stream`;
194
- }
195
- }
196
-
197
- /**
198
- * @typedef {Object} RequestGuildMembers
199
- * @property {String} guild_id - id of the guild
200
- * @property {String} query - string that the username starts with or empty to match all members
201
- * @property {Number} limit - limit of members that should be returned or 0 to return all
202
- * @private
203
- */
204
-
205
- /**
206
- * @typedef {Object} VoiceStateUpdate
207
- * @property {String} guild_id - id of the guild
208
- * @property {String|null} channel_id - id of the channel to join or null if leaving channel
209
- * @property {Boolean} self_mute - if the client is muted
210
- * @property {Boolean} self_deaf - if the client is deafened
211
- * @private
212
- */
213
-
214
- /**
215
- * @typedef {Object} Presence - Presence on a server, contains online status and game (if any)
216
- * @property {String} status - Status of the bot, use one of the [status types](https://discordapp.com/developers/docs/topics/gateway#gateway-status-update-status-types)
217
- * @property {Game} game - Game to set
218
- * @private
219
- */
220
-
221
- /**
222
- * @typedef {Object} Game - Game object which is used for showing games/streams
223
- * @property {String} name - name of the game
224
- * @property {Number} [type=0] - type of the game, see [game types](https://discordapp.com/developers/docs/topics/gateway#gateway-status-update-status-types)
225
- * @property {String} [url] - url of the game, used when streaming in combination with type 1 to provide a link to the account of streamer, **only https://twitch.tv is supported atm**
226
- * @private
227
- */
228
-
229
- module.exports = Client;
package/src/Constants.js DELETED
@@ -1,16 +0,0 @@
1
- 'use strict';
2
- module.exports.GATEWAY_OP_CODES = {
3
- DISPATCH: 0,
4
- HEARTBEAT: 1,
5
- IDENTIFY: 2,
6
- STATUS_UPDATE: 3,
7
- VOICE_STATE_UPDATE: 4,
8
- VOICE_SERVER_PING: 5,
9
- RESUME: 6,
10
- RECONNECT: 7,
11
- REQUEST_GUILD_MEMBERS: 8,
12
- INVALID_SESSION: 9,
13
- HELLO: 10,
14
- HEARTBEAT_ACK: 11
15
- };
16
- module.exports.GATEWAY_VERSION = 6;