-
Notifications
You must be signed in to change notification settings - Fork 927
/
cplogs.go
63 lines (53 loc) · 1.65 KB
/
cplogs.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
package common
import (
"encoding/json"
"fmt"
"github.com/jonas747/discordgo"
"github.com/mediocregopher/radix"
log "github.com/sirupsen/logrus"
"time"
)
type CPLogEntry struct {
Timestamp int64 `json:"ts"`
Action string `json:"action"`
TimestampString string `json:"-"`
}
func AddCPLogEntry(user *discordgo.User, guild int64, args ...interface{}) {
action := fmt.Sprintf("(UserID: %d) %s#%s: %s", user.ID, user.Username, user.Discriminator, fmt.Sprint(args...))
now := time.Now()
entry := &CPLogEntry{
Timestamp: now.Unix(),
Action: action,
}
serialized, err := json.Marshal(entry)
if err != nil {
log.WithError(err).Error("Failed marshalling cp log entry")
return
}
key := "cp_logs:" + discordgo.StrID(guild)
err = RedisPool.Do(radix.Cmd(nil, "LPUSH", key, string(serialized)))
RedisPool.Do(radix.Cmd(nil, "LTRIM", key, "0", "100"))
if err != nil {
log.WithError(err).WithField("guild", guild).Error("Failed updating cp logs")
}
}
func GetCPLogEntries(guild int64) ([]*CPLogEntry, error) {
var entriesRaw [][]byte
err := RedisPool.Do(radix.Cmd(&entriesRaw, "LRANGE", "cp_logs:"+discordgo.StrID(guild), "0", "-1"))
if err != nil {
return nil, err
}
result := make([]*CPLogEntry, len(entriesRaw))
for k, entryRaw := range entriesRaw {
var decoded *CPLogEntry
err = json.Unmarshal(entryRaw, &decoded)
if err != nil {
result[k] = &CPLogEntry{Action: "Failed decoding"}
log.WithError(err).WithField("guild", guild).WithField("cp_log_enry", k).Error("Failed decoding cp log entry")
} else {
decoded.TimestampString = time.Unix(decoded.Timestamp, 0).Format(time.Stamp)
result[k] = decoded
}
}
return result, nil
}