forked from brettbuddin/victor
/
campfire_adapter.go
115 lines (88 loc) · 2.35 KB
/
campfire_adapter.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
106
107
108
109
110
111
112
113
114
115
package victor
import (
"github.com/brettbuddin/victor/campfire"
"strings"
"strconv"
"log"
)
type Campfire struct {
*Robot
client *campfire.Client
}
func (self *Campfire) Run() {
log.Print("Starting up...")
rooms := self.RoomList()
client := self.Client()
channel := make(chan *campfire.Message)
for i := range rooms {
details, err := client.Room(rooms[i]).Show()
if err != nil {
continue
}
log.Print("Fetched room info.")
for _, user := range details.Users {
self.RememberUser(&User{Id: user.Id, Name: user.Name})
log.Print("Remembering: " + user.Name)
}
room := client.Room(rooms[i])
err = room.Join()
if err != nil {
continue
}
log.Print("Joined room.")
room.Stream(channel)
log.Print("Listening...")
}
for {
in := <-channel
if in.Type == "TextMessage" {
msg := &TextMessage{
Id: in.Id,
Body: in.Body,
CreatedAt: in.CreatedAt,
Send: self.Send(in.RoomId),
Reply: self.Reply(in.RoomId, in.UserId),
}
self.Receive(msg)
}
}
}
func (self *Campfire) Send(roomId int) func(string) {
room := self.Client().Room(roomId)
return func(text string) {
room.Say(text)
}
}
func (self *Campfire) Reply(roomId int, userId int) func(string) {
room := self.Client().Room(roomId)
user := self.UserForId(userId)
prefix := ""
if user != nil {
prefix = user.Name + ": "
}
return func(text string) {
room.Say(prefix + text)
}
}
func (self *Campfire) Client() *campfire.Client {
if self.client == nil {
client := campfire.NewClient(
self.Robot.options["account"],
self.Robot.options["token"],
)
self.client = client
}
return self.client
}
func (self *Campfire) RoomList() []int {
if _, exists := self.Robot.options["rooms"]; !exists {
panic("No rooms defined.")
}
roomIdStrings := strings.Split(self.Robot.options["rooms"], ",")
rooms := make([]int, 0)
for _, id := range roomIdStrings {
j, _ := strconv.Atoi(id)
rooms = append(rooms, j)
}
return rooms
}