-
Notifications
You must be signed in to change notification settings - Fork 27
/
updateable.go
77 lines (60 loc) · 1.75 KB
/
updateable.go
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
package slick
import (
"fmt"
"sync"
)
// UpdateableReply is a Reply that the bot sent, and that it is able
// to update after the fact.
type UpdateableReply struct {
reply *Reply
lock sync.Mutex
msgTimestamp string // TS from Slack, uniquely identifying our reply.
newMessage string // newMessage holds the new message we want to send, and will be dispatched upon reception of the Ack message if set.
updateMode updateMode // where/how to add/replace the message
}
func (u *UpdateableReply) dispatch() {
u.lock.Lock()
defer u.lock.Unlock()
if u.msgTimestamp == "" {
return
}
if u.newMessage != "" {
u.reply.bot.Slack.UpdateMessage(u.reply.OutgoingMessage.Channel, u.msgTimestamp, u.newFormattedMessage())
u.newMessage = ""
}
}
func (u *UpdateableReply) UpdateSuffix(format string, v ...interface{}) {
u.updateWithMode(updateSuffix, format, v...)
}
func (u *UpdateableReply) UpdatePrefix(format string, v ...interface{}) {
u.updateWithMode(updatePrefix, format, v...)
}
func (u *UpdateableReply) Update(format string, v ...interface{}) {
u.updateWithMode(updateWhole, format, v...)
}
func (u*UpdateableReply) newFormattedMessage() string {
prevMessage := u.reply.OutgoingMessage.Text
switch u.updateMode {
case updateSuffix:
return fmt.Sprintf("%s%s", prevMessage, u.newMessage)
case updatePrefix:
return fmt.Sprintf("%s%s", u.newMessage, prevMessage)
case updateWhole:
return u.newMessage
default:
panic("there's no other modes !")
}
}
func (u *UpdateableReply) updateWithMode(mode updateMode, format string, v ...interface{}) {
u.lock.Lock()
defer u.lock.Unlock()
u.newMessage = fmt.Sprintf(format, v...)
u.updateMode = mode
go u.dispatch()
}
type updateMode int
const (
updateSuffix updateMode = iota
updatePrefix
updateWhole
)