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`
This commit is contained in:
ks129 2020-05-24 13:49:23 +03:00 committed by diamondburned
parent 960ba486bd
commit 75fe1bd03a
3 changed files with 39 additions and 0 deletions

View File

@ -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

View File

@ -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
}
}
}
}

View File

@ -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:]
}