-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
113 lines (94 loc) · 2.58 KB
/
main.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
package main
import (
"fmt"
"github.com/slack-go/slack"
"io/ioutil"
"log"
"os"
"strconv"
"strings"
"time"
)
var (
token = os.Getenv("SLACK_BOT_TOKEN")
channelName = os.Getenv("SLACK_CHANNEL_NAME")
counterFile = "counter.txt"
)
func main() {
api := slack.New(token)
counter, lastUpdated, err := readCounterFromFile(counterFile)
if err != nil {
log.Fatalf("Error reading counter file: %v", err)
}
now := time.Now()
if !isSameDay(now, lastUpdated) {
counter++
err = writeCounterToFile(counterFile, counter, now)
if err != nil {
log.Fatalf("Error writing counter file: %v", err)
}
}
channelID, err := getChannelID(api, channelName)
if err != nil {
log.Fatalf("Error getting channel ID: %v", err)
}
_, timestamp, err := api.PostMessage(channelID, slack.MsgOptionText(fmt.Sprintf("BURPEE TIME! Drop and give me #%d", counter), false))
if err != nil {
log.Fatalf("Error posting message: %v", err)
}
fmt.Printf("Message successfully sent to channel %s at %s", channelName, timestamp)
}
func readCounterFromFile(filename string) (int, time.Time, error) {
data, err := ioutil.ReadFile(filename)
if err != nil {
if err != nil {
if os.IsNotExist(err) {
counter := 0
lastUpdated := time.Now()
err = writeCounterToFile(filename, counter, lastUpdated)
if err != nil {
return 0, time.Time{}, err
}
return counter, lastUpdated, nil
}
return 0, time.Time{}, err
}
}
lines := strings.Split(strings.TrimSpace(string(data)), "\n")
counter, err := strconv.Atoi(lines[0])
if err != nil {
return 0, time.Time{}, err
}
lastUpdated, err := time.Parse(time.RFC3339, lines[1])
if err != nil {
return 0, time.Time{}, err
}
return counter, lastUpdated, nil
}
func writeCounterToFile(filename string, counter int, lastUpdated time.Time) error {
data := fmt.Sprintf("%d\n%s", counter, lastUpdated.Format(time.RFC3339))
return ioutil.WriteFile(filename, []byte(data), 0644)
}
func getChannelID(api *slack.Client, channelName string) (string, error) {
channels, nextCursor, err := api.GetConversations(&slack.GetConversationsParameters{
Types: []string{"public_channel"},
ExcludeArchived: true,
Limit: 1000,
})
fmt.Printf("%s\n", nextCursor)
if err != nil {
return "", err
}
for _, channel := range channels {
fmt.Printf("Channel: %s\n", channel.Name)
if channel.Name == channelName {
return channel.ID, nil
}
}
return "", fmt.Errorf("Channel %s not found", channelName)
}
func isSameDay(t1, t2 time.Time) bool {
y1, m1, d1 := t1.Date()
y2, m2, d2 := t2.Date()
return y1 == y2 && m1 == m2 && d1 == d2
}