stream_chat

package module
v2.8.0 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2020 License: BSD-3-Clause Imports: 19 Imported by: 1

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/v2
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/v2"
)

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, []byte(APISecret))
	// 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 follow Go best-practices.

Documentation

Overview

Package stream_chat provides chat via stream API

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")
)

Variables

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

DefaultChannelConfig is the default channel configuration.

Functions

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"`
}

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"`
}

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) SetWebhookURL

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

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

	Config ChannelConfig `json:"config"`

	CreatedBy *User `json:"created_by"`
	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(userID string, message *Message) error

func (*Channel) AddMembers

func (ch *Channel) AddMembers(userIDs []string, message *Message) error

AddMembers adds members with given user IDs to the channel.

func (*Channel) AddModerators

func (ch *Channel) AddModerators(userIDs ...string) 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("thierry", "josh")
_ = channel.AddModerators(newModerators...)
_ = channel.DemoteModerators(newModerators...)
Output:

func (*Channel) AddModeratorsWithMessage

func (ch *Channel) AddModeratorsWithMessage(userIDs []string, msg *Message) error

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

func (*Channel) BanUser

func (ch *Channel) BanUser(targetID, userID string, options map[string]interface{}) 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() error

Delete removes the channel. Messages are permanently removed.

func (*Channel) DeleteFile

func (ch *Channel) DeleteFile(location string) error

DeleteFile removes uploaded file.

func (*Channel) DeleteImage

func (ch *Channel) DeleteImage(location string) error

DeleteImage removes uploaded image.

func (*Channel) DeleteReaction

func (ch *Channel) DeleteReaction(messageID, reactionType, userID string) (*Message, error)

DeleteReaction removes a reaction from message with given ID.

func (*Channel) DemoteModerators

func (ch *Channel) DemoteModerators(userIDs ...string) error

DemoteModerators moderators with given IDs from the channel.

func (*Channel) DemoteModeratorsWithMessage

func (ch *Channel) DemoteModeratorsWithMessage(userIDs []string, msg *Message) error

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

func (*Channel) GetReactions

func (ch *Channel) GetReactions(messageID string, options map[string][]string) ([]*Reaction, 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(parentID string, options map[string][]string) ([]*Message, 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(userID string) error

Hide makes channel hidden for userID.

func (*Channel) HideWithHistoryClear

func (ch *Channel) HideWithHistoryClear(userID string) error

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

func (*Channel) ImportMessages added in v2.8.0

func (ch *Channel) ImportMessages(messages ...*Message) (*ImportChannelMessagesResponse, error)

ImportMessages is a batch endpoint for inserting multiple messages.

func (*Channel) InviteMembers

func (ch *Channel) InviteMembers(userIDs ...string) error

InviteMembers invites users with given IDs to the channel.

func (*Channel) InviteMembersWithMessage

func (ch *Channel) InviteMembersWithMessage(userIDs []string, msg *Message) error

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

func (*Channel) MarkRead

func (ch *Channel) MarkRead(userID string, options map[string]interface{}) 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(userID string, expiration *time.Duration) (*ChannelMuteResponse, error)

func (*Channel) Query

func (ch *Channel) Query(data map[string]interface{}) error

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

func (*Channel) QueryMembers added in v2.6.0

func (ch *Channel) QueryMembers(q *QueryOption, sorters ...*SortOption) ([]*ChannelMember, error)

QueryMembers queries members of a channel.

func (*Channel) RejectInvite

func (ch *Channel) RejectInvite(userID string, message *Message) error

func (*Channel) RemoveMembers

func (ch *Channel) RemoveMembers(userIDs []string, message *Message) error

RemoveMembers deletes members with given IDs from the channel.

func (*Channel) SendAction

func (ch *Channel) SendAction(msgID string, formData map[string]string) (*Message, error)

SendAction for a message.

func (*Channel) SendEvent

func (ch *Channel) SendEvent(event *Event, userID string) error

SendEvent sends an event on this channel.

func (*Channel) SendFile

func (ch *Channel) SendFile(request SendFileRequest) (string, error)

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

func (*Channel) SendImage

func (ch *Channel) SendImage(request SendFileRequest) (string, error)

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

func (*Channel) SendMessage

func (ch *Channel) SendMessage(message *Message, userID string) (*Message, error)

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

func (*Channel) SendReaction

func (ch *Channel) SendReaction(reaction *Reaction, messageID, userID string) (*Message, 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(reaction, msgID, userID)
if err != nil {
	log.Fatalf("Found Error: %v", err)
}
Output:

func (*Channel) Show

func (ch *Channel) Show(userID string) error

Show makes channel visible for userID.

func (*Channel) Truncate

func (ch *Channel) Truncate() error

Truncate removes all messages from the channel.

func (*Channel) UnBanUser

func (ch *Channel) UnBanUser(targetID string, options map[string]string) 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(userID string) error

func (*Channel) Update

func (ch *Channel) Update(options map[string]interface{}, message *Message) error

Update edits the channel's custom properties

options: 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(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"`

	// 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"`
}

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"`
}

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"`
	Permissions []*Permission `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 Client

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

func NewClient

func NewClient(apiKey string, apiSecret []byte) (*Client, error)

NewClient creates new stream chat api client.

func (*Client) AddDevice

func (c *Client) AddDevice(device *Device) error

AddDevice adds new device.

Example
client, _ := NewClient("XXXX", []byte("XXXX"))

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

func (*Client) BanUser

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

// ban a user for 60 minutes from all channel
_ = client.BanUser("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("eviluser", "modUser",
	map[string]interface{}{"reason": "Profanity is not allowed here"})

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

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

func (*Client) Channel

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

Channel prepares a Channel object for future API calls. This does not in and of itself call the API.

func (*Client) CreateChannel

func (c *Client) CreateChannel(chanType, chanID, userID string, data map[string]interface{}) (*Channel, error)

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

func (*Client) CreateChannelType

func (c *Client) CreateChannelType(chType *ChannelType) (*ChannelType, 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,
	&Permission{
		Name:      "Allow reads for all",
		Priority:  999,
		Resources: []string{"ReadChannel", "CreateMessage"},
		Action:    "Allow",
	},
	&Permission{
		Name:      "Deny all",
		Priority:  1,
		Resources: []string{"*"},
		Action:    "Deny",
	},
)

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

func (*Client) CreateCommand added in v2.7.0

func (c *Client) CreateCommand(cmd *Command) (*Command, 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(newCommand)
Output:

func (*Client) CreateToken

func (c *Client) CreateToken(userID string, expire time.Time) ([]byte, 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(targetID string, options map[string]interface{}) error
Example
client, _ := NewClient("XXXX", []byte("XXXX"))

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

func (*Client) DeleteChannelType

func (c *Client) DeleteChannelType(name string) error
Example
client := &Client{}

_ = client.DeleteChannelType("public")
Output:

func (*Client) DeleteCommand added in v2.7.0

func (c *Client) DeleteCommand(cmdName string) error

DeleteCommand deletes a custom command referenced by cmdName.

Example
client := &Client{}

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

func (*Client) DeleteDevice

func (c *Client) DeleteDevice(userID, deviceID string) error

DeleteDevice deletes a device from the user.

Example
client, _ := NewClient("XXXX", []byte("XXXX"))

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

func (*Client) DeleteMessage

func (c *Client) DeleteMessage(msgID string) error

func (*Client) DeleteUser

func (c *Client) DeleteUser(targetID string, options map[string][]string) error
Example
client, _ := NewClient("XXXX", []byte("XXXX"))

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

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

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

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

func (*Client) ExportUser

func (c *Client) ExportUser(targetID string, options map[string][]string) (user *User, err error)
Example
client, _ := NewClient("XXXX", []byte("XXXX"))

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

func (*Client) FlagMessage

func (c *Client) FlagMessage(msgID string) error

func (*Client) FlagUser

func (c *Client) FlagUser(targetID string, options map[string]interface{}) error

func (*Client) GetAppConfig

func (c *Client) GetAppConfig() (*AppConfig, error)

GetAppConfig returns app settings.

func (*Client) GetChannelType

func (c *Client) GetChannelType(chanType string) (*ChannelType, error)

GetChannelType returns information about channel type.

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

func (*Client) GetCommand added in v2.7.0

func (c *Client) GetCommand(cmdName string) (*Command, error)

GetCommand retrieves a custom command referenced by cmdName.

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

func (*Client) GetDevices

func (c *Client) GetDevices(userID string) (devices []*Device, err error)

GetDevices retrieves the list of devices for user.

func (*Client) GetMessage

func (c *Client) GetMessage(msgID string) (*Message, error)

GetMessage returns message by ID.

func (*Client) ListChannelTypes

func (c *Client) ListChannelTypes() (map[string]*ChannelType, error)

ListChannelTypes returns all channel types.

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

func (*Client) ListCommands added in v2.7.0

func (c *Client) ListCommands() ([]*Command, error)

ListCommands returns a list of custom commands.

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

func (*Client) MarkAllRead

func (c *Client) MarkAllRead(userID string) error

MarkAllRead marks all messages as read for userID.

func (*Client) MuteUser

func (c *Client) MuteUser(targetID, userID string, options map[string]interface{}) error

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

func (*Client) MuteUsers

func (c *Client) MuteUsers(targetIDs []string, userID string, options map[string]interface{}) error

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

func (*Client) PartialUpdateUser

func (c *Client) PartialUpdateUser(update PartialUserUpdate) (*User, error)

PartialUpdateUser makes partial update for single user.

func (*Client) PartialUpdateUsers

func (c *Client) PartialUpdateUsers(updates []PartialUserUpdate) (map[string]*User, error)

PartialUpdateUsers makes partial update for users.

func (*Client) QueryChannels

func (c *Client) QueryChannels(q *QueryOption, sort ...*SortOption) ([]*Channel, 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) QueryUsers

func (c *Client) QueryUsers(q *QueryOption, sorters ...*SortOption) ([]*User, 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(targetID string, options map[string]interface{}) error
Example
client, _ := NewClient("XXXX", []byte("XXXX"))

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

func (*Client) Search

func (c *Client) Search(request SearchRequest) ([]*Message, error)

Search returns channels matching for given keyword.

func (*Client) UnBanUser

func (c *Client) UnBanUser(targetID string, options map[string]string) error

func (*Client) UnFlagUser

func (c *Client) UnFlagUser(targetID string, options map[string]interface{}) error

func (*Client) UnflagMessage

func (c *Client) UnflagMessage(msgID string) error

func (*Client) UnmuteUser

func (c *Client) UnmuteUser(targetID, userID string) 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(targetIDs []string, userID string) 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(settings *AppSettings) 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", []byte("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"))
if err != nil {
	log.Fatalf("Err: %v", err)
}

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

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

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

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

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

func (*Client) UpdateChannelType

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

_ = client.UpdateChannelType("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("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(
	"public",
	map[string]interface{}{
		"automod":            "disabled",
		"message_retention":  "7",
		"max_message_length": 140,
		"commands":           []interface{}{"ban", "unban"},
	},
)
Output:

Example (Permissions)
client := &Client{}

_ = client.UpdateChannelType(
	"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 added in v2.7.0

func (c *Client) UpdateCommand(cmdName string, options map[string]interface{}) (*Command, error)

UpdateCommand updates a custom command referenced by cmdName.

Example
client := &Client{}

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

func (*Client) UpdateMessage

func (c *Client) UpdateMessage(msg *Message, msgID string) (*Message, error)

UpdateMessage updates message with given msgID.

func (*Client) UpdateUser

func (c *Client) UpdateUser(user *User) (*User, error)

UpdateUser sending update users request, returns updated user info.

Example
client, _ := NewClient("XXXX", []byte("XXXX"))

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

func (*Client) UpdateUsers

func (c *Client) UpdateUsers(users ...*User) (map[string]*User, error)

UpdateUsers send update users request, returns updated user info.

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 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 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"

	// 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 FirebaseConfig

type FirebaseConfig struct {
	Enabled              bool   `json:"enabled"`
	NotificationTemplate string `json:"notification_template"`
}

type ImportChannelMessagesResponse added in v2.8.0

type ImportChannelMessagesResponse struct {
	Messages []Message `json:"messages"`
}

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"`

	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 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 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 {
	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 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 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
}

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 SearchRequest

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

	// Pagination, optional
	Limit  int `json:"limit,omitempty"`
	Offset int `json:"offset,omitempty"`
}

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 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 StreamChannel

type StreamChannel interface {
	// channel.go
	AddMembers(userIDs []string, message *Message) error
	AddModerators(userIDs ...string) error
	AddModeratorsWithMessage(userIDs []string, msg *Message) error
	BanUser(targetID string, userID string, options map[string]interface{}) error
	Delete() error
	DemoteModerators(userIDs ...string) error
	DemoteModeratorsWithMessage(userIDs []string, msg *Message) error
	MarkRead(userID string, options map[string]interface{}) error
	RemoveMembers(userIDs []string, message *Message) error
	QueryMembers(q *QueryOption, sort ...*SortOption) ([]*ChannelMember, error)
	Truncate() error
	UnBanUser(targetID string, options map[string]string) error
	Update(options map[string]interface{}, message *Message) error
	Query(data map[string]interface{}) error
	Show(userID string) error
	Hide(userID string) error
	HideWithHistoryClear(userID string) error
	InviteMembers(userIDs ...string) error
	InviteMembersWithMessage(userIDs []string, msg *Message) error
	SendFile(request SendFileRequest) (url string, err error)
	SendImage(request SendFileRequest) (url string, err error)
	DeleteFile(location string) error
	DeleteImage(location string) error
	AcceptInvite(userID string, message *Message) error
	RejectInvite(userID string, message *Message) error
	// event.go
	SendEvent(event *Event, userID string) error

	// message.go
	SendMessage(message *Message, userID string) (*Message, error)
	GetReplies(parentID string, options map[string][]string) (replies []*Message, err error)
	SendAction(msgID string, formData map[string]string) (*Message, error)

	// reaction.go
	DeleteReaction(messageID string, reactionType string, userID string) (*Message, error)
	GetReactions(messageID string, options map[string][]string) ([]*Reaction, error)
	SendReaction(reaction *Reaction, messageID string, userID string) (*Message, error)

	ImportMessages(messages ...*Message) (*ImportChannelMessagesResponse, error)
}

StreamChannel is a channel of communication.

type StreamClient

type StreamClient interface {
	// app.go
	GetAppConfig() (*AppConfig, error)
	UpdateAppSettings(settings *AppSettings) error

	// device.go
	AddDevice(device *Device) error
	DeleteDevice(userID string, deviceID string) error
	GetDevices(userID string) (devices []*Device, err error)

	// channel.go
	CreateChannel(chanType string, chanID string, userID string, data map[string]interface{}) (*Channel, error)

	// channel_type.go
	CreateChannelType(chType *ChannelType) (*ChannelType, error)
	DeleteChannelType(chType string) error
	GetChannelType(chanType string) (ct *ChannelType, err error)
	ListChannelTypes() (map[string]*ChannelType, error)
	UpdateChannelType(name string, options map[string]interface{}) error

	// command.go
	CreateCommand(cmd *Command) (*Command, error)
	DeleteCommand(cmdName string) error
	GetCommand(cmdName string) (*Command, error)
	ListCommands() ([]*Command, error)
	UpdateCommand(cmdName string, options map[string]interface{}) (*Command, error)

	// client.go
	CreateToken(userID string, expire time.Time) ([]byte, error)
	VerifyWebhook(body []byte, signature []byte) (valid bool)

	// message.go
	DeleteMessage(msgID string) error
	GetMessage(msgID string) (*Message, error)
	MarkAllRead(userID string) error
	UpdateMessage(msg *Message, msgID string) (*Message, error)
	FlagMessage(msgID string) error
	UnflagMessage(msgID string) error

	// query.go
	QueryUsers(q *QueryOption, sort ...*SortOption) ([]*User, error)
	QueryChannels(q *QueryOption, sort ...*SortOption) ([]*Channel, error)
	Search(request SearchRequest) ([]*Message, error)

	// user.go
	BanUser(targetID string, userID string, options map[string]interface{}) error
	DeactivateUser(targetID string, options map[string]interface{}) error
	ReactivateUser(targetID string, options map[string]interface{}) error
	DeleteUser(targetID string, options map[string][]string) error
	ExportUser(targetID string, options map[string][]string) (user *User, err error)
	FlagUser(targetID string, options map[string]interface{}) error
	MuteUser(targetID string, userID string, options map[string]interface{}) error
	MuteUsers(targetIDs []string, userID string, options map[string]interface{}) error
	UnBanUser(targetID string, options map[string]string) error
	UnFlagUser(targetID string, options map[string]interface{}) error
	UnmuteUser(targetID string, userID string) error
	UnmuteUsers(targetIDs []string, userID string) error
	UpdateUser(user *User) (*User, error)
	UpdateUsers(users ...*User) (map[string]*User, error)
	PartialUpdateUser(update PartialUserUpdate) (*User, error)
	PartialUpdateUsers(updates []PartialUserUpdate) (map[string]*User, error)
}

StreamClient is a client for chat.

type User

type User struct {
	ID    string `json:"id"`
	Name  string `json:"name,omitempty"`
	Image string `json:"image,omitempty"`
	Role  string `json:"role,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:"-"`
}

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.

Jump to

Keyboard shortcuts

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