From 0d0424a82c400730c5d69154a7e331ca73e22283 Mon Sep 17 00:00:00 2001 From: Ringo Hoffmann Date: Tue, 5 Oct 2021 09:54:21 +0200 Subject: [PATCH] add options handler --- context.go | 6 ++++ example/middlewares/commands/kick.go | 4 +-- options.go | 50 ++++++++++++++++++++++++++++ 3 files changed, 58 insertions(+), 2 deletions(-) create mode 100644 options.go diff --git a/context.go b/context.go index 0011958..20daaed 100644 --- a/context.go +++ b/context.go @@ -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 +} diff --git a/example/middlewares/commands/kick.go b/example/middlewares/commands/kick.go index b2260ae..0f028c6 100644 --- a/example/middlewares/commands/kick.go +++ b/example/middlewares/commands/kick.go @@ -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 diff --git a/options.go b/options.go new file mode 100644 index 0000000..2ca9bef --- /dev/null +++ b/options.go @@ -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 +}