Brigodier is a command parser & dispatcher, designed and developed for command lines such as for Discord bots or Minecraft chat commands. It is a complete port from Mojang's "brigadier" into Go.

brigodier

GitHub release (latest SemVer) Doc GitHub go.mod Go version Go Report Card test Discord

Brigodier is a command parser & dispatcher, designed and developed to provide a simple and flexible command framework.

It can be used in many command-line environments such as for chat commands in the Minecraft Java Edition.

It is completely ported to Go from Mojang's Brigadier (written in Java), including all features and tests.

Installation

For use in your projects go get it with:

go get -u go.minekube.com/brigodier

Usage

At the heart of Brigodier, you need a Dispatcher.

A command dispatcher holds a "command tree", which is a series of CommandNodes that represent the various possible syntax options that form a valid command.

Registering a new command

Before we can start parsing and dispatching commands, we need to build up our command tree. Every registration is an append operation, so you can freely extend existing commands in a project without needing access to the source code that created them.

Command registration also encourages the use of a builder pattern to keep code cruft to a minimum.

A "command" is a fairly loose term, but typically it means an exit point of the command tree. Every node can have an Executes function attached to it, which signifies that if the input stops here then this function will be called with the context so far.

Consider the following example:

var d Dispatcher

d.Register(
	Literal("foo").Then(
		Argument("bar", Int).
			Executes(CommandFunc(func(c *CommandContext) error {
				fmt.Println("Bar is", c.Int("bar"))
				return nil
			})),
	).Executes(CommandFunc(func(c *CommandContext) error {
		fmt.Println("Called foo with no arguments")
		return nil
	})),
)

This snippet registers two "commands": foo and foo <bar>. It is also common to refer to the <bar> as a "subcommand" of foo, as it's a child node.

At the start of the tree is a "root node", and it must have LiteralCommandNodes as children. Here, we register one command under the root: Literal("foo"), which means "the user must type the literal string 'foo'".

Under that is two extra definitions: a child node for possible further evaluation, or an executes block if the user input stops here.

The child node works exactly the same way, but is no longer limited to literals. The other type of node that is now allowed is an ArgumentCommandNode, which takes in a name, and an argument type.

Arguments can be anything, and you are encouraged to build your own for seamless integration into your own product. There are some builtin ArgumentTypes included, such as Int or String.

Argument types will be asked to parse input as much as they can, and then store the "result" of that argument however they see fit or throw a relevant error if they can't parse.

For example, an integer argument would parse "123" and store it as 123 (int), but throw an error if the input were onetwothree.

When a command function runs, it can access these arguments in the context provided to the registered function.

Parsing user input

So, we've registered some commands, and now we're ready to take in user input. If you're in a rush, you can just call dispatcher.Execute(ctx, "foo 123") and call it a day.

Go's context.Context can be used to track users/players/etc and will be provided to the command to give context on what's happening (e.g., who has run the command).

If the command failed or could not parse, some form of CommandSyntaxError will be returned, or the error that the Command returned.

If you wish to have more control over the parsing & executing of commands, or wish to cache the parse results, so you can execute it multiple times, you can split it up into two steps:

parse := dispatcher.Parse(ctx, "foo 123")
err := dispatcher.Execute(parse)

This is highly recommended as the parse step is the most expensive, and may be easily cached depending on your application.

You can also use this to do further introspection on a command, before (or without) actually running it.

The convenient method to parse and execute a command is:

err := dispatcher.Do(ctx, "foo 123")

Inspecting a command

If you Parse some input, you can find out what it will perform (if anything) and provide hints to the user safely and immediately.

The parse will never fail, and the ParseResults it returns will contain a possible context that a command may be called with (and from that, you can inspect which nodes the user entered, complete with start/end positions in the input string). It also contains a map of parse exceptions for each command node it encountered. If it couldn't build a valid context, then the reason is inside this exception map.

Displaying usage info

There are two forms of "usage strings" provided by this library, both require a target node.

  • dispatcher.AllUsage(ctx, node, restricted) will return a list of all possible commands (executable end-points) under the target node and their human-readable path. If restricted, it will ignore commands that ctx does not have access to. This will look like [foo, foo <bar>].

  • dispatcher.SmartUsage(ctx, node) will return a map of the child nodes to their "smart usage" human-readable path. This tries to squash future-nodes together and show optional & typed information, and can look like foo (<bar>).

Owner
Minekube
We are dedicated to make running Minecraft cloud native combining Kubernetes and best of breed open source projects!
Minekube
Similar Resources

Command-line tool to load csv and excel (xlsx) files and run sql commands

Command-line tool to load csv and excel (xlsx) files and run sql commands

csv-sql supports loading and saving results as CSV and XLSX files with data processing with SQLite compatible sql commands including joins.

Nov 2, 2022

GC2 is a Command and Control application that allows an attacker to execute commands on the target machine using Google Sheet and exfiltrate data using Google Drive.

GC2 is a Command and Control application that allows an attacker to execute commands on the target machine using Google Sheet and exfiltrate data using Google Drive.

GC2 GC2 (Google Command and Control) is a Command and Control application that allows an attacker to execute commands on the target machine using Goog

Dec 13, 2022

Yikes is a cli-application to simplify the process to maintaining a list of tasks to complete.

yikes Yikes is a cli-application to simplify the process to maintaining a list of tasks to complete. It also has commands to help store random notes a

Oct 7, 2021

A CLI application that allows you to run a complete ToDo app from your terminal application

todo-cli This is a CLI application that allows you to run a complete ToDo app from your terminal application. As a user you can: Create a list of todo

Oct 11, 2021

Viper: a complete configuration solution for Go applications including 12-Factor apps

Viper: a complete configuration solution for Go applications including 12-Factor apps

Viper v2 feedback Viper is heading towards v2 and we would love to hear what you would like to see in it. Share your thoughts here: https://forms.gle/

Dec 6, 2021

ReverseSSH - a statically-linked ssh server with reverse shell functionality for CTFs and such

 ReverseSSH - a statically-linked ssh server with reverse shell functionality for CTFs and such

ReverseSSH A statically-linked ssh server with a reverse connection feature for simple yet powerful remote access. Most useful during HackTheBox chall

Jan 5, 2023

A highly-scalable, entity-resolution technology that was originally developed to connect internal data together

TiloRes CLI What is TiloRes? TiloRes is a highly-scalable, “entity-resolution” technology that was originally developed to connect internal data toget

Jun 17, 2022

steal minecraft (bedrock) skins

skinsteal steal everyone on the servers skin ❤️ to gophertunnel for being awesome https://streamable.com/7niuie to setup: build main.go run output bin

May 10, 2021

steal minecraft (bedrock) skins

skinsteal steal everyone on the servers skin ❤️ to gophertunnel for being awesome https://streamable.com/7niuie to setup: build main.go run output bin

Jul 14, 2021
Comments
  • Configure Renovate

    Configure Renovate

    Mend Renovate

    Welcome to Renovate! This is an onboarding PR to help you understand and configure settings before regular Pull Requests begin.

    🚦 To activate Renovate, merge this Pull Request. To disable Renovate, simply close this Pull Request unmerged.


    Detected Package Files

    • .github/workflows/workflow.yml (github-actions)
    • go.mod (gomod)

    Configuration Summary

    Based on the default config's presets, Renovate will:

    • Start dependency updates only once this onboarding PR is merged
    • Enable Renovate Dependency Dashboard creation.
    • If Renovate detects semantic commits, it will use semantic commit type fix for dependencies and chore for all others.
    • Ignore node_modules, bower_components, vendor and various test/tests directories.
    • Autodetect whether to pin dependencies or maintain ranges.
    • Rate limit PR creation to a maximum of two per hour.
    • Limit to maximum 10 open PRs at any time.
    • Group known monorepo packages together.
    • Use curated list of recommended non-monorepo package groupings.
    • A collection of workarounds for known problems with packages.

    🔡 Would you like to change the way Renovate is upgrading your dependencies? Simply edit the renovate.json in this branch with your custom config and the list of Pull Requests in the "What to Expect" section below will be updated the next time Renovate runs.


    What to Expect

    With your current configuration, Renovate will create 2 Pull Requests:

    Update module github.com/emirpasic/gods to v1.18.1
    • Schedule: ["at any time"]
    • Branch name: renovate/github.com-emirpasic-gods-1.x
    • Merge into: main
    • Upgrade github.com/emirpasic/gods to v1.18.1
    Update module github.com/stretchr/testify to v1.8.1
    • Schedule: ["at any time"]
    • Branch name: renovate/github.com-stretchr-testify-1.x
    • Merge into: main
    • Upgrade github.com/stretchr/testify to v1.8.1

    ❓ Got questions? Check out Renovate's Docs, particularly the Getting Started section. If you need any further assistance then you can also request help here.


    This PR has been generated by Mend Renovate. View repository job log here.

Fast, realtime regex-extraction, and aggregation into common formats such as histograms, numerical summaries, tables, and more!
Fast, realtime regex-extraction, and aggregation into common formats such as histograms, numerical summaries, tables, and more!

rare A file scanner/regex extractor and realtime summarizor. Supports various CLI-based graphing and metric formats (histogram, table, etc). Features

Dec 29, 2022
painless task queue manager for shell commands with an intuitive cli interface (execute shell commands in distributed cloud-native queue manager).

EXEQ DOCS STILL IN PROGRESS. Execute shell commands in queues via cli or http interface. Features Simple intuitive tiny cli app. Modular queue backend

Dec 14, 2022
A CLI to execute AT Commands via serial port connections.
A CLI to execute AT Commands via serial port connections.

AT Command CLI A CLI to execute AT Commands via serial port connections. Development Install Go Run go run main.go

Dec 13, 2022
Tool to capture C/C++ compiler command lines for use by Sonargraph

ccspy Tool to capture C/C++ compiler command lines for use by Sonargraph-Architect. Purpose of the Tool When Sonargraph analyzes C/C++ code it must kn

Dec 7, 2021
Simple and complete API for building command line applications in Go

Simple and complete API for building command line applications in Go Module cli provides a simple, fast and complete API for building command line app

Nov 23, 2022
webify - Turn functions and commands into web services
webify - Turn functions and commands into web services

webify is a very basic CGI server which forwards all requests to a single script. A design goal is to be as zero-config as possible.

Dec 22, 2022
Command line tools for creating and compiling JavaScript Minecraft plugins.

@customrealms/cli CustomRealms command-line tools for setting up and compiling JavaScript Minecraft plugins. Installation Install the CLI on your comp

Aug 2, 2022
A go library for easy configure and run command chains. Such like pipelining in unix shells.

go-command-chain A go library for easy configure and run command chains. Such like pipelining in unix shells. Example cat log_file.txt | grep error |

Dec 27, 2022
Use go to count file's lines and print them.

用法 go run staticCodeLine.go -p [root path] -s [suffix name] -e [exclude dirs] 如果 -e 有多个参数,多次输入 -e [suffix name]。 ╰─± go run statisticCodeLine.go -p /U

Dec 12, 2022
A tool that finds and removes unnecessary lines from .gitignore files.

Allyignore A tool that finds and removes unnecessary lines from .gitignore files. Installation > go install github.com/Allyedge/allyignore@latest Usag

May 10, 2022