Debian Codegraph @

chat.go

raw symbols SCIP
1 package slack
2
3 import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "io/ioutil"
8 "net/http"
9 "net/url"
10 "strconv"
11
12 "github.com/slack-go/slack/slackutilsx"
13 )
14
15 const (
16 DEFAULT_MESSAGE_USERNAME = ""
17 DEFAULT_MESSAGE_REPLY_BROADCAST = false
18 DEFAULT_MESSAGE_ASUSER = false
19 DEFAULT_MESSAGE_PARSE = ""
20 DEFAULT_MESSAGE_THREAD_TIMESTAMP = ""
21 DEFAULT_MESSAGE_LINK_NAMES = 0
22 DEFAULT_MESSAGE_UNFURL_LINKS = false
23 DEFAULT_MESSAGE_UNFURL_MEDIA = true
24 DEFAULT_MESSAGE_ICON_URL = ""
25 DEFAULT_MESSAGE_ICON_EMOJI = ""
26 DEFAULT_MESSAGE_MARKDOWN = true
27 DEFAULT_MESSAGE_ESCAPE_TEXT = true
28 )
29
30 type chatResponseFull struct {
31 Channel string `json:"channel"`
32 Timestamp string `json:"ts"` //Regular message timestamp
33 MessageTimeStamp string `json:"message_ts"` //Ephemeral message timestamp
34 ScheduledMessageID string `json:"scheduled_message_id,omitempty"` //Scheduled message id
35 Text string `json:"text"`
36 SlackResponse
37 }
38
39 // getMessageTimestamp will inspect the `chatResponseFull` to ruturn a timestamp value
40 // in `chat.postMessage` its under `ts`
41 // in `chat.postEphemeral` its under `message_ts`
42 func (c chatResponseFull) getMessageTimestamp() string {
43 if len(c.Timestamp) > 0 {
44 return c.Timestamp
45 }
46 return c.MessageTimeStamp
47 }
48
49 // PostMessageParameters contains all the parameters necessary (including the optional ones) for a PostMessage() request
50 type PostMessageParameters struct {
51 Username string `json:"username"`
52 AsUser bool `json:"as_user"`
53 Parse string `json:"parse"`
54 ThreadTimestamp string `json:"thread_ts"`
55 ReplyBroadcast bool `json:"reply_broadcast"`
56 LinkNames int `json:"link_names"`
57 UnfurlLinks bool `json:"unfurl_links"`
58 UnfurlMedia bool `json:"unfurl_media"`
59 IconURL string `json:"icon_url"`
60 IconEmoji string `json:"icon_emoji"`
61 Markdown bool `json:"mrkdwn,omitempty"`
62 EscapeText bool `json:"escape_text"`
63
64 // chat.postEphemeral support
65 Channel string `json:"channel"`
66 User string `json:"user"`
67
68 // chat metadata support
69 MetaData SlackMetadata `json:"metadata"`
70 }
71
72 // NewPostMessageParameters provides an instance of PostMessageParameters with all the sane default values set
73 func NewPostMessageParameters() PostMessageParameters {
74 return PostMessageParameters{
75 Username: DEFAULT_MESSAGE_USERNAME,
76 User: DEFAULT_MESSAGE_USERNAME,
77 AsUser: DEFAULT_MESSAGE_ASUSER,
78 Parse: DEFAULT_MESSAGE_PARSE,
79 ThreadTimestamp: DEFAULT_MESSAGE_THREAD_TIMESTAMP,
80 LinkNames: DEFAULT_MESSAGE_LINK_NAMES,
81 UnfurlLinks: DEFAULT_MESSAGE_UNFURL_LINKS,
82 UnfurlMedia: DEFAULT_MESSAGE_UNFURL_MEDIA,
83 IconURL: DEFAULT_MESSAGE_ICON_URL,
84 IconEmoji: DEFAULT_MESSAGE_ICON_EMOJI,
85 Markdown: DEFAULT_MESSAGE_MARKDOWN,
86 EscapeText: DEFAULT_MESSAGE_ESCAPE_TEXT,
87 }
88 }
89
90 // DeleteMessage deletes a message in a channel
91 func (api *Client) DeleteMessage(channel, messageTimestamp string) (string, string, error) {
92 return api.DeleteMessageContext(context.Background(), channel, messageTimestamp)
93 }
94
95 // DeleteMessageContext deletes a message in a channel with a custom context
96 func (api *Client) DeleteMessageContext(ctx context.Context, channel, messageTimestamp string) (string, string, error) {
97 respChannel, respTimestamp, _, err := api.SendMessageContext(
98 ctx,
99 channel,
100 MsgOptionDelete(messageTimestamp),
101 )
102 return respChannel, respTimestamp, err
103 }
104
105 // ScheduleMessage sends a message to a channel.
106 // Message is escaped by default according to https://api.slack.com/docs/formatting
107 // Use http://davestevens.github.io/slack-message-builder/ to help crafting your message.
108 func (api *Client) ScheduleMessage(channelID, postAt string, options ...MsgOption) (string, string, error) {
109 return api.ScheduleMessageContext(context.Background(), channelID, postAt, options...)
110 }
111
112 // ScheduleMessageContext sends a message to a channel with a custom context
113 //
114 // For more details, see ScheduleMessage documentation.
115 func (api *Client) ScheduleMessageContext(ctx context.Context, channelID, postAt string, options ...MsgOption) (string, string, error) {
116 respChannel, respTimestamp, _, err := api.SendMessageContext(
117 ctx,
118 channelID,
119 MsgOptionSchedule(postAt),
120 MsgOptionCompose(options...),
121 )
122 return respChannel, respTimestamp, err
123 }
124
125 // PostMessage sends a message to a channel.
126 // Message is escaped by default according to https://api.slack.com/docs/formatting
127 // Use http://davestevens.github.io/slack-message-builder/ to help crafting your message.
128 func (api *Client) PostMessage(channelID string, options ...MsgOption) (string, string, error) {
129 return api.PostMessageContext(context.Background(), channelID, options...)
130 }
131
132 // PostMessageContext sends a message to a channel with a custom context
133 // For more details, see PostMessage documentation.
134 func (api *Client) PostMessageContext(ctx context.Context, channelID string, options ...MsgOption) (string, string, error) {
135 respChannel, respTimestamp, _, err := api.SendMessageContext(
136 ctx,
137 channelID,
138 MsgOptionPost(),
139 MsgOptionCompose(options...),
140 )
141 return respChannel, respTimestamp, err
142 }
143
144 // PostEphemeral sends an ephemeral message to a user in a channel.
145 // Message is escaped by default according to https://api.slack.com/docs/formatting
146 // Use http://davestevens.github.io/slack-message-builder/ to help crafting your message.
147 func (api *Client) PostEphemeral(channelID, userID string, options ...MsgOption) (string, error) {
148 return api.PostEphemeralContext(context.Background(), channelID, userID, options...)
149 }
150
151 // PostEphemeralContext sends an ephemeal message to a user in a channel with a custom context
152 // For more details, see PostEphemeral documentation
153 func (api *Client) PostEphemeralContext(ctx context.Context, channelID, userID string, options ...MsgOption) (timestamp string, err error) {
154 _, timestamp, _, err = api.SendMessageContext(
155 ctx,
156 channelID,
157 MsgOptionPostEphemeral(userID),
158 MsgOptionCompose(options...),
159 )
160 return timestamp, err
161 }
162
163 // UpdateMessage updates a message in a channel
164 func (api *Client) UpdateMessage(channelID, timestamp string, options ...MsgOption) (string, string, string, error) {
165 return api.UpdateMessageContext(context.Background(), channelID, timestamp, options...)
166 }
167
168 // UpdateMessageContext updates a message in a channel
169 func (api *Client) UpdateMessageContext(ctx context.Context, channelID, timestamp string, options ...MsgOption) (string, string, string, error) {
170 return api.SendMessageContext(
171 ctx,
172 channelID,
173 MsgOptionUpdate(timestamp),
174 MsgOptionCompose(options...),
175 )
176 }
177
178 // UnfurlMessage unfurls a message in a channel
179 func (api *Client) UnfurlMessage(channelID, timestamp string, unfurls map[string]Attachment, options ...MsgOption) (string, string, string, error) {
180 return api.UnfurlMessageContext(context.Background(), channelID, timestamp, unfurls, options...)
181 }
182
183 // UnfurlMessageContext unfurls a message in a channel with a custom context
184 func (api *Client) UnfurlMessageContext(ctx context.Context, channelID, timestamp string, unfurls map[string]Attachment, options ...MsgOption) (string, string, string, error) {
185 return api.SendMessageContext(ctx, channelID, MsgOptionUnfurl(timestamp, unfurls), MsgOptionCompose(options...))
186 }
187
188 // UnfurlMessageWithAuthURL sends an unfurl request containing an
189 // authentication URL.
190 // For more details see:
191 // https://api.slack.com/reference/messaging/link-unfurling#authenticated_unfurls
192 func (api *Client) UnfurlMessageWithAuthURL(channelID, timestamp string, userAuthURL string, options ...MsgOption) (string, string, string, error) {
193 return api.UnfurlMessageWithAuthURLContext(context.Background(), channelID, timestamp, userAuthURL, options...)
194 }
195
196 // UnfurlMessageWithAuthURLContext sends an unfurl request containing an
197 // authentication URL.
198 // For more details see:
199 // https://api.slack.com/reference/messaging/link-unfurling#authenticated_unfurls
200 func (api *Client) UnfurlMessageWithAuthURLContext(ctx context.Context, channelID, timestamp string, userAuthURL string, options ...MsgOption) (string, string, string, error) {
201 return api.SendMessageContext(ctx, channelID, MsgOptionUnfurlAuthURL(timestamp, userAuthURL), MsgOptionCompose(options...))
202 }
203
204 // SendMessage more flexible method for configuring messages.
205 func (api *Client) SendMessage(channel string, options ...MsgOption) (string, string, string, error) {
206 return api.SendMessageContext(context.Background(), channel, options...)
207 }
208
209 // SendMessageContext more flexible method for configuring messages with a custom context.
210 func (api *Client) SendMessageContext(ctx context.Context, channelID string, options ...MsgOption) (_channel string, _timestamp string, _text string, err error) {
211 var (
212 req *http.Request
213 parser func(*chatResponseFull) responseParser
214 response chatResponseFull
215 )
216
217 if req, parser, err = buildSender(api.endpoint, options...).BuildRequestContext(ctx, api.token, channelID); err != nil {
218 return "", "", "", err
219 }
220
221 if api.Debug() {
222 reqBody, err := ioutil.ReadAll(req.Body)
223 if err != nil {
224 return "", "", "", err
225 }
226 req.Body = ioutil.NopCloser(bytes.NewBuffer(reqBody))
227 api.Debugf("Sending request: %s", string(reqBody))
228 }
229
230 if err = doPost(ctx, api.httpclient, req, parser(&response), api); err != nil {
231 return "", "", "", err
232 }
233
234 return response.Channel, response.getMessageTimestamp(), response.Text, response.Err()
235 }
236
237 // UnsafeApplyMsgOptions utility function for debugging/testing chat requests.
238 // NOTE: USE AT YOUR OWN RISK: No issues relating to the use of this function
239 // will be supported by the library.
240 func UnsafeApplyMsgOptions(token, channel, apiurl string, options ...MsgOption) (string, url.Values, error) {
241 config, err := applyMsgOptions(token, channel, apiurl, options...)
242 return config.endpoint, config.values, err
243 }
244
245 func applyMsgOptions(token, channel, apiurl string, options ...MsgOption) (sendConfig, error) {
246 config := sendConfig{
247 apiurl: apiurl,
248 endpoint: apiurl + string(chatPostMessage),
249 values: url.Values{
250 "token": {token},
251 "channel": {channel},
252 },
253 }
254
255 for _, opt := range options {
256 if err := opt(&config); err != nil {
257 return config, err
258 }
259 }
260
261 return config, nil
262 }
263
264 func buildSender(apiurl string, options ...MsgOption) sendConfig {
265 return sendConfig{
266 apiurl: apiurl,
267 options: options,
268 }
269 }
270
271 type sendMode string
272
273 const (
274 chatUpdate sendMode = "chat.update"
275 chatPostMessage sendMode = "chat.postMessage"
276 chatScheduleMessage sendMode = "chat.scheduleMessage"
277 chatDelete sendMode = "chat.delete"
278 chatPostEphemeral sendMode = "chat.postEphemeral"
279 chatResponse sendMode = "chat.responseURL"
280 chatMeMessage sendMode = "chat.meMessage"
281 chatUnfurl sendMode = "chat.unfurl"
282 )
283
284 type sendConfig struct {
285 apiurl string
286 options []MsgOption
287 mode sendMode
288 endpoint string
289 values url.Values
290 attachments []Attachment
291 metadata SlackMetadata
292 blocks Blocks
293 responseType string
294 replaceOriginal bool
295 deleteOriginal bool
296 }
297
298 func (t sendConfig) BuildRequest(token, channelID string) (req *http.Request, _ func(*chatResponseFull) responseParser, err error) {
299 return t.BuildRequestContext(context.Background(), token, channelID)
300 }
301
302 func (t sendConfig) BuildRequestContext(ctx context.Context, token, channelID string) (req *http.Request, _ func(*chatResponseFull) responseParser, err error) {
303 if t, err = applyMsgOptions(token, channelID, t.apiurl, t.options...); err != nil {
304 return nil, nil, err
305 }
306
307 switch t.mode {
308 case chatResponse:
309 return responseURLSender{
310 endpoint: t.endpoint,
311 values: t.values,
312 attachments: t.attachments,
313 metadata: t.metadata,
314 blocks: t.blocks,
315 responseType: t.responseType,
316 replaceOriginal: t.replaceOriginal,
317 deleteOriginal: t.deleteOriginal,
318 }.BuildRequestContext(ctx)
319 default:
320 return formSender{endpoint: t.endpoint, values: t.values}.BuildRequestContext(ctx)
321 }
322 }
323
324 type formSender struct {
325 endpoint string
326 values url.Values
327 }
328
329 func (t formSender) BuildRequest() (*http.Request, func(*chatResponseFull) responseParser, error) {
330 return t.BuildRequestContext(context.Background())
331 }
332
333 func (t formSender) BuildRequestContext(ctx context.Context) (*http.Request, func(*chatResponseFull) responseParser, error) {
334 req, err := formReq(ctx, t.endpoint, t.values)
335 return req, func(resp *chatResponseFull) responseParser {
336 return newJSONParser(resp)
337 }, err
338 }
339
340 type responseURLSender struct {
341 endpoint string
342 values url.Values
343 attachments []Attachment
344 metadata SlackMetadata
345 blocks Blocks
346 responseType string
347 replaceOriginal bool
348 deleteOriginal bool
349 }
350
351 func (t responseURLSender) BuildRequest() (*http.Request, func(*chatResponseFull) responseParser, error) {
352 return t.BuildRequestContext(context.Background())
353 }
354
355 func (t responseURLSender) BuildRequestContext(ctx context.Context) (*http.Request, func(*chatResponseFull) responseParser, error) {
356 req, err := jsonReq(ctx, t.endpoint, Msg{
357 Text: t.values.Get("text"),
358 Timestamp: t.values.Get("ts"),
359 Attachments: t.attachments,
360 Blocks: t.blocks,
361 Metadata: t.metadata,
362 ResponseType: t.responseType,
363 ReplaceOriginal: t.replaceOriginal,
364 DeleteOriginal: t.deleteOriginal,
365 })
366 return req, func(resp *chatResponseFull) responseParser {
367 return newContentTypeParser(resp)
368 }, err
369 }
370
371 // MsgOption option provided when sending a message.
372 type MsgOption func(*sendConfig) error
373
374 // MsgOptionSchedule schedules a messages.
375 func MsgOptionSchedule(postAt string) MsgOption {
376 return func(config *sendConfig) error {
377 config.endpoint = config.apiurl + string(chatScheduleMessage)
378 config.values.Add("post_at", postAt)
379 return nil
380 }
381 }
382
383 // MsgOptionPost posts a messages, this is the default.
384 func MsgOptionPost() MsgOption {
385 return func(config *sendConfig) error {
386 config.endpoint = config.apiurl + string(chatPostMessage)
387 config.values.Del("ts")
388 return nil
389 }
390 }
391
392 // MsgOptionPostEphemeral - posts an ephemeral message to the provided user.
393 func MsgOptionPostEphemeral(userID string) MsgOption {
394 return func(config *sendConfig) error {
395 config.endpoint = config.apiurl + string(chatPostEphemeral)
396 MsgOptionUser(userID)(config)
397 config.values.Del("ts")
398
399 return nil
400 }
401 }
402
403 // MsgOptionMeMessage posts a "me message" type from the calling user
404 func MsgOptionMeMessage() MsgOption {
405 return func(config *sendConfig) error {
406 config.endpoint = config.apiurl + string(chatMeMessage)
407 return nil
408 }
409 }
410
411 // MsgOptionUpdate updates a message based on the timestamp.
412 func MsgOptionUpdate(timestamp string) MsgOption {
413 return func(config *sendConfig) error {
414 config.endpoint = config.apiurl + string(chatUpdate)
415 config.values.Add("ts", timestamp)
416 return nil
417 }
418 }
419
420 // MsgOptionDelete deletes a message based on the timestamp.
421 func MsgOptionDelete(timestamp string) MsgOption {
422 return func(config *sendConfig) error {
423 config.endpoint = config.apiurl + string(chatDelete)
424 config.values.Add("ts", timestamp)
425 return nil
426 }
427 }
428
429 // MsgOptionUnfurl unfurls a message based on the timestamp.
430 func MsgOptionUnfurl(timestamp string, unfurls map[string]Attachment) MsgOption {
431 return func(config *sendConfig) error {
432 config.endpoint = config.apiurl + string(chatUnfurl)
433 config.values.Add("ts", timestamp)
434 unfurlsStr, err := json.Marshal(unfurls)
435 if err == nil {
436 config.values.Add("unfurls", string(unfurlsStr))
437 }
438 return err
439 }
440 }
441
442 // MsgOptionUnfurlAuthURL unfurls a message using an auth url based on the timestamp.
443 func MsgOptionUnfurlAuthURL(timestamp string, userAuthURL string) MsgOption {
444 return func(config *sendConfig) error {
445 config.endpoint = config.apiurl + string(chatUnfurl)
446 config.values.Add("ts", timestamp)
447 config.values.Add("user_auth_url", userAuthURL)
448 return nil
449 }
450 }
451
452 // MsgOptionUnfurlAuthRequired requests that the user installs the
453 // Slack app for unfurling.
454 func MsgOptionUnfurlAuthRequired(timestamp string) MsgOption {
455 return func(config *sendConfig) error {
456 config.endpoint = config.apiurl + string(chatUnfurl)
457 config.values.Add("ts", timestamp)
458 config.values.Add("user_auth_required", "true")
459 return nil
460 }
461 }
462
463 // MsgOptionUnfurlAuthMessage attaches a message inviting the user to
464 // authenticate.
465 func MsgOptionUnfurlAuthMessage(timestamp string, msg string) MsgOption {
466 return func(config *sendConfig) error {
467 config.endpoint = config.apiurl + string(chatUnfurl)
468 config.values.Add("ts", timestamp)
469 config.values.Add("user_auth_message", msg)
470 return nil
471 }
472 }
473
474 // MsgOptionResponseURL supplies a url to use as the endpoint.
475 func MsgOptionResponseURL(url string, responseType string) MsgOption {
476 return func(config *sendConfig) error {
477 config.mode = chatResponse
478 config.endpoint = url
479 config.responseType = responseType
480 config.values.Del("ts")
481 return nil
482 }
483 }
484
485 // MsgOptionReplaceOriginal replaces original message with response url
486 func MsgOptionReplaceOriginal(responseURL string) MsgOption {
487 return func(config *sendConfig) error {
488 config.mode = chatResponse
489 config.endpoint = responseURL
490 config.replaceOriginal = true
491 return nil
492 }
493 }
494
495 // MsgOptionDeleteOriginal deletes original message with response url
496 func MsgOptionDeleteOriginal(responseURL string) MsgOption {
497 return func(config *sendConfig) error {
498 config.mode = chatResponse
499 config.endpoint = responseURL
500 config.deleteOriginal = true
501 return nil
502 }
503 }
504
505 // MsgOptionAsUser whether or not to send the message as the user.
506 func MsgOptionAsUser(b bool) MsgOption {
507 return func(config *sendConfig) error {
508 if b != DEFAULT_MESSAGE_ASUSER {
509 config.values.Set("as_user", "true")
510 }
511 return nil
512 }
513 }
514
515 // MsgOptionUser set the user for the message.
516 func MsgOptionUser(userID string) MsgOption {
517 return func(config *sendConfig) error {
518 config.values.Set("user", userID)
519 return nil
520 }
521 }
522
523 // MsgOptionUsername set the username for the message.
524 func MsgOptionUsername(username string) MsgOption {
525 return func(config *sendConfig) error {
526 config.values.Set("username", username)
527 return nil
528 }
529 }
530
531 // MsgOptionText provide the text for the message, optionally escape the provided
532 // text.
533 func MsgOptionText(text string, escape bool) MsgOption {
534 return func(config *sendConfig) error {
535 if escape {
536 text = slackutilsx.EscapeMessage(text)
537 }
538 config.values.Add("text", text)
539 return nil
540 }
541 }
542
543 // MsgOptionAttachments provide attachments for the message.
544 func MsgOptionAttachments(attachments ...Attachment) MsgOption {
545 return func(config *sendConfig) error {
546 if attachments == nil {
547 return nil
548 }
549
550 config.attachments = attachments
551
552 // FIXME: We are setting the attachments on the message twice: above for
553 // the json version, and below for the html version. The marshalled bytes
554 // we put into config.values below don't work directly in the Msg version.
555
556 attachmentBytes, err := json.Marshal(attachments)
557 if err == nil {
558 config.values.Set("attachments", string(attachmentBytes))
559 }
560
561 return err
562 }
563 }
564
565 // MsgOptionBlocks sets blocks for the message
566 func MsgOptionBlocks(blocks ...Block) MsgOption {
567 return func(config *sendConfig) error {
568 if blocks == nil {
569 return nil
570 }
571
572 config.blocks.BlockSet = append(config.blocks.BlockSet, blocks...)
573
574 blocks, err := json.Marshal(blocks)
575 if err == nil {
576 config.values.Set("blocks", string(blocks))
577 }
578 return err
579 }
580 }
581
582 // MsgOptionEnableLinkUnfurl enables link unfurling
583 func MsgOptionEnableLinkUnfurl() MsgOption {
584 return func(config *sendConfig) error {
585 config.values.Set("unfurl_links", "true")
586 return nil
587 }
588 }
589
590 // MsgOptionDisableLinkUnfurl disables link unfurling
591 func MsgOptionDisableLinkUnfurl() MsgOption {
592 return func(config *sendConfig) error {
593 config.values.Set("unfurl_links", "false")
594 return nil
595 }
596 }
597
598 // MsgOptionDisableMediaUnfurl disables media unfurling.
599 func MsgOptionDisableMediaUnfurl() MsgOption {
600 return func(config *sendConfig) error {
601 config.values.Set("unfurl_media", "false")
602 return nil
603 }
604 }
605
606 // MsgOptionDisableMarkdown disables markdown.
607 func MsgOptionDisableMarkdown() MsgOption {
608 return func(config *sendConfig) error {
609 config.values.Set("mrkdwn", "false")
610 return nil
611 }
612 }
613
614 // MsgOptionTS sets the thread TS of the message to enable creating or replying to a thread
615 func MsgOptionTS(ts string) MsgOption {
616 return func(config *sendConfig) error {
617 config.values.Set("thread_ts", ts)
618 return nil
619 }
620 }
621
622 // MsgOptionBroadcast sets reply_broadcast to true
623 func MsgOptionBroadcast() MsgOption {
624 return func(config *sendConfig) error {
625 config.values.Set("reply_broadcast", "true")
626 return nil
627 }
628 }
629
630 // MsgOptionCompose combines multiple options into a single option.
631 func MsgOptionCompose(options ...MsgOption) MsgOption {
632 return func(config *sendConfig) error {
633 for _, opt := range options {
634 if err := opt(config); err != nil {
635 return err
636 }
637 }
638 return nil
639 }
640 }
641
642 // MsgOptionParse set parse option.
643 func MsgOptionParse(b bool) MsgOption {
644 return func(config *sendConfig) error {
645 var v string
646 if b {
647 v = "full"
648 } else {
649 v = "none"
650 }
651 config.values.Set("parse", v)
652 return nil
653 }
654 }
655
656 // MsgOptionIconURL sets an icon URL
657 func MsgOptionIconURL(iconURL string) MsgOption {
658 return func(config *sendConfig) error {
659 config.values.Set("icon_url", iconURL)
660 return nil
661 }
662 }
663
664 // MsgOptionIconEmoji sets an icon emoji
665 func MsgOptionIconEmoji(iconEmoji string) MsgOption {
666 return func(config *sendConfig) error {
667 config.values.Set("icon_emoji", iconEmoji)
668 return nil
669 }
670 }
671
672 // MsgOptionMetadata sets message metadata
673 func MsgOptionMetadata(metadata SlackMetadata) MsgOption {
674 return func(config *sendConfig) error {
675 config.metadata = metadata
676 meta, err := json.Marshal(metadata)
677 if err == nil {
678 config.values.Set("metadata", string(meta))
679 }
680 return err
681 }
682 }
683
684 // UnsafeMsgOptionEndpoint deliver the message to the specified endpoint.
685 // NOTE: USE AT YOUR OWN RISK: No issues relating to the use of this Option
686 // will be supported by the library, it is subject to change without notice that
687 // may result in compilation errors or runtime behaviour changes.
688 func UnsafeMsgOptionEndpoint(endpoint string, update func(url.Values)) MsgOption {
689 return func(config *sendConfig) error {
690 config.endpoint = endpoint
691 update(config.values)
692 return nil
693 }
694 }
695
696 // MsgOptionPostMessageParameters maintain backwards compatibility.
697 func MsgOptionPostMessageParameters(params PostMessageParameters) MsgOption {
698 return func(config *sendConfig) error {
699 if params.Username != DEFAULT_MESSAGE_USERNAME {
700 config.values.Set("username", params.Username)
701 }
702
703 // chat.postEphemeral support
704 if params.User != DEFAULT_MESSAGE_USERNAME {
705 config.values.Set("user", params.User)
706 }
707
708 // never generates an error.
709 MsgOptionAsUser(params.AsUser)(config)
710
711 if params.Parse != DEFAULT_MESSAGE_PARSE {
712 config.values.Set("parse", params.Parse)
713 }
714 if params.LinkNames != DEFAULT_MESSAGE_LINK_NAMES {
715 config.values.Set("link_names", "1")
716 }
717
718 if params.UnfurlLinks != DEFAULT_MESSAGE_UNFURL_LINKS {
719 config.values.Set("unfurl_links", "true")
720 }
721
722 // I want to send a message with explicit `as_user` `true` and `unfurl_links` `false` in request.
723 // Because setting `as_user` to `true` will change the default value for `unfurl_links` to `true` on Slack API side.
724 if params.AsUser != DEFAULT_MESSAGE_ASUSER && params.UnfurlLinks == DEFAULT_MESSAGE_UNFURL_LINKS {
725 config.values.Set("unfurl_links", "false")
726 }
727 if params.UnfurlMedia != DEFAULT_MESSAGE_UNFURL_MEDIA {
728 config.values.Set("unfurl_media", "false")
729 }
730 if params.IconURL != DEFAULT_MESSAGE_ICON_URL {
731 config.values.Set("icon_url", params.IconURL)
732 }
733 if params.IconEmoji != DEFAULT_MESSAGE_ICON_EMOJI {
734 config.values.Set("icon_emoji", params.IconEmoji)
735 }
736 if params.Markdown != DEFAULT_MESSAGE_MARKDOWN {
737 config.values.Set("mrkdwn", "false")
738 }
739
740 if params.ThreadTimestamp != DEFAULT_MESSAGE_THREAD_TIMESTAMP {
741 config.values.Set("thread_ts", params.ThreadTimestamp)
742 }
743 if params.ReplyBroadcast != DEFAULT_MESSAGE_REPLY_BROADCAST {
744 config.values.Set("reply_broadcast", "true")
745 }
746
747 return nil
748 }
749 }
750
751 // PermalinkParameters are the parameters required to get a permalink to a
752 // message. Slack documentation can be found here:
753 // https://api.slack.com/methods/chat.getPermalink
754 type PermalinkParameters struct {
755 Channel string
756 Ts string
757 }
758
759 // GetPermalink returns the permalink for a message. It takes
760 // PermalinkParameters and returns a string containing the permalink. It
761 // returns an error if unable to retrieve the permalink.
762 func (api *Client) GetPermalink(params *PermalinkParameters) (string, error) {
763 return api.GetPermalinkContext(context.Background(), params)
764 }
765
766 // GetPermalinkContext returns the permalink for a message using a custom context.
767 func (api *Client) GetPermalinkContext(ctx context.Context, params *PermalinkParameters) (string, error) {
768 values := url.Values{
769 "channel": {params.Channel},
770 "message_ts": {params.Ts},
771 }
772
773 response := struct {
774 Channel string `json:"channel"`
775 Permalink string `json:"permalink"`
776 SlackResponse
777 }{}
778 err := api.getMethod(ctx, "chat.getPermalink", api.token, values, &response)
779 if err != nil {
780 return "", err
781 }
782 return response.Permalink, response.Err()
783 }
784
785 type GetScheduledMessagesParameters struct {
786 Channel string
787 Cursor string
788 Latest string
789 Limit int
790 Oldest string
791 }
792
793 // GetScheduledMessages returns the list of scheduled messages based on params
794 func (api *Client) GetScheduledMessages(params *GetScheduledMessagesParameters) (channels []ScheduledMessage, nextCursor string, err error) {
795 return api.GetScheduledMessagesContext(context.Background(), params)
796 }
797
798 // GetScheduledMessagesContext returns the list of scheduled messages in a Slack team with a custom context
799 func (api *Client) GetScheduledMessagesContext(ctx context.Context, params *GetScheduledMessagesParameters) (channels []ScheduledMessage, nextCursor string, err error) {
800 values := url.Values{
801 "token": {api.token},
802 }
803 if params.Channel != "" {
804 values.Add("channel", params.Channel)
805 }
806 if params.Cursor != "" {
807 values.Add("cursor", params.Cursor)
808 }
809 if params.Limit != 0 {
810 values.Add("limit", strconv.Itoa(params.Limit))
811 }
812 if params.Latest != "" {
813 values.Add("latest", params.Latest)
814 }
815 if params.Oldest != "" {
816 values.Add("oldest", params.Oldest)
817 }
818 response := struct {
819 Messages []ScheduledMessage `json:"scheduled_messages"`
820 ResponseMetaData responseMetaData `json:"response_metadata"`
821 SlackResponse
822 }{}
823
824 err = api.postMethod(ctx, "chat.scheduledMessages.list", values, &response)
825 if err != nil {
826 return nil, "", err
827 }
828
829 return response.Messages, response.ResponseMetaData.NextCursor, response.Err()
830 }
831
832 type DeleteScheduledMessageParameters struct {
833 Channel string
834 ScheduledMessageID string
835 AsUser bool
836 }
837
838 // DeleteScheduledMessage returns the list of scheduled messages based on params
839 func (api *Client) DeleteScheduledMessage(params *DeleteScheduledMessageParameters) (bool, error) {
840 return api.DeleteScheduledMessageContext(context.Background(), params)
841 }
842
843 // DeleteScheduledMessageContext returns the list of scheduled messages in a Slack team with a custom context
844 func (api *Client) DeleteScheduledMessageContext(ctx context.Context, params *DeleteScheduledMessageParameters) (bool, error) {
845 values := url.Values{
846 "token": {api.token},
847 "channel": {params.Channel},
848 "scheduled_message_id": {params.ScheduledMessageID},
849 "as_user": {strconv.FormatBool(params.AsUser)},
850 }
851 response := struct {
852 SlackResponse
853 }{}
854
855 err := api.postMethod(ctx, "chat.deleteScheduledMessage", values, &response)
856 if err != nil {
857 return false, err
858 }
859
860 return response.Ok, response.Err()
861 }