-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathold_keybase_bot_index.js
More file actions
1396 lines (1189 loc) · 41.1 KB
/
old_keybase_bot_index.js
File metadata and controls
1396 lines (1189 loc) · 41.1 KB
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var snakeCase = _interopDefault(require('lodash.snakecase'));
var camelCase = _interopDefault(require('lodash.camelcase'));
var kebabCase = _interopDefault(require('lodash.kebabcase'));
var os = _interopDefault(require('os'));
var crypto = _interopDefault(require('crypto'));
var child_process = require('child_process');
var readline = _interopDefault(require('readline'));
var mkdirp = _interopDefault(require('mkdirp'));
var util = require('util');
var fs = require('fs');
var fs__default = _interopDefault(fs);
var path = _interopDefault(require('path'));
/**
Takes a Keybase API input JavaScript object and recursively formats it into snake_case or kebab-case instead of camelCase for the service.
* @ignore
* @param obj - The object to be formatted.
* @param apiType - The type of api the the input is being served to. Currently Keybase has chat, team, and wallet apis.
* @returns - The new, formatted object.
* @example
* const inputOptions = formatAPIObject({unreadOnly: true})
* console.log(inputOptions) // {unread_only: true}
*/
function formatAPIObjectInput(obj, apiType) {
if (obj === null || obj === undefined || typeof obj !== 'object') {
return obj;
} else if (Array.isArray(obj)) {
return obj.map(item => formatAPIObjectInput(item, apiType));
} else {
return Object.keys(obj).reduce((newObj, key) => {
// TODO: hopefully we standardize how the Keybase API handles input keys
let formattedKey;
if (apiType === 'wallet') {
formattedKey = kebabCase(key);
} else {
formattedKey = snakeCase(key);
}
if (typeof obj[key] === 'object') {
return { ...newObj,
[formattedKey]: formatAPIObjectInput(obj[key], apiType)
};
}
return { ...newObj,
[formattedKey]: obj[key]
};
}, {});
}
}
/*
* An internal blacklist of parent levels at which formatAPIObjectOutput transformations
* shouldn't be performed. A `null` value matches everything.
*/
const transformsBlacklist = {
chat: {
read: [['messages', null, 'msg', 'reactions', 'reactions', null]]
}
/**
* Context of the object formatting process.
* @ignore
*/
};
/*
* Matches a context against the list of blacklisted parent levels.
* @ignore
* @param context - The context to match.
* @returns - Whether the context is blacklisted from being formatted.
*/
function matchBlacklist(context) {
if (!context || !transformsBlacklist[context.apiName] || !transformsBlacklist[context.apiName][context.method]) {
return false;
}
const parentLength = context.parent ? context.parent.length : 0;
for (const matcher of transformsBlacklist[context.apiName][context.method]) {
if (matcher.length !== parentLength) {
continue;
} // Iterate over the items of the matcher
let mismatch = false;
for (const [matcherIndex, desiredValue] of matcher.entries()) {
if (desiredValue === null) {
continue;
}
if (typeof context.parent === 'object' && context.parent[matcherIndex] !== desiredValue) {
mismatch = true;
break;
}
}
if (!mismatch) {
return true;
}
}
return false;
}
/*
* Appends a new key to the parents array in the formatting context.
* @ignore
* @param context - The context to copy and modify.
* @param key - The key to apprent to the parent array.
* @returns - A new context.
*/
function buildContext(context, key) {
if (!context) {
return context;
}
const copiedContext = { ...context
};
if (!copiedContext.parent) {
copiedContext.parent = [key];
} else {
copiedContext.parent = copiedContext.parent.slice();
copiedContext.parent.push(key);
}
return copiedContext;
}
/**
Takes a Keybase output object and formats it in a more digestable JavaScript style by using camelCase instead of snake_case.
* @ignore
* @param obj - The object to be formatted.
* @param context - An optional context with information about the called method required to perform blacklist lookups.
* @returns - The new, formatted object.
* @example
* const outputRes = formatAPIObject({unread_only: true})
* console.log(outputRes) // {unreadOnly: true}
*/
function formatAPIObjectOutput(obj, context) {
if (obj == null || typeof obj !== 'object') {
return obj;
} else if (Array.isArray(obj)) {
return obj.map((item, i) => formatAPIObjectOutput(item, buildContext(context, i)));
} else {
return Object.keys(obj).reduce((newObj, key) => {
const formattedKey = matchBlacklist(context) ? key : camelCase(key);
if (typeof obj[key] === 'object') {
return { ...newObj,
[formattedKey]: formatAPIObjectOutput(obj[key], buildContext(context, key))
};
}
return { ...newObj,
[formattedKey]: obj[key]
};
}, {});
}
}
const keybaseExec = (workingDir, homeDir, args, options = {
stdinBuffer: undefined,
onStdOut: undefined
}) => {
const runArgs = [...args];
if (homeDir) {
runArgs.unshift('--home', homeDir);
}
const keybasePath = path.join(workingDir, 'keybase');
const child = child_process.spawn(keybasePath, runArgs);
const stdOutBuffer = [];
const stdErrBuffer = [];
if (options.stdinBuffer) {
child.stdin.write(options.stdinBuffer);
}
child.stdin.end();
const lineReaderStdout = readline.createInterface({
input: child.stdout
}); // Use readline interface to parse each line (\n separated) when provided
// with onStdOut callback
if (options.onStdOut) {
lineReaderStdout.on('line', options.onStdOut);
} else {
child.stdout.on('data', chunk => {
stdOutBuffer.push(chunk);
});
} // Capture STDERR and use as error message if needed
child.stderr.on('data', chunk => {
stdErrBuffer.push(chunk);
});
return new Promise((resolve, reject) => {
child.on('close', code => {
let finalStdOut = null; // Pass back
if (code) {
const errorMessage = Buffer.concat(stdErrBuffer).toString('utf8');
reject(new Error(errorMessage));
} else {
const stdout = Buffer.concat(stdOutBuffer).toString('utf8');
try {
finalStdOut = options.json ? JSON.parse(stdout) : stdout;
} catch (e) {
reject(e);
}
}
resolve(finalStdOut);
});
});
};
function randomTempDir() {
const name = crypto.randomBytes(16).toString('hex');
return path.join(os.tmpdir(), `keybase_bot_${name}`);
}
async function rmdirRecursive(dirName) {
const fsLstat = util.promisify(fs__default.lstat);
const fsUnlink = util.promisify(fs__default.unlink);
const fsRmdir = util.promisify(fs__default.rmdir);
const fsReaddir = util.promisify(fs__default.readdir);
const dirStat = await fsLstat(dirName);
if (dirStat) {
for (const entry of await fsReaddir(dirName)) {
const entryPath = path.join(dirName, entry);
const stat = await fsLstat(entryPath);
if (stat.isDirectory()) {
await rmdirRecursive(entryPath);
} else {
await fsUnlink(entryPath);
}
}
await fsRmdir(dirName);
}
}
/**
* Useful information like the username, device, home directory of your bot and
* configuration options.
*/
/**
* Returns { username, devicename, homeDir } from `keybase status --json`.
* @ignore
* @param workingDir - the directory containing the binary, according to top level Bot
* @param homeDir - The home directory of the service you want to fetch the status from.
* @example
* keybaseStatus('/my/dir').then(status => console.log(status.username))
*/
async function keybaseStatus(workingDir, homeDir) {
const status = await keybaseExec(workingDir, homeDir, ['status', '--json'], {
json: true
});
if (status && status.Username && status.Device && status.Device.name) {
return {
username: status.Username,
devicename: status.Device.name,
homeDir
};
} else {
throw new Error('Failed to get current username and device name.');
}
}
/**
* Checks whether the keybase service is running by calling `keybase status --json`.
* @ignore
* @param workingDir - the directory containing the binary, according to top level Bot
* @param homeDir - The home directory of the service you want to fetch the status from.
* @example
* pingKeybaseService('/my/dir').then(status => console.log("service running", status))
*/
async function pingKeybaseService(workingDir, homeDir) {
// TODO: use a faster technique when core releases one
try {
await keybaseExec(workingDir, homeDir, ['--no-auto-fork', 'status', '--json'], {
json: true
});
return true;
} catch (err) {
return false;
}
}
const aExec = util.promisify(child_process.exec);
/**
* Returns the full path to the keybase binary or throws an error
* @ignore
* @example
* whichKeybase().then((path) => console.log(path))
*/
async function whichKeybase() {
const {
stdout
} = await aExec('which keybase');
if (!stdout || !stdout.trim().length) {
throw new Error('Could not find keybase binary');
}
const res = stdout.trim();
return res;
}
function timeout(time) {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, time);
});
}
class Service {
constructor(workingDir) {
this.workingDir = workingDir;
this.initialized = false;
this.verbose = false;
this.botLite = true;
this.disableTyping = true;
}
async init(username, paperkey, options) {
if (!username || typeof username !== 'string') {
throw new Error(`Please provide a username to initialize the bot. Got: ${JSON.stringify(username)}`);
}
if (!paperkey || typeof paperkey !== 'string') {
// Don't want to accidentally print the paperkey to STDERR.
throw new Error(`Please provide a paperkey to initialize the bot.`);
}
if (this.initialized) {
throw new Error('Cannot initialize an already initialized bot.');
}
this.homeDir = this.workingDir;
this.serviceLogFile = path.join(this.homeDir, 'Library', 'Logs', 'keybase.service.log');
this.botLite = options ? Boolean(typeof options.botLite !== 'boolean' || options.botLite) : true;
this.disableTyping = options ? Boolean(typeof options.disableTyping !== 'boolean' || options.disableTyping) : true; // Unlike with clients we don't need to store the service, since it shuts down with ctrl stop
try {
await this.startupService();
await keybaseExec(this.workingDir, this.homeDir, ['oneshot', '--username', username], {
stdinBuffer: paperkey
}); // Set the typing notification settings for the bot
await keybaseExec(this.workingDir, this.homeDir, ['chat', 'notification-settings', 'disable-typing', this.disableTyping.toString()]);
const currentInfo = await keybaseStatus(this.workingDir, this.homeDir);
if (currentInfo && currentInfo.username && currentInfo.devicename) {
this.initialized = 'paperkey';
this.username = currentInfo.username;
this.devicename = currentInfo.devicename;
this.verbose = options ? Boolean(options.verbose) : false;
}
if (this.username !== username) {
throw new Error('Failed to initialize service.');
}
} catch (err) {
await this._killCustomService();
throw err;
}
}
async initFromRunningService(homeDir, options) {
if (this.initialized) {
throw new Error('Cannot initialize an already initialized bot.');
}
this.homeDir = homeDir;
const currentInfo = await keybaseStatus(this.workingDir, this.homeDir);
if (currentInfo && currentInfo.username && currentInfo.devicename) {
this.initialized = 'runningService';
this.username = currentInfo.username;
this.devicename = currentInfo.devicename;
this.verbose = options ? Boolean(options.verbose) : false;
}
}
async _killCustomService() {
// these 2 commands might be unnecessary; since the service was `spawn`ed not detached
// they will also shutdown via SIGINT. We don't want to make service detached because it'd be nice for
// them to auto-shutdown if the user kills the process
try {
await keybaseExec(this.workingDir, this.homeDir, ['logout']);
} catch (e) {}
try {
await keybaseExec(this.workingDir, this.homeDir, ['ctl', 'stop', '--shutdown']);
} catch (e) {} // wait until the process quits by watching the running property
let i = 0;
while (true) {
await timeout(100);
if (!this.running) {
break;
}
if (++i >= 100) {
throw new Error(`The service didn't finish shutting down in time (${this.workingDir})`);
}
}
}
async deinit() {
if (!this.initialized) {
throw new Error('Cannot deinitialize an uninitialized bot.');
} // If we init the bot using paperkey credentials, then we want to stop the service and remove our generated directory.
if (this.initialized === 'paperkey') {
await this._killCustomService();
}
this.initialized = false;
}
myInfo() {
if (this.username && this.devicename) {
return {
username: this.username,
devicename: this.devicename,
homeDir: this.homeDir ? this.homeDir : undefined,
botLite: this.botLite,
disableTyping: this.disableTyping
};
}
return null;
}
/**
*
* @ignore
* This is a bit different from normal keybaseExecs and is unique to the service
* starting up
* @example
* service.startupService()
*/
async startupService() {
const args = ['service'];
if (this.homeDir) {
args.unshift('--home', this.homeDir);
}
if (this.serviceLogFile) {
args.unshift('-d', '--log-file', this.serviceLogFile);
}
if (this.botLite) {
args.unshift('--enable-bot-lite-mode');
}
const child = child_process.spawn(path.join(this.workingDir, 'keybase'), args, {
env: process.env
}); // keep track of the subprocess' state
this.running = true;
child.on('exit', code => {
this.running = false;
});
return new Promise(async (resolve, reject) => {
child.on('close', code => {
// any code here including 0 is bad here, if it happens before resolve
//, since this service should stay running
reject(new Error(`keybase service exited with code ${code} (${this.workingDir})`));
}); // Wait for the service to start up - give it 10s.
let i = 0;
while (!(await pingKeybaseService(this.workingDir, this.homeDir))) {
await timeout(100);
if (++i >= 100) {
throw new Error("Couldn't start up service fast enough");
}
}
resolve();
});
}
}
const API_VERSIONS = {
chat: 1,
team: 1,
wallet: 1
};
/**
* A Client base.
* @ignore
*/
class ClientBase {
constructor(workingDir) {
this._workingDir = workingDir;
this.initialized = false;
this.verbose = false;
this.spawnedProcesses = [];
}
async _init(homeDir, options) {
const initBotInfo = await keybaseStatus(this._workingDir, homeDir);
this.homeDir = homeDir;
this.username = initBotInfo.username;
this.devicename = initBotInfo.devicename;
this.initialized = true;
}
async _deinit() {
for (const child of this.spawnedProcesses) {
child.kill();
}
}
async _runApiCommand(arg) {
const options = arg.options ? formatAPIObjectInput(arg.options, arg.apiName) : undefined;
const input = {
method: arg.method,
params: {
version: API_VERSIONS[arg.apiName],
options
}
};
const inputString = JSON.stringify(input);
const size = inputString.length;
const output = await keybaseExec(this._workingDir, this.homeDir, [arg.apiName, 'api'], {
stdinBuffer: Buffer.alloc(size, inputString, 'utf8'),
json: true
});
if (output.hasOwnProperty('error')) {
throw new Error(output.error.message);
}
const res = formatAPIObjectOutput(output.result, {
apiName: arg.apiName,
method: arg.method
});
return res;
}
async _guardInitialized() {
if (!this.initialized) {
throw new Error('The client is not yet initialized.');
}
}
_pathToKeybaseBinary() {
return path.join(this._workingDir, 'keybase');
}
}
/** The chat module of your Keybase bot. For more info about the API this module uses, you may want to check out `keybase chat api`. */
class Chat extends ClientBase {
/**
* Lists your chats, with info on which ones have unread messages.
* @memberof Chat
* @param options - An object of options that can be passed to the method.
* @returns - An array of chat conversations. If there are no conversations, the array is empty.
* @example
* bot.chat.list({unreadOnly: true}).then(chatConversations => console.log(chatConversations))
*/
async list(options) {
await this._guardInitialized();
const res = await this._runApiCommand({
apiName: 'chat',
method: 'list',
options
});
if (!res) {
throw new Error('Keybase chat list returned nothing.');
}
return res.conversations || [];
}
/**
* Lists conversation channels in a team
* @memberof Chat
* @param name - Name of the team
* @param options - An object of options that can be passed to the method.
* @returns - An array of chat conversations. If there are no conversations, the array is empty.
* @example
* bot.chat.listChannels('team_name').then(chatConversations => console.log(chatConversations))
*/
async listChannels(name, options) {
await this._guardInitialized();
const optionsWithDefaults = { ...options,
name,
membersType: options && options.membersType ? options.membersType : 'team'
};
const res = await this._runApiCommand({
apiName: 'chat',
method: 'listconvsonname',
options: optionsWithDefaults
});
if (!res) {
throw new Error('Keybase chat list convs on name returned nothing.');
}
return res.conversations || [];
}
/**
* Reads the messages in a channel. You can read with or without marking as read.
* @memberof Chat
* @param channel - The chat channel to read messages in.
* @param options - An object of options that can be passed to the method.
* @returns - A summary of data about a message, including who send it, when, the content of the message, etc. If there are no messages in your channel, then an error is thrown.
* @example
* alice.chat.read(channel).then(messages => console.log(messages))
*/
async read(channel, options) {
await this._guardInitialized();
const optionsWithDefaults = { ...options,
channel,
peek: options && options.peek ? options.peek : false,
unreadOnly: options && options.unreadOnly !== undefined ? options.unreadOnly : false
};
const res = await this._runApiCommand({
apiName: 'chat',
method: 'read',
options: optionsWithDefaults
});
if (!res) {
throw new Error('Keybase chat read returned nothing.');
} // Pagination gets passed as-is, while the messages get cleaned up
return {
pagination: res.pagination,
messages: res.messages.map(message => message.msg)
};
}
/**
* Joins a team conversation.
* @param channel - The team chat channel to join.
* @example
* bot.chat.listConvsOnName('team_name').then(async teamConversations => {
* for (const conversation of teamConversations) {
* if (conversation.memberStatus !== 'active') {
* await bot.chat.join(conversation.channel)
* console.log('Joined team channel', conversation.channel)
* }
* }
* })
*/
async joinChannel(channel) {
await this._guardInitialized();
const res = await this._runApiCommand({
apiName: 'chat',
method: 'join',
options: {
channel
}
});
if (!res) {
throw new Error('Keybase chat join returned nothing');
}
}
/**
* Leaves a team conversation.
* @param channel - The team chat channel to leave.
* @example
* bot.chat.listConvsOnName('team_name').then(async teamConversations => {
* for (const conversation of teamConversations) {
* if (conversation.memberStatus === 'active') {
* await bot.chat.leave(conversation.channel)
* console.log('Left team channel', conversation.channel)
* }
* }
* })
*/
async leaveChannel(channel) {
await this._guardInitialized();
const res = await this._runApiCommand({
apiName: 'chat',
method: 'leave',
options: {
channel
}
});
if (!res) {
throw new Error('Keybase chat leave returned nothing');
}
}
/**
* Send a message to a certain channel.
* @memberof Chat
* @param channel - The chat channel to send the message in.
* @param message - The chat message to send.
* @param options - An object of options that can be passed to the method.
* @example
* const channel = {name: 'kbot,' + bot.myInfo().username, public: false, topicType: 'chat'}
* const message = {body: 'Hello kbot!'}
* bot.chat.send(channel, message).then(() => console.log('message sent!'))
*/
async send(channel, message, options) {
await this._guardInitialized();
const args = { ...options,
channel,
message
};
const res = await this._runApiCommand({
apiName: 'chat',
method: 'send',
options: args
});
if (!res) {
throw new Error('Keybase chat send returned nothing');
}
return {
id: res.id
};
}
/**
* Creates a new blank conversation.
* @memberof Chat
* @param channel - The chat channel to create.
* @example
* bot.chat.createChannel(channel).then(() => console.log('conversation created'))
*/
async createChannel(channel) {
await this._guardInitialized();
const args = {
channel
};
const res = await this._runApiCommand({
apiName: 'chat',
method: 'newconv',
options: args
});
if (!res) {
throw new Error('Keybase chat newconv returned nothing');
}
}
/**
* Send a file to a channel.
* @memberof Chat
* @param channel - The chat channel to send the message in.
* @param filename - The absolute path of the file to send.
* @param options - An object of options that can be passed to the method.
* @example
* bot.chat.attach(channel, '/Users/nathan/my_picture.png').then(() => console.log('Sent a picture!'))
*/
async attach(channel, filename, options) {
await this._guardInitialized();
const args = { ...options,
channel,
filename
};
const res = await this._runApiCommand({
apiName: 'chat',
method: 'attach',
options: args
});
if (!res) {
throw new Error('Keybase chat attach returned nothing');
}
return {
id: res.id
};
}
/**
* Download a file send via Keybase chat.
* @memberof Chat
* @param channel - The chat channel that the desired attacment to download is in.
* @param messageId - The message id of the attached file.
* @param output - The absolute path of where the file should be downloaded to.
* @param options - An object of options that can be passed to the method
* @example
* bot.chat.download(channel, 325, '/Users/nathan/Downloads/file.png')
*/
async download(channel, messageId, output, options) {
await this._guardInitialized();
const args = { ...options,
channel,
messageId,
output
};
const res = await this._runApiCommand({
apiName: 'chat',
method: 'download',
options: args
});
if (!res) {
throw new Error('Keybase chat download returned nothing');
}
}
/**
* Reacts to a given message in a channel. Messages have messageId's associated with
* them, which you can learn in `bot.chat.read`.
* @memberof Chat
* @param channel - The chat channel to send the message in.
* @param messageId - The id of the message to react to.
* @param reaction - The reaction emoji, in colon form.
* @param options - An object of options that can be passed to the method.
* @example
* bot.chat.react(channel, 314, ':+1:').then(() => console.log('Thumbs up!'))
*/
async react(channel, messageId, reaction, options) {
await this._guardInitialized();
const args = { ...options,
channel,
messageId,
message: {
body: reaction
}
};
const res = await this._runApiCommand({
apiName: 'chat',
method: 'reaction',
options: args
});
if (!res) {
throw new Error('Keybase chat react returned nothing.');
}
return {
id: res.id
};
}
/**
* Deletes a message in a channel. Messages have messageId's associated with
* them, which you can learn in `bot.chat.read`. Known bug: the GUI has a cache,
* and deleting from the CLI may not become apparent immediately.
* @memberof Chat
* @param channel - The chat channel to send the message in.
* @param messageId - The id of the message to delete.
* @param options - An object of options that can be passed to the method.
* @example
* bot.chat.delete(channel, 314).then(() => console.log('message deleted!'))
*/
async delete(channel, messageId, options) {
await this._guardInitialized();
const args = { ...options,
channel,
messageId
};
const res = await this._runApiCommand({
apiName: 'chat',
method: 'delete',
options: args
});
if (!res) {
throw new Error('Keybase chat delete returned nothing.');
}
}
/**
* Listens for new chat messages on a specified channel. The `onMessage` function is called for every message your bot receives. This is pretty similar to `watchAllChannelsForNewMessages`, except it specifically checks one channel. Note that it receives messages your own bot posts, but from other devices. You can filter out your own messages by looking at a message's sender object.
* Hides exploding messages by default.
* @memberof Chat
* @param channel - The chat channel to watch.
* @param onMessage - A callback that is triggered on every message your bot receives.
* @param onError - A callback that is triggered on any error that occurs while the method is executing.
* @param options - Options for the listen method.
* @example
* // Reply to all messages between you and `kbot` with 'thanks!'
* const channel = {name: 'kbot,' + bot.myInfo().username, public: false, topicType: 'chat'}
* const onMessage = message => {
* const channel = message.channel
* bot.chat.send(channel, {body: 'thanks!!!'})
* }
* bot.chat.watchChannelForNewMessages(channel, onMessage)
*/
async watchChannelForNewMessages(channel, onMessage, onError, options) {
await this._guardInitialized();
this._chatListen(onMessage, onError, channel, options);
}
/**
* This function will put your bot into full-read mode, where it reads
* everything it can and every new message it finds it will pass to you, so
* you can do what you want with it. For example, if you want to write a
* Keybase bot that talks shit at anyone who dares approach it, this is the
* function to use. Note that it receives messages your own bot posts, but from other devices.
* You can filter out your own messages by looking at a message's sender object.
* Hides exploding messages by default.
* @memberof Chat
* @param onMessage - A callback that is triggered on every message your bot receives.
* @param onError - A callback that is triggered on any error that occurs while the method is executing.
* @param options - Options for the listen method.
* @example
* // Reply to incoming traffic on all channels with 'thanks!'
* const onMessage = message => {
* const channel = message.channel
* bot.chat.send(channel, {body: 'thanks!!!'})
* }
* bot.chat.watchAllChannelsForNewMessages(onMessage)
*
*/
async watchAllChannelsForNewMessages(onMessage, onError, options) {
await this._guardInitialized();
this._chatListen(onMessage, onError, undefined, options);
}
/**
* Spawns the chat listen process and handles the calling of onMessage, onError, and filtering for a specific channel.
* @memberof Chat
* @ignore
* @param onMessage - A callback that is triggered on every message your bot receives.
* @param onError - A callback that is triggered on any error that occurs while the method is executing.
* @param channel - The chat channel to watch.
* @param options - Options for the listen method.
* @example
* this._chatListen(onMessage, onError)
*/
_chatListen(onMessage, onError, channel, options) {
const args = ['chat', 'api-listen'];
if (this.homeDir) {
args.unshift('--home', this.homeDir);
}
if (!options || options && options.hideExploding !== false) {
args.push('--hide-exploding');
}
if (channel) {
args.push('--filter-channel', JSON.stringify(formatAPIObjectInput(channel, 'chat')));
}
const child = child_process.spawn(this._pathToKeybaseBinary(), args);
this.spawnedProcesses.push(child);
const lineReaderStdout = readline.createInterface({
input: child.stdout
});
const onLine = line => {