Skip to content
This repository has been archived by the owner on Oct 6, 2024. It is now read-only.

Commit

Permalink
feat: use log, greaceful shutdown, use discord reffer for create cmd
Browse files Browse the repository at this point in the history
  • Loading branch information
lenisko committed Mar 1, 2024
1 parent c6e502d commit 0cbf08f
Show file tree
Hide file tree
Showing 6 changed files with 63 additions and 42 deletions.
6 changes: 3 additions & 3 deletions config/parser.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
package config

import (
"fmt"
"github.com/BurntSushi/toml"
"log"
)

func (config *Config) ParseConfig() error {
if _, err := toml.DecodeFile("default.toml", &config); err != nil {
fmt.Println("error decoding default config file,", err)
log.Println("error decoding default config file,", err)
return err
}

if _, err := toml.DecodeFile("config.toml", &config); err != nil {
fmt.Println("error decoding user config file,", err)
log.Println("error decoding user config file,", err)
return err
}

Expand Down
8 changes: 4 additions & 4 deletions database/db.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package database

import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
"log"

"porygon/config"
)
Expand Down Expand Up @@ -74,7 +74,7 @@ func GetRaidStats(db *sqlx.DB) ([]RaidStats, error) {
`
err := db.Select(&raidStatsList, query)
if err != nil {
fmt.Println(err)
log.Println(err)
return nil, err
}

Expand All @@ -97,7 +97,7 @@ func GetGymStats(db *sqlx.DB) (GymStats, error) {
`)

if err != nil {
fmt.Println(err)
log.Println(err)
return GymStats{}, err
}

Expand Down Expand Up @@ -132,7 +132,7 @@ func GetRewardStats(db *sqlx.DB) ([]TypeCountStats, error) {
GROUP BY reward_type
`)
if err != nil {
fmt.Println(err)
log.Println(err)
return rewardStatsList, err
}

Expand Down
9 changes: 5 additions & 4 deletions discord/constructor.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"github.com/bwmarrin/discordgo"
"github.com/dustin/go-humanize"
"log"
"os"
"porygon/config"
"porygon/database"
Expand Down Expand Up @@ -90,7 +91,7 @@ func GenerateFields(gathered GatheredStats, config config.Config) []*discordgo.M
if err != nil {
currentTemplateFile, err = os.ReadFile("templates/current.json")
if err != nil {
panic(err)
log.Panicln(err)
}
}

Expand All @@ -104,17 +105,17 @@ func GenerateFields(gathered GatheredStats, config config.Config) []*discordgo.M
"EventEmoji": func(level int) string { return convertToEmoji(level, config.EventEmoji) },
}).Parse(string(currentTemplateFile))
if err != nil {
panic(err)
log.Panicln(err)
}

var resultJSON bytes.Buffer
if err := tmpl.Execute(&resultJSON, gathered); err != nil {
panic(err)
log.Panicln(err)
}

var fields []*discordgo.MessageEmbedField
if err := json.Unmarshal(resultJSON.Bytes(), &fields); err != nil {
panic(err)
log.Panicln(err)
}

return fields
Expand Down
37 changes: 25 additions & 12 deletions discord/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/base64"
"fmt"
"github.com/bwmarrin/discordgo"
"log"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -55,12 +56,29 @@ func listEmotes(s *discordgo.Session, i *discordgo.InteractionCreate) {
}

func createEmotes(s *discordgo.Session, i *discordgo.InteractionCreate) {
emotesDir := "emojis"
var output strings.Builder
output.WriteString("```")

_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseDeferredChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral,
},
})

emotesDir := "emojis/override"
files, err := filepath.Glob(filepath.Join(emotesDir, "*.png"))

if len(files) > 0 {
output.WriteString("Using `emojis/override` directory as emotes source.\n")
} else {
output.WriteString("Using `emojis` directory as emotes source.\n")
emotesDir = "emojis"
files, err = filepath.Glob(filepath.Join(emotesDir, "*.png"))
}

files, err := os.ReadDir(emotesDir)
if err != nil {
fmt.Println("Error reading emotes directory:", err)
log.Println("Error reading emotes directory:", err)
return
}

Expand All @@ -71,16 +89,15 @@ func createEmotes(s *discordgo.Session, i *discordgo.InteractionCreate) {
existingEmotes[emote.Name] = true
}

output.WriteString("```")
// check and upload every emote we have under emotesDir
for _, file := range files {
emoteName := strings.TrimSuffix(file.Name(), ".png")
emoteName := strings.TrimSuffix(filepath.Base(file), ".png")

if _, exists := existingEmotes[emoteName]; exists {
output.WriteString(fmt.Sprintf("%s - already there\n", emoteName))
continue
}
emoteFile, err := os.ReadFile(filepath.Join(emotesDir, file.Name()))
emoteFile, err := os.ReadFile(filepath.Join(emotesDir, filepath.Base(file)))
encodedImage := base64.StdEncoding.EncodeToString(emoteFile)
dataURI := fmt.Sprintf("data:image/png;base64,%s", encodedImage)

Expand All @@ -96,11 +113,7 @@ func createEmotes(s *discordgo.Session, i *discordgo.InteractionCreate) {
}
output.WriteString("```")

_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: output.String(),
Flags: discordgo.MessageFlagsEphemeral,
},
_, _ = s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
Content: output.String(),
})
}
Empty file added emojis/override/.gitkeep
Empty file.
45 changes: 26 additions & 19 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ package main

import (
"encoding/json"
"fmt"
"github.com/bwmarrin/discordgo"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
"log"
"os"
"os/signal"
"syscall"
"time"

"porygon/api"
Expand All @@ -18,7 +20,7 @@ import (
func saveMessageIDs(filename string, messageIDs map[string]string) {
file, err := os.Create(filename)
if err != nil {
fmt.Println("error creating message IDs file:", err)
log.Println("error creating message IDs file:", err)
return
}
defer file.Close()
Expand All @@ -32,7 +34,7 @@ func loadMessageIDs(filename string) map[string]string {
if _, err := os.Stat(filename); os.IsNotExist(err) {
file, err := os.Create(filename)
if err != nil {
fmt.Println("error creating message IDs file:", err)
log.Println("error creating message IDs file:", err)
return messageIDs
}
defer file.Close()
Expand All @@ -41,7 +43,7 @@ func loadMessageIDs(filename string) map[string]string {
} else {
file, err := os.Open(filename)
if err != nil {
fmt.Println("error opening message IDs file:", err)
log.Println("error opening message IDs file:", err)
return messageIDs
}
defer file.Close()
Expand Down Expand Up @@ -128,14 +130,15 @@ func gatherStats(db *sqlx.DB, config config.Config) (discord.GatheredStats, erro
}

elapsed := time.Since(start)
fmt.Printf("Fetched stats in %s\n", elapsed)
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 {
panic(err)
log.Panicln(err)
}

messageIDs := loadMessageIDs("messageIDs.json")
Expand All @@ -144,47 +147,48 @@ func main() {
defer dg.Close()

if err != nil {
fmt.Println("error creating Discord session,", err)
log.Println("error creating Discord session,", err)
return
}

fmt.Println("Add slash commands handlers")
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)
}
})

fmt.Println("Open Discord connection")
log.Println("Open Discord connection")
err = dg.Open()
if err != nil {
fmt.Println("error opening connection,", err)
log.Println("error opening connection,", err)
return
}

fmt.Println("Register commands")
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 {
fmt.Printf("Cannot create '%v' command: %v\n", v.Name, err)
log.Printf("Cannot create '%v' command: %v\n", v.Name, err)
}
registeredCommands[i] = cmd
}

fmt.Println("Start loop")
log.Println("Start loop")
go func() {
for {
db, err := database.DbConn(c)
if err != nil {
fmt.Println("error connecting to MariaDB,", err)
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 {
fmt.Println("failed to fetch stats,", err)
log.Println("failed to fetch stats,", err)
time.Sleep(time.Duration(c.Config.ErrorRefreshInterval) * time.Second)
continue
}
Expand Down Expand Up @@ -213,7 +217,7 @@ func main() {
}

if err != nil {
fmt.Println("error sending or editing message in channel", channelID, ":", err)
log.Println("error sending or editing message in channel", channelID, ":", err)
continue
} else if msgID == "" || msgID != msg.ID {
messageIDs[channelID] = msg.ID
Expand All @@ -225,7 +229,10 @@ func main() {
}
}()

fmt.Println("Porygon is now running. Press CTRL-C to exit.")
<-make(chan struct{})
return
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...")
}

0 comments on commit 0cbf08f

Please sign in to comment.