dgc

package module
v0.0.0-...-a89f3bd Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 21, 2020 License: MIT Imports: 8 Imported by: 0

README

dgc

A DiscordGo command router with tons of useful features

If you find any bugs or if you have a feature request, please tell me by creating an issue.

Usage

Here's a commented example which should help you using this library:

func main() {
    // Open a simple Discord session
    token := "Your token"
    session, err := discordgo.New("Bot " + token)
    if err != nil {
        panic(err)
    }
    err = session.Open()
    if err != nil {
        panic(err)
    }

    // Create a dgc router
    // NOTE: The dgc.Create function makes sure all internal and external maps of the struct get initialized, so you should use it in every case!
    router := dgc.Create(&dgc.Router{
        // We will allow '!', '$' and the bot mention as command prefixes
        // NOTE: The first prefix (in our case '!') will be used as the prefix in the default help messages
        Prefixes: []string{
            "!",
            "$",
            "<@!" + session.State.User.ID + ">",
        },

        // Whether or not the parser should ignore the case of our prefixes (this would be redundant in our case)
        IgnorePrefixCase: false,

        // Whether or not bots should be allowed to execute our commands
        BotsAllowed: false,

        // We can define commands in here, but in this example we will use the provided method (later)
        Commands: []*dgc.Command{
            // ...
        },

        // We can define middlewares in here, but in this example we will use the provided method (later)
        Middlewares: map[string][]dgc.Middleware{
            // ...
        },

        // The ping handler will be executed if the message only contains the bot's mention (no arguments)
        PingHandler: func(ctx *dgc.Ctx) {
            _, err := ctx.Session.ChannelMessageSend(ctx.Event.ChannelID, "Pong!")
            if err != nil {
                // Error handling
            }
        },
    })

    // Add a simple command
    router.RegisterCmd(&dgc.Command{
        // The general name of the command
        Name: "hey",

        // The aliases of the command
        Aliases: []string{
            "hi",
            "hello",
        },

        // A brief description of the commands functionality
        Description: "Greets you",

        // The correct usage of the command
        Usage: "hey",

        // An example how to use the command
        Example: "hey",

        // Commands may have flags. They will be used for middleware selection and can also be used for grouping
        Flags: []string{
            "greeting",
        },

        // Whether or not the parser should ignore the case of our command
        IgnoreCase: true,

        // A list of sub commands
        SubCommands: []*dgc.Command{
            &dgc.Command{
                Name: "world",
                Description: "Greets the world",
                Usage: "hey world",
                Example: "greet world",
                Flags: []string{
                    "greeting",
                },
                IgnoreCase: true,
                Handler: func(ctx *dgc.Ctx) {
                    _, err := ctx.Session.ChannelMessageSend(ctx.Event.ChannelID, "Hello, world.")
                    if err != nil {
                        // Error handling
                    }
                },
            },
        },

        // dgc supports rate limiting. You can define a rate limiter here.
        RateLimiter: dgc.NewRateLimiter(5*time.Second, 2*time.Second, func (ctx *Ctx) {
            _, err := ctx.Sesion.ChannelMessageSend(ctx.Event.ChannelID, "You are being rate limited!")
            if err != nil {
                // Error handling
            }

            // HINT: You can get the timestamp when the next execution is allowed like this:
            nextExecution := ctx.CustomObjects.MustGet("dgc_nextExecution").(time.Time)
        }),

        // The handler of the command
        Handler: func(ctx *dgc.Ctx) {
            _, err := ctx.Session.ChannelMessageSend(ctx.Event.ChannelID, "Hello.")
            if err != nil {
                // Error handling
            }
        },
    })

    // Add a simple middleware that injects a custom object into the context
    // This middleware will be executed on every command, because we wildcard it using the '*'
    // NOTE: You have to return true or false. If you return false, the command will not be executed
    router.AddMiddleware("*", func(ctx *dgc.Ctx) bool {
        // Inject a custom object into the context
        ctx.CustomObjects.Set("myObjectName", "Hello, world")
        return true
    })

    // This middleware will only be executed for commands that implement the 'greeting' flag
    router.AddMiddleware("greeting", func(ctx *dgc.Ctx) bool {
        // Inject a custom object into the context
        ctx.CustomObjects.Set("foo", "bar")
        return true
    })

    // Enable the default help command
    router.RegisterDefaultHelpCommand(session, nil)

    // Initialize the router to make it functional
    router.Initialize(session)
}

Arguments

This library provides an enhanced argument parsing system. The following example will show you how to use it:

func SimpleCommandHandler(ctx *dgc.Ctx) {
    // Retrieve the arguments out of the context
    arguments := ctx.Arguments

    // Print all the arguments with spaces between each other to the console
    fmt.Println(arguments.Raw())

    // Print the amount of given arguments to the console
    fmt.Println(arguments.Amount())


    // Get the first argument
    argument := arguments.Get(0) // will be an argument with an emoty raw string if there is no argument at this index

    // Print it's raw value to the console
    fmt.Println(argument.Raw())

    // Parse the argument into a boolean
    parsedBool, err := argument.AsBool()
    if err != nil {
        // argument is no boolean
    }

    // Parse the argument into an int32
    parsedInt, err := argument.AsInt()
    if err != nil {
        // argument is no int32
    }
    // NOTE: You can use similiar methods (ex. AsInt8, AsInt16...) to parse the argument into these values

    // Parse the argument into a user ID if it is a user mention
    userID := argument.AsUserMentionID()
    if userID == "" {
        // argument is no user mention
    }
    // NOTE: You can also use the methods AsRoleMentionID and AsChannelMentionID
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// RegexArguments defines the regex the argument string has to match
	RegexArguments = regexp.MustCompile("(\"[^\"]+\"|[^\\s]+)")

	// RegexUserMention defines the regex a user mention has to match
	RegexUserMention = regexp.MustCompile("<@!?(\\d+)>")

	// RegexRoleMention defines the regex a role mention has to match
	RegexRoleMention = regexp.MustCompile("<@&(\\d+)>")

	// RegexChannelMention defines the regex a channel mention has to match
	RegexChannelMention = regexp.MustCompile("<#(\\d+)>")

	// RegexBigCodeblock defines the regex a big codeblock has to match
	RegexBigCodeblock = regexp.MustCompile("(?s)\\n*```(?:([\\w.\\-]*)\\n)?(.*)```")

	// RegexSmallCodeblock defines the regex a small codeblock has to match
	RegexSmallCodeblock = regexp.MustCompile("(?s)\\n*`(.*)`")

	// CodeblockLanguages defines which languages are valid codeblock languages
	CodeblockLanguages = []string{}/* 315 elements not displayed */

)

Functions

This section is empty.

Types

type Argument

type Argument struct {
	// contains filtered or unexported fields
}

Argument represents a single argument

func (*Argument) AsBool

func (argument *Argument) AsBool() (bool, error)

AsBool parses the given argument into a boolean

func (*Argument) AsChannelMentionID

func (argument *Argument) AsChannelMentionID() string

AsChannelMentionID returns the ID of the mentioned channel or an empty string if it is no mention

func (*Argument) AsInt

func (argument *Argument) AsInt() (int, error)

AsInt parses the given argument into an int32

func (*Argument) AsInt64

func (argument *Argument) AsInt64() (int64, error)

AsInt64 parses the given argument into an int64

func (*Argument) AsRoleMentionID

func (argument *Argument) AsRoleMentionID() string

AsRoleMentionID returns the ID of the mentioned role or an empty string if it is no mention

func (*Argument) AsUserMentionID

func (argument *Argument) AsUserMentionID() string

AsUserMentionID returns the ID of the mentioned user or an empty string if it is no mention

func (*Argument) Raw

func (argument *Argument) Raw() string

Raw returns the raw string value of the argument

type Arguments

type Arguments struct {
	// contains filtered or unexported fields
}

Arguments represents the arguments that may be used in a command context

func ParseArguments

func ParseArguments(raw string) *Arguments

ParseArguments parses the raw string into several arguments

func (*Arguments) Amount

func (arguments *Arguments) Amount() int

Amount returns the amount of given arguments

func (*Arguments) AsCodeblock

func (arguments *Arguments) AsCodeblock() *Codeblock

AsCodeblock parses the given arguments as a codeblock

func (*Arguments) AsSingle

func (arguments *Arguments) AsSingle() *Argument

AsSingle parses the given arguments as a single one

func (*Arguments) Get

func (arguments *Arguments) Get(n int) *Argument

Get returns the n'th argument

func (*Arguments) Raw

func (arguments *Arguments) Raw() string

Raw returns the raw string value of the arguments

type Codeblock

type Codeblock struct {
	Language string
	Content  string
}

Codeblock represents a Discord codeblock

type Command

type Command struct {
	Name        string
	Aliases     []string
	Description string
	Usage       string
	Example     string
	Flags       []string
	IgnoreCase  bool
	SubCommands []*Command
	Handler     ExecutionHandler
}

Command represents a simple command

func (*Command) GetSubCmd

func (command *Command) GetSubCmd(name string) *Command

GetSubCmd returns the sub command with the given name if it exists

type Ctx

type Ctx struct {
	Session   *discordgo.Session
	Event     *discordgo.MessageCreate
	Arguments *Arguments
	Router    *Router
	Command   *Command
}

Ctx represents the context for a command event

type ExecutionHandler

type ExecutionHandler func(*Ctx)

ExecutionHandler represents a handler for a context execution

type Middleware

type Middleware func(*Ctx) bool

Middleware defines how a middleware looks like

type Router

type Router struct {
	Prefixes         []string
	IgnorePrefixCase bool
	BotsAllowed      bool
	Commands         []*Command
	Middlewares      map[string][]Middleware
	PingHandler      ExecutionHandler
	// contains filtered or unexported fields
}

Router represents a DiscordGo command router

func Create

func Create(router *Router) *Router

Create creates a new router and makes sure that all maps get initialized

func (*Router) AddMiddleware

func (router *Router) AddMiddleware(flag string, middleware Middleware)

AddMiddleware adds a new middleware

func (*Router) GetCmd

func (router *Router) GetCmd(name string) *Command

GetCmd returns the command with the given name if it exists

func (*Router) Initialize

func (router *Router) Initialize(session *discordgo.Session)

Initialize initializes the message event listener

func (*Router) RegisterCmd

func (router *Router) RegisterCmd(command *Command)

RegisterCmd registers a new command

func (*Router) RegisterDefaultHelpCommand

func (router *Router) RegisterDefaultHelpCommand(session *discordgo.Session)

RegisterDefaultHelpCommand registers the default help command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL