notify

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	// LinkConnected 表示对端确实接上了(只有能判断这件事的适配器才会返回它)。
	LinkConnected = "connected"
	// LinkWaiting 表示实例在跑、但对端还没接上(QQ 绑好端口等 NapCat 握手就是这个态)。
	LinkWaiting = "waiting"
)

* 连通态取值。 * * 为什么不能直接拿 Healthy() 当「已连接」:这四个适配器里 Healthy() 的含义都只是 * **构造/启动成功**,不是对端真的接上了 —— * · QQ:监听端口一绑上就 healthy=true,而 NapCat 还没握手时发送会明确失败 * (「QQ 通道未连接 (NapCat 尚未握手)」);适配器自己的测试注释也写了这一点; * · Telegram:bot 造出来就 healthy=true,没做任何网络确认; * · Webhook:只判 config != nil; * · WeCom:恒为 true(它只是个出站 URL,没有长连接可言)。 * 所以把 Healthy() 映射成「已连接」会在界面上说一件不存在的事。

View Source
const (
	DigestWindow    = 30 * time.Second
	DigestThreshold = 5
	DigestMaxItems  = 50
)
View Source
const (
	EventRSSNew              = "rss.new"
	EventRSSMatched          = "rss.matched"
	EventRSSDigest           = "rss.digest"
	EventSubscribeDownloaded = "subscribe.downloaded"
	EventDoubanFailed        = "subscribe.douban_failed"
	EventFollowFound         = "media.followshow.found"
	EventFollowWaiting       = "media.followshow.waiting"
	EventFollowFailed        = "media.followshow.failed"
	EventMediaOrganized      = "media.organized"
	EventCalendarToday       = "media.calendar.today"
	EventMediaPlayback       = "media.playback"
	EventLoginExpiring       = "site.login_expiring"
	EventProbeFailed         = "site.probe_failed"
	EventProbeRecovered      = "site.probe_recovered"
	EventLoginTest           = "site.login_test"
	EventAttendanceDaily     = "attendance.daily"
	EventReportDaily         = "report.daily"
	EventDeadTorrents        = "downloader.dead_torrents"
	EventFreeEndPauseFailed  = "downloader.free_end_pause_failed"
	EventReseedRound         = "reseed.round"
	EventRemotePaired        = "remote.paired"
	EventBackupFailed        = "system.backup_failed"
	EventFreeWatchPushed     = "torrent.free_watch.pushed"
	EventFreeWatchExpired    = "torrent.free_watch.expired"
	EventFreeWatchFailed     = "torrent.free_watch.failed"
	EventTest                = "test"
)

事件类型。生产者用这些常量经 NewEvent 建事件;消息模板按它们一种一套。

View Source
const (
	GroupNotify    = "notify"
	GroupReply     = "reply"
	GroupAssistant = "assistant"
)

事件的组:通知(发到所有通知通道,Webhook 收到的也是这些)、ChatOps 命令回复、AI 助手在通知通道里的回复。 回复与助手的事件只有正文(NoTitle),只在回复命令或助手说话的那个通道里发。

View Source
const (
	EventReplyStatus    = "reply.status"
	EventReplyTorrents  = "reply.torrents"
	EventReplySites     = "reply.sites"
	EventReplySiteInfo  = "reply.site_info"
	EventReplyTasks     = "reply.tasks"
	EventReplySignin    = "reply.signin"
	EventReplyVersion   = "reply.version"
	EventReplyHelp      = "reply.help"
	EventReplySubs      = "reply.subs"
	EventReplyToday     = "reply.today"
	EventReplyOther     = "reply.other"
	EventAssistantReply = "assistant.reply"
)

ChatOps 命令回复与 AI 助手回复的事件类型。

Variables

View Source
var CommonVars = []Var{
	{Key: "event", Type: VarString, Desc: "事件类型", Sample: EventRSSMatched},
	{Key: "event_name", Type: VarString, Desc: "事件名称", Sample: "RSS 命中过滤规则"},
	{Key: "time", Type: VarString, Desc: "发生时间(本地时间,2006-01-02 15:04:05)", Sample: "2026-10-12 08:00:00"},
	{Key: "timestamp", Type: VarInt, Desc: "发生时间(秒级时间戳)", Sample: int64(1791763200)},
	{Key: "title", Type: VarString, Desc: "内置的标题"},
	{Key: "text", Type: VarString, Desc: "内置的正文"},
}

CommonVars 是每种事件都有的变量。

View Source
var ErrChannelTypeUnknown = errors.New("未知通知通道类型")
View Source
var Events = slices.Concat(
	inGroup(GroupNotify, false, notifyEvents),
	inGroup(GroupReply, true, replyEvents),
	inGroup(GroupAssistant, true, assistantEvents),
)

Events 是事件目录:通知、ChatOps 命令回复、AI 助手回复三组。改这里要同时改对应生产者(events_test 核对目录自身一致, 生产者的测试核对各变量的值)。

View Source
var Groups = []EventGroup{
	{Key: GroupNotify, Name: "通知", Desc: "发到所有通知通道的通知,Webhook 收到的也是这些"},
	{Key: GroupReply, Name: "ChatOps 命令回复", Desc: "在 Telegram、QQ 等通道里发命令时 pt-tools 的回复,只有正文"},
	{Key: GroupAssistant, Name: "AI 助手回复", Desc: "AI 助手在通知通道里发的回答、提示与确认,只有正文"},
}

Groups 是事件的组,按页面上的顺序。

View Source
var WebhookVars = []Var{
	{Key: "channel", Type: VarString, Desc: "通知通道的名称", Sample: "我的 Webhook"},
}

WebhookVars 是只有 Webhook 请求体与地址里才有的变量。

Functions

func CombineDigest

func CombineDigest(items []DigestItem) (title, text string)

CombineDigest 将多个条目合并为单条消息。单条直接透传;多条生成编号摘要。 超过 DigestMaxItems 的部分会被截断并提示剩余数量。

func IsNotifyEvent added in v1.0.0

func IsNotifyEvent(typ string) bool

IsNotifyEvent 报告这种事件是不是通知(Webhook 只会收到通知)。

func IsQuietNow

func IsQuietNow(now time.Time, start, end string) bool

IsQuietNow 判断 now 是否落入 [start, end) 的静默窗口(分钟粒度,不含秒)。 start/end 任一为空、格式非法、或两者相等时视为无静默。 当 start > end(如 22:00–08:00)窗口跨越午夜,等价于 [start,24:00) ∪ [00:00,end)。

func ListVars added in v1.0.0

func ListVars() map[string]bool

ListVars 是可以 range 的变量名。

func NextQuietEnd

func NextQuietEnd(now time.Time, end string) time.Time

NextQuietEnd 返回下一次静默结束时刻(>= now+1ns)。调用方应先确认当前处于静默时段。 当今天的 end 时刻已过,返回明天的 end 时刻;否则返回今天的 end 时刻。

func NormalizeIDs added in v1.0.0

func NormalizeIDs(items []string) []string

NormalizeIDs 是通道名单的规整规则:去掉首尾空白、跳过空项、去重,保持原来的顺序。 飞书应用机器人解析配置(adapter/feishuapp)与 app 层读名单(绑定页、通知收件人)共用它,两边认的名单一样。

func RegisterChannel

func RegisterChannel(typ string, factory Factory)

func RenderSample added in v1.0.0

func RenderSample(eventType string, kind tmpl.Kind, src string) (string, error)

RenderSample 用这种事件的示例数据渲染一份模板(变量名写错会报错),返回渲染结果:保存前的校验与预览用。 src 为空时返回内置文字的示例。

func TextKind added in v1.0.0

func TextKind(typ string) tmpl.Kind

TextKind 是这种事件的正文模板的种类:ChatOps 命令回复与 AI 助手回复的正文可能很长(助手的回答最多分 4 条发), 输出上限比通知的正文大。

Types

type Button

type Button struct {
	Text         string `json:"text"`
	CallbackData string `json:"callback_data,omitempty"`
	URL          string `json:"url,omitempty"`
}

type Channel

type Channel interface {
	Type() string
	Init(ctx context.Context, conf *models.NotificationConf) error
	SupportsInbound() bool
	Send(ctx context.Context, n Notification) error
	OnInbound(handler InboundHandler)
	Close(ctx context.Context) error
	Healthy() bool
}

type ConfLister

type ConfLister interface {
	ListNotificationConfs(ctx context.Context) ([]models.NotificationConf, error)
}

ConfLister lists notification channel configurations available to the router.

type ConfigChecker added in v1.0.0

type ConfigChecker interface {
	CheckConfig(conf *models.NotificationConf) error
}

ConfigChecker 由能在不做任何 I/O 的前提下检查配置的适配器实现,是可选能力: 保存配置前调用,配置有误时直接拒绝保存,不等热重载时才失败。ConfigJSON 是明文。

type DedupCache

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

func NewDedupCache

func NewDedupCache(capacity int, window time.Duration) *DedupCache

func (*DedupCache) Seen

func (d *DedupCache) Seen(eventType, primaryID string, confID uint) bool

type DigestBuffer

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

DigestBuffer 按 NotificationConf ID 缓冲一段时间内的通知,达到 threshold 立即合并、 否则在 window 到期时合并刷写。

func NewDigestBuffer

func NewDigestBuffer(ctx context.Context, flush DigestFlushFunc) *DigestBuffer

func NewDigestBufferWithWindow

func NewDigestBufferWithWindow(ctx context.Context, flush DigestFlushFunc, window time.Duration, threshold int) *DigestBuffer

NewDigestBufferWithWindow 暴露 window/threshold 用于单测。

func (*DigestBuffer) Add

func (b *DigestBuffer) Add(confID uint, item DigestItem)

Add 入列一条 DigestItem。命中阈值立即异步刷写,否则在窗口到期时刷写。

func (*DigestBuffer) FlushAll

func (b *DigestBuffer) FlushAll()

FlushAll 强制刷写所有 pending 条目,用于优雅退出。

type DigestFlushFunc

type DigestFlushFunc func(ctx context.Context, confID uint, items []DigestItem)

DigestFlushFunc 在窗口结束(条数达阈值或定时器到期)时被调用,由实现方完成 实际推送以及 rss_notification_log 行的结果更新。

type DigestItem

type DigestItem struct {
	LogID uint
	Title string
	Text  string
	// Event 是这一条自己的事件:只有一条时照它发,多条时从里面取站点与种子拼成 rss.digest
	Event *Event
}

DigestItem 是 DigestBuffer 内部的一条待合并通知。 LogID 指向触发该条目的 rss_notification_log 行 ID,flush 回调据此更新结果。

type Event added in v1.0.0

type Event struct {
	Type   string         `json:"type"`
	Time   time.Time      `json:"time"`
	Fields map[string]any `json:"fields,omitempty"`
}

Event 是一条通知对应的事件:类型、发生时间与结构化变量,给消息模板与 Webhook 请求体用。 只能经 NewEvent 建:变量按事件目录里声明的种类规范化(int → int64,float → float64,列表截到 tmpl.MaxList 项), JSON 往返(outbox、RSS 与监控通知的重试)以后用同一个函数规范化,所以实时发送与重试拿到的类型完全一样。

func NewEvent added in v1.0.0

func NewEvent(typ string, at time.Time, fields map[string]any) *Event

NewEvent 建一个事件。fields 的键要和事件目录里声明的变量一致:没声明的丢掉,没给的按零值补上。

func SampleEvent added in v1.0.0

func SampleEvent(typ string) (ev *Event, title, text string)

SampleEvent 是这种事件的示例(按目录里各变量的 Sample),与内置标题、正文的示例:预览与保存前的校验用。

func (*Event) Data added in v1.0.0

func (e *Event) Data(title, text string) map[string]any

Data 是渲染模板用的数据:先放好同一组所有事件的全部变量的零值(Webhook 收到别的通知时不会打出 <no value>), 再放这个事件的变量与公共变量。title、text 是内置的标题与正文。目录里没有的事件类型按通知组算。

func (*Event) UnmarshalJSON added in v1.0.0

func (e *Event) UnmarshalJSON(b []byte) error

UnmarshalJSON 解出持久化的事件,按目录重新规范化。

type EventGroup added in v1.0.0

type EventGroup struct {
	Key  string `json:"key"`
	Name string `json:"name"`
	Desc string `json:"desc"`
}

EventGroup 是消息模板页上的一组事件。

type EventSpec added in v1.0.0

type EventSpec struct {
	Type        string `json:"type"`
	Group       string `json:"group"`
	Name        string `json:"name"`
	Desc        string `json:"desc"`
	NoTitle     bool   `json:"no_title,omitempty"`
	Vars        []Var  `json:"vars"`
	SampleTitle string `json:"sample_title"`
	SampleText  string `json:"sample_text"`
}

EventSpec 是一种事件:所在的组、名称、说明、专有变量,以及界面上展示的内置标题与正文的示例(按 Sample 生成的样子)。 NoTitle 的事件(ChatOps 命令回复、AI 助手回复)只有正文,没有标题模板。

func Spec added in v1.0.0

func Spec(typ string) *EventSpec

Spec 是事件类型的说明,不认识的类型返回 nil。

type Factory

type Factory func() Channel

type InboundHandler

type InboundHandler func(ctx context.Context, msg InboundMessage) error

type InboundMessage

type InboundMessage struct {
	ChannelType   string `json:"channel_type"`
	SourceConfID  uint   `json:"source_conf_id"`
	ChannelUserID string `json:"channel_user_id"`
	Username      string `json:"username"`
	ChatID        string `json:"chat_id"`
	MessageType   string `json:"message_type,omitempty"` // "private" | "group" — used by reply routing
	Text          string `json:"text"`
	IsCallback    bool   `json:"is_callback"`
	CallbackData  string `json:"callback_data"`
}

type LinkStater added in v0.48.0

type LinkStater interface {
	LinkState() string
}

LinkStater 由**能判断对端是否真的接上**的适配器实现,是可选能力。 不实现它的适配器,上层只会说「运行中」,不会说「已连接」。

type LiveSender added in v1.0.0

type LiveSender interface {
	Send(ctx context.Context, confID uint, n Notification) error
}

LiveSender 经运行中的通道实例投递一条通知。

type Notification

type Notification struct {
	// Event 是这条通知对应的事件(消息模板与 Webhook 请求体用);没有时照内置的标题与正文发。
	Event             *Event            `json:"event,omitempty"`
	Title             string            `json:"title"`
	Text              string            `json:"text"`
	Image             string            `json:"image,omitempty"`
	Link              string            `json:"link,omitempty"`
	ChannelType       string            `json:"channel_type,omitempty"`
	SourceConfID      uint              `json:"source_conf_id,omitempty"`
	UserID            string            `json:"user_id,omitempty"`
	Targets           map[string]string `json:"targets,omitempty"`
	Buttons           [][]Button        `json:"buttons,omitempty"`
	DisableWebPreview bool              `json:"disable_web_preview,omitempty"`
	OriginalMessageID string            `json:"original_message_id,omitempty"`
}

type OutboxEnqueuer

type OutboxEnqueuer interface {
	Enqueue(ctx context.Context, confID uint, n Notification, errMsg string) error
}

OutboxEnqueuer persists failed deliveries for asynchronous retry.

type OutboxWorker

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

OutboxWorker scans pending notification_outbox rows and retries delivery with bounded exponential backoff.

func NewOutboxWorker

func NewOutboxWorker(db *gorm.DB, registry *Registry, interval time.Duration) *OutboxWorker

NewOutboxWorker creates a worker. interval defaults to 10s when <= 0.

func (*OutboxWorker) SetConfigDecrypter added in v1.0.0

func (w *OutboxWorker) SetConfigDecrypter(fn func(string) (string, error))

SetConfigDecrypter 设置回退路径解密 ConfigJSON 的函数。须在 Start 之前调用。

func (*OutboxWorker) SetLiveSender added in v1.0.0

func (w *OutboxWorker) SetLiveSender(s LiveSender)

SetLiveSender 让重试经运行中的通道投递,不再按配置另建实例。须在 Start 之前调用。

func (*OutboxWorker) SetTemplates added in v1.0.0

func (w *OutboxWorker) SetTemplates(t *Templates)

SetTemplates 设置回退路径套用的全局消息模板。须在 Start 之前调用。

func (*OutboxWorker) Start

func (w *OutboxWorker) Start(ctx context.Context)

Start launches one ticker goroutine. Repeated calls do not start additional workers.

func (*OutboxWorker) Stop

func (w *OutboxWorker) Stop()

Stop cancels the worker and waits up to 1s for the goroutine to exit.

func (*OutboxWorker) Tick

func (w *OutboxWorker) Tick(ctx context.Context) error

Tick performs one scan of due pending rows and attempts delivery.

type Registry

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

func DefaultRegistry

func DefaultRegistry() *Registry

func NewRegistry

func NewRegistry() *Registry

func (*Registry) Make

func (r *Registry) Make(typ string) (Channel, error)

func (*Registry) Register

func (r *Registry) Register(typ string, factory Factory)

func (*Registry) Types

func (r *Registry) Types() []string

type RouteScope

type RouteScope struct {
	ConfIDs    []uint
	EventType  string
	PrimaryID  string
	SkipDedupe bool
}

type Router

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

Router fans a notification out to enabled channel configurations, while keeping per-configuration channel instances private and reusable.

func NewRouter

func NewRouter(registry *Registry, outbox OutboxEnqueuer, confs ConfLister) *Router

func (*Router) Route

func (r *Router) Route(ctx context.Context, n Notification, scope RouteScope) error

type TemplateSource added in v1.0.0

type TemplateSource struct {
	EventType string
	Title     string
	Text      string
}

TemplateSource 是一种事件的全局消息模板原文。Title、Text 空着的一项用内置文字。

type Templates added in v1.0.0

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

Templates 是内存里的全局消息模板(按事件类型一套):启动时从库里读入,保存或恢复默认时整体替换。并发安全。 发送前经 Apply 套用;模板渲染出错或结果为空时保留内置文字,通知不会因为模板写坏而发不出去。

func NewTemplates added in v1.0.0

func NewTemplates(logf func(format string, args ...any)) *Templates

NewTemplates 建一个空的模板集(全部用内置文字)。logf 为 nil 时不记警告。

func (*Templates) Apply added in v1.0.0

func (t *Templates) Apply(n Notification) Notification

Apply 按 n.Event 的类型套用模板,重新生成标题与正文;没有事件、没有模板、渲染出错或结果为空时保留原来的。 按钮等其余字段原样保留。

func (*Templates) ApplyText added in v1.0.0

func (t *Templates) ApplyText(ev *Event, text string) string

ApplyText 按事件类型套用正文模板,给只有正文的 ChatOps 命令回复与 AI 助手回复用: 没有事件、没有模板、渲染出错或结果为空时返回 text。

func (*Templates) Replace added in v1.0.0

func (t *Templates) Replace(srcs []TemplateSource)

Replace 整体换成 srcs。每份都按防护规则重新解析,不合格的当没有模板并记一条警告(库里的数据可能早于现在的规则)。

type Var added in v1.0.0

type Var struct {
	Key    string  `json:"key"`
	Type   VarType `json:"type"`
	Desc   string  `json:"desc"`
	Sample any     `json:"sample,omitempty"`
	Item   []Var   `json:"item,omitempty"`
}

Var 是一个模板变量。列表的每一项是对象,字段在 Item 里。

type VarType added in v1.0.0

type VarType string

VarType 是变量的种类。数字分整数与浮点数:规范化按声明转成 int64 或 float64,不看字面上有没有小数点。

const (
	VarString VarType = "string"
	VarInt    VarType = "int"
	VarFloat  VarType = "float"
	VarBool   VarType = "bool"
	VarList   VarType = "list"
)

Directories

Path Synopsis
adapter
bark
Package bark 是 Bark(iOS 推送)出站通道:POST {server}/push,JSON 里带 device_key;返回 code 为 200 才算成功。
Package bark 是 Bark(iOS 推送)出站通道:POST {server}/push,JSON 里带 device_key;返回 code 为 200 才算成功。
dingtalk
Package dingtalk 是钉钉群自定义机器人出站通道。
Package dingtalk 是钉钉群自定义机器人出站通道。
feishu
Package feishu 是飞书(Lark)群自定义机器人出站通道。
Package feishu 是飞书(Lark)群自定义机器人出站通道。
feishuapp
Package feishuapp 是飞书(Lark)企业自建应用机器人通道(类型 feishu_app):经官方 Go SDK 的长连接收 「接收消息」事件,经 im/v1 接口发文字消息。
Package feishuapp 是飞书(Lark)企业自建应用机器人通道(类型 feishu_app):经官方 Go SDK 的长连接收 「接收消息」事件,经 im/v1 接口发文字消息。
ntfy
Package ntfy 是 ntfy 出站通道:按 JSON 发布,POST 到服务器根地址 {topic, title, message, priority, click}; 可选 access token(Bearer)或用户名密码(Basic)。
Package ntfy 是 ntfy 出站通道:按 JSON 发布,POST 到服务器根地址 {topic, title, message, priority, click}; 可选 access token(Bearer)或用户名密码(Basic)。
outbound
Package outbound 是只出站的通知适配器(Bark、Server 酱、ntfy、钉钉、飞书、企业微信群机器人)共用的发送工具。
Package outbound 是只出站的通知适配器(Bark、Server 酱、ntfy、钉钉、飞书、企业微信群机器人)共用的发送工具。
qq
serverchan
Package serverchan 是 Server 酱出站通道。
Package serverchan 是 Server 酱出站通道。
telegram
Package telegram implements the notify.Channel adapter for Telegram bots using mymmrac/telego with long-polling.
Package telegram implements the notify.Channel adapter for Telegram bots using mymmrac/telego with long-polling.
Package tmpl 是通知的模板引擎:Go 的 text/template,加上一组受控的函数与防护。
Package tmpl 是通知的模板引擎:Go 的 text/template,加上一组受控的函数与防护。

Jump to

Keyboard shortcuts

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