Skip to content

Commit

Permalink
Merge pull request #36 from antony-ramos/fix-bugs
Browse files Browse the repository at this point in the history
Fix bugs
  • Loading branch information
antony-ramos authored Sep 24, 2023
2 parents a04fad9 + 68f6589 commit 973f320
Show file tree
Hide file tree
Showing 31 changed files with 1,606 additions and 256 deletions.
4 changes: 4 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,14 @@ help: ## Display this message
##

artifact: ## Compile app from sources (linux)
@echo "### Building artifact ..."
@CGO_ENABLED=0 GOARCH=amd64 GOOS=linux go build -a -installsuffix cgo -ldflags '-extldflags "-static"' -o ${BINARY_NAME} ./cmd/${BINARY_NAME}
@echo "### Artifact built successfully"

artifact.osx: ## Compile app from sources (osx)
@echo "### Building artifact ..."
@CGO_ENABLED=0 GOARCH=amd64 GOOS=darwin go build -a -installsuffix cgo -ldflags '-extldflags "-static"' -o ${BINARY_NAME} ./cmd/${BINARY_NAME}
@echo "### Artifact built successfully"

image-ci: ## Build an image for CI Test Helm
docker build . --tag "ghcr.io/antony-ramos/${BINARY_NAME}:ci"
Expand Down
8 changes: 4 additions & 4 deletions TODO.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
### Todo

- [ ] Better error management, errors send to Discord are too descriptive
- [ ] Add more logs for each level
- [ ] Add tracing for each request
- [ ] Add API as controller
- [ ] Fix In UpdatePlayer: placeholder $1 already has type int, cannot assign varchar
- [ ] Add notes to players (for example: player cannot play on wednesday)

### In Progress

- [ ] Add comments to every functions
- [ ] Add tests to every functions
- [ ] Add tracing for each request
- [ ] Add more logs for each level

### Done ✓
- [X] Create CI linter
Expand All @@ -23,3 +21,5 @@
- [X] Add In CreatePlayer id to player entity
- [X] Add Usecase: player name is not discord name. Must implement a way to link them
- [X] Fix in SearchPlayer: player strikes must be import there not in usecase
- [X] Fix In UpdatePlayer: placeholder $1 already has type int, cannot assign varchar
- [X] Better error management, errors send to Discord are too descriptive
7 changes: 3 additions & 4 deletions cmd/guildops/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
"github.com/antony-ramos/guildops/pkg/tracing"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
Expand Down Expand Up @@ -82,7 +81,7 @@ func main() {
log.Fatal(err)
}
}()
ctx, span := otel.Tracer(spanName).Start(ctx, "main", trace.WithTimestamp(time.Now()))
ctx, span := otel.Tracer(spanName).Start(ctx, "main")

// Metrics
zap.L().Info(fmt.Sprintf("Starting metrics server on port %s", cfg.Metrics.Port))
Expand All @@ -96,12 +95,12 @@ func main() {
if err != nil {
span.RecordError(err)
zap.L().Fatal(err.Error())
span.End(trace.WithTimestamp(time.Now()))
span.End()
}
}()

// Run
zap.L().Info("Starting app")
app.Run(ctx, cfg)
span.End(trace.WithTimestamp(time.Now()))
span.End()
}
5 changes: 3 additions & 2 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@ type (

// Discord -.
Discord struct {
Token string `env:"DISCORD_TOKEN" env-required:"true" yaml:"token"`
GuildID int `env:"DISCORD_GUILD_ID" env-required:"true" yaml:"guild_id"`
Token string `env:"DISCORD_TOKEN" env-required:"true" yaml:"token"`
GuildID int `env:"DISCORD_GUILD_ID" env-required:"true" yaml:"guild_id"`
DeleteCommands bool `env:"DISCORD_DELETE_COMMANDS" env-required:"true" yaml:"delete_commands"`
}

// Log -.
Expand Down
4 changes: 4 additions & 0 deletions config/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ logger:
metrics:
port: 2213

discord:
delete_commands: true

postgres:
pool_max: 10
conn_attempts: 10
conn_timeout: 2s
url: user=coven-bot dbname=coven password=JcJXS6FFsRjHD60vgbajSQ host=coven-bot-9798.8nj.cockroachlabs.cloud port=26257 sslmode=verify-full
27 changes: 0 additions & 27 deletions install/guildops/DEBIAN/postinst

This file was deleted.

4 changes: 3 additions & 1 deletion internal/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ func Run(ctx context.Context, cfg *config.Config) {
LootUseCase: luc,
RaidUseCase: ruc,
StrikeUseCase: suc,
Fake: false,
}

var inits []func() map[string]func(
Expand Down Expand Up @@ -76,7 +77,8 @@ func Run(ctx context.Context, cfg *config.Config) {
discord.CommandHandlers(mapHandler),
discord.Token(cfg.Discord.Token),
discord.Command(handlers),
discord.GuildID(cfg.Discord.GuildID))
discord.GuildID(cfg.Discord.GuildID),
discord.DeleteCommands(cfg.Discord.DeleteCommands))

zap.L().Info("starting to serve to discord webhooks")
err = serve.Run(ctx)
Expand Down
147 changes: 78 additions & 69 deletions internal/controller/discord/absence.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@ package discordhandler

import (
"context"
"sync"
"fmt"
"time"

"github.com/bwmarrin/discordgo"
"go.uber.org/zap"
)

var AbsenceDescriptor = []discordgo.ApplicationCommand{
Expand Down Expand Up @@ -57,31 +56,44 @@ func (d Discord) InitAbsence() map[string]func(
}
}

func (d Discord) GenerateListAbsenceHandlerMsg(ctx context.Context, date string) (string, error) {
errorMsg := "Error while listing absences" +
": "

select {
case <-ctx.Done():
return ctxError,
fmt.Errorf("discord - GenerateListAbsenceHandlerMsg - ctx.Done: %w", ctx.Err())
default:
var msg string
dates, err := parseDate(date)
if err != nil {
msg = errorMsg + HumanReadableError(err)
} else {
msg = "Absence(s) pour le " + dates[0].Format("02-01-2006") + " :\n"
absences, err := d.ListAbsence(ctx, dates[0])
if err != nil {
msg = errorMsg + HumanReadableError(err)
return msg, err
} else {
for _, absence := range absences {
msg += "* " + absence.Player.Name + "\n"
}
}
}
return msg, err
}
}

func (d Discord) ListAbsenceHandler(
ctx context.Context, session *discordgo.Session, interaction *discordgo.InteractionCreate,
) error {
options := interaction.ApplicationCommandData().Options
optionMap := make(map[string]*discordgo.ApplicationCommandInteractionDataOption, len(options))

for _, opt := range options {
optionMap[opt.Name] = opt
}

var msg string
dates, err := parseDate(optionMap["date"].StringValue())
if err != nil {
msg = "Erreur lors de la récupération des absences: " + err.Error()
} else {
msg = "Absences pour le " + dates[0].Format("02-01-2006") + ":\n"
absences, err := d.ListAbsence(ctx, dates[0])
if err != nil {
msg = "Erreur lors de la récupération des absences: " + err.Error()
} else {
for _, absence := range absences {
msg += absence.Player.Name + "\n"
}
}
}
msg, err := d.GenerateListAbsenceHandlerMsg(ctx, optionMap["date"].StringValue())
_ = session.InteractionRespond(interaction.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Expand All @@ -91,6 +103,44 @@ func (d Discord) ListAbsenceHandler(
return err
}

func (d Discord) GenerateAbsenceHandlerMsg(
ctx context.Context, user string, dates string, created bool,
) (string, error) {
errorMsg := "Error while creating absence: "
msg := "Absence(s) créée(s) pour le(s) :\n"
if !created {
errorMsg = "Error while deleting absence: "
msg = "Absence(s) supprimée(s) pour le(s) :\n"
}
select {
case <-ctx.Done():
return ctxError,
fmt.Errorf("discord - GenerateAbsenceHandlerMsg - ctx.Done: %w", ctx.Err())
default:
dates, err := parseDate(dates)
if err != nil {
return errorMsg + HumanReadableError(err), err
}
for _, date := range dates {
date := date
if !created {
err = d.DeleteAbsence(ctx, user, date)
if err != nil {
return errorMsg + HumanReadableError(err), err
}
msg += "* " + date.Format("02-01-2006") + "\n"
} else {
err = d.CreateAbsence(ctx, user, date)
if err != nil {
return errorMsg + HumanReadableError(err), err
}
msg += "* " + date.Format("02-01-2006") + "\n"
}
}
}
return msg, nil
}

func (d Discord) AbsenceHandler(
ctx context.Context, session *discordgo.Session, interaction *discordgo.InteractionCreate,
) error {
Expand All @@ -111,54 +161,13 @@ func (d Discord) AbsenceHandler(
user = interaction.User.Username
}

dates, err := parseDate(optionMap["date"].StringValue())
var waitGroup sync.WaitGroup
for _, date := range dates {
date := date
waitGroup.Add(1)
go func() {
defer waitGroup.Done()
if interaction.ApplicationCommandData().Name == "coven-absence-delete" {
err = d.DeleteAbsence(ctx, user, date)
if err != nil {
err = session.InteractionRespond(interaction.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Erreur lors de la suppression de l'absence pour le " + date.Format("02-01-2006"),
},
})
}
err = session.InteractionRespond(interaction.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Absence supprimée pour le " + date.Format("02-01-2006"),
},
})
if err != nil {
zap.L().Error("discord - AbsenceHandler - session.InteractionRespond", zap.Error(err))
}
} else {
err = d.CreateAbsence(ctx, user, date)
if err != nil {
err = session.InteractionRespond(interaction.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Erreur lors de la suppression de l'absence pour le " + date.Format("02-01-2006"),
},
})
}
err = session.InteractionRespond(interaction.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Absence créée pour le " + date.Format("02-01-2006"),
},
})
if err != nil {
zap.L().Error("discord - AbsenceHandler - session.InteractionRespond", zap.Error(err))
}
}
}()
}
waitGroup.Wait()
return nil
msg, err := d.GenerateAbsenceHandlerMsg(
ctx, user, optionMap["date"].StringValue(), interaction.ApplicationCommandData().Name == "coven-absence-create")
_ = session.InteractionRespond(interaction.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: msg,
},
})
return err
}
Loading

0 comments on commit 973f320

Please sign in to comment.