From 75fe1bd03a571c1a3fc6f4752feae687eb1c4ce2 Mon Sep 17 00:00:00 2001 From: ks129 <45097959+ks129@users.noreply.github.com> Date: Sun, 24 May 2020 13:49:23 +0300 Subject: [PATCH] Implement command aliases - Add alias parsing to `Context.findCommand`. - Add new function to `Subcommand`: `AddAliases` that add new alias(es) to command. - Added `Aliases` property to `MethodContext` --- bot/command.go | 3 +++ bot/ctx_call.go | 12 ++++++++++++ bot/subcommand.go | 24 ++++++++++++++++++++++++ 3 files changed, 39 insertions(+) diff --git a/bot/command.go b/bot/command.go index 7f108eb..e6a8de6 100644 --- a/bot/command.go +++ b/bot/command.go @@ -85,6 +85,9 @@ type MethodContext struct { // Command is the Discord command used to call the method. Command string // plumb if empty + // Aliases is alternative way to call command in Discord. + Aliases []string + // Hidden if true will not be shown by (*Subcommand).HelpGenerate(). Hidden bool diff --git a/bot/ctx_call.go b/bot/ctx_call.go index f378687..4ca6eb1 100644 --- a/bot/ctx_call.go +++ b/bot/ctx_call.go @@ -322,6 +322,12 @@ func (ctx *Context) findCommand(parts []string) ([]string, *MethodContext, *Subc if c.Command == parts[0] { return parts[1:], c, ctx.Subcommand, nil } + // Check for alias + for _, alias := range c.Aliases { + if alias == parts[0] { + return parts[1:], c, ctx.Subcommand, nil + } + } } // Can't find the command, look for subcommands if len(args) has a 2nd @@ -343,6 +349,12 @@ func (ctx *Context) findCommand(parts []string) ([]string, *MethodContext, *Subc if c.Command == parts[1] { return parts[2:], c, s, nil } + // Check for aliases + for _, alias := range c.Aliases { + if alias == parts[1] { + return parts[2:], c, s, nil + } + } } } diff --git a/bot/subcommand.go b/bot/subcommand.go index 2e0ff01..d6c95d5 100644 --- a/bot/subcommand.go +++ b/bot/subcommand.go @@ -390,6 +390,30 @@ func (sub *Subcommand) SetPlumb(methodName string) { sub.plumbed = sub.FindCommand(methodName) } +// AddAliases add alias(es) to specific command (defined with MethodName). +// This removes silently all duplicate aliases. Use this instead overwriting aliases +// for safety reasons (duplicates). +func (sub *Subcommand) AddAliases(commandName string, aliases ...string) { + // Get command + command := sub.FindCommand(commandName) + + // Merge current aliases for duplicate removing + aliases = append(aliases, command.Aliases...) + + // Remove all duplicate aliases + keys := make(map[string]bool) + var uniqueAliases []string + for _, alias := range aliases { + if _, value := keys[alias]; !value { + keys[alias] = true + uniqueAliases = append(uniqueAliases, alias) + } + } + + // Write new listing of aliases + command.Aliases = uniqueAliases +} + func lowerFirstLetter(name string) string { return strings.ToLower(string(name[0])) + name[1:] }