stream_chat

package module
v4.0.1 Latest Latest
Warning

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

Go to latest
Published: Dec 23, 2021 License: BSD-3-Clause Imports: 21 Imported by: 0

README

stream-chat-go

build godoc

the official Golang API client for Stream chat a service for building chat applications.

You can sign up for a Stream account at https://getstream.io/chat/get_started/.

You can use this library to access chat API endpoints server-side, for the client-side integrations (web and mobile) have a look at the Javascript, iOS and Android SDK libraries (https://getstream.io/chat/).

Installation
go get github.com/GetStream/stream-chat-go/v4
Documentation

Official API docs

Supported features
  • Chat channels
  • Messages
  • Chat channel types
  • User management
  • Moderation API
  • Push configuration
  • User devices
  • User search
  • Channel search
  • Message search
Quickstart
package main

import (
	"os"

	stream "github.com/GetStream/stream-chat-go/v4"
)

var APIKey = os.Getenv("STREAM_CHAT_API_KEY")
var APISecret = os.Getenv("STREAM_CHAT_API_SECRET")
var userID = "" // your server user id

func main() {
	client, err := stream.NewClient(APIKey, APISecret)
	// handle error

	// use client methods

	// create channel with users
	users := []string{"id1", "id2", "id3"}
	channel, err := client.CreateChannel("messaging", "channel-id", userID, map[string]interface{}{
		"members": users,
	})

	// use channel methods
	msg, err := channel.SendMessage(&stream.Message{Text: "hello"}, userID)
}
Contributing

Contributions to this project are very much welcome, please make sure that your code changes are tested and that they follow Go best-practices. You can find some tips in CONTRIBUTING.md.

Documentation

Index

Examples

Constants

View Source
const (
	AutoModDisabled modType = "disabled"
	AutoModSimple   modType = "simple"
	AutoModAI       modType = "AI"

	ModBehaviourFlag  modBehaviour = "flag"
	ModBehaviourBlock modBehaviour = "block"

	MessageRetentionForever = "infinite"
)
View Source
const (
	PushProviderAPNS     = pushProvider("apn")
	PushProviderFirebase = pushProvider("firebase")
)
View Source
const (
	HeaderRateLimit     = "X-Ratelimit-Limit"
	HeaderRateRemaining = "X-Ratelimit-Remaining"
	HeaderRateReset     = "X-Ratelimit-Reset"
)

Variables

View Source
var DefaultChannelConfig = ChannelConfig{
	Automod:           AutoModDisabled,
	ModBehavior:       ModBehaviourFlag,
	MaxMessageLength:  defaultMessageLength,
	MessageRetention:  MessageRetentionForever,
	PushNotifications: true,
}

DefaultChannelConfig is the default channel configuration.

Functions

func MessageSkipPush

func MessageSkipPush(r *messageRequest)

MessageSkipPush is a flag that be given to SendMessage if you don't want to generate any push notifications.

func TruncateWithHardDelete

func TruncateWithHardDelete(hardDelete bool) func(*truncateOptions)

func TruncateWithMessage

func TruncateWithMessage(message *Message) func(*truncateOptions)

func TruncateWithSkipPush

func TruncateWithSkipPush(skipPush bool) func(*truncateOptions)

func TruncateWithTruncatedAt

func TruncateWithTruncatedAt(truncatedAt *time.Time) func(*truncateOptions)

func Version

func Version() string

Version returns the version of the library.

Types

type APNConfig

type APNConfig struct {
	Enabled              bool   `json:"enabled"`
	Development          bool   `json:"development"`
	AuthType             string `json:"auth_type,omitempty"`
	AuthKey              []byte `json:"auth_key,omitempty"`
	NotificationTemplate string `json:"notification_template"`
	Host                 string `json:"host,omitempty"`
	BundleID             string `json:"bundle_id,omitempty"`
	TeamID               string `json:"team_id,omitempty"`
	KeyID                string `json:"key_id,omitempty"`
}

type AppConfig

type AppConfig struct {
	Name                     string                    `json:"name"`
	OrganizationName         string                    `json:"organization"`
	WebhookURL               string                    `json:"webhook_url"`
	SuspendedExplanation     string                    `json:"suspended_explanation"`
	PushNotifications        PushNotificationFields    `json:"push_notifications"`
	ConfigNameMap            map[string]*ChannelConfig `json:"channel_configs"`
	Policies                 map[string][]Policy       `json:"policies"`
	Suspended                bool                      `json:"suspended"`
	DisableAuth              bool                      `json:"disable_auth_checks"`
	DisablePermissions       bool                      `json:"disable_permissions_checks"`
	MultiTenantEnabled       bool                      `json:"multi_tenant_enabled"`
	RevokeTokensIssuedBefore *time.Time                `json:"revoke_tokens_issued_before"`
	AsyncURLEnrichEnabled    bool                      `json:"async_url_enrich_enabled"`
}

type AppResponse

type AppResponse struct {
	App *AppConfig `json:"app"`
	Response
}

type AppSettings

type AppSettings struct {
	DisableAuth           *bool           `json:"disable_auth_checks,omitempty"`
	DisablePermissions    *bool           `json:"disable_permissions_checks,omitempty"`
	APNConfig             *APNConfig      `json:"apn_config,omitempty"`
	FirebaseConfig        *FirebaseConfig `json:"firebase_config,omitempty"`
	WebhookURL            *string         `json:"webhook_url,omitempty"`
	MultiTenantEnabled    *bool           `json:"multi_tenant_enabled,omitempty"`
	AsyncURLEnrichEnabled *bool           `json:"async_url_enrich_enabled,omitempty"`
}

func NewAppSettings

func NewAppSettings() *AppSettings

func (*AppSettings) SetAPNConfig

func (a *AppSettings) SetAPNConfig(c APNConfig) *AppSettings

func (*AppSettings) SetDisableAuth

func (a *AppSettings) SetDisableAuth(b bool) *AppSettings

func (*AppSettings) SetDisablePermissions

func (a *AppSettings) SetDisablePermissions(b bool) *AppSettings

func (*AppSettings) SetFirebaseConfig

func (a *AppSettings) SetFirebaseConfig(c FirebaseConfig) *AppSettings

func (*AppSettings) SetMultiTenant

func (a *AppSettings) SetMultiTenant(b bool) *AppSettings

func (*AppSettings) SetWebhookURL

func (a *AppSettings) SetWebhookURL(s string) *AppSettings

type AsyncTaskResponse

type AsyncTaskResponse struct {
	TaskID string `json:"task_id"`
	Response
}

type Attachment

type Attachment struct {
	Type string `json:"type,omitempty"` // text, image, audio, video

	AuthorName string `json:"author_name,omitempty"`
	Title      string `json:"title,omitempty"`
	TitleLink  string `json:"title_link,omitempty"`
	Text       string `json:"text,omitempty"`

	ImageURL    string `json:"image_url,omitempty"`
	ThumbURL    string `json:"thumb_url,omitempty"`
	AssetURL    string `json:"asset_url,omitempty"`
	OGScrapeURL string `json:"og_scrape_url,omitempty"`

	ExtraData map[string]interface{} `json:"-"`
}

func (Attachment) MarshalJSON

func (a Attachment) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Attachment) UnmarshalJSON

func (a *Attachment) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type Channel

type Channel struct {
	ID   string `json:"id"`
	Type string `json:"type"`
	CID  string `json:"cid"` // full id in format channel_type:channel_ID
	Team string `json:"team"`

	Config ChannelConfig `json:"config"`

	CreatedBy *User `json:"created_by"`
	Disabled  bool  `json:"disabled"`
	Frozen    bool  `json:"frozen"`

	MemberCount int              `json:"member_count"`
	Members     []*ChannelMember `json:"members"`

	Messages []*Message     `json:"messages"`
	Read     []*ChannelRead `json:"read"`

	CreatedAt     time.Time `json:"created_at"`
	UpdatedAt     time.Time `json:"updated_at"`
	LastMessageAt time.Time `json:"last_message_at"`

	ExtraData map[string]interface{} `json:"-"`
	// contains filtered or unexported fields
}

func (*Channel) AcceptInvite

func (ch *Channel) AcceptInvite(ctx context.Context, userID string, message *Message) (*Response, error)

func (*Channel) AddMembers

func (ch *Channel) AddMembers(ctx context.Context, userIDs []string, message *Message, options map[string]interface{}) (*Response, error)

AddMembers adds members with given user IDs to the channel. You can set a message for channel object notifications. If you want to hide history of the channel for new members, you can pass "hide_history": true to options parameter.

func (*Channel) AddModerators

func (ch *Channel) AddModerators(ctx context.Context, userIDs ...string) (*Response, error)

AddModerators adds moderators with given IDs to the channel.

Example

See https://getstream.io/chat/docs/channel_members/ for more details.

channel := &Channel{}
newModerators := []string{"bob", "sue"}

_, _ = channel.AddModerators(context.Background(), "thierry", "josh")
_, _ = channel.AddModerators(context.Background(), newModerators...)
_, _ = channel.DemoteModerators(context.Background(), newModerators...)
Output:

func (*Channel) AddModeratorsWithMessage

func (ch *Channel) AddModeratorsWithMessage(ctx context.Context, userIDs []string, msg *Message) (*Response, error)

AddModerators adds moderators with given IDs to the channel and produce system message.

func (*Channel) AssignRole

func (ch *Channel) AssignRole(ctx context.Context, assignments []*RoleAssignment, msg *Message) (*Response, error)

AssignRoles assigns roles to members with given IDs.

func (*Channel) BanUser

func (ch *Channel) BanUser(ctx context.Context, targetID, userID string, options map[string]interface{}) (*Response, error)

BanUser bans target user ID from this channel userID: user who bans target. options: additional ban options, ie {"timeout": 3600, "reason": "offensive language is not allowed here"}.

func (*Channel) Delete

func (ch *Channel) Delete(ctx context.Context) (*Response, error)

Delete removes the channel. Messages are permanently removed.

func (*Channel) DeleteFile

func (ch *Channel) DeleteFile(ctx context.Context, location string) (*Response, error)

DeleteFile removes uploaded file.

func (*Channel) DeleteImage

func (ch *Channel) DeleteImage(ctx context.Context, location string) (*Response, error)

DeleteImage removes uploaded image.

func (*Channel) DeleteReaction

func (ch *Channel) DeleteReaction(ctx context.Context, messageID, reactionType, userID string) (*ReactionResponse, error)

DeleteReaction removes a reaction from message with given ID.

func (*Channel) DemoteModerators

func (ch *Channel) DemoteModerators(ctx context.Context, userIDs ...string) (*Response, error)

DemoteModerators moderators with given IDs from the channel.

func (*Channel) DemoteModeratorsWithMessage

func (ch *Channel) DemoteModeratorsWithMessage(ctx context.Context, userIDs []string, msg *Message) (*Response, error)

DemoteModerators moderators with given IDs from the channel and produce system message.

func (*Channel) GetReactions

func (ch *Channel) GetReactions(ctx context.Context, messageID string, options map[string][]string) (*ReactionsResponse, error)

GetReactions returns list of the reactions for message with given ID. options: Pagination params, ie {"limit":{"10"}, "idlte": {"10"}}

func (*Channel) GetReplies

func (ch *Channel) GetReplies(ctx context.Context, parentID string, options map[string][]string) (*RepliesResponse, error)

GetReplies returns list of the message replies for a parent message. options: Pagination params, ie {limit:10, idlte: 10}

func (*Channel) Hide

func (ch *Channel) Hide(ctx context.Context, userID string) (*Response, error)

Hide makes channel hidden for userID.

func (*Channel) HideWithHistoryClear

func (ch *Channel) HideWithHistoryClear(ctx context.Context, userID string) (*Response, error)

HideWithHistoryClear clear marks channel as hidden and remove all messages for user.

func (*Channel) InviteMembers

func (ch *Channel) InviteMembers(ctx context.Context, userIDs ...string) (*Response, error)

InviteMembers invites users with given IDs to the channel.

func (*Channel) InviteMembersWithMessage

func (ch *Channel) InviteMembersWithMessage(ctx context.Context, userIDs []string, msg *Message) (*Response, error)

InviteMembers invites users with given IDs to the channel and produce system message.

func (*Channel) MarkRead

func (ch *Channel) MarkRead(ctx context.Context, userID string, options map[string]interface{}) (*Response, error)

MarkRead send the mark read event for user with given ID, only works if the `read_events` setting is enabled. options: additional data, ie {"messageID": last_messageID}

func (Channel) MarshalJSON

func (ch Channel) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Channel) Mute

func (ch *Channel) Mute(ctx context.Context, userID string, expiration *time.Duration) (*ChannelMuteResponse, error)

func (*Channel) PartialUpdate

func (ch *Channel) PartialUpdate(ctx context.Context, update PartialUpdate) (*Response, error)

PartialUpdate set and unset specific fields when it is necessary to retain additional custom data fields on the object. AKA a patch style update.

func (*Channel) Query

func (ch *Channel) Query(ctx context.Context, data map[string]interface{}) (*Response, error)

Query fills channel info with state (messages, members, reads).

func (*Channel) QueryMembers

func (ch *Channel) QueryMembers(ctx context.Context, q *QueryOption, sorters ...*SortOption) (*QueryMembersResponse, error)

QueryMembers queries members of a channel.

func (*Channel) RejectInvite

func (ch *Channel) RejectInvite(ctx context.Context, userID string, message *Message) (*Response, error)

func (*Channel) RemoveMembers

func (ch *Channel) RemoveMembers(ctx context.Context, userIDs []string, message *Message) (*Response, error)

RemoveMembers deletes members with given IDs from the channel.

func (*Channel) RemoveShadowBan

func (ch *Channel) RemoveShadowBan(ctx context.Context, userID string) (*Response, error)

RemoveShadowBan removes the shadow ban for target user ID on this channel.

func (*Channel) SendAction

func (ch *Channel) SendAction(ctx context.Context, msgID string, formData map[string]string) (*MessageResponse, error)

SendAction for a message.

func (*Channel) SendEvent

func (ch *Channel) SendEvent(ctx context.Context, event *Event, userID string) (*Response, error)

SendEvent sends an event on this channel.

func (*Channel) SendFile

func (ch *Channel) SendFile(ctx context.Context, request SendFileRequest) (*SendFileResponse, error)

SendFile sends file to the channel. Returns file url or error.

func (*Channel) SendImage

func (ch *Channel) SendImage(ctx context.Context, request SendFileRequest) (*SendFileResponse, error)

SendFile sends image to the channel. Returns file url or error.

func (*Channel) SendMessage

func (ch *Channel) SendMessage(ctx context.Context, message *Message, userID string, options ...SendMessageOption) (*MessageResponse, error)

SendMessage sends a message to the channel. Returns full message details from server.

func (*Channel) SendReaction

func (ch *Channel) SendReaction(ctx context.Context, reaction *Reaction, messageID, userID string) (*ReactionResponse, error)

SendReaction sends a reaction to message with given ID.

Example
channel := &Channel{}
msgID := "123"
userID := "bob-1"

reaction := &Reaction{
	Type:      "love",
	ExtraData: map[string]interface{}{"my_custom_field": 123},
}
_, err := channel.SendReaction(context.Background(), reaction, msgID, userID)
if err != nil {
	log.Fatalf("Found Error: %v", err)
}
Output:

func (*Channel) ShadowBan

func (ch *Channel) ShadowBan(ctx context.Context, userID, bannedByID string, options map[string]interface{}) (*Response, error)

ShadowBan shadow bans userID from this channel bannedByID: user who shadow bans userID. options: additional shadow ban options, ie {"timeout": 3600, "reason": "offensive language is not allowed here"}.

func (*Channel) Show

func (ch *Channel) Show(ctx context.Context, userID string) (*Response, error)

Show makes channel visible for userID.

func (*Channel) Truncate

func (ch *Channel) Truncate(ctx context.Context, options ...TruncateOption) (*Response, error)

Truncate removes all messages from the channel. You can pass in options such as hard_delete, skip_push or a custom message.

func (*Channel) UnBanUser

func (ch *Channel) UnBanUser(ctx context.Context, targetID string, options map[string]string) (*Response, error)

UnBanUser removes the ban for target user ID on this channel.

func (*Channel) UnmarshalJSON

func (ch *Channel) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*Channel) Unmute

func (ch *Channel) Unmute(ctx context.Context, userID string) (*Response, error)

func (*Channel) Update

func (ch *Channel) Update(ctx context.Context, properties map[string]interface{}, message *Message) (*Response, error)

Update edits the channel's custom properties.

properties: the object to update the custom properties of this channel with message: optional update message

Example
// https://getstream.io/chat/docs/channel_permissions/?language=python
client := &Client{}

data := map[string]interface{}{
	"image":      "https://path/to/image",
	"created_by": "elon",
	"roles":      map[string]string{"elon": "admin", "gwynne": "moderator"},
}

spacexChannel := client.Channel("team", "spacex")
if _, err := spacexChannel.Update(context.Background(), data, nil); err != nil {
	log.Fatalf("Error: %v", err)
}
Output:

type ChannelConfig

type ChannelConfig struct {
	Name string `json:"name"`

	// features
	// show typing indicators or not (probably auto disable if more than X users in a channel)
	TypingEvents bool `json:"typing_events"`
	// store who has read the message, or at least when they last viewed the chat
	ReadEvents bool `json:"read_events"`
	// connect events can get very noisy for larger chat groups
	ConnectEvents bool `json:"connect_events"`
	// make messages searchable
	Search    bool `json:"search"`
	Reactions bool `json:"reactions"`
	Replies   bool `json:"replies"`
	Mutes     bool `json:"mutes"`
	// enable/disable push notifications
	PushNotifications bool `json:"push_notifications"`
	Uploads           bool `json:"uploads"`
	URLEnrichment     bool `json:"url_enrichment"`
	CustomEvents      bool `json:"custom_events"`

	// number of days to keep messages, must be MessageRetentionForever or numeric string
	MessageRetention string `json:"message_retention"`
	MaxMessageLength int    `json:"max_message_length"`

	Automod     modType      `json:"automod"` // disabled, simple or AI
	ModBehavior modBehaviour `json:"automod_behavior"`

	BlockList         string       `json:"blocklist"`
	BlockListBehavior modBehaviour `json:"blocklist_behavior"`
	AutomodThresholds *Thresholds  `json:"automod_thresholds"`
}

ChannelConfig is the configuration for a channel.

type ChannelMember

type ChannelMember struct {
	UserID      string `json:"user_id,omitempty"`
	User        *User  `json:"user,omitempty"`
	IsModerator bool   `json:"is_moderator,omitempty"`

	Invited          bool       `json:"invited,omitempty"`
	InviteAcceptedAt *time.Time `json:"invite_accepted_at,omitempty"`
	InviteRejectedAt *time.Time `json:"invite_rejected_at,omitempty"`
	Role             string     `json:"role,omitempty"`

	CreatedAt time.Time `json:"created_at,omitempty"`
	UpdatedAt time.Time `json:"updated_at,omitempty"`
}

type ChannelMute

type ChannelMute struct {
	User      User       `json:"user"`
	Channel   Channel    `json:"channel"`
	Expires   *time.Time `json:"expires"`
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
}

ChannelMute represents a channel mute.

type ChannelMuteResponse

type ChannelMuteResponse struct {
	ChannelMute ChannelMute `json:"channel_mute"`
	Response
}

type ChannelRead

type ChannelRead struct {
	User     *User     `json:"user"`
	LastRead time.Time `json:"last_read"`
}

type ChannelType

type ChannelType struct {
	ChannelConfig

	Commands []*Command `json:"commands"`
	// Deprecated: Use Permissions V2 API instead,
	// that can be found in permission_client.go.
	// See https://getstream.io/chat/docs/go-golang/migrating_from_legacy/?language=go
	Permissions []*ChannelTypePermission `json:"permissions"`

	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

func NewChannelType

func NewChannelType(name string) *ChannelType

NewChannelType returns initialized ChannelType with default values.

type ChannelTypePermission

type ChannelTypePermission struct {
	Name   string `json:"name"`   // required
	Action string `json:"action"` // one of: Deny Allow

	Resources []string `json:"resources"` // required
	Roles     []string `json:"roles"`
	Owner     bool     `json:"owner"`
	Priority  int      `json:"priority"` // required
}

type ChannelTypeResponse

type ChannelTypeResponse struct {
	*ChannelType

	Commands []string `json:"commands"`

	CreatedAt time.Time `json:"-"`
	UpdatedAt time.Time `json:"-"`

	Response
}

type ChannelTypesResponse

type ChannelTypesResponse struct {
	ChannelTypes map[string]*ChannelType `json:"channel_types"`
	Response
}

type Client

type Client struct {
	BaseURL string
	HTTP    *http.Client `json:"-"`
	// contains filtered or unexported fields
}

func NewClient

func NewClient(apiKey, apiSecret string) (*Client, error)

NewClient creates new stream chat api client.

func (*Client) AddDevice

func (c *Client) AddDevice(ctx context.Context, device *Device) (*Response, error)

AddDevice adds new device.

Example
client, _ := NewClient("XXXX", "XXXX")

_, _ = client.AddDevice(context.Background(), &Device{
	ID:           "2ffca4ad6599adc9b5202d15a5286d33c19547d472cd09de44219cda5ac30207",
	UserID:       "elon",
	PushProvider: PushProviderAPNS,
})
Output:

func (*Client) BanUser

func (c *Client) BanUser(ctx context.Context, targetID, userID string, options map[string]interface{}) (*Response, error)
Example
client, _ := NewClient("XXXX", "XXXX")

// ban a user for 60 minutes from all channel
_, _ = client.BanUser(context.Background(), "eviluser", "modUser",
	map[string]interface{}{"timeout": 60, "reason": "Banned for one hour"})

// ban a user from the livestream:fortnite channel
channel := client.Channel("livestream", "fortnite")
_, _ = channel.BanUser(context.Background(), "eviluser", "modUser",
	map[string]interface{}{"reason": "Profanity is not allowed here"})

// remove ban from channel
channel = client.Channel("livestream", "fortnite")
_, _ = channel.UnBanUser(context.Background(), "eviluser", nil)

// remove global ban
_, _ = client.UnBanUser(context.Background(), "eviluser", nil)
Output:

func (*Client) Channel

func (c *Client) Channel(channelType, channelID string) *Channel

Channel returns a Channel object for future API calls.

func (*Client) CreateChannel

func (c *Client) CreateChannel(ctx context.Context, chanType, chanID, userID string, data map[string]interface{}) (*CreateChannelResponse, error)

CreateChannel creates new channel of given type and id or returns already created one.

func (*Client) CreateChannelType

func (c *Client) CreateChannelType(ctx context.Context, chType *ChannelType) (*ChannelTypeResponse, error)

CreateChannelType adds new channel type.

Example

See https://getstream.io/chat/docs/channel_features/ for more details.

client := &Client{}

newChannelType := &ChannelType{
	// Copy the default settings.
	ChannelConfig: DefaultChannelConfig,
}

newChannelType.Name = "public"
newChannelType.Mutes = false
newChannelType.Reactions = false
newChannelType.Permissions = append(newChannelType.Permissions,
	&ChannelTypePermission{
		Name:      "Allow reads for all",
		Priority:  999,
		Resources: []string{"ReadChannel", "CreateMessage"},
		Action:    "Allow",
	},
	&ChannelTypePermission{
		Name:      "Deny all",
		Priority:  1,
		Resources: []string{"*"},
		Action:    "Deny",
	},
)

_, _ = client.CreateChannelType(context.Background(), newChannelType)
Output:

func (*Client) CreateCommand

func (c *Client) CreateCommand(ctx context.Context, cmd *Command) (*CommandResponse, error)

CreateCommand registers a new custom command.

Example

See https://getstream.io/chat/docs/custom_commands/ for more details.

client := &Client{}

newCommand := &Command{
	Name:        "my-command",
	Description: "my command",
	Args:        "[@username]",
	Set:         "custom_cmd_set",
}

_, _ = client.CreateCommand(context.Background(), newCommand)
Output:

func (*Client) CreateToken

func (c *Client) CreateToken(userID string, expire time.Time, issuedAt ...time.Time) (string, error)

CreateToken creates a new token for user with optional expire time. Zero time is assumed to be no expire.

func (*Client) DeactivateUser

func (c *Client) DeactivateUser(ctx context.Context, targetID string, options map[string]interface{}) (*Response, error)
Example
client, _ := NewClient("XXXX", "XXXX")

_, _ = client.DeactivateUser(context.Background(), "userID", nil)
Output:

func (*Client) DeleteChannelType

func (c *Client) DeleteChannelType(ctx context.Context, name string) (*Response, error)
Example
client := &Client{}

_, _ = client.DeleteChannelType(context.Background(), "public")
Output:

func (*Client) DeleteChannels

func (c *Client) DeleteChannels(ctx context.Context, cids []string, hardDelete bool) (*AsyncTaskResponse, error)

DeleteChannels deletes channels asynchronously. Channels and messages will be hard deleted if hardDelete is true. It returns an AsyncTaskResponse object which contains the task ID, the status of the task can be check with client.GetTask method.

func (*Client) DeleteCommand

func (c *Client) DeleteCommand(ctx context.Context, cmdName string) (*Response, error)

DeleteCommand deletes a custom command referenced by cmdName.

Example
client := &Client{}

_, _ = client.DeleteCommand(context.Background(), "my-command")
Output:

func (*Client) DeleteDevice

func (c *Client) DeleteDevice(ctx context.Context, userID, deviceID string) (*Response, error)

DeleteDevice deletes a device from the user.

Example
client, _ := NewClient("XXXX", "XXXX")

deviceID := "2ffca4ad6599adc9b5202d15a5286d33c19547d472cd09de44219cda5ac30207"
userID := "elon"
_, _ = client.DeleteDevice(context.Background(), userID, deviceID)
Output:

func (*Client) DeleteMessage

func (c *Client) DeleteMessage(ctx context.Context, msgID string) (*Response, error)

func (*Client) DeleteUser

func (c *Client) DeleteUser(ctx context.Context, targetID string, options map[string][]string) (*Response, error)
Example
client, _ := NewClient("XXXX", "XXXX")

_, _ = client.DeleteUser(context.Background(), "userID", nil)
Output:

Example (Hard)
client, _ := NewClient("XXXX", "XXXX")

options := map[string][]string{
	"mark_messages_deleted": {"true"},
	"hard_delete":           {"true"},
}

_, _ = client.DeleteUser(context.Background(), "userID", options)
Output:

func (*Client) DeleteUsers

func (c *Client) DeleteUsers(ctx context.Context, userIDs []string, options DeleteUserOptions) (*AsyncTaskResponse, error)

DeleteUsers deletes users asynchronously. User will be deleted either "hard" or "soft" Conversations (1to1 channels) will be deleted if either "hard" or "soft" Messages will be deleted if either "hard" or "soft" NewChannelOwnerID any channels owned by the hard-deleted user will be transferred to this user ID It returns an AsyncTaskResponse object which contains the task ID, the status of the task can be check with client.GetTask method.

func (*Client) ExportChannels

func (c *Client) ExportChannels(ctx context.Context, channels []*ExportableChannel, clearDeletedMessageText, includeTruncatedMessages *bool) (*AsyncTaskResponse, error)

ExportChannels requests an asynchronous export of the provided channels. It returns an AsyncTaskResponse object which contains the task ID, the status of the task can be check with client.GetTask method.

func (*Client) ExportUser

func (c *Client) ExportUser(ctx context.Context, targetID string, options map[string][]string) (*ExportUserResponse, error)
Example
client, _ := NewClient("XXXX", "XXXX")

user, _ := client.ExportUser(context.Background(), "userID", nil)
log.Printf("%#v", user)
Output:

func (*Client) FlagMessage

func (c *Client) FlagMessage(ctx context.Context, msgID, userID string) (*Response, error)

func (*Client) FlagUser

func (c *Client) FlagUser(ctx context.Context, targetID string, options map[string]interface{}) (*Response, error)

func (*Client) GetAppConfig

func (c *Client) GetAppConfig(ctx context.Context) (*AppResponse, error)

GetAppConfig returns app settings.

func (*Client) GetChannelType

func (c *Client) GetChannelType(ctx context.Context, chanType string) (*GetChannelTypeResponse, error)

GetChannelType returns information about channel type.

Example
client := &Client{}
_, _ = client.GetChannelType(context.Background(), "public")
Output:

func (*Client) GetCommand

func (c *Client) GetCommand(ctx context.Context, cmdName string) (*GetCommandResponse, error)

GetCommand retrieves a custom command referenced by cmdName.

Example
client := &Client{}
_, _ = client.GetCommand(context.Background(), "my-command")
Output:

func (*Client) GetDevices

func (c *Client) GetDevices(ctx context.Context, userID string) (*DevicesResponse, error)

GetDevices retrieves the list of devices for user.

func (*Client) GetExportChannelsTask

func (c *Client) GetExportChannelsTask(ctx context.Context, taskID string) (*TaskResponse, error)

GetExportChannelsTask returns current state of the export task.

func (*Client) GetMessage

func (c *Client) GetMessage(ctx context.Context, msgID string) (*MessageResponse, error)

GetMessage returns message by ID.

func (*Client) GetRateLimits

func (c *Client) GetRateLimits(ctx context.Context, options ...GetRateLimitsOption) (GetRateLimitsResponse, error)

GetRateLimits returns the current rate limit quotas and usage. If no options are passed, all the limits for all platforms are returned.

func (*Client) GetTask

func (c *Client) GetTask(ctx context.Context, id string) (*TaskResponse, error)

GetTask returns the status of a task that has been ran asynchronously.

func (*Client) HardDeleteMessage

func (c *Client) HardDeleteMessage(ctx context.Context, msgID string) (*Response, error)

func (*Client) ListChannelTypes

func (c *Client) ListChannelTypes(ctx context.Context) (*ChannelTypesResponse, error)

ListChannelTypes returns all channel types.

Example
client := &Client{}
_, _ = client.ListChannelTypes(context.Background())
Output:

func (*Client) ListCommands

func (c *Client) ListCommands(ctx context.Context) (*CommandsResponse, error)

ListCommands returns a list of custom commands.

Example
client := &Client{}
_, _ = client.ListCommands(context.Background())
Output:

func (*Client) MarkAllRead

func (c *Client) MarkAllRead(ctx context.Context, userID string) (*Response, error)

MarkAllRead marks all messages as read for userID.

func (*Client) MuteUser

func (c *Client) MuteUser(ctx context.Context, targetID, userID string, options map[string]interface{}) (*Response, error)

MuteUser creates a mute. targetID: the user getting muted. userID: the user is muting the target.

func (*Client) MuteUsers

func (c *Client) MuteUsers(ctx context.Context, targetIDs []string, userID string, options map[string]interface{}) (*Response, error)

MuteUsers creates mutes for multiple users. targetIDs: the users getting muted. userID: the user is muting the target.

func (*Client) PartialUpdateMessage

func (c *Client) PartialUpdateMessage(ctx context.Context, messageID string, updates PartialUpdate, options map[string]interface{}) (*MessageResponse, error)

PartialUpdateMessage partially updates message with given msgID. options["skip_enrich_url"] do not try to enrich the URLs within message.

func (*Client) PartialUpdateUser

func (c *Client) PartialUpdateUser(ctx context.Context, update PartialUserUpdate) (*User, error)

PartialUpdateUser makes partial update for single user.

func (*Client) PartialUpdateUsers

func (c *Client) PartialUpdateUsers(ctx context.Context, updates []PartialUserUpdate) (*UsersResponse, error)

PartialUpdateUsers makes partial update for users.

func (*Client) Permissions

func (c *Client) Permissions() *PermissionClient

Permissions returns a client for handling app permissions.

func (*Client) PinMessage

func (c *Client) PinMessage(ctx context.Context, msgID, pinnedByID string, expiration *time.Time) (*MessageResponse, error)

PinMessage pins the message with given msgID.

func (*Client) QueryChannels

func (c *Client) QueryChannels(ctx context.Context, q *QueryOption, sort ...*SortOption) (*QueryChannelsResponse, error)

QueryChannels returns list of channels with members and messages, that match QueryOption. If any number of SortOption are set, result will be sorted by field and direction in oder of sort options.

func (*Client) QueryMessageFlags

func (c *Client) QueryMessageFlags(ctx context.Context, q *QueryOption) (*QueryMessageFlagsResponse, error)

QueryMessageFlags returns list of message flags that match QueryOption.

func (*Client) QueryUsers

func (c *Client) QueryUsers(ctx context.Context, q *QueryOption, sorters ...*SortOption) (*QueryUsersResponse, error)

QueryUsers returns list of users that match QueryOption. If any number of SortOption are set, result will be sorted by field and direction in the order of sort options.

func (*Client) ReactivateUser

func (c *Client) ReactivateUser(ctx context.Context, targetID string, options map[string]interface{}) (*Response, error)
Example
client, _ := NewClient("XXXX", "XXXX")

_, _ = client.ReactivateUser(context.Background(), "userID", nil)
Output:

func (*Client) RemoveShadowBan

func (c *Client) RemoveShadowBan(ctx context.Context, userID string, options map[string]string) (*Response, error)

RemoveShadowBan removes the ban for userID.

func (*Client) RevokeTokens

func (c *Client) RevokeTokens(ctx context.Context, before *time.Time) (*Response, error)

RevokeTokens revokes all tokens for an application issued before given time.

func (*Client) RevokeUserToken

func (c *Client) RevokeUserToken(ctx context.Context, userID string, before *time.Time) (*Response, error)

RevokeUserToken revoke token for a user issued before given time.

func (*Client) RevokeUsersTokens

func (c *Client) RevokeUsersTokens(ctx context.Context, userIDs []string, before *time.Time) (*Response, error)

RevokeUsersTokens revoke tokens for users issued before given time.

func (*Client) Search

func (c *Client) Search(ctx context.Context, request SearchRequest) (*SearchResponse, error)

Search returns messages matching for given keyword.

func (*Client) SearchWithFullResponse

func (c *Client) SearchWithFullResponse(ctx context.Context, request SearchRequest) (*SearchFullResponse, error)

SearchWithFullResponse performs a search and returns the full results.

func (*Client) SendUserCustomEvent

func (c *Client) SendUserCustomEvent(ctx context.Context, targetUserID string, event *UserCustomEvent) (*Response, error)

SendUserCustomEvent sends a custom event to all connected clients for the target user id.

func (*Client) ShadowBan

func (c *Client) ShadowBan(ctx context.Context, userID, bannedByID string, options map[string]interface{}) (*Response, error)

ShadowBan shadow bans userID bannedByID: user who shadow bans userID. options: additional shadow ban options, ie {"timeout": 3600, "reason": "offensive language is not allowed here"}.

func (*Client) UnBanUser

func (c *Client) UnBanUser(ctx context.Context, targetID string, options map[string]string) (*Response, error)

func (*Client) UnPinMessage

func (c *Client) UnPinMessage(ctx context.Context, msgID, userID string) (*MessageResponse, error)

UnPinMessage unpins the message with given msgID.

func (*Client) UnmuteUser

func (c *Client) UnmuteUser(ctx context.Context, targetID, userID string) (*Response, error)

UnmuteUser removes a mute. targetID: the user is getting un-muted. userID: the user is muting the target.

func (*Client) UnmuteUsers

func (c *Client) UnmuteUsers(ctx context.Context, targetIDs []string, userID string) (*Response, error)

UnmuteUsers removes a mute. targetID: the users are getting un-muted. userID: the user is muting the target.

func (*Client) UpdateAppSettings

func (c *Client) UpdateAppSettings(ctx context.Context, settings *AppSettings) (*Response, error)

UpdateAppSettings makes request to update app settings Example of usage:

settings := NewAppSettings().SetDisableAuth(true)
err := client.UpdateAppSettings(settings)
Example (Disable_auth)

See https://getstream.io/chat/docs/app_settings_auth/ for more details.

client, err := NewClient("XXXXXXXXXXXX", "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
if err != nil {
	log.Fatalf("Err: %v", err)
}

// disable auth checks, allows dev token usage
settings := NewAppSettings().SetDisableAuth(true)
_, err = client.UpdateAppSettings(context.Background(), settings)
if err != nil {
	log.Fatalf("Err: %v", err)
}

// re-enable auth checks
_, err = client.UpdateAppSettings(context.Background(), NewAppSettings().SetDisableAuth(false))
if err != nil {
	log.Fatalf("Err: %v", err)
}
Output:

Example (Disable_permission)
client, err := NewClient("XXXX", "XXXX")
if err != nil {
	log.Fatalf("Err: %v", err)
}

// disable permission checkse
settings := NewAppSettings().SetDisablePermissions(true)
_, err = client.UpdateAppSettings(context.Background(), settings)
if err != nil {
	log.Fatalf("Err: %v", err)
}

// re-enable permission checks
_, err = client.UpdateAppSettings(context.Background(), NewAppSettings().SetDisablePermissions(false))
if err != nil {
	log.Fatalf("Err: %v", err)
}
Output:

func (*Client) UpdateChannelType

func (c *Client) UpdateChannelType(ctx context.Context, name string, options map[string]interface{}) (*Response, error)
Example
client := &Client{}

_, _ = client.UpdateChannelType(context.Background(), "public", map[string]interface{}{
	"permissions": []map[string]interface{}{
		{
			"name":      "Allow reads for all",
			"priority":  999,
			"resources": []string{"ReadChannel", "CreateMessage"},
			"role":      "*",
			"action":    "Allow",
		},
		{
			"name":      "Deny all",
			"priority":  1,
			"resources": []string{"*"},
			"role":      "*",
			"action":    "Deny",
		},
	},
	"replies":  false,
	"commands": []string{"all"},
})
Output:

Example (Bool)
client := &Client{}

_, _ = client.UpdateChannelType(context.Background(), "public", map[string]interface{}{
	"typing_events":  false,
	"read_events":    true,
	"connect_events": true,
	"search":         false,
	"reactions":      true,
	"replies":        false,
	"mutes":          true,
})
Output:

Example (Other)
client := &Client{}

_, _ = client.UpdateChannelType(context.Background(),
	"public",
	map[string]interface{}{
		"automod":            "disabled",
		"message_retention":  "7",
		"max_message_length": 140,
		"commands":           []interface{}{"ban", "unban"},
	},
)
Output:

Example (Permissions)
client := &Client{}

_, _ = client.UpdateChannelType(context.Background(),
	"public",
	map[string]interface{}{
		"permissions": []map[string]interface{}{
			{
				"name":      "Allow reads for all",
				"priority":  999,
				"resources": []string{"ReadChannel", "CreateMessage"},
				"role":      "*",
				"action":    "Allow",
			},
			{
				"name":      "Deny all",
				"priority":  1,
				"resources": []string{"*"},
				"action":    "Deny",
			},
		},
	},
)
Output:

func (*Client) UpdateCommand

func (c *Client) UpdateCommand(ctx context.Context, cmdName string, options map[string]interface{}) (*CommandResponse, error)

UpdateCommand updates a custom command referenced by cmdName.

Example
client := &Client{}

_, _ = client.UpdateCommand(context.Background(), "my-command", map[string]interface{}{
	"description": "updated description",
})
Output:

func (*Client) UpdateMessage

func (c *Client) UpdateMessage(ctx context.Context, msg *Message, msgID string) (*MessageResponse, error)

UpdateMessage updates message with given msgID.

func (*Client) UpsertUser

func (c *Client) UpsertUser(ctx context.Context, user *User) (*UpsertUserResponse, error)

UpsertUser is a single user version of UpsertUsers for convenience.

Example
client, _ := NewClient("XXXX", "XXXX")

_, err := client.UpsertUser(context.Background(), &User{
	ID:   "tommaso",
	Name: "Tommaso",
	Role: "Admin",
})
if err != nil {
	log.Fatalf("Err: %v", err)
}
Output:

func (*Client) UpsertUsers

func (c *Client) UpsertUsers(ctx context.Context, users ...*User) (*UsersResponse, error)

UpsertUsers creates the given users. If a user doesn't exist, it will be created. Otherwise, custom data will be extended or updated. Missing data is never removed.

func (*Client) VerifyWebhook

func (c *Client) VerifyWebhook(body, signature []byte) (valid bool)

VerifyWebhook validates if hmac signature is correct for message body.

type Command

type Command struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Args        string `json:"args"`
	Set         string `json:"set"`
}

Command represents a custom command.

type CommandResponse

type CommandResponse struct {
	Command *Command `json:"command"`
	Response
}

CommandResponse represents an API response containing one Command.

type CommandsResponse

type CommandsResponse struct {
	Commands []*Command
}

CommandsResponse represents an API response containing a list of Command.

type CreateChannelResponse

type CreateChannelResponse struct {
	Channel *Channel
	*Response
}

type DeleteType

type DeleteType string
const (
	HardDelete DeleteType = "hard"
	SoftDelete DeleteType = "soft"
)

type DeleteUserOptions

type DeleteUserOptions struct {
	User              DeleteType `json:"user"`
	Messages          DeleteType `json:"messages,omitempty"`
	Conversations     DeleteType `json:"conversations,omitempty"`
	NewChannelOwnerID string     `json:"new_channel_owner_id,omitempty"`
}

type Device

type Device struct {
	ID           string       `json:"id"`            // The device ID.
	UserID       string       `json:"user_id"`       // The user ID for this device.
	PushProvider pushProvider `json:"push_provider"` // The push provider for this device. One of constants PushProvider*
}

type DevicesResponse

type DevicesResponse struct {
	Devices []*Device `json:"devices"`
	Response
}

type Error

type Error struct {
	Code            int               `json:"code"`
	Message         string            `json:"message"`
	ExceptionFields map[string]string `json:"exception_fields,omitempty"`
	StatusCode      int               `json:"StatusCode"`
	Duration        string            `json:"duration"`
	MoreInfo        string            `json:"more_info"`

	RateLimit *RateLimitInfo `json:"-"`
}

func (Error) Error

func (e Error) Error() string

type Event

type Event struct {
	CID          string           `json:"cid,omitempty"` // Channel ID
	Type         EventType        `json:"type"`          // Event type, one of Event* constants
	Message      *Message         `json:"message,omitempty"`
	Reaction     *Reaction        `json:"reaction,omitempty"`
	Channel      *Channel         `json:"channel,omitempty"`
	Member       *ChannelMember   `json:"member,omitempty"`
	Members      []*ChannelMember `json:"members,omitempty"`
	User         *User            `json:"user,omitempty"`
	UserID       string           `json:"user_id,omitempty"`
	OwnUser      *User            `json:"me,omitempty"`
	WatcherCount int              `json:"watcher_count,omitempty"`

	ExtraData map[string]interface{} `json:"-"`

	CreatedAt time.Time `json:"created_at,omitempty"`
}

Event is received from a webhook, or sent with the SendEvent function.

func (Event) MarshalJSON

func (e Event) MarshalJSON() ([]byte, error)

func (*Event) UnmarshalJSON

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

type EventType

type EventType string

EventType marks which of the various sub-types of a webhook event you are receiving or sending.

const (
	// EventMessageNew is fired when a new message is added.
	EventMessageNew EventType = "message.new"
	// EventMessageUpdated is fired when a message is updated.
	EventMessageUpdated EventType = "message.updated"
	// EventMessageDeleted is fired when a message is deleted.
	EventMessageDeleted EventType = "message.deleted"
	// EventMessageRead is fired when a user calls mark as read.
	EventMessageRead EventType = "message.read"

	// EventReactionNew is fired when a message reaction is added.
	EventReactionNew EventType = "reaction.new"
	// EventReactionDeleted is fired when a message reaction deleted.
	EventReactionDeleted EventType = "reaction.deleted"

	// EventMemberAdded is fired when a member is added to a channel.
	EventMemberAdded EventType = "member.added"
	// EventMemberUpdated is fired when a member is updated.
	EventMemberUpdated EventType = "member.updated"
	// EventMemberRemoved is fired when a member is removed from a channel.
	EventMemberRemoved EventType = "member.removed"

	// EventChannelCreated is fired when a channel is created.
	EventChannelCreated EventType = "channel.created"
	// EventChannelUpdated is fired when a channel is updated.
	EventChannelUpdated EventType = "channel.updated"
	// EventChannelDeleted is fired when a channel is deleted.
	EventChannelDeleted EventType = "channel.deleted"
	// EventChannelTruncated is fired when a channel is truncated.
	EventChannelTruncated EventType = "channel.truncated"

	// EventHealthCheck is fired when a user is updated.
	EventHealthCheck EventType = "health.check"

	// EventNotificationNewMessage and family are fired when a notification is
	// created, marked read, invited to a channel, and so on.
	EventNotificationNewMessage         EventType = "notification.message_new"
	EventNotificationMarkRead           EventType = "notification.mark_read"
	EventNotificationInvited            EventType = "notification.invited"
	EventNotificationInviteAccepted     EventType = "notification.invite_accepted"
	EventNotificationAddedToChannel     EventType = "notification.added_to_channel"
	EventNotificationRemovedFromChannel EventType = "notification.removed_from_channel"
	EventNotificationMutesUpdated       EventType = "notification.mutes_updated"

	// EventTypingStart and EventTypingStop are fired when a user starts or stops typing.
	EventTypingStart EventType = "typing.start"
	EventTypingStop  EventType = "typing.stop"

	// EventUserMuted is fired when a user is muted.
	EventUserMuted EventType = "user.muted"
	// EventUserUnmuted is fired when a user is unmuted.
	EventUserUnmuted         EventType = "user.unmuted"
	EventUserPresenceChanged EventType = "user.presence.changed"
	EventUserWatchingStart   EventType = "user.watching.start"
	EventUserWatchingStop    EventType = "user.watching.stop"
	EventUserUpdated         EventType = "user.updated"
)

type ExportUserResponse

type ExportUserResponse struct {
	*User
	Response
}

type ExportableChannel

type ExportableChannel struct {
	Type          string     `json:"type"`
	ID            string     `json:"id"`
	MessagesSince *time.Time `json:"messages_since,omitempty"`
	MessagesUntil *time.Time `json:"messages_until,omitempty"`
}

type FirebaseConfig

type FirebaseConfig struct {
	Enabled              bool   `json:"enabled"`
	ServerKey            string `json:"server_key"`
	NotificationTemplate string `json:"notification_template,omitempty"`
	DataTemplate         string `json:"data_template,omitempty"`
}

type GetChannelTypeResponse

type GetChannelTypeResponse struct {
	*ChannelType
	Response
}

type GetCommandResponse

type GetCommandResponse struct {
	*Command
	Response
}

type GetPermissionResponse

type GetPermissionResponse struct {
	Permission *Permission `json:"permission"`
	Response
}

type GetRateLimitsOption

type GetRateLimitsOption func(p *getRateLimitsParams)

GetRateLimitsOption configures the Client.GetRateLimits call.

func WithAndroid

func WithAndroid() GetRateLimitsOption

WithAndroid restricts the returned limits to Android clients only.

func WithEndpoints

func WithEndpoints(endpoints ...string) GetRateLimitsOption

WithEndpoints restricts the returned limits info to the specified endpoints.

func WithIOS

func WithIOS() GetRateLimitsOption

WithIOS restricts the returned limits to iOS clients only.

func WithServerSide

func WithServerSide() GetRateLimitsOption

WithServerSide restricts the returned limits to server-side clients only.

func WithWeb

func WithWeb() GetRateLimitsOption

WithWeb restricts the returned limits to web clients only.

type GetRateLimitsResponse

type GetRateLimitsResponse struct {
	ServerSide RateLimitsMap `json:"server_side,omitempty"`
	Android    RateLimitsMap `json:"android,omitempty"`
	IOS        RateLimitsMap `json:"ios,omitempty"`
	Web        RateLimitsMap `json:"web,omitempty"`
}

GetRateLimitsResponse is the response of the Client.GetRateLimits call. It includes, if present, the rate limits for the supported platforms, namely server-side, Android, iOS, and web.

type LabelThresholds

type LabelThresholds struct {
	Flag  float32 `json:"flag"`
	Block float32 `json:"block"`
}

type ListPermissionsResponse

type ListPermissionsResponse struct {
	Permissions []*Permission `json:"permissions"`
	Response
}

type Message

type Message struct {
	ID string `json:"id"`

	Text string `json:"text"`
	HTML string `json:"html"`

	Type   MessageType `json:"type,omitempty"` // one of MessageType* constants
	Silent bool        `json:"silent,omitempty"`

	User            *User          `json:"user"`
	Attachments     []*Attachment  `json:"attachments"`
	LatestReactions []*Reaction    `json:"latest_reactions"` // last reactions
	OwnReactions    []*Reaction    `json:"own_reactions"`
	ReactionCounts  map[string]int `json:"reaction_counts"`

	ParentID      string `json:"parent_id"`       // id of parent message if it's reply
	ShowInChannel bool   `json:"show_in_channel"` // show reply message also in channel

	ReplyCount int `json:"reply_count,omitempty"`

	MentionedUsers []*User `json:"mentioned_users"`

	Shadowed bool       `json:"shadowed,omitempty"`
	PinnedAt *time.Time `json:"pinned_at,omitempty"`
	PinnedBy *User      `json:"pinned_by,omitempty"`

	CreatedAt *time.Time `json:"created_at,omitempty"`
	UpdatedAt *time.Time `json:"updated_at,omitempty"`
	DeletedAt *time.Time `json:"deleted_at,omitempty"`

	ExtraData map[string]interface{} `json:"-"`
}

func (Message) MarshalJSON

func (m Message) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Message) UnmarshalJSON

func (m *Message) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type MessageFlag

type MessageFlag struct {
	CreatedByAutomod bool `json:"created_by_automod"`
	ModerationResult *struct {
		MessageID            string `json:"message_id"`
		Action               string `json:"action"`
		ModeratedBy          string `json:"moderated_by"`
		BlockedWord          string `json:"blocked_word"`
		BlocklistName        string `json:"blocklist_name"`
		ModerationThresholds *struct {
			Explicit *struct {
				Flag  float32 `json:"flag"`
				Block float32 `json:"block"`
			} `json:"explicit"`
			Spam *struct {
				Flag  float32 `json:"flag"`
				Block float32 `json:"block"`
			} `json:"spam"`
			Toxic *struct {
				Flag  float32 `json:"flag"`
				Block float32 `json:"block"`
			} `json:"toxic"`
		} `json:"moderation_thresholds"`
		AIModerationResponse *struct {
			Toxic    float32 `json:"toxic"`
			Explicit float32 `json:"explicit"`
			Spam     float32 `json:"spam"`
		} `json:"ai_moderation_response"`
		UserKarma    float64   `json:"user_karma"`
		UserBadKarma bool      `json:"user_bad_karma"`
		CreatedAt    time.Time `json:"created_at"`
		UpdatedAt    time.Time `json:"updated_at"`
	} `json:"moderation_result"`
	User    *User    `json:"user"`
	Message *Message `json:"message"`

	CreatedAt  time.Time `json:"created_at"`
	UpdatedAt  time.Time `json:"updated_at"`
	ReviewedAt time.Time `json:"reviewed_at"`
	ReviewedBy *User     `json:"reviewed_by"`
	ApprovedAt time.Time `json:"approved_at"`
	RejectedAt time.Time `json:"rejected_at"`
}

type MessageResponse

type MessageResponse struct {
	Message *Message `json:"message"`

	Response
}

type MessageType

type MessageType string
const (
	MessageTypeRegular   MessageType = "regular"
	MessageTypeError     MessageType = "error"
	MessageTypeReply     MessageType = "reply"
	MessageTypeSystem    MessageType = "system"
	MessageTypeEphemeral MessageType = "ephemeral"
)

type Mute

type Mute struct {
	User      User       `json:"user"`
	Target    User       `json:"target"`
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
	Expires   *time.Time `json:"expires"`
}

Mute represents a user mute.

type PartialUpdate

type PartialUpdate struct {
	Set   map[string]interface{} `json:"set"`
	Unset []string               `json:"unset"`
}

type PartialUserUpdate

type PartialUserUpdate struct {
	ID    string                 `json:"id"`              // User ID, required
	Set   map[string]interface{} `json:"set,omitempty"`   // map of field.name => value; optional
	Unset []string               `json:"unset,omitempty"` // list of field names to unset
}

PartialUserUpdate request; Set and Unset fields can be set at same time, but should not be same field, for example you cannot set 'field.path.name' and unset 'field.path' at the same time. Field path should not contain spaces or dots (dot is path separator).

type Permission

type Permission struct {
	ID          string                 `json:"id"`
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	Action      string                 `json:"action"`
	Owner       bool                   `json:"owner"`
	SameTeam    bool                   `json:"same_team"`
	Condition   map[string]interface{} `json:"condition"`
	Custom      bool                   `json:"custom"`
	Level       string                 `json:"level"`
}

type PermissionClient

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

func (*PermissionClient) CreatePermission

func (p *PermissionClient) CreatePermission(ctx context.Context, perm *Permission) (*Response, error)

CreatePermission creates a new permission.

func (*PermissionClient) CreateRole

func (p *PermissionClient) CreateRole(ctx context.Context, name string) (*Response, error)

CreateRole creates a new role.

func (*PermissionClient) DeletePermission

func (p *PermissionClient) DeletePermission(ctx context.Context, id string) (*Response, error)

DeletePermission deletes a permission by id.

func (*PermissionClient) DeleteRole

func (p *PermissionClient) DeleteRole(ctx context.Context, name string) (*Response, error)

DeleteRole deletes an existing role by name.

func (*PermissionClient) GetPermission

func (p *PermissionClient) GetPermission(ctx context.Context, id string) (*GetPermissionResponse, error)

GetPermission returns a permission by id.

func (*PermissionClient) ListPermissions

func (p *PermissionClient) ListPermissions(ctx context.Context) (*ListPermissionsResponse, error)

ListPermissions returns all permissions of an app.

func (*PermissionClient) ListRoles

func (p *PermissionClient) ListRoles(ctx context.Context) (*RolesResponse, error)

ListRole returns all roles.

func (*PermissionClient) UpdatePermission

func (p *PermissionClient) UpdatePermission(ctx context.Context, id string, perm *Permission) (*Response, error)

UpdatePermission updates an existing permission by id. Only custom permissions can be updated.

type Policy

type Policy struct {
	Name      string    `json:"name"`
	Resources []string  `json:"resources"`
	Roles     []string  `json:"roles"`
	Action    int       `json:"action"` // allow: 1, deny: 0
	Owner     bool      `json:"owner"`
	Priority  int       `json:"priority"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

type PushNotificationFields

type PushNotificationFields struct {
	APNConfig      APNConfig      `json:"apn"`
	FirebaseConfig FirebaseConfig `json:"firebase"`
}

type QueryChannelsResponse

type QueryChannelsResponse struct {
	Channels []*Channel
	Response
}

type QueryMembersResponse

type QueryMembersResponse struct {
	Members []*ChannelMember `json:"members"`

	Response
}

type QueryMessageFlagsResponse

type QueryMessageFlagsResponse struct {
	Flags []*MessageFlag `json:"flags"`
	Response
}

type QueryOption

type QueryOption struct {
	// https://getstream.io/chat/docs/#query_syntax
	Filter map[string]interface{} `json:"filter_conditions,omitempty"`
	Sort   []*SortOption          `json:"sort,omitempty"`

	UserID       string `json:"user_id,omitempty"`
	Limit        int    `json:"limit,omitempty"`  // pagination option: limit number of results
	Offset       int    `json:"offset,omitempty"` // pagination option: offset to return items from
	MessageLimit *int   `json:"message_limit,omitempty"`
	MemberLimit  *int   `json:"member_limit,omitempty"`
}

type QueryUsersResponse

type QueryUsersResponse struct {
	Users []*User `json:"users"`
	Response
}

type RateLimitInfo

type RateLimitInfo struct {
	// Limit is the maximum number of API calls for a single time window (1 minute).
	Limit int64 `json:"limit"`
	// Remaining is the number of API calls remaining in the current time window (1 minute).
	Remaining int64 `json:"remaining"`
	// Reset is the Unix timestamp of the expiration of the current rate limit time window.
	Reset int64 `json:"reset"`
}

RateLimitInfo represents the quota and usage for a single endpoint.

func NewRateLimitFromHeaders

func NewRateLimitFromHeaders(headers http.Header) *RateLimitInfo

func (RateLimitInfo) ResetTime

func (i RateLimitInfo) ResetTime() time.Time

ResetTime is a simple helper to get the time.Time representation of the Reset field of the given limit window.

type RateLimitsMap

type RateLimitsMap map[string]RateLimitInfo

RateLimitsMap holds the rate limit information, where the keys are the names of the endpoints and the values are the related RateLimitInfo containing the quota, usage, and reset data.

type Reaction

type Reaction struct {
	MessageID string `json:"message_id"`
	UserID    string `json:"user_id"`
	Type      string `json:"type"`

	// any other fields the user wants to attach a reaction
	ExtraData map[string]interface{} `json:"-"`
}

func (Reaction) MarshalJSON

func (s Reaction) MarshalJSON() ([]byte, error)

func (*Reaction) UnmarshalJSON

func (s *Reaction) UnmarshalJSON(data []byte) error

type ReactionResponse

type ReactionResponse struct {
	Message  *Message  `json:"message"`
	Reaction *Reaction `json:"reaction"`
	Response
}

type ReactionsResponse

type ReactionsResponse struct {
	Reactions []*Reaction `json:"reactions"`
	Response
}

type RepliesResponse

type RepliesResponse struct {
	Messages []*Message `json:"messages"`
	Response
}

type Response

type Response struct {
	RateLimitInfo *RateLimitInfo `json:"ratelimit"`
}

Response is the base response returned to client. It contains rate limit information. All specific response returned to the client should embed this type.

type Role

type Role struct {
	Name      string    `json:"name"`
	Custom    bool      `json:"custom"`
	Scopes    []string  `json:"scoped"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

type RoleAssignment

type RoleAssignment struct {
	// UserID is the ID of the user to assign the role to.
	UserID string `json:"user_id"`

	// ChannelRole is the role to assign to the user.
	ChannelRole string `json:"channel_role"`
}

type RolesResponse

type RolesResponse struct {
	Roles []*Role `json:"roles"`
	Response
}

type SearchFullResponse

type SearchFullResponse struct {
	Results  []SearchMessageResponse `json:"results"`
	Next     string                  `json:"next,omitempty"`
	Previous string                  `json:"previous,omitempty"`
	Response
}

type SearchMessageResponse

type SearchMessageResponse struct {
	Message *Message `json:"message"`
}

type SearchRequest

type SearchRequest struct {
	// Required
	Query          string                 `json:"query"`
	Filters        map[string]interface{} `json:"filter_conditions"`
	MessageFilters map[string]interface{} `json:"message_filter_conditions"`

	// Pagination, optional
	Limit  int    `json:"limit,omitempty"`
	Offset int    `json:"offset,omitempty"`
	Next   string `json:"next,omitempty"`

	// Sort, optional
	Sort []SortOption `json:"sort,omitempty"`
}

type SearchResponse

type SearchResponse struct {
	Messages []*Message
	Response
}

type SendFileRequest

type SendFileRequest struct {
	Reader io.Reader `json:"-"`
	// name of the file would be stored
	FileName string
	// User object; required
	User *User
	// file content type, required for SendImage
	ContentType string
}

type SendFileResponse

type SendFileResponse struct {
	File string `json:"file"`
	Response
}

type SendMessageOption

type SendMessageOption func(*messageRequest)

SendMessageOption is an option that modifies behavior of send message request.

type SortOption

type SortOption struct {
	Field     string `json:"field"`     // field name to sort by,from json tags(in camel case), for example created_at
	Direction int    `json:"direction"` // [-1, 1]
}

type TaskResponse

type TaskResponse struct {
	TaskID    string     `json:"task_id"`
	Status    TaskStatus `json:"status"`
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`

	Result map[string]interface{} `json:"result,omitempty"`
	Response
}

type TaskStatus

type TaskStatus string
const (
	TaskStatusWaiting   TaskStatus = "waiting"
	TaskStatusPending   TaskStatus = "pending"
	TaskStatusRunning   TaskStatus = "running"
	TaskStatusCompleted TaskStatus = "completed"
	TaskStatusFailed    TaskStatus = "failed"
)

type Thresholds

type Thresholds struct {
	Explicit *LabelThresholds `json:"explicit"`
	Spam     *LabelThresholds `json:"spam"`
	Toxic    *LabelThresholds `json:"toxic"`
}

type TruncateOption

type TruncateOption func(*truncateOptions)

type UpsertUserResponse

type UpsertUserResponse struct {
	User *User
	Response
}

type User

type User struct {
	ID    string   `json:"id"`
	Name  string   `json:"name,omitempty"`
	Image string   `json:"image,omitempty"`
	Role  string   `json:"role,omitempty"`
	Teams []string `json:"teams,omitempty"`

	Online    bool `json:"online,omitempty"`
	Invisible bool `json:"invisible,omitempty"`

	CreatedAt  *time.Time `json:"created_at,omitempty"`
	UpdatedAt  *time.Time `json:"updated_at,omitempty"`
	LastActive *time.Time `json:"last_active,omitempty"`

	Mutes                    []*Mute                `json:"mutes,omitempty"`
	ChannelMutes             []*ChannelMute         `json:"channel_mutes,omitempty"`
	ExtraData                map[string]interface{} `json:"-"`
	RevokeTokensIssuedBefore *time.Time             `json:"revoke_tokens_issued_before,omitempty"`
}

func (User) MarshalJSON

func (u User) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*User) UnmarshalJSON

func (u *User) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type UserCustomEvent

type UserCustomEvent struct {
	// Type should be a custom type. Using a built-in event is not supported here.
	Type string `json:"type"`

	ExtraData map[string]interface{} `json:"-"`

	CreatedAt time.Time `json:"created_at,omitempty"`
}

UserCustomEvent is a custom event sent to a particular user.

func (UserCustomEvent) MarshalJSON

func (e UserCustomEvent) MarshalJSON() ([]byte, error)

func (*UserCustomEvent) UnmarshalJSON

func (e *UserCustomEvent) UnmarshalJSON(data []byte) error

type UsersResponse

type UsersResponse struct {
	Users map[string]*User `json:"users"`
	Response
}

Jump to

Keyboard shortcuts

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