Skip to content

Commit

Permalink
feat: Introduce Command Aliases (#141)
Browse files Browse the repository at this point in the history
  • Loading branch information
raed-shomali authored Jul 30, 2023
1 parent 0722a13 commit 22775bb
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 1 deletion.
25 changes: 24 additions & 1 deletion command.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
// CommandDefinition structure contains definition of the bot command
type CommandDefinition struct {
Command string
Aliases []string
Description string
Examples []string
Middlewares []CommandMiddlewareHandler
Expand All @@ -19,9 +20,15 @@ type CommandDefinition struct {

// newCommand creates a new bot command object
func newCommand(definition *CommandDefinition) Command {
cmdAliases := make([]*commander.Command, 0)
for _, alias := range definition.Aliases {
cmdAliases = append(cmdAliases, commander.NewCommand(alias))
}

return &command{
definition: definition,
cmd: commander.NewCommand(definition.Command),
cmdAliases: cmdAliases,
}
}

Expand All @@ -37,6 +44,7 @@ type Command interface {
type command struct {
definition *CommandDefinition
cmd *commander.Command
cmdAliases []*commander.Command
}

// Definition returns the command definition
Expand All @@ -46,7 +54,22 @@ func (c *command) Definition() *CommandDefinition {

// Match determines whether the bot should respond based on the text received
func (c *command) Match(text string) (*proper.Properties, bool) {
return c.cmd.Match(text)
properties, isMatch := c.cmd.Match(text)
if isMatch {
return properties, isMatch
}

allCommands := make([]*commander.Command, 0)
allCommands = append(allCommands, c.cmd)
allCommands = append(allCommands, c.cmdAliases...)

for _, cmd := range allCommands {
properties, isMatch := cmd.Match(text)
if isMatch {
return properties, isMatch
}
}
return nil, false
}

// Tokenize returns the command format's tokens
Expand Down
39 changes: 39 additions & 0 deletions examples/command-aliases/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package main

import (
"context"
"log"
"os"

"github.com/shomali11/slacker/v2"
)

// Defining a command with aliases

func main() {
bot := slacker.NewClient(os.Getenv("SLACK_BOT_TOKEN"), os.Getenv("SLACK_APP_TOKEN"))
bot.AddCommand(&slacker.CommandDefinition{
Command: "echo {word}",
Aliases: []string{
"repeat {word}",
"mimic {word}",
},
Description: "Echo a word!",
Examples: []string{
"echo hello",
"repeat hello",
"mimic hello",
},
Handler: func(ctx *slacker.CommandContext) {
word := ctx.Request().Param("word")
ctx.Response().Reply(word)
},
})
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

err := bot.Listen(ctx)
if err != nil {
log.Fatal(err)
}
}

0 comments on commit 22775bb

Please sign in to comment.