diff --git a/config.go b/config.go index 5cae8e7..d8c2033 100644 --- a/config.go +++ b/config.go @@ -4,6 +4,8 @@ import ( "encoding/json" "log" "os" + + "github.com/pkg/errors" ) type Configuration struct { @@ -11,15 +13,15 @@ type Configuration struct { Token string `json:"token"` } -var config Configuration - -func init() { +func config() Configuration { + var config Configuration fileBytes, err := os.ReadFile("config.json") if err != nil { - log.Fatal(err) + log.Fatal(errors.Wrap(err, "could not open config")) } err = json.Unmarshal(fileBytes, &config) if err != nil { - log.Fatal(err) + log.Fatal(errors.Wrap(err, "could not parse config")) } + return config } diff --git a/doc.go b/doc.go index e51d7cf..d505236 100644 --- a/doc.go +++ b/doc.go @@ -6,6 +6,7 @@ import ( "log" "path" "strings" + "sync" "time" "github.com/diamondburned/arikawa/v3/api" @@ -35,18 +36,23 @@ type interactionData struct { full bool } -var interactionMap = map[string]*interactionData{} +var ( + interactionMap = map[string]*interactionData{} + mu sync.Mutex +) func init() { go func() { for { time.Sleep(time.Minute * 5) now := time.Now() + mu.Lock() for _, data := range interactionMap { - if data.created.After(now) { + if now.After(data.created.Add(time.Minute * 5)) { delete(interactionMap, data.id) } } + mu.Unlock() } }() } @@ -64,16 +70,18 @@ func (b *botState) handleDocs(e *gateway.InteractionCreateEvent) { } query := args["query"].String() - embed := b.onDocs(e, args["query"].String(), false) + embed := b.onDocs(e, query, false) var components *[]discord.Component if !strings.HasPrefix(embed.Title, "Error") { + mu.Lock() interactionMap[e.ID.String()] = &interactionData{ id: e.ID.String(), created: time.Now(), user: e.User, query: query, } + mu.Unlock() components = &[]discord.Component{ discord.ActionRowComponent{ @@ -159,7 +167,9 @@ func (b *botState) onDocsComponent(e *gateway.InteractionCreateEvent, data *inte embed = b.onDocs(e, data.query, data.full) embed.Description = "" embed.Footer = nil + mu.Lock() delete(interactionMap, data.id) + mu.Unlock() } if e.GuildID != discord.NullGuildID { diff --git a/main.go b/main.go index a496def..3956ff2 100644 --- a/main.go +++ b/main.go @@ -43,13 +43,14 @@ func main() { flag.Parse() update = *updateVar - if config.Token == "" { - log.Fatalln("no token provided") + cfg := config() + if cfg.Token == "" { + log.Fatal("no token provided") } - s, err := state.New("Bot " + config.Token) + s, err := state.New("Bot " + cfg.Token) if err != nil { - log.Fatalln("session failed:", err) + log.Fatalln(errors.Wrap(err, "could not open session")) } searcher := doc.New(http.DefaultClient, godocs.Parser)