Skip to content

Commit

Permalink
Add websocket options
Browse files Browse the repository at this point in the history
  • Loading branch information
Alexey Chelnakov committed Jun 28, 2024
1 parent 3d84dda commit 73b06d5
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
22 changes: 21 additions & 1 deletion v1/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -912,8 +912,20 @@ func (c *MgClient) UploadFileByURL(request UploadFileByUrlRequest) (UploadFileRe
return resp, status, err
}

type wsOptions struct {
params []string
}

type WsOption interface {
apply(*wsOptions)
}

func (c WsOptionParam) apply(opts *wsOptions) {
opts.params = append(opts.params, string(c))
}

// WsMeta let you receive url & headers to open web socket connection
func (c *MgClient) WsMeta(events []string) (string, http.Header, error) {
func (c *MgClient) WsMeta(events []string, opts ...WsOption) (string, http.Header, error) {
var url string

if len(events) < 1 {
Expand All @@ -923,6 +935,14 @@ func (c *MgClient) WsMeta(events []string) (string, http.Header, error) {

url = fmt.Sprintf("%s%s%s%s", strings.Replace(c.URL, "https", "wss", 1), prefix, "/ws?events=", strings.Join(events[:], ","))

var wsOpts wsOptions
for _, opt := range opts {
opt.apply(&wsOpts)
}
if len(wsOpts.params) > 0 {
url = fmt.Sprintf("%s&options=%s", url, strings.Join(wsOpts.params, ","))
}

if url == "" {
err := errors.New("empty WS URL")
return url, nil, err
Expand Down
18 changes: 18 additions & 0 deletions v1/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -846,6 +846,24 @@ func TestMgClient_CommandEditDelete(t *testing.T) {
t.Logf("%v", d)
}

func TestMgClient_WsMeta_With_Options(t *testing.T) {
c := client()
events := []string{"user_updated", "user_join_chat"}
options := []WsOption{WsOptionIncludeMassCommunication}

url, headers, err := c.WsMeta(events, options...)

if err != nil {
t.Errorf("%v", err)
}

resUrl := "wss://api.example.com/api/bot/v1/ws?events=user_updated,user_join_chat&options=include_mass_communication"
resToken := c.Token

assert.Equal(t, resUrl, url)
assert.Equal(t, resToken, headers["X-Bot-Token"][0])
}

func TestMgClient_WsMeta(t *testing.T) {
c := client()
events := []string{"user_updated", "user_join_chat"}
Expand Down
7 changes: 7 additions & 0 deletions v1/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ const (
WsEventSettingsUpdated string = "settings_updated"
WsEventChatsDeleted string = "chats_deleted"

WsOptionIncludeMassCommunication WsOptionParam = "include_mass_communication"

ChannelFeatureNone string = "none"
ChannelFeatureReceive string = "receive"
ChannelFeatureSend string = "send"
Expand Down Expand Up @@ -434,6 +436,11 @@ type (
}
)

// WS options
type (
WsOptionParam string
)

// Single entity types
type (
Message struct {
Expand Down

0 comments on commit 73b06d5

Please sign in to comment.