drim

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 34 Imported by: 0

README

DeepRespond IM 服务端 Go SDK

版本 v1.0.2,MIT 许可证,Go 1.23 或以上,仅依赖标准库。

使用应用身份调用 OpenAPI,管理用户、群组、消息、文件、聊天室、推送与音视频频道,并签发用户登录凭证。提供签名回调的校验、防重放、事件去重与处理器。 模块 github.com/DeepRespond-AI/deeprespond-im-server-go-sdk,包名 drim;回调在 callback,模拟服务与测试辅助在 drimtest。

安装

go get github.com/DeepRespond-AI/deeprespond-im-server-go-sdk@v1.0.2
import drim "github.com/DeepRespond-AI/deeprespond-im-server-go-sdk"
import "github.com/DeepRespond-AI/deeprespond-im-server-go-sdk/callback"

在线文档 · Demo 指南 · 更新记录

客户端应用需要以 IM 用户身份登录、建立长连接和收发消息时,请使用 Go 客户端 SDK。客户端和服务端 SDK 使用不同身份与凭证。

调用 OpenAPI

import drim "github.com/DeepRespond-AI/deeprespond-im-server-go-sdk"

client, err := drim.New(drim.Config{
    BaseURL:      "https://im.example.com",
    OrgName:      "1100250925",
    AppName:      "demo",
    ClientID:     os.Getenv("IM_CLIENT_ID"),
    ClientSecret: os.Getenv("IM_CLIENT_SECRET"),
})
if err != nil {
    return err
}
defer client.Close()

// 用户登录业务系统后,为他签发登录凭证,交给 App 用客户端 SDK 登录
ticket, err := client.Users.IssueLoginTicket(ctx, "zhangsan", drim.IssueLoginTicketParams{AutoCreate: true})

// 以业务的通知账号发单聊;业务单号作为 client_msg_id,重试也不会重复发送
msg, err := client.Messages.Send(ctx, drim.SendMessageParams{
    From: "notice", ToUser: "zhangsan", ClientMsgID: "order-1001-paid",
    Type: "custom", Body: drim.JSON(`{"card":"order","order_id":"1001"}`),
})

for user, err := range client.Users.All(ctx, drim.ListUsersParams{Status: "active"}) { // 自动翻页
    if err != nil { return err }
    _ = user
}
  • 客户端在进程中复用:它可以被多个协程同时使用,持有连接池和 App Token;App Token 由 SDK 换取、缓存、提前续期,失效后自动重新换取。
  • ctx 是整次调用的总时限(含重试、限流等待和等待换取令牌);每次尝试的时限是 Config.Timeout(默认 30 秒)。单次调用的选项通过 ctx 传入:drim.WithRequestID、WithAttemptTimeout、WithMaxAttempts、WithMaxRetryAfter。
  • 重试:查询、带幂等键的写操作(发消息)、本身幂等的写操作在网络错误、超时、5xx 时自动重试;建群、设置密码等不幂等的写操作发出后不重试。被限流时按 Retry-After 等待后重发:应用额度用完时整个客户端一起等待,某个群、聊天室被限流时只有这个请求等待。
  • 三种状态的参数:drim.Field[T] 区分“不传”(零值)、drim.Null[T]() 和 drim.Set(v),如修改资料时 Attributes: drim.Set(map[string]drim.Field[string]{"level": drim.Null[string]()}) 删除一项属性;只有“不传”和“传值”的用指针(drim.String、drim.Int64)。
  • 原样发送 JSON:消息的 Body、Ext 是 json.RawMessage(drim.JSON(s),或 drim.Marshal(v) 编码时不转义 <>&),发送时只去掉空白,写法逐字节保留;响应中的 Body 与服务端返回的逐字节相同。每个响应类型都有 Raw。
错误
var e *drim.Error
if errors.As(err, &e) {
    log.Print(e.Code, e.Reason(), e.RequestID) // 按 Code 判断,不解析 Message
}
drim.IsCode(err, drim.CodeAlreadyExists)
drim.IsTemporary(err)          // 网络错误、超时、5xx、rate_limited

自动重试后得到 already_exists、not_found、version_conflict 时,e.Retried 为真:前一次尝试可能已经执行。批量接口逐项的失败在结果中(FailedItems()、OK()、Err())。

文件
f, _ := os.Open("a.jpg")
st, _ := f.Stat()
file, err := client.Media.Upload(ctx, f, st.Size(), drim.UploadParams{Purpose: "attachment", Kind: "image"})
client.Messages.Send(ctx, drim.SendMessageParams{From: "notice", ToUser: "zhangsan", Type: "image",
    Body: drim.JSON(`{"url":"` + file.URL + `"}`)})
n, err := client.Media.Download(ctx, file.URL, w)

不超过 32 MB 的一次上传,更大的分片并发上传;中断后可以用 ResumeUpload(ctx, fileID, r, size, params) 续传。

接收回调

import "github.com/DeepRespond-AI/deeprespond-im-server-go-sdk/callback"

h, err := callback.NewHandler(callback.Config{
    Secrets: callback.StaticSecrets{"1840200000000000007": {"cbs_新密钥…", "cbs_旧密钥…"}},
    Nonces:  callback.NewMemoryNonceStore(),        // 多实例部署时换成共享存储
    Dedup:   callback.NewMemoryDedupStore(24 * time.Hour),
    Events: callback.EventHandlers{
        MessageSent: func(ctx context.Context, ev *callback.Event, d *callback.MessageSent) error {
            return archive(d.MessageID, d.Body) // d.Body 与请求体中的逐字节相同
        },
    },
    Hooks: callback.HookHandlers{
        MessageBeforeSend: func(ctx context.Context, req *callback.MessageBeforeSend) (callback.Verdict, error) {
            if containsBannedWord(req.Body) {
                return callback.Reject("forbidden_word", "消息中有不允许的内容"), nil
            }
            return callback.Allow(), nil
        },
    },
})
http.Handle("POST /im/callback", h) // Gin:gin.WrapH(h);Echo:echo.WrapHandler(h)
  • 重复的事件(同一个事件 ID)不再调用处理函数,返回 2xx;一批事件中有处理失败的,停止处理并整批返回 503,服务端稍后重发(已完成的被跳过)。处理函数返回 callback.RetryAfter(d, err) 时带上 Retry-After。
  • 同步回调的处理函数的 ctx 截止时间为 timeout_ms 减 50 毫秒,超时或出错时返回 HookFallback(没有设置时 503);返回的结果在本地检查,不合规的不发出。
  • 量大的消息抄送用异步方式:Queue 交给调用方的持久队列,入队即完成。
共享存储(Redis)

SDK 只依赖标准库,没有内置 Redis 的实现。用 github.com/redis/go-redis/v9 实现三个接口的写法:

type RedisStores struct{ R *redis.Client; Prefix string }

// 令牌存储(drim.TokenStore):值为 "{到期的毫秒}:{令牌}"
func (s RedisStores) Get(ctx context.Context, key string) (string, time.Time, bool, error) {
    v, err := s.R.Get(ctx, s.Prefix+key).Result()
    if errors.Is(err, redis.Nil) { return "", time.Time{}, false, nil }
    if err != nil { return "", time.Time{}, false, err }
    ms, token, ok := strings.Cut(v, ":")
    n, _ := strconv.ParseInt(ms, 10, 64)
    return token, time.UnixMilli(n), ok, nil
}
func (s RedisStores) Set(ctx context.Context, key, token string, expiresAt time.Time) error {
    return s.R.Set(ctx, s.Prefix+key, fmt.Sprintf("%d:%s", expiresAt.UnixMilli(), token), time.Until(expiresAt)).Err()
}
var compareAndDelete = redis.NewScript(`local v = redis.call('GET', KEYS[1])
if v then local i = string.find(v, ':', 1, true)
  if i and string.sub(v, i + 1) == ARGV[1] then return redis.call('DEL', KEYS[1]) end end
return 0`)
func (s RedisStores) CompareAndDelete(ctx context.Context, key, token string) error {
    return compareAndDelete.Run(ctx, s.R, []string{s.Prefix + key}, token).Err()
}

// 随机数(callback.NonceStore)
func (s RedisStores) Seen(ctx context.Context, nonce string, ttl time.Duration) (bool, error) {
    ok, err := s.R.SetNX(ctx, s.Prefix+"nonce:"+nonce, 1, ttl).Result()
    return !ok, err
}

// 事件去重(callback.DedupStore):占用、完成、释放都按占用的令牌比较;完成后保留 7 天
var claim = redis.NewScript(`local v = redis.call('GET', KEYS[1])
if not v then redis.call('SET', KEYS[1], 'busy:' .. ARGV[1], 'PX', ARGV[2]) return 'acquired' end
if v == 'done' then return 'done' end
return 'busy'`)
var complete = redis.NewScript(`if redis.call('GET', KEYS[1]) == 'busy:' .. ARGV[1] then
  redis.call('SET', KEYS[1], 'done', 'PX', ARGV[2]) return 1 end
return 0`)
var release = redis.NewScript(`if redis.call('GET', KEYS[1]) == 'busy:' .. ARGV[1] then return redis.call('DEL', KEYS[1]) end
return 0`)
func (s RedisStores) Claim(ctx context.Context, id string, ttl time.Duration) (callback.ClaimState, string, error) {
    token := uuid.NewString()
    r, err := claim.Run(ctx, s.R, []string{s.Prefix + "event:" + id}, token, ttl.Milliseconds()).Text()
    switch {
    case err != nil: return 0, "", err
    case r == "acquired": return callback.Acquired, token, nil
    case r == "done": return callback.Done, "", nil
    }
    return callback.Busy, "", nil
}
func (s RedisStores) Complete(ctx context.Context, id, token string) error {
    return complete.Run(ctx, s.R, []string{s.Prefix + "event:" + id}, token, (7 * 24 * time.Hour).Milliseconds()).Err()
}
func (s RedisStores) Release(ctx context.Context, id, token string) error {
    return release.Run(ctx, s.R, []string{s.Prefix + "event:" + id}, token).Err()
}

测试自己的代码

srv := drimtest.NewServer()            // 假的 OpenAPI
defer srv.Close()
srv.Fail("messages.send", "rate_limited", drimtest.FailOptions{RetryAfter: "1"})
client, _ := drim.New(srv.Config())
// ...
calls := srv.Calls("messages.send")    // 收到的请求

req := drimtest.SignedRequest(endpointID, drimtest.EventRequest(drimtest.Event{Type: "user.created", Data: data}), secret)
handler.ServeHTTP(recorder, req)        // 带正确签名的回调请求

drimtest.SignatureVectors() 是签名的测试向量(与服务端和对外文档相同),可以用来确认部署环境(如反向代理没有改动请求体)。

Demo

demo/ 是单进程 Web 即时通讯演示,使用本 SDK 完成业务服务端操作,通过签名回调实时推送。 设备适配层只在后端保存 User Token,处理用户可见历史、撤回、原子改密和登录有效性;它不扩展 SDK 的公共 API。 文件结构、启动方式和带截图的回归命令见 demo/README.md。

服务端 SDK 使用应用权限,调用方必须在业务接口中校验当前用户、会话归属和群角色。 尤其 Conversations.Messages 是管理视角,不过滤逐用户删除、清空及入退群范围;用户界面应通过客户端接口读取历史。 Media.Download 只写出文件字节;HTTP 代理需要自行设置安全的响应类型、下载方式和缓存策略,不能信任用户传入的 MIME。

开发

  • 类型、参数和方法由 spec 生成(*_gen.go):改了接口描述后运行 go generate(即 python3 internal/codegen/generate.py,需要 PyYAML)。
  • make sdk-server-go-test:生成代码一致性、gofmt、go vet、go test -race。
  • make sdk-server-go-integration:连接 sdk/conformance/harness 的集成测试和回调的端到端测试(go test -tags integration ./integration/)。

独立 RTC 频道管理已提供生成的强类型 Channels/channels API:创建、修改、关闭、票据、成员管理、统计与更正列表。Go 使用 RTCChannel*Params/Result,Node.js/Python 返回具体模型;Python 支持同步/异步。期限保留未设置/null/值三态,票据签发不自动重试。旧 Go 原始 JSON 接口需迁移到新参数/结果;管理 API 不能代替用户登录获取媒体 Token。完整契约及计费规则见仓库 docs/RTC频道/4.实现与部署.md。

Documentation

Overview

Package drim 是深应智能(DeepRespond)IM 的服务端 Go SDK:在业务服务端调用 OpenAPI(管理用户、好友、群组、消息、文件、 推送设置、聊天室、内容安全、通话和在线状态,签发登录凭证)。接收回调见子包 callback,测试辅助见子包 drimtest。

一个客户端对应一个应用,可以被多个协程同时使用,应在进程中复用:

client, err := drim.New(drim.Config{
	BaseURL:      "https://im.example.com",
	OrgName:      "1100250925",
	AppName:      "demo",
	ClientID:     os.Getenv("IM_CLIENT_ID"),
	ClientSecret: os.Getenv("IM_CLIENT_SECRET"),
})
ticket, err := client.Users.IssueLoginTicket(ctx, "zhangsan", drim.IssueLoginTicketParams{AutoCreate: true})

每个方法的第一个参数是 context.Context:截止时间是整次调用的总时限(含重试、限流等待和等待换取令牌)。 返回的错误都是 *Error(errors.As),按 Code 和 Details 判断。

行为规则见仓库中的 docs/server-go。类型、参数和方法由 sdk/server/spec 生成(*_gen.go,go generate 重新生成)。

Index

Constants

View Source
const (
	ToolRunning = "running"
	ToolDone    = "done"
	ToolFailed  = "failed"
)

工具调用的状态。

View Source
const (
	CodeInvalidArgument   = "invalid_argument"
	CodeUnauthenticated   = "unauthenticated"
	CodeInvalidClient     = "invalid_client"
	CodePermissionDenied  = "permission_denied"
	CodeIPNotAllowed      = "ip_not_allowed"
	CodeTenantUnavailable = "tenant_unavailable"
	CodeAppUnavailable    = "app_unavailable"
	CodeUserDisabled      = "user_disabled"
	CodeNotGroupMember    = "not_group_member"
	CodeGroupDisabled     = "group_disabled"
	CodeChatroomDisabled  = "chatroom_disabled"
	CodeMessageRejected   = "message_rejected"
	CodeContentRejected   = "content_rejected"
	CodeFileBlocked       = "file_blocked"
	CodeNotFound          = "not_found"
	CodeMethodNotAllowed  = "method_not_allowed"
	CodeAlreadyExists     = "already_exists"
	CodeConflict          = "conflict"
	CodeUnavailable       = "unavailable"
	CodeVersionConflict   = "version_conflict"
	CodeLimitExceeded     = "limit_exceeded"
	CodeFileExpired       = "file_expired"
	CodePayloadTooLarge   = "payload_too_large" // 也是 SDK 的本地错误(StatusCode 为 0)
	CodeRateLimited       = "rate_limited"
	CodeInternal          = "internal"
	CodeStreamInProgress  = "stream_in_progress" // 会话中已有进行中的 AI 回复,details.stream_id
	CodeStreamClosed      = "stream_closed"      // AI 回复已结束,details.reason 为结束状态
	CodeSeqGap            = "seq_gap"            // 增量序号不连续,details.expected_seq
	CodeNetworkError      = "network_error"      // 连接失败、连接中断、TLS 错误
	CodeTimeout           = "timeout"            // 尝试超时或 ctx 的截止时间已到
	CodeCanceled          = "canceled"           // ctx 被取消
	CodeInvalidParams     = "invalid_params"     // 本地检查不通过,Details["field"] 指出参数
	CodeInvalidResponse   = "invalid_response"   // 响应不是预期的 JSON,Details["body_prefix"] 为响应体的前 512 字节
	CodeClientUnavailable = "client_unavailable" // 客户端已关闭、已永久失效,或处于换取令牌失败后的冷却期

)

服务端的错误码(《1.功能概述文档》第 5 节)。以后新增的错误码照常放在 Error.Code 中。

View Source
const Version = "1.0.2"

Version 是 SDK 的版本,出现在 User-Agent 中(deeprespond-im-server-sdk/go/{Version})。

Variables

View Source
var (
	// ErrStreamStopped 表示用户点了停止生成,或流已被平台结束(超时、被替换等)。
	ErrStreamStopped = errors.New("drim: 回复已被停止或结束")
)

停止的原因,ai.stream_stopped 和 stream_closed 时 Stream.Context 的 Cause。

Functions

func Bool

func Bool(b bool) *bool

Bool 返回 b 的指针。

func Float64

func Float64(f float64) *float64

Float64 返回 f 的指针。

func Int

func Int(n int) *int

Int 返回 n 的指针。

func Int64

func Int64(n int64) *int64

Int64 返回 n 的指针(seq、版本号、时长等)。

func IsCode

func IsCode(err error, code string) bool

IsCode 判断 err 是不是错误码为 code 的 *Error。

func IsPermanentlyUnavailable

func IsPermanentlyUnavailable(err error) bool

IsPermanentlyUnavailable 应用已删除、租户已注销(unauthenticated 的 app_deleted、tenant_closed), 以及因此永久失效的客户端返回的 client_unavailable:应清除保存的凭据。

func IsReason

func IsReason(err error, code, reason string) bool

IsReason 判断 err 是不是错误码为 code、details.reason 为 reason 的 *Error。

func IsServiceUnavailable

func IsServiceUnavailable(err error) bool

IsServiceUnavailable 服务暂停或只读:tenant_unavailable、app_unavailable,以及冷却期中最初为二者的 client_unavailable。

func IsTemporary

func IsTemporary(err error) bool

IsTemporary 网络错误、超时、internal、5xx、rate_limited:稍后可以再试。

func JSON

func JSON(s string) json.RawMessage

JSON 把 JSON 文本转为 json.RawMessage,用于消息的 Body、Ext 等自由内容;发送时原样保留写法(只去掉空白)。

func Marshal

func Marshal(v any) (json.RawMessage, error)

Marshal 把 v 编码为 JSON,不转义 HTML 字符(<、>、& 原样),用于构造消息的 Body、Ext。 encoding/json 的 json.Marshal 会把它们写成 < 等,消息的大小变大,租户对内容的签名也对不上。

func String

func String(s string) *string

String 返回 s 的指针,用于只有“不传”和“传值”两种状态的可选参数(如 UpdateUserParams.Nickname)。

func WithAttemptTimeout

func WithAttemptTimeout(ctx context.Context, d time.Duration) context.Context

WithAttemptTimeout 这次调用中每次尝试的时限,覆盖 Config.Timeout(也覆盖完成上传的 150 秒)。

func WithMaxAttempts

func WithMaxAttempts(ctx context.Context, n int) context.Context

WithMaxAttempts 这次调用中网络错误、超时、5xx 的最多尝试次数(含第一次),1 表示不自动重试; 限流后的等待重发仍按 RetryPolicy.MaxRateLimited。

func WithMaxRetryAfter

func WithMaxRetryAfter(ctx context.Context, d time.Duration) context.Context

WithMaxRetryAfter 这次调用自动等待的 Retry-After 上限;0 表示被限流时不等待,直接返回 rate_limited。

func WithRequestID

func WithRequestID(ctx context.Context, id string) context.Context

WithRequestID 作为 X-Request-ID 发送调用方的追踪 ID(服务端原样沿用并写入日志),同一次调用的重试沿用同一个 ID。 必须是 1 到 64 个字母、数字或 - _ .,不合规的在本地以 invalid_params 拒绝(服务端会把它换掉,日志就对不上了)。

Types

type AICreateBotResult added in v1.0.2

type AICreateBotResult struct {
	Bot Bot `json:"bot"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

AICreateBotResult AICreateBotResult

func (*AICreateBotResult) UnmarshalJSON added in v1.0.2

func (v *AICreateBotResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type AICreateStreamResult added in v1.0.2

type AICreateStreamResult struct {
	Stream AIStream `json:"stream"`
	// Duplicate 由状态码得出:为真表示重复提交,结果是第一次的。
	Duplicate bool `json:"-"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

AICreateStreamResult AICreateStreamResult

func (*AICreateStreamResult) UnmarshalJSON added in v1.0.2

func (v *AICreateStreamResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type AIDelta added in v1.0.2

type AIDelta struct {
	// 必填
	Seq int64
	// 必填
	Ops []AIOp
}

AIDelta 一段增量

type AIDisableBotResult added in v1.0.2

type AIDisableBotResult struct {
	Bot Bot `json:"bot"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

AIDisableBotResult AIDisableBotResult

func (*AIDisableBotResult) UnmarshalJSON added in v1.0.2

func (v *AIDisableBotResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type AIEnableBotResult added in v1.0.2

type AIEnableBotResult struct {
	Bot Bot `json:"bot"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

AIEnableBotResult AIEnableBotResult

func (*AIEnableBotResult) UnmarshalJSON added in v1.0.2

func (v *AIEnableBotResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type AIError added in v1.0.2

type AIError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

AIError AIError

func (*AIError) UnmarshalJSON added in v1.0.2

func (v *AIError) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type AIFailStreamResult added in v1.0.2

type AIFailStreamResult struct {
	Stream AIStream `json:"stream"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

AIFailStreamResult AIFailStreamResult

func (*AIFailStreamResult) UnmarshalJSON added in v1.0.2

func (v *AIFailStreamResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type AIFinishStreamResult added in v1.0.2

type AIFinishStreamResult struct {
	Stream AIStream `json:"stream"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

AIFinishStreamResult AIFinishStreamResult

func (*AIFinishStreamResult) UnmarshalJSON added in v1.0.2

func (v *AIFinishStreamResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type AIGetBotResult added in v1.0.2

type AIGetBotResult struct {
	Bot Bot `json:"bot"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

AIGetBotResult AIGetBotResult

func (*AIGetBotResult) UnmarshalJSON added in v1.0.2

func (v *AIGetBotResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type AIGetStreamResult added in v1.0.2

type AIGetStreamResult struct {
	Stream AIStream `json:"stream"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

AIGetStreamResult AIGetStreamResult

func (*AIGetStreamResult) UnmarshalJSON added in v1.0.2

func (v *AIGetStreamResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type AIOp added in v1.0.2

type AIOp struct {
	// 必填
	Op string
	// 必填
	Index int64
	Type  string
	Text  string
	Part  *AIPart
}

AIOp 增量中的一个操作:append 向文字片段追加(type、text),put 整体设置一个片段(part)

type AIPart added in v1.0.2

type AIPart struct {
	Type     string `json:"type"`
	Text     string `json:"text"`
	URL      string `json:"url"`
	Width    int64  `json:"width"`
	Height   int64  `json:"height"`
	Alt      string `json:"alt"`
	Name     string `json:"name"`
	Size     int64  `json:"size"`
	MimeType string `json:"mime_type"`
	ID       string `json:"id"`
	Title    string `json:"title"`
	State    string `json:"state"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

AIPart 片段:text、reasoning 为文字;image、file 为附件;tool 为工具调用的进度

func (*AIPart) UnmarshalJSON added in v1.0.2

func (v *AIPart) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type AIService added in v1.0.2

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

AIService AI 对话:机器人管理与流式回复(client.AI);流式写入用 StartStream。

func (*AIService) AllBots added in v1.0.2

func (s *AIService) AllBots(ctx context.Context, params ListOptions) iter.Seq2[Bot, error]

AllBots 逐项遍历 ListBots 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。

func (*AIService) CreateBot added in v1.0.2

func (s *AIService) CreateBot(ctx context.Context, username string, params CreateBotParams) (*AICreateBotResult, error)

CreateBot 创建机器人

在同一事务中创建 kind 为 bot 的 IM 用户和机器人配置,加好友方式设为 allow_any。用户名已存在返回 already_exists; 应用的机器人数已达上限返回 limit_exceeded(app_bots)。机器人不能登录、不能入群。

接口:POST /ai/bots(ai.create_bot)。以唯一标识创建,可以自动重试;重试后得到 already_exists 时错误的 Retried 为真,可以按“前一次尝试已经创建”处理。

func (*AIService) CreateStream added in v1.0.2

func (s *AIService) CreateStream(ctx context.Context, bot, to string, params CreateStreamParams) (*AICreateStreamResult, error)

CreateStream 开始一条流式回复(底层接口,通常用 StartStream)

以机器人的身份给用户写入一条 status 为 streaming 的 ai 消息。按 client_stream_id 去重:重复提交返回 200 和已有的流(不论是否已结束), 没有给时 SDK 生成。会话中已有进行中的回复返回 stream_in_progress(details.stream_id),replace 为真时先把它结束为 stopped(replaced)。 机器人停用为 permission_denied(bot_disabled),用户拉黑了机器人为 user_blocked,进行中的回复数已达上限为 limit_exceeded(bot_active_streams)。

接口:POST /ai/streams(ai.create_stream)。带幂等键的写操作,用同一个键自动重试。

func (*AIService) DeleteBot added in v1.0.2

func (s *AIService) DeleteBot(ctx context.Context, username string) error

DeleteBot 删除机器人及其 IM 用户

进行中的回复以 failed(bot_deleted)结束。机器人不存在返回 not_found。

接口:DELETE /ai/bots/{username}(ai.delete_bot)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*AIService) DisableBot added in v1.0.2

func (s *AIService) DisableBot(ctx context.Context, username string) (*AIDisableBotResult, error)

DisableBot 停用机器人

停用后不再回调,开始新回复返回 permission_denied(bot_disabled);进行中的回复不受影响。

接口:POST /ai/bots/{username}/disable(ai.disable_bot)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*AIService) EnableBot added in v1.0.2

func (s *AIService) EnableBot(ctx context.Context, username string) (*AIEnableBotResult, error)

EnableBot 启用机器人

接口:POST /ai/bots/{username}/enable(ai.enable_bot)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*AIService) FailStream added in v1.0.2

func (s *AIService) FailStream(ctx context.Context, streamID, code, message string) (*AIFailStreamResult, error)

FailStream 报告失败(生成中断)

以 failed(developer)结束,已生成的部分保留;客户端显示 message。流已结束返回 stream_closed。

接口:POST /ai/streams/{stream_id}/fail(ai.fail_stream)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*AIService) FinishStream added in v1.0.2

func (s *AIService) FinishStream(ctx context.Context, streamID string, lastSeq int64, params FinishStreamParams) (*AIFinishStreamResult, error)

FinishStream 结束流(已完成)

last_seq 必须等于已接受的最后一段,否则返回 seq_gap;流已结束返回 stream_closed。

接口:POST /ai/streams/{stream_id}/finish(ai.finish_stream)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*AIService) GetBot added in v1.0.2

func (s *AIService) GetBot(ctx context.Context, username string) (*AIGetBotResult, error)

GetBot 查询机器人

用户不存在返回 not_found;用户不是机器人返回 invalid_argument(not_bot)。

接口:GET /ai/bots/{username}(ai.get_bot)。查询,网络错误、超时、5xx 时自动重试。

func (*AIService) GetStream added in v1.0.2

func (s *AIService) GetStream(ctx context.Context, streamID string) (*AIGetStreamResult, error)

GetStream 查询流

生成中和结束 10 分钟内带 content(累积的片段)。

接口:GET /ai/streams/{stream_id}(ai.get_stream)。查询,网络错误、超时、5xx 时自动重试。

func (*AIService) ListBots added in v1.0.2

func (s *AIService) ListBots(ctx context.Context, params ListOptions) (*Page[Bot], error)

ListBots 分页列出机器人

接口:GET /ai/bots(ai.list_bots)。查询,网络错误、超时、5xx 时自动重试。

func (*AIService) StartStream added in v1.0.2

func (s *AIService) StartStream(ctx context.Context, in StartStreamInput) (*Stream, error)

StartStream 开始一条流式回复,返回的 Stream 可以被多个协程同时写入。ctx 结束时停止发送,未结束的流由平台按超时结束; 用户停止生成时 Stream.Context() 被取消。

func (*AIService) StreamStopped added in v1.0.2

func (s *AIService) StreamStopped(streamID string) bool

StreamStopped 在收到 ai.stream_stopped 时调用:本进程中有这个流时取消它的 Context,模型调用随之中止。 返回是否找到了流(流在其他进程中时为 false,那边的写入会在下一次发送时收到 stream_closed)。 callback.Handler 收到这个事件时会自动调用,自己处理回调(如从队列取出事件)时才需要调用它。

func (*AIService) UpdateBot added in v1.0.2

func (s *AIService) UpdateBot(ctx context.Context, username string, version int64, params UpdateBotParams) (*AIUpdateBotResult, error)

UpdateBot 修改机器人的配置

带 version(版本号不一致返回 version_conflict);昵称和头像用 IM 用户的接口修改。endpoint_id 为 null 表示改用订阅了 ai.message_received 的地址。

接口:PATCH /ai/bots/{username}(ai.update_bot)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*AIService) WriteDeltas added in v1.0.2

func (s *AIService) WriteDeltas(ctx context.Context, streamID string, deltas []AIDelta) (*AIWriteDeltasResult, error)

WriteDeltas 按批写入增量(底层接口,通常用 Stream 的写入方法)

一次最多 100 段、64 KB。已接受过的段跳过;序号不连续返回 seq_gap(details.expected_seq);流已结束返回 stream_closed; 累积内容超过 1 MB 时流以 failed(too_large)结束并返回 payload_too_large(content)。

接口:POST /ai/streams/{stream_id}/deltas:batch(ai.write_deltas)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

type AIStream added in v1.0.2

type AIStream struct {
	StreamID       string `json:"stream_id"`
	Bot            string `json:"bot"`
	To             string `json:"to"`
	ConversationID string `json:"conversation_id"`
	MessageID      string `json:"message_id"`
	// AI 消息在会话中的序号
	Seq            int64   `json:"seq"`
	ClientStreamID *string `json:"client_stream_id"`
	ReplyToSeq     *int64  `json:"reply_to_seq"`
	Status         string  `json:"status"`
	// 已接受的最后一段增量的序号
	LastSeq      int64      `json:"last_seq"`
	FinishReason *string    `json:"finish_reason"`
	Error        *AIError   `json:"error"`
	Model        *string    `json:"model"`
	Usage        *AIUsage   `json:"usage"`
	ContentBytes int64      `json:"content_bytes"`
	FirstDeltaMs *int64     `json:"first_delta_ms"`
	StartedAt    time.Time  `json:"started_at"`
	FinishedAt   *time.Time `json:"finished_at"`
	// 累积的片段;生成中和结束 10 分钟内才有
	Content []AIPart `json:"content"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

AIStream 一条流式回复

func (*AIStream) UnmarshalJSON added in v1.0.2

func (v *AIStream) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type AIUpdateBotResult added in v1.0.2

type AIUpdateBotResult struct {
	Bot Bot `json:"bot"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

AIUpdateBotResult AIUpdateBotResult

func (*AIUpdateBotResult) UnmarshalJSON added in v1.0.2

func (v *AIUpdateBotResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type AIUsage added in v1.0.2

type AIUsage struct {
	InputTokens  int64 `json:"input_tokens"`
	OutputTokens int64 `json:"output_tokens"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

AIUsage AIUsage

func (*AIUsage) UnmarshalJSON added in v1.0.2

func (v *AIUsage) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type AIWriteDeltasResult added in v1.0.2

type AIWriteDeltasResult struct {
	AckedSeq int64 `json:"acked_seq"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

AIWriteDeltasResult AIWriteDeltasResult

func (*AIWriteDeltasResult) UnmarshalJSON added in v1.0.2

func (v *AIWriteDeltasResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ActiveCalls

type ActiveCalls struct {
	// 正在进行的通话(含成员),没有为 null
	Current *Call `json:"current"`
	// 正在呼叫他、未超时的通话(含成员),最多 20 个
	Incoming []Call `json:"incoming"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ActiveCalls 用户正在进行的通话和正在振铃的来电

func (*ActiveCalls) UnmarshalJSON

func (v *ActiveCalls) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type AddFriendItem

type AddFriendItem struct {
	// 对方的用户名(必填)
	Username string
	// 备注,只设置所有者一侧;去掉首尾空白后最长 64 个字符,不能含控制字符
	Remark string
	// 自定义属性,只设置所有者一侧;最多 16 个键(1 到 32 个 [A-Za-z0-9_.-])、合计 1 KB;已是好友时按项合并,null 清空全部,某一项为 null 删除这一项;三种状态:零值不发送,Null 发送 null,Set 发送值
	Attributes Field[map[string]Field[string]]
	// 添加来源,双方相同;最长 32 个 [A-Za-z0-9_.:-];已是好友时忽略
	AddSource string
	// 成为好友的时间,不能晚于当前时间;不给为当前时间,已是好友时忽略
	CreatedAt time.Time
}

AddFriendItem 批量添加好友的一项(字段的规则与单个添加相同)

type AddFriendParams

type AddFriendParams struct {
	// 备注,只设置 {username} 一侧;去掉首尾空白后最长 64 个字符,不能含控制字符;空字符串为没有备注
	Remark string
	// 自定义属性,只设置 {username} 一侧;最多 16 个键(1 到 32 个 [A-Za-z0-9_.-])、合计 1 KB;已是好友时按项合并,null 清空全部,某一项为 null 删除这一项;三种状态:零值不发送,Null 发送 null,Set 发送值
	Attributes Field[map[string]Field[string]]
	// 添加来源,双方相同;最长 32 个 [A-Za-z0-9_.:-];已是好友时忽略
	AddSource string
	// 成为好友的时间,不能晚于当前时间,用于迁移时保留原来的时间;不给为当前时间,已是好友时忽略
	CreatedAt time.Time
}

AddFriendParams 直接添加好友(双方同时成为好友)的参数(Friends.Add)。

type AddWordsResult

type AddWordsResult struct {
	// 新增的个数
	Added int64 `json:"added"`
	// 已存在的词条(原样)
	Duplicated []string    `json:"duplicated"`
	Invalid    []ItemError `json:"invalid"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

AddWordsResult 添加词条的结果

func (*AddWordsResult) Err

func (v *AddWordsResult) Err() error

Err 有失败的项时返回汇总的错误(*BatchError),全部成功时为 nil。

func (*AddWordsResult) FailedItems

func (v *AddWordsResult) FailedItems() []ItemError

FailedItems 失败的项(项的标识在 Key 中);全部成功时为 nil。

func (*AddWordsResult) OK

func (v *AddWordsResult) OK() bool

OK 全部成功。

func (*AddWordsResult) UnmarshalJSON

func (v *AddWordsResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type AppToken

type AppToken struct {
	AccessToken string `json:"access_token"`
	// 有效期(秒),由应用的 app_token_ttl_seconds 决定,默认 604800
	ExpiresIn int64 `json:"expires_in"`
	// 应用 ID
	Application string `json:"application"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

AppToken AppToken

func (AppToken) String

func (v AppToken) String() string

String 遮掩敏感的字段。

func (*AppToken) UnmarshalJSON

func (v *AppToken) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type BatchAddFriendsResult

type BatchAddFriendsResult struct {
	// 添加成功的好友(含原本就是好友的)
	Added  []Friend    `json:"added"`
	Failed []ItemError `json:"failed"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

BatchAddFriendsResult BatchAddFriendsResult

func (*BatchAddFriendsResult) Err

func (v *BatchAddFriendsResult) Err() error

Err 有失败的项时返回汇总的错误(*BatchError),全部成功时为 nil。

func (*BatchAddFriendsResult) FailedItems

func (v *BatchAddFriendsResult) FailedItems() []ItemError

FailedItems 失败的项(项的标识在 Key 中);全部成功时为 nil。

func (*BatchAddFriendsResult) OK

func (v *BatchAddFriendsResult) OK() bool

OK 全部成功。

func (*BatchAddFriendsResult) UnmarshalJSON

func (v *BatchAddFriendsResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type BatchBlacklistResult

type BatchBlacklistResult struct {
	// 只在批量拉黑的结果中出现:拉黑成功的用户名(小写,含原本就在黑名单中的)
	Added []string `json:"added"`
	// 只在批量移出的结果中出现:移出成功的用户名(小写,含原本就不在黑名单中的)
	Removed []string    `json:"removed"`
	Failed  []ItemError `json:"failed"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

BatchBlacklistResult 批量拉黑的结果有 added,批量移出的结果有 removed

func (*BatchBlacklistResult) Err

func (v *BatchBlacklistResult) Err() error

Err 有失败的项时返回汇总的错误(*BatchError),全部成功时为 nil。

func (*BatchBlacklistResult) FailedItems

func (v *BatchBlacklistResult) FailedItems() []ItemError

FailedItems 失败的项(项的标识在 Key 中);全部成功时为 nil。

func (*BatchBlacklistResult) OK

func (v *BatchBlacklistResult) OK() bool

OK 全部成功。

func (*BatchBlacklistResult) UnmarshalJSON

func (v *BatchBlacklistResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type BatchCreateUsersResult

type BatchCreateUsersResult struct {
	Created []User      `json:"created"`
	Failed  []ItemError `json:"failed"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

BatchCreateUsersResult BatchCreateUsersResult

func (*BatchCreateUsersResult) Err

func (v *BatchCreateUsersResult) Err() error

Err 有失败的项时返回汇总的错误(*BatchError),全部成功时为 nil。

func (*BatchCreateUsersResult) FailedItems

func (v *BatchCreateUsersResult) FailedItems() []ItemError

FailedItems 失败的项(项的标识在 Key 中);全部成功时为 nil。

func (*BatchCreateUsersResult) OK

func (v *BatchCreateUsersResult) OK() bool

OK 全部成功。

func (*BatchCreateUsersResult) UnmarshalJSON

func (v *BatchCreateUsersResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type BatchDecideParams

type BatchDecideParams struct {
	// 必填
	ItemIDs []string
	// 必填
	Decision string
	// 只能是撤回消息、屏蔽文件、清除资料、删除属性
	Actions []ModerationActionInput
	// 是否计入作者的违规,默认 true
	CountViolation *bool
	// 说明,最长 256 个字符
	Note string
}

BatchDecideParams 批量作出同样的结论(每次最多 100 条)的参数(Moderation.BatchDecide)。

type BatchDecideResult

type BatchDecideResult struct {
	Results []BatchDecideResultItem `json:"results"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

BatchDecideResult 批量结论的结果

func (*BatchDecideResult) Err

func (v *BatchDecideResult) Err() error

Err 有失败的项时返回汇总的错误(*BatchError),全部成功时为 nil。

func (*BatchDecideResult) FailedItems

func (v *BatchDecideResult) FailedItems() []ItemError

FailedItems 失败的项(项的标识在 Key 中);全部成功时为 nil。

func (*BatchDecideResult) OK

func (v *BatchDecideResult) OK() bool

OK 全部成功。

func (*BatchDecideResult) UnmarshalJSON

func (v *BatchDecideResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type BatchDecideResultItem

type BatchDecideResultItem struct {
	ItemID string          `json:"item_id"`
	Item   *ModerationItem `json:"item"`
	// Error 失败时的错误(Key 为这一项的标识),成功时为 nil。
	Error *ItemError `json:"-"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

BatchDecideResultItem 一条记录的结果:成功的有 item,失败的有 error

func (*BatchDecideResultItem) UnmarshalJSON

func (v *BatchDecideResultItem) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type BatchDeleteFriendsResult

type BatchDeleteFriendsResult struct {
	// 删除成功的用户名(小写,含原本就不是好友的)
	Deleted []string    `json:"deleted"`
	Failed  []ItemError `json:"failed"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

BatchDeleteFriendsResult BatchDeleteFriendsResult

func (*BatchDeleteFriendsResult) Err

Err 有失败的项时返回汇总的错误(*BatchError),全部成功时为 nil。

func (*BatchDeleteFriendsResult) FailedItems

func (v *BatchDeleteFriendsResult) FailedItems() []ItemError

FailedItems 失败的项(项的标识在 Key 中);全部成功时为 nil。

func (*BatchDeleteFriendsResult) OK

OK 全部成功。

func (*BatchDeleteFriendsResult) UnmarshalJSON

func (v *BatchDeleteFriendsResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type BatchError

type BatchError struct {
	Failed []ItemError
}

BatchError 由批量结果的 Err() 返回:有项失败(请求本身成功了,不是 *Error)。

func (*BatchError) Error

func (e *BatchError) Error() string

type BatchRecallResult

type BatchRecallResult struct {
	// 按请求的顺序,每个消息 ID 一项(含重复的)
	Results []BatchRecallResultItem `json:"results"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

BatchRecallResult 批量撤回的结果

func (*BatchRecallResult) Err

func (v *BatchRecallResult) Err() error

Err 有失败的项时返回汇总的错误(*BatchError),全部成功时为 nil。

func (*BatchRecallResult) FailedItems

func (v *BatchRecallResult) FailedItems() []ItemError

FailedItems 失败的项(项的标识在 Key 中);全部成功时为 nil。

func (*BatchRecallResult) OK

func (v *BatchRecallResult) OK() bool

OK 全部成功。

func (*BatchRecallResult) UnmarshalJSON

func (v *BatchRecallResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type BatchRecallResultItem

type BatchRecallResultItem struct {
	MessageID string `json:"message_id"`
	// 为 false 表示已经撤回过
	Changed bool `json:"changed"`
	// Error 失败时的错误(Key 为这一项的标识),成功时为 nil。
	Error *ItemError `json:"-"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

BatchRecallResultItem 批量撤回中一条消息的结果

func (*BatchRecallResultItem) UnmarshalJSON

func (v *BatchRecallResultItem) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type BatchSendParams

type BatchSendParams struct {
	// 发送者的用户名(必填)
	From string
	// 接收人的用户名,1 到应用的 max_recipients_per_message 个(默认 600、最多 1000,含重复的)(必填)
	ToUsers []string
	// 去重 ID,1 到 64 个可见 ASCII 字符,不能以 evt_、sys_ 开头;自动拆分时各批用同一个(必填)
	ClientMsgID string
	// 必填
	Type string
	// 消息内容,规则同 send(必填)
	Body json.RawMessage
	// 自定义扩展;null 与不传相同
	Ext json.RawMessage
	// 不计入接收者的未读数,也不发离线推送
	ExcludeFromUnread bool
	Push              *MessagePushOptions
	// 是否同步到发送者的其他设备
	SyncToSender bool
}

BatchSendParams 批量发送单聊消息(每次最多应用的 max_recipients_per_message 个接收人)的参数(Messages.BatchSend)。

type BatchSendResult

type BatchSendResult struct {
	// 按 to_users 的顺序,每个用户名一项(含重复的)
	Results []BatchSendResultItem `json:"results"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

BatchSendResult 批量发送的结果

func (*BatchSendResult) Err

func (v *BatchSendResult) Err() error

Err 有失败的项时返回汇总的错误(*BatchError),全部成功时为 nil。

func (*BatchSendResult) FailedItems

func (v *BatchSendResult) FailedItems() []ItemError

FailedItems 失败的项(项的标识在 Key 中);全部成功时为 nil。

func (*BatchSendResult) OK

func (v *BatchSendResult) OK() bool

OK 全部成功。

func (*BatchSendResult) UnmarshalJSON

func (v *BatchSendResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type BatchSendResultItem

type BatchSendResultItem struct {
	// 接收人,与请求中的写法相同
	Username string `json:"username"`
	// duplicate 为这个接收人的会话中已有这个 client_msg_id 的消息
	Status         string `json:"status"`
	ConversationID string `json:"conversation_id"`
	Seq            int64  `json:"seq"`
	MessageID      string `json:"message_id"`
	// Error 失败时的错误(Key 为这一项的标识),成功时为 nil。
	Error *ItemError `json:"-"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

BatchSendResultItem 批量发送中一个接收人的结果

func (*BatchSendResultItem) UnmarshalJSON

func (v *BatchSendResultItem) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type BlacklistChange

type BlacklistChange struct {
	Entry *BlacklistEntry `json:"entry"`
	// 这次请求是否改变了所有者的黑名单
	Changed bool `json:"changed"`
	// 所有者黑名单的版本号;改变时为新版本号,没有改变时为当前的版本号
	BlacklistVersion int64 `json:"blacklist_version"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

BlacklistChange 黑名单的写操作结果;拉黑时有 entry(已在黑名单中时为原来的记录),移出时没有

func (*BlacklistChange) UnmarshalJSON

func (v *BlacklistChange) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type BlacklistEntry

type BlacklistEntry struct {
	// 被拉黑的用户名(小写)
	Username string `json:"username"`
	// 被拉黑用户的昵称,没有时为空字符串
	Nickname string `json:"nickname"`
	// 被拉黑用户的头像地址,没有时为空字符串
	AvatarURL string `json:"avatar_url"`
	// 拉黑的时间
	CreatedAt time.Time `json:"created_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

BlacklistEntry 黑名单中的一项

func (*BlacklistEntry) UnmarshalJSON

func (v *BlacklistEntry) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type BlacklistService

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

BlacklistService 用户的黑名单(client.Blacklist)。

func (*BlacklistService) Add

func (s *BlacklistService) Add(ctx context.Context, username, target string) (*BlacklistChange, error)

Add 把用户加入黑名单

拉黑是单向的,不解除好友关系;同时撤回 {username} 发给对方、尚未处理的好友申请(不通知对方)。 已在黑名单中时返回 200、changed 为 false,entry 为原来的记录。黑名单最多 1000 人,已满返回 limit_exceeded(details.reason 为 blacklist_limit)。 应用关闭黑名单拦截时照常写入(客户端拉黑会被拒绝),便于开启前导入。{target} 与 {username} 相同返回 invalid_argument。只读状态下照常执行。

接口:PUT /users/{username}/blacklist/{target}(blacklist.add)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*BlacklistService) All

All 逐项遍历 List 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。 不带 KnownVersion(遍历要的是全部数据)。

func (*BlacklistService) BatchAdd

func (s *BlacklistService) BatchAdd(ctx context.Context, username string, usernames []string) (*BatchBlacklistResult, error)

BatchAdd 批量拉黑(每次最多 100 个)

逐个处理,整体返回 200;原本就在黑名单中的也算成功、出现在 added 中。黑名单已满的项为 limit_exceeded(details.reason 为 blacklist_limit), 对方用户不存在的项为 not_found。同一个用户名出现多次时不去重。结果不带 changed 和版本号。 按项数计入 OpenAPI 额度,额度不足时整个请求返回 rate_limited、任何一项都没有执行。只读状态下照常执行。

接口:POST /users/{username}/blacklist/batch(blacklist.batch_add)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*BlacklistService) BatchRemove

func (s *BlacklistService) BatchRemove(ctx context.Context, username string, usernames []string) (*BatchBlacklistResult, error)

BatchRemove 批量移出黑名单(每次最多 100 个)

逐个处理,整体返回 200;原本就不在黑名单中的也算成功、出现在 removed 中,对方用户不存在的项为 not_found。 同一个用户名出现多次时不去重。按项数计入 OpenAPI 额度,额度不足时整个请求返回 rate_limited、任何一项都没有执行。

接口:POST /users/{username}/blacklist/batch-delete(blacklist.batch_remove)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*BlacklistService) List

List 分页列出用户的黑名单(带版本号)

按被拉黑用户的内部用户 ID 排序。known_version 只在不带 cursor 时生效:与当前版本号相同时只返回 version、not_modified、count、max_count。 跳过已删除、清理尚未完成的用户,一页的条数可能少于 limit 甚至为 0,是否还有下一页只看 next_cursor。max_count 固定为 1000。

接口:GET /users/{username}/blacklist(blacklist.list)。查询,网络错误、超时、5xx 时自动重试。

func (*BlacklistService) Remove

func (s *BlacklistService) Remove(ctx context.Context, username, target string) (*BlacklistChange, error)

Remove 把用户移出黑名单

不在黑名单中时也返回 200,changed 为 false;对方用户不存在或已删除返回 not_found。只读状态下照常执行。

接口:DELETE /users/{username}/blacklist/{target}(blacklist.remove)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

type Bot added in v1.0.2

type Bot struct {
	Username  string `json:"username"`
	Nickname  string `json:"nickname"`
	AvatarURL string `json:"avatar_url"`
	Status    string `json:"status"`
	// IM 用户的状态(active / disabled)
	UserStatus         string    `json:"user_status"`
	EndpointID         *string   `json:"endpoint_id"`
	ContextMessages    int64     `json:"context_messages"`
	IdleTimeoutSeconds int64     `json:"idle_timeout_seconds"`
	MaxActiveStreams   int64     `json:"max_active_streams"`
	Description        string    `json:"description"`
	Version            int64     `json:"version"`
	CreatedAt          time.Time `json:"created_at"`
	UpdatedAt          time.Time `json:"updated_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

Bot 机器人

func (*Bot) UnmarshalJSON added in v1.0.2

func (v *Bot) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type Call

type Call struct {
	CallID string `json:"call_id"`
	Type   string `json:"type"`
	// 群通话所属的群,一对一为 null
	GroupID *string `json:"group_id"`
	Media   string  `json:"media"`
	Status  string  `json:"status"`
	// 发起人的用户名,已删除的为 null
	Initiator *string `json:"initiator"`
	// 人数上限(含发起人),一对一为 2
	MaxParticipants int64 `json:"max_participants"`
	// 当前在通话中的人数
	JoinedCount int64 `json:"joined_count"`
	// 全部成员,按 media_uid 升序;列表中不出现
	Members []CallMember `json:"members"`
	// 发起时附带的字符串键值对,没有为 null
	Ext map[string]string `json:"ext"`
	// 发起时间
	CreatedAt time.Time `json:"created_at"`
	// 接通时间
	AnsweredAt *time.Time `json:"answered_at"`
	EndedAt    *time.Time `json:"ended_at"`
	EndReason  *string    `json:"end_reason"`
	// 结束通话的用户名;服务端、控制台、平台和系统结束的、用户已删除的为 null
	EndedBy *string `json:"ended_by"`
	// 接通到结束(未结束时到现在)的秒数,向下取整;未接通为 0
	DurationSeconds int64 `json:"duration_seconds"`
	// 通话的版本号,每次状态变化加 1
	Version  int64   `json:"version"`
	EndedVia *string `json:"ended_via"`
	// 成员数,含已离开、拒绝、未接听的
	MemberCount int64 `json:"member_count"`
	// 同时在通话中的最多人数
	PeakJoined int64 `json:"peak_joined"`
	// 计费的分钟数(各成员的通话时长分别向上取整到分钟后之和),结束时写入,之前为 0
	BillableMinutes int64 `json:"billable_minutes"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

Call 通话(服务端视角)

func (*Call) UnmarshalJSON

func (v *Call) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type CallChange

type CallChange struct {
	Call Call `json:"call"`
	// 为 false 表示这次没有改变任何状态
	Changed bool `json:"changed"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

CallChange 结束通话、移出成员的结果

func (*CallChange) UnmarshalJSON

func (v *CallChange) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type CallDayStats

type CallDayStats struct {
	// 统计日(统计时区)
	Date string `json:"date"`
	// 结束的通话数,含一对一和群通话
	Calls int64 `json:"calls"`
	// 其中的群通话数
	GroupCalls int64 `json:"group_calls"`
	// 其中接通过的通话数
	AnsweredCalls int64 `json:"answered_calls"`
	// 结束原因为 completed 的通话数
	EndedCompleted      int64 `json:"ended_completed"`
	EndedCanceled       int64 `json:"ended_canceled"`
	EndedRejected       int64 `json:"ended_rejected"`
	EndedBusy           int64 `json:"ended_busy"`
	EndedNoAnswer       int64 `json:"ended_no_answer"`
	EndedConnectionLost int64 `json:"ended_connection_lost"`
	// 其余结束原因的通话数
	EndedOther int64 `json:"ended_other"`
	// 接通的通话从接通到结束的时长合计
	DurationMs int64 `json:"duration_ms"`
	// 语音通话的成员通话时长合计
	AudioParticipantMs int64 `json:"audio_participant_ms"`
	// 视频通话的成员通话时长合计
	VideoParticipantMs int64 `json:"video_participant_ms"`
	// 语音通话的计费分钟数合计
	BillableAudioMinutes int64 `json:"billable_audio_minutes"`
	// 视频通话的计费分钟数合计
	BillableVideoMinutes int64 `json:"billable_video_minutes"`
	// 接通的通话从发起到接通的时间合计,除以 answered_calls 为平均等待时间
	AnswerWaitMs int64 `json:"answer_wait_ms"`
	// 接通的通话中加入过的成员人次
	JoinedMembers int64 `json:"joined_members"`
	// 其中媒体服务从未观察到连入房间的人次
	MediaMissingMembers int64 `json:"media_missing_members"`
	// 当天每分钟采样的进行中的通话数的最大值
	PeakConcurrentCalls int64 `json:"peak_concurrent_calls"`
	// 峰值出现的时间
	PeakAt *time.Time `json:"peak_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

CallDayStats 一个统计日的通话统计

func (*CallDayStats) UnmarshalJSON

func (v *CallDayStats) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type CallMember

type CallMember struct {
	// 已删除的用户为 null
	Username *string `json:"username"`
	Role     string  `json:"role"`
	State    string  `json:"state"`
	// 成员在媒体服务中的数字身份,从 1 起
	MediaUID int64 `json:"media_uid"`
	// 最近一次的邀请人,发起人和自己加入的为 null
	InvitedBy *string `json:"invited_by"`
	// 最近一次邀请的振铃截止时间
	RingExpiresAt *time.Time `json:"ring_expires_at"`
	// 最近一次加入的时间
	JoinedAt *time.Time `json:"joined_at"`
	// 最近一次离开的时间
	LeftAt *time.Time `json:"left_at"`
	// 最近一次离开的原因
	LeaveReason *string `json:"leave_reason"`
	// 最近一次被邀请的时间
	InvitedAt *time.Time `json:"invited_at"`
	// 最近一次加入时的平台,取值与登录设备的 platform 相同
	JoinedPlatform *string `json:"joined_platform"`
	// 加入的次数
	JoinCount int64 `json:"join_count"`
	// 接通之后累计在通话中的毫秒数
	JoinedMs int64 `json:"joined_ms"`
	// 第一次加入的时间
	FirstJoinedAt *time.Time `json:"first_joined_at"`
	// 媒体服务第一次观察到他连入房间的时间
	MediaJoinedAt *time.Time `json:"media_joined_at"`
	// 媒体服务最近一次观察到他离开房间的时间
	MediaLeftAt *time.Time `json:"media_left_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

CallMember 通话的成员(服务端视角)

func (*CallMember) UnmarshalJSON

func (v *CallMember) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type CallsService

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

CallsService 音视频通话的查询与结束、统计(client.Calls)。

func (*CallsService) ActiveOf

func (s *CallsService) ActiveOf(ctx context.Context, username string) (*ActiveCalls, error)

ActiveOf 查询用户正在进行的通话和正在振铃的来电

用户不存在返回 not_found。来电最多 20 个,每项是通话本身(含成员),没有客户端接口中的 inviter、group。

接口:GET /users/{username}/calls/active(calls.active_of)。查询,网络错误、超时、5xx 时自动重试。

func (*CallsService) All

All 逐项遍历 List 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。

func (*CallsService) End

func (s *CallsService) End(ctx context.Context, callID, reason string) (*CallChange, error)

End 结束通话

end_reason 为 server_ended,ended_via 为 openapi,写入操作日志。已结束的返回 200、changed 为 false(重试的结果相同)。 只读状态下、应用关闭音视频后照常可用。

接口:POST /calls/{call_id}/end(calls.end)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*CallsService) Get

func (s *CallsService) Get(ctx context.Context, callID string) (*Call, error)

Get 查询通话详情(含成员)

通话不存在返回 not_found。

接口:GET /calls/{call_id}(calls.get)。查询,网络错误、超时、5xx 时自动重试。

func (*CallsService) List

func (s *CallsService) List(ctx context.Context, params ListCallsParams) (*Page[Call], error)

List 分页列出应用的通话

按通话 ID 倒序,列表中的通话不含 members。按 username 筛选时用户不存在得到空页。 服务端一页最多扫描 1000 条,条件很少命中时可能不足 limit 条甚至为空页而仍有下一页,是否结束只看 next_cursor(没有下一页时为空字符串)。

接口:GET /calls(calls.list)。查询,网络错误、超时、5xx 时自动重试。

func (*CallsService) RemoveMember

func (s *CallsService) RemoveMember(ctx context.Context, callID, username, reason string) (*CallChange, error)

RemoveMember 把成员移出通话

在通话中的离开(leave_reason 为 removed)并从媒体服务的房间中移出,正在振铃的改为 canceled,然后执行结束判定;一对一通话等同结束通话(server_ended)。 用户不存在或不是这个通话的成员返回 not_found;已不在通话中也不在振铃的、通话已结束的返回 200、changed 为 false。写入操作日志。

接口:POST /calls/{call_id}/members/{username}/remove(calls.remove_member)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*CallsService) Stats

func (s *CallsService) Stats(ctx context.Context, from, to string) ([]CallDayStats, error)

Stats 按日查询应用的通话统计

from、to 为统计时区的日期,含两端,最多 92 天;缺少、格式不对或超出范围返回 invalid_argument(details.reason 为 invalid_date_range)。 按日期升序,没有通话的日期不出现;一个通话按结束时间计入某一天。

接口:GET /rtc/stats(calls.stats)。查询,网络错误、超时、5xx 时自动重试。

type ChannelsIssueTicketsUsers

type ChannelsIssueTicketsUsers struct {
	// 必填
	Username string
	Role     string
}

ChannelsIssueTicketsUsers ChannelsIssueTicketsUsers

type ChannelsService

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

ChannelsService 独立 RTC 频道管理与用量更正(client.Channels)。

func (*ChannelsService) Ban

func (s *ChannelsService) Ban(ctx context.Context, channelID, username string, params RTCChannelBanParams) (*RTCChannelBanCreateResult, error)

Ban Ban RTC channel

接口:PUT /rtc/channels/{channel_id}/bans/{username}(channels.ban)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ChannelsService) Bans

Bans Bans RTC channel

接口:GET /rtc/channels/{channel_id}/bans(channels.bans)。查询,网络错误、超时、5xx 时自动重试。

func (*ChannelsService) Close

Close Close RTC channel

接口:POST /rtc/channels/{channel_id}/close(channels.close)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ChannelsService) Create

Create Create RTC channel

接口:PUT /rtc/channels/{channel_id}(channels.create)。带幂等键的写操作,用同一个键自动重试。

func (*ChannelsService) Get

func (s *ChannelsService) Get(ctx context.Context, channelID string) (*RTCChannelResult, error)

Get Get RTC channel

接口:GET /rtc/channels/{channel_id}(channels.get)。查询,网络错误、超时、5xx 时自动重试。

func (*ChannelsService) GetBan

func (s *ChannelsService) GetBan(ctx context.Context, channelID, username string) (*RTCChannelBanResult, error)

GetBan GetBan RTC channel

接口:GET /rtc/channels/{channel_id}/bans/{username}(channels.get_ban)。查询,网络错误、超时、5xx 时自动重试。

func (*ChannelsService) IssueTickets

IssueTickets IssueTickets RTC channel

接口:POST /rtc/channels/{channel_id}/tickets(channels.issue_tickets)。不幂等:请求发出后不自动重试(被限流的照常等待后重发),超时后先查询结果再决定是否重试。

func (*ChannelsService) List

List List RTC channel

接口:GET /rtc/channels(channels.list)。查询,网络错误、超时、5xx 时自动重试。

func (*ChannelsService) RemoveMember

func (s *ChannelsService) RemoveMember(ctx context.Context, channelID, username string, params RTCChannelRemoveMemberParams) (*RTCChannelRemoveResult, error)

RemoveMember RemoveMember RTC channel

接口:POST /rtc/channels/{channel_id}/members/{username}/remove(channels.remove_member)。带幂等键的写操作,用同一个键自动重试。

func (*ChannelsService) RevokeTickets

RevokeTickets RevokeTickets RTC channel

接口:POST /rtc/channels/{channel_id}/tickets/revoke(channels.revoke_tickets)。带幂等键的写操作,用同一个键自动重试。

func (*ChannelsService) Sessions

Sessions Sessions RTC channel

接口:GET /rtc/channels/{channel_id}/sessions(channels.sessions)。查询,网络错误、超时、5xx 时自动重试。

func (*ChannelsService) Stats

Stats Stats RTC channel

接口:GET /rtc/channel-stats(channels.stats)。查询,网络错误、超时、5xx 时自动重试。

func (*ChannelsService) Unban

func (s *ChannelsService) Unban(ctx context.Context, channelID, username string, params RTCChannelUnbanParams) (*RTCChannelBanResult, error)

Unban Unban RTC channel

接口:DELETE /rtc/channels/{channel_id}/bans/{username}(channels.unban)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ChannelsService) Update

func (s *ChannelsService) Update(ctx context.Context, channelID string, params RTCChannelUpdateParams) (*RTCChannelResult, error)

Update Update RTC channel

接口:PATCH /rtc/channels/{channel_id}(channels.update)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ChannelsService) UsageAdjustments

UsageAdjustments 查询频道用量更正状态

接口:GET /rtc/channel-usage-adjustments(channels.usage_adjustments)。查询,网络错误、超时、5xx 时自动重试。

type Chatroom

type Chatroom struct {
	RoomID string `json:"room_id"`
	Name   string `json:"name"`
	// 简介,没有时为空字符串
	Description string `json:"description"`
	// 封面地址,没有时为空字符串
	AvatarURL string `json:"avatar_url"`
	// 公告,没有时为空字符串
	Announcement string `json:"announcement"`
	// 公告的修改时间,没有公告时为 null
	AnnouncementUpdatedAt *time.Time `json:"announcement_updated_at"`
	// 修改公告的用户名;服务端修改的和修改人已删除的为 null
	AnnouncementUpdatedBy *string `json:"announcement_updated_by"`
	// 所有者的用户名;没有所有者或已删除时为 null
	Owner *string `json:"owner"`
	// 管理员的用户名,按设置的先后排列,最多 99 个,已删除的不列出
	Admins []string `json:"admins"`
	// 实际生效的人数上限(聊天室自己的与应用策略中较小的)
	MaxMembers int `json:"max_members"`
	// 是否开启了全员禁言
	MuteAll bool `json:"mute_all"`
	// 是否出现在客户端的聊天室列表中
	Listed bool   `json:"listed"`
	Status string `json:"status"`
	// 封禁方,没有封禁时为 null
	DisabledBy *string `json:"disabled_by"`
	// 在线人数,近似值(缓存 5 秒);封禁、解散的为 0
	MemberCount int64 `json:"member_count"`
	// 资料的版本号,资料、全员禁言、所有者、管理员、封禁状态变化时加 1
	InfoVersion int64 `json:"info_version"`
	// 属性的版本号
	AttributesVersion int64     `json:"attributes_version"`
	CreatedAt         time.Time `json:"created_at"`
	// 封禁的原因,没有时为 null
	StatusReason *string `json:"status_reason"`
	// 聊天室自己设置的人数上限,没有设置时为 null
	MaxMembersSetting *int64 `json:"max_members_setting"`
	CreatedVia        string `json:"created_via"`
	// 客户端创建者的用户名;服务端、控制台创建的和创建者已删除的为 null
	CreatedBy *string `json:"created_by"`
	// 解散的时间,没有解散时为 null
	DismissedAt *time.Time `json:"dismissed_at"`
	// 属性的个数
	AttributeCount int64 `json:"attribute_count"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

Chatroom 聊天室(服务端看到的信息)

func (*Chatroom) UnmarshalJSON

func (v *Chatroom) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ChatroomChange

type ChatroomChange struct {
	RoomID string `json:"room_id"`
	Name   string `json:"name"`
	// 简介,没有时为空字符串
	Description string `json:"description"`
	// 封面地址,没有时为空字符串
	AvatarURL string `json:"avatar_url"`
	// 公告,没有时为空字符串
	Announcement string `json:"announcement"`
	// 公告的修改时间,没有公告时为 null
	AnnouncementUpdatedAt *time.Time `json:"announcement_updated_at"`
	// 修改公告的用户名;服务端修改的和修改人已删除的为 null
	AnnouncementUpdatedBy *string `json:"announcement_updated_by"`
	// 所有者的用户名;没有所有者或已删除时为 null
	Owner *string `json:"owner"`
	// 管理员的用户名,按设置的先后排列,最多 99 个,已删除的不列出
	Admins []string `json:"admins"`
	// 实际生效的人数上限(聊天室自己的与应用策略中较小的)
	MaxMembers int `json:"max_members"`
	// 是否开启了全员禁言
	MuteAll bool `json:"mute_all"`
	// 是否出现在客户端的聊天室列表中
	Listed bool   `json:"listed"`
	Status string `json:"status"`
	// 封禁方,没有封禁时为 null
	DisabledBy *string `json:"disabled_by"`
	// 在线人数,近似值(缓存 5 秒);封禁、解散的为 0
	MemberCount int64 `json:"member_count"`
	// 资料的版本号,资料、全员禁言、所有者、管理员、封禁状态变化时加 1
	InfoVersion int64 `json:"info_version"`
	// 属性的版本号
	AttributesVersion int64     `json:"attributes_version"`
	CreatedAt         time.Time `json:"created_at"`
	// 封禁的原因,没有时为 null
	StatusReason *string `json:"status_reason"`
	// 聊天室自己设置的人数上限,没有设置时为 null
	MaxMembersSetting *int64 `json:"max_members_setting"`
	CreatedVia        string `json:"created_via"`
	// 客户端创建者的用户名;服务端、控制台创建的和创建者已删除的为 null
	CreatedBy *string `json:"created_by"`
	// 解散的时间,没有解散时为 null
	DismissedAt *time.Time `json:"dismissed_at"`
	// 属性的个数
	AttributeCount int64 `json:"attribute_count"`
	// 这次是否有变化
	Changed bool `json:"changed"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ChatroomChange 写操作的结果:修改后的聊天室(字段同 Chatroom)和 changed

func (*ChatroomChange) UnmarshalJSON

func (v *ChatroomChange) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ChatroomsService

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

ChatroomsService 聊天室、成员、禁言、封禁、白名单、属性与消息(client.Chatrooms)。

func (*ChatroomsService) AddToAllowlist

func (s *ChatroomsService) AddToAllowlist(ctx context.Context, roomID string, usernames []string) (*RoomBatchResult, error)

AddToAllowlist 加入白名单(每次最多 100 个)

逐项为 added 或 unchanged(已在白名单中);白名单最多 500 人(limit_exceeded,allowlist_limit)。 整批在一个事务中执行,按去重后的人数计入额度;只读状态下返回 app_unavailable。

接口:POST /chatrooms/{room_id}/allowlist(chatrooms.add_to_allowlist)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ChatroomsService) All

All 逐项遍历 List 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。

func (*ChatroomsService) AllAllowlist

func (s *ChatroomsService) AllAllowlist(ctx context.Context, roomID string, params ListOptions) iter.Seq2[RoomAllowlistEntry, error]

AllAllowlist 逐项遍历 Allowlist 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。

func (*ChatroomsService) AllBans

func (s *ChatroomsService) AllBans(ctx context.Context, roomID string, params ListOptions) iter.Seq2[RoomBan, error]

AllBans 逐项遍历 Bans 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。

func (*ChatroomsService) AllMembers

func (s *ChatroomsService) AllMembers(ctx context.Context, roomID string, params ListOptions) iter.Seq2[RoomMember, error]

AllMembers 逐项遍历 Members 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。 完全离开后又进入的用户可能在后面的页再次出现,这里按用户名去重。

func (*ChatroomsService) AllMutes

func (s *ChatroomsService) AllMutes(ctx context.Context, roomID string, params ListOptions) iter.Seq2[RoomMute, error]

AllMutes 逐项遍历 Mutes 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。

func (*ChatroomsService) Allowlist

func (s *ChatroomsService) Allowlist(ctx context.Context, roomID string, params ListOptions) (*Page[RoomAllowlistEntry], error)

Allowlist 分页列出白名单

白名单中的用户在全员禁言时仍能发送消息。按用户 ID 排列;跳过已删除的用户,一页可能少于 limit。

接口:GET /chatrooms/{room_id}/allowlist(chatrooms.allowlist)。查询,网络错误、超时、5xx 时自动重试。

func (*ChatroomsService) Attributes

func (s *ChatroomsService) Attributes(ctx context.Context, roomID string, keys ...string) (*RoomAttributes, error)

Attributes 查询聊天室属性

不给 keys 时返回全部(最多 100 个键);不存在的键不出现在结果中。不要求在聊天室里。

接口:GET /chatrooms/{room_id}/attributes(chatrooms.attributes)。查询,网络错误、超时、5xx 时自动重试。

func (*ChatroomsService) Ban

func (s *ChatroomsService) Ban(ctx context.Context, roomID string, usernames []string, params RoomPenaltyParams) (*RoomBatchResult, error)

Ban 在聊天室中封禁用户(每次最多 100 个)

封禁期间不能进入,在聊天室里的随即被移出。逐项为 banned 或 unchanged(已在封禁中,不修改原记录;要改时长先解封)。 不能封禁所有者(owner_protected);封禁管理员同时取消他的管理员身份(info_version 加 1);未到期的封禁最多 1 万个(limit_exceeded,ban_limit)。 整批在一个事务中执行,按去重后的人数计入额度。

接口:POST /chatrooms/{room_id}/bans(chatrooms.ban)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ChatroomsService) Bans

func (s *ChatroomsService) Bans(ctx context.Context, roomID string, params ListOptions) (*Page[RoomBan], error)

Bans 分页列出被封禁的用户

只列出未到期的,按用户 ID 排列;跳过已删除的用户,一页可能少于 limit。

接口:GET /chatrooms/{room_id}/bans(chatrooms.bans)。查询,网络错误、超时、5xx 时自动重试。

func (*ChatroomsService) Create

Create 创建聊天室

不幂等,不自动重试:超时后按 name_prefix、owner 查询,多出的解散。owner 不存在返回 not_found; 名称、简介、公告经过内容安全检查(拒绝时返回 content_rejected,也可能被替换,返回的与传入的不同)。 应用的聊天室数已达上限返回 limit_exceeded(chatroom_limit);只读状态下返回 app_unavailable。

接口:POST /chatrooms(chatrooms.create)。不幂等:请求发出后不自动重试(被限流的照常等待后重发),超时后先查询结果再决定是否重试。

func (*ChatroomsService) Delete

func (s *ChatroomsService) Delete(ctx context.Context, roomID string) error

Delete 解散聊天室

断开全部连接、删除最近的消息;已解散的也返回 204。平台封禁的返回 permission_denied。 解散后 30 天内仍可用 get 查询(status 为 dismissed)。只读状态下也可以解散。

接口:DELETE /chatrooms/{room_id}(chatrooms.delete)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ChatroomsService) Disable

func (s *ChatroomsService) Disable(ctx context.Context, roomID, reason string) (*ChatroomChange, error)

Disable 封禁聊天室

断开全部连接、删除最近的消息;封禁期间不能进入和发送消息,服务端的管理操作照常可用。 已被租户封禁的再次封禁只更新原因(原因不同时 changed 为 true,info_version 不变);已被平台封禁的不做任何改变(changed 为 false)。

接口:POST /chatrooms/{room_id}/disable(chatrooms.disable)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ChatroomsService) Enable

func (s *ChatroomsService) Enable(ctx context.Context, roomID string) (*ChatroomChange, error)

Enable 解封聊天室

没有封禁时 changed 为 false;平台封禁的返回 permission_denied。

接口:POST /chatrooms/{room_id}/enable(chatrooms.enable)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ChatroomsService) Get

func (s *ChatroomsService) Get(ctx context.Context, roomID string) (*Chatroom, error)

Get 查询聊天室

解散 30 天内仍可查询(status 为 dismissed,带 dismissed_at),其他接口对它返回 not_found(details.reason 为 chatroom_dismissed)。

接口:GET /chatrooms/{room_id}(chatrooms.get)。查询,网络错误、超时、5xx 时自动重试。

func (*ChatroomsService) Kick

func (s *ChatroomsService) Kick(ctx context.Context, roomID string, usernames []string) (*RoomBatchResult, error)

Kick 移出用户(每次最多 100 个)

逐项为 removed 或 not_in_room(不在聊天室里);不能移出所有者(permission_denied,owner_protected),可以移出管理员;不存在的用户为 not_found。 被移出的用户可以立即重新进入,需要禁止时用 ban。按去重后的人数计入额度;网关暂时不可用时整个请求返回 internal(dependency_unavailable)。

接口:POST /chatrooms/{room_id}/members/batch-delete(chatrooms.kick)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ChatroomsService) List

List 分页列出聊天室

按 room_id 倒序(即创建时间倒序);给出 name_prefix 时按名称、room_id 升序。owner 不存在时得到空页。

接口:GET /chatrooms(chatrooms.list)。查询,网络错误、超时、5xx 时自动重试。

func (*ChatroomsService) Member

func (s *ChatroomsService) Member(ctx context.Context, roomID, username string) (*RoomMemberState, error)

Member 查询用户是否在聊天室里

用户不存在返回 not_found;不在聊天室里的也给出身份。

接口:GET /chatrooms/{room_id}/members/{username}(chatrooms.member)。查询,网络错误、超时、5xx 时自动重试。

func (*ChatroomsService) Members

func (s *ChatroomsService) Members(ctx context.Context, roomID string, params ListOptions) (*Page[RoomMember], error)

Members 分页列出在聊天室里的用户

按进入时间升序。离开后又进入的用户可能在后面的页再次出现,遍历方法(Go 的 AllMembers、Python 的 iter_members)按用户名去重; 跳过已删除的用户,一页可能少于 limit。网关暂时不可用时返回 internal(dependency_unavailable)。

接口:GET /chatrooms/{room_id}/members(chatrooms.members)。查询,网络错误、超时、5xx 时自动重试。

func (*ChatroomsService) Mute

func (s *ChatroomsService) Mute(ctx context.Context, roomID string, usernames []string, params RoomPenaltyParams) (*RoomBatchResult, error)

Mute 在聊天室中禁言用户(每次最多 100 个)

逐项为 muted 或 unchanged(已在禁言中,且新的到期时间与原来的相差 1 分钟以内,或都是永久);其他情况以这次的时长和原因覆盖(可能缩短)。 不要求对方在聊天室里;不能禁言所有者(owner_protected);未到期的禁言最多 1 万个(limit_exceeded,mute_limit)。 整批在一个事务中执行,按去重后的人数计入额度。

接口:POST /chatrooms/{room_id}/mutes(chatrooms.mute)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ChatroomsService) Mutes

func (s *ChatroomsService) Mutes(ctx context.Context, roomID string, params ListOptions) (*Page[RoomMute], error)

Mutes 分页列出被禁言的用户

只列出未到期的,按用户 ID 排列;跳过已删除的用户,一页可能少于 limit。

接口:GET /chatrooms/{room_id}/mutes(chatrooms.mutes)。查询,网络错误、超时、5xx 时自动重试。

func (*ChatroomsService) OnlineCounts

func (s *ChatroomsService) OnlineCounts(ctx context.Context, roomIDs []string) ([]RoomOnlineCount, error)

OnlineCounts 批量查询在线人数(每次最多 100 个,含重复的)

不存在、已解散的不出现在结果中,格式不对的 ID 忽略,封禁的为 0;结果按请求的顺序(去重)。 在线人数是近似值,按聊天室缓存 5 秒。给出的 ID 为空或全部无效时返回空列表。

接口:POST /chatrooms/online-counts(chatrooms.online_counts)。查询,网络错误、超时、5xx 时自动重试。

func (*ChatroomsService) Recall

func (s *ChatroomsService) Recall(ctx context.Context, roomID, messageID, reason string) (*RoomRecallResult, error)

Recall 撤回聊天室消息

服务端不受身份和时限限制,也可以撤回系统消息;封禁中的聊天室也可以撤回。 每次都推送撤回通知并返回 changed 为 true,包括消息已不在最近的消息中(超过 24 小时、被挤出或已撤回)时, 所以重复撤回会再推送一次(客户端忽略不认识的消息 ID);只有同时撤回同一条时,后完成的 changed 为 false。

接口:POST /chatrooms/{room_id}/messages/{message_id}/recall(chatrooms.recall)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ChatroomsService) RecentMessages

func (s *ChatroomsService) RecentMessages(ctx context.Context, roomID string, limit int) ([]RoomMessage, error)

RecentMessages 查询最近的消息(不分页)

最近 24 小时内的普通和高优先级消息(低优先级的不保存,已撤回的不在其中),从旧到新;不要求在聊天室里。 条数最多为应用的 chatroom_history_size(默认 50,最多 200);一次合计不超过 1 MB,超出时丢掉最早的。聊天室封禁时清空。

接口:GET /chatrooms/{room_id}/messages(chatrooms.recent_messages)。查询,网络错误、超时、5xx 时自动重试。

func (*ChatroomsService) RemoveAdmin

func (s *ChatroomsService) RemoveAdmin(ctx context.Context, roomID, username string) (*RoomAdminChange, error)

RemoveAdmin 取消管理员

对方不是管理员时 changed 为 false;用户不存在返回 not_found。

接口:DELETE /chatrooms/{room_id}/admins/{username}(chatrooms.remove_admin)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ChatroomsService) RemoveAttributes

func (s *ChatroomsService) RemoveAttributes(ctx context.Context, roomID string, keys []string) (*RoomAttributesChange, error)

RemoveAttributes 删除聊天室属性(每次 1 到 20 个键)

不存在的键忽略;服务端可以删除任何人设置的键,failed 总是为空。 每个聊天室每秒最多 20 次属性写入(rate_limited,room_attribute_rate)。

接口:POST /chatrooms/{room_id}/attributes/batch-delete(chatrooms.remove_attributes)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ChatroomsService) RemoveFromAllowlist

func (s *ChatroomsService) RemoveFromAllowlist(ctx context.Context, roomID string, usernames []string) (*RoomBatchResult, error)

RemoveFromAllowlist 移出白名单(每次最多 100 个)

逐项为 removed 或 unchanged(不在白名单中)。整批在一个事务中执行,按去重后的人数计入额度。

接口:POST /chatrooms/{room_id}/allowlist/batch-delete(chatrooms.remove_from_allowlist)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ChatroomsService) Send

Send 发送聊天室消息

from 为空时以系统身份发送。服务端发送不检查禁言、全员禁言和全局禁言,不要求发送者在聊天室里,任何身份都可以发高优先级; 封禁中的聊天室返回 chatroom_disabled;from 被平台封禁时返回 user_disabled(租户封禁的可以发送);不检查附件地址。 type、body、ext 合计(紧凑 JSON)不超过应用的 max_chatroom_message_bytes(默认 2 KB),否则 payload_too_large; 发送前检查(内容安全、回调)拒绝时返回 message_rejected,也可能替换内容。 普通和高优先级按“聊天室、发送者、client_msg_id”去重 5 分钟,没有 client_msg_id 时由 SDK 生成。返回 200 且 dropped 为 false 的是重复提交: 服务端只保证 message_id、created_at 是第一次的(类型和内容取自这次请求,发送者字段为空,sender_type 为空字符串),SDK 把其余字段置为零值。 低优先级不去重、不自动重试,超出聊天室的频率时被丢弃:返回 200,dropped 为 true,message_id、created_at 为 null,没有其他消息字段; 普通和高优先级超出频率返回 rate_limited(room_send_rate)。只读状态下返回 app_unavailable(重复提交仍返回第一次的结果)。

接口:POST /chatrooms/{room_id}/messages(chatrooms.send)。带幂等键的写操作,用同一个键自动重试。低优先级(Priority 为 low)的消息不去重,不自动重试。

func (*ChatroomsService) SetAdmin

func (s *ChatroomsService) SetAdmin(ctx context.Context, roomID, username string) (*RoomAdminChange, error)

SetAdmin 设置管理员

不要求对方在聊天室里;用户不存在返回 not_found。最多 99 个管理员(limit_exceeded,admin_limit); 对方正在被封禁时返回 permission_denied(target_banned);对方是所有者或已是管理员时 changed 为 false。

接口:PUT /chatrooms/{room_id}/admins/{username}(chatrooms.set_admin)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ChatroomsService) SetAttributes

func (s *ChatroomsService) SetAttributes(ctx context.Context, roomID string, attributes map[string]string) (*RoomAttributesChange, error)

SetAttributes 设置聊天室属性(每次 1 到 20 个键)

总是覆盖,不论原来由谁设置;写入后键的所有者为服务端(owner 为 null),auto_delete 为 false。与原值相同的不算变化。 超出聊天室上限(100 个键、合计 16 KB)的键在 failed 中(limit_exceeded,attribute_limit),其余照常写入。 每个聊天室每秒最多 20 次属性写入(rate_limited,room_attribute_rate);只读状态下返回 app_unavailable。

接口:PUT /chatrooms/{room_id}/attributes(chatrooms.set_attributes)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ChatroomsService) SetMuteAll

func (s *ChatroomsService) SetMuteAll(ctx context.Context, roomID string, on bool) (*ChatroomChange, error)

SetMuteAll 开启全员禁言(on 为真)或关闭全员禁言(on 为假)。

接口:PUT、DELETE /chatrooms/{room_id}/mute-all。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ChatroomsService) TransferOwner

func (s *ChatroomsService) TransferOwner(ctx context.Context, roomID string, username Field[string]) (*ChatroomChange, error)

TransferOwner 转让或清空所有者

新所有者须是存在的用户(否则 not_found),不要求在聊天室里;他原来的管理员身份、在这个聊天室中的禁言和封禁记录被清除,原所有者成为普通用户。 转给现在的所有者时 changed 为 false。

接口:PUT /chatrooms/{room_id}/owner(chatrooms.transfer_owner)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ChatroomsService) Unban

func (s *ChatroomsService) Unban(ctx context.Context, roomID string, usernames []string) (*RoomBatchResult, error)

Unban 解除聊天室中的封禁(每次最多 100 个)

逐项为 unbanned 或 unchanged(没有封禁);服务端可以解除任何人设置的封禁。整批在一个事务中执行,按去重后的人数计入额度。

接口:POST /chatrooms/{room_id}/bans/batch-delete(chatrooms.unban)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ChatroomsService) Unmute

func (s *ChatroomsService) Unmute(ctx context.Context, roomID string, usernames []string) (*RoomBatchResult, error)

Unmute 解除聊天室中的禁言(每次最多 100 个)

逐项为 unmuted 或 unchanged(没有禁言);服务端可以解除任何人设置的禁言。整批在一个事务中执行,按去重后的人数计入额度。

接口:POST /chatrooms/{room_id}/mutes/batch-delete(chatrooms.unmute)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ChatroomsService) Update

func (s *ChatroomsService) Update(ctx context.Context, roomID string, params UpdateChatroomParams) (*ChatroomChange, error)

Update 修改聊天室资料

只修改给出的字段;文本字段和 listed 为 null 与不传相同(不改),清空文本传空字符串。没有要改的字段或与原值相同时 changed 为 false(不报错)。 给出 version 时只有与当前的 info_version 一致才修改,否则 version_conflict(details.info_version 为当前值)。 名称、简介、公告经过内容安全检查。封禁中的聊天室也可以修改;只读状态下返回 app_unavailable。

接口:PATCH /chatrooms/{room_id}(chatrooms.update)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

type CheckTextParams

type CheckTextParams struct {
	// 必填
	Scene string
	// 要检查的文本,结果的键为 text
	Text string
	// 字段名到文本
	Fields map[string]string
	// 是否同步调用第三方审核,默认 false
	WithProvider bool
}

CheckTextParams 按当前规则检查文本(不记录)的参数(Moderation.CheckText)。

type Client

type Client struct {
	Users         *UsersService
	Friends       *FriendsService
	Blacklist     *BlacklistService
	Groups        *GroupsService
	Messages      *MessagesService
	Conversations *ConversationsService
	Media         *MediaService
	Push          *PushService
	Chatrooms     *ChatroomsService
	Moderation    *ModerationService
	Calls         *CallsService
	Channels      *ChannelsService
	Presence      *PresenceService
	AI            *AIService
	// contains filtered or unexported fields
}

Client 是一个应用的服务端 SDK 客户端(《2.接口设计》第 1、3 节)。

客户端可以被多个协程同时使用,内部共享 App Token、连接池和限流等待,应在进程中复用,不要每个请求新建; 同一进程管理多个应用时各建一个客户端。

func New

func New(cfg Config) (*Client, error)

New 检查配置并创建客户端,不发请求(第一次调用时换取 App Token)。

func (*Client) AppID

func (c *Client) AppID() string

AppID 换取令牌时得到的应用 ID,还没换取过时为空。

func (*Client) Close

func (c *Client) Close() error

Close 停止后台的换取,关闭 SDK 自己创建的 HTTP 客户端的空闲连接;之后的调用返回 client_unavailable。

func (*Client) Stats

func (c *Client) Stats() Stats

Stats 按接口名统计的请求数、失败数、重试数和限流等待的总时长(快照)。

func (*Client) Token

func (c *Client) Token(ctx context.Context) (string, error)

Token 返回当前有效的 App Token(排查用,需要时换取)。不要把它写入日志或交给客户端。

func (*Client) UpdateCredentials

func (c *Client) UpdateCredentials(clientID, clientSecret string)

UpdateCredentials 在控制台轮换 Secret 后更新凭据:丢弃当前令牌、结束换取失败后的冷却期,下一次请求用新凭据换取。 令牌存储的键随 Client ID 变化。

type Config

type Config struct {
	BaseURL      string // 服务端地址,如 https://im.example.com;可以带路径前缀,不能带查询参数和片段
	OrgName      string
	AppName      string
	ClientID     string
	ClientSecret string

	// HTTPClient 默认由 SDK 创建(每个主机最多 100 个空闲连接、空闲 90 秒关闭、TLS 握手 10 秒、使用环境变量的代理、
	// 不跟随重定向);Close 时关闭它的空闲连接。调用方传入的,SDK 不修改也不关闭。
	HTTPClient *http.Client
	// Timeout 每次尝试的时限(从发出到读完响应),默认 30 秒;完成上传为 150 秒,不受它影响。
	Timeout time.Duration
	// Retry 自动重试的设置(《1.功能概述文档》第 6 节)。
	Retry RetryPolicy
	// MaxRetryAfter 自动等待的 Retry-After 上限,默认 60 秒;超过的不等待,直接返回 rate_limited。
	MaxRetryAfter time.Duration
	// RateLimit 本地限速,默认关闭;用于批量导入、群发等后台任务,把额度留给线上请求。
	RateLimit *RateLimit
	// TokenStore 让多个服务实例共用一个 App Token;默认只在进程内存中。
	TokenStore TokenStore
	// Logger 默认不输出。
	Logger *slog.Logger
	// Hooks 请求前后的钩子(注入追踪头、记录指标)。
	Hooks Hooks
	// UserAgentSuffix 附加到 User-Agent 之后,如 "order-svc/2.3"。
	UserAgentSuffix string
}

Config 是创建客户端的配置(《2.接口设计》第 3 节)。一个客户端对应一个应用。

type ConversationInfo

type ConversationInfo struct {
	ConversationID   string `json:"conversation_id"`
	ConversationType string `json:"conversation_type"`
	// 单聊的两个用户名(按用户 ID 从小到大,已删除的为 null);群聊为 null
	Users []*string `json:"users"`
	// 群聊的群 ID;单聊为 null
	GroupID *string `json:"group_id"`
	// 最后一条消息的序号
	MaxSeq int64 `json:"max_seq"`
	// 不大于它的消息已过期删除
	ExpiredSeq int64 `json:"expired_seq"`
	// 会话中已有消息的变更版本号
	MessageVersion int64      `json:"message_version"`
	LastMessageAt  *time.Time `json:"last_message_at"`
	// ended 为群已解散
	Status    string    `json:"status"`
	CreatedAt time.Time `json:"created_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ConversationInfo 会话信息(服务端的视角)

func (*ConversationInfo) UnmarshalJSON

func (v *ConversationInfo) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ConversationMute

type ConversationMute struct {
	ConversationType string `json:"conversation_type"`
	// 单聊为对方的用户名,群为群 ID
	Target string `json:"target"`
	// none 不推送;mention_only 只在有人 @ 本人时推送(只用于群)
	Mode string `json:"mode"`
	// 到期时间,null 为一直有效
	Until     *time.Time `json:"until"`
	UpdatedAt time.Time  `json:"updated_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ConversationMute 一项会话免打扰

func (*ConversationMute) UnmarshalJSON

func (v *ConversationMute) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ConversationMuteChange

type ConversationMuteChange struct {
	ConversationType string `json:"conversation_type"`
	// 单聊为对方的用户名,群为群 ID
	Target string `json:"target"`
	Mode   string `json:"mode"`
	// 到期时间,null 为一直有效
	Until           *time.Time `json:"until"`
	UpdatedAt       time.Time  `json:"updated_at"`
	Changed         bool       `json:"changed"`
	SettingsVersion int64      `json:"settings_version"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ConversationMuteChange 设置会话免打扰的结果:这一项、是否有变化和版本号

func (*ConversationMuteChange) UnmarshalJSON

func (v *ConversationMuteChange) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ConversationState

type ConversationState struct {
	ConversationID   string `json:"conversation_id"`
	ConversationType string `json:"conversation_type"`
	// 单聊的对方(已删除为 null);群聊为 null
	Peer *string `json:"peer"`
	// 群聊的群 ID;单聊为 null
	GroupID *string `json:"group_id"`
	// 群聊中用户的身份(成员、已退出、已被移出、群已解散);单聊为 null
	Membership *string `json:"membership"`
	// 用户可见的第一条消息的序号(已计入入群时间、清空的位置和过期的消息)
	StartSeq int64 `json:"start_seq"`
	// 用户可见的最后一条消息的序号;已离开群的为离开时可见的最后一条
	MaxSeq int64 `json:"max_seq"`
	// 已读到的序号
	ReadSeq     int64 `json:"read_seq"`
	UnreadCount int64 `json:"unread_count"`
	// 是否被标记为未读
	MarkedUnread bool `json:"marked_unread"`
	// 单聊中对方已读到的序号;群聊和应用关闭单聊已读回执时为 null
	PeerReadSeq *int64 `json:"peer_read_seq"`
	// 还没读到的 @ 用户或 @ 全体成员的最近一条消息,没有时为 null
	MentionSeq *int64 `json:"mention_seq"`
	// 清空聊天记录的位置,0 表示没有清空
	ClearedSeq int64 `json:"cleared_seq"`
	// 删除会话时的位置,0 表示没有删除
	HiddenSeq int64 `json:"hidden_seq"`
	// 会话是否处于删除状态(不在会话列表中显示)
	Hidden bool `json:"hidden"`
	// 置顶会话的时间,没有置顶为 null
	PinnedAt *time.Time `json:"pinned_at"`
	// 群聊中本次入群的时间;单聊为 null
	JoinedAt *time.Time `json:"joined_at"`
	// 群聊中离开的时间;仍是成员和单聊为 null
	LeftAt *time.Time `json:"left_at"`
	// 会话当前的变更版本号
	MessageVersion int64 `json:"message_version"`
	// 用户可见的最后一条消息的时间,没有消息时为 null
	LastMessageAt *time.Time `json:"last_message_at"`
	// 这个会话的状态最近一次变化时用户会话列表的版本号;群会话还没有用户的会话状态时为 0
	Version int64 `json:"version"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ConversationState 用户在一个会话中的状态(与客户端看到的相同)

func (*ConversationState) UnmarshalJSON

func (v *ConversationState) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ConversationStateChange

type ConversationStateChange struct {
	Conversation ConversationState `json:"conversation"`
	// 为 false 表示这次没有改变任何状态
	Changed bool `json:"changed"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ConversationStateChange 代用户操作会话的结果

func (*ConversationStateChange) UnmarshalJSON

func (v *ConversationStateChange) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ConversationUnmuteChange

type ConversationUnmuteChange struct {
	// 没有这一项时为 false
	Changed         bool  `json:"changed"`
	SettingsVersion int64 `json:"settings_version"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ConversationUnmuteChange 取消会话免打扰的结果

func (*ConversationUnmuteChange) UnmarshalJSON

func (v *ConversationUnmuteChange) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ConversationsService

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

ConversationsService 会话信息与消息,用户的会话状态、未读数、标记已读、删除与清空(client.Conversations)。

func (*ConversationsService) AllMessages

func (s *ConversationsService) AllMessages(ctx context.Context, conversationID string, params SeqParams) iter.Seq2[Message, error]

AllMessages 逐条遍历会话消息(服务端视角),自动翻页:给出 AfterSeq(或只给 StartTime)时向新的方向(序号从小到大), 否则从 BeforeSeq(不给为最新)向旧的方向(序号从大到小)。按 has_more 判断结束,一页可能为空。不支持 AroundSeq。

func (*ConversationsService) AllOfUser

func (s *ConversationsService) AllOfUser(ctx context.Context, username string, params ListOptions) iter.Seq2[ConversationState, error]

AllOfUser 逐项遍历 OfUser 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。

func (*ConversationsService) AllPins

func (s *ConversationsService) AllPins(ctx context.Context, conversationID string) iter.Seq2[Message, error]

AllPins 逐项遍历 Pins 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。

func (*ConversationsService) Clear

func (s *ConversationsService) Clear(ctx context.Context, username, conversationID string) (*ConversationStateChange, error)

Clear 代用户清空聊天记录

用户看不到此前的全部消息(cleared_seq 为可见的最新一条),已读位置前进到它(与标记已读相同),@ 提醒和标记为未读随之消失。 重复清空返回 200、changed 为 false。只读状态下照常可用;访问规则同 state_of_user。

接口:POST /users/{username}/conversations/{conversation_id}/clear(conversations.clear)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ConversationsService) Delete

func (s *ConversationsService) Delete(ctx context.Context, username, conversationID string, clearMessages bool) (*ConversationStateChange, error)

Delete 代用户删除会话

把会话从用户的会话列表中隐藏(hidden_seq 为可见的最新一条),已读位置前进到它(与标记已读相同,推进单聊对方看到的已读位置), 同时取消置顶会话和标记为未读;clear_messages 为真时同时清空聊天记录。之后有了计入未读的新消息时会话重新出现。 重复删除返回 200、changed 为 false。只读状态下照常可用;访问规则同 state_of_user。

接口:DELETE /users/{username}/conversations/{conversation_id}(conversations.delete)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ConversationsService) DeleteMessages

func (s *ConversationsService) DeleteMessages(ctx context.Context, username, conversationID string, seqs []int64) (*DeleteMessagesResult, error)

DeleteMessages 代用户删除消息(只对这个用户不可见)

参数是会话中的序号,不是消息 ID。只处理用户可见的序号,不存在、不可见、已删除的忽略;有新删除的 changed 为 true。 只读状态下照常可用;访问规则同 state_of_user。

接口:POST /users/{username}/conversations/{conversation_id}/messages/delete(conversations.delete_messages)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ConversationsService) Get

func (s *ConversationsService) Get(ctx context.Context, conversationID string) (*ConversationInfo, error)

Get 查询会话信息

服务端的视角。群的会话 ID 即群 ID,还没有消息的群为 not_found。

接口:GET /conversations/{conversation_id}(conversations.get)。查询,网络错误、超时、5xx 时自动重试。

func (*ConversationsService) MarkAllRead

func (s *ConversationsService) MarkAllRead(ctx context.Context, username string) (*MarkAllReadResult, error)

MarkAllRead 代用户把全部会话标记为已读

范围与未读总数相同:当前所在的群中有未读或标记为未读的,加上按最后一条消息的时间倒序最近 1000 个单聊和已离开的群中的; 更早的还有会话时 truncated 为 true。单聊开启已读回执时同样推进对方看到的已读位置。只读状态下照常可用。用户不存在为 not_found。

接口:POST /users/{username}/conversations/read-all(conversations.mark_all_read)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ConversationsService) MarkRead

func (s *ConversationsService) MarkRead(ctx context.Context, username, conversationID string, seq *int64) (*ConversationStateChange, error)

MarkRead 代用户标记会话已读

与用户本人标记相同,是真正的已读:推进单聊对方看到的已读位置(开启单聊已读回执时),计入群已读回执并通知发送者; 用于“用户已在别处看过”的场景,与服务端发送消息(不算已读)不同。同时清除标记为未读。 seq 不给或大于可见的最新一条时读到最新(以执行时为准,需要精确时给出 seq);已读位置只前进,没有任何变化时 changed 为 false。 已离开的群也可以标记。只读状态下照常可用;访问规则同 state_of_user。

接口:POST /users/{username}/conversations/{conversation_id}/read(conversations.mark_read)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ConversationsService) Messages

func (s *ConversationsService) Messages(ctx context.Context, conversationID string, params SeqParams) (*SeqPage, error)

Messages 按序号拉取会话中的消息

服务端的视角:看到全部消息,不受任何用户的删除、清空和可见范围影响,仍按保留期过滤;已撤回、已擦除的不含内容。结果都按序号从小到大。 after_seq、before_seq、around_seq 至多给一个(多个为 invalid_argument,conflicting_params),都不给时为最新的一页; around_seq 取它本身、它之前的 limit / 2 条和之后的其余条数。 start_time、end_time 把范围限定在这段时间内,可以与序号参数同时使用:只给时间时从时间段的起点向新的方向取(响应为 next_after_seq), 之后带上 after_seq 继续。一页最多扫描 1000 个序号、合计不超过 1 MB,可能为空而 has_more 为真;是否结束只看 has_more (按 around_seq 取时为两个方向各自的 has_more_before、has_more_after)。会话不存在为 not_found。

接口:GET /conversations/{conversation_id}/messages(conversations.messages)。查询,网络错误、超时、5xx 时自动重试。

func (*ConversationsService) OfUser

func (s *ConversationsService) OfUser(ctx context.Context, username string, params ListOptions) (*Page[ConversationState], error)

OfUser 分页列出用户的会话状态

按会话 ID 排序,含处于删除状态的会话和已离开的群;已入群但还没有会话状态的群不在其中(入群事件处理后就有)。 每个满页都有 next_cursor,最后可能有一个空页。用户不存在为 not_found。

接口:GET /users/{username}/conversations(conversations.of_user)。查询,网络错误、超时、5xx 时自动重试。

func (*ConversationsService) Pins

func (s *ConversationsService) Pins(ctx context.Context, conversationID, cursor string) (*Page[Message], error)

Pins 分页列出会话中置顶的消息

服务端的视角,按置顶时间从新到旧,超过保留期的跳过。没有 limit,一页合计不超过 1 MB,超过时给出 next_cursor。会话不存在为 not_found。

接口:GET /conversations/{conversation_id}/pins(conversations.pins)。查询,网络错误、超时、5xx 时自动重试。

func (*ConversationsService) Single

func (s *ConversationsService) Single(ctx context.Context, username, peer string) (*ConversationInfo, error)

Single 查询两个用户之间的单聊会话

单聊的会话 ID 在第一条消息时生成,不能由双方的用户名算出,用这个方法查询;两个用户名的顺序无关。 任一用户不存在、两人之间还没有消息为 not_found。

接口:GET /single-conversations/{username}/{peer}(conversations.single)。查询,网络错误、超时、5xx 时自动重试。

func (*ConversationsService) StateOfUser

func (s *ConversationsService) StateOfUser(ctx context.Context, username, conversationID string) (*ConversationState, error)

StateOfUser 查询用户在一个会话中的状态

格式与客户端看到的相同。用户不是会话的参与者为 not_found(公开群为 not_group_member);刚离开群、离开处理还没完成时为 not_group_member(details.reason 为 leave_pending)。用户不存在为 not_found。

接口:GET /users/{username}/conversations/{conversation_id}(conversations.state_of_user)。查询,网络错误、超时、5xx 时自动重试。

func (*ConversationsService) UnreadCount

func (s *ConversationsService) UnreadCount(ctx context.Context, username string) (*UnreadCount, error)

UnreadCount 查询用户的未读总数

与客户端相同:当前所在的群全部计算,单聊和已离开的群按最后一条消息的时间倒序最多统计 1000 个,更早的还有会话时 truncated 为 true; 处于删除状态的会话不计。用户不存在为 not_found。

接口:GET /users/{username}/unread-count(conversations.unread_count)。查询,网络错误、超时、5xx 时自动重试。

type CreateBotParams added in v1.0.2

type CreateBotParams struct {
	Nickname  string
	AvatarURL string
	// 接收 ai.message_received 的回调地址;不给时用订阅了它的地址
	EndpointID string
	// 回调附带的最近消息条数,默认 10
	ContextMessages *int64
	// 没有新内容的超时,默认 60
	IdleTimeoutSeconds *int64
	// 同时进行的回复数上限,默认 1000
	MaxActiveStreams *int64
	// 备注,最多 256 个字符
	Description string
}

CreateBotParams 创建机器人的参数(AI.CreateBot)。

type CreateChatroomParams

type CreateChatroomParams struct {
	// 1 到 128 个字符(去掉首尾空白),不能包含控制字符(必填)
	Name string
	// 最长 512 个字符,可以换行
	Description string
	// 最长 512 字节的 http(s) 地址
	AvatarURL string
	// 最长 2048 个字符,可以换行
	Announcement string
	// 聊天室自己的人数上限,实际取它与应用策略中较小的;不给时跟随应用策略
	MaxMembers int
	// 是否出现在客户端的聊天室列表中
	Listed *bool
	// 所有者的用户名;不给时没有所有者
	Owner string
	// 初始属性,最多 100 个键、键和值合计 16 KB;键为 1 到 128 个 [A-Za-z0-9_.:-],值最长 4096 字节;所有者为服务端
	Attributes map[string]string
}

CreateChatroomParams 创建聊天室的参数(Chatrooms.Create)。

type CreateGroupParams

type CreateGroupParams struct {
	// 群主的用户名(必填)
	Owner string
	// 不给为 private
	Type string
	// 最长 64 个字符,不能包含控制字符(去掉首尾空白)
	Name string
	// 最长 512 字节的 http(s) 地址
	AvatarURL string
	// 最长 512 个字符,可以换行
	Description string
	// 最长 2048 个字符,可以换行
	Announcement string
	// 最多 32 个键、合计 4 KB;键为 1 到 32 个 [A-Za-z0-9_.-]
	Attributes map[string]string
	// 普通成员能否邀请,不给为 free
	MemberInvite string
	// 公开群的申请加入方式,不给为 approval;私有群给出返回 invalid_argument
	JoinMode string
	// 群自己的人数上限,不给为跟随应用
	MaxMembers int
	// 初始成员的用户名,最多 100 个(含重复的)
	Members []string
}

CreateGroupParams 建群(初始成员直接入群)的参数(Groups.Create)。

type CreateGroupResult

type CreateGroupResult struct {
	GroupID string `json:"group_id"`
	Type    string `json:"type"`
	// 群名称,没有时为空字符串
	Name string `json:"name"`
	// 群头像地址,没有时为空字符串
	AvatarURL string `json:"avatar_url"`
	// 群简介,没有时为空字符串
	Description string `json:"description"`
	// 群公告,没有时为空字符串
	Announcement string `json:"announcement"`
	// 公告最近一次修改的时间,从未设置过为 null
	AnnouncementUpdatedAt *time.Time `json:"announcement_updated_at"`
	// 公告最近一次的修改人;服务端修改或修改人已删除时为 null
	AnnouncementUpdatedBy *string `json:"announcement_updated_by"`
	// 自定义属性,没有时为 null
	Attributes map[string]string `json:"attributes"`
	// 群主的用户名,群主已删除时为 null
	Owner *string `json:"owner"`
	// 普通成员能否邀请:直接邀请、需要审批、不能邀请
	MemberInvite string `json:"member_invite"`
	// 公开群的申请加入方式,私有群为 null
	JoinMode *string `json:"join_mode"`
	// 是否开启了全员禁言
	MuteAll bool `json:"mute_all"`
	// 实际生效的人数上限(群自己的上限、应用策略和套餐中最小的)
	MaxMembers  int    `json:"max_members"`
	MemberCount int64  `json:"member_count"`
	Status      string `json:"status"`
	// 封禁方,没有封禁时为 null
	DisabledBy *string `json:"disabled_by"`
	// 群资料的版本号
	InfoVersion int64 `json:"info_version"`
	// 成员列表的版本号
	MemberVersion int64     `json:"member_version"`
	CreatedAt     time.Time `json:"created_at"`
	// 封禁的原因,没有封禁或没有原因时为 null
	StatusReason *string `json:"status_reason"`
	// 群自己设置的人数上限,没有设置时为 null
	MaxMembersSetting *int64     `json:"max_members_setting"`
	CreatedVia        string     `json:"created_via"`
	DismissedAt       *time.Time `json:"dismissed_at"`
	// 每个初始成员的结果,按去重后的顺序,没有初始成员时为空数组
	Results []GroupMemberResultItem `json:"results"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

CreateGroupResult 建群的结果:群的全部字段,另有每个初始成员的结果 results

func (*CreateGroupResult) Err

func (v *CreateGroupResult) Err() error

Err 有失败的项时返回汇总的错误(*BatchError),全部成功时为 nil。

func (*CreateGroupResult) FailedItems

func (v *CreateGroupResult) FailedItems() []ItemError

FailedItems 失败的项(项的标识在 Key 中);全部成功时为 nil。

func (*CreateGroupResult) OK

func (v *CreateGroupResult) OK() bool

OK 全部成功。

func (*CreateGroupResult) UnmarshalJSON

func (v *CreateGroupResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type CreateStreamParams added in v1.0.2

type CreateStreamParams struct {
	// 回复的是会话中的哪条消息(消息中显示为引用)
	ReplyToSeq *int64
	// 幂等标识,1 到 64 个可见 ASCII 字符
	ClientStreamID string
	// 会话中已有进行中的回复时先结束它
	Replace bool
}

CreateStreamParams 开始一条流式回复(底层接口,通常用 StartStream)的参数(AI.CreateStream)。

type CreateUploadParams

type CreateUploadParams struct {
	// 用途;chatroom_avatar 只在服务端装配了聊天室模块时可用(必填)
	Purpose string
	// 类型。附件为 image、voice、video、file;头像和聊天室封面为 image;群文件为 image、video、file(必填)
	Kind string
	// 字节数。头像和聊天室封面不超过 5 MB;附件和群文件不超过应用的 max_upload_bytes,其中图片不超过 20 MB、语音不超过 5 MB(必填)
	Size int64
	// 最长 128 个字符;只作提示,格式由服务端按内容识别
	ContentType string
	// 文件名,最长 255 个字符,不能含控制字符、/、\ 和改变文字方向的字符;kind 为 file 和群文件必填
	Name string
	// 群 ID;群文件必填,其他用途不能带
	GroupID string
	// 所属用户的用户名;user_avatar 必填且必须是使用这个头像的用户,其他用途可选
	Owner string
}

CreateUploadParams 创建上传的参数(Media.CreateUpload)。

type CreateUserParams

type CreateUserParams struct {
	// 1 到 64 个 [A-Za-z0-9_.-],不能是 . 或 ..(必填)
	Username string
	// 1 到 64 个字符;不给时只能用登录凭证登录
	Password string
	// 最长 64 个字符
	Nickname string
	// 最长 512 字节的 http(s) 地址
	AvatarURL string
	// 最多 32 个键、合计 4 KB
	Attributes map[string]string
}

CreateUserParams 创建用户的参数(批量创建的每一项相同)

type CreateWordListParams

type CreateWordListParams struct {
	// 1 到 64 个字符,不能有控制字符,应用内唯一(必填)
	Name string
	// 屏蔽词库或放行词库,默认 block;创建后不能修改
	Kind string
	// 命中时的处理;屏蔽词库必填,放行词库不能给
	Action string
	// 默认 contains;放行词库只能为 contains
	MatchMode string
	// 默认 custom
	Category string
	// 适用的场景,不能为空数组、不能重复;不给为全部场景
	Scenes []string
	// 默认 true
	Enabled *bool
}

CreateWordListParams 创建词库的参数(Moderation.CreateWordList)。

type DND

type DND struct {
	// 开启的时长(秒);不给为一直开启
	DurationSeconds *int64
}

DND 全局免打扰:null 关闭;对象为开启

type DecideParams

type DecideParams struct {
	// 必填
	Decision string
	// 处置,只用于 violation
	Actions []ModerationActionInput
	// 是否计入作者的违规,默认 true
	CountViolation *bool
	// 说明,最长 256 个字符
	Note string
	// 期望的记录版本
	Version *int64
}

DecideParams 作出结论或改判的参数(Moderation.Decide)。

type Decision

type Decision struct {
	Decision       string                  // violation、no_violation 等(必填)
	Actions        []ModerationActionInput // 处置,只用于 violation
	CountViolation *bool                   // 是否计入作者的违规,默认是
	Note           string                  // 说明,最长 256 个字符
}

Decision 是 ProcessPending 的处理函数作出的结论(《内容安全/3.接口设计》第 4 节)。

type DeleteMessagesResult

type DeleteMessagesResult struct {
	// 有新删除的消息
	Changed bool `json:"changed"`
	// 用户会话列表的版本号(没有变化时为当前值)
	Version int64 `json:"version"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

DeleteMessagesResult 代用户删除消息的结果

func (*DeleteMessagesResult) UnmarshalJSON

func (v *DeleteMessagesResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type DisableUserParams

type DisableUserParams struct {
	// 最长 256 个字符
	Reason string
	// 不给为永久
	DurationSeconds *int64
}

DisableUserParams 封禁用户的参数(Users.Disable)。

type DownloadURLItem

type DownloadURLItem struct {
	// 请求中的地址
	URL string `json:"url"`
	// 下载地址,请求时不带 Authorization
	DownloadURL string `json:"download_url"`
	// 下载地址的到期时间(60 到 90 分钟后)
	ExpiresAt time.Time `json:"expires_at"`
	// Error 失败时的错误(Key 为这一项的标识),成功时为 nil。
	Error *ItemError `json:"-"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

DownloadURLItem 换取下载地址的一项:成功时有 download_url、expires_at,失败时有 code、message

func (DownloadURLItem) String

func (v DownloadURLItem) String() string

String 遮掩敏感的字段。

func (*DownloadURLItem) UnmarshalJSON

func (v *DownloadURLItem) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type EditMessageParams

type EditMessageParams struct {
	// 新的内容,整体替换,规则同发送
	Body json.RawMessage
	// 新的自定义扩展,整体替换;null 清除;不传不变;三种状态:零值不发送,Null 发送 null,Set 发送值
	Ext Field[json.RawMessage]
	// 原因,写入操作日志
	Reason *string
}

EditMessageParams 编辑消息的参数(Messages.Edit)。

type Error

type Error struct {
	StatusCode int            // HTTP 状态码;SDK 自己的错误为 0(invalid_response 为实际的状态码)
	Code       string         // 服务端的错误码,或 SDK 的本地错误码(CodeNetworkError 等)
	Message    string         // 服务端的说明,只用于日志
	Details    map[string]any // 原样;没有时为 nil
	RequestID  string         // 错误体中的 request_id,没有时为响应头 X-Request-ID,都没有时为 SDK 发出的
	RetryAfter time.Duration  // 响应头 Retry-After
	Op         string         // 接口名,如 users.create
	Attempts   int            // 这次调用一共尝试了几次
	// Retried 为真表示这个错误来自自动重试的尝试,而之前的尝试结果不明(可能已经执行):
	// already_exists、not_found、version_conflict 时可以按“前一次尝试已经执行”处理(《1.功能概述文档》第 6.1 节)。
	Retried bool
	Err     error // 底层错误(网络错误、context.Canceled、context.DeadlineExceeded 等)
}

Error 是 SDK 返回的错误:服务端的错误({ "error": { code, message, details, request_id } })和 SDK 自己的错误 (《2.接口设计》第 4 节)。用 errors.As(err, &e) 取得;按 Code 和 Details 判断,不解析 Message。

func (*Error) Error

func (e *Error) Error() string

Error 如 "users.create: 409 already_exists: 用户名已被占用 (request_id=...)",不含请求体和令牌。

func (*Error) Reason

func (e *Error) Reason() string

Reason 返回 details.reason,没有时为空。

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap 返回底层错误:超时为 context.DeadlineExceeded(ctx 的截止时间已到时),取消为 context.Canceled。

type ExportPage

type ExportPage struct {
	Items              []Message
	NextAfterMessageID string // 下一页的 AfterMessageID
	HasMore            bool
	Raw                json.RawMessage
}

ExportPage 是按消息 ID 导出的一页(从旧到新)。是否结束只看 HasMore:服务端在本页条数等于 Limit 时就给 true,下一页可能为空。

func (*ExportPage) UnmarshalJSON

func (p *ExportPage) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ExportParams

type ExportParams struct {
	// 从这条消息之后开始(不含);不给时从最早的开始
	AfterMessageID string
	Limit          int
}

ExportParams 按消息 ID 从旧到新导出应用的消息的参数(Messages.Export)。

type Field

type Field[T any] struct {
	// contains filtered or unexported fields
}

Field 是修改类参数中区分“不传”“传 null”“传值”三种状态的字段(《1.功能概述文档》第 4 节)。

零值为未设置,不出现在请求中;Null 发送 null;Set 发送值。例如修改用户资料时 Attributes: Set(map[string]Field[string]{"vip": Set("1"), "level": Null[string]()}) 修改 vip、删除 level,Attributes: Null[map[string]Field[string]]() 清空全部。

func Null

func Null[T any]() Field[T]

Null 返回传 null 的 Field。

func Set

func Set[T any](v T) Field[T]

Set 返回传值的 Field。

func (Field[T]) IsNull

func (f Field[T]) IsNull() bool

IsNull 为真表示传 null。

func (Field[T]) IsSet

func (f Field[T]) IsSet() bool

IsSet 为真表示会出现在请求中(传 null 或传值)。

func (Field[T]) Value

func (f Field[T]) Value() (v T, ok bool)

Value 返回值;ok 为假表示未设置或为 null。

type File

type File struct {
	FileID  string `json:"file_id"`
	Purpose string `json:"purpose"`
	Kind    string `json:"kind"`
	// pending 为上传中
	Status string `json:"status"`
	// 文件地址(头像为公开地址),写入消息的 body 或资料的 avatar_url;不是下载地址
	URL string `json:"url"`
	// 缩略图地址,只有可用或被屏蔽的图片附件、图片群文件有
	ThumbnailURL *string `json:"thumbnail_url"`
	// 文件名
	Name *string `json:"name"`
	// 按内容识别出的格式,上传中的为 null
	ContentType *string `json:"content_type"`
	// 字节数:图片去掉元数据、头像缩放之后的值;上传中的为声明的大小
	Size int64 `json:"size"`
	// 图片的宽度(像素)
	Width *int64 `json:"width"`
	// 图片的高度(像素)
	Height *int64 `json:"height"`
	// 所属用户的用户名,没有或已删除为 null
	Owner *string `json:"owner"`
	// 群文件所在的群
	GroupID *string `json:"group_id"`
	// 上传方式
	Via       string    `json:"via"`
	CreatedAt time.Time `json:"created_at"`
	// 按应用当前的保留天数算出的过期时间,只有附件和设置了保留天数的群文件有
	ExpiresAt *time.Time `json:"expires_at"`
	// 头像是否正在被资料使用,其他用途为 false
	InUse bool `json:"in_use"`
	// 保存内容的 SHA-256(十六进制),只有图片附件、图片群文件和头像有
	SHA256 *string `json:"sha256"`
	// 上传者:OpenAPI 为签发 App Token 的 secret_id,控制台为账号 ID,客户端为 null
	CreatedBy *string    `json:"created_by"`
	BlockedAt *time.Time `json:"blocked_at"`
	// 屏蔽方
	BlockedBy *string `json:"blocked_by"`
	// 引起屏蔽的规则来源
	BlockRuleSource *string    `json:"block_rule_source"`
	BlockReason     *string    `json:"block_reason"`
	DeletedAt       *time.Time `json:"deleted_at"`
	DeleteReason    *string    `json:"delete_reason"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

File 文件(服务端的字段)

func (*File) UnmarshalJSON

func (v *File) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type FilePart added in v1.0.2

type FilePart struct {
	URL      string
	Name     string
	Size     int64
	MimeType string
}

FilePart 是文件片段。

type FinishOptions added in v1.0.2

type FinishOptions struct {
	FinishReason string // 如 stop、length、tool_calls,默认 stop
	Model        string
	Usage        *AIUsage
}

FinishOptions 是结束的可选信息。

type FinishStreamParams added in v1.0.2

type FinishStreamParams struct {
	// 如 stop、length、tool_calls,默认 stop
	FinishReason string
	Model        string
	Usage        *AIUsage
}

FinishStreamParams 结束流(已完成)的参数(AI.FinishStream)。

type Friend

type Friend struct {
	// 好友的用户名(小写)
	Username string `json:"username"`
	// 好友的昵称,没有时为空字符串
	Nickname string `json:"nickname"`
	// 好友的头像地址,没有时为空字符串
	AvatarURL string `json:"avatar_url"`
	// 备注,没有时为空字符串
	Remark string `json:"remark"`
	// 自定义属性,没有时为 null(不是空对象)
	Attributes map[string]string `json:"attributes"`
	// 添加来源,没有时为空字符串
	AddSource string `json:"add_source"`
	// 成为好友的时间
	CreatedAt time.Time `json:"created_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

Friend 好友(所有者一侧看到的,备注和自定义属性只有所有者能看到)

func (*Friend) UnmarshalJSON

func (v *Friend) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type FriendChange

type FriendChange struct {
	Friend *Friend `json:"friend"`
	// 这次请求是否改变了所有者的好友列表
	Changed bool `json:"changed"`
	// 所有者好友列表的版本号;改变时为新版本号,没有改变时为当前的版本号(可能含其他设备的修改)
	FriendVersion int64 `json:"friend_version"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

FriendChange 好友列表的写操作结果;添加、修改时有 friend,删除时没有

func (*FriendChange) UnmarshalJSON

func (v *FriendChange) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type FriendCheck

type FriendCheck struct {
	// 用户名(小写)
	Username string `json:"username"`
	IsFriend bool   `json:"is_friend"`
	// 所有者是否拉黑了这个用户
	Blocked bool `json:"blocked"`
	// 两人之间未过期的待处理申请;sent 为所有者发出的,received 为对方发来的,没有为 null
	Request *string `json:"request"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

FriendCheck 所有者与一个用户的关系

func (*FriendCheck) UnmarshalJSON

func (v *FriendCheck) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type FriendRequest

type FriendRequest struct {
	// 对方的用户名(收到的为申请人,发出的为被申请人)
	Username string `json:"username"`
	// 对方的昵称,没有时为空字符串
	Nickname string `json:"nickname"`
	// 对方的头像地址,没有时为空字符串
	AvatarURL string `json:"avatar_url"`
	// 附言,没有时为空字符串
	Message string `json:"message"`
	// 只在发出的申请中出现:申请人预先设置的备注
	Remark string `json:"remark"`
	// 添加来源,没有时为空字符串
	AddSource string `json:"add_source"`
	// expired 为已过期的待处理申请
	Status string `json:"status"`
	// 只在收到的申请中出现:是否未读,只有未过期的待处理申请可能为 true
	Unread bool `json:"unread"`
	// 最近一次发送的时间
	RequestedAt time.Time `json:"requested_at"`
	// 待处理申请的过期时间,其他状态为 null
	ExpiresAt *time.Time `json:"expires_at"`
	// 处理的时间,没有处理时为 null
	HandledAt *time.Time `json:"handled_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

FriendRequest 好友申请(站在所有者的角度)

func (*FriendRequest) UnmarshalJSON

func (v *FriendRequest) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type FriendSettings

type FriendSettings struct {
	// 用户自己的设置,没有设置过为 null(跟随应用的默认值)
	FriendAddMode *string `json:"friend_add_mode"`
	// 实际生效的值
	EffectiveFriendAddMode string `json:"effective_friend_add_mode"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

FriendSettings 加好友方式

func (*FriendSettings) UnmarshalJSON

func (v *FriendSettings) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type FriendsService

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

FriendsService 好友、好友申请(查询)与加好友方式(client.Friends)。

func (*FriendsService) Add

func (s *FriendsService) Add(ctx context.Context, username, friend string, params AddFriendParams) (*FriendChange, error)

Add 直接添加好友(双方同时成为好友)

服务端添加不检查加好友方式和双方的黑名单,不经过加好友前回调和内容安全;双方的好友数上限照常检查, 已满返回 limit_exceeded(details.reason 为 friend_limit 或 peer_friend_limit)。两人之间未过期的待处理申请改为 accepted。 remark、attributes 只设置 {username} 一侧,没给 remark 时取 {username} 发给对方的待处理申请中预设的备注;对方一侧取对方申请中预设的备注。 已是好友时按修改处理:写入这次给出的 remark、attributes(add_source、created_at 忽略),内容有变化时 changed 为 true,所以重复调用时 changed 为 false。 {friend} 与 {username} 相同返回 invalid_argument;对方被封禁不影响添加。只读状态下返回 app_unavailable。

接口:PUT /users/{username}/friends/{friend}(friends.add)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*FriendsService) All

func (s *FriendsService) All(ctx context.Context, username string, params ListFriendsParams) iter.Seq2[Friend, error]

All 逐项遍历 List 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。 不带 KnownVersion(遍历要的是全部数据)。

func (*FriendsService) AllRequests

func (s *FriendsService) AllRequests(ctx context.Context, username string, params ListFriendRequestsParams) iter.Seq2[FriendRequest, error]

AllRequests 逐项遍历 Requests 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。

func (*FriendsService) BatchAdd

func (s *FriendsService) BatchAdd(ctx context.Context, username string, friends []AddFriendItem) (*BatchAddFriendsResult, error)

BatchAdd 批量直接添加好友(每次最多 100 个)

逐个处理、各项独立成败,整体返回 200;每项的规则与单个添加相同,参数不合法、用户不存在、好友数已满的项出现在 failed 中。 已是好友的按修改处理,也出现在 added 中。同一个用户名出现多次时不去重,按出现的次数处理。结果不带 changed 和版本号。 按项数计入 OpenAPI 额度,额度不足时整个请求返回 rate_limited、任何一项都没有执行。只读状态下返回 app_unavailable。

接口:POST /users/{username}/friends/batch(friends.batch_add)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*FriendsService) BatchAddAll

func (s *FriendsService) BatchAddAll(ctx context.Context, username string, friends []AddFriendItem) (*BatchAddFriendsResult, error)

BatchAddAll 按上限(100 项)拆分、依次提交、合并结果;服务端以 too_many_items 给出更小的上限(应用的设置)时按它重新拆分。 某一批整体失败时停止,返回已完成部分的合并结果和那一批的错误;没有出现在结果中的项可以再提交一次。

func (*FriendsService) BatchDelete

func (s *FriendsService) BatchDelete(ctx context.Context, username string, usernames []string) (*BatchDeleteFriendsResult, error)

BatchDelete 批量删除好友(每次最多 100 个)

逐个处理,整体返回 200;原本就不是好友的也算成功、出现在 deleted 中,对方用户不存在的项为 not_found。 同一个用户名出现多次时不去重。按项数计入 OpenAPI 额度,额度不足时整个请求返回 rate_limited、任何一项都没有执行。只读状态下照常执行。

接口:POST /users/{username}/friends/batch-delete(friends.batch_delete)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*FriendsService) Check

func (s *FriendsService) Check(ctx context.Context, username string, usernames []string) ([]FriendCheck, error)

Check 检查用户与一组用户的关系(每次最多 100 个)

结果按请求的顺序、转为小写后去重;不存在、已删除、格式不对的用户名和 {username} 本人不出现在结果中。 blocked 只表示 {username} 是否拉黑了对方,不含对方是否拉黑了 {username};应用关闭黑名单拦截时仍按已有的数据返回。 是读操作,按一次请求计入额度(不按项数)。

接口:POST /users/{username}/friends/check(friends.check)。查询,网络错误、超时、5xx 时自动重试。

func (*FriendsService) Delete

func (s *FriendsService) Delete(ctx context.Context, username, friend string) (*FriendChange, error)

Delete 删除好友(双方的关系同时解除)

两边的备注和自定义属性一并删除,双方收到原因为 server 的 friend.removed。 不是好友时也返回 200,changed 为 false(不是 not_found);对方用户不存在或已删除返回 not_found。只读状态下照常执行。

接口:DELETE /users/{username}/friends/{friend}(friends.delete)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*FriendsService) DeleteAll

func (s *FriendsService) DeleteAll(ctx context.Context, username string) (int, error)

DeleteAll 删除用户的全部好友(每次请求最多 100 位,SDK 循环到 has_more 为 false)

每次请求按好友的内部用户 ID 取出最多 100 位逐个删除,返回这次实际删除的人数 deleted_count 和 has_more; SDK 循环调用直到 has_more 为 false,返回 deleted_count 的总和。每次请求按取出的人数计入 OpenAPI 额度。 双方的关系同时解除,每位好友收到原因为 server 的 friend.removed;已删除、尚未补写删除标记的好友同样删除(这时 friend_username 为空)。 中途出错时整个请求返回错误,已删除的不回滚,再次调用即可继续,所以可以重试。只读状态下照常执行。

接口:DELETE /users/{username}/friends(friends.delete_all)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

SDK 循环调用直到 has_more 为假,返回删除的总数(出错时返回已删除的数和错误)。

func (*FriendsService) Get

func (s *FriendsService) Get(ctx context.Context, username, friend string) (*Friend, error)

Get 查询一位好友

不是好友、对方用户不存在或已删除都返回 not_found;{friend} 与 {username} 相同返回 invalid_argument。

接口:GET /users/{username}/friends/{friend}(friends.get)。查询,网络错误、超时、5xx 时自动重试。

func (*FriendsService) List

func (s *FriendsService) List(ctx context.Context, username string, params ListFriendsParams) (*VersionedPage[Friend], error)

List 分页列出用户的好友(带版本号)

按好友的内部用户 ID 排序。known_version 只在不带 cursor 时生效:与当前版本号相同时只返回 version、not_modified、count、max_count,没有 items 和 next_cursor。 跳过已删除、清理尚未完成的用户,一页的条数可能少于 limit 甚至为 0,是否还有下一页只看 next_cursor;count 取自计数,这段时间可能比实际返回的多。 max_count 为应用的好友数上限。{username} 不存在或已删除返回 not_found。

接口:GET /users/{username}/friends(friends.list)。查询,网络错误、超时、5xx 时自动重试。

func (*FriendsService) Requests

func (s *FriendsService) Requests(ctx context.Context, username string, params ListFriendRequestsParams) (*Page[FriendRequest], error)

Requests 分页列出用户收到或发出的好友申请

按发送时间倒序。status 为 pending 只含未过期的待处理申请,expired 为已过期的待处理申请。 跳过已删除的用户,一页的条数可能少于 limit。OpenAPI 不提供发送、同意、拒绝申请,需要建立好友关系时直接添加。

接口:GET /users/{username}/friend-requests(friends.requests)。查询,网络错误、超时、5xx 时自动重试。

func (*FriendsService) SetSettings

func (s *FriendsService) SetSettings(ctx context.Context, username string, friendAddMode Field[string]) (*FriendSettings, error)

SetSettings 设置用户的加好友方式

friend_add_mode 必须出现,null 表示改用应用的默认值;缺少时返回 invalid_argument。 与当前的设置相同时不做修改,重复调用结果相同。设置不通知其他设备、不发布事件;只读状态下照常执行。

接口:PUT /users/{username}/friend-settings(friends.set_settings)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*FriendsService) Settings

func (s *FriendsService) Settings(ctx context.Context, username string) (*FriendSettings, error)

Settings 查询用户的加好友方式

接口:GET /users/{username}/friend-settings(friends.settings)。查询,网络错误、超时、5xx 时自动重试。

func (*FriendsService) Update

func (s *FriendsService) Update(ctx context.Context, username, friend string, params UpdateFriendParams) (*FriendChange, error)

Update 修改好友的备注和自定义属性

只修改 {username} 一侧,对方看不到。remark、attributes 都没给(remark 为 null 等于没给)时返回 invalid_argument。 与原值相同时 changed 为 false、不发布事件,所以重复调用结果相同。不是好友返回 not_found;只读状态下返回 app_unavailable。

接口:PATCH /users/{username}/friends/{friend}(friends.update)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

type Group

type Group struct {
	GroupID string `json:"group_id"`
	Type    string `json:"type"`
	// 群名称,没有时为空字符串
	Name string `json:"name"`
	// 群头像地址,没有时为空字符串
	AvatarURL string `json:"avatar_url"`
	// 群简介,没有时为空字符串
	Description string `json:"description"`
	// 群公告,没有时为空字符串
	Announcement string `json:"announcement"`
	// 公告最近一次修改的时间,从未设置过为 null
	AnnouncementUpdatedAt *time.Time `json:"announcement_updated_at"`
	// 公告最近一次的修改人;服务端修改或修改人已删除时为 null
	AnnouncementUpdatedBy *string `json:"announcement_updated_by"`
	// 自定义属性,没有时为 null
	Attributes map[string]string `json:"attributes"`
	// 群主的用户名,群主已删除时为 null
	Owner *string `json:"owner"`
	// 普通成员能否邀请:直接邀请、需要审批、不能邀请
	MemberInvite string `json:"member_invite"`
	// 公开群的申请加入方式,私有群为 null
	JoinMode *string `json:"join_mode"`
	// 是否开启了全员禁言
	MuteAll bool `json:"mute_all"`
	// 实际生效的人数上限(群自己的上限、应用策略和套餐中最小的)
	MaxMembers  int    `json:"max_members"`
	MemberCount int64  `json:"member_count"`
	Status      string `json:"status"`
	// 封禁方,没有封禁时为 null
	DisabledBy *string `json:"disabled_by"`
	// 群资料的版本号
	InfoVersion int64 `json:"info_version"`
	// 成员列表的版本号
	MemberVersion int64     `json:"member_version"`
	CreatedAt     time.Time `json:"created_at"`
	// 封禁的原因,没有封禁或没有原因时为 null
	StatusReason *string `json:"status_reason"`
	// 群自己设置的人数上限,没有设置时为 null
	MaxMembersSetting *int64     `json:"max_members_setting"`
	CreatedVia        string     `json:"created_via"`
	DismissedAt       *time.Time `json:"dismissed_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

Group 群(服务端接口看到的全部字段)

func (*Group) UnmarshalJSON

func (v *Group) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type GroupBlacklistChange

type GroupBlacklistChange struct {
	// 拉黑时为这一条记录(已在黑名单中时为原来的记录);移出时不出现
	Entry   *GroupBlacklistEntry `json:"entry"`
	Changed bool                 `json:"changed"`
	// 被拉黑的人是成员时同时被移出,为新的成员列表版本号,否则为当前的
	MemberVersion int64 `json:"member_version"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

GroupBlacklistChange 拉黑、移出群黑名单的结果

func (*GroupBlacklistChange) UnmarshalJSON

func (v *GroupBlacklistChange) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type GroupBlacklistEntry

type GroupBlacklistEntry struct {
	Username  string `json:"username"`
	Nickname  string `json:"nickname"`
	AvatarURL string `json:"avatar_url"`
	// 没有时为空字符串
	Reason string `json:"reason"`
	// 拉黑的人的用户名;服务端拉黑或拉黑的人已删除时为 null
	CreatedBy *string `json:"created_by"`
	// 拉黑时的身份
	CreatedByRole string    `json:"created_by_role"`
	CreatedAt     time.Time `json:"created_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

GroupBlacklistEntry 群黑名单中的一项

func (*GroupBlacklistEntry) UnmarshalJSON

func (v *GroupBlacklistEntry) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type GroupChange

type GroupChange struct {
	GroupID string `json:"group_id"`
	Type    string `json:"type"`
	// 群名称,没有时为空字符串
	Name string `json:"name"`
	// 群头像地址,没有时为空字符串
	AvatarURL string `json:"avatar_url"`
	// 群简介,没有时为空字符串
	Description string `json:"description"`
	// 群公告,没有时为空字符串
	Announcement string `json:"announcement"`
	// 公告最近一次修改的时间,从未设置过为 null
	AnnouncementUpdatedAt *time.Time `json:"announcement_updated_at"`
	// 公告最近一次的修改人;服务端修改或修改人已删除时为 null
	AnnouncementUpdatedBy *string `json:"announcement_updated_by"`
	// 自定义属性,没有时为 null
	Attributes map[string]string `json:"attributes"`
	// 群主的用户名,群主已删除时为 null
	Owner *string `json:"owner"`
	// 普通成员能否邀请:直接邀请、需要审批、不能邀请
	MemberInvite string `json:"member_invite"`
	// 公开群的申请加入方式,私有群为 null
	JoinMode *string `json:"join_mode"`
	// 是否开启了全员禁言
	MuteAll bool `json:"mute_all"`
	// 实际生效的人数上限(群自己的上限、应用策略和套餐中最小的)
	MaxMembers  int    `json:"max_members"`
	MemberCount int64  `json:"member_count"`
	Status      string `json:"status"`
	// 封禁方,没有封禁时为 null
	DisabledBy *string `json:"disabled_by"`
	// 群资料的版本号
	InfoVersion int64 `json:"info_version"`
	// 成员列表的版本号
	MemberVersion int64     `json:"member_version"`
	CreatedAt     time.Time `json:"created_at"`
	// 封禁的原因,没有封禁或没有原因时为 null
	StatusReason *string `json:"status_reason"`
	// 群自己设置的人数上限,没有设置时为 null
	MaxMembersSetting *int64     `json:"max_members_setting"`
	CreatedVia        string     `json:"created_via"`
	DismissedAt       *time.Time `json:"dismissed_at"`
	// 这次请求是否改变了群
	Changed bool `json:"changed"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

GroupChange 修改群资料和设置、转让群主、全员禁言、封禁和解封的结果:群的全部字段,另有 changed

func (*GroupChange) UnmarshalJSON

func (v *GroupChange) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type GroupFilesPage

type GroupFilesPage struct {
	Items []File `json:"items"`
	// 下一页的游标,空表示没有下一页
	NextCursor string `json:"next_cursor"`
	// 群中可用的文件数
	FileCount int64 `json:"file_count"`
	// 群文件占用的字节数
	UsedBytes int64 `json:"used_bytes"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

GroupFilesPage GroupFilesPage

func (*GroupFilesPage) UnmarshalJSON

func (v *GroupFilesPage) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type GroupInviteSettings

type GroupInviteSettings struct {
	// 用户设置的值,没有设置过(跟随应用)为 null
	InviteMode *string `json:"invite_mode"`
	// 实际生效的值
	EffectiveInviteMode string `json:"effective_invite_mode"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

GroupInviteSettings 用户的入群邀请方式

func (*GroupInviteSettings) UnmarshalJSON

func (v *GroupInviteSettings) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type GroupMember

type GroupMember struct {
	Username string `json:"username"`
	// 用户资料中的昵称
	Nickname string `json:"nickname"`
	// 用户资料中的头像
	AvatarURL string `json:"avatar_url"`
	Role      string `json:"role"`
	// 本群的群昵称,没有时为空字符串
	GroupNickname string `json:"group_nickname"`
	// 成员属性,没有时为 null
	Attributes map[string]string `json:"attributes"`
	// 此刻是否被禁言
	Muted bool `json:"muted"`
	// 禁言的到期时间;没有被禁言或永久禁言时为 null
	MutedUntil *time.Time `json:"muted_until"`
	JoinedVia  string     `json:"joined_via"`
	// 邀请人的用户名;没有或已删除时为 null
	Inviter  *string   `json:"inviter"`
	JoinedAt time.Time `json:"joined_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

GroupMember 群成员

func (*GroupMember) UnmarshalJSON

func (v *GroupMember) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type GroupMemberChange

type GroupMemberChange struct {
	Member  GroupMember `json:"member"`
	Changed bool        `json:"changed"`
	// 改变时为新的成员列表版本号,否则为当前的
	MemberVersion int64 `json:"member_version"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

GroupMemberChange 修改一位成员(群昵称、成员属性、角色、禁言)的结果

func (*GroupMemberChange) UnmarshalJSON

func (v *GroupMemberChange) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type GroupMemberResultItem

type GroupMemberResultItem struct {
	// 用户名(小写)
	Username string `json:"username"`
	Status   string `json:"status"`
	// Error 失败时的错误(Key 为这一项的标识),成功时为 nil。
	Error *ItemError `json:"-"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

GroupMemberResultItem 批量加人、移人和建群中一个用户的结果:成功时有 status,失败时有 code、message、details

func (*GroupMemberResultItem) UnmarshalJSON

func (v *GroupMemberResultItem) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type GroupMembersResult

type GroupMembersResult struct {
	// 这次请求是否改变了成员列表
	Changed bool `json:"changed"`
	// 改变时为新的成员列表版本号,否则为当前的
	MemberVersion int64 `json:"member_version"`
	// 按去重后的顺序
	Results []GroupMemberResultItem `json:"results"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

GroupMembersResult 批量加人、移人的结果

func (*GroupMembersResult) Err

func (v *GroupMembersResult) Err() error

Err 有失败的项时返回汇总的错误(*BatchError),全部成功时为 nil。

func (*GroupMembersResult) FailedItems

func (v *GroupMembersResult) FailedItems() []ItemError

FailedItems 失败的项(项的标识在 Key 中);全部成功时为 nil。

func (*GroupMembersResult) OK

func (v *GroupMembersResult) OK() bool

OK 全部成功。

func (*GroupMembersResult) UnmarshalJSON

func (v *GroupMembersResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type GroupRequest

type GroupRequest struct {
	GroupID string `json:"group_id"`
	// 申请、待审批的成员邀请、待被邀请人确认的邀请
	Kind string `json:"kind"`
	// 目标用户(申请人或被邀请人)
	Username  string `json:"username"`
	Nickname  string `json:"nickname"`
	AvatarURL string `json:"avatar_url"`
	// 邀请人;申请或邀请人已删除时为 null
	Inviter *GroupRequestInviter `json:"inviter"`
	// 申请理由或邀请附言,没有时为空字符串
	Message string `json:"message"`
	// 拒绝理由,没有时为空字符串
	Reason string `json:"reason"`
	// 对外显示的状态
	Status string `json:"status"`
	// 失效的原因;群被封禁期间显示为 canceled 的为 null
	CancelCause *string   `json:"cancel_cause"`
	RequestedAt time.Time `json:"requested_at"`
	// 只有待处理时有值
	ExpiresAt *time.Time `json:"expires_at"`
	HandledAt *time.Time `json:"handled_at"`
	// 处理人的用户名;系统处理或处理人已删除时为 null
	HandledBy *string `json:"handled_by"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

GroupRequest 一条入群申请或邀请

func (*GroupRequest) UnmarshalJSON

func (v *GroupRequest) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type GroupRequestInviter

type GroupRequestInviter struct {
	Username  string `json:"username"`
	Nickname  string `json:"nickname"`
	AvatarURL string `json:"avatar_url"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

GroupRequestInviter 邀请人;申请或邀请人已删除时为 null

func (*GroupRequestInviter) UnmarshalJSON

func (v *GroupRequestInviter) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type GroupsService

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

GroupsService 群组、群成员、群黑名单、申请与邀请(查询)、入群邀请方式(client.Groups)。

func (*GroupsService) AddMembers

func (s *GroupsService) AddMembers(ctx context.Context, groupID string, usernames []string) (*GroupMembersResult, error)

AddMembers 批量加人(每次最多 100 个,直接入群)

用户名转为小写、去重后为 1 到 100 个,按去重后的项数计入 OpenAPI 额度;结果按去重后的顺序,同一个事务中完成,member_version 只加 1。 直接入群(joined_via 为 server),不检查群的邀请设置、用户的入群邀请方式和用户之间的黑名单,不经过加群前回调;检查群黑名单和上限。 逐项为 joined、already_member(重试时已加入的也是它),或失败:not_found(用户不存在)、permission_denied(details.reason 为 group_blacklisted)、limit_exceeded(group_member_limit、user_group_limit)。群被封禁返回 group_disabled,只读状态下返回 app_unavailable。

接口:POST /groups/{group_id}/members/batch(groups.add_members)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*GroupsService) AddToBlacklist

func (s *GroupsService) AddToBlacklist(ctx context.Context, groupID, username, reason string) (*GroupBlacklistChange, error)

AddToBlacklist 拉入群黑名单

不要求是成员;是成员时同时移出,他在本群的待处理请求失效。已在黑名单中时不修改原记录(包括原因),changed 为假,entry 为原来的记录。 不能拉黑群主(permission_denied);每个群最多 1000 人,已满返回 limit_exceeded(group_blacklist_limit)。被封禁的群、只读状态下也可以拉黑。

接口:PUT /groups/{group_id}/blacklist/{username}(groups.add_to_blacklist)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*GroupsService) All

All 逐项遍历 List 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。

func (*GroupsService) AllBlacklist

func (s *GroupsService) AllBlacklist(ctx context.Context, groupID string, params ListOptions) iter.Seq2[GroupBlacklistEntry, error]

AllBlacklist 逐项遍历 Blacklist 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。

func (*GroupsService) AllMembers

func (s *GroupsService) AllMembers(ctx context.Context, groupID string, params ListMembersParams) iter.Seq2[GroupMember, error]

AllMembers 逐项遍历 Members 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。 不带 KnownVersion(遍历要的是全部数据)。

func (*GroupsService) AllOfUser

func (s *GroupsService) AllOfUser(ctx context.Context, username string, params ListOptions) iter.Seq2[UserGroup, error]

AllOfUser 逐项遍历 OfUser 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。

func (*GroupsService) AllRequests

func (s *GroupsService) AllRequests(ctx context.Context, groupID string, params ListGroupRequestsParams) iter.Seq2[GroupRequest, error]

AllRequests 逐项遍历 Requests 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。

func (*GroupsService) Blacklist

func (s *GroupsService) Blacklist(ctx context.Context, groupID string, params ListOptions) (*Page[GroupBlacklistEntry], error)

Blacklist 分页列出群黑名单(按用户 ID 升序)

跳过已删除的用户,一页可能少于 limit 条。

接口:GET /groups/{group_id}/blacklist(groups.blacklist)。查询,网络错误、超时、5xx 时自动重试。

func (*GroupsService) Create

Create 建群(初始成员直接入群)

群 ID 由服务端生成,不幂等、不自动重试:超时后按 owner 调用 list 确认(把业务 ID 写进 attributes 便于识别)。 初始成员直接入群(joined_via 为 create),逐项结果在 results 中,某一项失败不影响建群;群主出现在 members 中时为 already_member。 失败的项:not_found(用户不存在)、limit_exceeded(details.reason 为 group_member_limit、user_group_limit)。 群主不存在返回 not_found;群主加入的群数已满返回 limit_exceeded(user_group_limit),应用的群数达到套餐上限返回 limit_exceeded(app_group_limit),都不建群。名称、简介、公告和头像经过内容安全检查,可能被替换(返回的与传入的不同)或返回 content_rejected。按 max(去重后的成员数, 1) 计入 OpenAPI 额度。只读状态下返回 app_unavailable。

接口:POST /groups(groups.create)。不幂等:请求发出后不自动重试(被限流的照常等待后重发),超时后先查询结果再决定是否重试。

func (*GroupsService) Delete

func (s *GroupsService) Delete(ctx context.Context, groupID, reason string) error

Delete 解散群

不可恢复:状态立即改为 dismissed,成员保留 1 小时后由后台移出。重复解散(已解散的群)也返回 204。 被平台封禁的群返回 permission_denied。只读状态下允许。

接口:DELETE /groups/{group_id}(groups.delete)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*GroupsService) Disable

func (s *GroupsService) Disable(ctx context.Context, groupID, reason string) (*GroupChange, error)

Disable 封禁群

成员保留,不能发言、加人,客户端不能修改资料,待处理的请求暂停。已被本应用封禁的群再次封禁只更新原因,changed 为假 (客户端看不到原因);已被平台封禁的群不做任何改变,返回当前的群。只读状态下允许。

接口:POST /groups/{group_id}/disable(groups.disable)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*GroupsService) Enable

func (s *GroupsService) Enable(ctx context.Context, groupID string) (*GroupChange, error)

Enable 解封群

平台封禁的群返回 permission_denied;没有封禁的群 changed 为假。解封后尚未过期的待处理请求恢复有效。只读状态下允许。

接口:POST /groups/{group_id}/enable(groups.enable)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*GroupsService) Get

func (s *GroupsService) Get(ctx context.Context, groupID string) (*Group, error)

Get 查询群

任何状态的群(含已解散的)都返回全部字段;群 ID 格式不对时返回 not_found。

接口:GET /groups/{group_id}(groups.get)。查询,网络错误、超时、5xx 时自动重试。

func (*GroupsService) InviteSettings

func (s *GroupsService) InviteSettings(ctx context.Context, username string) (*GroupInviteSettings, error)

InviteSettings 查询用户的入群邀请方式

接口:GET /users/{username}/group-settings(groups.invite_settings)。查询,网络错误、超时、5xx 时自动重试。

func (*GroupsService) List

func (s *GroupsService) List(ctx context.Context, params ListGroupsParams) (*Page[Group], error)

List 分页列出应用的群(按创建时间倒序)

不按 status 筛选时含已解散的群;owner 不存在时返回空列表。

接口:GET /groups(groups.list)。查询,网络错误、超时、5xx 时自动重试。

func (*GroupsService) Member

func (s *GroupsService) Member(ctx context.Context, groupID, username string) (*GroupMember, error)

Member 查询一位成员

不是成员返回 not_group_member,用户不存在返回 not_found。

接口:GET /groups/{group_id}/members/{username}(groups.member)。查询,网络错误、超时、5xx 时自动重试。

func (*GroupsService) Members

func (s *GroupsService) Members(ctx context.Context, groupID string, params ListMembersParams) (*VersionedPage[GroupMember], error)

Members 分页列出群成员(按用户 ID 升序)

已解散、成员清理尚未完成的群也返回。跳过已删除的用户,一页可能少于 limit 条,是否还有下一页只看 next_cursor。 第一页带 known_version 且与当前的 member_version 相同时,只返回 member_version 和 not_modified 为真。

接口:GET /groups/{group_id}/members(groups.members)。查询,网络错误、超时、5xx 时自动重试。

func (*GroupsService) MuteMember

func (s *GroupsService) MuteMember(ctx context.Context, groupID, username string, durationSeconds *int64) (*GroupMemberChange, error)

MuteMember 在群里禁言成员

不能禁言群主(permission_denied)。同样的禁言(已永久禁言时再永久禁言,或新的到期时间与现有的相差 60 秒内)changed 为假、 到期时间不变;否则从现在起按新的时长重新计算。被封禁的群、只读状态下也可以禁言。

接口:PUT /groups/{group_id}/members/{username}/mute(groups.mute_member)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*GroupsService) OfUser

func (s *GroupsService) OfUser(ctx context.Context, username string, params ListOptions) (*Page[UserGroup], error)

OfUser 分页列出用户加入的群(按群 ID 升序)

每项为群的全部字段,另有该用户在群里的信息 self;包括已解散、成员清理尚未完成的群。用户不存在返回 not_found。

接口:GET /users/{username}/groups(groups.of_user)。查询,网络错误、超时、5xx 时自动重试。

func (*GroupsService) RemoveFromBlacklist

func (s *GroupsService) RemoveFromBlacklist(ctx context.Context, groupID, username string) (*GroupBlacklistChange, error)

RemoveFromBlacklist 移出群黑名单

不在黑名单中时 changed 为假。被封禁的群、只读状态下也可以移出。

接口:DELETE /groups/{group_id}/blacklist/{username}(groups.remove_from_blacklist)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*GroupsService) RemoveMembers

func (s *GroupsService) RemoveMembers(ctx context.Context, groupID string, usernames []string) (*GroupMembersResult, error)

RemoveMembers 批量移出成员(每次最多 100 个)

用户名转为小写、去重后为 1 到 100 个,按去重后的项数计入 OpenAPI 额度。逐项为 removed、not_member(原本就不是成员,视为成功), 或失败:not_found(用户不存在)、permission_denied(群主不能移出)。被封禁的群、只读状态下也可以移出。

接口:POST /groups/{group_id}/members/batch-delete(groups.remove_members)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*GroupsService) Requests

func (s *GroupsService) Requests(ctx context.Context, groupID string, params ListGroupRequestsParams) (*Page[GroupRequest], error)

Requests 分页列出群的入群申请和邀请(按发起时间倒序)

status 按对外显示的状态筛选:待处理且已过期的为 expired,群被封禁或已解散时待处理的为 canceled。读取后再筛选、跳过已删除的用户, 一页可能少于 limit 条甚至为空,是否还有下一页只看 next_cursor。

接口:GET /groups/{group_id}/requests(groups.requests)。查询,网络错误、超时、5xx 时自动重试。

func (*GroupsService) SetInviteSettings

func (s *GroupsService) SetInviteSettings(ctx context.Context, username string, inviteMode Field[string]) (*GroupInviteSettings, error)

SetInviteSettings 设置用户的入群邀请方式

invite_mode 必须出现:null 改为跟随应用的默认值,allow_any 被邀请时直接入群,need_confirm 需要本人确认。 只影响客户端的邀请,服务端加人不看它。只读状态下允许。

接口:PUT /users/{username}/group-settings(groups.set_invite_settings)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*GroupsService) SetMuteAll

func (s *GroupsService) SetMuteAll(ctx context.Context, groupID string, on bool) (*GroupChange, error)

SetMuteAll 开启全员禁言(on 为真)或关闭全员禁言(on 为假)。

接口:PUT、DELETE /groups/{group_id}/mute-all。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*GroupsService) SetRole

func (s *GroupsService) SetRole(ctx context.Context, groupID, username, role string) (*GroupMemberChange, error)

SetRole 设置成员的角色(管理员或普通成员)

不能用它设置或改变群主(invalid_argument,改用 transfer_owner);管理员已满(20 个)返回 limit_exceeded(admin_limit)。 已是这个角色时 changed 为假。取消管理员时他生成的入群链接失效。被封禁的群、只读状态下也可以设置。

接口:PUT /groups/{group_id}/members/{username}/role(groups.set_role)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*GroupsService) TransferOwner

func (s *GroupsService) TransferOwner(ctx context.Context, groupID, username string) (*GroupChange, error)

TransferOwner 转让群主

新群主须是成员(否则 not_group_member);原群主变为普通成员,新群主的禁言解除,原群主生成的入群链接失效。 新群主已是群主时 changed 为假。被封禁的群也可以转让(客户端不能)。只读状态下允许。

接口:PUT /groups/{group_id}/owner(groups.transfer_owner)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*GroupsService) UnmuteMember

func (s *GroupsService) UnmuteMember(ctx context.Context, groupID, username string) (*GroupMemberChange, error)

UnmuteMember 解除成员在群里的禁言

没有被禁言(或禁言已到期)时 changed 为假。被封禁的群、只读状态下也可以解除。

接口:DELETE /groups/{group_id}/members/{username}/mute(groups.unmute_member)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*GroupsService) Update

func (s *GroupsService) Update(ctx context.Context, groupID string, params UpdateGroupParams) (*GroupChange, error)

Update 修改群资料和设置

只修改给出的字段;与原值相同的不算变化(changed 为假,不加 info_version);没有任何要改的字段时返回 invalid_argument。 文本字段为 null 与不传相同,清空传空字符串。给出 version 时只有与当前的 info_version 一致才修改,否则 version_conflict。 公开群改为私有群时 join_mode 清空、待处理的申请失效;私有群改为公开群时 join_mode 默认为 approval;对私有群(含同时改为私有群) 设置 join_mode 返回 invalid_argument。被封禁的群也可以修改(用于清除违规内容),已解散的群返回 not_found。 名称、简介、公告和头像经过内容安全检查(只检查真正修改的),可能被替换或返回 content_rejected。只读状态下返回 app_unavailable。

接口:PATCH /groups/{group_id}(groups.update)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*GroupsService) UpdateMember

func (s *GroupsService) UpdateMember(ctx context.Context, groupID, username string, params UpdateMemberParams) (*GroupMemberChange, error)

UpdateMember 修改成员的群昵称和成员属性

只修改给出的字段;与原值相同时 changed 为假;没有任何要改的字段时返回 invalid_argument。不是成员返回 not_group_member。 群昵称经过内容安全检查,可能被替换或返回 content_rejected。被封禁的群也可以修改;只读状态下返回 app_unavailable。

接口:PATCH /groups/{group_id}/members/{username}(groups.update_member)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

type Hooks

type Hooks struct {
	BeforeRequest func(ctx context.Context, req *http.Request)
	AfterResponse func(ctx context.Context, info RequestInfo)
}

Hooks 请求前后的钩子,在发出请求的协程中同步调用,不能阻塞太久;换取令牌的请求同样调用(接口名 app.token)。 BeforeRequest 看到的请求中 Authorization 和请求体照常存在,钩子不应记录它们。钩子 panic 时 SDK 不恢复。

type ImagePart added in v1.0.2

type ImagePart struct {
	URL    string // https 地址,建议先用媒体模块上传
	Width  int64
	Height int64
	Alt    string
}

ImagePart 是图片片段。

type IssueLoginTicketParams

type IssueLoginTicketParams struct {
	// 用户不存在时创建
	AutoCreate bool
}

IssueLoginTicketParams 签发登录凭证的参数(Users.IssueLoginTicket)。

type ItemContent

type ItemContent struct {
	ItemID string `json:"item_id"`
	// 内容快照,结构随对象的类型不同;已清空时为 null
	Content json.RawMessage        `json:"content"`
	Reports []ModerationItemReport `json:"reports"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ItemContent 审核记录的内容和举报

func (*ItemContent) UnmarshalJSON

func (v *ItemContent) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ItemError

type ItemError struct {
	Key     string         `json:"-"`       // 项的标识:用户名、消息 ID、记录 ID、属性的键等(服务端返回的,用户名为小写)
	Code    string         `json:"code"`    // 错误码,与 *Error 的相同
	Message string         `json:"message"` // 说明,只用于日志;有的接口没有
	Details map[string]any `json:"details"` // 可能为 nil
}

ItemError 是批量接口中一项的失败(《2.接口设计》第 6 节)。不是 *Error:请求本身成功了,只有这一项失败。

func (ItemError) Error

func (e ItemError) Error() string

Error 让 ItemError 也可以作为 error 使用。

func (ItemError) Reason

func (e ItemError) Reason() string

Reason 返回 details.reason,没有时为空。

type ListBlacklistParams

type ListBlacklistParams struct {
	// 已有的版本号;只在不带 cursor 时生效,与当前版本号相同时不返回列表
	KnownVersion *int64
	ListOptions
}

ListBlacklistParams 分页列出用户的黑名单(带版本号)的参数(Blacklist.List)。

type ListCallsParams

type ListCallsParams struct {
	// 参与过的成员
	Username string
	// 群通话所属的群
	GroupID string
	Type    string
	Status  string
	// 发起时间不早于它(按通话 ID 换算)
	StartTime time.Time
	// 发起时间早于它(按通话 ID 换算)
	EndTime time.Time
	ListOptions
}

ListCallsParams 分页列出应用的通话的参数(Calls.List)。

type ListChatroomsParams

type ListChatroomsParams struct {
	// 按状态筛选;不给为正常和封禁的,dismissed 为解散 30 天内的
	Status string
	// 按所有者的用户名筛选
	Owner string
	// 按名称前缀搜索,最长 128 个字符
	NamePrefix string
	ListOptions
}

ListChatroomsParams 分页列出聊天室的参数(Chatrooms.List)。

type ListFriendRequestsParams

type ListFriendRequestsParams struct {
	// received 为收到的,sent 为发出的(必填)
	Direction string
	// 按状态筛选
	Status string
	ListOptions
}

ListFriendRequestsParams 分页列出用户收到或发出的好友申请的参数(Friends.Requests)。

type ListFriendsParams

type ListFriendsParams struct {
	// 已有的版本号;只在不带 cursor 时生效,与当前版本号相同时不返回列表
	KnownVersion *int64
	ListOptions
}

ListFriendsParams 分页列出用户的好友(带版本号)的参数(Friends.List)。

type ListGroupRequestsParams

type ListGroupRequestsParams struct {
	// 按类型筛选
	Kind string
	// 按对外显示的状态筛选
	Status string
	ListOptions
}

ListGroupRequestsParams 分页列出群的入群申请和邀请(按发起时间倒序)的参数(Groups.Requests)。

type ListGroupsParams

type ListGroupsParams struct {
	// 按类型筛选
	Type string
	// 按状态筛选
	Status string
	// 按群主的用户名筛选
	Owner string
	// 按群名称前缀搜索
	NamePrefix string
	ListOptions
}

ListGroupsParams 分页列出应用的群(按创建时间倒序)的参数(Groups.List)。

type ListItemsParams

type ListItemsParams struct {
	// 可以给多个;不给为 pending、auto_violation
	Status []string
	// report 为举报用户、群、聊天室
	Scene      string
	TargetType string
	Category   string
	// 来源中有这一种
	Source string
	// 作者的用户名
	Author   string
	Priority *int64
	// 创建时间不早于它
	From time.Time
	// 创建时间早于它
	To time.Time
	// 为 true 时改为列出本应用转交平台的记录(平台队列中的)
	Escalated *bool
	// oldest 为旧的在前(处理积压)
	Order string
	ListOptions
}

ListItemsParams 分页列出租户队列的审核记录的参数(Moderation.Items)。

type ListMembersParams

type ListMembersParams struct {
	// 按角色筛选
	Role string
	// 为 true 时只列出此刻被禁言的成员
	Muted *bool
	// 本地的 member_version,只在第一页(不带 cursor)时生效
	KnownVersion *int64
	ListOptions
}

ListMembersParams 分页列出群成员(按用户 ID 升序)的参数(Groups.Members)。

type ListMutedParams

type ListMutedParams struct {
	Scope string
	ListOptions
}

ListMutedParams 分页列出应用中被全局禁言的用户的参数(Users.ListMuted)。

type ListOptions

type ListOptions struct {
	Cursor string
	Limit  int
}

ListOptions 游标分页的参数:Cursor 为上一页的 NextCursor(原样传回,不解析),Limit 为 0 时用服务端的默认值。 游标只在同样的筛选条件下有效,改变条件要从第一页开始。

type ListPushMutesParams

type ListPushMutesParams struct {
	// 本地的 settings_version,只在第一页有效
	KnownVersion *int64
	ListOptions
}

ListPushMutesParams 分页列出用户的会话免打扰的参数(Push.Mutes)。

type ListUsersParams

type ListUsersParams struct {
	// 按状态筛选
	Status string
	// 按用户名前缀搜索(给出时按用户名排序)
	UsernamePrefix string
	ListOptions
}

ListUsersParams 分页列出用户的参数(Users.List)。

type ListWordsParams

type ListWordsParams struct {
	// 按规范化后的前缀搜索
	Prefix string
	ListOptions
}

ListWordsParams 分页列出词库中的词条的参数(Moderation.Words)。

type LoginTicket

type LoginTicket struct {
	// 登录凭证(ult_ 开头)
	Ticket string `json:"ticket"`
	// 有效期(秒),300
	ExpiresIn int64 `json:"expires_in"`
	// 这次是否创建了用户
	UserCreated bool `json:"user_created"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

LoginTicket LoginTicket

func (LoginTicket) String

func (v LoginTicket) String() string

String 遮掩敏感的字段。

func (*LoginTicket) UnmarshalJSON

func (v *LoginTicket) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type MarkAllReadResult

type MarkAllReadResult struct {
	// 标记的会话数
	Count int64 `json:"count"`
	// 单聊和已离开的群超过 1000 个、更早的没有处理
	Truncated bool `json:"truncated"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

MarkAllReadResult 全部标记已读的结果

func (*MarkAllReadResult) UnmarshalJSON

func (v *MarkAllReadResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type MediaPurposeUsage

type MediaPurposeUsage struct {
	UsedBytes int64 `json:"used_bytes"`
	FileCount int64 `json:"file_count"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

MediaPurposeUsage 一种用途的用量

func (*MediaPurposeUsage) UnmarshalJSON

func (v *MediaPurposeUsage) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type MediaService

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

MediaService 文件的上传与下载、文件信息、群文件、存储用量(client.Media)。

func (*MediaService) AllGroupFiles

func (s *MediaService) AllGroupFiles(ctx context.Context, groupID string, params ListOptions) iter.Seq2[File, error]

AllGroupFiles 逐项遍历 GroupFiles 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。

func (*MediaService) CancelUpload

func (s *MediaService) CancelUpload(ctx context.Context, fileID string) error

CancelUpload 取消上传

已取消、已过期的也返回 204;已完成的返回 version_conflict(upload_completed),删除已完成的文件用 delete_file。 只能操作本应用通过 OpenAPI 创建的上传,其他返回 not_found。

接口:DELETE /media/uploads/{file_id}(media.cancel_upload)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*MediaService) CompleteUpload

func (s *MediaService) CompleteUpload(ctx context.Context, fileID string) (*File, error)

CompleteUpload 完成上传

服务端核对内容、识别格式、处理图片,最长 2 分钟(超时返回 internal,文件仍在上传中);已完成的再次完成返回同一个文件,所以可以重试。 version_conflict:upload_completing(另一个完成请求正在处理,稍后重试)、upload_changed(核对期间内容又被重新上传,重新完成即可)。 以下几种文件仍在上传中,可以补传后再完成:invalid_argument 的 upload_incomplete(内容没传完、分片不全或大小不对)、 size_mismatch(上传的大小与声明的不同),rate_limited 的 image_busy(图片处理繁忙,只有这个请求等待)。 以下几种使这次上传失败并删除,之后再完成返回 invalid_argument(upload_failed),需要重新创建上传:invalid_argument 的 unsupported_type(格式不符合类型,带 details.content_type)、image_too_large(超过 5000 万像素)、invalid_image(图片无法解码); limit_exceeded(group_file_limit,群文件已满);not_found(所属用户已删除、群已解散)。 已被屏蔽的返回 file_blocked;已取消、已过期或不是本应用通过 OpenAPI 创建的返回 not_found。

接口:POST /media/uploads/{file_id}/complete(media.complete_upload)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*MediaService) CreateUpload

func (s *MediaService) CreateUpload(ctx context.Context, params CreateUploadParams) (*UploadSession, error)

CreateUpload 创建上传

每次创建一个新的上传,不自动重试;超时后不必确认,直接再创建一次:没有完成的上传到期作废(一次上传 1 小时、分片上传 24 小时),不计入用量。 不超过 32 MB 的为一次上传(upload 给出地址、方法和请求头),更大的为分片上传(每片 16 MB,用 part_urls 索取各片的地址)。 上传内容的请求发到对象存储,带上返回的 headers,不带 Authorization。 超过这种用途的大小上限返回 payload_too_large(details.max_bytes);用途与类型不匹配为 invalid_argument(invalid_purpose), 文件名不合规为 invalid_name;存储额度已满为 limit_exceeded(storage_quota),群文件已满 1000 个为 limit_exceeded(group_file_limit); owner 不存在、群不存在或已解散为 not_found。群文件不检查成员身份、群的封禁和应用的 group_file_enabled。只读状态下返回 app_unavailable。

接口:POST /media/uploads(media.create_upload)。不幂等:请求发出后不自动重试(被限流的照常等待后重发),超时后先查询结果再决定是否重试。

func (*MediaService) DeleteFile

func (s *MediaService) DeleteFile(ctx context.Context, fileID string) error

DeleteFile 删除文件

可以删除附件、头像、聊天室封面和群文件。已删除的也返回 204;还在上传中的返回 not_found(应取消上传);被屏蔽的返回 file_blocked。 删除后客户端换取下载地址得到 file_expired;删除正在使用的头像后资料中的地址随之失效。

接口:DELETE /media/files/{file_id}(media.delete_file)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*MediaService) Download

func (s *MediaService) Download(ctx context.Context, url string, w io.Writer) (int64, error)

Download 换取下载地址后直接请求(不带 Authorization),把内容写入 w,返回写入的字节数。 不经过 OpenAPI 的重试和限流(只有换取下载地址那一步经过);下载地址过期(对象存储返回 403)时重新换取一次。 缩略图的地址(文件地址加 /thumb)同样可以下载。

func (*MediaService) DownloadURLs

func (s *MediaService) DownloadURLs(ctx context.Context, urls []string) ([]DownloadURLItem, error)

DownloadURLs 换取下载地址(每次最多 100 个)

按输入的顺序逐项给出下载地址或错误,同一个地址可以出现多次,只计一次额度。单项的错误:not_found(不是本服务的文件地址、 不属于本应用、密钥不对、还在上传中、头像的公开地址、非图片的缩略图地址)、file_expired(已过期或已删除)、file_blocked(已被屏蔽)。 下载地址 60 到 90 分钟有效,同一个文件在同一个 30 分钟内得到相同的地址;不要保存或写进消息。不检查群成员身份。

接口:POST /media/download-urls(media.download_urls)。查询,网络错误、超时、5xx 时自动重试。

func (*MediaService) File

func (s *MediaService) File(ctx context.Context, fileID string) (*File, error)

File 查询文件

任何状态都能查到(含上传中的和已删除但记录还在的);不属于本应用的返回 not_found。

接口:GET /media/files/{file_id}(media.file)。查询,网络错误、超时、5xx 时自动重试。

func (*MediaService) GroupFiles

func (s *MediaService) GroupFiles(ctx context.Context, groupID string, params ListOptions) (*GroupFilesPage, error)

GroupFiles 分页列出群文件

按上传时间倒序,只列出可用的(active)文件;页中另有群文件的总数和字节数。群不存在返回 not_found,已解散的群返回还没清理完的文件; 不检查成员身份。

接口:GET /media/groups/{group_id}/files(media.group_files)。查询,网络错误、超时、5xx 时自动重试。

func (*MediaService) PartURLs

func (s *MediaService) PartURLs(ctx context.Context, fileID string, partNumbers []int) ([]PartURL, error)

PartURLs 索取分片的上传地址(每次 1 到 100 个分片)

每次调用都签发新的地址,地址 1 小时内有效、不晚于上传的有效期;同一个分片可以重新上传覆盖。 一次上传返回 invalid_argument;分片号超出 1 到 part_count 或重复为 invalid_argument。上传已完成返回 version_conflict(upload_completed), 已取消、已过期或不是本应用通过 OpenAPI 创建的返回 not_found。

接口:POST /media/uploads/{file_id}/parts(media.part_urls)。查询,网络错误、超时、5xx 时自动重试。

func (*MediaService) ResumeUpload

func (s *MediaService) ResumeUpload(ctx context.Context, fileID string, r io.ReaderAt, size int64, params UploadParams) (*File, error)

ResumeUpload 分片上传中断后续传(同一份内容,分片上传 24 小时内):查询已上传的分片,补传缺少的和大小不对的,再完成。 ctx 被取消时只停止,不取消上传(之后还可以再续传)。

func (*MediaService) Upload

func (s *MediaService) Upload(ctx context.Context, r io.ReaderAt, size int64, params UploadParams) (*File, error)

Upload 上传文件:创建上传、上传内容(不超过 32 MB 一次上传,更大的分片并发上传)、完成上传,返回文件信息。

r 用于分片的并发读取和重传(*os.File、*bytes.Reader、*strings.Reader 都实现了 io.ReaderAt;只有 io.Reader 的先写入临时文件)。 上传内容的请求发到对象存储:带上返回的请求头(Content-Length),不带 Authorization。完成上传的各种结果按第 10 节的表处理。 ctx 被取消或到期时停止上传,并尽力取消这次上传(独立的 5 秒时限,失败不报错)。 File.URL 是文件地址,写入消息的 Body 或资料的 AvatarURL;不要保存下载地址。

func (*MediaService) UploadedParts

func (s *MediaService) UploadedParts(ctx context.Context, fileID string) ([]UploadedPart, error)

UploadedParts 查询已上传的分片(不分页)

用于断点续传,按分片号升序一次返回全部(最多 128 片)。一次上传返回 invalid_argument;上传已完成返回 version_conflict(upload_completed), 已取消、已过期或不是本应用通过 OpenAPI 创建的返回 not_found。

接口:GET /media/uploads/{file_id}/parts(media.uploaded_parts)。查询,网络错误、超时、5xx 时自动重试。

func (*MediaService) Usage

func (s *MediaService) Usage(ctx context.Context) (*MediaUsage, error)

Usage 查询应用的存储用量

从数据库读取,不缓存。

接口:GET /media/usage(media.usage)。查询,网络错误、超时、5xx 时自动重试。

type MediaUsage

type MediaUsage struct {
	UsedBytes int64 `json:"used_bytes"`
	FileCount int64 `json:"file_count"`
	// 存储额度,0 表示不限
	LimitBytes int64 `json:"limit_bytes"`
	// 按用途的用量,列出全部应用级用途(attachment、user_avatar、group_avatar、chatroom_avatar、group_file),没有文件的为 0
	ByPurpose map[string]MediaPurposeUsage `json:"by_purpose"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

MediaUsage 应用的存储用量

func (*MediaUsage) UnmarshalJSON

func (v *MediaUsage) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type Mentions

type Mentions struct {
	// 被 @ 的用户名,最多 20 个
	Usernames []string
	// 是否 @ 全体成员
	All bool
}

Mentions 只用于群聊;不是群成员的用户名被忽略

type Message

type Message struct {
	// 会话 ID;群会话的即群 ID
	ConversationID   string `json:"conversation_id"`
	ConversationType string `json:"conversation_type"`
	// 在会话中的序号,从 1 开始连续递增
	Seq int64 `json:"seq"`
	// 全局唯一的消息 ID
	MessageID string `json:"message_id"`
	// 去重 ID;群提示以 evt_ 开头,其他模块写入的以 sys_ 开头
	ClientMsgID string `json:"client_msg_id"`
	// 发送者的用户名;系统发送或发送者已删除时为 null
	Sender *string `json:"sender"`
	// system 为群提示和以系统身份发送的群消息
	SenderType string `json:"sender_type"`
	// 单聊的接收者(已删除为 null);群聊为 null
	Recipient *string `json:"recipient"`
	// tip(群提示)、call(通话记录)只由系统写入
	Type string `json:"type"`
	// 消息内容;已撤回、已擦除的为 null;群提示中的用户以用户名表示
	Body json.RawMessage `json:"body"`
	// 自定义扩展;没有和已撤回、已擦除的为 null
	Ext json.RawMessage `json:"ext"`
	// @ 的成员;没有 @ 和已撤回、已擦除的为 null
	Mentions *MessageMentions `json:"mentions"`
	// 引用的消息;没有引用和已撤回、已擦除的为 null
	ReplyTo *MessageReply `json:"reply_to"`
	// 是否要求已读回执(群聊)
	NeedReceipt bool `json:"need_receipt"`
	// 是否不计入未读
	ExcludeFromUnread bool `json:"exclude_from_unread"`
	// 每种表情一项;没有回应和已撤回、已擦除的为 null
	Reactions []MessageReaction `json:"reactions"`
	// 置顶信息;没有置顶为 null
	Pinned *MessagePinInfo `json:"pinned"`
	// 编辑信息;没有编辑过为 null
	Edited *MessageEditInfo `json:"edited"`
	// 撤回信息;没有撤回为 null
	Recalled *MessageRecallInfo `json:"recalled"`
	// 是否已被擦除(不含内容)
	Erased bool `json:"erased"`
	// 写入的入口;涉及资金、订单的业务卡片只应信任不是 client 的
	Via       string    `json:"via"`
	CreatedAt time.Time `json:"created_at"`
	// 这条消息最近一次变更时会话的 message_version,没有变更过为 0
	MessageVersion int64 `json:"message_version"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

Message 消息(服务端的视角)

func (*Message) UnmarshalJSON

func (v *Message) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type MessageChange

type MessageChange struct {
	Message Message `json:"message"`
	// 为 false 表示这次没有改变任何状态
	Changed bool `json:"changed"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

MessageChange 撤回、编辑、置顶消息的结果

func (*MessageChange) UnmarshalJSON

func (v *MessageChange) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type MessageEditInfo

type MessageEditInfo struct {
	// 最近一次编辑的时间
	At time.Time `json:"at"`
	// 编辑的次数,最多 100
	Count int64 `json:"count"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

MessageEditInfo 消息的编辑信息

func (*MessageEditInfo) UnmarshalJSON

func (v *MessageEditInfo) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type MessageMentions

type MessageMentions struct {
	// 被 @ 的用户名,不含已删除的用户
	Usernames []string `json:"usernames"`
	// 是否 @ 全体成员
	All bool `json:"all"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

MessageMentions 消息中的 @

func (*MessageMentions) UnmarshalJSON

func (v *MessageMentions) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type MessagePinInfo

type MessagePinInfo struct {
	// 置顶的用户;服务端和控制台置顶的为 null
	By *string   `json:"by"`
	At time.Time `json:"at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

MessagePinInfo 消息的置顶信息

func (*MessagePinInfo) UnmarshalJSON

func (v *MessagePinInfo) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type MessagePushOptions

type MessagePushOptions struct {
	// 不发离线推送
	Disabled bool
	// 不受接收者免打扰的限制;不能与 disabled 同时为真,对不计入未读的消息无效
	Force bool
	// 通知的标题,1 到 64 个字符,不能有控制字符;不给时按模板生成
	Title string
	// 通知的正文,1 到 256 个字符,不能有控制字符;不给时按模板生成
	Body string
	// 随通知交给 App 的 JSON 对象,紧凑编码后最多 512 字节
	Ext json.RawMessage
}

MessagePushOptions 消息的离线推送选项(《推送/3.接口设计》第 10.1 节),整个对象按紧凑 JSON 不超过 2 KB;不符合的为 invalid_argument (invalid_push,details.field 指出字段)。

type MessageReaction

type MessageReaction struct {
	Key string `json:"key"`
	// 回应的人数,含已删除的用户
	Count int64 `json:"count"`
	// 按用户 ID 从小到大的前 3 个回应的人,已删除的为 null
	Users []*string `json:"users"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

MessageReaction 消息上一种表情回应的汇总

func (*MessageReaction) UnmarshalJSON

func (v *MessageReaction) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type MessageRecallInfo

type MessageRecallInfo struct {
	// 撤回的用户;服务端和平台撤回的为 null
	By *string `json:"by"`
	// 撤回者的身份
	Role string    `json:"role"`
	At   time.Time `json:"at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

MessageRecallInfo 消息的撤回信息

func (*MessageRecallInfo) UnmarshalJSON

func (v *MessageRecallInfo) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type MessageReply

type MessageReply struct {
	// 原消息的序号
	Seq int64 `json:"seq"`
	// 原消息的发送者;已删除或系统发送时为 null
	Sender *string `json:"sender"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

MessageReply 消息引用的原消息

func (*MessageReply) UnmarshalJSON

func (v *MessageReply) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type MessagesService

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

MessagesService 消息的发送、查询与导出、撤回、编辑、置顶(client.Messages)。

func (*MessagesService) AllSentBy

func (s *MessagesService) AllSentBy(ctx context.Context, username string, params SentByParams) iter.Seq2[Message, error]

AllSentBy 逐项遍历 SentBy 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。

func (*MessagesService) BatchRecall

func (s *MessagesService) BatchRecall(ctx context.Context, messageIDs []string, reason string) (*BatchRecallResult, error)

BatchRecall 批量撤回消息(每次最多 100 条)

逐条撤回,规则同 recall,每条一个事务,某条失败(如 not_found)不影响其他条;结果按请求的顺序,重复的 ID 各有一项(后面的 changed 为 false)。 按条数计入 OpenAPI 额度,额度不足时整个请求返回 rate_limited、任何一条都没有执行。

接口:POST /messages/batch-recall(messages.batch_recall)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*MessagesService) BatchSend

func (s *MessagesService) BatchSend(ctx context.Context, params BatchSendParams) (*BatchSendResult, error)

BatchSend 批量发送单聊消息(每次最多应用的 max_recipients_per_message 个接收人)

以同一个发送者、同样的内容给每个接收人各发一条单聊消息,服务端的发送规则同 send。不能带 mentions、need_receipt、online_only (为未知字段,invalid_argument)和 reply_to(invalid_reply)。 client_msg_id 必填,在每个接收人的会话中各用一次:已经写入过的接收人结果为 duplicate(不计入应用的消息数),用同一个 client_msg_id 重试是安全的。 逐个处理,整体返回 200,结果按 to_users 的顺序(重复的用户名各有一项,用户名与请求中的写法相同)。失败的项:not_found(用户不存在)、 invalid_argument(self_conversation)、app_unavailable(只读状态)、rate_limited(app_message_rate:应用每分钟的消息数不够时超出的人失败, details 带 retry_after_seconds,可能只发出了一部分)、message_rejected(发送前检查只调用一次,拒绝时全部失败,替换时全部写入替换后的内容)。 按接收人数计入 OpenAPI 额度,额度不足时整个请求返回 rate_limited、任何一项都没有执行;from 不存在、被平台封禁和参数错误同样整个请求失败。

接口:POST /messages/batch(messages.batch_send)。带幂等键的写操作,用同一个键自动重试。

func (*MessagesService) BatchSendAll

func (s *MessagesService) BatchSendAll(ctx context.Context, params BatchSendParams) (*BatchSendResult, error)

BatchSendAll 按上限(1000 项)拆分、依次提交、合并结果;服务端以 too_many_items 给出更小的上限(应用的设置)时按它重新拆分。 某一批整体失败时停止,返回已完成部分的合并结果和那一批的错误;没有出现在结果中的项可以再提交一次。 各批用同一个 ClientMsgID(服务端按接收人去重),重试和重新提交都不会重复发送。

func (*MessagesService) Edit

func (s *MessagesService) Edit(ctx context.Context, messageID string, params EditMessageParams) (*MessageChange, error)

Edit 编辑消息

body、ext 至少给一个(都不给为 invalid_argument,empty_edit)。只能编辑 text、custom(其他类型为 permission_denied,not_editable), 已撤回、已擦除的为 permission_denied(message_recalled),已编辑 100 次为 limit_exceeded(edit_limit)。 新内容照常校验类型和大小,并经过内容安全和发消息前回调(可能被拒绝或替换);@、引用、已读回执不能改。 内容与现在相同时不修改、changed 为 false(重试的结果相同)。只读状态下返回 app_unavailable。

接口:PATCH /messages/{message_id}(messages.edit)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*MessagesService) Export

func (s *MessagesService) Export(ctx context.Context, params ExportParams) (*ExportPage, error)

Export 按消息 ID 从旧到新导出应用的消息

服务端的视角:含已撤回、已擦除的消息(不含内容),超过保留期的跳过。只导出消息 ID 中的时间早于当前 30 秒的消息, 一页合计超过 1 MB 时提前结束。本页(跳过之前)的条数等于 limit 时 has_more 就为 true,下一页可能为空;是否结束只看 has_more。 要求逐条不漏的实时归档用回调模块的消息抄送。

接口:GET /messages(messages.export)。查询,网络错误、超时、5xx 时自动重试。

func (*MessagesService) ExportAll

func (s *MessagesService) ExportAll(ctx context.Context, params ExportParams) iter.Seq2[Message, error]

ExportAll 逐条遍历消息导出(按消息 ID 从旧到新),自动翻页:按 has_more 判断结束(最后一页可能为空)。 从 params.AfterMessageID 之后开始;出错时产出这个错误后结束,调用方可以记下最后一条的消息 ID,之后从那里继续。

func (*MessagesService) Get

func (s *MessagesService) Get(ctx context.Context, messageID string) (*Message, error)

Get 按 ID 读取消息

服务端的视角,任何会话的消息都可以读取;已撤回、已擦除的不含内容。不存在或超过保留期为 not_found。

接口:GET /messages/{message_id}(messages.get)。查询,网络错误、超时、5xx 时自动重试。

func (*MessagesService) Pin

func (s *MessagesService) Pin(ctx context.Context, messageID, reason string) (*MessageChange, error)

Pin 置顶消息

不检查角色,pinned 的 by 为 null。已置顶的返回 200、changed 为 false。已撤回、已擦除的为 permission_denied(message_recalled), 会话中置顶的消息已达应用的 max_pinned_messages_per_conversation(默认 20)为 limit_exceeded(pinned_message_limit)。 只读状态下返回 app_unavailable。不存在或超过保留期为 not_found。

接口:PUT /messages/{message_id}/pin(messages.pin)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*MessagesService) Recall

func (s *MessagesService) Recall(ctx context.Context, messageID, reason string) (*MessageChange, error)

Recall 撤回消息

不受撤回时间限制,recalled 的 role 为 server、by 为 null;撤回后 body、ext、mentions、reply_to、reactions、pinned 都为 null。 已撤回的返回 200、changed 为 false(重试的结果相同)。只读状态下照常可用。不存在或超过保留期为 not_found。

接口:POST /messages/{message_id}/recall(messages.recall)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*MessagesService) Send

Send 发送一条消息(单聊或群聊)

to_user、to_group 恰好给一个(否则为 invalid_argument,invalid_recipient)。单聊必须给 from(否则为 from_required);群聊不给 from 时以系统身份发送。 服务端发送不检查用户的禁言和租户封禁、好友关系、双方的黑名单、群的禁言和全员禁言,不按用户限流,@ 全体成员不要求群主或管理员, 附件地址只检查格式(不检查是否为本服务的文件,body 中的 url 应是上传得到的文件地址,不是下载地址)。照常检查:平台封禁 (发送者为 user_disabled、群为 group_disabled,details.disabled_by 为 platform;租户封禁的可以)、from 的群成员身份(not_group_member)、 按群和按应用的频率限制(rate_limited,details.reason 为 group_send_rate、app_message_rate)、只读状态(app_unavailable)、 内容安全和发消息前回调(拒绝为 message_rejected,也可能替换内容;租户规则只在场景开启了“含服务端发送”时检查)。 服务端发送不算发送者已读(发送者原本没有未读时除外),不改变对方看到的已读位置。 按“会话、发送者、client_msg_id”去重,没有时间窗口:重复提交返回 200 和第一次写入的消息(即使这次内容不同), 去重排在只读状态、频率限制和发送前检查之前;单聊中第一次发送后接收者被删除的,重试得到 not_found。没有给 client_msg_id 时 SDK 生成。 online_only 为真时只推给在线的设备:不保存、不分配序号、不去重、不发事件,返回 200 和精简结果(online_only 为真,不是重复提交); 重发会让在线的设备收到两次,所以不自动重试,超时后无法确认是否已推送。 其他错误:发送者、接收者不存在为 not_found,群不存在或已解散为 not_found;invalid_argument 的 details.reason 为 self_conversation、 unknown_type、invalid_body(details.field)、invalid_client_msg_id、reserved_client_msg_id、mentions_not_allowed、invalid_reply、 receipt_not_allowed、invalid_online_only、invalid_push(details.field);need_receipt 而应用没有开启群已读回执为 permission_denied (read_ack_disabled);内容超过应用的 max_message_body_bytes 为 payload_too_large(details.max_bytes)。

接口:POST /messages(messages.send)。带幂等键的写操作,用同一个键自动重试。OnlineOnly 为真(只推在线的消息)时不去重,按不幂等处理,不自动重试。

func (*MessagesService) SentBy

func (s *MessagesService) SentBy(ctx context.Context, username string, params SentByParams) (*Page[Message], error)

SentBy 分页列出用户发过的消息

按消息 ID 从新到旧,用于处理投诉和刷屏;含已撤回的消息(不含内容),超过保留期的跳过。一页可能少于 limit 条甚至为空而仍有下一页, 是否结束只看 next_cursor。用户不存在为 not_found。

接口:GET /users/{username}/sent-messages(messages.sent_by)。查询,网络错误、超时、5xx 时自动重试。

func (*MessagesService) Unpin

func (s *MessagesService) Unpin(ctx context.Context, messageID, reason string) (*MessageChange, error)

Unpin 取消置顶消息

没有置顶的返回 200、changed 为 false。只读状态下照常可用。不存在或超过保留期为 not_found。

接口:DELETE /messages/{message_id}/pin(messages.unpin)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

type ModerationActionInput

type ModerationActionInput struct {
	// 必填
	Kind string
	// mute_user 必填
	Scopes []string
	// mute_user、disable_user 的时长,不给为永久
	DurationSeconds *int64
	// clear_profile 清除的字段,不给为快照中的全部
	Fields []string
	// block_file 的文件,不给为消息中全部本应用的文件
	FileIDs []string
}

ModerationActionInput 结论中选择的一个处置

type ModerationCategoryAction

type ModerationCategoryAction struct {
	// 建议拒绝时
	Block string `json:"block"`
	// 建议人工复审时
	Review string `json:"review"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ModerationCategoryAction 一个类别的第三方审核结果的处理

func (*ModerationCategoryAction) UnmarshalJSON

func (v *ModerationCategoryAction) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ModerationCategoryActionUpdate

type ModerationCategoryActionUpdate struct {
	// 第三方审核建议拒绝时的处理
	Block *string
	// 第三方审核建议人工复审时的处理
	Review *string
}

ModerationCategoryActionUpdate ModerationCategoryActionUpdate

type ModerationConfig

type ModerationConfig struct {
	// 全部场景的有效设置,键为场景
	Scenes             map[string]ModerationSceneSetting `json:"scenes"`
	CustomMessageCheck string                            `json:"custom_message_check"`
	// 租户的审核账号(只能在控制台选择)
	ProviderAccountID *string `json:"provider_account_id"`
	// 按类别的第三方审核结果的处理,没有设置的类别不出现(取默认值),全部为默认时不出现
	CategoryActions map[string]ModerationCategoryAction `json:"category_actions"`
	// 同步调用第三方审核的超时(毫秒),默认 800
	SyncTimeoutMs int64 `json:"sync_timeout_ms"`
	// 同步审核超时的处理,默认 pass
	OnTimeout string `json:"on_timeout"`
	// 自动处罚规则,null 为不自动处罚
	PenaltyRules []PenaltyRule            `json:"penalty_rules"`
	Platform     ModerationConfigPlatform `json:"platform"`
	Version      int64                    `json:"version"`
	// 还没有配置过时为 null
	UpdatedAt *time.Time `json:"updated_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ModerationConfig 应用的内容安全配置

func (*ModerationConfig) UnmarshalJSON

func (v *ModerationConfig) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ModerationConfigPlatform

type ModerationConfigPlatform struct {
	// 平台规则是否对本应用生效
	RulesEnabled bool `json:"rules_enabled"`
	// 平台为本应用做第三方审核的场景,没有的场景不出现
	Scenes map[string]ModerationProviderSetting `json:"scenes"`
	// 平台账号每天为本应用审核的次数上限,0 为不限
	DailyQuota int64 `json:"daily_quota"`
	// 平台强制处理的类别
	EnforcedCategories []string `json:"enforced_categories"`
	// scenes 取平台的默认值
	InheritedScenes bool `json:"inherited_scenes"`
	// daily_quota 取平台的默认值
	InheritedDailyQuota bool `json:"inherited_daily_quota"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ModerationConfigPlatform 平台对本应用的设置(只读)

func (*ModerationConfigPlatform) UnmarshalJSON

func (v *ModerationConfigPlatform) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ModerationEvidence

type ModerationEvidence struct {
	MessageID      string          `json:"message_id"`
	ConversationID string          `json:"conversation_id"`
	Sender         *string         `json:"sender"`
	Type           string          `json:"type"`
	Body           json.RawMessage `json:"body"`
	CreatedAt      time.Time       `json:"created_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ModerationEvidence 举报时保存的一条证据消息

func (*ModerationEvidence) UnmarshalJSON

func (v *ModerationEvidence) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ModerationItem

type ModerationItem struct {
	ItemID string `json:"item_id"`
	// platform 为已转交平台
	Queue  string `json:"queue"`
	Status string `json:"status"`
	// 场景,举报用户、群、聊天室为 report
	Scene      string `json:"scene"`
	TargetType string `json:"target_type"`
	// 消息、群、聊天室、属性、文件的 ID;对象含用户的(user、user_profile、group_member、group_request、friend_request)为 null
	TargetID *string `json:"target_id"`
	// 对象含用户时为这个用户
	TargetUsername *string `json:"target_username"`
	// group_member、group_request 的群
	TargetGroupID  *string `json:"target_group_id"`
	ConversationID *string `json:"conversation_id"`
	// 作者的用户名;没有作者或已删除时为 null
	Author     *string                `json:"author"`
	Sources    []ModerationItemSource `json:"sources"`
	Categories []string               `json:"categories"`
	// 第三方审核的建议
	Suggestion *string `json:"suggestion"`
	// 已自动执行的处置
	AutoActions []string `json:"auto_actions"`
	ReportCount int64    `json:"report_count"`
	// 0 最高,2 最低
	Priority int64 `json:"priority"`
	// 结论,没有时为 null
	Decision    *ModerationItemDecision `json:"decision"`
	EscalatedAt *time.Time              `json:"escalated_at"`
	// 内容快照是否还在
	ContentAvailable bool       `json:"content_available"`
	Version          int64      `json:"version"`
	CreatedAt        time.Time  `json:"created_at"`
	ClosedAt         *time.Time `json:"closed_at"`
	CloseReason      *string    `json:"close_reason"`
	// 这条记录引起的处置;只在单个记录的响应中,没有时不出现
	Actions []ModerationItemAction `json:"actions"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ModerationItem 审核记录(不含内容)

func (*ModerationItem) UnmarshalJSON

func (v *ModerationItem) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ModerationItemAction

type ModerationItemAction struct {
	ActionID  string     `json:"action_id"`
	Kind      string     `json:"kind"`
	Authority string     `json:"authority"`
	Trigger   string     `json:"trigger"`
	Status    string     `json:"status"`
	LastError *string    `json:"last_error"`
	CreatedAt time.Time  `json:"created_at"`
	DoneAt    *time.Time `json:"done_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ModerationItemAction 审核记录引起的一个处置

func (*ModerationItemAction) UnmarshalJSON

func (v *ModerationItemAction) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ModerationItemDecision

type ModerationItemDecision struct {
	Result string `json:"result"`
	ByType string `json:"by_type"`
	// 作出结论的人;平台作出的为 null
	By        *string   `json:"by"`
	Note      string    `json:"note"`
	DecidedAt time.Time `json:"decided_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ModerationItemDecision 审核记录的结论

func (*ModerationItemDecision) UnmarshalJSON

func (v *ModerationItemDecision) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ModerationItemReport

type ModerationItemReport struct {
	ReportID string `json:"report_id"`
	// 举报人的用户名,已删除时为 null
	Reporter    *string              `json:"reporter"`
	Reason      string               `json:"reason"`
	Description string               `json:"description"`
	Evidence    []ModerationEvidence `json:"evidence"`
	Via         string               `json:"via"`
	CreatedAt   time.Time            `json:"created_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ModerationItemReport 审核人员看到的一次举报

func (*ModerationItemReport) UnmarshalJSON

func (v *ModerationItemReport) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ModerationItemSource

type ModerationItemSource struct {
	Type     string            `json:"type"`
	ListID   string            `json:"list_id"`
	ListName string            `json:"list_name"`
	Word     string            `json:"word"`
	Platform bool              `json:"platform"`
	Category string            `json:"category"`
	Provider string            `json:"provider"`
	Labels   []ModerationLabel `json:"labels"`
	// 举报的次数
	Count int64 `json:"count"`
	// 举报的原因
	Reason string `json:"reason"`
	// 地址无法审核的原因、转交的说明
	Note string `json:"note"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ModerationItemSource 进入审核的一个原因;字段随 type 不同,租户看到的平台词库命中只有 platform 和 category

func (*ModerationItemSource) UnmarshalJSON

func (v *ModerationItemSource) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ModerationLabel

type ModerationLabel struct {
	Category string `json:"category"`
	// 服务商的原始标签
	Label string  `json:"label"`
	Score float64 `json:"score"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ModerationLabel 服务商的一个标签

func (*ModerationLabel) UnmarshalJSON

func (v *ModerationLabel) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ModerationProviderSetting

type ModerationProviderSetting struct {
	TextProvider  string `json:"text_provider"`
	MediaProvider string `json:"media_provider"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ModerationProviderSetting 平台在一个场景做第三方审核的方式

func (*ModerationProviderSetting) UnmarshalJSON

func (v *ModerationProviderSetting) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ModerationSceneSetting

type ModerationSceneSetting struct {
	// 是否启用租户规则
	Enabled bool `json:"enabled"`
	// 文本的第三方审核方式
	TextProvider string `json:"text_provider"`
	// 图片、语音、视频的第三方审核方式
	MediaProvider string `json:"media_provider"`
	// 是否检查服务端提交的内容
	IncludeServerSent bool `json:"include_server_sent"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ModerationSceneSetting 一个场景的设置

func (*ModerationSceneSetting) UnmarshalJSON

func (v *ModerationSceneSetting) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ModerationSceneUpdate

type ModerationSceneUpdate struct {
	// 是否启用租户规则
	Enabled *bool
	// async 只能用于 message、chatroom_message;media_upload 只能为 off
	TextProvider *string
	// sync 只能用于 user_profile、group_profile;async 只能用于 message、chatroom_message、media_upload
	MediaProvider *string
	// 是否检查服务端提交的内容;chatroom_attribute 不能开启
	IncludeServerSent *bool
}

ModerationSceneUpdate ModerationSceneUpdate

type ModerationService

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

ModerationService 内容安全:配置、词库、文本检查、审核记录与结论、举报、违规(client.Moderation)。

func (*ModerationService) AddWords

func (s *ModerationService) AddWords(ctx context.Context, listID string, words []string) (*AddWordsResult, error)

AddWords 添加词条(每次最多 1000 个)

规范化后与已有的或同一批中前面的相同的列入 duplicated(原样);不合法的列入 invalid。重试时已添加的列入 duplicated。 添加后超过单个词库 1 万条或应用合计 5 万条时整批不添加,返回 limit_exceeded(word_limit)。按项数计入 OpenAPI 额度。

接口:POST /moderation/word-lists/{list_id}/words/batch(moderation.add_words)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ModerationService) AllItems

AllItems 逐项遍历 Items 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。

func (*ModerationService) AllPlatformActions

func (s *ModerationService) AllPlatformActions(ctx context.Context, params ListOptions) iter.Seq2[PlatformAction, error]

AllPlatformActions 逐项遍历 PlatformActions 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。

func (*ModerationService) AllViolations

func (s *ModerationService) AllViolations(ctx context.Context, username string, params ListOptions) iter.Seq2[Violation, error]

AllViolations 逐项遍历 Violations 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。

func (*ModerationService) AllWords

func (s *ModerationService) AllWords(ctx context.Context, listID string, params ListWordsParams) iter.Seq2[Word, error]

AllWords 逐项遍历 Words 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。

func (*ModerationService) BatchDecide

BatchDecide 批量作出同样的结论(每次最多 100 条)

逐条处理,某条失败不影响其他的,整体返回 200;失败的项在 error 中。不能带 mute_user、disable_user、disable_group、disable_chatroom(整个请求返回 invalid_argument、invalid_action)。 已结束的记录(超时结束的除外)单项为 version_conflict(details.current 为记录),重试后 SDK 把结论与本次相同的这种单项按成功处理。按项数计入 OpenAPI 额度。

接口:POST /moderation/items/batch-decide(moderation.batch_decide)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ModerationService) CheckText

func (s *ModerationService) CheckText(ctx context.Context, params CheckTextParams) (*TextCheckResult, error)

CheckText 按当前规则检查文本(不记录)

text 和 fields 合计 1 到 10 项。只给 text 时服务端直接返回一个 TextCheck,否则为 {fields: {字段名: TextCheck}}(text 的键为 text); SDK 统一为 TextCheckResult(x-drim-postprocess: text_check)。 不写入审核记录和违规、不计入检查的统计;with_provider 为真且这个场景开启了第三方审核时同步调用服务商(计入用量和费用),调用失败时只有词库的结果。

接口:POST /moderation/text-check(moderation.check_text)。查询,网络错误、超时、5xx 时自动重试。

func (*ModerationService) ClearViolations

func (s *ModerationService) ClearViolations(ctx context.Context, username, reason string) (int, error)

ClearViolations 清除用户的租户规则违规,返回清除的条数

平台规则的违规保留;没有可清除的返回 0。用户不存在返回 not_found。

接口:DELETE /moderation/users/{username}/violations(moderation.clear_violations)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ModerationService) Config

Config 查询应用的内容安全配置

scenes 含全部场景的有效设置(没有设置过的为默认值);还没有配置过的应用返回默认值、version 为 1、updated_at 为 null。 platform 为平台对本应用的设置,只读。

接口:GET /moderation/config(moderation.config)。查询,网络错误、超时、5xx 时自动重试。

func (*ModerationService) CreateWordList

func (s *ModerationService) CreateWordList(ctx context.Context, params CreateWordListParams) (*WordList, error)

CreateWordList 创建词库

名称在应用内重复返回 invalid_argument(details.field 为 name);已有 20 个词库返回 limit_exceeded(word_list_limit); 屏蔽词库没有 action、放行词库带 action 返回 invalid_argument(unsupported_action)。 不幂等,不自动重试:超时后用 list_word_lists 按名称查找,没有再创建。

接口:POST /moderation/word-lists(moderation.create_word_list)。不幂等:请求发出后不自动重试(被限流的照常等待后重发),超时后先查询结果再决定是否重试。

func (*ModerationService) Decide

func (s *ModerationService) Decide(ctx context.Context, itemID string, params DecideParams) (*ModerationItem, error)

Decide 作出结论或改判

actions 只用于 violation,按对象允许的处置,否则返回 invalid_argument(invalid_action)。给出 version 时与当前不一致返回 version_conflict(details.current 为记录)。 记录已是这个结论、由同一凭据作出且没有带 actions 的,直接返回当前记录(不检查 version);带 actions 而没有 version 的重复请求会再执行一次处置, 所以不自动重试,超时后用 get_item 查看 decision 和 actions 再决定。 已转交平台、平台作出的结论、无违规改为违规、违规改判超过 30 天、因转交或对象删除而结束的,返回 permission_denied(not_revisable)。处置提交后异步执行,响应中为 pending。

接口:POST /moderation/items/{item_id}/decide(moderation.decide)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。带 Actions 而没有 Version 时按不幂等处理,不自动重试(服务端会重复执行处置)。

func (*ModerationService) DeleteWordList

func (s *ModerationService) DeleteWordList(ctx context.Context, listID string) error

DeleteWordList 删除词库和其中的全部词条

重复删除返回 not_found。

接口:DELETE /moderation/word-lists/{list_id}(moderation.delete_word_list)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ModerationService) Escalate

func (s *ModerationService) Escalate(ctx context.Context, itemID, note string) (*ModerationItem, error)

Escalate 把租户队列中未结束的记录转交平台

平台队列中已有同一对象未结束的记录时合并到那一条,原记录改为 expired(close_reason 为 escalated),返回平台那一条(item_id 与请求的不同)。 已转交或已结束的返回 permission_denied(not_revisable),所以不自动重试;超时后用 get_item 查看原记录:escalated_at 不为 null 或 close_reason 为 escalated 即已转交。

接口:POST /moderation/items/{item_id}/escalate(moderation.escalate)。不幂等:请求发出后不自动重试(被限流的照常等待后重发),超时后先查询结果再决定是否重试。

func (*ModerationService) Item

func (s *ModerationService) Item(ctx context.Context, itemID string) (*ModerationItem, error)

Item 查询审核记录(含它引起的处置)

不含内容。平台队列中没有转交的记录返回 not_found。

接口:GET /moderation/items/{item_id}(moderation.item)。查询,网络错误、超时、5xx 时自动重试。

func (*ModerationService) ItemContent

func (s *ModerationService) ItemContent(ctx context.Context, itemID string) (*ItemContent, error)

ItemContent 读取审核记录的内容和举报

content 的结构随对象的类型不同:消息为 type、body、ext、created_at、edits、review_urls;资料为 fields;文件为 file_id、kind、name、review_urls; 用户、群、聊天室为 profile、versions。快照已清空(记录结束 30 天后)时为 null。review_urls 的查看地址 10 分钟内有效,平台规则屏蔽的文件为 null。 OpenAPI 的读取不写操作日志、不按人限流。

接口:GET /moderation/items/{item_id}/content(moderation.item_content)。查询,网络错误、超时、5xx 时自动重试。

func (*ModerationService) Items

Items 分页列出租户队列的审核记录

不含内容和 actions。默认只列未结束的(pending、auto_violation),列未结束的状态时按优先级(0 最高)、再按 ID 从新到旧,只列已结束的状态时只按 ID。 按作者筛选时用户不存在得到空页。

接口:GET /moderation/items(moderation.items)。查询,网络错误、超时、5xx 时自动重试。

func (*ModerationService) PlatformActions

func (s *ModerationService) PlatformActions(ctx context.Context, params ListOptions) (*Page[PlatformAction], error)

PlatformActions 分页列出平台对本应用执行的处置

只读,按时间倒序;不含内容、记录 ID 和平台的操作人。

接口:GET /moderation/platform-actions(moderation.platform_actions)。查询,网络错误、超时、5xx 时自动重试。

func (*ModerationService) ProcessPending

func (s *ModerationService) ProcessPending(ctx context.Context, opts ProcessOptions,
	handle func(ctx context.Context, item ModerationItem, content ItemContent) (*Decision, error)) (int, error)

ProcessPending 遍历租户队列中待处理的审核记录(pending、auto_violation):读取内容,调用 handle,按返回的结论作出结论; handle 返回 nil 的结论为跳过。作出结论时带上读到的 Version,所以可以安全重试;记录已被别人处理(version_conflict)的跳过。 返回作出结论的条数;遍历本身出错(如取下一页失败)时返回已作出的条数和这个错误。

func (*ModerationService) RemoveWords

func (s *ModerationService) RemoveWords(ctx context.Context, listID string, words []string) (int, error)

RemoveWords 删除词条(每次最多 1000 个),返回删除的个数

原样或规范化后的都可以;不存在的忽略。按项数计入 OpenAPI 额度。

接口:POST /moderation/word-lists/{list_id}/words/batch-delete(moderation.remove_words)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ModerationService) Report

func (s *ModerationService) Report(ctx context.Context, params ReportParams) (*ReportResult, error)

Report 代用户举报

reporter 不存在返回 invalid_argument(details.field 为 reporter);对象不存在、举报人看不到或消息已撤回返回 not_found; 举报自己或自己的消息为 invalid_argument(self_report),证据消息不符为 invalid_evidence。 同一举报人对同一未结束(或 7 天内判定无违规)的对象只记一次,重复的返回原举报和 200(duplicate 为真),新举报为 201。 不受应用的 report_enabled 和按用户的限流约束;每个应用每分钟 600 次,超出返回 rate_limited。

接口:POST /moderation/reports(moderation.report)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ModerationService) Stats

Stats 查询应用的内容安全统计

from、to 为统计时区的日期,含两端,最多 90 天;格式不对或超出范围返回 invalid_argument(details.field 为 from 或 to)。 days 只含有数据的日期和场景;pending 为租户队列中未结束的记录(不含平台队列)。

接口:GET /moderation/stats(moderation.stats)。查询,网络错误、超时、5xx 时自动重试。

func (*ModerationService) UpdateConfig

UpdateConfig 修改应用的内容安全配置

只修改给出的字段,没有改变任何值时版本号不变。给出 version 时与当前不一致返回 version_conflict(details.current 为 {version, updated_at})。 场景不支持的检查方式返回 invalid_argument(unsupported_scene);开启第三方审核而控制台没有选择审核账号返回 invalid_argument(provider_account_required); penalty_rules 超过 5 条返回 limit_exceeded(penalty_rule_limit)。审核账号 provider_account_id 只能在控制台选择,platform 部分只读,读到的配置不能原样提交。

接口:PATCH /moderation/config(moderation.update_config)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ModerationService) UpdateWordList

func (s *ModerationService) UpdateWordList(ctx context.Context, listID string, params UpdateWordListParams) (*WordList, error)

UpdateWordList 修改词库的属性

只修改给出的字段;不能修改 kind。名称在应用内重复返回 invalid_argument(details.field 为 name)。

接口:PATCH /moderation/word-lists/{list_id}(moderation.update_word_list)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*ModerationService) Violations

func (s *ModerationService) Violations(ctx context.Context, username string, params ListOptions) (*ViolationsPage, error)

Violations 分页列出用户的违规记录

按时间倒序;页中另有违规次数 violation_count 和最近 10 条处罚 penalties。用户不存在返回 not_found。

接口:GET /moderation/users/{username}/violations(moderation.violations)。查询,网络错误、超时、5xx 时自动重试。

func (*ModerationService) WordList

func (s *ModerationService) WordList(ctx context.Context, listID string) (*WordList, error)

WordList 查询词库

接口:GET /moderation/word-lists/{list_id}(moderation.word_list)。查询,网络错误、超时、5xx 时自动重试。

func (*ModerationService) WordLists

func (s *ModerationService) WordLists(ctx context.Context) ([]WordList, error)

WordLists 列出应用的词库(不分页,最多 20 个)

接口:GET /moderation/word-lists(moderation.word_lists)。查询,网络错误、超时、5xx 时自动重试。

func (*ModerationService) Words

func (s *ModerationService) Words(ctx context.Context, listID string, params ListWordsParams) (*Page[Word], error)

Words 分页列出词库中的词条

按规范化后的词排序。

接口:GET /moderation/word-lists/{list_id}/words(moderation.words)。查询,网络错误、超时、5xx 时自动重试。

type ModerationStats

type ModerationStats struct {
	Days []ModerationStatsDay `json:"days"`
	// 租户队列中未结束的记录
	Pending ModerationStatsPending `json:"pending"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ModerationStats 应用的内容安全统计

func (*ModerationStats) UnmarshalJSON

func (v *ModerationStats) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ModerationStatsDay

type ModerationStatsDay struct {
	Date string `json:"date"`
	// 场景,举报为 report
	Scene string `json:"scene"`
	// checked、rejected、replaced、flagged、auto_actioned、provider_calls、platform_calls_text(_image、_audio、_video)、cache_hits、provider_errors、timeouts、quota_skipped、reports;没有的不出现
	Metrics map[string]int64 `json:"metrics"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ModerationStatsDay 一天一个场景的指标

func (*ModerationStatsDay) UnmarshalJSON

func (v *ModerationStatsDay) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ModerationStatsParams

type ModerationStatsParams struct {
	// 开始日期(含)(必填)
	From string
	// 结束日期(含)(必填)
	To    string
	Scene string
}

ModerationStatsParams 查询应用的内容安全统计的参数(Moderation.Stats)。

type ModerationStatsPending

type ModerationStatsPending struct {
	Count int64 `json:"count"`
	// 最早一条已等待的秒数,没有时为 null
	OldestWaitSeconds *int64 `json:"oldest_wait_seconds"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ModerationStatsPending 租户队列中未结束的记录

func (*ModerationStatsPending) UnmarshalJSON

func (v *ModerationStatsPending) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type MuteConversationParams

type MuteConversationParams struct {
	// none 不推送;mention_only 只在有人 @ 本人时推送(必填)
	Mode string
	// 时长(秒);不给为一直有效
	DurationSeconds *int64
}

MuteConversationParams 设置群免打扰的参数(Push.MuteGroup)。

type MuteParams

type MuteParams struct {
	// 不给为永久
	DurationSeconds *int64
	// 最长 256 个字符
	Reason string
}

MuteParams 全局禁言用户的参数(Users.Mute)。

type OpStats

type OpStats struct {
	Requests      int64         // 尝试的次数(含重试)
	Failures      int64         // 最终失败的调用数
	Retries       int64         // 重试的次数
	RateLimitWait time.Duration // 限流等待的总时长
}

OpStats 是一个接口的统计。

type Page

type Page[T any] struct {
	Items      []T
	NextCursor string          // 空表示没有下一页(null 和空字符串都转为空)
	Raw        json.RawMessage // 这一页的原始 JSON
}

Page 是游标分页的一页。一页的条数可能少于 Limit 甚至为 0 而仍有下一页,是否结束只看 NextCursor。

func (*Page[T]) UnmarshalJSON

func (p *Page[T]) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type PartURL

type PartURL struct {
	PartNumber int `json:"part_number"`
	// 对象存储的预签名地址
	URL string `json:"url"`
	// PUT
	Method string `json:"method"`
	// 上传时必须带上的请求头(这一片的 Content-Length)
	Headers   map[string]string `json:"headers"`
	ExpiresAt time.Time         `json:"expires_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

PartURL 一个分片的上传地址

func (PartURL) String

func (v PartURL) String() string

String 遮掩敏感的字段。

func (*PartURL) UnmarshalJSON

func (v *PartURL) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type Penalty

type Penalty struct {
	Kind      string        `json:"kind"`
	Params    PenaltyParams `json:"params"`
	Status    string        `json:"status"`
	CreatedAt time.Time     `json:"created_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

Penalty 一次禁言或封禁

func (*Penalty) UnmarshalJSON

func (v *Penalty) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type PenaltyParams

type PenaltyParams struct {
	// 禁言的场景
	Scopes []string `json:"scopes"`
	// 时长,不出现为永久
	DurationSeconds int64  `json:"duration_seconds"`
	Reason          string `json:"reason"`
	// 平台审核人员作出结论时的管理员
	AdminID int64 `json:"admin_id"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

PenaltyParams PenaltyParams

func (*PenaltyParams) UnmarshalJSON

func (v *PenaltyParams) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type PenaltyRule

type PenaltyRule struct {
	WindowHours int64 `json:"window_hours"`
	// 违规次数
	Threshold int64 `json:"threshold"`
	// 只统计这些类别,null 为全部
	Categories []string `json:"categories"`
	Action     string   `json:"action"`
	// mute 时必填;disable 时为 null
	MuteScopes []string `json:"mute_scopes"`
	// null 为永久
	DurationSeconds *int64 `json:"duration_seconds"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

PenaltyRule 自动处罚规则:时间窗口内违规达到次数时处罚

func (*PenaltyRule) UnmarshalJSON

func (v *PenaltyRule) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type PlatformAction

type PlatformAction struct {
	TargetType string `json:"target_type"`
	// 对象含用户的为 null
	TargetID       *string `json:"target_id"`
	TargetUsername *string `json:"target_username"`
	TargetGroupID  *string `json:"target_group_id"`
	// 所属记录的主要类别,没有所属记录时为空字符串
	Category  string     `json:"category"`
	Kind      string     `json:"kind"`
	Status    string     `json:"status"`
	CreatedAt time.Time  `json:"created_at"`
	DoneAt    *time.Time `json:"done_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

PlatformAction 平台对本应用执行的一个处置

func (*PlatformAction) UnmarshalJSON

func (v *PlatformAction) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type Presence

type Presence struct {
	// 用户名(小写)
	Username string `json:"username"`
	Online   bool   `json:"online"`
	// 在线的平台(取值与登录设备的 platform 相同),按字母排序;离线时为空数组
	Platforms []string `json:"platforms"`
	// 离线时为最近一次变为离线的时间,30 天内没有上线过为 null;在线时为 null
	LastSeenAt *time.Time `json:"last_seen_at"`
	// 在线状态的版本号,每次变化都变大;从未连接过或 30 天没有变化为 0
	Version int64 `json:"version"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

Presence 在线状态

func (*Presence) UnmarshalJSON

func (v *Presence) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type PresenceService

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

PresenceService 在线状态(client.Presence)。

func (*PresenceService) Get

func (s *PresenceService) Get(ctx context.Context, username string) (*Presence, error)

Get 查询用户的在线状态

不受应用的在线状态设置限制;用户不存在或已删除返回 not_found。网关的 Redis 不可用时返回 internal(details.reason 为 dependency_unavailable)。

接口:GET /users/{username}/presence(presence.get)。查询,网络错误、超时、5xx 时自动重试。

func (*PresenceService) Query

func (s *PresenceService) Query(ctx context.Context, usernames []string) ([]Presence, error)

Query 批量查询在线状态(每次最多 100 个,含重复的)

不受应用的在线状态开关、可见范围和 presence_last_seen_visible 的限制,按一次请求计入额度。 重复的用户名只返回一次,不存在、已删除的不出现在结果中,结果按请求中的顺序。网关的 Redis 不可用时返回 internal(details.reason 为 dependency_unavailable)。

接口:POST /presence/query(presence.query)。查询,网络错误、超时、5xx 时自动重试。

type ProcessOptions

type ProcessOptions struct {
	Scene       string // 只处理这个场景的记录,空为全部
	Limit       int    // 每页的条数,0 为服务端的默认值
	StopOnError bool   // 处理函数或作出结论出错时停止并返回错误;默认记警告日志后继续下一条
}

ProcessOptions 是 ProcessPending 的选项。

type PushDevice

type PushDevice struct {
	// 登录会话的 ID
	SessionID string `json:"session_id"`
	DeviceID  string `json:"device_id"`
	Platform  string `json:"platform"`
	// 设备登记的语言(BCP 47)
	Language *string           `json:"language"`
	Tokens   []PushDeviceToken `json:"tokens"`
	// 当前的角标计数
	Badge     int64     `json:"badge"`
	LoginAt   time.Time `json:"login_at"`
	UpdatedAt time.Time `json:"updated_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

PushDevice 登记了推送的设备

func (*PushDevice) UnmarshalJSON

func (v *PushDevice) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type PushDeviceToken

type PushDeviceToken struct {
	// alert 为普通推送,voip 为 iOS 的 VoIP 推送
	Kind string `json:"kind"`
	// 普通推送令牌的先后顺序,从 1 开始
	Priority int64 `json:"priority"`
	// 凭据名称,凭据已删除时为空字符串
	Credential string `json:"credential"`
	Channel    string `json:"channel"`
	// 只显示前 6 位和后 4 位,中间为 …
	Token string `json:"token"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

PushDeviceToken 设备的一个推送令牌(已遮掩)

func (*PushDeviceToken) UnmarshalJSON

func (v *PushDeviceToken) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type PushService

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

PushService 用户的推送设置、会话免打扰、推送设备(client.Push)。

func (*PushService) AllMutes

func (s *PushService) AllMutes(ctx context.Context, username string, params ListPushMutesParams) iter.Seq2[ConversationMute, error]

AllMutes 逐项遍历 Mutes 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。 不带 KnownVersion(遍历要的是全部数据)。

func (*PushService) Devices

func (s *PushService) Devices(ctx context.Context, username string) ([]PushDevice, error)

Devices 列出用户登记了推送的设备(不分页)

按 session_id 升序;推送令牌已遮掩。

接口:GET /users/{username}/push-devices(push.devices)。查询,网络错误、超时、5xx 时自动重试。

func (*PushService) MuteGroup

func (s *PushService) MuteGroup(ctx context.Context, username, groupID string, params MuteConversationParams) (*ConversationMuteChange, error)

MuteGroup 设置群免打扰

同样的方式和时长(到期时间相差不超过 1 分钟)再设一次,changed 为 false、到期时间不变;有变化时 settings_version 加一,并通知该用户的全部在线设备。 群不存在返回 not_found;群已解散或用户不是成员返回 not_group_member。一个用户最多 10000 个会话免打扰,超出返回 limit_exceeded(conversation_setting_limit)。

接口:PUT /users/{username}/push-settings/conversations/group/{group_id}(push.mute_group)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*PushService) MuteSingle

func (s *PushService) MuteSingle(ctx context.Context, username, peer string, params MuteConversationParams) (*ConversationMuteChange, error)

MuteSingle 设置单聊免打扰

同样的方式和时长(到期时间相差不超过 1 分钟)再设一次,changed 为 false、到期时间不变;有变化时 settings_version 加一,并通知该用户的全部在线设备。 对方不存在或已删除返回 not_found;对方是用户本人返回 invalid_argument(self_conversation); 一个用户最多 10000 个会话免打扰,超出返回 limit_exceeded(conversation_setting_limit)。

接口:PUT /users/{username}/push-settings/conversations/single/{peer}(push.mute_single)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*PushService) Mutes

Mutes 分页列出用户的会话免打扰

按会话类型和对方排序,跳过已到期的和对方已删除的,一页的条数可能少于 limit;没有下一页时 next_cursor 为空字符串。 known_version 只在第一页有效,与当前版本号相同时只返回 not_modified 和 settings_version。

接口:GET /users/{username}/push-settings/conversations(push.mutes)。查询,网络错误、超时、5xx 时自动重试。

func (*PushService) Settings

func (s *PushService) Settings(ctx context.Context, username string) (*PushSettings, error)

Settings 查询用户的推送设置

从未设置过的用户 dnd、quiet_hours、preview 都为 null,settings_version 为 0;已到期的全局免打扰为 null。

接口:GET /users/{username}/push-settings(push.settings)。查询,网络错误、超时、5xx 时自动重试。

func (*PushService) UnbindDevice

func (s *PushService) UnbindDevice(ctx context.Context, username, sessionID string) error

UnbindDevice 解绑一台设备的推送

删除这台设备登记的推送令牌,登录会话不受影响,SDK 下次启动时会重新登记。 重复解绑返回 not_found(会话没有登记推送或不属于这个用户同样为 not_found)。

接口:DELETE /users/{username}/push-devices/{session_id}(push.unbind_device)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*PushService) UnmuteGroup

func (s *PushService) UnmuteGroup(ctx context.Context, username, groupID string) (*ConversationUnmuteChange, error)

UnmuteGroup 取消群免打扰

恢复正常推送;不检查群和成员身份,没有设置过(或已到期、群不存在)的返回 200,changed 为 false。

接口:DELETE /users/{username}/push-settings/conversations/group/{group_id}(push.unmute_group)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*PushService) UnmuteSingle

func (s *PushService) UnmuteSingle(ctx context.Context, username, peer string) (*ConversationUnmuteChange, error)

UnmuteSingle 取消单聊免打扰

恢复正常推送;没有设置过(或已到期)的返回 200,changed 为 false。对方不存在或已删除返回 not_found。

接口:DELETE /users/{username}/push-settings/conversations/single/{peer}(push.unmute_single)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*PushService) UpdateSettings

func (s *PushService) UpdateSettings(ctx context.Context, username string, params UpdatePushSettingsParams) (*PushSettingsChange, error)

UpdateSettings 修改用户的推送设置

只修改给出的字段,三项都区分不传、null 和值;请求体为 {} 时什么也不改,changed 为 false。有变化时 settings_version 加一, 并通知该用户的全部在线设备。同样的时长(到期时间相差不超过 1 分钟)再开一次全局免打扰,changed 为 false、到期时间不变, 所以 1 分钟内的重试结果相同,超过 1 分钟的重试会顺延到期时间。 details.reason:invalid_duration、invalid_quiet_hours(时刻格式不对或开始等于结束)、invalid_timezone、invalid_preview; 不认识的字段、dnd 不是对象也不是 null 时为 invalid_argument,没有 details.reason,details.field 指出字段。

接口:PATCH /users/{username}/push-settings(push.update_settings)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

type PushSettings

type PushSettings struct {
	// 全局免打扰,没有开启或已到期为 null
	DND *PushSettingsDND `json:"dnd"`
	// 夜间免打扰,没有设置为 null
	QuietHours *PushSettingsQuietHours `json:"quiet_hours"`
	// 用户选择的预览方式,没有选择为 null
	Preview *string `json:"preview"`
	// 实际生效的预览方式(没有选择时为应用的默认值)
	EffectivePreview string `json:"effective_preview"`
	// 推送设置和会话免打扰共用的版本号,从未设置过为 0
	SettingsVersion int64 `json:"settings_version"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

PushSettings 用户的推送设置

func (*PushSettings) UnmarshalJSON

func (v *PushSettings) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type PushSettingsChange

type PushSettingsChange struct {
	// 全局免打扰,没有开启为 null
	DND *PushSettingsChangeDND `json:"dnd"`
	// 夜间免打扰,没有设置为 null
	QuietHours *PushSettingsChangeQuietHours `json:"quiet_hours"`
	// 用户选择的预览方式,没有选择为 null
	Preview *string `json:"preview"`
	// 实际生效的预览方式(没有选择时为应用的默认值)
	EffectivePreview string `json:"effective_preview"`
	// 推送设置和会话免打扰共用的版本号
	SettingsVersion int64 `json:"settings_version"`
	// 这次是否有变化;没有变化时版本号不变
	Changed bool `json:"changed"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

PushSettingsChange 修改后的推送设置和这次是否有变化

func (*PushSettingsChange) UnmarshalJSON

func (v *PushSettingsChange) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type PushSettingsChangeDND

type PushSettingsChangeDND struct {
	// 到期时间,null 为一直开启
	Until *time.Time `json:"until"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

PushSettingsChangeDND 全局免打扰,没有开启为 null

func (*PushSettingsChangeDND) UnmarshalJSON

func (v *PushSettingsChangeDND) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type PushSettingsChangeQuietHours

type PushSettingsChangeQuietHours struct {
	// HH:MM
	Start string `json:"start"`
	// HH:MM;早于 start 表示跨过午夜
	End string `json:"end"`
	// IANA 时区名称
	Timezone string `json:"timezone"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

PushSettingsChangeQuietHours 夜间免打扰,没有设置为 null

func (*PushSettingsChangeQuietHours) UnmarshalJSON

func (v *PushSettingsChangeQuietHours) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type PushSettingsDND

type PushSettingsDND struct {
	// 到期时间,null 为一直开启
	Until *time.Time `json:"until"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

PushSettingsDND 全局免打扰,没有开启或已到期为 null

func (*PushSettingsDND) UnmarshalJSON

func (v *PushSettingsDND) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type PushSettingsQuietHours

type PushSettingsQuietHours struct {
	// HH:MM
	Start string `json:"start"`
	// HH:MM;早于 start 表示跨过午夜
	End string `json:"end"`
	// IANA 时区名称
	Timezone string `json:"timezone"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

PushSettingsQuietHours 夜间免打扰,没有设置为 null

func (*PushSettingsQuietHours) UnmarshalJSON

func (v *PushSettingsQuietHours) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type QuietHours

type QuietHours struct {
	// 开始的时刻,HH:MM(24 小时制,两位数)(必填)
	Start string
	// 结束的时刻,HH:MM;不能等于 start,早于 start 表示跨过午夜(必填)
	End string
	// IANA 时区名称,如 Asia/Shanghai(必填)
	Timezone string
}

QuietHours 夜间免打扰:null 关闭

type RTCChannel

type RTCChannel struct {
	ChannelID       string          `json:"channel_id"`
	ChannelUID      string          `json:"channel_uid"`
	Name            string          `json:"name"`
	Media           string          `json:"media"`
	AccessMode      string          `json:"access_mode"`
	DefaultRole     string          `json:"default_role"`
	Status          string          `json:"status"`
	MaxParticipants int64           `json:"max_participants"`
	SeatCount       int64           `json:"seat_count"`
	JoinedCount     int64           `json:"joined_count"`
	MediaState      string          `json:"media_state"`
	MediaObservedAt *time.Time      `json:"media_observed_at"`
	Generation      int64           `json:"generation"`
	ExpiresAt       *time.Time      `json:"expires_at"`
	Ext             json.RawMessage `json:"ext"`
	Version         int64           `json:"version"`
	MembersVersion  int64           `json:"members_version"`
	CreatedAt       time.Time       `json:"created_at"`
	UpdatedAt       time.Time       `json:"updated_at"`
	ClosingAt       *time.Time      `json:"closing_at"`
	ClosedAt        *time.Time      `json:"closed_at"`
	CloseReason     string          `json:"close_reason"`
	CloseNote       string          `json:"close_note"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RTCChannel RTCChannel

func (*RTCChannel) UnmarshalJSON

func (v *RTCChannel) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RTCChannelAdjustmentPage

type RTCChannelAdjustmentPage struct {
	Items      []RTCChannelUsageAdjustment `json:"items"`
	NextCursor *string                     `json:"next_cursor"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RTCChannelAdjustmentPage RTCChannelAdjustmentPage

func (*RTCChannelAdjustmentPage) UnmarshalJSON

func (v *RTCChannelAdjustmentPage) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RTCChannelBan

type RTCChannelBan struct {
	Username  string     `json:"username"`
	Status    string     `json:"status"`
	ExpiresAt *time.Time `json:"expires_at"`
	Reason    string     `json:"reason"`
	Version   int64      `json:"version"`
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RTCChannelBan RTCChannelBan

func (*RTCChannelBan) UnmarshalJSON

func (v *RTCChannelBan) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RTCChannelBanCreateResult

type RTCChannelBanCreateResult struct {
	Ban RTCChannelBan `json:"ban"`
	// Created 由状态码得出:为真表示新建(201);为假表示已有结果(200)。
	Created bool `json:"-"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RTCChannelBanCreateResult RTCChannelBanCreateResult

func (*RTCChannelBanCreateResult) UnmarshalJSON

func (v *RTCChannelBanCreateResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RTCChannelBanPage

type RTCChannelBanPage struct {
	Items      []RTCChannelBan `json:"items"`
	NextCursor *string         `json:"next_cursor"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RTCChannelBanPage RTCChannelBanPage

func (*RTCChannelBanPage) UnmarshalJSON

func (v *RTCChannelBanPage) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RTCChannelBanParams

type RTCChannelBanParams struct {
	// 必填
	Version int64
	// 必填
	Reason string
	// 三种状态:零值不发送,Null 发送 null,Set 发送值
	ExpiresAt Field[time.Time]
}

RTCChannelBanParams Ban RTC channel的参数(Channels.Ban)。

type RTCChannelBanResult

type RTCChannelBanResult struct {
	Ban *RTCChannelBan `json:"ban"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RTCChannelBanResult RTCChannelBanResult

func (*RTCChannelBanResult) UnmarshalJSON

func (v *RTCChannelBanResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RTCChannelBansParams

type RTCChannelBansParams struct {
	ListOptions
}

RTCChannelBansParams Bans RTC channel的参数(Channels.Bans)。

type RTCChannelCloseParams

type RTCChannelCloseParams struct {
	// 必填
	Reason string
}

RTCChannelCloseParams Close RTC channel的参数(Channels.Close)。

type RTCChannelCloseResult

type RTCChannelCloseResult struct {
	Channel RTCChannel `json:"channel"`
	// Pending 由状态码得出:为真表示仍在异步处理(202)。
	Pending bool `json:"-"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RTCChannelCloseResult RTCChannelCloseResult

func (*RTCChannelCloseResult) UnmarshalJSON

func (v *RTCChannelCloseResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RTCChannelCreateParams

type RTCChannelCreateParams struct {
	// 必填
	Name string
	// 必填
	Media           string
	AccessMode      string
	DefaultRole     string
	MaxParticipants *int64
	Ext             json.RawMessage
	// 三种状态:零值不发送,Null 发送 null,Set 发送值
	ExpiresAt Field[time.Time]
}

RTCChannelCreateParams Create RTC channel的参数(Channels.Create)。

type RTCChannelCreateResult

type RTCChannelCreateResult struct {
	Channel RTCChannel `json:"channel"`
	// Created 由状态码得出:为真表示新建(201);为假表示已有结果(200)。
	Created bool `json:"-"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RTCChannelCreateResult RTCChannelCreateResult

func (*RTCChannelCreateResult) UnmarshalJSON

func (v *RTCChannelCreateResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RTCChannelDayStats

type RTCChannelDayStats struct {
	Date               string  `json:"date"`
	Status             string  `json:"status"`
	Finalized          bool    `json:"finalized"`
	Version            *int64  `json:"version"`
	AudioParticipantMs *string `json:"audio_participant_ms"`
	VideoParticipantMs *string `json:"video_participant_ms"`
	AudioEstimatedMs   *string `json:"audio_estimated_ms"`
	VideoEstimatedMs   *string `json:"video_estimated_ms"`
	AudioMinutes       *int64  `json:"audio_minutes"`
	VideoMinutes       *int64  `json:"video_minutes"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RTCChannelDayStats RTCChannelDayStats

func (*RTCChannelDayStats) UnmarshalJSON

func (v *RTCChannelDayStats) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RTCChannelIssueTicketsParams

type RTCChannelIssueTicketsParams struct {
	// 必填
	Users      []ChannelsIssueTicketsUsers
	TTLSeconds *int64
}

RTCChannelIssueTicketsParams IssueTickets RTC channel的参数(Channels.IssueTickets)。

type RTCChannelListParams

type RTCChannelListParams struct {
	Status string
	ListOptions
}

RTCChannelListParams List RTC channel的参数(Channels.List)。

type RTCChannelPage

type RTCChannelPage struct {
	Items      []RTCChannel `json:"items"`
	NextCursor *string      `json:"next_cursor"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RTCChannelPage RTCChannelPage

func (*RTCChannelPage) UnmarshalJSON

func (v *RTCChannelPage) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RTCChannelRemoveMemberParams

type RTCChannelRemoveMemberParams struct {
	OperationID string
	// 必填
	Reason string
}

RTCChannelRemoveMemberParams RemoveMember RTC channel的参数(Channels.RemoveMember)。

type RTCChannelRemoveResult

type RTCChannelRemoveResult struct {
	OperationID string              `json:"operation_id"`
	Sessions    []RTCChannelSession `json:"sessions"`
	// Pending 由状态码得出:为真表示仍在异步处理(202)。
	Pending bool `json:"-"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RTCChannelRemoveResult RTCChannelRemoveResult

func (*RTCChannelRemoveResult) UnmarshalJSON

func (v *RTCChannelRemoveResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RTCChannelResult

type RTCChannelResult struct {
	Channel RTCChannel `json:"channel"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RTCChannelResult RTCChannelResult

func (*RTCChannelResult) UnmarshalJSON

func (v *RTCChannelResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RTCChannelRevokeResult

type RTCChannelRevokeResult struct {
	OperationID  string `json:"operation_id"`
	RevokedCount int64  `json:"revoked_count"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RTCChannelRevokeResult RTCChannelRevokeResult

func (*RTCChannelRevokeResult) UnmarshalJSON

func (v *RTCChannelRevokeResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RTCChannelRevokeTicketsParams

type RTCChannelRevokeTicketsParams struct {
	OperationID string
	// 必填
	Usernames []string
	// 必填
	Reason string
}

RTCChannelRevokeTicketsParams RevokeTickets RTC channel的参数(Channels.RevokeTickets)。

type RTCChannelSession

type RTCChannelSession struct {
	SessionID       string     `json:"session_id"`
	ChannelID       string     `json:"channel_id"`
	Username        string     `json:"username"`
	Role            string     `json:"role"`
	Status          string     `json:"status"`
	Version         int64      `json:"version"`
	ReservedAt      time.Time  `json:"reserved_at"`
	JoinDeadline    time.Time  `json:"join_deadline"`
	MaxExpiresAt    time.Time  `json:"max_expires_at"`
	JoinedAt        *time.Time `json:"joined_at"`
	LeavingAt       *time.Time `json:"leaving_at"`
	LeftAt          *time.Time `json:"left_at"`
	LeaveReason     string     `json:"leave_reason"`
	LeaveNote       string     `json:"leave_note"`
	MediaConnected  *bool      `json:"media_connected"`
	MediaObservedAt *time.Time `json:"media_observed_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RTCChannelSession RTCChannelSession

func (*RTCChannelSession) UnmarshalJSON

func (v *RTCChannelSession) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RTCChannelSessionPage

type RTCChannelSessionPage struct {
	Items      []RTCChannelSession `json:"items"`
	NextCursor *string             `json:"next_cursor"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RTCChannelSessionPage RTCChannelSessionPage

func (*RTCChannelSessionPage) UnmarshalJSON

func (v *RTCChannelSessionPage) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RTCChannelSessionsParams

type RTCChannelSessionsParams struct {
	Status string
	ListOptions
}

RTCChannelSessionsParams Sessions RTC channel的参数(Channels.Sessions)。

type RTCChannelStatsParams

type RTCChannelStatsParams struct {
	// 必填
	From string
	// 必填
	To string
}

RTCChannelStatsParams Stats RTC channel的参数(Channels.Stats)。

type RTCChannelStatsResult

type RTCChannelStatsResult struct {
	Timezone         string               `json:"timezone"`
	FinalizedThrough *string              `json:"finalized_through"`
	Items            []RTCChannelDayStats `json:"items"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RTCChannelStatsResult RTCChannelStatsResult

func (*RTCChannelStatsResult) UnmarshalJSON

func (v *RTCChannelStatsResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RTCChannelTicket

type RTCChannelTicket struct {
	Username  string    `json:"username"`
	Role      string    `json:"role"`
	Ticket    string    `json:"ticket"`
	ExpiresAt time.Time `json:"expires_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RTCChannelTicket RTCChannelTicket

func (RTCChannelTicket) String

func (v RTCChannelTicket) String() string

String 遮掩敏感的字段。

func (*RTCChannelTicket) UnmarshalJSON

func (v *RTCChannelTicket) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RTCChannelTicketsResult

type RTCChannelTicketsResult struct {
	Tickets []RTCChannelTicket `json:"tickets"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RTCChannelTicketsResult RTCChannelTicketsResult

func (RTCChannelTicketsResult) String

func (v RTCChannelTicketsResult) String() string

String 遮掩敏感的字段。

func (*RTCChannelTicketsResult) UnmarshalJSON

func (v *RTCChannelTicketsResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RTCChannelUnbanParams

type RTCChannelUnbanParams struct {
	// 必填
	Version int64
	// 必填
	Reason string
}

RTCChannelUnbanParams Unban RTC channel的参数(Channels.Unban)。

type RTCChannelUpdateParams

type RTCChannelUpdateParams struct {
	// 必填
	Version int64
	Name    *string
	Ext     json.RawMessage
	// 三种状态:零值不发送,Null 发送 null,Set 发送值
	ExpiresAt Field[time.Time]
}

RTCChannelUpdateParams Update RTC channel的参数(Channels.Update)。

type RTCChannelUsageAdjustment

type RTCChannelUsageAdjustment struct {
	Date                  string  `json:"date"`
	Media                 string  `json:"media"`
	Status                string  `json:"status"`
	ProposalVersion       int64   `json:"proposal_version"`
	TargetVersion         int64   `json:"target_version"`
	ParticipantMs         string  `json:"participant_ms"`
	Minutes               int64   `json:"minutes"`
	ProposedParticipantMs string  `json:"proposed_participant_ms"`
	ProposedMinutes       int64   `json:"proposed_minutes"`
	BillingAdjustmentID   *string `json:"billing_adjustment_id"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RTCChannelUsageAdjustment RTCChannelUsageAdjustment

func (*RTCChannelUsageAdjustment) UnmarshalJSON

func (v *RTCChannelUsageAdjustment) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RTCChannelUsageAdjustmentsParams

type RTCChannelUsageAdjustmentsParams struct {
	ListOptions
}

RTCChannelUsageAdjustmentsParams 查询频道用量更正状态的参数(Channels.UsageAdjustments)。

type RateLimit

type RateLimit struct {
	PerSecond float64 // 每秒的请求数
	Burst     int     // 桶的容量,默认 max(1, ceil(PerSecond))
}

RateLimit 本地限速(令牌桶)。批量接口按项数计(与服务端的额度计算一致),一个请求最多扣到桶的容量。

type ReplyTo

type ReplyTo struct {
	// 被引用消息在同一会话中的序号;必须存在、在保留期内、没有撤回或擦除,且发送者能看到(必填)
	Seq int64
}

ReplyTo ReplyTo

type ReportParams

type ReportParams struct {
	// 举报人的用户名(必填)
	Reporter string
	// 必填
	TargetType string
	// target_type 为 message、chatroom_message 时
	MessageID string
	// target_type 为 user 时
	Username string
	// target_type 为 group 时
	GroupID string
	// target_type 为 chatroom、chatroom_message 时
	RoomID string
	// 必填
	Reason string
	// 最长 500 个字符,不能有换行、制表符以外的控制字符
	Description string
	// 证据消息,只用于 user、group
	EvidenceMessageIDs []string
}

ReportParams 代用户举报的参数(Moderation.Report)。

type ReportResult

type ReportResult struct {
	ReportID   string  `json:"report_id"`
	TargetType string  `json:"target_type"`
	Username   *string `json:"username"`
	MessageID  *string `json:"message_id"`
	GroupID    *string `json:"group_id"`
	RoomID     *string `json:"room_id"`
	Reason     string  `json:"reason"`
	// 所属审核记录未结束为 pending,其余为 closed
	Status    string    `json:"status"`
	CreatedAt time.Time `json:"created_at"`
	// Duplicate 由状态码得出:为真表示重复提交,结果是第一次的。
	Duplicate bool `json:"-"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ReportResult 举报(SDK 另有 duplicate,按状态码得出)

func (*ReportResult) UnmarshalJSON

func (v *ReportResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RequestInfo

type RequestInfo struct {
	Op            string        // 接口名,如 users.create;换取令牌为 app.token
	Method        string        // HTTP 方法
	URL           string        // 不含查询参数的地址
	Attempt       int           // 第几次尝试,从 1 开始
	StatusCode    int           // 没有收到响应时为 0
	Code          string        // 错误码(服务端的或 network_error、timeout 等),成功时为空
	Reason        string        // details.reason
	RequestID     string        // 响应头 X-Request-ID 或错误体中的,没有时为 SDK 发出的
	Duration      time.Duration // 这次尝试的耗时
	RateLimitWait time.Duration // 这次尝试之前限流等待(含本地限速)的时长
}

RequestInfo 是一次尝试的结果,交给 Hooks.AfterResponse。

type RetryPolicy

type RetryPolicy struct {
	// MaxAttempts 网络错误、超时、5xx 的最多尝试次数(含第一次),默认 4;1 表示不重试。
	MaxAttempts int
	// MaxRateLimited rate_limited 后等待重发的次数,默认 3。
	MaxRateLimited int
	// Disabled 两种都不重试(不幂等的写操作本来就不重试);令牌失效后换取一次再重发不受影响。
	Disabled bool
}

RetryPolicy 自动重试的设置。

type RoomAdminChange

type RoomAdminChange struct {
	Changed bool `json:"changed"`
	// 当前的资料版本号
	InfoVersion int64 `json:"info_version"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RoomAdminChange 设置、取消管理员的结果

func (*RoomAdminChange) UnmarshalJSON

func (v *RoomAdminChange) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RoomAllowlistEntry

type RoomAllowlistEntry struct {
	Username string `json:"username"`
	// 没有时为空字符串
	Nickname string `json:"nickname"`
	// 没有时为空字符串
	AvatarURL string `json:"avatar_url"`
	// 设置人的用户名;服务端设置的和设置人已删除的为 null
	CreatedBy *string   `json:"created_by"`
	CreatedAt time.Time `json:"created_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RoomAllowlistEntry 白名单中的一项

func (*RoomAllowlistEntry) UnmarshalJSON

func (v *RoomAllowlistEntry) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RoomAttribute

type RoomAttribute struct {
	Value string `json:"value"`
	// 最近一次设置这个键的用户;服务端设置的和设置人已删除的为 null
	Owner *string `json:"owner"`
	// 设置人离开聊天室时是否自动删除
	AutoDelete bool      `json:"auto_delete"`
	UpdatedAt  time.Time `json:"updated_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RoomAttribute 聊天室的一个属性

func (*RoomAttribute) UnmarshalJSON

func (v *RoomAttribute) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RoomAttributes

type RoomAttributes struct {
	// 键到属性,没有时为空对象
	Attributes        map[string]RoomAttribute `json:"attributes"`
	AttributesVersion int64                    `json:"attributes_version"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RoomAttributes 聊天室的属性

func (*RoomAttributes) UnmarshalJSON

func (v *RoomAttributes) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RoomAttributesChange

type RoomAttributesChange struct {
	Changed bool `json:"changed"`
	// 操作之后的属性版本号
	AttributesVersion int64 `json:"attributes_version"`
	// 失败的键,没有时为空对象
	Failed map[string]ItemError `json:"failed"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RoomAttributesChange 设置、删除属性的结果;failed 的每项只有 code 和 details,没有 message

func (*RoomAttributesChange) Err

func (v *RoomAttributesChange) Err() error

Err 有失败的项时返回汇总的错误(*BatchError),全部成功时为 nil。

func (*RoomAttributesChange) FailedItems

func (v *RoomAttributesChange) FailedItems() []ItemError

FailedItems 失败的项(项的标识在 Key 中);全部成功时为 nil。

func (*RoomAttributesChange) OK

func (v *RoomAttributesChange) OK() bool

OK 全部成功。

func (*RoomAttributesChange) UnmarshalJSON

func (v *RoomAttributesChange) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RoomBan

type RoomBan struct {
	Username string `json:"username"`
	// 没有时为空字符串
	Nickname string `json:"nickname"`
	// 没有时为空字符串
	AvatarURL string `json:"avatar_url"`
	// 到期时间,永久为 null
	ExpiresAt *time.Time `json:"expires_at"`
	// 没有时为空字符串
	Reason string `json:"reason"`
	// 设置人的用户名;服务端设置的和设置人已删除的为 null
	CreatedBy     *string   `json:"created_by"`
	CreatedByRole string    `json:"created_by_role"`
	CreatedAt     time.Time `json:"created_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RoomBan 一项聊天室封禁

func (*RoomBan) UnmarshalJSON

func (v *RoomBan) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RoomBatchResult

type RoomBatchResult struct {
	// 是否有任何一项发生了变化
	Changed bool `json:"changed"`
	// 按请求的顺序(去重后)
	Results []RoomBatchResultItem `json:"results"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RoomBatchResult 名单批量操作的结果(移出、禁言、封禁、白名单)

func (*RoomBatchResult) Err

func (v *RoomBatchResult) Err() error

Err 有失败的项时返回汇总的错误(*BatchError),全部成功时为 nil。

func (*RoomBatchResult) FailedItems

func (v *RoomBatchResult) FailedItems() []ItemError

FailedItems 失败的项(项的标识在 Key 中);全部成功时为 nil。

func (*RoomBatchResult) OK

func (v *RoomBatchResult) OK() bool

OK 全部成功。

func (*RoomBatchResult) UnmarshalJSON

func (v *RoomBatchResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RoomBatchResultItem

type RoomBatchResultItem struct {
	// 用户名(小写)
	Username string `json:"username"`
	Result   string `json:"result"`
	// Error 失败时的错误(Key 为这一项的标识),成功时为 nil。
	Error *ItemError `json:"-"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RoomBatchResultItem 批量操作中一个用户的结果:成功时有 result,失败时有 code、message、details

func (*RoomBatchResultItem) UnmarshalJSON

func (v *RoomBatchResultItem) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RoomMember

type RoomMember struct {
	Username string `json:"username"`
	// 没有时为空字符串
	Nickname string `json:"nickname"`
	// 没有时为空字符串
	AvatarURL string `json:"avatar_url"`
	Role      string `json:"role"`
	// 进入的时间
	JoinedAt time.Time `json:"joined_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RoomMember 在聊天室里的一个用户

func (*RoomMember) UnmarshalJSON

func (v *RoomMember) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RoomMemberState

type RoomMemberState struct {
	// 是否有连接在聊天室里
	InRoom bool `json:"in_room"`
	// 进入的时间,不在聊天室里时为 null
	JoinedAt *time.Time `json:"joined_at"`
	Role     string     `json:"role"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RoomMemberState 一个用户在聊天室中的状态

func (*RoomMemberState) UnmarshalJSON

func (v *RoomMemberState) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RoomMessage

type RoomMessage struct {
	RoomID    string `json:"room_id"`
	MessageID string `json:"message_id"`
	// 服务端发送没有给时为服务端生成的 UUID;客户端的低优先级消息可能为 null
	ClientMsgID *string `json:"client_msg_id"`
	// 发送者的用户名,系统消息为 null
	Sender     *string `json:"sender"`
	SenderType string  `json:"sender_type"`
	// 发送时的昵称,系统消息为 null
	SenderNickname *string `json:"sender_nickname"`
	// 发送时的头像,系统消息为 null
	SenderAvatarURL *string `json:"sender_avatar_url"`
	// 发送时的身份,系统消息为 null
	SenderRole *string         `json:"sender_role"`
	Type       string          `json:"type"`
	Body       json.RawMessage `json:"body"`
	Ext        json.RawMessage `json:"ext"`
	Priority   string          `json:"priority"`
	Via        string          `json:"via"`
	CreatedAt  time.Time       `json:"created_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RoomMessage 聊天室消息

func (*RoomMessage) UnmarshalJSON

func (v *RoomMessage) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RoomMute

type RoomMute struct {
	Username string `json:"username"`
	// 没有时为空字符串
	Nickname string `json:"nickname"`
	// 没有时为空字符串
	AvatarURL string `json:"avatar_url"`
	// 到期时间,永久为 null
	MutedUntil *time.Time `json:"muted_until"`
	// 没有时为空字符串
	Reason string `json:"reason"`
	// 设置人的用户名;服务端设置的和设置人已删除的为 null
	CreatedBy     *string   `json:"created_by"`
	CreatedByRole string    `json:"created_by_role"`
	CreatedAt     time.Time `json:"created_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RoomMute 一项聊天室禁言

func (*RoomMute) UnmarshalJSON

func (v *RoomMute) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RoomOnlineCount

type RoomOnlineCount struct {
	RoomID string `json:"room_id"`
	// 近似值(缓存 5 秒);封禁的为 0
	MemberCount int64 `json:"member_count"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RoomOnlineCount 一个聊天室的在线人数

func (*RoomOnlineCount) UnmarshalJSON

func (v *RoomOnlineCount) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RoomPenaltyParams

type RoomPenaltyParams struct {
	// 不给为永久
	DurationSeconds *int64
	// 最长 256 个字符,不能包含控制字符
	Reason string
}

RoomPenaltyParams 在聊天室中封禁用户(每次最多 100 个)的参数(Chatrooms.Ban)。

type RoomRecallResult

type RoomRecallResult struct {
	// 是否推送了撤回通知
	Changed bool `json:"changed"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RoomRecallResult 撤回的结果

func (*RoomRecallResult) UnmarshalJSON

func (v *RoomRecallResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type RoomSendResult

type RoomSendResult struct {
	RoomID string `json:"room_id"`
	// 被丢弃时为 null
	MessageID *string `json:"message_id"`
	// 没有给时为服务端生成的 UUID;被丢弃且没有给时为 null
	ClientMsgID *string `json:"client_msg_id"`
	// 发送者的用户名,系统身份为 null
	Sender *string `json:"sender"`
	// 重复提交时为空字符串
	SenderType      string  `json:"sender_type"`
	SenderNickname  *string `json:"sender_nickname"`
	SenderAvatarURL *string `json:"sender_avatar_url"`
	// 发送者此刻的身份,系统身份为 null
	SenderRole *string `json:"sender_role"`
	Type       string  `json:"type"`
	// 发送前检查替换了内容时为替换后的
	Body     json.RawMessage `json:"body"`
	Ext      json.RawMessage `json:"ext"`
	Priority string          `json:"priority"`
	Via      string          `json:"via"`
	// 被丢弃时为 null
	CreatedAt *time.Time `json:"created_at"`
	// 低优先级的消息因频率限制被丢弃
	Dropped bool `json:"dropped"`
	// Duplicate 由状态码得出:为真表示重复提交,结果是第一次的。
	Duplicate bool `json:"-"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

RoomSendResult 发送的结果。201 为新消息;200 且 dropped 为 false 为重复提交(只有 message_id、created_at 可靠); dropped 为 true 时只有 room_id、client_msg_id、priority,message_id、created_at 为 null。

func (*RoomSendResult) UnmarshalJSON

func (v *RoomSendResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type SendMessageParams

type SendMessageParams struct {
	// 发送者的用户名。单聊必填;群聊不给时以系统身份发送(sender 为 null),给出的必须是群成员
	From string
	// 单聊的接收者,不能是发送者本人;与 to_group 恰好给一个
	ToUser string
	// 群聊的群 ID;与 to_user 恰好给一个
	ToGroup string
	// 去重 ID,1 到 64 个可见 ASCII 字符,不能以 evt_、sys_ 开头;不给时由 SDK 生成
	ClientMsgID string
	// 必填
	Type string
	// 消息内容,JSON 对象,格式由 type 决定:text 为 {text};image 为 {url, thumbnail_url, width, height, size, format};
	// voice 为 {url, duration_seconds, size, format};video 为 {url, duration_seconds, thumbnail_url, width, height, size, format};
	// file 为 {name, url, size, format};location 为 {latitude, longitude, name, address};custom 不限。
	// 嵌套不超过 10 层、键合计不超过 256 个、没有重复的键、字符串不含控制字符(text 的 text 可以有换行和制表符)。
	// type、body、ext、mentions、reply_to 合计不超过应用的 max_message_body_bytes(默认 5120 字节,按紧凑 JSON 计算)。
	// (必填)
	Body json.RawMessage
	// 自定义扩展(JSON 对象,规则同 body);null 与不传相同
	Ext json.RawMessage
	// 只用于群聊;不是群成员的用户名被忽略
	Mentions *Mentions
	ReplyTo  *ReplyTo
	// 要求已读回执;只用于群聊,不能以系统身份发送,应用要开启群已读回执
	NeedReceipt bool
	// 不计入接收者的未读数,也不发离线推送(设置了 push.force 的也不发)
	ExcludeFromUnread bool
	Push              *MessagePushOptions
	// 只推给在线的设备;只能是 custom 类型,不能带 mentions、reply_to、need_receipt、exclude_from_unread、push
	OnlineOnly bool
	// 是否同步到发送者的其他设备;只对单聊和只推在线的消息有效,群聊的消息总是同步
	SyncToSender *bool
}

SendMessageParams 发送一条消息(单聊或群聊)的参数(Messages.Send)。

type SendResult

type SendResult struct {
	// 会话 ID;群会话的即群 ID
	ConversationID   string `json:"conversation_id"`
	ConversationType string `json:"conversation_type"`
	// 在会话中的序号
	Seq int64 `json:"seq"`
	// 全局唯一的消息 ID
	MessageID string `json:"message_id"`
	// 去重 ID;只推在线的消息没有给时为 message_id
	ClientMsgID string `json:"client_msg_id"`
	// 发送者的用户名;以系统身份发送时为 null
	Sender     *string `json:"sender"`
	SenderType string  `json:"sender_type"`
	// 单聊的接收者;群聊为 null
	Recipient *string `json:"recipient"`
	Type      string  `json:"type"`
	// 消息内容(发送前检查可能替换过)
	Body json.RawMessage `json:"body"`
	// 自定义扩展,没有时为 null
	Ext json.RawMessage `json:"ext"`
	// @ 的成员(已去掉不是成员的),没有 @ 时为 null
	Mentions *MessageMentions `json:"mentions"`
	// 引用的消息,没有时为 null
	ReplyTo           *MessageReply      `json:"reply_to"`
	NeedReceipt       bool               `json:"need_receipt"`
	ExcludeFromUnread bool               `json:"exclude_from_unread"`
	Reactions         []MessageReaction  `json:"reactions"`
	Pinned            *MessagePinInfo    `json:"pinned"`
	Edited            *MessageEditInfo   `json:"edited"`
	Recalled          *MessageRecallInfo `json:"recalled"`
	Erased            bool               `json:"erased"`
	Via               string             `json:"via"`
	CreatedAt         time.Time          `json:"created_at"`
	MessageVersion    int64              `json:"message_version"`
	// 只在只推在线的结果中出现,为 true
	OnlineOnly bool `json:"online_only"`
	// Duplicate 由状态码得出:为真表示重复提交,结果是第一次的。
	Duplicate bool `json:"-"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

SendResult 发送的结果。新消息(201)和重复提交(200,返回第一次写入的消息)为完整的消息,字段同 Message; 只推在线的消息(200)只有 message_id、client_msg_id、created_at 和 online_only(为 true),不是重复提交。

func (*SendResult) UnmarshalJSON

func (v *SendResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type SendRoomMessageParams

type SendRoomMessageParams struct {
	// 发送者的用户名;不给为系统身份
	From string
	// 1 到 64 个可见 ASCII 字符,不以 evt_、sys_ 开头;普通和高优先级不给时由 SDK 生成
	ClientMsgID string
	// 必填
	Type string
	// 消息内容,格式由 type 决定(必填)
	Body json.RawMessage
	// 扩展内容(JSON 对象)
	Ext      json.RawMessage
	Priority string
}

SendRoomMessageParams 发送聊天室消息的参数(Chatrooms.Send)。

type SentByParams

type SentByParams struct {
	// 只取这个时间及之后发送的
	StartTime time.Time
	// 只取早于这个时间发送的
	EndTime time.Time
	ListOptions
}

SentByParams 分页列出用户发过的消息的参数(Messages.SentBy)。

type SeqPage

type SeqPage struct {
	Items         []Message
	HasMore       bool
	NextAfterSeq  *int64 // 下一页的 AfterSeq(向新的方向)
	NextBeforeSeq *int64 // 下一页的 BeforeSeq(向旧的方向)
	HasMoreBefore *bool  // 只在按 AroundSeq 取时有
	HasMoreAfter  *bool  // 只在按 AroundSeq 取时有
	Raw           json.RawMessage
}

SeqPage 是按序号取的会话消息(按序号从小到大)。是否结束只看 HasMore(按 AroundSeq 取时为两个方向各自的 HasMoreBefore、HasMoreAfter);一页可能为空而 HasMore 为真(一页最多扫描 1000 个序号或 1 MB)。

func (*SeqPage) UnmarshalJSON

func (p *SeqPage) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type SeqParams

type SeqParams struct {
	// 取序号大于它的消息(向新的方向)
	AfterSeq *int64
	// 取序号小于它的消息(向旧的方向)
	BeforeSeq *int64
	// 取以它为中心的消息
	AroundSeq *int64
	// 只取这个时间及之后的消息
	StartTime time.Time
	// 只取早于这个时间的消息
	EndTime time.Time
	Limit   int
}

SeqParams 按序号拉取会话中的消息的参数(Conversations.Messages)。

type Session

type Session struct {
	SessionID    string     `json:"session_id"`
	DeviceID     string     `json:"device_id"`
	DeviceName   string     `json:"device_name"`
	Platform     string     `json:"platform"`
	SDKVersion   string     `json:"sdk_version"`
	LoginMethod  string     `json:"login_method"`
	IP           string     `json:"ip"`
	CreatedAt    time.Time  `json:"created_at"`
	LastActiveAt time.Time  `json:"last_active_at"`
	ExpiresAt    *time.Time `json:"expires_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

Session 登录设备

func (*Session) UnmarshalJSON

func (v *Session) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type StartStreamInput added in v1.0.2

type StartStreamInput struct {
	Bot            string // 机器人的用户名
	To             string // 接收回复的用户名
	ReplyToSeq     int64  // 回复的是会话中的哪条消息,0 表示不引用
	ClientStreamID string // 幂等标识,不给时 SDK 生成
	Replace        bool   // 会话中已有进行中的回复时先结束它
	BatchOnly      bool   // 只用按批写入(运行环境不支持流式请求体时,如部分云函数)
}

StartStreamInput 是 StartStream 的参数。

type Stats

type Stats struct {
	Ops map[string]OpStats
}

Stats 是按接口名的统计(Client.Stats 返回的快照)。

type Stream added in v1.0.2

type Stream struct {
	// Info 是开始时的流对象。
	Info AIStream
	// ID 是流 ID,开发者在 ai.stream_stopped 回调中按它找到流。
	ID string
	// contains filtered or unexported fields
}

Stream 是一条进行中的流式回复。

func (*Stream) Close added in v1.0.2

func (s *Stream) Close() error

Close 停止发送并释放资源,没有调用 Finish 或 Fail 时以 Fail("canceled") 结束。可以重复调用。

func (*Stream) Context added in v1.0.2

func (s *Stream) Context() context.Context

Context 在用户停止生成、流被平台结束或写入失败时取消,context.Cause 给出原因。开发者把它传给模型的请求,停止时模型调用随之中止。

func (*Stream) Fail added in v1.0.2

func (s *Stream) Fail(ctx context.Context, code, message string) (*AIStream, error)

Fail 报告失败:以“生成中断”结束,已生成的部分保留,客户端显示 message。已发出但未确认的内容尽量先确认。

func (*Stream) Finish added in v1.0.2

func (s *Stream) Finish(ctx context.Context, opts FinishOptions) (*AIStream, error)

Finish 发出全部内容并等待确认后结束流(已完成)。流已被用户停止或平台结束时返回 *Error(stream_closed)。

func (*Stream) Flush added in v1.0.2

func (s *Stream) Flush(ctx context.Context) error

Flush 立即发出已写入的内容,等待服务端确认。

func (*Stream) PipeAnthropic added in v1.0.2

func (s *Stream) PipeAnthropic(src any) (*AIStream, error)

PipeAnthropic 对接 Anthropic Messages 的流:text_delta 写为正文,thinking_delta 写为思考过程,tool_use 写为工具调用。

func (*Stream) PipeGemini added in v1.0.2

func (s *Stream) PipeGemini(src any) (*AIStream, error)

PipeGemini 对接 Gemini generateContent 的流:thought 为真的部分写为思考过程,其余写为正文。

func (*Stream) PipeOpenAI added in v1.0.2

func (s *Stream) PipeOpenAI(src any) (*AIStream, error)

PipeOpenAI 对接 OpenAI Chat Completions 的流:delta.content 写为正文,delta.reasoning_content 写为思考过程,tool_calls 写为工具调用。

func (*Stream) PipeOpenAIResponses added in v1.0.2

func (s *Stream) PipeOpenAIResponses(src any) (*AIStream, error)

PipeOpenAIResponses 对接 OpenAI Responses API 的流。

func (*Stream) Stopped added in v1.0.2

func (s *Stream) Stopped()

Stopped 由回调处理器在收到 ai.stream_stopped 时调用:取消 Stream.Context,停止发送。

func (*Stream) String added in v1.0.2

func (s *Stream) String() string

String 返回流 ID,便于日志。

func (*Stream) WriteFile added in v1.0.2

func (s *Stream) WriteFile(file FilePart) error

WriteFile 写入一个文件。

func (*Stream) WriteImage added in v1.0.2

func (s *Stream) WriteImage(image ImagePart) error

WriteImage 写入一张图片。

func (*Stream) WriteReasoning added in v1.0.2

func (s *Stream) WriteReasoning(text string) error

WriteReasoning 追加思考过程。

func (*Stream) WriteText added in v1.0.2

func (s *Stream) WriteText(text string) error

WriteText 追加正文(Markdown)。

func (*Stream) WriteTool added in v1.0.2

func (s *Stream) WriteTool(id, name, title, state string) error

WriteTool 写入工具调用的进度:同一个 id 的再次写入更新同一个片段(如 running 变为 done)。只用于展示,不含参数和结果。

type TextCheck

type TextCheck struct {
	Action string `json:"action"`
	// 有替换时为替换后的文本,否则为原文
	Text string         `json:"text"`
	Hits []TextCheckHit `json:"hits"`
	// 第三方审核的结果,没有调用时为 null
	ProviderResult *TextCheckProviderResult `json:"provider_result"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

TextCheck 一个字段的检查结果

func (*TextCheck) UnmarshalJSON

func (v *TextCheck) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type TextCheckHit

type TextCheckHit struct {
	ListID   string `json:"list_id"`
	ListName string `json:"list_name"`
	// 平台词库的命中,只在为 true 时出现
	Platform bool   `json:"platform"`
	Category string `json:"category"`
	Action   string `json:"action"`
	// 命中的词条(规范化后的)
	Word string `json:"word"`
	// 原文中的开始位置(按 Unicode 字符计)
	Start int64 `json:"start"`
	// 原文中的结束位置(不含)
	End int64 `json:"end"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

TextCheckHit 一次词库的命中;平台词库的命中只有 platform 和 category

func (*TextCheckHit) UnmarshalJSON

func (v *TextCheckHit) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type TextCheckProviderResult

type TextCheckProviderResult struct {
	Suggestion string   `json:"suggestion"`
	Categories []string `json:"categories"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

TextCheckProviderResult 第三方审核的结果

func (*TextCheckProviderResult) UnmarshalJSON

func (v *TextCheckProviderResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type TextCheckResult

type TextCheckResult struct {
	// 字段名到结果,text 的键为 text
	Fields map[string]TextCheck `json:"fields"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

TextCheckResult 检查文本的结果(SDK 统一为按字段)

func (*TextCheckResult) UnmarshalJSON

func (v *TextCheckResult) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type TokenStore

type TokenStore interface {
	Get(ctx context.Context, key string) (token string, expiresAt time.Time, ok bool, err error)
	Set(ctx context.Context, key string, token string, expiresAt time.Time) error
	// CompareAndDelete 只在存储中的令牌等于 token 时删除(避免删掉别的实例刚换来的新令牌)。
	CompareAndDelete(ctx context.Context, key string, token string) error
}

TokenStore 让多个服务实例共用一个 App Token。Get 返回 ok 为假时由本实例换取后 Set。 存储出错时 SDK 退回本进程换取,不影响请求(记警告日志)。键为 drim:token:{16 个十六进制字符},不含 Secret。

type UnreadCount

type UnreadCount struct {
	// 全部会话的未读数之和
	Total int64 `json:"total"`
	// 有未读的会话数
	ConversationCount int64 `json:"conversation_count"`
	// 未读数为 0 而被标记为未读的会话数
	MarkedUnreadCount int64 `json:"marked_unread_count"`
	// 单聊和已离开的群超过 1000 个、更早的没有统计
	Truncated bool `json:"truncated"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

UnreadCount 用户的未读总数

func (*UnreadCount) UnmarshalJSON

func (v *UnreadCount) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type UpdateBotParams added in v1.0.2

type UpdateBotParams struct {
	EndpointID         *string
	ContextMessages    *int64
	IdleTimeoutSeconds *int64
	MaxActiveStreams   *int64
	Description        *string
}

UpdateBotParams 修改机器人的配置的参数(AI.UpdateBot)。

type UpdateChatroomParams

type UpdateChatroomParams struct {
	// 1 到 128 个字符(去掉首尾空白),不能包含控制字符
	Name *string
	// 最长 512 个字符,可以换行;空字符串清空
	Description *string
	// 最长 512 字节的 http(s) 地址;空字符串清空
	AvatarURL *string
	// 最长 2048 个字符,可以换行;空字符串清空
	Announcement *string
	// 是否出现在客户端的聊天室列表中
	Listed *bool
	// 聊天室自己的人数上限;null 清除,跟随应用策略;三种状态:零值不发送,Null 发送 null,Set 发送值
	MaxMembers Field[int]
	// 期望的当前 info_version
	Version *int64
}

UpdateChatroomParams 修改聊天室资料的参数(Chatrooms.Update)。

type UpdateFriendParams

type UpdateFriendParams struct {
	// 去掉首尾空白后最长 64 个字符,不能含控制字符;空字符串清空
	Remark *string
	// null 清空全部;按项合并,某一项为 null 删除这一项;合并后最多 16 个键、合计 1 KB;三种状态:零值不发送,Null 发送 null,Set 发送值
	Attributes Field[map[string]Field[string]]
}

UpdateFriendParams 修改好友的备注和自定义属性的参数(Friends.Update)。

type UpdateGroupParams

type UpdateGroupParams struct {
	Type *string
	// 最长 64 个字符;空字符串清空
	Name *string
	// 最长 512 字节的 http(s) 地址;空字符串清空
	AvatarURL *string
	// 最长 512 个字符;空字符串清空
	Description *string
	// 最长 2048 个字符;空字符串清空
	Announcement *string
	// null 清空全部;按项合并,某一项为 null 删除这一项;合并后最多 32 个键、合计 4 KB;三种状态:零值不发送,Null 发送 null,Set 发送值
	Attributes   Field[map[string]Field[string]]
	MemberInvite *string
	// 只用于公开群
	JoinMode *string
	// 群自己的人数上限;null 清除,改为跟随应用;三种状态:零值不发送,Null 发送 null,Set 发送值
	MaxMembers Field[int]
	// 期望的当前 info_version
	Version *int64
}

UpdateGroupParams 修改群资料和设置的参数(Groups.Update)。

type UpdateMemberParams

type UpdateMemberParams struct {
	// 最长 64 个字符;空字符串清除
	GroupNickname *string
	// null 清空全部;按项合并,某一项为 null 删除这一项;合并后最多 16 个键、合计 1 KB;三种状态:零值不发送,Null 发送 null,Set 发送值
	Attributes Field[map[string]Field[string]]
}

UpdateMemberParams 修改成员的群昵称和成员属性的参数(Groups.UpdateMember)。

type UpdateModerationConfigParams

type UpdateModerationConfigParams struct {
	// 按场景合并,只修改给出的场景和字段;键为场景
	Scenes map[string]ModerationSceneUpdate
	// 自定义消息是检查其中的字符串还是不检查
	CustomMessageCheck *string
	// 按类别合并,键为类别;某一类为 null 恢复默认(block 为 reject、review 为 review)
	CategoryActions map[string]Field[ModerationCategoryActionUpdate]
	// 同步调用第三方审核的超时(毫秒)
	SyncTimeoutMs *int64
	// 同步审核超时的处理
	OnTimeout *string
	// 自动处罚规则,整体替换;null 为不自动处罚;三种状态:零值不发送,Null 发送 null,Set 发送值
	PenaltyRules Field[[]PenaltyRule]
	// 期望的当前版本
	Version *int64
	// 写入操作日志的原因
	Reason *string
}

UpdateModerationConfigParams 修改应用的内容安全配置的参数(Moderation.UpdateConfig)。

type UpdatePushSettingsParams

type UpdatePushSettingsParams struct {
	// 全局免打扰:null 关闭;对象为开启;三种状态:零值不发送,Null 发送 null,Set 发送值
	DND Field[DND]
	// 夜间免打扰:null 关闭;三种状态:零值不发送,Null 发送 null,Set 发送值
	QuietHours Field[QuietHours]
	// 预览方式:full 显示发送者和内容,sender_only 只显示发送者,none 都不显示;null 清除用户的选择,改用应用的默认值;三种状态:零值不发送,Null 发送 null,Set 发送值
	Preview Field[string]
}

UpdatePushSettingsParams 修改用户的推送设置的参数(Push.UpdateSettings)。

type UpdateUserParams

type UpdateUserParams struct {
	// 最长 64 个字符;空字符串清空
	Nickname *string
	// 最长 512 字节的 http(s) 地址;空字符串清空
	AvatarURL *string
	// null 清空全部;按项合并,某一项为 null 删除这一项;三种状态:零值不发送,Null 发送 null,Set 发送值
	Attributes Field[map[string]Field[string]]
	// 期望的当前版本
	Version *int64
}

UpdateUserParams 修改用户资料的参数(Users.Update)。

type UpdateWordListParams

type UpdateWordListParams struct {
	// 1 到 64 个字符,不能有控制字符,应用内唯一
	Name *string
	// 只用于屏蔽词库
	Action *string
	// 放行词库只能为 contains
	MatchMode *string
	Category  *string
	// 适用的场景,不能为空数组、不能重复;null 为全部场景;三种状态:零值不发送,Null 发送 null,Set 发送值
	Scenes  Field[[]string]
	Enabled *bool
}

UpdateWordListParams 修改词库的属性的参数(Moderation.UpdateWordList)。

type UploadParams

type UploadParams struct {
	Purpose     string // attachment、user_avatar、group_avatar、chatroom_avatar、group_file
	Kind        string // image、voice、video、file
	Name        string // 类型为 file 和群文件必填;最长 255,不含 / \ 和控制字符
	ContentType string // 只作提示,格式由服务端按内容识别
	GroupID     string // 群文件的群
	Owner       string // 用户头像的所属用户(必填),其他用途可选
	Concurrency int    // 分片并发,默认 4
	// OnProgress 每个分片(一次上传为整个文件)完成后调用,同一时刻只有一个协程调用,不能阻塞。
	OnProgress func(uploaded, total int64)
}

UploadParams 是上传的参数。

type UploadSession

type UploadSession struct {
	FileID string `json:"file_id"`
	// single 为一次上传,multipart 为分片上传
	UploadMethod string `json:"upload_method"`
	// 一次上传的地址,分片上传为 null
	Upload *UploadSessionUpload `json:"upload"`
	// 每片的字节数(16 MB,最后一片可以较小),一次上传为 null
	PartSize *int64 `json:"part_size"`
	// 分片数,一次上传为 0
	PartCount int64 `json:"part_count"`
	// 上传的有效期:一次上传 1 小时、分片上传 24 小时
	ExpiresAt time.Time `json:"expires_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

UploadSession 创建上传的结果

func (*UploadSession) UnmarshalJSON

func (v *UploadSession) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type UploadSessionUpload

type UploadSessionUpload struct {
	// 对象存储的预签名地址,1 小时内有效
	URL string `json:"url"`
	// PUT
	Method string `json:"method"`
	// 上传时必须带上的请求头(Content-Length)
	Headers map[string]string `json:"headers"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

UploadSessionUpload 一次上传的地址,分片上传为 null

func (UploadSessionUpload) String

func (v UploadSessionUpload) String() string

String 遮掩敏感的字段。

func (*UploadSessionUpload) UnmarshalJSON

func (v *UploadSessionUpload) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type UploadedPart

type UploadedPart struct {
	PartNumber int `json:"part_number"`
	// 字节数;除最后一片外应为 16 MB
	Size int64 `json:"size"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

UploadedPart 已上传的一个分片

func (*UploadedPart) UnmarshalJSON

func (v *UploadedPart) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type User

type User struct {
	// 用户名(小写)
	Username string `json:"username"`
	// 昵称,没有时为空字符串
	Nickname string `json:"nickname"`
	// 头像地址,没有时为空字符串
	AvatarURL string `json:"avatar_url"`
	// 自定义属性,没有时为空对象
	Attributes map[string]string `json:"attributes"`
	Status     string            `json:"status"`
	// 封禁的原因
	StatusReason *string `json:"status_reason"`
	DisabledBy   *string `json:"disabled_by"`
	// 封禁的到期时间,封禁中为 null 表示永久
	DisabledUntil *time.Time `json:"disabled_until"`
	HasPassword   bool       `json:"has_password"`
	CreatedVia    string     `json:"created_via"`
	CreatedAt     time.Time  `json:"created_at"`
	LastLoginAt   *time.Time `json:"last_login_at"`
	// 资料的版本号,从 1 开始
	Version int64 `json:"version"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

User 用户

func (*User) UnmarshalJSON

func (v *User) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type UserGroup

type UserGroup struct {
	GroupID string `json:"group_id"`
	Type    string `json:"type"`
	// 群名称,没有时为空字符串
	Name string `json:"name"`
	// 群头像地址,没有时为空字符串
	AvatarURL string `json:"avatar_url"`
	// 群简介,没有时为空字符串
	Description string `json:"description"`
	// 群公告,没有时为空字符串
	Announcement string `json:"announcement"`
	// 公告最近一次修改的时间,从未设置过为 null
	AnnouncementUpdatedAt *time.Time `json:"announcement_updated_at"`
	// 公告最近一次的修改人;服务端修改或修改人已删除时为 null
	AnnouncementUpdatedBy *string `json:"announcement_updated_by"`
	// 自定义属性,没有时为 null
	Attributes map[string]string `json:"attributes"`
	// 群主的用户名,群主已删除时为 null
	Owner *string `json:"owner"`
	// 普通成员能否邀请:直接邀请、需要审批、不能邀请
	MemberInvite string `json:"member_invite"`
	// 公开群的申请加入方式,私有群为 null
	JoinMode *string `json:"join_mode"`
	// 是否开启了全员禁言
	MuteAll bool `json:"mute_all"`
	// 实际生效的人数上限(群自己的上限、应用策略和套餐中最小的)
	MaxMembers  int    `json:"max_members"`
	MemberCount int64  `json:"member_count"`
	Status      string `json:"status"`
	// 封禁方,没有封禁时为 null
	DisabledBy *string `json:"disabled_by"`
	// 群资料的版本号
	InfoVersion int64 `json:"info_version"`
	// 成员列表的版本号
	MemberVersion int64     `json:"member_version"`
	CreatedAt     time.Time `json:"created_at"`
	// 封禁的原因,没有封禁或没有原因时为 null
	StatusReason *string `json:"status_reason"`
	// 群自己设置的人数上限,没有设置时为 null
	MaxMembersSetting *int64     `json:"max_members_setting"`
	CreatedVia        string     `json:"created_via"`
	DismissedAt       *time.Time `json:"dismissed_at"`
	// 该用户在群里的信息
	Self UserGroupSelf `json:"self"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

UserGroup 用户加入的一个群:群的全部字段,另有该用户在群里的信息 self

func (*UserGroup) UnmarshalJSON

func (v *UserGroup) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type UserGroupSelf

type UserGroupSelf struct {
	Role string `json:"role"`
	// 没有时为空字符串
	GroupNickname string `json:"group_nickname"`
	// 此刻是否被禁言
	Muted bool `json:"muted"`
	// 禁言的到期时间;没有被禁言或永久禁言时为 null
	MutedUntil *time.Time `json:"muted_until"`
	JoinedAt   time.Time  `json:"joined_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

UserGroupSelf 该用户在群里的信息

func (*UserGroupSelf) UnmarshalJSON

func (v *UserGroupSelf) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type UserMute

type UserMute struct {
	// 只在应用的禁言列表中出现
	Username string `json:"username"`
	Scope    string `json:"scope"`
	// null 为永久
	ExpiresAt *time.Time `json:"expires_at"`
	// 没有时为空字符串
	Reason string `json:"reason"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

UserMute 一项全局禁言

func (*UserMute) UnmarshalJSON

func (v *UserMute) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type UsersService

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

UsersService IM 用户:创建、查询、修改、封禁、删除,登录凭证、登录设备与全局禁言(client.Users)。

func (*UsersService) All

All 逐项遍历 List 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。

func (*UsersService) AllMuted

func (s *UsersService) AllMuted(ctx context.Context, params ListMutedParams) iter.Seq2[UserMute, error]

AllMuted 逐项遍历 ListMuted 的结果,自动翻页:按 next_cursor 是否为空判断结束,不按条数判断(一页可能为空而仍有下一页)。 出错时产出这个错误后结束,已产出的项有效。

func (*UsersService) BatchCreate

func (s *UsersService) BatchCreate(ctx context.Context, users []CreateUserParams) (*BatchCreateUsersResult, error)

BatchCreate 批量创建用户(每次最多 100 个)

逐个处理,整体返回 200;同一批中重复的用户名,后面的失败为 already_exists。失败的项没有 details。 按项数计入 OpenAPI 额度,额度不足时整个请求返回 rate_limited、任何一项都没有执行。

接口:POST /users/batch(users.batch_create)。以唯一标识创建,可以自动重试;重试后得到 already_exists 时错误的 Retried 为真,可以按“前一次尝试已经创建”处理。

func (*UsersService) BatchCreateAll

func (s *UsersService) BatchCreateAll(ctx context.Context, users []CreateUserParams) (*BatchCreateUsersResult, error)

BatchCreateAll 按上限(100 项)拆分、依次提交、合并结果;服务端以 too_many_items 给出更小的上限(应用的设置)时按它重新拆分。 某一批整体失败时停止,返回已完成部分的合并结果和那一批的错误;没有出现在结果中的项可以再提交一次。

func (*UsersService) Create

func (s *UsersService) Create(ctx context.Context, params CreateUserParams) (*User, error)

Create 创建用户

用户名已存在时返回 409 already_exists(没有返回已有的用户)。带密码的创建计入每个应用每秒 100 次的密码哈希限制; 昵称和头像经过内容安全检查,昵称可能被替换,返回的与传入的不同。只读状态下返回 app_unavailable。

接口:POST /users(users.create)。以唯一标识创建,可以自动重试;重试后得到 already_exists 时错误的 Retried 为真,可以按“前一次尝试已经创建”处理。

func (*UsersService) Delete

func (s *UsersService) Delete(ctx context.Context, username string) error

Delete 删除用户

同步删除,用户名随即可以重新使用;重复删除返回 not_found。平台封禁的用户返回 permission_denied。

接口:DELETE /users/{username}(users.delete)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*UsersService) Disable

func (s *UsersService) Disable(ctx context.Context, username string, params DisableUserParams) (*User, error)

Disable 封禁用户

重复封禁以这次的原因和时长覆盖(同样的参数重试结果相同);平台封禁的用户不变。

接口:POST /users/{username}/disable(users.disable)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*UsersService) Enable

func (s *UsersService) Enable(ctx context.Context, username string) (*User, error)

Enable 解封用户

平台封禁的用户返回 permission_denied。

接口:POST /users/{username}/enable(users.enable)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*UsersService) Get

func (s *UsersService) Get(ctx context.Context, username string) (*User, error)

Get 查询用户

接口:GET /users/{username}(users.get)。查询,网络错误、超时、5xx 时自动重试。

func (*UsersService) IssueLoginTicket

func (s *UsersService) IssueLoginTicket(ctx context.Context, username string, params IssueLoginTicketParams) (*LoginTicket, error)

IssueLoginTicket 签发登录凭证

凭证 5 分钟内有效、只能用一次。每次签发得到新的凭证、旧的仍然有效,所以重试无害,只把最后拿到的交给 App。 auto_create 为真时用户不存在则创建(只读状态下返回 app_unavailable);封禁的用户返回 user_disabled。

接口:POST /users/{username}/login-tickets(users.issue_login_ticket)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*UsersService) Kick

func (s *UsersService) Kick(ctx context.Context, username, sessionID string) error

Kick 踢掉用户的一台设备

已下线的会话也返回 204;会话不存在或不属于这个用户时返回 not_found。

接口:DELETE /users/{username}/sessions/{session_id}(users.kick)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*UsersService) KickAll

func (s *UsersService) KickAll(ctx context.Context, username string) error

KickAll 踢掉用户的全部设备

每次调用都递增用户的安全纪元,重试会把中间新登录的设备也踢掉,所以不自动重试。

接口:DELETE /users/{username}/sessions(users.kick_all)。不幂等:请求发出后不自动重试(被限流的照常等待后重发),超时后先查询结果再决定是否重试。

func (*UsersService) List

func (s *UsersService) List(ctx context.Context, params ListUsersParams) (*Page[User], error)

List 分页列出用户

接口:GET /users(users.list)。查询,网络错误、超时、5xx 时自动重试。

func (*UsersService) ListMuted

func (s *UsersService) ListMuted(ctx context.Context, params ListMutedParams) (*Page[UserMute], error)

ListMuted 分页列出应用中被全局禁言的用户

接口:GET /mutes(users.list_muted)。查询,网络错误、超时、5xx 时自动重试。

func (*UsersService) Lookup

func (s *UsersService) Lookup(ctx context.Context, usernames []string) ([]User, error)

Lookup 按用户名批量查询(每次最多 100 个,含重复的)

不存在、已删除、格式不对的用户名不出现在结果中,结果按请求的顺序。

接口:POST /users/lookup(users.lookup)。查询,网络错误、超时、5xx 时自动重试。

func (*UsersService) Mute

func (s *UsersService) Mute(ctx context.Context, username, scope string, params MuteParams) (*UserMute, error)

Mute 全局禁言用户

重复调用从现在起重新计算到期时间。

接口:PUT /users/{username}/mutes/{scope}(users.mute)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*UsersService) Mutes

func (s *UsersService) Mutes(ctx context.Context, username string) ([]UserMute, error)

Mutes 列出用户当前的全局禁言(不分页)

接口:GET /users/{username}/mutes(users.mutes)。查询,网络错误、超时、5xx 时自动重试。

func (*UsersService) Sessions

func (s *UsersService) Sessions(ctx context.Context, username string) ([]Session, error)

Sessions 列出用户的登录设备(不分页)

接口:GET /users/{username}/sessions(users.sessions)。查询,网络错误、超时、5xx 时自动重试。

func (*UsersService) SetPassword

func (s *UsersService) SetPassword(ctx context.Context, username, password string) error

SetPassword 设置密码

每次调用都递增用户的安全纪元,踢掉全部设备并作废未用的登录凭证,所以不自动重试。

接口:PUT /users/{username}/password(users.set_password)。不幂等:请求发出后不自动重试(被限流的照常等待后重发),超时后先查询结果再决定是否重试。

func (*UsersService) Unmute

func (s *UsersService) Unmute(ctx context.Context, username, scope string) error

Unmute 解除全局禁言

没有禁言时也返回 204。

接口:DELETE /users/{username}/mutes/{scope}(users.unmute)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

func (*UsersService) Update

func (s *UsersService) Update(ctx context.Context, username string, params UpdateUserParams) (*User, error)

Update 修改用户资料

只修改给出的字段;没有任何要改的字段时返回 invalid_argument。给出 version 时只有与当前版本一致才修改,否则 version_conflict。 昵称和头像经过内容安全检查。只读状态下返回 app_unavailable。

接口:PATCH /users/{username}(users.update)。本身幂等,可以自动重试;重试后得到 not_found、version_conflict 时错误的 Retried 为真。

type VersionedPage

type VersionedPage[T any] struct {
	Page[T]
	Version     int64 // friend_version、blacklist_version、member_version、settings_version
	NotModified bool
	Count       int // 好友数、黑名单人数、群成员数;推送的会话免打扰没有
	MaxCount    int // 好友列表、黑名单才有
}

VersionedPage 是带版本号的列表(好友、黑名单、群成员、推送的会话免打扰)的一页。 KnownVersion 只在第一页有效:与当前版本相同时 NotModified 为真,Items 为空、NextCursor 为空。

func (*VersionedPage[T]) UnmarshalJSON

func (p *VersionedPage[T]) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON;版本号、数量的字段名因接口而不同,由 SDK 按接口填入。

type Violation

type Violation struct {
	ViolationID string `json:"violation_id"`
	Scene       string `json:"scene"`
	Category    string `json:"category"`
	Source      string `json:"source"`
	// 违反的是租户规则还是平台规则
	Authority string    `json:"authority"`
	ItemID    *string   `json:"item_id"`
	CreatedAt time.Time `json:"created_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

Violation 一次违规

func (*Violation) UnmarshalJSON

func (v *Violation) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type ViolationsPage

type ViolationsPage struct {
	Items []Violation `json:"items"`
	// 下一页的游标,空表示没有下一页
	NextCursor string `json:"next_cursor"`
	// 当前计入的违规次数
	ViolationCount int64 `json:"violation_count"`
	// 最近 10 条处罚
	Penalties []Penalty `json:"penalties"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

ViolationsPage 一页违规记录

func (*ViolationsPage) UnmarshalJSON

func (v *ViolationsPage) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type Word

type Word struct {
	// 规范化后的词
	Word string `json:"word"`
	// 添加时的原样
	Original  string    `json:"original"`
	CreatedAt time.Time `json:"created_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

Word 词条

func (*Word) UnmarshalJSON

func (v *Word) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

type WordList

type WordList struct {
	ListID string `json:"list_id"`
	Name   string `json:"name"`
	// 屏蔽词库或放行词库
	Kind string `json:"kind"`
	// 命中时的处理,放行词库为 null
	Action    *string `json:"action"`
	MatchMode string  `json:"match_mode"`
	Category  string  `json:"category"`
	// 适用的场景,null 为全部场景
	Scenes    []string  `json:"scenes"`
	Enabled   bool      `json:"enabled"`
	WordCount int64     `json:"word_count"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
	// Raw 服务端返回的这个对象的原始 JSON;服务端新增的字段可以从中读取。
	Raw json.RawMessage `json:"-"`
}

WordList 词库

func (*WordList) UnmarshalJSON

func (v *WordList) UnmarshalJSON(b []byte) error

UnmarshalJSON 解码并保存原始 JSON。

Directories

Path Synopsis
Package callback 处理回调请求(《server-go/2.接口设计》第 9、10 节):校验签名、防重放、按事件 ID 去重、 回应 URL 验证、分派事件回调和同步回调。
Package callback 处理回调请求(《server-go/2.接口设计》第 9、10 节):校验签名、防重放、按事件 ID 去重、 回应 URL 验证、分派事件回调和同步回调。
Package drimtest 是测试辅助(《server-go/2.接口设计》第 11 节):假的 OpenAPI 服务、回调请求的构造与签名、签名的测试向量。
Package drimtest 是测试辅助(《server-go/2.接口设计》第 11 节):假的 OpenAPI 服务、回调请求的构造与签名、签名的测试向量。
examples
callbackreceiver command
示例:回调接收端。
示例:回调接收端。
importusers command
示例:从旧系统迁移用户。
示例:从旧系统迁移用户。
loginticket command
示例:业务服务端为已登录的用户签发 IM 登录凭证,交给 App 用客户端 SDK 登录(《server-go/1.功能概述文档》第 9 节)。
示例:业务服务端为已登录的用户签发 IM 登录凭证,交给 App 用客户端 SDK 登录(《server-go/1.功能概述文档》第 9 节)。
sendmessage command
示例:以业务的通知账号发单聊和群聊消息;业务单号作为 client_msg_id,业务层重试也不会重复发送。
示例:以业务的通知账号发单聊和群聊消息;业务单号作为 client_msg_id,业务层重试也不会重复发送。
Package integration 是连接真实服务端的集成测试和回调的端到端测试(《server-go/3.实现与测试》第 5 节), 带构建标签 integration:先启动 sdk/conformance/harness,再运行 go test -tags integration ./integration/。
Package integration 是连接真实服务端的集成测试和回调的端到端测试(《server-go/3.实现与测试》第 5 节), 带构建标签 integration:先启动 sdk/conformance/harness,再运行 go test -tags integration ./integration/。
internal
aistop
Package aistop 是本进程中进行中的 AI 流式回复的登记:drim.Stream 开始时登记、结束时注销, 回调处理器收到 ai.stream_stopped 时按流 ID 找到它并停止(《AI对话/3.接口设计》第 7.1 节“停止”)。
Package aistop 是本进程中进行中的 AI 流式回复的登记:drim.Stream 开始时登记、结束时注销, 回调处理器收到 ai.stream_stopped 时按流 ID 找到它并停止(《AI对话/3.接口设计》第 7.1 节“停止”)。
endpoints
Package endpoints 是每个 OpenAPI 接口的元数据(由 internal/codegen/generate.py 从 sdk/server/spec 生成): 接口名、方法、路径、请求类别、批量、分页、超时等。
Package endpoints 是每个 OpenAPI 接口的元数据(由 internal/codegen/generate.py 从 sdk/server/spec 生成): 接口名、方法、路径、请求类别、批量、分页、超时等。

Jump to

Keyboard shortcuts

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