anybot

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2026 License: MIT Imports: 16 Imported by: 0

README

AnyBot

AnyBot

AnyBot 是一个 Go 实现的聊天机器人框架,当前内置 OneBot v11 适配器。

安装

go get github.com/tty00a381/anybot
go install github.com/tty00a381/anybot/cmd/anybot@latest

本仓库使用 Go 1.24。

快速开始

本指南假设你已经有一个 OneBot v11 协议端了。如果没有,可以试试 NapCat

先生成一个最小项目:

anybot init -module example.com/bot -dir ./mybot
cd ./mybot
go mod tidy
anybot doctor
go run .

生成的项目默认使用反向 WebSocket,地址 ws://127.0.0.1:6700。请在协议端启用反向 WebSocket,填入上述地址。

如果启用了访问令牌,AnyBot 和协议端要使用同一个令牌:

export ONEBOT_ACCESS_TOKEN=你的令牌

最小代码

package main

import (
	"context"
	"log"
	"os"
	"os/signal"
	"syscall"

	"github.com/tty00a381/anybot"
	"github.com/tty00a381/anybot/adapters/onebot11"
)

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	app := anybot.New(
		anybot.WithAdapter(onebot11.ReverseWS("127.0.0.1:6700",
			onebot11.WithAccessToken(os.Getenv("ONEBOT_ACCESS_TOKEN")),
		)),
	)
	app.Use(anybot.Recover(), anybot.Trace())

	app.Command("ping").Handle(func(c *anybot.Context) error {
		_, err := c.ReplyText("pong")
		return err
	})

	if err := app.Run(ctx); err != nil && ctx.Err() == nil {
		log.Fatal(err)
	}
}

一些概念

  • App:一个机器人进程。适配器、路由、中间件、插件等所有组件,都挂在它上面。
  • Route:一条处理规则。规则匹配后,即执行你编写的处理函数。
  • Context:处理函数的工具箱。事件、接口调用、会话状态、路由结果等都从这里拿。
  • Event:AnyBot 整理过的事件。包含一些常用字段,必要时也能取回原始事件。
  • message.Chain:一条要发送的消息。由 message.Segment 组成。
  • Plugin:一组可以手动安装的路由、中间件或 hook。

写路由

路由就是「什么事件交给什么函数处理」。常见写法有命令、正则、普通消息规则:

app.Command("echo").Handle(func(c *anybot.Context) error {
	_, err := c.ReplyText(c.Args())
	return err
})

app.Regex(`^复读\s+(.+)$`).Handle(func(c *anybot.Context) error {
	matches := c.Match().Vars["matches"].([]string)
	_, err := c.ReplyText(matches[1])
	return err
})

app.OnMessage(anybot.ToMe(), anybot.Contains("帮助")).Handle(func(c *anybot.Context) error {
	_, err := c.ReplyText("我在")
	return err
})

常用规则有 PrivateGroupFromUserInGroupMentionedToMeContainsPrefixAllAnyOfNot

处理函数里可以用 c.Stop() 不再让后面的路由处理这条事件,也可以 return c.Pass() 跳过当前路由,让后面的路由继续。

中间件 & 事件顺序

中间件放在处理函数外层,适合做日志、panic 恢复、超时、权限检查、限速等通用功能:

app.Use(
	anybot.Recover(),
	anybot.Trace(),
	anybot.Timeout(10*time.Second),
	anybot.RateLimit(5, time.Minute),
)

app.Command("admin").
	Use(anybot.OnlyGroup(), anybot.SuperUser("10000")).
	Handle(func(c *anybot.Context) error {
		_, err := c.ReplyText("权限正常")
		return err
	})

AnyBot 默认并发处理事件。如果某个会话里的多条消息必须按顺序处理,如多轮问答、表单收集等临时事务,则可以启用会话串行:

app := anybot.New(
	anybot.WithAdapter(adapter),
	anybot.WithSerialByConversation(),
)

保存会话状态

默认的内存存储,支持过期时间,适合保存短期状态。Context 提供三个常用入口:

c.Session()      // 当前会话
c.UserSession()  // 当前用户
c.GroupSession() // 当前群或频道

若需要把状态放进数据库,请实现 Store 接口后通过 WithStore 传给 App

OneBot v11 适配器

adapters/onebot11 支持三种连接方式:

onebot11.ReverseWS("127.0.0.1:6700")
onebot11.WebSocket("ws://127.0.0.1:6701")
onebot11.HTTP("http://127.0.0.1:3000", "127.0.0.1:6702")

推荐优先使用反向 WebSocket,即 AnyBot 监听端口、OneBot v11 协议端主动连进来。WebSocket 连接状态可以通过 hook 观察:

adapter := onebot11.ReverseWS("127.0.0.1:6700",
	onebot11.WithConnectionHook(func(ctx context.Context, event onebot11.ConnectionEvent) {
		slog.Info("连接状态变化", "state", event.State, "transport", event.Transport)
	}),
)

常用 OneBot v11 接口已经封装成 Go 方法,如发送消息、撤回消息、读取登录信息、读取好友和群列表、管理群成员、处理加好友或加群请求、检查媒体能力、读取版本状态、操作群文件等。对于未封装的接口,可以直接用 CallCallRaw

client := onebot11.MustClient(c)
info, err := client.GetLoginInfo(c.Context)
if err != nil {
	return err
}
_, err = c.ReplyText(info.Nickname)
return err

NapCat 额外提供的接口放在 adapters/onebot11/napcat,避免和标准 OneBot v11 方法混在一起。其他协议端如果也有扩展能力,可以按同样思路放在独立包里。

api := napcat.New(c.Client())
history, err := api.GetGroupMessageHistory(c.Context, c.GroupID(), 0, 20)

发送消息

业务代码可以先拼一条消息,再让当前事件的自然目标接收它:

chain := message.New(
	message.Reply(c.Event().ID),
	message.Text("你好"),
	message.At(c.UserID()),
	message.Image("file:///tmp/a.png"),
)
_, err := c.Reply(chain)

OneBot v11 适配器会把这条消息转成 OneBot 消息段。需要 OneBot v11 特有消息段时,可以使用 onebot11.JSONonebot11.XMLonebot11.Shareonebot11.Node 等构造器。

插件

插件是一组可以手动安装的路由、中间件或 hook。

CLI 可以生成插件骨架:

anybot new plugin hello

插件就是普通类型,请显式安装到 App 上。

type helloPlugin struct{}

func (helloPlugin) Manifest() anybot.Manifest {
	return anybot.Manifest{Name: "hello", Version: "1.0.0"}
}

func (helloPlugin) Install(app *anybot.App) error {
	app.Command("hello").Handle(func(c *anybot.Context) error {
		_, err := c.ReplyText("world")
		return err
	})
	return nil
}

安装插件:

if err := app.UsePlugins(helloPlugin{}); err != nil {
	log.Fatal(err)
}

仓库内置了少量示例插件:plugins/helpplugins/echoplugins/adminplugins/ratelimit

CLI

anybot init [-module 模块名] [-dir 目录] [-force]
anybot run [go run 参数...]
anybot new plugin <名称> [-dir 目录] [-force]
anybot doctor [-config anybot.yaml] [-connect]
anybot version

示例

  • examples/ping:最小 ping 机器人。
  • examples/reversews:反向 WebSocket 接入。
  • examples/websocket:正向 WebSocket。
  • examples/httpaction:HTTP 接口调用 & 事件回调。
  • examples/media:登录信息读取 & 图片发送。
  • examples/pluginbot:显式插件。
  • examples/permission:权限控制 & 限速。
  • examples/session:会话状态。

发布

本地开发测试:

make check

发布前检查:

make release-check

Documentation

Overview

anybot 包提供机器人运行时、事件路由、中间件、会话存储、插件生命周期和协议适配核心。

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrPass 表示当前路由主动让出处理权,后续路由继续匹配。
	ErrPass = errors.New("anybot: pass route")
	// ErrStop 表示当前事件应停止向后续路由传播。
	ErrStop = errors.New("anybot: stop route")
	// ErrUnauthorized 表示当前事件没有通过权限检查。
	ErrUnauthorized = errors.New("anybot: unauthorized")
	// ErrRateLimited 表示当前限速窗口已被耗尽。
	ErrRateLimited = errors.New("anybot: rate limited")
)

Functions

func Configure

func Configure(opts ...Option)

Configure 将配置选项应用到默认 App。

func OnError

func OnError(handler ErrorHandler)

OnError 向默认 App 注册错误处理回调。

func OnReady

func OnReady(hook Hook)

OnReady 向默认 App 注册就绪钩子。

func OnShutdown

func OnShutdown(hook Hook)

OnShutdown 向默认 App 注册关闭钩子。

func OnStart

func OnStart(hook Hook)

OnStart 向默认 App 注册启动钩子。

func OnStop

func OnStop(hook Hook)

OnStop 是 OnShutdown 的兼容别名。

func ResetDefault

func ResetDefault(opts ...Option)

ResetDefault 使用新配置替换默认 App,主要用于测试和极小工具。

func Run

func Run(ctxs ...context.Context) error

Run 启动默认 App;未传 context 时使用 context.Background。

func Use

func Use(middleware ...Middleware)

Use 向默认 App 注册全局中间件。

func UsePlugin

func UsePlugin(plugin Plugin) error

UsePlugin 向默认 App 安装插件。

func UsePlugins

func UsePlugins(plugins ...Plugin) error

UsePlugins 向默认 App 按顺序安装多个插件。

Types

type ActionClient

type ActionClient interface {
	Call(context.Context, string, any, any) error
	CallRaw(context.Context, string, any) (*ActionResponse, error)
	Send(context.Context, ReplyTarget, message.Chain) (MessageReceipt, error)
}

ActionClient 定义协议动作调用和消息发送能力。

type ActionError

type ActionError struct {
	Action  string
	Status  string
	RetCode int
	Message string
	Wording string
}

ActionError 描述一次由协议端明确拒绝或返回失败状态的动作调用。

func (*ActionError) Error

func (e *ActionError) Error() string

type ActionResponse

type ActionResponse struct {
	Status  string
	RetCode int
	Message string
	Wording string
	Echo    string
	Data    json.RawMessage
	Raw     json.RawMessage
}

ActionResponse 是协议无关的动作响应封套,保留标准字段和原始 data。

func (*ActionResponse) Decode

func (r *ActionResponse) Decode(out any) error

Decode 将动作响应的 data 字段解码到 out;空 data 会被视为成功空值。

func (*ActionResponse) OK

func (r *ActionResponse) OK() bool

OK 判断动作响应是否表示成功。

type Adapter

type Adapter interface {
	Protocol() Protocol
	Start(context.Context, EmitFunc) error
	Client() ActionClient
}

Adapter 把具体聊天协议接入 AnyBot 运行时。

type App

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

App 是 AnyBot 的运行时入口,负责连接适配器、调度事件并执行路由链。

func Default

func Default() *App

Default 返回快捷入口使用的进程级默认 App。

func New

func New(opts ...Option) *App

New 创建新的运行时实例,并应用传入的配置选项。

func (*App) Adapter

func (a *App) Adapter() Adapter

Adapter 返回当前运行时配置的协议适配器;未配置时返回 nil。

func (*App) Client

func (a *App) Client() ActionClient

Client 返回适配器提供的动作客户端;运行时或适配器为空时返回 nil。

func (*App) Command

func (a *App) Command(names ...string) *Route

Command 注册命令路由,默认识别 /、!、. 三种命令前缀。

func (*App) Dispatch

func (a *App) Dispatch(ctx context.Context, event *Event) error

Dispatch 将标准化事件直接投递给运行时,常用于单元测试或自定义适配器。

func (*App) Group

func (a *App) Group(rules ...Rule) *Router

Group 创建共享基础规则的路由组,便于把同类路由收束在一起。

func (*App) Logger

func (a *App) Logger() *slog.Logger

Logger 返回运行时使用的日志器。

func (*App) On

func (a *App) On(rules ...Rule) *Route

On 注册通用事件路由。

func (*App) OnError

func (a *App) OnError(handler ErrorHandler)

OnError 注册路由处理错误的回调。

func (*App) OnMessage

func (a *App) OnMessage(rules ...Rule) *Route

OnMessage 注册消息事件路由,相当于在规则前追加 MessageEvent。

func (*App) OnReady

func (a *App) OnReady(hook Hook)

OnReady 注册就绪钩子,事件调度器准备好后、适配器启动前执行。

func (*App) OnShutdown

func (a *App) OnShutdown(hook Hook)

OnShutdown 注册关闭钩子,执行顺序与注册顺序相反。

func (*App) OnStart

func (a *App) OnStart(hook Hook)

OnStart 注册启动钩子,适配器启动前执行。

func (*App) OnStop

func (a *App) OnStop(hook Hook)

OnStop 是 OnShutdown 的兼容别名。

func (*App) Plugins

func (a *App) Plugins() []Manifest

Plugins 返回已成功安装插件的清单副本。

func (*App) Regex

func (a *App) Regex(pattern string) *Route

Regex 注册文本正则路由,并把匹配结果写入 Context 的匹配变量。

func (*App) Router

func (a *App) Router() *Router

Router 返回根路由器,适合在需要细分路由组时使用。

func (*App) Run

func (a *App) Run(ctx context.Context) error

Run 启动生命周期钩子、适配器和事件调度器,并在 ctx 结束后退出。

func (*App) Store

func (a *App) Store() Store

Store 返回运行时使用的会话存储。

func (*App) Use

func (a *App) Use(middleware ...Middleware)

Use 注册全局中间件。全局中间件会包裹所有路由处理函数。

func (*App) UsePlugin

func (a *App) UsePlugin(plugin Plugin) error

UsePlugin 立即安装插件,并在成功后记录插件清单。

func (*App) UsePlugins

func (a *App) UsePlugins(plugins ...Plugin) error

UsePlugins 按传入顺序安装多个插件,遇到错误时停止。

type Context

type Context struct {
	context.Context
	// contains filtered or unexported fields
}

Context 是路由处理函数的工作上下文,聚合事件、运行时能力、匹配结果和局部值。

func NewTestContext

func NewTestContext(app *App, event *Event) *Context

NewTestContext 创建测试用上下文;app 为空时会使用默认配置的新 App。

func (*Context) Adapter

func (c *Context) Adapter() Adapter

Adapter 返回当前运行时配置的协议适配器。

func (*Context) App

func (c *Context) App() *App

App 返回当前上下文所属的运行时。

func (*Context) Args

func (c *Context) Args() string

Args 返回命令名之后的原始参数文本。

func (*Context) Argv

func (c *Context) Argv() []string

Argv 返回按空白拆分后的命令参数,并保留简单引号与转义处理。

func (*Context) Client

func (c *Context) Client() ActionClient

Client 返回适配器动作客户端,可用于发送消息或调用协议 API。

func (*Context) Command

func (c *Context) Command() string

Command 返回命令规则匹配到的命令名。

func (*Context) ConversationID

func (c *Context) ConversationID() string

ConversationID 返回当前事件对应的会话键,可直接用于会话存储。

func (*Context) Event

func (c *Context) Event() *Event

Event 返回当前正在处理的标准化事件。

func (*Context) Get

func (c *Context) Get(key string) (any, bool)

Get 读取当前处理链内的局部值。

func (*Context) GroupID

func (c *Context) GroupID() string

GroupID 返回当前事件的群 ID,非群事件返回空字符串。

func (*Context) GroupSession

func (c *Context) GroupSession() *Session

GroupSession 返回当前群或频道维度的存储视图。

func (*Context) IsGroup

func (c *Context) IsGroup() bool

IsGroup 判断当前事件是否为群消息。

func (*Context) IsPrivate

func (c *Context) IsPrivate() bool

IsPrivate 判断当前事件是否为私聊消息。

func (*Context) Logger

func (c *Context) Logger() *slog.Logger

Logger 返回运行时日志器;上下文未绑定运行时时返回 slog.Default。

func (*Context) Match

func (c *Context) Match() Match

Match 返回当前路由的匹配详情,包括评分、原因和规则写入的变量。

func (*Context) Pass

func (c *Context) Pass() error

Pass 跳过当前路由且不视为失败,后续路由仍会继续匹配。

func (*Context) RawEvent

func (c *Context) RawEvent() any

RawEvent 返回适配器保留的原始协议事件对象,便于在需要时访问协议专属字段。

func (*Context) Reply

func (c *Context) Reply(chain message.Chain) (MessageReceipt, error)

Reply 使用事件的自然目标发送消息。

func (*Context) ReplyText

func (c *Context) ReplyText(text string) (MessageReceipt, error)

ReplyText 使用事件的自然目标发送纯文本回复。

func (*Context) Route

func (c *Context) Route() *Route

Route 返回当前正在执行的路由。

func (*Context) RouteName

func (c *Context) RouteName() string

RouteName 返回当前路由的诊断名称,未命名时返回空字符串。

func (*Context) SelfID

func (c *Context) SelfID() string

SelfID 返回当前机器人账号 ID,事件为空时返回空字符串。

func (*Context) Session

func (c *Context) Session() *Session

Session 返回当前会话维度的存储视图。

func (*Context) SessionBy

func (c *Context) SessionBy(key string) *Session

SessionBy 返回指定键空间下的存储视图;key 为空时使用默认会话键。

func (*Context) Set

func (c *Context) Set(key string, value any)

Set 写入当前处理链内可见的局部值。

func (*Context) Stop

func (c *Context) Stop()

Stop 停止当前事件继续传播到后续路由。

func (*Context) StopError

func (c *Context) StopError() error

StopError 返回可用于处理函数的停止错误,同时标记当前上下文已停止。

func (*Context) Stopped

func (c *Context) Stopped() bool

Stopped 报告当前事件是否已被要求停止传播。

func (*Context) Store

func (c *Context) Store() Store

Store 返回运行时配置的会话存储。

func (*Context) String

func (c *Context) String(key string) string

String 读取字符串局部值;不存在或类型不匹配时返回空字符串。

func (*Context) Target

func (c *Context) Target() ReplyTarget

Target 返回当前事件的自然回复目标。

func (*Context) Text

func (c *Context) Text() string

Text 返回事件中的文本内容,优先使用标准化文本,再回退到消息链文本。

func (*Context) UserID

func (c *Context) UserID() string

UserID 返回当前事件的用户 ID,事件为空时返回空字符串。

func (*Context) UserSession

func (c *Context) UserSession() *Session

UserSession 返回当前用户维度的存储视图。

type EmitFunc

type EmitFunc func(context.Context, *Event) error

EmitFunc 是适配器向 AnyBot 运行时投递标准化事件的函数。

type ErrorHandler

type ErrorHandler func(*Context, error)

ErrorHandler 处理路由处理函数或中间件返回的错误。

type Event

type Event struct {
	ID         string
	Protocol   Protocol
	SelfID     string
	Type       string
	DetailType string
	SubType    string

	UserID    string
	GroupID   string
	GuildID   string
	ChannelID string

	Text    string
	Message message.Chain

	Raw  json.RawMessage
	Data any
}

Event 是 AnyBot 的协议无关事件封套,保留常用标准字段和原始协议数据。

func (*Event) ConversationID

func (e *Event) ConversationID() string

ConversationID 返回适合会话存储的稳定键,优先按频道、群聊、私聊逐级区分。

func (*Event) DecodeRaw

func (e *Event) DecodeRaw(out any) error

DecodeRaw 将原始协议事件 JSON 解码到 out;没有原始数据时直接返回 nil。

func (*Event) GroupSessionID

func (e *Event) GroupSessionID() string

GroupSessionID 返回按群或频道维度隔离的存储键。

func (*Event) IsMessage

func (e *Event) IsMessage() bool

IsMessage 判断该事件是否为消息事件。

func (*Event) Target

func (e *Event) Target() ReplyTarget

Target 返回该事件的自然回复目标,供 Context.Reply 和适配器发送消息使用。

func (*Event) UserSessionID

func (e *Event) UserSessionID() string

UserSessionID 返回按用户维度隔离的存储键。

type EventKeyFunc

type EventKeyFunc func(*Event) string

EventKeyFunc 返回事件串行调度使用的键;空键表示不参与串行化。

type Handler

type Handler func(*Context) error

Handler 处理已经匹配成功的事件。

type Hook

type Hook func(context.Context) error

Hook 是 App 生命周期钩子函数。

type Manifest

type Manifest struct {
	Name        string
	Version     string
	Description string
	Config      any
}

Manifest 描述插件的名称、版本、说明和可选配置。

type Match

type Match struct {
	Score  float64
	Reason string
	Vars   map[string]any
}

Match 描述规则匹配结果,包含评分、诊断原因和传递给处理函数的变量。

func (Match) WithVar

func (m Match) WithVar(key string, value any) Match

WithVar 向匹配结果追加变量,并返回更新后的 Match。

type MemoryStore

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

MemoryStore 是 goroutine 安全的进程内 Store,适合短期会话状态。

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore 创建默认内存存储。

func (*MemoryStore) Delete

func (s *MemoryStore) Delete(ctx context.Context, key string) error

Delete 删除指定键。

func (*MemoryStore) Get

func (s *MemoryStore) Get(ctx context.Context, key string) ([]byte, bool, error)

Get 读取指定键的值;键不存在或已过期时返回 ok=false。

func (*MemoryStore) Set

func (s *MemoryStore) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error

Set 写入指定键的值。ttl 大于 0 时,值会在到期后失效。

func (*MemoryStore) Sweep

func (s *MemoryStore) Sweep(ctx context.Context) error

Sweep 立即清理所有已过期的内存项。

type MessageReceipt

type MessageReceipt struct {
	ID string
}

MessageReceipt 是协议无关的消息发送回执。

type Middleware

type Middleware func(Handler) Handler

Middleware 包装处理函数,用于实现日志、鉴权、限速等横切能力。

func OnlyGroup

func OnlyGroup() Middleware

OnlyGroup 仅允许群消息进入后续处理链,其他事件会停止传播。

func OnlyPrivate

func OnlyPrivate() Middleware

OnlyPrivate 仅允许私聊消息进入后续处理链,其他事件会停止传播。

func RateLimit

func RateLimit(limit int, window time.Duration) Middleware

RateLimit 使用当前会话键做简单的进程内限速。

func RateLimitBy

func RateLimitBy(limit int, window time.Duration, keyFunc func(*Context) string) Middleware

RateLimitBy 使用自定义键做进程内限速;键为空时回退到会话、用户或全局维度。

func Recover

func Recover(loggers ...*slog.Logger) Middleware

Recover 捕获处理链中的 panic,记录调用栈,并把 panic 转成 PanicError。

func SuperUser

func SuperUser(ids ...any) Middleware

SuperUser 仅允许指定用户进入后续处理链,未授权时返回 ErrUnauthorized。

func Timeout

func Timeout(timeout time.Duration) Middleware

Timeout 为后续处理函数派生带超时的 context;timeout 不大于 0 时不生效。

func Trace

func Trace(loggers ...*slog.Logger) Middleware

Trace 在每次路由处理结束后记录耗时、路由名称和事件关键信息。

type Option

type Option func(*App)

Option 调整 App 的运行时配置。

func WithAdapter

func WithAdapter(adapter Adapter) Option

WithAdapter 配置运行时使用的协议适配器。

func WithBuffer

func WithBuffer(size int) Option

WithBuffer 配置事件队列大小;不大于 0 的值会被忽略。

func WithErrorHandler

func WithErrorHandler(handler ErrorHandler) Option

WithErrorHandler 注册错误处理器。

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger 配置运行时日志器;nil 会被忽略。

func WithSerialBy

func WithSerialBy(fn EventKeyFunc) Option

WithSerialBy 按自定义事件键串行处理同键事件,适合保护会话状态流转。

func WithSerialByConversation

func WithSerialByConversation() Option

WithSerialByConversation 让同一会话内的事件按顺序处理。

func WithStore

func WithStore(store Store) Option

WithStore 配置会话存储;nil 会被忽略。

func WithWorkers

func WithWorkers(workers int) Option

WithWorkers 配置并发处理事件的 worker 数;不大于 0 时由适配器回调同步处理。

type PanicError

type PanicError struct {
	Value any
	Stack []byte
}

PanicError 包装处理函数或中间件中恢复到的 panic 值和调用栈。

func (*PanicError) Error

func (e *PanicError) Error() string

type Plugin

type Plugin interface {
	Manifest() Manifest
	Install(*App) error
}

Plugin 是可显式安装到 App 的扩展单元。

type PluginFunc

type PluginFunc struct {
	Info Manifest
	Fn   func(*App) error
}

PluginFunc 将普通安装函数适配为 Plugin。

func (PluginFunc) Install

func (p PluginFunc) Install(app *App) error

Install 执行插件安装函数;未提供函数时视为成功。

func (PluginFunc) Manifest

func (p PluginFunc) Manifest() Manifest

Manifest 返回插件清单。

type Protocol

type Protocol string

Protocol 标识事件和动作所属的协议。

const (
	// ProtocolOneBot11 表示 OneBot v11 协议。
	ProtocolOneBot11 Protocol = "onebot11"
)

type ReplyTarget

type ReplyTarget struct {
	Protocol  Protocol
	SelfID    string
	UserID    string
	GroupID   string
	GuildID   string
	ChannelID string
	EventID   string
}

ReplyTarget 描述一次消息回复的自然目标。

type Route

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

Route 表示一条可配置的事件路由。

func Command

func Command(names ...string) *Route

Command 向默认 App 注册命令路由。

func On

func On(rules ...Rule) *Route

On 向默认 App 注册通用事件路由。

func OnMessage

func OnMessage(rules ...Rule) *Route

OnMessage 向默认 App 注册消息事件路由。

func Regex

func Regex(pattern string) *Route

Regex 向默认 App 注册文本正则路由。

func (*Route) Handle

func (r *Route) Handle(handler Handler) *Route

Handle 设置路由处理函数。

func (*Route) Name

func (r *Route) Name(name string) *Route

Name 设置路由名称,便于日志、追踪和错误诊断。

func (*Route) Priority

func (r *Route) Priority(priority int) *Route

Priority 设置路由优先级;数值越大越先执行,同优先级保持注册顺序。

func (*Route) Use

func (r *Route) Use(middleware ...Middleware) *Route

Use 追加只作用于当前路由的中间件。

type Router

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

Router 组织路由、中间件和共享基础规则。

func (*Router) Command

func (r *Router) Command(names ...string) *Route

Command 注册命令路由,默认识别 /、!、. 三种前缀。

func (*Router) Group

func (r *Router) Group(rules ...Rule) *Router

Group 创建继承当前基础规则的子路由器。

func (*Router) On

func (r *Router) On(rules ...Rule) *Route

On 注册一条通用事件路由。

func (*Router) OnMessage

func (r *Router) OnMessage(rules ...Rule) *Route

OnMessage 注册消息事件路由。

func (*Router) Regex

func (r *Router) Regex(pattern string) *Route

Regex 注册文本正则路由。

func (*Router) Use

func (r *Router) Use(middleware ...Middleware)

Use 追加路由器中间件。根路由器上的中间件作用于所有路由。

type Rule

type Rule interface {
	Match(context.Context, *Context) (Match, bool)
}

Rule 判断路由是否应处理当前事件。

func All

func All(rules ...Rule) Rule

All 要求传入的所有规则都匹配,并合并它们的匹配结果。

func Any

func Any() Rule

Any 匹配所有事件,常用于兜底路由或测试。

func AnyOf

func AnyOf(rules ...Rule) Rule

AnyOf 在任意一个规则匹配时通过,并返回第一个成功规则的匹配结果。

func CommandRule

func CommandRule(names ...string) Rule

CommandRule 使用默认前缀 /、!、. 匹配命令。

func CommandWithPrefixes

func CommandWithPrefixes(prefixes []string, names ...string) Rule

CommandWithPrefixes 使用显式前缀集合匹配命令,并写入 prefix、command、args 和 argv。

func Contains

func Contains(substr string) Rule

Contains 匹配文本中包含指定片段的消息。

func DetailType

func DetailType(kind string) Rule

DetailType 匹配标准化事件细分类型,例如 group、private 或心跳事件。

func EventType

func EventType(kind string) Rule

EventType 匹配标准化事件类型,例如 message、notice 或 request。

func FromSelf

func FromSelf() Rule

FromSelf 匹配由当前机器人账号自己发送的消息。

func FromUser

func FromUser(ids ...any) Rule

FromUser 匹配指定发送者 ID。

func Group

func Group() Rule

Group 匹配群消息。

func InGroup

func InGroup(ids ...any) Rule

InGroup 匹配指定群 ID。

func Mentioned

func Mentioned(ids ...any) Rule

Mentioned 匹配提及指定用户的消息;未传 ID 时匹配任意提及。

func MessageEvent

func MessageEvent() Rule

MessageEvent 匹配标准化消息事件。

func Not

func Not(rule Rule) Rule

Not 在传入规则不匹配时通过。

func NotFromSelf

func NotFromSelf() Rule

NotFromSelf 排除当前机器人账号自己发送的消息。

func Prefix

func Prefix(prefix string) Rule

Prefix 匹配指定文本前缀,并把剩余文本写入 rest 变量。

func Private

func Private() Rule

Private 匹配私聊消息。

func RegexRule

func RegexRule(pattern string) Rule

RegexRule 使用正则表达式字符串匹配事件文本。

func RegexpRule

func RegexpRule(re *regexp.Regexp) Rule

RegexpRule 使用已编译的正则表达式匹配事件文本,并写入 matches 与命名分组变量。

func ToMe

func ToMe() Rule

ToMe 匹配私聊消息,或群聊中提及当前机器人的消息。

type RuleFunc

type RuleFunc func(context.Context, *Context) (Match, bool)

RuleFunc 将普通函数适配为 Rule。

func (RuleFunc) Match

func (f RuleFunc) Match(ctx context.Context, c *Context) (Match, bool)

Match 调用底层函数完成规则匹配。

type Session

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

Session 是基于固定键前缀的 Store 视图。

func NewSession

func NewSession(store Store, key string) *Session

NewSession 创建指定键前缀下的会话视图。

func (*Session) Delete

func (s *Session) Delete(ctx context.Context, name string) error

Delete 删除会话视图中的值。

func (*Session) Get

func (s *Session) Get(ctx context.Context, name string) ([]byte, bool, error)

Get 读取会话视图中的原始字节值。

func (*Session) Key

func (s *Session) Key() string

Key 返回当前会话视图使用的键前缀。

func (*Session) LoadJSON

func (s *Session) LoadJSON(ctx context.Context, name string, out any) (bool, error)

LoadJSON 读取会话值并按 JSON 解码到 out。

func (*Session) SaveJSON

func (s *Session) SaveJSON(ctx context.Context, name string, value any, ttl time.Duration) error

SaveJSON 将 value 编码为 JSON 后写入会话视图。

func (*Session) Set

func (s *Session) Set(ctx context.Context, name string, value []byte, ttl time.Duration) error

Set 写入会话视图中的原始字节值。

type Store

type Store interface {
	Get(context.Context, string) ([]byte, bool, error)
	Set(context.Context, string, []byte, time.Duration) error
	Delete(context.Context, string) error
}

Store 定义会话数据的读写接口,值以字节形式存储并可带 TTL。

Directories

Path Synopsis
adapters
onebot11
onebot11 包提供 AnyBot 的 OneBot v11 适配器、消息段构造器和类型化动作客户端。
onebot11 包提供 AnyBot 的 OneBot v11 适配器、消息段构造器和类型化动作客户端。
onebot11/napcat
napcat 包提供 NapCat 专属 OneBot v11 扩展动作的类型化辅助方法。
napcat 包提供 NapCat 专属 OneBot v11 扩展动作的类型化辅助方法。
cmd
anybot command
examples
httpaction command
media command
permission command
ping command
pluginbot command
reversews command
session command
websocket command
internal
message 包定义 AnyBot 的协议中立消息链。
message 包定义 AnyBot 的协议中立消息链。
plugins
admin
admin 包提供一个超级用户命令示例插件。
admin 包提供一个超级用户命令示例插件。
echo
echo 包提供一个复读命令示例插件。
echo 包提供一个复读命令示例插件。
help
help 包提供一个可配置的基础帮助命令插件。
help 包提供一个可配置的基础帮助命令插件。
ratelimit
ratelimit 包提供把会话限速中间件打包后的示例插件。
ratelimit 包提供把会话限速中间件打包后的示例插件。

Jump to

Keyboard shortcuts

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