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

Commit

Permalink
refactor(log): replaced zerolog by slog from Go STL
Browse files Browse the repository at this point in the history
  • Loading branch information
Wittano committed Mar 21, 2024
1 parent 1c40090 commit cc88391
Show file tree
Hide file tree
Showing 13 changed files with 69 additions and 109 deletions.
36 changes: 19 additions & 17 deletions cmd/komputer/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,26 @@ import (
"github.com/bwmarrin/discordgo"
"github.com/google/uuid"
"github.com/joho/godotenv"
zerolog "github.com/rs/zerolog/log"
"github.com/wittano/komputer/internal"
"github.com/wittano/komputer/internal/command"
"github.com/wittano/komputer/internal/log"
"github.com/wittano/komputer/internal/mongo"
"github.com/wittano/komputer/internal/schedule"
"github.com/wittano/komputer/internal/voice"
"log"
"log/slog"
"os"
"os/signal"
"time"
)

var (
bot *discordgo.Session
commands = map[string]command.DiscordCommand{
command.WelcomeCommand.Command.Name: command.WelcomeCommand,
command.JokeCommand.Command.Name: command.JokeCommand,
command.AddJokeCommand.Command.Name: command.AddJokeCommand,
command.SpockCommand.Command.Name: command.SpockCommand,
command.SpockStopCommand.Command.Name: command.SpockStopCommand,
command.WelcomeCommand.String(): command.WelcomeCommand,
command.JokeCommand.String(): command.JokeCommand,
command.AddJokeCommand.String(): command.AddJokeCommand,
command.SpockCommand.String(): command.SpockCommand,
command.SpockStopCommand.String(): command.SpockStopCommand,
}
)

Expand All @@ -39,25 +40,27 @@ func init() {

bot, err = discordgo.New(fmt.Sprintf("Bot %s", os.Getenv("DISCORD_BOT_TOKEN")))
if err != nil {
panic(err)
log.Fatalf("failed connect with Discord: %s", err)
}
}

func init() {
bot.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) {
ctx := context.WithValue(context.Background(), "traceID", uuid.New().String())
ctx := context.WithValue(context.Background(), "requestID", uuid.New().String())
deadlineCtx, cancel := context.WithTimeout(ctx, time.Second*3)
defer cancel()

if i.Type == discordgo.InteractionMessageComponent {
if handler, ok := internal.JokeMessageComponentHandler[i.Data.(discordgo.MessageComponentInteractionData).CustomID]; ok {
log.Info(ctx, fmt.Sprintf("User %s execute message component action '%s'", i.Member.User.ID, i.Data.(discordgo.MessageComponentInteractionData).CustomID))
handler(ctx, s, i)
slog.InfoContext(deadlineCtx, fmt.Sprintf("User %s execute message component action '%s'", i.Member.User.ID, i.Data.(discordgo.MessageComponentInteractionData).CustomID))
handler(deadlineCtx, s, i)
return
}
}

if c, ok := commands[i.ApplicationCommandData().Name]; ok {
log.Info(ctx, fmt.Sprintf("User %s execute slash command '%s'", i.Member.User.ID, i.ApplicationCommandData().Name))
c.Execute(ctx, s, i)
slog.InfoContext(deadlineCtx, fmt.Sprintf("User %s execute slash command '%s'", i.Member.User.ID, i.ApplicationCommandData().Name))
c.Execute(deadlineCtx, s, i)
}
})
}
Expand All @@ -71,7 +74,7 @@ func init() {
os.Getenv("SERVER_GUID"),
&c.Command,
); err != nil {
log.Error(context.Background(), "Registration slash command failed", err)
log.Fatalf("registration slash command failed: %s", err)
}
}
}
Expand All @@ -83,7 +86,7 @@ func init() {
func checkEnvVariables(vars ...string) {
for _, v := range vars {
if _, ok := os.LookupEnv(v); !ok {
zerolog.Fatal().Msg(fmt.Sprintf("Missing %s varaiable", v))
log.Fatalf("Missing %s varaiable", v)
}
}
}
Expand All @@ -93,12 +96,11 @@ func main() {
defer bot.Close()
defer schedule.Scheduler.Stop()
defer mongo.CloseDb()
defer log.FileLog.Close()

schedule.Scheduler.StartAsync()

stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
log.Info(context.Background(), "Bot is ready!. Press Ctrl+C to exit")
slog.Info("Bot is ready!. Press Ctrl+C to exit")
<-stop
}
1 change: 1 addition & 0 deletions internal/assets/audio.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"path/filepath"
)

// TODO removed local storage of audio
const assertDir = "assets"

func Audios() ([]string, error) {
Expand Down
4 changes: 4 additions & 0 deletions internal/command/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,7 @@ type DiscordCommand struct {
Command discordgo.ApplicationCommand
Execute discordHandler
}

func (d DiscordCommand) String() string {
return d.Command.Name
}
8 changes: 4 additions & 4 deletions internal/command/joke.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import (
"fmt"
"github.com/bwmarrin/discordgo"
"github.com/wittano/komputer/internal/interaction"
"github.com/wittano/komputer/internal/log"
"github.com/wittano/komputer/internal/mongo"
"github.com/wittano/komputer/internal/types"
"log/slog"
"os"
)

Expand Down Expand Up @@ -69,7 +69,7 @@ func executeAddJokeCommand(ctx context.Context, s *discordgo.Session, i *discord
case "question":
j.Question = o.Value.(string)
default:
log.Warn(ctx, fmt.Sprintf("Invalid option for %s", o.Name))
slog.WarnContext(ctx, "Invalid option for %s", o.Name)
}
}

Expand All @@ -90,7 +90,7 @@ func executeAddJokeCommand(ctx context.Context, s *discordgo.Session, i *discord

id, err := mongo.AddJoke(ctx, j)
if err != nil {
log.Error(ctx, "Failed add new joke into database", err)
slog.ErrorContext(ctx, "Failed add new joke into database", err)
interaction.CreateDiscordInteractionResponse(ctx, i, s, interaction.CreateDiscordMsg("BEEP BOOP. Coś poszło nie tak z dodanie twego żartu Kapitanie"))
return
}
Expand All @@ -114,7 +114,7 @@ func executeJokeCommand(ctx context.Context, s *discordgo.Session, i *discordgo.
case "type":
jokeType = types.JokeType(o.Value.(string))
default:
log.Warn(ctx, fmt.Sprintf("Invalid option for %s", o.Name))
slog.WarnContext(ctx, fmt.Sprintf("Invalid option for %s", o.Name))
}
}

Expand Down
17 changes: 9 additions & 8 deletions internal/command/spock.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@ package command

import (
"context"
"errors"
"fmt"
"github.com/bwmarrin/discordgo"
"github.com/wittano/komputer/internal/assets"
"github.com/wittano/komputer/internal/interaction"
"github.com/wittano/komputer/internal/log"
"github.com/wittano/komputer/internal/voice"
"log/slog"
"os"
"path/filepath"
"strings"
)

// TODO Replace chan bool by chan struct{} (0-bytes channel)
var SpockMusicStopCh = map[string]chan bool{}

var SpockCommand = DiscordCommand{
Expand All @@ -35,10 +35,11 @@ var SpockCommand = DiscordCommand{
Execute: execSpookSpeak,
}

// TODO Add context
func audioIdOptions() []*discordgo.ApplicationCommandOptionChoice {
list, err := assets.Audios()
if err != nil {
log.Fatal(context.Background(), "Failed to get audios form assets folder", err)
slog.Error("failed to get audios form assets folder", err)
}

result := make([]*discordgo.ApplicationCommandOptionChoice, len(list))
Expand All @@ -60,7 +61,7 @@ func execSpookSpeak(ctx context.Context, s *discordgo.Session, i *discordgo.Inte

userVoiceChat, ok := voice.UserVoiceChatMap[i.Member.User.ID]
if !ok || userVoiceChat.GuildID != i.GuildID {
log.Error(ctx, fmt.Sprintf("Failed find user on voice channels on %s server", i.Member.GuildID), errors.New(fmt.Sprintf("user with ID %s wasn't found on any voice chat on %s server", i.Member.User.ID, i.GuildID)))
slog.ErrorContext(ctx, fmt.Sprintf("failed find user on voice channels on %s server", i.Member.GuildID), fmt.Errorf("user with ID %s wasn't found on any voice chat on %s server", i.Member.User.ID, i.GuildID))
interaction.CreateDiscordInteractionResponse(ctx, i, s, interaction.CreateDiscordMsg("BEEP BOOP. Kapitanie gdzie jesteś? Wejdź na kanał głosowy a ja dołącze"))
return
}
Expand All @@ -70,7 +71,7 @@ func execSpookSpeak(ctx context.Context, s *discordgo.Session, i *discordgo.Inte

voiceJoin, err := s.ChannelVoiceJoin(i.GuildID, userVoiceChat.ChannelID, false, true)
if err != nil {
log.Error(ctx, "Failed join to voice channel", err)
slog.ErrorContext(ctx, "failed join to voice channel", err)
return
}
defer voiceJoin.Close()
Expand All @@ -84,7 +85,7 @@ func execSpookSpeak(ctx context.Context, s *discordgo.Session, i *discordgo.Inte
default:
songPath, err = assets.RandomAudio()
if err != nil {
log.Error(ctx, "Failed find any audio in assets directory", err)
slog.ErrorContext(ctx, "failed find any audio in assets directory", err)
return
}
}
Expand All @@ -93,7 +94,7 @@ func execSpookSpeak(ctx context.Context, s *discordgo.Session, i *discordgo.Inte
if songPath == "" {
songPath, err = assets.RandomAudio()
if err != nil {
log.Error(ctx, "Failed find any audio in assets directory", err)
slog.ErrorContext(ctx, "failed find any audio in assets directory", err)
return
}
}
Expand All @@ -102,7 +103,7 @@ func execSpookSpeak(ctx context.Context, s *discordgo.Session, i *discordgo.Inte
SpockMusicStopCh[i.GuildID] = stop

if err = voice.PlayAudio(voiceJoin, songPath, stop); err != nil {
log.Error(ctx, fmt.Sprintf("Failed play '%s' songPath", songPath), err)
slog.ErrorContext(ctx, fmt.Sprintf("failed play '%s' songPath", songPath), err)
}

voiceJoin.Disconnect()
Expand Down
6 changes: 3 additions & 3 deletions internal/interaction/joke.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import (
"errors"
"github.com/bwmarrin/discordgo"
"github.com/wittano/komputer/internal/joke"
"github.com/wittano/komputer/internal/log"
"github.com/wittano/komputer/internal/mongo"
"github.com/wittano/komputer/internal/types"
"log/slog"
"math/rand"
)

Expand Down Expand Up @@ -35,7 +35,7 @@ func SendJoke(ctx context.Context, s *discordgo.Session, i *discordgo.Interactio
case types.Single:
j, err := getSingleTypeJokeGenerator()(ctx, c)
if err != nil {
log.Error(ctx, "Failed during getting single joke from JokeDev", err)
slog.ErrorContext(ctx, "failed during getting single joke from JokeDev", err)

if errors.Is(err, types.ErrJokeNotFound{Category: c, JokeType: t}) || errors.Is(err, joke.ErrJokeCategoryNotSupported{}) {
CreateDiscordInteractionResponse(ctx, i, s, CreateJokeNotFoundMsg(t, c))
Expand All @@ -50,7 +50,7 @@ func SendJoke(ctx context.Context, s *discordgo.Session, i *discordgo.Interactio
case types.TwoPart:
j, err := getTwoPartsTypeJokeGenerator()(ctx, c)
if err != nil {
log.Error(ctx, "Failed during getting two-part joke from JokeDev", err)
slog.ErrorContext(ctx, "failed during getting two-part joke from JokeDev", err)

if errors.Is(err, types.ErrJokeNotFound{Category: c, JokeType: t}) || errors.Is(err, joke.ErrJokeCategoryNotSupported{}) {
CreateDiscordInteractionResponse(ctx, i, s, CreateJokeNotFoundMsg(t, c))
Expand Down
5 changes: 3 additions & 2 deletions internal/interaction/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import (
"context"
"fmt"
"github.com/bwmarrin/discordgo"
"github.com/wittano/komputer/internal/log"
"github.com/wittano/komputer/internal/types"
"log/slog"
"strings"
)

Expand Down Expand Up @@ -134,11 +134,12 @@ func createButtonReactions() []discordgo.MessageComponent {
}
}

// TODO Improved message
func CreateDiscordInteractionResponse(ctx context.Context, i *discordgo.InteractionCreate, s *discordgo.Session, msg *discordgo.InteractionResponseData) {
if err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: msg,
}); err != nil {
log.Error(ctx, "Failed send response to discord user", err)
slog.ErrorContext(ctx, "Failed send response to discord user", err)
}
}
11 changes: 7 additions & 4 deletions internal/joke/humorapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,16 @@ import (
"encoding/json"
"errors"
"fmt"
"github.com/wittano/komputer/internal/log"
"github.com/wittano/komputer/internal/types"
"io"
"log/slog"

Check failure on line 10 in internal/joke/humorapi.go

View workflow job for this annotation

GitHub Actions / build

package log/slog is not in GOROOT (/opt/hostedtoolcache/go/1.20.14/x64/src/log/slog)
"net/http"
"net/url"
"os"
)

const humorApiURL = "https://humor-jokes-and-memes.p.rapidapi.com/jokes/random?exclude-tags=nsfw&include-tags="

type HumorAPIRes struct {
JokeRes string `json:"joke"`
ID int64 `json:"id"`
Expand All @@ -28,12 +30,13 @@ type HumorAPILimitExceededErr struct {
type HumorAPIKeyMissingErr struct {
}

// TODO Remove or refactor errors
func (h HumorAPIKeyMissingErr) Error() string {
return "RAPID_API_KEY is missing"
}

func (h HumorAPILimitExceededErr) Error() string {
return "Humor API limit exceeded"
return "HumorAPI limit exceeded"
}

func GetRandomJokeFromHumorAPI(ctx context.Context, category types.JokeCategory) (HumorAPIRes, error) {
Expand All @@ -42,7 +45,7 @@ func GetRandomJokeFromHumorAPI(ctx context.Context, category types.JokeCategory)
return HumorAPIRes{}, HumorAPIKeyMissingErr{}
}

u, err := url.Parse("https://humor-jokes-and-memes.p.rapidapi.com/jokes/random?exclude-tags=nsfw&include-tags=" + category.ToHumorAPICategory())
u, err := url.Parse(humorApiURL + category.ToHumorAPICategory())
if err != nil {
return HumorAPIRes{}, err
}
Expand All @@ -67,7 +70,7 @@ func GetRandomJokeFromHumorAPI(ctx context.Context, category types.JokeCategory)
} else if res.StatusCode != 200 {
msg, err := io.ReadAll(res.Body)
if err != nil {
log.Error(ctx, "Failed read response body from HumorAPI", err)
slog.ErrorContext(ctx, "Failed read response body from HumorAPI", err)
msg = []byte{}
}

Expand Down
56 changes: 0 additions & 56 deletions internal/log/log.go

This file was deleted.

Loading

0 comments on commit cc88391

Please sign in to comment.