-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrealtime.go
105 lines (91 loc) · 2.19 KB
/
realtime.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
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
package guac
import (
"encoding/json"
"sync/atomic"
"github.com/doozr/guac/realtime"
"github.com/doozr/jot"
)
var counter uint64
// nextID returns the next message ID for this run.
func nextID() uint64 {
return atomic.AddUint64(&counter, 1)
}
// realTimeClient is the default implementation of RealTimeClient
type realTimeClient struct {
WebClient
connection realtime.Connection
}
// ID of the bot
func (c *realTimeClient) ID() string {
return c.connection.ID()
}
// Name of the bot
func (c *realTimeClient) Name() string {
return c.connection.Name()
}
func (c *realTimeClient) RealTime() (RealTimeClient, error) {
return c, nil
}
// Close terminates the connection.
func (c *realTimeClient) Close() {
c.connection.Close()
}
// PostMessage sends a chat message to the given channel.
//
// The message is posted as the bot itself, and does not try to take on the
// identity of a user. Use the API formatting standard.
func (c *realTimeClient) PostMessage(channel, text string) (err error) {
id := nextID()
m := MessageEvent{
Type: "message",
ID: id,
Channel: channel,
User: "",
Text: text,
}
payload, err := json.Marshal(m)
if err == nil {
err = c.connection.Send(payload)
}
return
}
// Ping sends a ping request.
//
// Sends a bare ping with no additional information.
func (c *realTimeClient) Ping() (err error) {
id := nextID()
m := PingPongEvent{
Type: "ping",
ID: id,
}
payload, err := json.Marshal(m)
if err == nil {
err = c.connection.Send(payload)
}
return
}
// Receive an event or an error.
//
// Blocks until an known event type arrives or an error occurs.
func (c *realTimeClient) Receive() (event interface{}, err error) {
var raw []byte
for {
// Bail out on error immediately
raw, err = c.connection.Receive()
if err != nil {
jot.Print("realtimeclient.Receive error from realtime.Receive: ", err)
return
}
jot.Print("realtime.Receive raw ", string(raw))
// Only return if there is something worth returning, or an error
event, err = convertEvent(raw)
if err != nil {
jot.Print("realtimeclient.Receive error converting event: ", err)
return
}
if event != nil {
jot.Print("realtime.Receive event ", event)
return
}
}
}