-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
453 lines (395 loc) · 12.4 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
#!/bin/env node
'use strict';
import Connection from 'euphoria-connection';
import EventEmitter from 'events';
import { v4 as uuid } from 'uuid';
// TODO: filters for commands.
class Bot extends EventEmitter {
constructor(
nick = '><>',
room = 'test',
settings = {
commands: [], // extra default commands
disconnect_on_kill: false, // disconnect intead of stopping when killed
stateless: false, // if a bot is stateless it does not keep track of server side state, rather trusting the information it has, this also disables listing and logging
reconnect: true, // reconnect on unexpected disconnect
ping_interval: 5000, // ping the server every ping_interval. Set to 0 to disable.
log_max: 0 // the maximum size of the log 0 means limitless
},
defaults = {
room: room,
human: 0,
host: 'wss://euphoria.io',
options: { origin: 'https://euphoria.io' },
}) {
super();
process.setMaxListeners(100);
this.setMaxListeners(100);
this.connection = new Connection(defaults.room, defaults.human, defaults.host, defaults.options, json => this._handle_snapshot(json));
// properties
this._room = defaults.room;
this._human = defaults.human;
this._host = defaults.host;
this._connection_options = defaults.options;
this._settings = settings;
this._nick = nick;
this._reconnect_delay = 5000;
this._ping_interval = settings.ping_interval || 5000
this._listing = [];
this._log = [];
this._config = {
regex: false,
disconnect_on_kill: settings.disconnect_on_kill || false
};
this._reconnect = settings.reconnect || true;
// TODO: create an immutable way to refer to self and make this clear to any user
this._id = uuid();
this.self = this._id;
this.commands = settings.commands || [];
this.commands['!help'] = this._make_reaction('I\'m a bot created using https://github.com/kaliumxyz/euphoria.js');
this.commands[`!help ${this._id}`] = this._make_reaction('I\'m a bot created using https://github.com/kaliumxyz/euphoria.js');
this.commands['!ping'] = this._make_reaction('pong!');
this.commands[`!kill ${this._id}`] = id => {
this.post('/me is exiting', id);
if (!this._config.disconnect_on_kill)
process.exit(0);
else
this.connection.close();
};
this.commands[`!ping ${this._id}`] = this._make_reaction('pong!');
this._add_listeners(this);
this._heartbeat_interval;
this.connection.once('open', () => {
this._heartbeat_interval = setInterval(_ => this._heartbeat(this.connection), this._ping_interval)
if (nick !== "") {
this.nick = nick;
this.connection.once('nick-reply', () => {
this.emit('open');
})
} else {
this.emit('open');
}
});
process.on('exit', () => {
this._reconnect = false;
this.connection.close();
});
}
_add_listeners(that) {
that.connection.setMaxListeners(100);
that.connection.on('close', () => {
if(that._reconnect)
setTimeout(() => {that.reconnect()}, that._reconnect_delay)
});
that.connection.on('error', err => {
if(that._reconnect)
this.connection.close();
});
that.connection.on('send-reply', json => {
if (!json.error) {
that._handle_send_event(json);
} else {
console.error(json.error)
}
that.emit('send-reply', json);
});
that.connection.on('send-event', json => {
that._handle_send_event(json);
});
that.connection.on('nick-event', json => {
that._handle_nick_event(json);
});
that.connection.on('hello-event', json => {
that._handle_hello_event(json);
});
that.connection.on('join-event', json => {
that._handle_join_event(json);
});
that.connection.on('part-event', json => {
that._handle_part_event(json);
});
that.connection.on('ping-reply', json => {
that.emit('ping-reply', json);
});
}
/**
*
* sends public message with ${content} and optionally as a reply to ${parent}. But async
* @param {*} content
* @param {*} parent
*/
post_async(content, parent) {
return new Promise((resolve, reject) => {
const pattern = new RegExp(this.self, 'g')
const parsed = content.replace(pattern, `@${this._nick}`);
if (Array.isArray(parent)) {
parent.forEach(parent => {
this.emit('posting', {content: parsed,bot: {unparsed: content}, parent: parent});
this.connection.post(parsed, parent);
});
} else {
this.emit('posting', {content: parsed,bot: {unparsed: content}, parent: parent});
this.connection.post(parsed, parent);
}
this.once('send-reply', json => resolve(json.data));
});
}
/**
*
* sends public message with ${content} and optionally as a reply to ${parent}
* @param {*} content
* @param {*} parent
*/
post(content, parent) {
const pattern = new RegExp(this.self, 'g')
const parsed = content.replace(pattern, `@${this._nick}`);
if (Array.isArray(parent)) {
parent.forEach(parent => {
this.emit('posting', {content: parsed, bot: {unparsed: content}, parent: parent});
this.connection.post(parsed, parent);
});
} else {
this.emit('posting', {content: parsed, bot: {unparsed: content}, parent: parent});
this.connection.post(parsed, parent);
}
return this;
}
/**
*
* sends public message without replacing bot.self with ${content} and optionally as a reply to ${parent}
* @param {*} content
* @param {*} parent
*/
post_raw(content, parent) {
if (Array.isArray(parent)) {
parent.forEach(parent => {
this.emit('posting', {content: content, bot: {unparsed: content}, parent: parent});
this.connection.post(content, parent);
});
} else {
this.emit('posting', {content: content, bot: {unparsed: content}, parent: parent});
this.connection.post(content, parent);
}
return this;
}
/* reply to the last post or post of id
*
*/
reply(content){
this.post(content, this.log[ this.log.length - 1 ].id);
return this;
}
_make_reaction(message) {
return id => this.post(message, id);
}
/**
* add a comand, returns the index of the command
* TODO: add real command object that is returned, which has features to allow for mutating the command.
* TODO: add the ability to define commands using templates
* @param {*} command
* @param {*} reaction
*/
add_command(command, reaction) {
// check if command is a string or regular expression.
if (reaction === void(0))
throw new Error('reaction is Undefined');
if (typeof command === 'string' || command.test) {
const command_index = uuid();
switch(typeof reaction) {
case 'string':
this.commands[command_index] = this._make_reaction(reaction);
break;
case 'function':
this.commands[command_index] = reaction;
break;
default:
this.commands[command_index] = this._make_reaction(reaction.toString());
break;
}
return command_index;
}
throw new Error('Command is not of type String or has property .test');
}
_handle_send_event(json) {
const data = json.data;
if (!this._settings.stateless) {
if (this._settings.log_max && this._settings.log_max !== 0 && this._settings.log_max < this._log.length) {
this._log.pop();
}
this._log.push(data);
} else { // just keep one item in log for reply to work
this._log.pop();
this._log.push(data);
}
// any functionality must come AFTER pushing to log, in case the log is needed
// replace the nick with its ID in the context of the commands.
const pattern = new RegExp(`@${this._stripped_nick}`, 'g')
const content = data.content.replace(pattern, this._id);
const reaction = this.commands[content];
if(reaction)
reaction(data.id);
// we want to allow things further up the chain to know if there already has been a reaction, and access the modified content
const bot = {
reaction: reaction,
parsed: content
};
json.bot = bot;
data.bot = bot;
this.emit('send-event', json);
this.emit('post', data);
}
_handle_hello_event(json) {
const data = json.data;
if (!this._settings.stateless)
this._listing.push(data.session);
this.emit('hello-event', json);
}
_handle_join_event(json) {
const data = json.data;
if (!this._settings.stateless)
this._listing.push(data);
this.emit('join-event', json);
}
_handle_part_event(json) {
const data = json.data;
if (!this._settings.stateless)
this._listing.splice(this._listing.findIndex(item => item.id === data.id), 1);
this.emit('part-event', json);
}
_handle_nick_event(json) {
const data = json.data;
if (!this._settings.stateless) {
const index = this._listing.findIndex(item => item.session_id === data.session_id)
if (this._listing[index]) {
this._listing[index].name = data.nick;
}
}
this.emit('nick-event', json);
}
_handle_snapshot(json) {
const data = json.data;
this._identity = data.identity;
this._session_id = data.session_id;
this._version = data.version;
if (!this._settings.stateless) {
this._listing = this._listing.concat(data.listing);
this._log = data.log;
}
this.emit('ready');
}
_heartbeat(connection) {
const timestamp = Date.now();
connection.ping(timestamp, data => {
const time = timestamp;
if (data && data.data && data.data.time && data.data.time === time) {
// server is still alive
} else {
// server died. We close the connection and start reconnecting or if
// reconnecting is disabled, we exit.
this.reconnect();
}
});
}
reconnect(room) {
clearInterval(this._heartbeat_interval)
this.emit('reconnecting');
const rec = this._reconnect;
this._reconnect = false;
this.connection.close();
if (room)
this._room = room;
//TODO: figure out if the old connection gets GCd or not
this.connection = new Connection(this.room, this.human, this.host, this.connection_options);
this._add_listeners(this);
this.connection.once('open', () => {
//TODO save the listeners
this._reconnect = rec;
this._heartbeat_interval = setInterval(_ => this._heartbeat(this.connection), this._ping_interval)
this.nick = this.nick;
this.emit('reconnected');
});
return this;
}
set nick(nick) {
if (!nick || typeof(nick) !== 'string') {
return
}
this.connection.nick(nick);
this._nick = nick;
// private nick without spaces to be compatible with euphoria completion / calling
this._stripped_nick = nick?nick.split(' ').join(''):nick;
this.connection.once('nick-reply', json => {
const data = json.data;
if (data && data.to) {
if (!this._settings.stateless) {
nick = data.to
this._nick = nick;
this._stripped_nick = nick?nick.split(' ').join(''):nick;
const index = this._listing.findIndex(item => item.session_id === data.session_id)
if (this._listing[index]) {
this._listing[index].name = nick;
}
}
this.emit('nick-set', data.to);
}
});
}
get nick() {
return this._nick;
}
get users() {
return this._users;
}
set room(room) {
const that = this;
setTimeout(_=> {
that.reconnect(room)
},10)
}
get room() {
return this._room;
}
get human() {
return this._human;
}
get connection_options() {
return this._connection_options;
}
get host() {
return this._host;
}
/**
* return the first n from the log
* @param {Number} n
*/
head(n) {
// slice creates a copy.
return this._log.slice(0, n);
}
/**
* return the last n from the log
* @param {Number} n
*/
tail(n) {
// slice creates a copy.
return this._log.slice(this._log.length - n);
}
get log() {
// slice creates a copy.
return this._log.slice(0);
}
get version() {
return this._version;
}
get listing() {
// slice creates a copy.
return this._listing.slice(0);
}
get identity() {
return this._identity;
}
}
/* TODO: create factories for replies (e.g., make_reply, make_reply_html_get).
* remove the current outside of the Bot constructor to prevent it from getting too bloated.
*/
export {Bot};