commands

package
v1.0.11 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2025 License: BSD-3-Clause Imports: 3 Imported by: 0

README

commands Go Reference

dead simple command handler & registerer.

getting started
package main

import (
	"codeberg.org/Yonle/irc/commands"
)

var cmds commands.Commands = make(commands.Commands)

in another code file:

package main

import (
	"codeberg.org/Yonle/irc"
	"codeberg.org/Yonle/irc/commands"
)

// assuming this code is for "ping" command

func init() {
	cmds.RegisterCommand("ping", func (conn io.Writer, user irc.User, to, _ string) {
		irc.Chat(conn, to, user.Nick + ": Pong!")
	})
}

then, let the helper listen to messages in your scanner:

var cmds commands.Commands
for s.Scan() {
	// ...
	user, cmd, flags, fullmsg := irc.ParseLine(line)
	if cmd == "PRIVMSG" {
		msg, hasPrefix := strings.CutPrefix(fullmsg, "!") // assuming ! is your bot's prefix
		if !hasPrefix {
			continue // ignore message that has no bot prefix
		}

		to := flags[0]

		if to == botnick {
			to = user.Nick // this is PM
		}

		invalid := cmds.ReadMessage(conn, user, to, msg)
		if invalid {
			irc.Chat(conn, to, fmt.Sprintf("%s: Unknown command", user.Nick))
		}
	}
}

finally, boot up your bot, and send !ping. it should replies.

<Anon> !ping
<ircbot> Anon: Pong!

documentation

press this: Go Reference

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CommandRunFunc

type CommandRunFunc func(w io.Writer, user irc.User, to, args string)

type Commands

type Commands map[string]CommandRunFunc

func (Commands) ReadMessage

func (s Commands) ReadMessage(w io.Writer, user irc.User, to, msg string) (invalid bool)

Message Reader. Prefix must be manually cutted. Every run function provided by a command will be run with goroutine.

var cmds commands.Commands
for s.Scan() {
	// ...
	user, cmd, flags, fullmsg := irc.ParseLine(line)
	if cmd == "PRIVMSG" {
		msg, hasPrefix := strings.CutPrefix(fullmsg, "!") // assuming ! is your bot's prefix
		if !hasPrefix {
			continue // ignore message that has no bot prefix
		}

		to := flags[0]

		if to == botnick {
			to = user.Nick // this is PM
		}

		invalid := cmds.ReadMessage(conn, user, to, msg)
		if invalid {
			irc.Chat(conn, to, fmt.Sprintf("%s: Unknown command", user.Nick))
		}
	}
}

func (Commands) RegisterCommand

func (s Commands) RegisterCommand(name string, run CommandRunFunc) (overrided bool)

Command registerer. `overrided` may return false if existing command has been registered in a map.

Jump to

Keyboard shortcuts

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