Skip to content

Commit

Permalink
feat: add params command for discord + updating commands
Browse files Browse the repository at this point in the history
  • Loading branch information
freak12techno committed May 20, 2024
1 parent 82d06c2 commit 8577dee
Show file tree
Hide file tree
Showing 10 changed files with 225 additions and 16 deletions.
1 change: 1 addition & 0 deletions pkg/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ func NewApp(configPath string, filesystem fs.FS, version string) *App {
log,
stateManager,
mutesManager,
dataManager,
stateGenerator,
timeZone,
tracer,
Expand Down
71 changes: 60 additions & 11 deletions pkg/reporters/discord/discord.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package discord

import (
"context"
"main/pkg/data"
mutes "main/pkg/mutes"
"main/pkg/report/entry"
statePkg "main/pkg/state"
Expand Down Expand Up @@ -30,6 +31,7 @@ type Reporter struct {
Config *types.Config
Manager *statePkg.Manager
MutesManager *mutes.Manager
DataManager *data.Manager
TemplatesManager templatesPkg.Manager
Commands map[string]*Command
Tracer trace.Tracer
Expand All @@ -42,6 +44,7 @@ func NewReporter(
logger *zerolog.Logger,
manager *statePkg.Manager,
mutesManager *mutes.Manager,
dataManager *data.Manager,
stateGenerator *statePkg.Generator,
timezone *time.Location,
tracer trace.Tracer,
Expand All @@ -54,6 +57,7 @@ func NewReporter(
Logger: logger.With().Str("component", "discord_reporter").Logger(),
Manager: manager,
MutesManager: mutesManager,
DataManager: dataManager,
StateGenerator: stateGenerator,
TemplatesManager: templatesPkg.NewDiscordTemplatesManager(logger, timezone),
Commands: make(map[string]*Command, 0),
Expand Down Expand Up @@ -91,6 +95,7 @@ func (reporter *Reporter) Init() error {
"proposals_mute": reporter.GetAddMuteCommand(),
"proposals_unmute": reporter.GetDeleteMuteCommand(),
"proposals_mutes": reporter.GetMutesCommand(),
"params": reporter.GetParamsCommand(),

Check warning on line 98 in pkg/reporters/discord/discord.go

View check run for this annotation

Codecov / codecov/patch

pkg/reporters/discord/discord.go#L92-L98

Added lines #L92 - L98 were not covered by tests
}

go reporter.InitCommands()
Expand All @@ -116,8 +121,32 @@ func (reporter *Reporter) InitCommands() {
return

Check warning on line 121 in pkg/reporters/discord/discord.go

View check run for this annotation

Codecov / codecov/patch

pkg/reporters/discord/discord.go#L118-L121

Added lines #L118 - L121 were not covered by tests
}

for _, command := range registeredCommands {
wg.Add(1)
desiredCommands := utils.Map(
utils.MapToArray(reporter.Commands),
func(c *Command) *discordgo.ApplicationCommand { return c.Info },

Check warning on line 126 in pkg/reporters/discord/discord.go

View check run for this annotation

Codecov / codecov/patch

pkg/reporters/discord/discord.go#L124-L126

Added lines #L124 - L126 were not covered by tests
)

commandsToAdd := utils.Subtract(desiredCommands, registeredCommands, func(v *discordgo.ApplicationCommand) string {
return v.Name
})

Check warning on line 131 in pkg/reporters/discord/discord.go

View check run for this annotation

Codecov / codecov/patch

pkg/reporters/discord/discord.go#L129-L131

Added lines #L129 - L131 were not covered by tests

commandsToDelete := utils.Subtract(registeredCommands, desiredCommands, func(v *discordgo.ApplicationCommand) string {
return v.Name
})

Check warning on line 135 in pkg/reporters/discord/discord.go

View check run for this annotation

Codecov / codecov/patch

pkg/reporters/discord/discord.go#L133-L135

Added lines #L133 - L135 were not covered by tests

commandsToUpdate := utils.Union(registeredCommands, desiredCommands, func(v *discordgo.ApplicationCommand) string {
return v.Name
})

Check warning on line 139 in pkg/reporters/discord/discord.go

View check run for this annotation

Codecov / codecov/patch

pkg/reporters/discord/discord.go#L137-L139

Added lines #L137 - L139 were not covered by tests

reporter.Logger.Info().
Int("commands_to_add", len(commandsToAdd)).
Int("commands_to_delete", len(commandsToDelete)).
Int("commands_to_update", len(commandsToUpdate)).
Msg("Updating Discord slash commands")

Check warning on line 145 in pkg/reporters/discord/discord.go

View check run for this annotation

Codecov / codecov/patch

pkg/reporters/discord/discord.go#L141-L145

Added lines #L141 - L145 were not covered by tests

wg.Add(len(commandsToAdd) + len(commandsToDelete) + len(commandsToUpdate))

Check warning on line 147 in pkg/reporters/discord/discord.go

View check run for this annotation

Codecov / codecov/patch

pkg/reporters/discord/discord.go#L147

Added line #L147 was not covered by tests

for _, command := range commandsToDelete {
go func(command *discordgo.ApplicationCommand) {
defer wg.Done()

Check warning on line 151 in pkg/reporters/discord/discord.go

View check run for this annotation

Codecov / codecov/patch

pkg/reporters/discord/discord.go#L149-L151

Added lines #L149 - L151 were not covered by tests

Expand All @@ -130,27 +159,47 @@ func (reporter *Reporter) InitCommands() {
}(command)
}

wg.Wait()

for key, command := range reporter.Commands {
wg.Add(1)
go func(key string, command *Command) {
for _, command := range commandsToAdd {
go func(command *discordgo.ApplicationCommand) {
defer wg.Done()

Check warning on line 164 in pkg/reporters/discord/discord.go

View check run for this annotation

Codecov / codecov/patch

pkg/reporters/discord/discord.go#L162-L164

Added lines #L162 - L164 were not covered by tests

cmd, err := session.ApplicationCommandCreate(session.State.User.ID, reporter.Guild, command.Info)
cmd, err := session.ApplicationCommandCreate(session.State.User.ID, reporter.Guild, command)
if err != nil {
reporter.Logger.Error().Err(err).Str("command", command.Info.Name).Msg("Could not create command")
reporter.Logger.Error().Err(err).Str("command", command.Name).Msg("Could not create command")
return

Check warning on line 169 in pkg/reporters/discord/discord.go

View check run for this annotation

Codecov / codecov/patch

pkg/reporters/discord/discord.go#L166-L169

Added lines #L166 - L169 were not covered by tests
}
reporter.Logger.Info().Str("command", cmd.Name).Msg("Created command")

Check warning on line 171 in pkg/reporters/discord/discord.go

View check run for this annotation

Codecov / codecov/patch

pkg/reporters/discord/discord.go#L171

Added line #L171 was not covered by tests

mutex.Lock()
reporter.Commands[key].Info = cmd
reporter.Commands[command.Name].Info = cmd
mutex.Unlock()

Check warning on line 175 in pkg/reporters/discord/discord.go

View check run for this annotation

Codecov / codecov/patch

pkg/reporters/discord/discord.go#L173-L175

Added lines #L173 - L175 were not covered by tests
}(key, command)
}(command)
}

for _, command := range commandsToUpdate {
go func(command *discordgo.ApplicationCommand) {
defer wg.Done()

Check warning on line 181 in pkg/reporters/discord/discord.go

View check run for this annotation

Codecov / codecov/patch

pkg/reporters/discord/discord.go#L179-L181

Added lines #L179 - L181 were not covered by tests

cmd, err := session.ApplicationCommandEdit(
session.State.User.ID,
reporter.Guild,
command.ID,
command,
)
if err != nil {
reporter.Logger.Error().Err(err).Str("command", command.Name).Msg("Could not update command")
return

Check warning on line 191 in pkg/reporters/discord/discord.go

View check run for this annotation

Codecov / codecov/patch

pkg/reporters/discord/discord.go#L183-L191

Added lines #L183 - L191 were not covered by tests
}
reporter.Logger.Info().Str("command", cmd.Name).Msg("Updated command")

Check warning on line 193 in pkg/reporters/discord/discord.go

View check run for this annotation

Codecov / codecov/patch

pkg/reporters/discord/discord.go#L193

Added line #L193 was not covered by tests

mutex.Lock()
reporter.Commands[command.Name].Info = cmd
mutex.Unlock()

Check warning on line 197 in pkg/reporters/discord/discord.go

View check run for this annotation

Codecov / codecov/patch

pkg/reporters/discord/discord.go#L195-L197

Added lines #L195 - L197 were not covered by tests
}(command)
}

wg.Wait()
reporter.Logger.Info().Msg("All commands updated")

Check warning on line 202 in pkg/reporters/discord/discord.go

View check run for this annotation

Codecov / codecov/patch

pkg/reporters/discord/discord.go#L201-L202

Added lines #L201 - L202 were not covered by tests
}

func (reporter *Reporter) Enabled() bool {
Expand Down
3 changes: 2 additions & 1 deletion pkg/reporters/discord/list_mutes.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package discord

import (
"github.com/bwmarrin/discordgo"
mutes "main/pkg/mutes"
"main/pkg/utils"

"github.com/bwmarrin/discordgo"
)

func (reporter *Reporter) GetMutesCommand() *Command {
Expand Down
File renamed without changes.
32 changes: 32 additions & 0 deletions pkg/reporters/discord/params.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package discord

import (
"context"
"fmt"

"github.com/bwmarrin/discordgo"
)

func (reporter *Reporter) GetParamsCommand() *Command {
return &Command{
Info: &discordgo.ApplicationCommand{
Name: "params",
Description: "List all chains params.",
},
Handler: func(s *discordgo.Session, i *discordgo.InteractionCreate) {
params, err := reporter.DataManager.GetParams(context.Background())
if err != nil {
reporter.BotRespond(s, i, fmt.Sprintf("Error getting chain params: %s", err))
return

Check warning on line 20 in pkg/reporters/discord/params.go

View check run for this annotation

Codecov / codecov/patch

pkg/reporters/discord/params.go#L10-L20

Added lines #L10 - L20 were not covered by tests
}

template, err := reporter.TemplatesManager.Render("params", params)
if err != nil {
reporter.Logger.Error().Err(err).Str("template", "params").Msg("Error rendering template")
return

Check warning on line 26 in pkg/reporters/discord/params.go

View check run for this annotation

Codecov / codecov/patch

pkg/reporters/discord/params.go#L23-L26

Added lines #L23 - L26 were not covered by tests
}

reporter.BotRespond(s, i, template)

Check warning on line 29 in pkg/reporters/discord/params.go

View check run for this annotation

Codecov / codecov/patch

pkg/reporters/discord/params.go#L29

Added line #L29 was not covered by tests
},
}
}
53 changes: 53 additions & 0 deletions pkg/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,59 @@ func Contains[T comparable](slice []T, elt T) bool {
return false
}

// Subtract returns a new slice than includes values that are presented in the first, but not
// the second array.
func Subtract[T any, C comparable](first, second []T, predicate func(T) C) []T {
valuesMap := make(map[C]bool, len(second))
for _, value := range second {
valuesMap[predicate(value)] = true
}

newSlice := make([]T, 0)

for _, value := range first {
predicateResult := predicate(value)
_, ok := valuesMap[predicateResult]
if !ok {
newSlice = append(newSlice, value)
}
}

return newSlice
}

func Union[T any, C comparable](first, second []T, predicate func(T) C) []T {
valuesMap := make(map[C]bool, len(second))
for _, value := range second {
valuesMap[predicate(value)] = true
}

newSlice := make([]T, 0)

for _, value := range first {
predicateResult := predicate(value)
_, ok := valuesMap[predicateResult]
if ok {
newSlice = append(newSlice, value)
}
}

return newSlice
}

func MapToArray[K comparable, T any](source map[K]T) []T {
newSlice := make([]T, len(source))

index := 0

for _, value := range source {
newSlice[index] = value
index++
}

return newSlice
}

func FormatDuration(duration time.Duration) string {
days := int64(duration.Hours() / 24)
hours := int64(math.Mod(duration.Hours(), 24))
Expand Down
63 changes: 63 additions & 0 deletions pkg/utils/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,3 +147,66 @@ func TestSplitStringIntoChunksMoreChunks(t *testing.T) {
chunks := SplitStringIntoChunks(str, 10)
assert.Len(t, chunks, 3, "There should be 3 chunks!")
}

func TestSubtract(t *testing.T) {
t.Parallel()

type TestStruct struct {
Value string
}

first := []TestStruct{
{Value: "1"},
{Value: "2"},
{Value: "3"},
}

second := []TestStruct{
{Value: "2"},
{Value: "4"},
}

result := Subtract(first, second, func(v TestStruct) any { return v.Value })
assert.Len(t, result, 2)
assert.Equal(t, "1", result[0].Value)
assert.Equal(t, "3", result[1].Value)
}

func TestUnion(t *testing.T) {
t.Parallel()

type TestStruct struct {
Value string
}

first := []TestStruct{
{Value: "1"},
{Value: "2"},
{Value: "3"},
}

second := []TestStruct{
{Value: "2"},
{Value: "4"},
}

result := Union(first, second, func(v TestStruct) any { return v.Value })
assert.Len(t, result, 1)
assert.Equal(t, "2", result[0].Value)
}

func TestMapToArray(t *testing.T) {
t.Parallel()

testMap := map[string]string{
"test1": "1",
"test2": "2",
"test3": "3",
}

result := MapToArray(testMap)
assert.Len(t, result, 3)
assert.Equal(t, "1", result[0])
assert.Equal(t, "2", result[1])
assert.Equal(t, "3", result[2])
}
7 changes: 4 additions & 3 deletions templates/discord/help.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
Notifies you about the proposals your wallets hasn't voted upon.
Can understand the following commands:
- </proposals:{{ .Commands.proposals.Info.ID }}> - displays active proposals and your wallets' votes on them
- </proposals_mute:{{ .Commands.proposals_mute.Info.ID}}> - mute notifications for a specific chain/proposal
- </proposals_unmute:{{ .Commands.proposals_unmute.Info.ID}}> - unmute notifications for a specific chain/proposal
- </proposals_mutes:{{ .Commands.proposals_mutes.Info.ID}}> - displays the active mutes list
- </proposals_mute:{{ .Commands.proposals_mute.Info.ID }}> - mute notifications for a specific chain or proposal
- </proposals_unmute:{{ .Commands.proposals_unmute.Info.ID }}> - unmute notifications for a specific chain or proposal
- </proposals_mutes:{{ .Commands.proposals_mutes.Info.ID }}> - displays the active mutes list
- </params:{{ .Commands.params.Info.ID }}> - list chains params
- </help:{{ .Commands.help.Info.ID }}> - display this message

Created by [🐹 Quokka Stake](<https://quokkastake.io>) with ❤️.
Expand Down
7 changes: 7 additions & 0 deletions templates/discord/params.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{{- range $chainName, $params := . }}
**Params of chain {{ $params.Chain.GetName }}:**
{{- range $param := .Params }}
{{ $param.GetDescription }}: {{ $param.Serialize }}
{{- end }}

{{ end }}
4 changes: 3 additions & 1 deletion templates/telegram/help.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
Notifies you about the proposals your wallets hasn't voted upon.
Can understand the following commands:
- /proposals - displays active proposals and your wallets' votes on them
- /proposals_mute &lt;duration&gt; &lt;chain&gt; &lt;proposal ID&gt; - mute notifications for a specific proposal
- /proposals_mute &lt;duration&gt; &lt;chain&gt; &lt;proposal ID&gt; - mute notifications for a specific chain/proposal
- /proposals_unmute [&lt;chain&gt; &lt;proposal ID&gt;] - unmute notifications for a specific chain/proposal
- /proposals_mutes - display the active proposals mutes list
- /params - list chains params
- /help - display this command

Created by <a href="https://quokkastake.io">🐹 Quokka Stake</a> with ❤️.
Expand Down

0 comments on commit 8577dee

Please sign in to comment.