1
0
Fork 0
mirror of https://github.com/diamondburned/arikawa.git synced 2024-11-08 07:54:58 +00:00
arikawa/bot/subcommand.go

405 lines
11 KiB
Go
Raw Normal View History

2020-01-19 06:06:00 +00:00
package bot
import (
"reflect"
"strings"
2020-01-26 09:06:54 +00:00
"github.com/diamondburned/arikawa/api"
"github.com/diamondburned/arikawa/discord"
2020-01-19 06:06:00 +00:00
"github.com/diamondburned/arikawa/gateway"
"github.com/pkg/errors"
)
var (
typeMessageCreate = reflect.TypeOf((*gateway.MessageCreateEvent)(nil))
2020-05-15 01:52:15 +00:00
typeMessageUpdate = reflect.TypeOf((*gateway.MessageUpdateEvent)(nil))
2020-01-26 09:06:54 +00:00
typeString = reflect.TypeOf("")
typeEmbed = reflect.TypeOf((*discord.Embed)(nil))
typeSend = reflect.TypeOf((*api.SendMessageData)(nil))
typeSubcmd = reflect.TypeOf((*Subcommand)(nil))
2020-01-19 06:06:00 +00:00
typeIError = reflect.TypeOf((*error)(nil)).Elem()
typeIManP = reflect.TypeOf((*ManualParser)(nil)).Elem()
typeICusP = reflect.TypeOf((*CustomParser)(nil)).Elem()
typeIParser = reflect.TypeOf((*Parser)(nil)).Elem()
2020-04-09 04:25:50 +00:00
typeIUsager = reflect.TypeOf((*Usager)(nil)).Elem()
2020-05-14 03:42:31 +00:00
typeSetupFn = methodType((*CanSetup)(nil), "Setup")
typeHelpFn = methodType((*CanHelp)(nil), "Help")
2020-01-19 06:06:00 +00:00
)
2020-05-14 03:42:31 +00:00
func methodType(iface interface{}, name string) reflect.Type {
method, _ := reflect.TypeOf(iface).
Elem().
MethodByName(name)
return method.Type
}
2020-04-10 06:10:21 +00:00
// HelpUnderline formats command arguments with an underline, similar to
// manpages.
var HelpUnderline = true
func underline(word string) string {
if HelpUnderline {
return "__" + word + "__"
}
return word
}
// Subcommand is any form of command, which could be a top-level command or a
// subcommand.
//
// Allowed method signatures
//
// These are the acceptable function signatures that would be parsed as commands
// or events. A return type <T> implies that return value will be ignored.
//
// func(*gateway.MessageCreateEvent, ...) (string, error)
// func(*gateway.MessageCreateEvent, ...) (*discord.Embed, error)
// func(*gateway.MessageCreateEvent, ...) (*api.SendMessageData, error)
// func(*gateway.MessageCreateEvent, ...) (T, error)
// func(*gateway.MessageCreateEvent, ...) error
// func(*gateway.MessageCreateEvent, ...)
// func(<AnyEvent>) (T, error)
// func(<AnyEvent>) error
// func(<AnyEvent>)
//
2020-01-19 06:06:00 +00:00
type Subcommand struct {
2020-05-14 03:42:31 +00:00
// Description is a string that's appended after the subcommand name in
// (*Context).Help().
2020-01-19 06:06:00 +00:00
Description string
2020-05-14 03:42:31 +00:00
// Hidden if true will not be shown by (*Context).Help(). It will
// also cause unknown command errors to be suppressed.
Hidden bool
// Raw struct name, including the flag (only filled for actual subcommands,
// will be empty for Context):
StructName string
// Parsed command name:
Command string
2020-01-29 00:01:39 +00:00
// SanitizeMessage is executed on the message content if the method returns
// a string content or a SendMessageData.
SanitizeMessage func(content string) string
2020-01-26 09:06:54 +00:00
// Commands can actually return either a string, an embed, or a
// SendMessageData, with error as the second argument.
// All registered method contexts:
Events []*MethodContext
Commands []*MethodContext
plumbed *MethodContext
2020-01-19 06:06:00 +00:00
2020-05-10 08:45:00 +00:00
// Global middlewares.
globalmws []*MiddlewareContext
2020-01-19 06:06:00 +00:00
// Directly to struct
cmdValue reflect.Value
cmdType reflect.Type
// Pointer value
ptrValue reflect.Value
ptrType reflect.Type
2020-05-14 03:42:31 +00:00
helper func() string
2020-01-19 06:06:00 +00:00
command interface{}
}
// CanSetup is used for subcommands to change variables, such as Description.
// This method will be triggered when InitCommands is called, which is during
// New for Context and during RegisterSubcommand for subcommands.
type CanSetup interface {
// Setup should panic when it has an error.
Setup(*Subcommand)
2020-01-19 06:06:00 +00:00
}
2020-05-14 03:42:31 +00:00
// CanHelp is an interface that subcommands can implement to return its own help
// message. Those messages will automatically be indented into suitable sections
// by the default Help() implementation. Unlike Usager or CanSetup, the Help()
// method will be called every time it's needed.
type CanHelp interface {
Help() string
}
// NewSubcommand is used to make a new subcommand. You usually wouldn't call
// this function, but instead use (*Context).RegisterSubcommand().
2020-01-19 06:06:00 +00:00
func NewSubcommand(cmd interface{}) (*Subcommand, error) {
var sub = Subcommand{
command: cmd,
2020-01-26 09:06:54 +00:00
SanitizeMessage: func(c string) string {
return c
},
2020-01-19 06:06:00 +00:00
}
if err := sub.reflectCommands(); err != nil {
2020-05-16 21:14:49 +00:00
return nil, errors.Wrap(err, "failed to reflect commands")
2020-01-19 06:06:00 +00:00
}
if err := sub.parseCommands(); err != nil {
2020-05-16 21:14:49 +00:00
return nil, errors.Wrap(err, "failed to parse commands")
2020-01-19 06:06:00 +00:00
}
return &sub, nil
}
// NeedsName sets the name for this subcommand. Like InitCommands, this
// shouldn't be called at all, rather you should use RegisterSubcommand.
func (sub *Subcommand) NeedsName() {
sub.StructName = sub.cmdType.Name()
2020-05-10 08:45:00 +00:00
sub.Command = lowerFirstLetter(sub.StructName)
2020-01-19 06:06:00 +00:00
}
// FindCommand finds the MethodContext. It panics if methodName is not found.
func (sub *Subcommand) FindCommand(methodName string) *MethodContext {
for _, c := range sub.Commands {
2020-05-10 08:45:00 +00:00
if c.MethodName == methodName {
return c
2020-04-09 06:06:46 +00:00
}
}
2020-05-10 08:45:00 +00:00
panic("Can't find method " + methodName)
2020-04-09 06:06:46 +00:00
}
// ChangeCommandInfo changes the matched methodName's Command and Description.
2020-05-14 03:42:31 +00:00
// Empty means unchanged. This function panics if methodName is not found.
func (sub *Subcommand) ChangeCommandInfo(methodName, cmd, desc string) {
var command = sub.FindCommand(methodName)
if cmd != "" {
command.Command = cmd
}
if desc != "" {
command.Description = desc
}
}
// Help calls the subcommand's Help() or auto-generates one with HelpGenerate()
// if the subcommand doesn't implement CanHelp.
func (sub *Subcommand) Help() string {
// Check if the subcommand implements CanHelp.
if sub.helper != nil {
return sub.helper()
}
return sub.HelpGenerate()
}
// HelpGenerate auto-generates a help message. Use this only if you want to
// override the Subcommand's help, else use Help().
func (sub *Subcommand) HelpGenerate() string {
// A wider space character.
const s = "\u2000"
var buf strings.Builder
for i, cmd := range sub.Commands {
if cmd.Hidden {
continue
}
2020-05-14 03:42:31 +00:00
buf.WriteString(sub.Command + " " + cmd.Command)
// Write the usages first.
for _, usage := range cmd.Usage() {
// Is the last argument trailing? If so, append ellipsis.
if cmd.Variadic {
usage += "..."
}
// Uses \u2000, which is wider than a space.
buf.WriteString(s + "__" + usage + "__")
}
2020-05-14 03:42:31 +00:00
// Write the description if there's any.
if cmd.Description != "" {
buf.WriteString(": " + cmd.Description)
}
2020-05-14 03:42:31 +00:00
// Add a new line if this isn't the last command.
if i != len(sub.Commands)-1 {
buf.WriteByte('\n')
}
}
2020-05-14 03:42:31 +00:00
return buf.String()
}
2020-05-14 03:42:31 +00:00
// Hide marks a command as hidden, meaning it won't be shown in help and its
// UnknownCommand errors will be suppressed.
func (sub *Subcommand) Hide(methodName string) {
sub.FindCommand(methodName).Hidden = true
2020-01-24 06:46:17 +00:00
}
2020-01-19 06:06:00 +00:00
func (sub *Subcommand) reflectCommands() error {
t := reflect.TypeOf(sub.command)
v := reflect.ValueOf(sub.command)
if t.Kind() != reflect.Ptr {
return errors.New("sub is not a pointer")
}
// Set the pointer fields
sub.ptrValue = v
sub.ptrType = t
ts := t.Elem()
vs := v.Elem()
if ts.Kind() != reflect.Struct {
return errors.New("sub is not pointer to struct")
}
// Set the struct fields
sub.cmdValue = vs
sub.cmdType = ts
return nil
}
// InitCommands fills a Subcommand with a context. This shouldn't be called at
// all, rather you should use the RegisterSubcommand method of a Context.
func (sub *Subcommand) InitCommands(ctx *Context) error {
// Start filling up a *Context field
if err := sub.fillStruct(ctx); err != nil {
return err
}
// See if struct implements CanSetup:
if v, ok := sub.command.(CanSetup); ok {
v.Setup(sub)
}
2020-05-14 03:42:31 +00:00
// See if struct implements CanHelper:
if v, ok := sub.command.(CanHelp); ok {
sub.helper = v.Help
}
return nil
}
func (sub *Subcommand) fillStruct(ctx *Context) error {
2020-01-19 06:06:00 +00:00
for i := 0; i < sub.cmdValue.NumField(); i++ {
field := sub.cmdValue.Field(i)
if !field.CanSet() || !field.CanInterface() {
continue
}
if _, ok := field.Interface().(*Context); !ok {
continue
}
field.Set(reflect.ValueOf(ctx))
return nil
}
2020-05-16 21:14:49 +00:00
return errors.New("no fields with *bot.Context found")
2020-01-19 06:06:00 +00:00
}
func (sub *Subcommand) parseCommands() error {
var numMethods = sub.ptrValue.NumMethod()
for i := 0; i < numMethods; i++ {
method := sub.ptrValue.Method(i)
if !method.CanInterface() {
continue
}
2020-05-10 08:45:00 +00:00
methodT := sub.ptrType.Method(i)
if methodT.Name == "Setup" && methodT.Type == typeSetupFn {
continue
}
2020-05-10 08:45:00 +00:00
cctx := parseMethod(method, methodT)
if cctx == nil {
2020-01-19 06:06:00 +00:00
continue
}
2020-05-10 08:45:00 +00:00
// Append.
if cctx.event == typeMessageCreate {
sub.Commands = append(sub.Commands, cctx)
} else {
sub.Events = append(sub.Events, cctx)
}
2020-05-10 08:45:00 +00:00
}
2020-01-19 06:06:00 +00:00
2020-05-10 08:45:00 +00:00
return nil
}
2020-01-24 06:27:21 +00:00
2020-05-14 03:42:31 +00:00
// AddMiddleware adds a middleware into multiple or all methods, including
// commands and events. Multiple method names can be comma-delimited. For all
// methods, use a star (*).
2020-05-10 08:45:00 +00:00
func (sub *Subcommand) AddMiddleware(methodName string, middleware interface{}) {
var mw *MiddlewareContext
// Allow *MiddlewareContext to be passed into.
if v, ok := middleware.(*MiddlewareContext); ok {
mw = v
} else {
mw = ParseMiddleware(middleware)
}
2020-01-19 06:06:00 +00:00
2020-05-10 08:45:00 +00:00
// Parse method name:
for _, method := range strings.Split(methodName, ",") {
// Trim space.
if method = strings.TrimSpace(method); method == "*" {
// Append middleware to global middleware slice.
sub.globalmws = append(sub.globalmws, mw)
2020-05-14 03:42:31 +00:00
continue
2020-01-26 09:06:54 +00:00
}
2020-05-14 03:42:31 +00:00
// Append middleware to that individual function.
sub.findMethod(method).addMiddleware(mw)
2020-05-10 08:45:00 +00:00
}
}
2020-01-26 09:06:54 +00:00
2020-05-14 03:42:31 +00:00
func (sub *Subcommand) findMethod(name string) *MethodContext {
for _, ev := range sub.Events {
if ev.MethodName == name {
return ev
}
2020-05-10 08:45:00 +00:00
}
2020-05-14 03:42:31 +00:00
return sub.FindCommand(name)
2020-05-10 08:45:00 +00:00
}
2020-05-10 08:45:00 +00:00
func (sub *Subcommand) eventCallers(evT reflect.Type) (callers []caller) {
// Search for global middlewares.
for _, mw := range sub.globalmws {
if mw.isEvent(evT) {
callers = append(callers, mw)
}
2020-05-10 08:45:00 +00:00
}
2020-05-10 08:45:00 +00:00
// Search for specific handlers.
for _, cctx := range sub.Events {
2020-05-10 08:45:00 +00:00
// We only take middlewares and callers if the event matches and is not
// a MessageCreate. The other function already handles that.
if cctx.isEvent(evT) {
2020-05-10 08:45:00 +00:00
// Add the command's middlewares first.
for _, mw := range cctx.middlewares {
// Concrete struct to interface conversion done implicitly.
callers = append(callers, mw)
2020-01-19 06:06:00 +00:00
}
2020-05-10 08:45:00 +00:00
callers = append(callers, cctx)
}
2020-05-10 08:45:00 +00:00
}
return
}
2020-05-14 03:42:31 +00:00
// SetPlumb sets the method as the plumbed command.
2020-05-10 08:45:00 +00:00
func (sub *Subcommand) SetPlumb(methodName string) {
2020-05-14 03:42:31 +00:00
sub.plumbed = sub.FindCommand(methodName)
2020-01-19 06:06:00 +00:00
}
// AddAliases add alias(es) to specific command (defined with commandName).
func (sub *Subcommand) AddAliases(commandName string, aliases ...string) {
// Get command
command := sub.FindCommand(commandName)
// Write new listing of aliases
command.Aliases = append(command.Aliases, aliases...)
}
func lowerFirstLetter(name string) string {
return strings.ToLower(string(name[0])) + name[1:]
}