bot

package
v0.0.0-...-713866f Latest Latest
Warning

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

Go to latest
Published: Jun 3, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package bot 提供命令路由、事件路由和回复分发。

Index

Constants

View Source
const (
	EnvOneBotToken = "MICQ_ONEBOT_TOKEN"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Bot

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

func New

func New(runtime Runtime) (*Bot, error)

New constructs a Bot from a resolved Runtime. It creates ConfigDir/DataDir on demand and wires the default OneBot client.

func (*Bot) BroadcastGroups

func (b *Bot) BroadcastGroups(message msg.Message)

func (*Bot) Call

func (b *Bot) Call(ctx context.Context, action string, params any) (json.RawMessage, error)

func (*Bot) CommandHints

func (b *Bot) CommandHints() CommandHints

func (*Bot) Connected

func (b *Bot) Connected() bool

func (*Bot) On

func (b *Bot) On(match Match, h HandlerFunc, opts ...MatchOption)

func (*Bot) OnCommand

func (b *Bot) OnCommand(verb string, h HandlerFunc, args ...any)

func (*Bot) OnEvent

func (b *Bot) OnEvent(kind EventKind, h EventHandlerFunc, opts ...EventMatchOption)

func (*Bot) OnMessage

func (b *Bot) OnMessage(h HandlerFunc, opts ...MatchOption)

func (*Bot) Run

func (b *Bot) Run(ctx context.Context) error

func (*Bot) Runtime

func (b *Bot) Runtime() Runtime

Runtime returns the resolved runtime layout the bot was constructed with.

func (*Bot) SendGroup

func (b *Bot) SendGroup(groupID int64, message msg.Message) error

func (*Bot) SendPrivate

func (b *Bot) SendPrivate(userID int64, message msg.Message) error

func (*Bot) UsePlugin

func (b *Bot) UsePlugin(plugin Plugin) error

func (*Bot) Verbs

func (b *Bot) Verbs() []string

type CommandHints

type CommandHints struct {
	Prefixes []string
}

type Config

type Config struct {
	URL            string   `yaml:"url"`
	AccessToken    string   `yaml:"access_token"`
	Prefixes       Prefixes `yaml:"prefix"`
	Groups         []int64  `yaml:"groups"`
	Admins         []int64  `yaml:"admins"`
	ReplyLimit     int      `yaml:"reply_limit"`
	HandlerTimeout Duration `yaml:"handler_timeout"`
	HandlerWorkers int      `yaml:"handler_workers"`
	HandlerQueue   int      `yaml:"handler_queue"`
}

type Context

type Context struct {
	Context  context.Context
	Args     []string
	Captures []string
	Msg      Message
	Plugin   string
	Log      *slog.Logger
	// contains filtered or unexported fields
}

func (*Context) Call

func (c *Context) Call(action string, params any) (json.RawMessage, error)

func (*Context) Cancel

func (c *Context) Cancel()

func (*Context) Cancelled

func (c *Context) Cancelled() bool

func (*Context) Next

func (c *Context) Next(timeout time.Duration, h HandlerFunc, onTimeout func(*TimeoutContext))

func (*Context) Replies

func (c *Context) Replies() []msg.Message

func (*Context) Reply

func (c *Context) Reply(segments ...msg.Segment)

func (*Context) ReplyText

func (c *Context) ReplyText(text string)

func (*Context) Send

func (c *Context) Send(segments ...msg.Segment)

func (*Context) SendText

func (c *Context) SendText(text string)

func (*Context) Stop

func (c *Context) Stop()

func (*Context) Stopped

func (c *Context) Stopped() bool

type Duration

type Duration time.Duration

func (Duration) Duration

func (d Duration) Duration() time.Duration

func (Duration) IsZero

func (d Duration) IsZero() bool

func (Duration) MarshalYAML

func (d Duration) MarshalYAML() (any, error)

func (*Duration) UnmarshalYAML

func (d *Duration) UnmarshalYAML(node *yaml.Node) error

type Event

type Event struct {
	Kind          EventKind
	Scope         Scope
	Message       Message
	PostType      string
	MessageType   string
	NoticeType    string
	RequestType   string
	MetaEventType string
	SubType       string
	MessageID     int64
	GroupID       int64
	UserID        int64
	OperatorID    int64
	Comment       string
	Flag          string
	Raw           onebot.Event
}

type EventContext

type EventContext struct {
	Context context.Context
	Kind    EventKind
	Event   Event
	Plugin  string
	Log     *slog.Logger
	// contains filtered or unexported fields
}

func (*EventContext) Replies

func (c *EventContext) Replies() []EventReply

func (*EventContext) Reply

func (c *EventContext) Reply(segments ...msg.Segment)

func (*EventContext) ReplyPrivateTextTo

func (c *EventContext) ReplyPrivateTextTo(userID int64, text string)

func (*EventContext) ReplyPrivateTo

func (c *EventContext) ReplyPrivateTo(userID int64, segments ...msg.Segment)

func (*EventContext) ReplyText

func (c *EventContext) ReplyText(text string)

func (*EventContext) ReplyTextTo

func (c *EventContext) ReplyTextTo(groupID int64, text string)

func (*EventContext) ReplyTo

func (c *EventContext) ReplyTo(groupID int64, segments ...msg.Segment)

func (*EventContext) Stop

func (c *EventContext) Stop()

func (*EventContext) Stopped

func (c *EventContext) Stopped() bool

type EventHandlerFunc

type EventHandlerFunc func(*EventContext)

type EventKind

type EventKind string
const (
	EventGroupMessage   EventKind = "message.group"
	EventPrivateMessage EventKind = "message.private"

	EventGroupUpload   EventKind = "notice.group_upload"
	EventGroupAdmin    EventKind = "notice.group_admin"
	EventGroupDecrease EventKind = "notice.group_decrease"
	EventGroupIncrease EventKind = "notice.group_increase"
	EventGroupBan      EventKind = "notice.group_ban"
	EventFriendAdd     EventKind = "notice.friend_add"
	EventGroupRecall   EventKind = "notice.group_recall"
	EventFriendRecall  EventKind = "notice.friend_recall"
	EventGroupCard     EventKind = "notice.group_card"
	EventOfflineFile   EventKind = "notice.offline_file"
	EventClientStatus  EventKind = "notice.client_status"
	EventEssence       EventKind = "notice.essence"
	EventNotify        EventKind = "notice.notify"

	EventFriendRequest EventKind = "request.friend"
	EventGroupRequest  EventKind = "request.group"

	EventLifecycle EventKind = "meta_event.lifecycle"
	EventHeartbeat EventKind = "meta_event.heartbeat"
)

type EventMatch

type EventMatch struct {
	Scopes    []Scope
	Groups    []int64
	Users     []int64
	Admins    bool
	Predicate EventPredicate
}

type EventMatchOption

type EventMatchOption func(*EventMatch)

func EventFromAdmin

func EventFromAdmin() EventMatchOption

func EventFromUser

func EventFromUser(users ...int64) EventMatchOption

func EventInGroup

func EventInGroup(groups ...int64) EventMatchOption

func EventInPrivate

func EventInPrivate() EventMatchOption

func EventInScope

func EventInScope(scopes ...Scope) EventMatchOption

func EventWhen

func EventWhen(predicate EventPredicate) EventMatchOption

type EventPredicate

type EventPredicate func(*EventContext) bool

type EventReply

type EventReply struct {
	Scope   Scope
	GroupID int64
	UserID  int64
	Message msg.Message
}

type FrameworkConfig

type FrameworkConfig struct {
	OneBot Config    `yaml:"onebot,omitempty"`
	Log    LogConfig `yaml:"log,omitempty"`
}

func DefaultFrameworkConfig

func DefaultFrameworkConfig() FrameworkConfig

type Group

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

func (*Group) Group

func (g *Group) Group(args ...any) *Group

func (*Group) On

func (g *Group) On(match Match, h HandlerFunc, opts ...MatchOption)

func (*Group) OnCommand

func (g *Group) OnCommand(verb string, h HandlerFunc, args ...any)

func (*Group) OnMessage

func (g *Group) OnMessage(h HandlerFunc, opts ...MatchOption)

func (*Group) Use

func (g *Group) Use(mw ...Middleware) *Group

type HandlerFunc

type HandlerFunc func(*Context)

type LogConfig

type LogConfig struct {
	Level string `yaml:"level,omitempty"`
}

type Match

type Match struct {
	TextEquals string
	TextRegex  *regexp.Regexp
	Scopes     []Scope
	Groups     []int64
	Users      []int64
	Admins     bool
	Predicate  Predicate
}

type MatchOption

type MatchOption func(*Match)

func FromAdmin

func FromAdmin() MatchOption

func FromUser

func FromUser(users ...int64) MatchOption

func InGroup

func InGroup(groups ...int64) MatchOption

func InPrivate

func InPrivate() MatchOption

func InScope

func InScope(scopes ...Scope) MatchOption

func RequireAdmin

func RequireAdmin() MatchOption

func When

func When(predicate Predicate) MatchOption

type Message

type Message struct {
	ID          int64
	Scope       Scope
	GroupID     int64
	UserID      int64
	Text        string
	Body        string
	Prefix      string
	Command     string
	IsCommand   bool
	DisplayName string
}

type Middleware

type Middleware func(HandlerFunc) HandlerFunc

type Plugin

type Plugin interface {
	Name() string
	Init(*PluginContext) error
}

Plugin is the minimum a plugin must satisfy. Plugins MAY additionally implement Starter or Stopper.

type PluginContext

type PluginContext struct {
	// Bot is the OneBot surface (send/call/broadcast/...). For routing, use the
	// On* methods on this PluginContext.
	Bot PluginHost
	// Name is the plugin name as returned from Plugin.Name().
	Name string
	// ConfigDir is the directory holding this plugin's YAML config files.
	ConfigDir string
	// ConfigPath is the absolute path to this plugin's primary YAML config.
	ConfigPath string
	// DataDir is the per-plugin scratch directory. Created on demand by the
	// framework.
	DataDir string
	// Log is a logger pre-tagged with `plugin=<name>`.
	Log *slog.Logger

	// Version is the MICQ framework version the bot is running.
	Version string
	// contains filtered or unexported fields
}

PluginContext is what each plugin receives from Init. It carries the per-plugin paths, logger, and a narrow Bot handle.

func (*PluginContext) Group

func (c *PluginContext) Group(args ...any) *Group

func (*PluginContext) LoadConfig

func (c *PluginContext) LoadConfig(dst any) error

func (*PluginContext) On

func (c *PluginContext) On(match Match, h HandlerFunc, opts ...MatchOption)

func (*PluginContext) OnCommand

func (c *PluginContext) OnCommand(verb string, h HandlerFunc, args ...any)

func (*PluginContext) OnEvent

func (c *PluginContext) OnEvent(kind EventKind, h EventHandlerFunc, opts ...EventMatchOption)

func (*PluginContext) OnMessage

func (c *PluginContext) OnMessage(h HandlerFunc, opts ...MatchOption)

func (*PluginContext) PluginDataPath

func (c *PluginContext) PluginDataPath(parts ...string) string

func (*PluginContext) WriteDefaultConfig

func (c *PluginContext) WriteDefaultConfig(data []byte) error

type PluginHost

type PluginHost interface {
	SendGroup(int64, msg.Message) error
	SendPrivate(int64, msg.Message) error
	Call(ctx context.Context, action string, params any) (json.RawMessage, error)
	BroadcastGroups(msg.Message)
	Connected() bool
	CommandHints() CommandHints
}

PluginHost is the narrow host surface plugins receive through PluginContext.Bot. It deliberately omits the routing methods (use PluginContext.OnCommand/OnEvent/... for those).

type Predicate

type Predicate func(*Context) bool

type Prefixes

type Prefixes []string

Prefixes 在 YAML 中同时接受 `prefix: /m` 和 `prefix: [/m, /man]`。

func (*Prefixes) UnmarshalYAML

func (p *Prefixes) UnmarshalYAML(value *yaml.Node) error

type Runtime

type Runtime struct {
	WorkDir    string
	ConfigDir  string
	DataDir    string
	ConfigPath string
	Version    string
	Config     FrameworkConfig
}

Runtime is the fully-resolved layout and configuration the bot runs on. Build one with ResolveRuntime for normal use, or by hand in tests.

func ResolveRuntime

func ResolveRuntime(configPath string) (Runtime, error)

ResolveRuntime computes the canonical runtime layout from config/core.yaml, loads it if present, and applies env-var overrides.

func ResolveRuntimeInWorkDir

func ResolveRuntimeInWorkDir(workDir string) (Runtime, error)

ResolveRuntimeInWorkDir computes the canonical work-dir layout from a runtime directory.

type Scope

type Scope string
const (
	ScopeGroup   Scope = "group"
	ScopePrivate Scope = "private"
	ScopeAll     Scope = "*"
)

type Starter

type Starter interface {
	Start(context.Context) error
}

Starter is implemented by plugins that need to run background work while the bot is alive.

type Stopper

type Stopper interface {
	Stop(context.Context) error
}

Stopper is implemented by plugins that need to release resources on shutdown.

type TimeoutContext

type TimeoutContext struct {
	Scope   Scope
	GroupID int64
	UserID  int64
	// contains filtered or unexported fields
}

func (*TimeoutContext) Reply

func (c *TimeoutContext) Reply(segments ...msg.Segment)

func (*TimeoutContext) ReplyText

func (c *TimeoutContext) ReplyText(text string)

Directories

Path Synopsis
Package msg 提供机器人回复使用的消息段。
Package msg 提供机器人回复使用的消息段。
Package onebot 实现 OneBot v11 正向 WebSocket 客户端。
Package onebot 实现 OneBot v11 正向 WebSocket 客户端。

Jump to

Keyboard shortcuts

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