This repository has been archived by the owner on Oct 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.go
238 lines (197 loc) · 5.46 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
package main
import (
"encoding/json"
"github.com/bwmarrin/discordgo"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
"log"
"os"
"os/signal"
"syscall"
"time"
"porygon/api"
"porygon/config"
"porygon/database"
"porygon/discord"
)
func saveMessageIDs(filename string, messageIDs map[string]string) {
file, err := os.Create(filename)
if err != nil {
log.Println("error creating message IDs file:", err)
return
}
defer file.Close()
json.NewEncoder(file).Encode(messageIDs)
}
func loadMessageIDs(filename string) map[string]string {
messageIDs := make(map[string]string)
if _, err := os.Stat(filename); os.IsNotExist(err) {
file, err := os.Create(filename)
if err != nil {
log.Println("error creating message IDs file:", err)
return messageIDs
}
defer file.Close()
json.NewEncoder(file).Encode(messageIDs)
} else {
file, err := os.Open(filename)
if err != nil {
log.Println("error opening message IDs file:", err)
return messageIDs
}
defer file.Close()
json.NewDecoder(file).Decode(&messageIDs)
}
return messageIDs
}
func gatherStats(db *sqlx.DB, config config.Config) (discord.GatheredStats, error) {
start := time.Now()
var err error
var gathered discord.GatheredStats
gathered.Pokemon, err = database.GetPokeStats(db)
if err != nil {
return gathered, err
}
gathered.RaidEgg, err = database.GetRaidStats(db)
if err != nil {
return gathered, err
}
gathered.Gym, err = database.GetGymStats(db)
if err != nil {
return gathered, err
}
gathered.Pokestop, err = database.GetPokestopStats(db)
if err != nil {
return gathered, err
}
gathered.Reward, err = database.GetRewardStats(db)
if err != nil {
return gathered, err
}
gathered.Lure, err = database.GetLureStats(db)
if err != nil {
return gathered, err
}
gathered.Rocket, err = database.GetRocketStats(db)
if err != nil {
return gathered, err
}
gathered.Event, err = database.GetEventStats(db)
if err != nil {
return gathered, err
}
gathered.Route, err = database.GetRoutesStats(db)
if err != nil {
return gathered, err
}
// probs break this out into query? again idk how to handle passing the config well just yet
if config.Config.IncludeActiveCounts {
hundoApiResponses, err := api.ApiRequest(config, 15, 15)
if err != nil {
return gathered, err
}
hundoSpawnIds := make(map[int]bool)
for _, apiResponse := range hundoApiResponses {
hundoSpawnIds[apiResponse.SpawnId] = true
}
gathered.HundoActiveCount = len(hundoSpawnIds)
nundoApiResponses, err := api.ApiRequest(config, 0, 0)
if err != nil {
return gathered, err
}
nundoSpawnIds := make(map[int]bool)
for _, apiResponse := range nundoApiResponses {
nundoSpawnIds[apiResponse.SpawnId] = true
}
gathered.NundoActiveCount = len(nundoSpawnIds)
}
elapsed := time.Since(start)
log.Printf("Fetched stats in %s\n", elapsed)
return gathered, nil
}
func main() {
var c config.Config
log.Println("Starting porygon")
if err := c.ParseConfig(); err != nil {
log.Panicln(err)
}
messageIDs := loadMessageIDs("messageIDs.json")
dg, err := discordgo.New("Bot " + c.Discord.Token)
defer dg.Close()
if err != nil {
log.Println("error creating Discord session,", err)
return
}
log.Println("Add slash commands handlers")
dg.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) {
if h, ok := discord.CommandHandlers[i.ApplicationCommandData().Name]; ok {
h(s, i)
}
})
log.Println("Open Discord connection")
err = dg.Open()
if err != nil {
log.Println("error opening connection,", err)
return
}
log.Println("Register commands")
registeredCommands := make([]*discordgo.ApplicationCommand, len(discord.Commands))
for i, v := range discord.Commands {
cmd, err := dg.ApplicationCommandCreate(dg.State.User.ID, "", v)
if err != nil {
log.Printf("Cannot create '%v' command: %v\n", v.Name, err)
}
registeredCommands[i] = cmd
}
log.Println("Start loop")
go func() {
for {
db, err := database.DbConn(c)
if err != nil {
log.Println("error connecting to MariaDB,", err)
time.Sleep(time.Duration(c.Config.ErrorRefreshInterval) * time.Second)
continue
}
gathered, err := gatherStats(db, c)
db.Close()
if err != nil {
log.Println("failed to fetch stats,", err)
time.Sleep(time.Duration(c.Config.ErrorRefreshInterval) * time.Second)
continue
}
fields := discord.GenerateFields(gathered, c)
embed := &discordgo.MessageEmbed{
Title: c.Config.EmbedTitle,
Fields: fields,
Timestamp: time.Now().Format(time.RFC3339),
}
for _, channelID := range c.Discord.ChannelIDs {
var msg *discordgo.Message
var err error
var msgID string
var ok bool
if msgID, ok = messageIDs[channelID]; ok {
msg, err = dg.ChannelMessageEditEmbed(channelID, msgID, embed)
if err != nil {
msg, err = dg.ChannelMessageSendEmbed(channelID, embed)
}
} else {
msg, err = dg.ChannelMessageSendEmbed(channelID, embed)
}
if err != nil {
log.Println("error sending or editing message in channel", channelID, ":", err)
continue
} else if msgID == "" || msgID != msg.ID {
messageIDs[channelID] = msg.ID
saveMessageIDs("messageIDs.json", messageIDs)
}
}
time.Sleep(time.Duration(c.Config.RefreshInterval) * time.Second)
}
}()
log.Println("Porygon is now running. Press CTRL-C to exit.")
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
<-stop
log.Println("Received signal. Exiting...")
}