Skip to content

Commit

Permalink
add options handler
Browse files Browse the repository at this point in the history
  • Loading branch information
zekroTJA committed Oct 5, 2021
1 parent 7fb34fd commit 0d0424a
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 2 deletions.
6 changes: 6 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,9 @@ func (c *Ctx) User() (u *discordgo.User) {
}
return
}

// Options returns the application command data options
// with additional functionality methods.
func (c *Ctx) Options() CommandOptions {
return c.Event.ApplicationCommandData().Options
}
4 changes: 2 additions & 2 deletions example/middlewares/commands/kick.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@ func (c *KickCommand) Run(ctx *ken.Ctx) (err error) {
return
}

user := ctx.Event.ApplicationCommandData().Options[0].UserValue(ctx.Session)
reason := ctx.Event.ApplicationCommandData().Options[1].StringValue()
user := ctx.Options().GetByName("member").UserValue(ctx.Session)
reason := ctx.Options().GetByName("reason").StringValue()

if err = ctx.Session.GuildMemberDeleteWithReason(ctx.Event.GuildID, user.ID, reason); err != nil {
return
Expand Down
50 changes: 50 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package ken

import (
"github.com/bwmarrin/discordgo"
)

// CommandOptions provides additional functionailities to
// an array of ApplicationCommandInteractionDataOptions.
type CommandOptions []*discordgo.ApplicationCommandInteractionDataOption

// Get safely returns an options from command options
// by index.
func (co CommandOptions) Get(i int) *discordgo.ApplicationCommandInteractionDataOption {
if i < 0 {
i = 0
}
if i >= len(co) {
i = len(co) - 1
}
return co[i]
}

// Options returns wrapped underlying options
// of a sub command by ID.
func (co CommandOptions) Options(i int) CommandOptions {
return co.Get(i).Options
}

// GetByNameOptional returns an option by name. If the option with the
// name does not exist, the returned value for ok is false.
//
// This should be used for non-required options.
func (co CommandOptions) GetByNameOptional(name string) (ok bool, opt *discordgo.ApplicationCommandInteractionDataOption) {
for _, c := range co {
if c.Name == name {
ok = true
opt = c
break
}
}
return
}

// GetByName returns an option by name.
//
// This should only be used on required options.
func (co CommandOptions) GetByName(name string) (opt *discordgo.ApplicationCommandInteractionDataOption) {
_, opt = co.GetByNameOptional(name)
return
}

0 comments on commit 0d0424a

Please sign in to comment.