-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
326 lines (288 loc) · 8.23 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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package main
import (
"context"
"encoding/gob"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/mattn/go-mastodon"
)
// config
var (
userAgent = "kombu-erea-bot (repo https://github.com/plainbanana/kombu-erea-bot)"
mastodonServer = "https://mustardon.tokyo"
mastodonAppWebsite = "https://github.com/plainbanana/kombu-erea-bot"
// following conf should be set by environments
mastodonClientID = ""
mastodonClientSecret = ""
mastodonAppYourEmail = ""
mastodonAppYourPassword = ""
TootHourScanDuration time.Duration = 2
TootMinuteScanDuration time.Duration = 10
TootTotalScanDuration time.Duration = 6 // also used as api chaching interval
timezone = time.FixedZone("Asia/Tokyo", 9*60*60)
chacheFile = "api_chache.gob"
)
const (
splatoon2API = "https://spla2.yuu26.com"
tootTimeFormat = "2006-01-02 15:04 -07:00"
tootNoMention tootConfig = "nomention"
tootMention tootConfig = "mention"
)
type tootConfig string
type splatoonRespSchedules struct {
Result []struct {
Rule string `json:"rule"`
RuleEx struct {
Key string `json:"key"`
Name string `json:"name"`
Statink string `json:"statink"`
} `json:"rule_ex"`
Maps []string `json:"maps"`
MapsEx []struct {
ID int `json:"id"`
Name string `json:"name"`
Image string `json:"image"`
Statink string `json:"statink"`
} `json:"maps_ex"`
Start string `json:"start"`
StartUtc time.Time `json:"start_utc"`
StartT int `json:"start_t"`
End string `json:"end"`
EndUtc time.Time `json:"end_utc"`
EndT int `json:"end_t"`
Tooted struct {
First bool
Secound bool
}
} `json:"result"`
Timestamp time.Time
WhenTootTotal time.Time
}
func init() {
exe, err := os.Executable()
if !errors.Is(err, nil) {
log.Fatal(err)
}
if p := filepath.Dir(exe); !strings.Contains(p, "go-build") {
chacheFile = filepath.Join(p, chacheFile)
}
log.Println("chache file is", chacheFile)
if s := os.Getenv("USERAGENT"); s != "" {
userAgent = s
}
if s := os.Getenv("MASTODONSERVER"); s != "" {
mastodonServer = s
}
if s := os.Getenv("MASTODONAPPWEBSITE"); s != "" {
mastodonAppWebsite = s
}
if s := os.Getenv("TOOTHOUR"); s != "" {
t, err := strconv.Atoi(s)
if errors.Is(err, nil) {
tt := time.Duration(int64(t))
TootHourScanDuration = tt
}
}
if s := os.Getenv("TOOTMIN"); s != "" {
t, err := strconv.Atoi(s)
if errors.Is(err, nil) {
tt := time.Duration(int64(t))
TootMinuteScanDuration = tt
}
}
if s := os.Getenv("TOOTTOTAL"); s != "" {
t, err := strconv.Atoi(s)
if errors.Is(err, nil) {
tt := time.Duration(int64(t))
TootTotalScanDuration = tt
}
}
mastodonClientID = os.Getenv("MASTODONCLIENTID")
mastodonClientSecret = os.Getenv("MASTODONCLIENTSECRET")
if mastodonClientID == "" || mastodonClientSecret == "" {
app, err := mastodon.RegisterApp(context.Background(), &mastodon.AppConfig{
Server: mastodonServer,
ClientName: "kombu-erea-bot",
Scopes: "read write follow",
Website: mastodonAppWebsite,
})
if !errors.Is(err, nil) {
log.Fatal(err)
}
fmt.Printf("For example, you can use following environments\n")
fmt.Printf("env MASTODONCLIENTID=%s MASTODONCLIENTSECRET=%s\n", app.ClientID, app.ClientSecret)
log.Fatalln("OMG! luck of environments for your app: MASTODONCLIENTID or MASTODONCLIENTSECRET")
}
mastodonAppYourEmail = os.Getenv("MASTODONAPPYOUREMAIL")
mastodonAppYourPassword = os.Getenv("MASTODONAPPYOURPASSWORD")
if mastodonAppYourEmail == "" || mastodonAppYourPassword == "" {
log.Fatalln("OMG! luck of environments for your app: MASTODONAPPYOUREMAIL or MASTODONAPPYOURPASSWORD")
}
}
func main() {
const prefixTolalStatus string = "コンブエリア schedules\n"
var totalStatusText string = prefixTolalStatus
schedules := getSplatoon2GachiSchedules("gachi/schedule")
for i, v := range schedules.Result {
if v.Rule == "ガチエリア" && isContain(v.Maps, "コンブトラック") && v.EndUtc.After(time.Now()) {
if schedules.WhenTootTotal.Add(time.Hour * TootTotalScanDuration).Before(time.Now()) {
totalStatusText += "start at " +
v.StartUtc.In(timezone).Format(tootTimeFormat) + " \n"
}
if time.Now().Add(time.Minute*TootMinuteScanDuration).After(v.StartUtc) && !schedules.Result[i].Tooted.Secound {
statusText := "コンブエリア soon start at " +
v.StartUtc.In(timezone).Format(tootTimeFormat) + " \n"
toot(statusText, tootMention)
schedules.Result[i].Tooted.Secound = true
schedules.Result[i].Tooted.First = true
}
if time.Now().Add(time.Hour*TootHourScanDuration).After(v.StartUtc) && !schedules.Result[i].Tooted.First {
statusText := "コンブエリア start at " +
v.StartUtc.In(timezone).Format(tootTimeFormat) + " \n"
toot(statusText, tootMention)
schedules.Result[i].Tooted.First = true
}
}
}
if totalStatusText != prefixTolalStatus {
toot(totalStatusText, tootNoMention)
schedules.WhenTootTotal = time.Now().In(timezone)
}
storeRespToFile(schedules)
}
func toot(text string, settings tootConfig) {
c := mastodon.NewClient(&mastodon.Config{
Server: mastodonServer,
ClientID: mastodonClientID,
ClientSecret: mastodonClientSecret,
})
err := c.Authenticate(context.Background(), mastodonAppYourEmail, mastodonAppYourPassword)
if !errors.Is(err, nil) {
log.Fatal(err)
}
curUser, err := c.GetAccountCurrentUser(context.Background())
if !errors.Is(err, nil) {
log.Fatal(err)
}
curFollowers, err := c.GetAccountFollowers(context.Background(), curUser.ID, nil)
if !errors.Is(err, nil) {
log.Fatal(err)
}
switch settings {
case tootNoMention:
t := text
c.PostStatus(context.Background(), &mastodon.Toot{
Status: t,
Visibility: "unlisted",
})
log.Println("toot NoMention", t)
case tootMention:
for _, v := range strings.Split(parseAccountsToMention(curFollowers), " ") {
if v != "" {
t := v + " " + text
c.PostStatus(context.Background(), &mastodon.Toot{
Status: t,
Visibility: "unlisted",
})
log.Println("toot Mention", t)
}
}
default:
log.Fatalln("OMG! no settings")
}
}
func getSplatoon2GachiSchedules(uri string) splatoonRespSchedules {
if oldResp := restoreRespFromFile(); oldResp.Timestamp.Add(time.Hour*TootTotalScanDuration).After(time.Now()) && !oldResp.Timestamp.IsZero() {
log.Println("use old response fetched at", oldResp.Timestamp.In(timezone).Format(tootTimeFormat))
return oldResp
}
log.Println("call API")
resp := getFromSpla2API(uri)
resp.Timestamp = time.Now()
return resp
}
func getFromSpla2API(uri string) splatoonRespSchedules {
base, err := url.Parse(splatoon2API)
if !errors.Is(err, nil) {
log.Fatal(err)
}
base.Path = path.Join(base.Path, uri)
req, err := http.NewRequest("GET", base.String(), nil)
if !errors.Is(err, nil) {
log.Fatal(err)
}
req.Header.Set("User-Agent", userAgent)
c := http.DefaultClient
resp, err := c.Do(req)
if !errors.Is(err, nil) {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if !errors.Is(err, nil) {
log.Fatal(err)
}
var result splatoonRespSchedules
err = json.Unmarshal(body, &result)
if !errors.Is(err, nil) {
log.Fatal(err)
}
return result
}
func storeRespToFile(b splatoonRespSchedules) {
f, err := os.Create(chacheFile)
if !errors.Is(err, nil) {
log.Fatal(err)
}
defer f.Close()
enc := gob.NewEncoder(f)
if err := enc.Encode(b); !errors.Is(err, nil) {
log.Fatal(err)
}
}
func restoreRespFromFile() splatoonRespSchedules {
f, err := os.Open(chacheFile)
if !errors.Is(err, nil) {
return splatoonRespSchedules{}
}
defer f.Close()
var resp splatoonRespSchedules
dec := gob.NewDecoder(f)
if err := dec.Decode(&resp); !errors.Is(err, nil) {
log.Fatal(err)
}
return resp
}
func isContain(s []string, str string) bool {
for _, v := range s {
if v == str {
return true
}
}
return false
}
func parseAccountsToMention(accounts []*mastodon.Account) string {
var result string
for _, v := range accounts {
if v.Bot {
continue
}
result += parseAccountToMention(v)
}
return result
}
func parseAccountToMention(account *mastodon.Account) string {
s := strings.Split(account.URL, "/")
return s[len(s)-1] + "@" + s[len(s)-2] + " "
}