summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/keybase/go-keybase-chat-bot/kbchat/chat.go
blob: 3eca02cd5a67556fda92b2421ea062c6a628d903 (plain) (blame)
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
package kbchat

import (
	"encoding/json"
	"errors"
	"fmt"

	"github.com/keybase/go-keybase-chat-bot/kbchat/types/chat1"
	"github.com/keybase/go-keybase-chat-bot/kbchat/types/keybase1"
)

type Thread struct {
	Result chat1.Thread `json:"result"`
	Error  *Error       `json:"error,omitempty"`
}

type Inbox struct {
	Result Result `json:"result"`
	Error  *Error `json:"error,omitempty"`
}

type sendMessageBody struct {
	Body string
}

type sendMessageOptions struct {
	Channel          chat1.ChatChannel `json:"channel,omitempty"`
	ConversationID   chat1.ConvIDStr   `json:"conversation_id,omitempty"`
	Message          sendMessageBody   `json:",omitempty"`
	Filename         string            `json:"filename,omitempty"`
	Title            string            `json:"title,omitempty"`
	MsgID            chat1.MessageID   `json:"message_id,omitempty"`
	ConfirmLumenSend bool              `json:"confirm_lumen_send"`
	ReplyTo          *chat1.MessageID  `json:"reply_to,omitempty"`
}

type sendMessageParams struct {
	Options sendMessageOptions
}

type sendMessageArg struct {
	Method string
	Params sendMessageParams
}

func newSendArg(options sendMessageOptions) sendMessageArg {
	return sendMessageArg{
		Method: "send",
		Params: sendMessageParams{
			Options: options,
		},
	}
}

// GetConversations reads all conversations from the current user's inbox.
func (a *API) GetConversations(unreadOnly bool) ([]chat1.ConvSummary, error) {
	apiInput := fmt.Sprintf(`{"method":"list", "params": { "options": { "unread_only": %v}}}`, unreadOnly)
	output, err := a.doFetch(apiInput)
	if err != nil {
		return nil, err
	}

	var inbox Inbox
	if err := json.Unmarshal(output, &inbox); err != nil {
		return nil, err
	} else if inbox.Error != nil {
		return nil, errors.New(inbox.Error.Message)
	}
	return inbox.Result.Convs, nil
}

func (a *API) GetConversation(convID chat1.ConvIDStr) (res chat1.ConvSummary, err error) {
	apiInput := fmt.Sprintf(`{"method":"list", "params": { "options": { "conversation_id": "%s"}}}`, convID)
	output, err := a.doFetch(apiInput)
	if err != nil {
		return res, err
	}

	var inbox Inbox
	if err := json.Unmarshal(output, &inbox); err != nil {
		return res, err
	} else if inbox.Error != nil {
		return res, errors.New(inbox.Error.Message)
	} else if len(inbox.Result.Convs) == 0 {
		return res, errors.New("conversation not found")
	}
	return inbox.Result.Convs[0], nil
}

// GetTextMessages fetches all text messages from a given channel. Optionally can filter
// ont unread status.
func (a *API) GetTextMessages(channel chat1.ChatChannel, unreadOnly bool) ([]chat1.MsgSummary, error) {
	channelBytes, err := json.Marshal(channel)
	if err != nil {
		return nil, err
	}
	apiInput := fmt.Sprintf(`{"method": "read", "params": {"options": {"channel": %s}}}`, string(channelBytes))
	output, err := a.doFetch(apiInput)
	if err != nil {
		return nil, err
	}

	var thread Thread

	if err := json.Unmarshal(output, &thread); err != nil {
		return nil, fmt.Errorf("unable to decode thread: %v", err)
	} else if thread.Error != nil {
		return nil, errors.New(thread.Error.Message)
	}

	var res []chat1.MsgSummary
	for _, msg := range thread.Result.Messages {
		if msg.Msg.Content.TypeName == "text" {
			res = append(res, *msg.Msg)
		}
	}

	return res, nil
}

func (a *API) SendMessage(channel chat1.ChatChannel, body string, args ...interface{}) (SendResponse, error) {
	arg := newSendArg(sendMessageOptions{
		Channel: channel,
		Message: sendMessageBody{
			Body: fmt.Sprintf(body, args...),
		},
	})
	return a.doSend(arg)
}

func (a *API) Broadcast(body string, args ...interface{}) (SendResponse, error) {
	return a.SendMessage(chat1.ChatChannel{
		Name:   a.GetUsername(),
		Public: true,
	}, fmt.Sprintf(body, args...))
}

func (a *API) SendMessageByConvID(convID chat1.ConvIDStr, body string, args ...interface{}) (SendResponse, error) {
	arg := newSendArg(sendMessageOptions{
		ConversationID: convID,
		Message: sendMessageBody{
			Body: fmt.Sprintf(body, args...),
		},
	})
	return a.doSend(arg)
}

// SendMessageByTlfName sends a message on the given TLF name
func (a *API) SendMessageByTlfName(tlfName string, body string, args ...interface{}) (SendResponse, error) {
	arg := newSendArg(sendMessageOptions{
		Channel: chat1.ChatChannel{
			Name: tlfName,
		},
		Message: sendMessageBody{
			Body: fmt.Sprintf(body, args...),
		},
	})
	return a.doSend(arg)
}

func (a *API) SendMessageByTeamName(teamName string, inChannel *string, body string, args ...interface{}) (SendResponse, error) {
	channel := "general"
	if inChannel != nil {
		channel = *inChannel
	}
	arg := newSendArg(sendMessageOptions{
		Channel: chat1.ChatChannel{
			MembersType: "team",
			Name:        teamName,
			TopicName:   channel,
		},
		Message: sendMessageBody{
			Body: fmt.Sprintf(body, args...),
		},
	})
	return a.doSend(arg)
}

func (a *API) SendReply(channel chat1.ChatChannel, replyTo *chat1.MessageID, body string, args ...interface{}) (SendResponse, error) {
	arg := newSendArg(sendMessageOptions{
		Channel: channel,
		Message: sendMessageBody{
			Body: fmt.Sprintf(body, args...),
		},
		ReplyTo: replyTo,
	})
	return a.doSend(arg)
}

func (a *API) SendReplyByConvID(convID chat1.ConvIDStr, replyTo *chat1.MessageID, body string, args ...interface{}) (SendResponse, error) {
	arg := newSendArg(sendMessageOptions{
		ConversationID: convID,
		Message: sendMessageBody{
			Body: fmt.Sprintf(body, args...),
		},
		ReplyTo: replyTo,
	})
	return a.doSend(arg)
}

func (a *API) SendReplyByTlfName(tlfName string, replyTo *chat1.MessageID, body string, args ...interface{}) (SendResponse, error) {
	arg := newSendArg(sendMessageOptions{
		Channel: chat1.ChatChannel{
			Name: tlfName,
		},
		Message: sendMessageBody{
			Body: fmt.Sprintf(body, args...),
		},
		ReplyTo: replyTo,
	})
	return a.doSend(arg)
}

func (a *API) SendAttachmentByTeam(teamName string, inChannel *string, filename string, title string) (SendResponse, error) {
	channel := "general"
	if inChannel != nil {
		channel = *inChannel
	}
	arg := sendMessageArg{
		Method: "attach",
		Params: sendMessageParams{
			Options: sendMessageOptions{
				Channel: chat1.ChatChannel{
					MembersType: "team",
					Name:        teamName,
					TopicName:   channel,
				},
				Filename: filename,
				Title:    title,
			},
		},
	}
	return a.doSend(arg)
}

func (a *API) SendAttachmentByConvID(convID chat1.ConvIDStr, filename string, title string) (SendResponse, error) {
	arg := sendMessageArg{
		Method: "attach",
		Params: sendMessageParams{
			Options: sendMessageOptions{
				ConversationID: convID,
				Filename:       filename,
				Title:          title,
			},
		},
	}
	return a.doSend(arg)
}

////////////////////////////////////////////////////////
// React to chat ///////////////////////////////////////
////////////////////////////////////////////////////////

type reactionOptions struct {
	ConversationID chat1.ConvIDStr `json:"conversation_id"`
	Message        sendMessageBody
	MsgID          chat1.MessageID   `json:"message_id"`
	Channel        chat1.ChatChannel `json:"channel"`
}

type reactionParams struct {
	Options reactionOptions
}

type reactionArg struct {
	Method string
	Params reactionParams
}

func newReactionArg(options reactionOptions) reactionArg {
	return reactionArg{
		Method: "reaction",
		Params: reactionParams{Options: options},
	}
}

func (a *API) ReactByChannel(channel chat1.ChatChannel, msgID chat1.MessageID, reaction string) (SendResponse, error) {
	arg := newReactionArg(reactionOptions{
		Message: sendMessageBody{Body: reaction},
		MsgID:   msgID,
		Channel: channel,
	})
	return a.doSend(arg)
}

func (a *API) ReactByConvID(convID chat1.ConvIDStr, msgID chat1.MessageID, reaction string) (SendResponse, error) {
	arg := newReactionArg(reactionOptions{
		Message:        sendMessageBody{Body: reaction},
		MsgID:          msgID,
		ConversationID: convID,
	})
	return a.doSend(arg)
}

func (a *API) EditByConvID(convID chat1.ConvIDStr, msgID chat1.MessageID, text string) (SendResponse, error) {
	arg := reactionArg{
		Method: "edit",
		Params: reactionParams{Options: reactionOptions{
			Message:        sendMessageBody{Body: text},
			MsgID:          msgID,
			ConversationID: convID,
		}},
	}
	return a.doSend(arg)
}

////////////////////////////////////////////////////////
// Manage channels /////////////////////////////////////
////////////////////////////////////////////////////////

type ChannelsList struct {
	Result Result `json:"result"`
	Error  *Error `json:"error,omitempty"`
}

type JoinChannel struct {
	Error  *Error         `json:"error,omitempty"`
	Result chat1.EmptyRes `json:"result"`
}

type LeaveChannel struct {
	Error  *Error         `json:"error,omitempty"`
	Result chat1.EmptyRes `json:"result"`
}

func (a *API) ListChannels(teamName string) ([]string, error) {
	apiInput := fmt.Sprintf(`{"method": "listconvsonname", "params": {"options": {"topic_type": "CHAT", "members_type": "team", "name": "%s"}}}`, teamName)
	output, err := a.doFetch(apiInput)
	if err != nil {
		return nil, err
	}

	var channelsList ChannelsList
	if err := json.Unmarshal(output, &channelsList); err != nil {
		return nil, err
	} else if channelsList.Error != nil {
		return nil, errors.New(channelsList.Error.Message)
	}

	var channels []string
	for _, conv := range channelsList.Result.Convs {
		channels = append(channels, conv.Channel.TopicName)
	}
	return channels, nil
}

func (a *API) JoinChannel(teamName string, channelName string) (chat1.EmptyRes, error) {
	empty := chat1.EmptyRes{}

	apiInput := fmt.Sprintf(`{"method": "join", "params": {"options": {"channel": {"name": "%s", "members_type": "team", "topic_name": "%s"}}}}`, teamName, channelName)
	output, err := a.doFetch(apiInput)
	if err != nil {
		return empty, err
	}

	joinChannel := JoinChannel{}
	err = json.Unmarshal(output, &joinChannel)
	if err != nil {
		return empty, fmt.Errorf("failed to parse output from keybase team api: %v", err)
	} else if joinChannel.Error != nil {
		return empty, errors.New(joinChannel.Error.Message)
	}

	return joinChannel.Result, nil
}

func (a *API) LeaveChannel(teamName string, channelName string) (chat1.EmptyRes, error) {
	empty := chat1.EmptyRes{}

	apiInput := fmt.Sprintf(`{"method": "leave", "params": {"options": {"channel": {"name": "%s", "members_type": "team", "topic_name": "%s"}}}}`, teamName, channelName)
	output, err := a.doFetch(apiInput)
	if err != nil {
		return empty, err
	}

	leaveChannel := LeaveChannel{}
	err = json.Unmarshal(output, &leaveChannel)
	if err != nil {
		return empty, fmt.Errorf("failed to parse output from keybase team api: %v", err)
	} else if leaveChannel.Error != nil {
		return empty, errors.New(leaveChannel.Error.Message)
	}

	return leaveChannel.Result, nil
}

////////////////////////////////////////////////////////
// Send lumens in chat /////////////////////////////////
////////////////////////////////////////////////////////

func (a *API) InChatSend(channel chat1.ChatChannel, body string, args ...interface{}) (SendResponse, error) {
	arg := newSendArg(sendMessageOptions{
		Channel: channel,
		Message: sendMessageBody{
			Body: fmt.Sprintf(body, args...),
		},
		ConfirmLumenSend: true,
	})
	return a.doSend(arg)
}

func (a *API) InChatSendByConvID(convID chat1.ConvIDStr, body string, args ...interface{}) (SendResponse, error) {
	arg := newSendArg(sendMessageOptions{
		ConversationID: convID,
		Message: sendMessageBody{
			Body: fmt.Sprintf(body, args...),
		},
		ConfirmLumenSend: true,
	})
	return a.doSend(arg)
}

func (a *API) InChatSendByTlfName(tlfName string, body string, args ...interface{}) (SendResponse, error) {
	arg := newSendArg(sendMessageOptions{
		Channel: chat1.ChatChannel{
			Name: tlfName,
		},
		Message: sendMessageBody{
			Body: fmt.Sprintf(body, args...),
		},
		ConfirmLumenSend: true,
	})
	return a.doSend(arg)
}

////////////////////////////////////////////////////////
// Misc commands ///////////////////////////////////////
////////////////////////////////////////////////////////

type Advertisement struct {
	Alias          string `json:"alias,omitempty"`
	Advertisements []chat1.AdvertiseCommandAPIParam
}

type ListCommandsResponse struct {
	Result struct {
		Commands []chat1.UserBotCommandOutput `json:"commands"`
	} `json:"result"`
	Error *Error `json:"error,omitempty"`
}

type advertiseCmdsParams struct {
	Options Advertisement
}

type advertiseCmdsMsgArg struct {
	Method string
	Params advertiseCmdsParams
}

func newAdvertiseCmdsMsgArg(ad Advertisement) advertiseCmdsMsgArg {
	return advertiseCmdsMsgArg{
		Method: "advertisecommands",
		Params: advertiseCmdsParams{
			Options: ad,
		},
	}
}

func (a *API) AdvertiseCommands(ad Advertisement) (SendResponse, error) {
	return a.doSend(newAdvertiseCmdsMsgArg(ad))
}

func (a *API) ClearCommands() error {
	arg := struct {
		Method string
	}{
		Method: "clearcommands",
	}
	_, err := a.doSend(arg)
	return err
}

type listCmdsOptions struct {
	Channel        chat1.ChatChannel `json:"channel,omitempty"`
	ConversationID chat1.ConvIDStr   `json:"conversation_id,omitempty"`
}

type listCmdsParams struct {
	Options listCmdsOptions
}

type listCmdsArg struct {
	Method string
	Params listCmdsParams
}

func newListCmdsArg(options listCmdsOptions) listCmdsArg {
	return listCmdsArg{
		Method: "listcommands",
		Params: listCmdsParams{
			Options: options,
		},
	}
}

func (a *API) ListCommands(channel chat1.ChatChannel) ([]chat1.UserBotCommandOutput, error) {
	arg := newListCmdsArg(listCmdsOptions{
		Channel: channel,
	})
	return a.listCommands(arg)
}

func (a *API) ListCommandsByConvID(convID chat1.ConvIDStr) ([]chat1.UserBotCommandOutput, error) {
	arg := newListCmdsArg(listCmdsOptions{
		ConversationID: convID,
	})
	return a.listCommands(arg)
}

func (a *API) listCommands(arg listCmdsArg) ([]chat1.UserBotCommandOutput, error) {
	bArg, err := json.Marshal(arg)
	if err != nil {
		return nil, err
	}
	output, err := a.doFetch(string(bArg))
	if err != nil {
		return nil, err
	}
	var res ListCommandsResponse
	if err := json.Unmarshal(output, &res); err != nil {
		return nil, err
	} else if res.Error != nil {
		return nil, errors.New(res.Error.Message)
	}
	return res.Result.Commands, nil
}

type listMembersOptions struct {
	Channel        chat1.ChatChannel `json:"channel,omitempty"`
	ConversationID chat1.ConvIDStr   `json:"conversation_id,omitempty"`
}

type listMembersParams struct {
	Options listMembersOptions
}

type listMembersArg struct {
	Method string
	Params listMembersParams
}

func newListMembersArg(options listMembersOptions) listMembersArg {
	return listMembersArg{
		Method: "listmembers",
		Params: listMembersParams{
			Options: options,
		},
	}
}

func (a *API) ListMembers(channel chat1.ChatChannel) (keybase1.TeamMembersDetails, error) {
	arg := newListMembersArg(listMembersOptions{
		Channel: channel,
	})
	return a.listMembers(arg)
}

func (a *API) ListMembersByConvID(conversationID chat1.ConvIDStr) (keybase1.TeamMembersDetails, error) {
	arg := newListMembersArg(listMembersOptions{
		ConversationID: conversationID,
	})
	return a.listMembers(arg)
}

func (a *API) listMembers(arg listMembersArg) (res keybase1.TeamMembersDetails, err error) {
	bArg, err := json.Marshal(arg)
	if err != nil {
		return res, err
	}
	output, err := a.doFetch(string(bArg))
	if err != nil {
		return res, err
	}
	members := ListTeamMembers{}
	err = json.Unmarshal(output, &members)
	if err != nil {
		return res, UnmarshalError{err}
	}
	if members.Error.Message != "" {
		return res, members.Error
	}
	return members.Result.Members, nil
}

type GetMessagesResult struct {
	Result struct {
		Messages []chat1.Message `json:"messages"`
	} `json:"result"`
	Error *Error `json:"error,omitempty"`
}

type getMessagesOptions struct {
	Channel        chat1.ChatChannel `json:"channel,omitempty"`
	ConversationID chat1.ConvIDStr   `json:"conversation_id,omitempty"`
	MessageIDs     []chat1.MessageID `json:"message_ids,omitempty"`
}

type getMessagesParams struct {
	Options getMessagesOptions
}

type getMessagesArg struct {
	Method string
	Params getMessagesParams
}

func newGetMessagesArg(options getMessagesOptions) getMessagesArg {
	return getMessagesArg{
		Method: "get",
		Params: getMessagesParams{
			Options: options,
		},
	}
}

func (a *API) GetMessages(channel chat1.ChatChannel, msgIDs []chat1.MessageID) ([]chat1.Message, error) {
	arg := newGetMessagesArg(getMessagesOptions{
		Channel:    channel,
		MessageIDs: msgIDs,
	})
	return a.getMessages(arg)
}

func (a *API) GetMessagesByConvID(conversationID chat1.ConvIDStr, msgIDs []chat1.MessageID) ([]chat1.Message, error) {
	arg := newGetMessagesArg(getMessagesOptions{
		ConversationID: conversationID,
		MessageIDs:     msgIDs,
	})
	return a.getMessages(arg)
}

func (a *API) getMessages(arg getMessagesArg) ([]chat1.Message, error) {
	bArg, err := json.Marshal(arg)
	if err != nil {
		return nil, err
	}
	output, err := a.doFetch(string(bArg))
	if err != nil {
		return nil, err
	}
	var res GetMessagesResult
	err = json.Unmarshal(output, &res)
	if err != nil {
		return nil, UnmarshalError{err}
	}
	if res.Error != nil {
		return nil, res.Error
	}
	return res.Result.Messages, nil
}