-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
204 lines (174 loc) · 5.18 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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
package main
import (
"flag"
"fmt"
"os"
"regexp"
"strings"
"time"
"github.com/golang/glog"
"github.com/golang/protobuf/jsonpb"
bdaybot "github.com/j-fuentes/bdaybot-slack/api"
"github.com/j-fuentes/bdaybot-slack/internal/calendar/googlesheet"
"github.com/j-fuentes/bdaybot-slack/internal/oauth2"
"github.com/j-fuentes/bdaybot-slack/internal/slack"
)
var configFile string
var userTokenFile string
var auth bool
// SheetIDFromURL is a regexp to extract Google sheetID from url
var SheetIDFromURL = regexp.MustCompile(`https://docs.google.com/spreadsheets/d/(?P<id>.*)/.*`)
func init() {
flag.StringVar(&configFile, "config", "./config.json", "Path to the config file.")
flag.StringVar(&userTokenFile, "userTokenFile", "./token.json", "Path to a file with user oauth2 token.")
flag.BoolVar(&auth, "auth", false, "Triggers the auth workflow.")
flag.Parse()
}
func main() {
configReader, err := os.Open(configFile)
if err != nil {
glog.Fatalf("%+v", err)
}
var config bdaybot.Config
jsonpb.Unmarshal(configReader, &config)
adminWebhookURL := config.GetSlack().GetAdminWebhookUrl()
if auth {
glog.Info("Starting auth workflow...")
token, err := oauth2.RetrieveTokenInteractively(googlesheet.GenOauthConfig(
config.GetOauth2().GetClientId(),
config.GetOauth2().GetClientSecret(),
))
if err != nil {
glog.Fatalf("%v", err)
}
err = oauth2.WriteTokenToFile(token, userTokenFile)
if err != nil {
glog.Fatalf("%v", err)
}
os.Exit(0)
}
var slackAdminClient *slack.Client
if adminWebhookURL != "" {
glog.Infof("Found slack webhook for admin, events will be reported to %s\n", adminWebhookURL)
slackAdminClient = slack.NewClient(adminWebhookURL)
} else {
glog.Infof("Did not found a slack webhook for admin\n")
}
reader, err := genGooglesheetReader(config)
if err != nil {
sendErrorToSlack(
slackAdminClient,
"Cannot connect to Google Spreadsheets",
err,
)
glog.Fatalf("%+v", err)
}
spreadsheetURL := config.GetCalendar().GetGoogleSheet().GetUrl()
glog.Infof("Reading bdays from %s\n", spreadsheetURL)
bdays, err := reader.GetBdays()
if err != nil {
sendErrorToSlack(
slackAdminClient,
fmt.Sprintf("Error while reading data from spreadsheet (%s)", spreadsheetURL),
err,
)
glog.Fatalf("%+v", err)
}
glog.Infof("%d names were loaded.\n", len(bdays))
webhookURL := config.GetSlack().GetWebhookUrl()
prefix := config.GetSlack().GetSalutePrefix()
suffix := config.GetSlack().GetSaluteSuffix()
_, month, day := time.Now().Date()
names := []string{}
for _, bday := range bdays {
if bday.GetDate().GetMonth() == int32(month) &&
bday.GetDate().GetDay() == int32(day) {
glog.Infof("It is @%s bday!\n", bday.GetUserId())
names = append(names, bday.GetUserId())
}
}
if numNames := len(names); numNames > 0 {
people := fmt.Sprintf("@%s", names[0])
if numNames > 1 {
people = fmt.Sprintf("@%s and @%s", strings.Join(names[:len(names)-1], ", "), names[len(names)-1])
}
glog.Infof("Sending salute to %s via Slack webhook %s\n", people, webhookURL)
sendInfoToSlack(
slackAdminClient,
fmt.Sprintf("Saying happy birthday to %s", people),
fmt.Sprintf("%d bdays were found in the spreadsheet (%s)", numNames, spreadsheetURL),
)
slackClient := slack.NewClient(webhookURL)
err := slackClient.SendMessage(fmt.Sprintf("%s %s %s", prefix, people, suffix))
if err != nil {
glog.Fatalf("%+v", err)
}
} else {
sendInfoToSlack(
slackAdminClient,
"Today is no one's birthday",
fmt.Sprintf("No birthdays found on the spreadsheet (%s)", spreadsheetURL),
)
glog.Info("Today is no one's birthday")
}
}
func genGooglesheetReader(config bdaybot.Config) (*googlesheet.Reader, error) {
oauthConfig := googlesheet.GenOauthConfig(config.GetOauth2().GetClientId(), config.GetOauth2().GetClientSecret())
sheetID, err := getSheetID(config.GetCalendar().GetGoogleSheet())
if err != nil {
return nil, fmt.Errorf("%+v", err)
}
token, err := oauth2.ReadTokenFromFile(userTokenFile)
if err != nil {
return nil, err
}
client := oauth2.GetHTTPClient(oauthConfig, token)
return googlesheet.NewReader(client, sheetID)
}
func getSheetID(sheet *bdaybot.GoogleSheet) (string, error) {
url := sheet.GetUrl()
match := SheetIDFromURL.FindStringSubmatch(url)
if len(match) != 2 {
return "", fmt.Errorf("Cannot get sheet ID from url %q", url)
}
return match[1], nil
}
func sendErrorToSlack(client *slack.Client, title string, err error) {
if client == nil {
return
}
err2 := client.Send(&slack.SlackRequestBody{
Text: "Error from bdaybot",
Parse: "full",
Attachments: []*slack.Attachment{
&slack.Attachment{
Color: "#e23434",
Pretext: "Something bad happened",
Title: title,
Text: fmt.Sprintf("```%+v```", err),
},
},
})
if err2 != nil {
glog.Infof("Cannot send information to slack: %+v", err)
}
}
func sendInfoToSlack(client *slack.Client, title string, msg string) {
if client == nil {
return
}
err := client.Send(&slack.SlackRequestBody{
Text: "Info from bdaybot",
Parse: "full",
Attachments: []*slack.Attachment{
&slack.Attachment{
Color: "#2159b2",
Title: title,
Text: msg,
},
},
})
if err != nil {
glog.Infof("Cannot send information to slack: %+v", err)
}
}