From 73b06d5de42bd46d3615ef1029c8b66578adacb6 Mon Sep 17 00:00:00 2001 From: Alexey Chelnakov Date: Fri, 28 Jun 2024 18:04:49 +0300 Subject: [PATCH] Add websocket options --- v1/client.go | 22 +++++++++++++++++++++- v1/client_test.go | 18 ++++++++++++++++++ v1/types.go | 7 +++++++ 3 files changed, 46 insertions(+), 1 deletion(-) diff --git a/v1/client.go b/v1/client.go index afb1860..efc9e65 100644 --- a/v1/client.go +++ b/v1/client.go @@ -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 { @@ -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 diff --git a/v1/client_test.go b/v1/client_test.go index 5965543..718b538 100644 --- a/v1/client_test.go +++ b/v1/client_test.go @@ -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"} diff --git a/v1/types.go b/v1/types.go index 2376efc..4261892 100644 --- a/v1/types.go +++ b/v1/types.go @@ -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" @@ -434,6 +436,11 @@ type ( } ) +// WS options +type ( + WsOptionParam string +) + // Single entity types type ( Message struct {