1
0
Fork 0
mirror of https://github.com/diamondburned/arikawa.git synced 2024-11-27 17:23:00 +00:00

Bot: Added ArgsParser for each Context instead of global

This commit is contained in:
diamondburned (Forefront) 2020-05-05 23:23:52 -07:00
parent 7dbdc78d67
commit 85c1326526
6 changed files with 16 additions and 8 deletions

View file

@ -5,8 +5,6 @@ import (
"reflect"
"strconv"
"strings"
"github.com/diamondburned/arikawa/bot/shellwords"
)
type argumentValueFn func(string) (reflect.Value, error)
@ -117,10 +115,6 @@ var ShellwordsEscaper = strings.NewReplacer(
"\\", "\\\\",
)
var ParseArgs = func(args string) ([]string, error) {
return shellwords.Parse(args)
}
// nilV, only used to return an error
var nilV = reflect.Value{}

View file

@ -7,6 +7,7 @@ import (
"strings"
"sync"
"github.com/diamondburned/arikawa/bot/extras/shellwords"
"github.com/diamondburned/arikawa/gateway"
"github.com/diamondburned/arikawa/state"
"github.com/pkg/errors"
@ -29,7 +30,15 @@ func NewPrefix(prefixes ...string) Prefixer {
}
}
// TODO: add variadic arguments
// ArgsParser is the function type for parsing message content into fields,
// usually delimited by spaces.
type ArgsParser func(content string) ([]string, error)
// DefaultArgsParser implements a parser similar to that of shell's,
// implementing quotes as well as escapes.
func DefaultArgsParser() ArgsParser {
return shellwords.Parse
}
// Context is the bot state for commands and subcommands.
//
@ -73,6 +82,9 @@ type Context struct {
// Descriptive help body
Description string
// Called to parse message content, default to DefaultArgsParser().
ParseArgs ArgsParser
// Called to check a message's prefix. The default prefix is "!". Refer to
// NewPrefix().
HasPrefix Prefixer
@ -178,6 +190,7 @@ func New(s *state.State, cmd interface{}) (*Context, error) {
ctx := &Context{
Subcommand: c,
State: s,
ParseArgs: DefaultArgsParser(),
HasPrefix: NewPrefix("~"),
FormatError: func(err error) string {
// Escape all pings, including @everyone.

View file

@ -154,7 +154,7 @@ func (ctx *Context) callMessageCreate(mc *gateway.MessageCreateEvent) error {
}
// parse arguments
parts, err := ParseArgs(content)
parts, err := ctx.ParseArgs(content)
if err != nil {
return errors.Wrap(err, "Failed to parse command")
}

View file

@ -90,6 +90,7 @@ func TestContext(t *testing.T) {
var ctx = &Context{
Subcommand: s,
State: state,
ParseArgs: DefaultArgsParser(),
}
t.Run("init commands", func(t *testing.T) {