groups

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: AGPL-3.0 Imports: 21 Imported by: 1 module, 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.

README

StuHelper Groups

QQ 群服务候选模块,采用 AGPL-3.0-only。模块提供群配置、入群资格、成员处置、消息留存、举报建议、群事件订阅与娱乐命令。所有管理操作由服务端按学校、群和能力调用 platform admin.Service.Evaluate。

OpenAPI 版本为 0.4.0,HTTP 接口统一使用 /api/v1/groups 前缀,生成客户端位于 sdk。装配指南 描述 backend、数据库与 Koishi 接入;实施状态 记录验证与剩余接口。

pnpm install --frozen-lockfile
pnpm exec lefthook install
bash scripts/check-with-postgres.sh

Go 使用 1.27.3,Node 使用 24.22.1,pnpm 使用 10.33.4。platform 依赖固定为 stuhelper-platform v0.2.0,GOWORK=off 独立构建。

测试脚本创建仅监听独立 Unix socket 的 PostgreSQL,结束时删除本次数据库目录。可通过 STUHELPER_TEST_PG_BIN 指定 PostgreSQL 程序目录。测试不访问真实 QQ 账号、真实群或生产系统。

按账号信息查询的 Go 接口、能力、字段与范围限制见账号查询规格。

Documentation

Overview

Package groups owns group admission, management and voluntary entertainment.

Index

Constants

View Source
const MaxEventGroups = 1000

A bounded transaction provides all-or-nothing fanout. Overflow is a failure, not a partial acknowledgement; Sweep remains available for periodic recovery.

View Source
const OutboxChannel = "groups_outbox"

Variables

View Source
var (
	ErrUnprocessable   = errors.New("groups_unprocessable")
	ErrInvalid         = errors.New("groups_invalid_request")
	ErrUnauthenticated = errors.New("groups_unauthenticated")
	ErrForbidden       = errors.New("groups_forbidden")
	ErrNotFound        = errors.New("groups_not_found")
	ErrConflict        = errors.New("groups_conflict")
	ErrUnavailable     = errors.New("groups_unavailable")
	ErrDisabled        = errors.New("groups_disabled")
	ErrCooldown        = errors.New("groups_cooldown")
)

Functions

func OpenAPI

func OpenAPI() []byte

OpenAPI returns the exact provider contract for consumer compatibility checks.

Types

type Action

type Action struct {
	LeaseUntil *time.Time `json:"lease_until,omitempty"`
	ID         string     `json:"id"`
	Group      string     `json:"group"`
	Actor      Actor      `json:"actor"`
	Capability string     `json:"capability"`
	Command    Command    `json:"command"`
	State      string     `json:"state"`
	Result     string     `json:"result"`
	Created    time.Time  `json:"created"`
}

type Actor

type Actor struct {
	Issuer  string `json:"issuer"`
	Subject string `json:"subject"`
}

func (Actor) Key

func (a Actor) Key() string

func (Actor) Principal

func (a Actor) Principal() account.Principal

type Analyzer

type Analyzer interface {
	Analyze(context.Context, string) (string, []string, error)
}

type Authorizer

type Authorizer interface {
	Evaluate(context.Context, account.Principal, string, admin.Scope) error
}

type Blacklist

type Blacklist struct {
	ID        string    `json:"id"`
	Reason    string    `json:"reason"`
	Until     time.Time `json:"until"`
	Permanent bool      `json:"permanent"`
}

type BlacklistInput

type BlacklistInput struct {
	Groups  []string `json:"groups"`
	Target  string   `json:"target"`
	Reason  string   `json:"reason"`
	Seconds int64    `json:"seconds"`
	Remove  bool     `json:"remove"`
}

type Bot

type Bot interface {
	Execute(context.Context, Action) (Outcome, error)
	Lookup(context.Context, string) (Outcome, bool, error)
}

type BotIdentity

type BotIdentity struct {
	Bot    BotScope
	UserID string
}

type BotScope

type BotScope struct {
	Platform string
	BotID    string
}

BotScope identifies a registered adapter instance. Platform is onebot or official; connect is never a bot transport or evidence of a shared QQ identity.

type Bulk

type Bulk struct {
	Targets []string `json:"targets"`
	Command Command  `json:"command"`
	Preview bool     `json:"preview"`
}

type BulkItem

type BulkItem struct {
	Target string `json:"target"`
	Result Result `json:"result"`
}

type BulkResult

type BulkResult struct {
	Items []BulkItem `json:"items"`
}

type CardField

type CardField struct {
	Allowed   bool
	Available bool
	Value     string
}

CardField separates disclosure permission from source availability. Only allowed and available fields may enter a group card; absence is not a violation.

type Command

type Command struct {
	Kind     string `json:"kind"`
	Target   string `json:"target,omitempty"`
	Text     string `json:"text,omitempty"`
	Seconds  int64  `json:"seconds,omitempty"`
	Message  string `json:"message,omitempty"`
	Receiver string `json:"receiver,omitempty"`
	Enabled  bool   `json:"enabled,omitempty"`
}

type Delivery

type Delivery struct {
	ID       string `json:"id"`
	Receiver string `json:"receiver"`
	Action   string `json:"action"`
	State    string `json:"state"`
}

type EligibilityChange

type EligibilityChange struct {
	Owner    string `json:"owner"`
	Revision int64  `json:"revision"`
}

type Event

type Event struct {
	SpecVersion string          `json:"specversion"`
	ID          string          `json:"id"`
	Source      string          `json:"source"`
	Type        string          `json:"type"`
	Subject     string          `json:"subject"`
	Time        time.Time       `json:"time"`
	Revision    int64           `json:"revision"`
	Data        json.RawMessage `json:"data"`
}

type Facts

type Facts struct {
	StudentKnown bool
	StageKnown   bool
	Bound        bool
	Student      bool
	Alumni       bool
	Temporary    bool
	Fields       map[string]CardField
}

Facts contains current eligibility and card disclosure decisions supplied by backend. Bound is true only when all three independent QQ bindings are currently complete.

type FactsProvider

type FactsProvider interface {
	GroupFacts(ctx context.Context, principal account.Principal, owner, school string) (Facts, error)
}

FactsProvider is owned by groups; backend implements all provider mappings. Unknown stages and provider failures must not be turned into valid eligibility.

type GroupConfig

type GroupConfig struct {
	GroupSettings
	Number      string `json:"number"`
	Revision    int64  `json:"revision"`
	PasswordSet bool   `json:"password_set"`
}

type GroupConfigInput

type GroupConfigInput struct {
	GroupSettings
	Number           *string `json:"number,omitempty"`
	ExpectedRevision int64   `json:"expected_revision"`
	Password         *string `json:"password,omitempty"`
}

type GroupCounts

type GroupCounts struct{ Members, Pending int64 }

type GroupSettings

type GroupSettings struct {
	Name             string   `json:"name"`
	BotEnabled       bool     `json:"bot_enabled"`
	Welcome          string   `json:"welcome"`
	RulesTemplate    string   `json:"rules_template"`
	CheckCard        bool     `json:"check_card"`
	RemindCard       bool     `json:"remind_card"`
	BlockLinks       bool     `json:"block_links"`
	FrequencySeconds int64    `json:"frequency_seconds"`
	FrequencyLimit   int64    `json:"frequency_limit"`
	WarningLimit     int64    `json:"warning_limit"`
	ID               string   `json:"id"`
	School           string   `json:"school"`
	Mode             string   `json:"mode"`
	RequireStudent   bool     `json:"require_student"`
	AcceptAlumni     bool     `json:"accept_alumni"`
	AcceptTemporary  bool     `json:"accept_temporary"`
	GraceSeconds     int64    `json:"grace_seconds"`
	ReminderSeconds  int64    `json:"reminder_seconds"`
	RetentionSeconds int64    `json:"retention_seconds"`
	CardTemplate     string   `json:"card_template"`
	AutoCard         bool     `json:"auto_card"`
	DiceSides        int64    `json:"dice_sides"`
	MuteProbability  int64    `json:"mute_probability"`
	MuteSeconds      int64    `json:"mute_seconds"`
	CooldownSeconds  int64    `json:"cooldown_seconds"`
	Pity             int64    `json:"pity"`
	Keywords         []string `json:"keywords"`
	RepeatThreshold  int64    `json:"repeat_threshold"`
	AutoActions      []string `json:"auto_actions"`
}

type GroupSummary

type GroupSummary struct {
	ID             string `json:"id"`
	School         string `json:"school"`
	Name           string `json:"name"`
	Number         string `json:"number"`
	MemberCount    int64  `json:"member_count"`
	BotEnabled     bool   `json:"bot_enabled"`
	RequireStudent bool   `json:"require_student"`
	PendingCount   int64  `json:"pending_count"`
	Revision       int64  `json:"revision"`
}

type Hit

type Hit struct {
	ID      string   `json:"id"`
	Owner   string   `json:"owner"`
	Message string   `json:"message"`
	Rules   []string `json:"rules"`
	State   string   `json:"state"`
}

type IdentityResolver

type IdentityResolver interface {
	ResolveOwner(ctx context.Context, principal account.Principal, identity BotIdentity) (string, error)
	ResolveBotIdentity(ctx context.Context, principal account.Principal, owner string, bot BotScope) (BotIdentity, error)
}

IdentityResolver is the backend bot bridge's consumer-owned port. The provider must check the current service identity, bot scope and binding on every call. Errors use groups sentinels (errors.Is); unavailable is never a missing binding.

type ManagedGroup

type ManagedGroup struct {
	ID     string `json:"id"`
	School string `json:"school"`
}

ManagedGroup identifies a configured group; it deliberately omits card fields, messages, raw QQ identifiers and other membership data.

type Member

type Member struct {
	ID         string    `json:"id"`
	Joined     bool      `json:"joined"`
	Owner      string    `json:"owner"`
	State      string    `json:"state"`
	Deadline   time.Time `json:"deadline"`
	Reminder   time.Time `json:"reminder"`
	Password   bool      `json:"password"`
	Exempt     bool      `json:"exempt"`
	Extended   bool      `json:"extended"`
	Failures   int64     `json:"failures"`
	LastPlay   time.Time `json:"last_play"`
	MutedUntil time.Time `json:"muted_until"`
}

type Message

type Message struct {
	Attachments []string  `json:"attachments"`
	ID          string    `json:"id"`
	Owner       string    `json:"owner"`
	Body        string    `json:"body"`
	Recalled    bool      `json:"recalled"`
	Expires     time.Time `json:"expires"`
}

type MyGroup

type MyGroup struct {
	ID                string     `json:"id"`
	Name              string     `json:"name"`
	School            string     `json:"school"`
	Number            string     `json:"number"`
	Joined            bool       `json:"joined"`
	State             string     `json:"state"`
	Deadline          *time.Time `json:"deadline"`
	RequiresPassword  bool       `json:"requires_password"`
	Eligibility       string     `json:"eligibility"`
	MissingConditions []string   `json:"missing_conditions"`
	UnknownConditions []string   `json:"unknown_conditions"`
	NextActions       []string   `json:"next_actions"`
}

type OutboxReader

type OutboxReader interface {
	PendingOutbox(ctx context.Context, limit int, excludeSubjects []string) ([]Event, error)
	ConfirmOutbox(ctx context.Context, id string) error
}

OutboxReader is a trusted backend relay port. Exclusions are applied in SQL before ordering and limiting. Confirm only after all consumers commit durably.

type Outcome

type Outcome struct {
	Success bool
	Code    string
}

Bot must deduplicate by Action.ID and query actual outcomes after timeouts. Lookup returns found=false only when no execution took place. Never guess success.

type OwnerGroupRecord

type OwnerGroupRecord struct {
	Config GroupConfig
	Member Member
}

OwnerGroupRecord is internal repository data. Public owner queries still return only ManagedGroup; MyGroups explicitly projects a separate user-safe shape.

type Page

type Page[T any] struct {
	Items      []T    `json:"items"`
	NextCursor string `json:"next_cursor"`
}

type Report

type Report struct {
	ID          string   `json:"id"`
	Reporter    string   `json:"reporter"`
	Message     string   `json:"message"`
	Reason      string   `json:"reason"`
	State       string   `json:"state"`
	Analysis    string   `json:"analysis,omitempty"`
	Suggestions []string `json:"suggestions,omitempty"`
	Feedback    string   `json:"feedback,omitempty"`
}

type Repository

type Repository interface {
	Transaction(context.Context, func(Tx) error) error
}

type Result

type Result struct {
	ID     string `json:"id"`
	State  string `json:"state"`
	Action string `json:"action"`
	Value  int64  `json:"value"`
	Detail string `json:"detail"`
}

type Row

type Row struct {
	ID   string
	Data json.RawMessage
}

type Service

type Service struct {
	PlatformIdentity admin.Identity
	Repo             Repository
	Auth             Authorizer
	Facts            FactsProvider
	FactsPrincipal   account.Principal
	Bot              Bot
	AI               Analyzer
	Now              func() time.Time
	Random           func(int64) (int64, error)
}

func (*Service) Actions

func (s *Service) Actions(ctx context.Context, p account.Principal, g, cursor string, limit int) (Page[Action], error)

func (*Service) Batch

func (s *Service) Batch(ctx context.Context, p account.Principal, g, key string, in Bulk) (BulkResult, error)

func (*Service) Blacklist

func (s *Service) Blacklist(ctx context.Context, p account.Principal, g, cursor string, limit int) (Page[Blacklist], error)

func (*Service) Blacklists

func (s *Service) Blacklists(ctx context.Context, p account.Principal, key string, in BlacklistInput) (Result, error)

func (*Service) Cleanup

func (s *Service) Cleanup(ctx context.Context, g, cursor string) (string, error)

func (*Service) Command

func (s *Service) Command(ctx context.Context, p account.Principal, g, key string, cmd Command) (Result, error)

func (*Service) Configuration

func (s *Service) Configuration(ctx context.Context, p account.Principal, g string) (GroupConfig, error)

func (*Service) Configure

func (s *Service) Configure(ctx context.Context, p account.Principal, key string, in GroupConfigInput) (GroupConfig, error)

func (*Service) Consume

func (s *Service) Consume(ctx context.Context, event UpstreamEvent) error

Consume atomically records inbox/revision and reevaluates all affected groups. Source data only identifies the owner: current facts always come from Facts.

func (*Service) Deliveries

func (s *Service) Deliveries(ctx context.Context, p account.Principal, g, cursor string, limit int) (Page[Delivery], error)

func (*Service) Execute

func (s *Service) Execute(ctx context.Context, g, id string) (Action, error)

Execute serializes claims before an external call. Interrupted calls remain unknown and are resolved via Lookup on the next invocation with the same ID.

func (*Service) Fanout

func (s *Service) Fanout(ctx context.Context, e Event) error

Fanout consumes committed disposition events, independently queuing each enabled recipient. Delivery state is the recipient action's actual state.

func (*Service) Groups

func (s *Service) Groups(ctx context.Context, p account.Principal, cursor string, limit int) (Page[GroupSummary], error)

func (*Service) GroupsForOwner

func (s *Service) GroupsForOwner(ctx context.Context, owner account.Principal, cursor string, limit int) (Page[ManagedGroup], error)

GroupsForOwner is a trusted backend query, not an HTTP authorization bypass. It returns joined, non-removed memberships whose group configuration exists.

func (*Service) Hits

func (s *Service) Hits(ctx context.Context, p account.Principal, g, cursor string, limit int) (Page[Hit], error)

func (*Service) Ingest

func (s *Service) Ingest(ctx context.Context, g string, event Event, m Message) error

Ingest is a trusted backend boundary, never mounted as a public route. Only authenticated bot adapters may provide the actual group and sender.

func (*Service) MemberEvent

func (s *Service) MemberEvent(ctx context.Context, g string, event Event, owner string) error

MemberEvent receives verified group membership from the host bot adapter. A web application alone cannot claim that a QQ user has already joined.

func (*Service) Members

func (s *Service) Members(ctx context.Context, p account.Principal, g, cursor string, limit int) (Page[Member], error)

func (*Service) Messages

func (s *Service) Messages(ctx context.Context, p account.Principal, g, cursor string, limit int) (Page[Message], error)

func (*Service) MyGroups

func (s *Service) MyGroups(ctx context.Context, p account.Principal, cursor string, limit int) (Page[MyGroup], error)

MyGroups shares the indexed reverse lookup behind GroupsForOwner, including active applications. The only owner is the authenticated principal; no caller supplied owner, admin scope, or content fields enter the response.

func (*Service) Progress

func (s *Service) Progress(ctx context.Context, p account.Principal, g string) (Member, error)

func (*Service) Recover

func (s *Service) Recover(ctx context.Context, g, cursor string) (string, error)

Recover is called by the host for expired execution leases, with bounded pages.

func (*Service) Reports

func (s *Service) Reports(ctx context.Context, p account.Principal, g, cursor string, limit int) (Page[Report], error)

func (*Service) Subscriptions

func (s *Service) Subscriptions(ctx context.Context, p account.Principal, g, cursor string, limit int) (Page[Subscription], error)

func (*Service) Sweep

func (s *Service) Sweep(ctx context.Context, g, cursor string) (string, error)

Sweep is a bounded host job for qualification deadlines and reminders. Host persists its cursor and periodically starts at the beginning for new deadlines.

func (*Service) Warnings

func (s *Service) Warnings(ctx context.Context, p account.Principal, g, cursor string, limit int) (Page[Warnings], error)

func (*Service) Watch

func (s *Service) Watch(ctx context.Context, p account.Principal, g, cursor string, limit int) (Page[Watch], error)

type Subscription

type Subscription struct {
	ID       string `json:"id"`
	Receiver string `json:"receiver"`
	Enabled  bool   `json:"enabled"`
	Actor    Actor  `json:"actor"`
}

type Tx

type Tx interface {
	Get(string, string, any) error
	Put(string, string, any) error
	Delete(string, string) error
	List(string, string, int) ([]Row, error)
	PendingActions(string) (int, error)
	GroupCounts([]string) (map[string]GroupCounts, error)
	OwnerGroups(owner, cursor string, limit int, includeApplicants bool) (Page[ManagedGroup], error)
	OwnerGroupRecords(owner, cursor string, limit int, includeApplicants bool) (Page[OwnerGroupRecord], error)
	Emit(Event) error
	Accept(Event) (bool, error)
}

type UpstreamEvent

type UpstreamEvent struct {
	SpecVersion     string            `json:"specversion"`
	ID              string            `json:"id"`
	Source          string            `json:"source"`
	Type            string            `json:"type"`
	Subject         string            `json:"subject"`
	Time            time.Time         `json:"time"`
	DataContentType string            `json:"datacontenttype"`
	SchoolID        string            `json:"schoolid,omitempty"`
	Data            EligibilityChange `json:"data"`
}

UpstreamEvent uses the providers' public CloudEvents shape. Preserve source and subject: verification uses object streams; qq-binding uses an owner stream.

type Warnings

type Warnings struct {
	ID    string `json:"id"`
	Count int64  `json:"count"`
}

type Watch

type Watch struct {
	ID      string `json:"id"`
	Enabled bool   `json:"enabled"`
	Reason  string `json:"reason"`
}

Directories

Path Synopsis
Package accountquery provides the module-owned account investigation port.
Package accountquery provides the module-owned account investigation port.
Package httpapi accepts principals only from the host authentication middleware.
Package httpapi accepts principals only from the host authentication middleware.
Package postgres owns all groups SQL.
Package postgres owns all groups SQL.
Package sdk provides primitives to interact with the openapi HTTP API.
Package sdk provides primitives to interact with the openapi HTTP API.

Jump to

Keyboard shortcuts

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