forked from knative/pkg
/
message_read.go
95 lines (80 loc) · 2.58 KB
/
message_read.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
/*
Copyright 2019 The Knative Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// message_read.go includes functions to read messages from Slack.
package slackutil
import (
"encoding/json"
"fmt"
"html"
"io/ioutil"
"net/url"
"strconv"
"strings"
"time"
)
const conversationHistoryURL = "https://slack.com/api/conversations.history"
// ReadOperations defines the read operations that can be done to Slack
type ReadOperations interface {
MessageHistory(channel string, startTime time.Time) ([]string, error)
}
// readClient contains Slack bot related information to perform read operations
type readClient struct {
userName string
tokenStr string
}
// NewReadClient reads token file and stores it for later authentication
func NewReadClient(userName, tokenPath string) (ReadOperations, error) {
b, err := ioutil.ReadFile(tokenPath)
if err != nil {
return nil, err
}
return &readClient{
userName: userName,
tokenStr: strings.TrimSpace(string(b)),
}, nil
}
// MessageHistory returns the list of messages sent by the user in the given
// channel since the given startTime.
func (c *readClient) MessageHistory(channel string, startTime time.Time) ([]string, error) {
u, _ := url.Parse(conversationHistoryURL)
q := u.Query()
q.Add("token", c.tokenStr)
q.Add("channel", channel)
q.Add("oldest", strconv.FormatInt(startTime.Unix(), 10))
u.RawQuery = q.Encode()
content, err := get(u.String())
if err != nil {
return nil, err
}
// response code could also be 200 if channel doesn't exist, parse response body to find out
type m struct {
Text string `json:"text"`
UserName string `json:"username"`
}
var r struct {
OK bool `json:"ok"`
Messages []m `json:"messages"`
}
if err = json.Unmarshal(content, &r); nil != err || !r.OK {
return nil, fmt.Errorf("response not ok '%s'", string(content))
}
res := make([]string, 0)
for _, message := range r.Messages {
if message.UserName == c.userName {
// the message text queried from Slack will be escaped,
// so we unescape it to restore to the original text
res = append(res, html.UnescapeString(message.Text))
}
}
return res, nil
}