-
Notifications
You must be signed in to change notification settings - Fork 65
/
index.ts
639 lines (603 loc) · 22.2 KB
/
index.ts
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
import {spawn} from 'child_process'
import readline from 'readline'
import ClientBase from '../client-base'
import {formatAPIObjectOutput, formatAPIObjectInput} from '../utils'
import * as chat1 from '../types/chat1'
/** A function to call when a message is received. */
export type OnMessage = (message: chat1.MsgSummary) => void | Promise<void>
/** A function to call when an error occurs. */
export type OnError = (error: Error) => void | Promise<void>
/**
* Options for the `list` method of the chat module.
*/
export interface ChatListOptions {
failOffline?: boolean
showErrors?: boolean
topicType?: chat1.TopicType
unreadOnly?: boolean
}
/**
* Options for the `listChannels` method of the chat module.
*/
export interface ChatListChannelsOptions {
topicType?: chat1.TopicType
membersType?: chat1.ConversationMembersType
}
/**
* Options for the `read` method of the chat module.
*/
export interface ChatReadOptions {
conversationId?: string
failOffline?: boolean
pagination?: chat1.Pagination
peek?: boolean
unreadOnly?: boolean
}
/**
* Options for the `send` method of the chat module.
*/
export interface ChatSendOptions {
conversationId?: string
nonblock?: boolean
membersType?: chat1.ConversationMembersType
confirmLumenSend?: boolean
}
/**
* Options for the `attach` method of the chat module.
*/
export interface ChatAttachOptions {
conversationId?: string
title?: string
preview?: string
}
/**
* Options for the `download` method of the chat module.
*/
export interface ChatDownloadOptions {
conversationId?: string
preview?: string
noStream?: boolean
}
/**
* Options for the `react` method of the chat module.
*/
export interface ChatReactOptions {
conversationId?: string
}
/**
* Options for the `delete` method of the chat module.
*/
export interface ChatDeleteOptions {
conversationId?: string
}
/**
* Options for the methods in the chat module that listen for new messages.
* Local messages are ones sent by your device. Including them in the output is
* useful for applications such as logging conversations, monitoring own flips
* and building tools that seamlessly integrate with a running client used by
* the user.
*/
export interface ListenOptions {
hideExploding: boolean
showLocal: boolean
}
export interface Advertisement {
alias?: string
advertisements: chat1.AdvertiseCommandAPIParam[]
}
export interface AdvertisementsLookup {
channel: chat1.ChatChannel
conversationID?: string
}
export interface ReadResult {
messages: chat1.MsgSummary[]
pagination: chat1.Pagination
}
/** 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
* const chatConversations = await bot.chat.list({unreadOnly: true})
* console.log(chatConversations)
*/
public async list(options?: ChatListOptions): Promise<chat1.ConvSummary[]> {
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))
*/
public async listChannels(name: string, options?: ChatListChannelsOptions): Promise<chat1.ConvSummary[]> {
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))
*/
public async read(channel: chat1.ChatChannel, options?: ChatReadOptions): Promise<ReadResult> {
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: chat1.MsgNotification): chat1.MsgSummary => 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)
* }
* }
* })
*/
public async joinChannel(channel: chat1.ChatChannel): Promise<void> {
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)
* }
* }
* })
*/
public async leaveChannel(channel: chat1.ChatChannel): Promise<void> {
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!'))
*/
public async send(channel: chat1.ChatChannel, message: chat1.ChatMessage, options?: ChatSendOptions): Promise<chat1.SendRes> {
await this._guardInitialized()
const args = {
...options,
channel,
message,
}
this._adminDebugLogger.info(`sending message "${message.body}" in channel ${JSON.stringify(channel)}`)
const res = await this._runApiCommand({
apiName: 'chat',
method: 'send',
options: args,
})
if (!res) {
throw new Error('Keybase chat send returned nothing')
}
this._adminDebugLogger.info(`message sent with id ${res.id}`)
return res
}
/**
* Creates a new blank conversation.
* @memberof Chat
* @param channel - The chat channel to create.
* @example
* bot.chat.createChannel(channel).then(() => console.log('conversation created'))
*/
public async createChannel(channel: chat1.ChatChannel): Promise<void> {
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!'))
*/
public async attach(channel: chat1.ChatChannel, filename: string, options?: ChatAttachOptions): Promise<chat1.SendRes> {
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 res
}
/**
* 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')
*/
public async download(channel: chat1.ChatChannel, messageId: number, output: string, options?: ChatDownloadOptions): Promise<void> {
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!'))
*/
public async react(channel: chat1.ChatChannel, messageId: number, reaction: string, options?: ChatReactOptions): Promise<chat1.SendRes> {
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 res
}
/**
* 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!'))
*/
public async delete(channel: chat1.ChatChannel, messageId: number, options?: ChatDeleteOptions): Promise<void> {
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.')
}
}
/**
* Gets current unfurling settings
* @example
* bot.chat.getUnfurlSettings().then((mode) => console.log(mode))
*/
public async getUnfurlSettings(): Promise<chat1.UnfurlSettings> {
await this._guardInitialized()
const res = await this._runApiCommand({apiName: 'chat', method: 'getunfurlsettings', options: {}})
if (!res) {
throw new Error('Keybase chat get unfurl mode returned nothing.')
}
return res
}
/**
* Sets the unfurling mode
* In Keybase, unfurling means generating previews for links that you're sending
* in chat messages. If the mode is set to always or the domain in the URL is
* present on the whitelist, the Keybase service will automatically send a preview
* to the message recipient in a background chat channel.
* @param mode - the new unfurl mode
* @example
* bot.chat.setUnfurlMode({
* "mode": "always",
* }).then((mode) => console.log('mode updated!'))
*/
public async setUnfurlSettings(mode: chat1.UnfurlSettings): Promise<void> {
await this._guardInitialized()
const res = await this._runApiCommand({apiName: 'chat', method: 'setunfurlsettings', options: mode})
if (!res) {
throw new Error('Keybase chat set unfurl mode returned nothing.')
}
}
/**
* Loads a flip's details
* @param conversationID - conversation ID received in API listen.
* @param flipConversationID - flipConvID from the message summary.
* @param messageID - ID of the message in the conversation.
* @param gameID - gameID from the flip message contents.
* @example
* // check demos/es7/poker-hands.js
*/
public async loadFlip(
conversationID: string,
flipConversationID: string,
messageID: number,
gameID: string
): Promise<chat1.UICoinFlipStatus> {
await this._guardInitialized()
const res = await this._runApiCommand({
apiName: 'chat',
method: 'loadflip',
options: formatAPIObjectInput({conversationID, flipConversationID, messageID, gameID}, 'chat'),
timeout: 2000,
})
if (!res) {
throw new Error('Keybase chat load flip returned nothing.')
}
return res.status
}
/**
* Publishes a commands advertisement which is shown in the "!" chat autocomplete.
* @param advertisement - details of the advertisement
* @example
* await bot.chat.advertiseCommands({
* advertisements: [
* {
* type: 'public',
* commands: [
* {
* name: '!echo',
* description: 'Sends out your message to the current channel.',
* usage: '[your text]',
* },
* ]
* }
* ],
* })
*/
public async advertiseCommands(advertisement: Advertisement): Promise<void> {
await this._guardInitialized()
const res = await this._runApiCommand({apiName: 'chat', method: 'advertisecommands', options: advertisement})
if (!res) {
throw new Error('Keybase chat advertise commands returned nothing.')
}
}
/**
* Clears all published commands advertisements.
* @param advertisement - advertisement parameters
* @example
* await bot.chat.clearCommands()
*/
public async clearCommands(): Promise<void> {
await this._guardInitialized()
const res = await this._runApiCommand({apiName: 'chat', method: 'clearcommands'})
if (!res) {
throw new Error('Keybase chat clear commands returned nothing.')
}
}
/**
* Lists all commands advertised in a channel.
* @param lookup - either conversation id or channel
* @example
* const commandsList = await bot.chat.listCommands({
* channel: channel,
* })
* console.log(commandsList)
* // prints out something like:
* // {
* // commands: [
* // {
* // name: '!helloworld',
* // description: 'sample description',
* // usage: '[command arguments]',
* // username: 'userwhopublished',
* // }
* // ]
* // }
*/
public async listCommands(lookup: AdvertisementsLookup): Promise<{commands: chat1.UserBotCommandOutput[]}> {
await this._guardInitialized()
const res = await this._runApiCommand({apiName: 'chat', method: 'listcommands', options: lookup})
if (!res) {
throw new Error('Keybase chat list commands returned nothing.')
}
return {commands: res.commands || []}
}
/**
* 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)
*/
public async watchChannelForNewMessages(
channel: chat1.ChatChannel,
onMessage: OnMessage,
onError?: OnError,
options?: ListenOptions
): Promise<void> {
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)
*
*/
public async watchAllChannelsForNewMessages(onMessage: OnMessage, onError?: OnError, options?: ListenOptions): Promise<void> {
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)
*/
private _chatListen(onMessage: OnMessage, onError?: OnError, channel?: chat1.ChatChannel, options?: ListenOptions): void {
const args = ['chat', 'api-listen']
if (this.homeDir) {
args.unshift('--home', this.homeDir)
}
if (!options || (options && options.hideExploding !== false)) {
args.push('--hide-exploding')
}
if (options && options.showLocal === true) {
args.push('--local')
}
if (channel) {
args.push('--filter-channel', JSON.stringify(formatAPIObjectInput(channel, 'chat')))
}
const child = spawn(this._pathToKeybaseBinary(), args)
this._spawnedProcesses.push(child)
const cmdSample = this._pathToKeybaseBinary() + ' ' + args.join(' ')
this._adminDebugLogger.info(`beginning listen on channel=${JSON.stringify(channel || 'ALL')} using ${cmdSample}`)
child.on('error', (err: Error): void => {
this._adminDebugLogger.error(`got listen error ${err.message}`)
})
child.on('exit', (): void => {
this._adminDebugLogger.info(`got listen exit`)
})
child.on('close', (): void => {
this._adminDebugLogger.info(`got listen close`)
})
child.on('disconnect', (): void => {
this._adminDebugLogger.info(`got listen disconnect`)
})
const lineReaderStderr = readline.createInterface({input: child.stderr})
lineReaderStderr.on('line', (line: string): void => {
this._adminDebugLogger.error(`stderr from listener: ${line}`)
})
const lineReaderStdout = readline.createInterface({input: child.stdout})
const onLine = (line: string): void => {
this._adminDebugLogger.info(`stdout from listener: ${line}`)
try {
const messageObject: chat1.MsgNotification = formatAPIObjectOutput(JSON.parse(line))
if (messageObject.hasOwnProperty('error')) {
throw new Error(messageObject.error)
} else if (
// fire onMessage if it was from a different sender or at least a different device
// from this sender. Bots can filter out their own messages from other devices.
(options && options.showLocal) ||
(this.username &&
this.devicename &&
(messageObject.msg.sender.username !== this.username.toLowerCase() || messageObject.msg.sender.deviceName !== this.devicename))
) {
onMessage(messageObject.msg)
}
} catch (error) {
if (onError) {
onError(error)
}
}
}
lineReaderStdout.on('line', onLine)
}
}
export default Chat