1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
//! Post chat messages to Slack.


#[allow(unused_imports)]
use std::collections::HashMap;
use std::convert::From;
use std::error::Error;
use std::fmt;

use serde_json;

use requests::SlackWebRequestSender;

/// Deletes a message.
///
/// Wraps https://api.slack.com/methods/chat.delete

pub fn delete<R>(client: &R,
                 token: &str,
                 request: &DeleteRequest)
                 -> Result<DeleteResponse, DeleteError<R::Error>>
    where R: SlackWebRequestSender
{

    let params = vec![Some(("token", token)),
                      Some(("ts", request.ts)),
                      Some(("channel", request.channel)),
                      request
                          .as_user
                          .map(|as_user| ("as_user", if as_user { "1" } else { "0" }))];
    let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>();
    let url = ::get_slack_url_for_method("chat.delete");
    client
        .send(&url, &params[..])
        .map_err(|err| DeleteError::Client(err))
        .and_then(|result| {
                      serde_json::from_str::<DeleteResponse>(&result)
                            .map_err(|e| DeleteError::MalformedResponse(e))
                  })
        .and_then(|o| o.into())
}

#[derive(Clone, Default, Debug)]
pub struct DeleteRequest<'a> {
    /// Timestamp of the message to be deleted.
    pub ts: &'a str,
    /// Channel containing the message to be deleted.
    pub channel: &'a str,
    /// Pass true to delete the message as the authed user. Bot users in this context are considered authed users.
    pub as_user: Option<bool>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct DeleteResponse {
    pub channel: Option<String>,
    error: Option<String>,
    #[serde(default)]
    ok: bool,
    pub ts: Option<String>,
}


impl<E: Error> Into<Result<DeleteResponse, DeleteError<E>>> for DeleteResponse {
    fn into(self) -> Result<DeleteResponse, DeleteError<E>> {
        if self.ok {
            Ok(self)
        } else {
            Err(self.error
                    .as_ref()
                    .map(String::as_ref)
                    .unwrap_or("")
                    .into())
        }
    }
}
#[derive(Debug)]
pub enum DeleteError<E: Error> {
    /// No message exists with the requested timestamp.
    MessageNotFound,
    /// Value passed for channel was invalid.
    ChannelNotFound,
    /// Authenticated user does not have permission to delete this message.
    CantDeleteMessage,
    /// Compliance exports are on, messages can not be deleted
    ComplianceExportsPreventDeletion,
    /// No authentication token provided.
    NotAuthed,
    /// Invalid authentication token.
    InvalidAuth,
    /// Authentication token is for a deleted user or team.
    AccountInactive,
    /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.
    InvalidArgName,
    /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.
    InvalidArrayArg,
    /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.
    InvalidCharset,
    /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.
    InvalidFormData,
    /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.
    InvalidPostType,
    /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.
    MissingPostType,
    /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.
    TeamAddedToOrg,
    /// The method was called via a POST request, but the POST data was either missing or truncated.
    RequestTimeout,
    /// The response was not parseable as the expected object
    MalformedResponse(serde_json::error::Error),
    /// The response returned an error that was unknown to the library
    Unknown(String),
    /// The client had an error sending the request to Slack
    Client(E),
}

impl<'a, E: Error> From<&'a str> for DeleteError<E> {
    fn from(s: &'a str) -> Self {
        match s {
            "message_not_found" => DeleteError::MessageNotFound,
            "channel_not_found" => DeleteError::ChannelNotFound,
            "cant_delete_message" => DeleteError::CantDeleteMessage,
            "compliance_exports_prevent_deletion" => DeleteError::ComplianceExportsPreventDeletion,
            "not_authed" => DeleteError::NotAuthed,
            "invalid_auth" => DeleteError::InvalidAuth,
            "account_inactive" => DeleteError::AccountInactive,
            "invalid_arg_name" => DeleteError::InvalidArgName,
            "invalid_array_arg" => DeleteError::InvalidArrayArg,
            "invalid_charset" => DeleteError::InvalidCharset,
            "invalid_form_data" => DeleteError::InvalidFormData,
            "invalid_post_type" => DeleteError::InvalidPostType,
            "missing_post_type" => DeleteError::MissingPostType,
            "team_added_to_org" => DeleteError::TeamAddedToOrg,
            "request_timeout" => DeleteError::RequestTimeout,
            _ => DeleteError::Unknown(s.to_owned()),
        }
    }
}

impl<E: Error> fmt::Display for DeleteError<E> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.description())
    }
}

impl<E: Error> Error for DeleteError<E> {
    fn description(&self) -> &str {
        match self {
            &DeleteError::MessageNotFound => "message_not_found: No message exists with the requested timestamp.",
            &DeleteError::ChannelNotFound => "channel_not_found: Value passed for channel was invalid.",
            &DeleteError::CantDeleteMessage => "cant_delete_message: Authenticated user does not have permission to delete this message.",
            &DeleteError::ComplianceExportsPreventDeletion => "compliance_exports_prevent_deletion: Compliance exports are on, messages can not be deleted",
            &DeleteError::NotAuthed => "not_authed: No authentication token provided.",
            &DeleteError::InvalidAuth => "invalid_auth: Invalid authentication token.",
            &DeleteError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.",
            &DeleteError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.",
            &DeleteError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.",
            &DeleteError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.",
            &DeleteError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.",
            &DeleteError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.",
            &DeleteError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.",
            &DeleteError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.",
            &DeleteError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.",
            &DeleteError::MalformedResponse(ref e) => e.description(),
            &DeleteError::Unknown(ref s) => s,
            &DeleteError::Client(ref inner) => inner.description(),
        }
    }

    fn cause(&self) -> Option<&Error> {
        match self {
            &DeleteError::MalformedResponse(ref e) => Some(e),
            &DeleteError::Client(ref inner) => Some(inner),
            _ => None,
        }
    }
}

/// Share a me message into a channel.
///
/// Wraps https://api.slack.com/methods/chat.meMessage

pub fn me_message<R>(client: &R,
                     token: &str,
                     request: &MeMessageRequest)
                     -> Result<MeMessageResponse, MeMessageError<R::Error>>
    where R: SlackWebRequestSender
{

    let params = vec![Some(("token", token)),
                      Some(("channel", request.channel)),
                      Some(("text", request.text))];
    let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>();
    let url = ::get_slack_url_for_method("chat.meMessage");
    client
        .send(&url, &params[..])
        .map_err(|err| MeMessageError::Client(err))
        .and_then(|result| {
                      serde_json::from_str::<MeMessageResponse>(&result)
                            .map_err(|e| MeMessageError::MalformedResponse(e))
                  })
        .and_then(|o| o.into())
}

#[derive(Clone, Default, Debug)]
pub struct MeMessageRequest<'a> {
    /// Channel to send message to. Can be a public channel, private group or IM channel. Can be an encoded ID, or a name.
    pub channel: &'a str,
    /// Text of the message to send.
    pub text: &'a str,
}

#[derive(Clone, Debug, Deserialize)]
pub struct MeMessageResponse {
    pub channel: Option<String>,
    error: Option<String>,
    #[serde(default)]
    ok: bool,
    pub ts: Option<String>,
}


impl<E: Error> Into<Result<MeMessageResponse, MeMessageError<E>>> for MeMessageResponse {
    fn into(self) -> Result<MeMessageResponse, MeMessageError<E>> {
        if self.ok {
            Ok(self)
        } else {
            Err(self.error
                    .as_ref()
                    .map(String::as_ref)
                    .unwrap_or("")
                    .into())
        }
    }
}
#[derive(Debug)]
pub enum MeMessageError<E: Error> {
    /// Value passed for channel was invalid.
    ChannelNotFound,
    /// Cannot post user messages to a channel they are not in.
    NotInChannel,
    /// Channel has been archived.
    IsArchived,
    /// Message text is too long
    MsgTooLong,
    /// No message text provided
    NoText,
    /// Application has posted too many messages, read the Rate Limit documentation for more information
    RateLimited,
    /// No authentication token provided.
    NotAuthed,
    /// Invalid authentication token.
    InvalidAuth,
    /// Authentication token is for a deleted user or team.
    AccountInactive,
    /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.
    InvalidArgName,
    /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.
    InvalidArrayArg,
    /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.
    InvalidCharset,
    /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.
    InvalidFormData,
    /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.
    InvalidPostType,
    /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.
    MissingPostType,
    /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.
    TeamAddedToOrg,
    /// The method was called via a POST request, but the POST data was either missing or truncated.
    RequestTimeout,
    /// The response was not parseable as the expected object
    MalformedResponse(serde_json::error::Error),
    /// The response returned an error that was unknown to the library
    Unknown(String),
    /// The client had an error sending the request to Slack
    Client(E),
}

impl<'a, E: Error> From<&'a str> for MeMessageError<E> {
    fn from(s: &'a str) -> Self {
        match s {
            "channel_not_found" => MeMessageError::ChannelNotFound,
            "not_in_channel" => MeMessageError::NotInChannel,
            "is_archived" => MeMessageError::IsArchived,
            "msg_too_long" => MeMessageError::MsgTooLong,
            "no_text" => MeMessageError::NoText,
            "rate_limited" => MeMessageError::RateLimited,
            "not_authed" => MeMessageError::NotAuthed,
            "invalid_auth" => MeMessageError::InvalidAuth,
            "account_inactive" => MeMessageError::AccountInactive,
            "invalid_arg_name" => MeMessageError::InvalidArgName,
            "invalid_array_arg" => MeMessageError::InvalidArrayArg,
            "invalid_charset" => MeMessageError::InvalidCharset,
            "invalid_form_data" => MeMessageError::InvalidFormData,
            "invalid_post_type" => MeMessageError::InvalidPostType,
            "missing_post_type" => MeMessageError::MissingPostType,
            "team_added_to_org" => MeMessageError::TeamAddedToOrg,
            "request_timeout" => MeMessageError::RequestTimeout,
            _ => MeMessageError::Unknown(s.to_owned()),
        }
    }
}

impl<E: Error> fmt::Display for MeMessageError<E> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.description())
    }
}

impl<E: Error> Error for MeMessageError<E> {
    fn description(&self) -> &str {
        match self {
            &MeMessageError::ChannelNotFound => "channel_not_found: Value passed for channel was invalid.",
            &MeMessageError::NotInChannel => "not_in_channel: Cannot post user messages to a channel they are not in.",
            &MeMessageError::IsArchived => "is_archived: Channel has been archived.",
            &MeMessageError::MsgTooLong => "msg_too_long: Message text is too long",
            &MeMessageError::NoText => "no_text: No message text provided",
            &MeMessageError::RateLimited => "rate_limited: Application has posted too many messages, read the Rate Limit documentation for more information",
            &MeMessageError::NotAuthed => "not_authed: No authentication token provided.",
            &MeMessageError::InvalidAuth => "invalid_auth: Invalid authentication token.",
            &MeMessageError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.",
            &MeMessageError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.",
            &MeMessageError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.",
            &MeMessageError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.",
            &MeMessageError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.",
            &MeMessageError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.",
            &MeMessageError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.",
            &MeMessageError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.",
            &MeMessageError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.",
            &MeMessageError::MalformedResponse(ref e) => e.description(),
            &MeMessageError::Unknown(ref s) => s,
            &MeMessageError::Client(ref inner) => inner.description(),
        }
    }

    fn cause(&self) -> Option<&Error> {
        match self {
            &MeMessageError::MalformedResponse(ref e) => Some(e),
            &MeMessageError::Client(ref inner) => Some(inner),
            _ => None,
        }
    }
}

/// Sends a message to a channel.
///
/// Wraps https://api.slack.com/methods/chat.postMessage

pub fn post_message<R>(client: &R,
                       token: &str,
                       request: &PostMessageRequest)
                       -> Result<PostMessageResponse, PostMessageError<R::Error>>
    where R: SlackWebRequestSender
{

    let params =
        vec![Some(("token", token)),
             Some(("channel", request.channel)),
             Some(("text", request.text)),
             request.parse.map(|parse| ("parse", parse)),
             request
                 .link_names
                 .map(|link_names| ("link_names", if link_names { "1" } else { "0" })),
             request
                 .attachments
                 .map(|attachments| ("attachments", attachments)),
             request
                 .unfurl_links
                 .map(|unfurl_links| ("unfurl_links", if unfurl_links { "1" } else { "0" })),
             request
                 .unfurl_media
                 .map(|unfurl_media| ("unfurl_media", if unfurl_media { "1" } else { "0" })),
             request.username.map(|username| ("username", username)),
             request
                 .as_user
                 .map(|as_user| ("as_user", if as_user { "1" } else { "0" })),
             request.icon_url.map(|icon_url| ("icon_url", icon_url)),
             request
                 .icon_emoji
                 .map(|icon_emoji| ("icon_emoji", icon_emoji)),
             request
                 .thread_ts
                 .map(|thread_ts| ("thread_ts", thread_ts)),
             request
                 .reply_broadcast
                 .map(|reply_broadcast| {
                          ("reply_broadcast", if reply_broadcast { "1" } else { "0" })
                      })];
    let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>();
    let url = ::get_slack_url_for_method("chat.postMessage");
    client
        .send(&url, &params[..])
        .map_err(|err| PostMessageError::Client(err))
        .and_then(|result| {
                      serde_json::from_str::<PostMessageResponse>(&result)
                            .map_err(|e| PostMessageError::MalformedResponse(e))
                  })
        .and_then(|o| o.into())
}

#[derive(Clone, Default, Debug)]
pub struct PostMessageRequest<'a> {
    /// Channel, private group, or IM channel to send message to. Can be an encoded ID, or a name. See below for more details.
    pub channel: &'a str,
    /// Text of the message to send. See below for an explanation of formatting. This field is usually required, unless you're providing only attachments instead.
    pub text: &'a str,
    /// Change how messages are treated. Defaults to none. See below.
    pub parse: Option<&'a str>,
    /// Find and link channel names and usernames.
    pub link_names: Option<bool>,
    /// Structured message attachments.
    pub attachments: Option<&'a str>,
    /// Pass true to enable unfurling of primarily text-based content.
    pub unfurl_links: Option<bool>,
    /// Pass false to disable unfurling of media content.
    pub unfurl_media: Option<bool>,
    /// Set your bot's user name. Must be used in conjunction with as_user set to false, otherwise ignored. See authorship below.
    pub username: Option<&'a str>,
    /// Pass true to post the message as the authed user, instead of as a bot. Defaults to false. See authorship below.
    pub as_user: Option<bool>,
    /// URL to an image to use as the icon for this message. Must be used in conjunction with as_user set to false, otherwise ignored. See authorship below.
    pub icon_url: Option<&'a str>,
    /// Emoji to use as the icon for this message. Overrides icon_url. Must be used in conjunction with as_user set to false, otherwise ignored. See authorship below.
    pub icon_emoji: Option<&'a str>,
    /// Provide another message's ts value to make this message a reply. Avoid using a reply's ts value; use its parent instead.
    pub thread_ts: Option<&'a str>,
    /// Used in conjunction with thread_ts and indicates whether reply should be made visible to everyone in the channel or conversation. Defaults to false.
    pub reply_broadcast: Option<bool>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct PostMessageResponse {
    pub channel: Option<String>,
    error: Option<String>,
    pub message: Option<::Message>,
    #[serde(default)]
    ok: bool,
    pub ts: Option<String>,
}


impl<E: Error> Into<Result<PostMessageResponse, PostMessageError<E>>> for PostMessageResponse {
    fn into(self) -> Result<PostMessageResponse, PostMessageError<E>> {
        if self.ok {
            Ok(self)
        } else {
            Err(self.error
                    .as_ref()
                    .map(String::as_ref)
                    .unwrap_or("")
                    .into())
        }
    }
}
#[derive(Debug)]
pub enum PostMessageError<E: Error> {
    /// Value passed for channel was invalid.
    ChannelNotFound,
    /// Cannot post user messages to a channel they are not in.
    NotInChannel,
    /// Channel has been archived.
    IsArchived,
    /// Message text is too long
    MsgTooLong,
    /// No message text provided
    NoText,
    /// Too many attachments were provided with this message. A maximum of 100 attachments are allowed on a message.
    TooManyAttachments,
    /// Application has posted too many messages, read the Rate Limit documentation for more information
    RateLimited,
    /// No authentication token provided.
    NotAuthed,
    /// Invalid authentication token.
    InvalidAuth,
    /// Authentication token is for a deleted user or team.
    AccountInactive,
    /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.
    InvalidArgName,
    /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.
    InvalidArrayArg,
    /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.
    InvalidCharset,
    /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.
    InvalidFormData,
    /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.
    InvalidPostType,
    /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.
    MissingPostType,
    /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.
    TeamAddedToOrg,
    /// The method was called via a POST request, but the POST data was either missing or truncated.
    RequestTimeout,
    /// The response was not parseable as the expected object
    MalformedResponse(serde_json::error::Error),
    /// The response returned an error that was unknown to the library
    Unknown(String),
    /// The client had an error sending the request to Slack
    Client(E),
}

impl<'a, E: Error> From<&'a str> for PostMessageError<E> {
    fn from(s: &'a str) -> Self {
        match s {
            "channel_not_found" => PostMessageError::ChannelNotFound,
            "not_in_channel" => PostMessageError::NotInChannel,
            "is_archived" => PostMessageError::IsArchived,
            "msg_too_long" => PostMessageError::MsgTooLong,
            "no_text" => PostMessageError::NoText,
            "too_many_attachments" => PostMessageError::TooManyAttachments,
            "rate_limited" => PostMessageError::RateLimited,
            "not_authed" => PostMessageError::NotAuthed,
            "invalid_auth" => PostMessageError::InvalidAuth,
            "account_inactive" => PostMessageError::AccountInactive,
            "invalid_arg_name" => PostMessageError::InvalidArgName,
            "invalid_array_arg" => PostMessageError::InvalidArrayArg,
            "invalid_charset" => PostMessageError::InvalidCharset,
            "invalid_form_data" => PostMessageError::InvalidFormData,
            "invalid_post_type" => PostMessageError::InvalidPostType,
            "missing_post_type" => PostMessageError::MissingPostType,
            "team_added_to_org" => PostMessageError::TeamAddedToOrg,
            "request_timeout" => PostMessageError::RequestTimeout,
            _ => PostMessageError::Unknown(s.to_owned()),
        }
    }
}

impl<E: Error> fmt::Display for PostMessageError<E> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.description())
    }
}

impl<E: Error> Error for PostMessageError<E> {
    fn description(&self) -> &str {
        match self {
            &PostMessageError::ChannelNotFound => "channel_not_found: Value passed for channel was invalid.",
            &PostMessageError::NotInChannel => "not_in_channel: Cannot post user messages to a channel they are not in.",
            &PostMessageError::IsArchived => "is_archived: Channel has been archived.",
            &PostMessageError::MsgTooLong => "msg_too_long: Message text is too long",
            &PostMessageError::NoText => "no_text: No message text provided",
            &PostMessageError::TooManyAttachments => "too_many_attachments: Too many attachments were provided with this message. A maximum of 100 attachments are allowed on a message.",
            &PostMessageError::RateLimited => "rate_limited: Application has posted too many messages, read the Rate Limit documentation for more information",
            &PostMessageError::NotAuthed => "not_authed: No authentication token provided.",
            &PostMessageError::InvalidAuth => "invalid_auth: Invalid authentication token.",
            &PostMessageError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.",
            &PostMessageError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.",
            &PostMessageError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.",
            &PostMessageError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.",
            &PostMessageError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.",
            &PostMessageError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.",
            &PostMessageError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.",
            &PostMessageError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.",
            &PostMessageError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.",
            &PostMessageError::MalformedResponse(ref e) => e.description(),
            &PostMessageError::Unknown(ref s) => s,
            &PostMessageError::Client(ref inner) => inner.description(),
        }
    }

    fn cause(&self) -> Option<&Error> {
        match self {
            &PostMessageError::MalformedResponse(ref e) => Some(e),
            &PostMessageError::Client(ref inner) => Some(inner),
            _ => None,
        }
    }
}

/// Unfurl a URL that a user posted
///
/// Wraps https://api.slack.com/methods/chat.unfurl

pub fn unfurl<R>(client: &R,
                 token: &str,
                 request: &UnfurlRequest)
                 -> Result<UnfurlResponse, UnfurlError<R::Error>>
    where R: SlackWebRequestSender
{

    let params = vec![Some(("token", token)),
                      Some(("channel", request.channel)),
                      Some(("ts", request.ts)),
                      Some(("unfurls", request.unfurls)),
                      request
                          .user_auth_required
                          .map(|user_auth_required| {
                                   ("user_auth_required",
                                    if user_auth_required { "1" } else { "0" })
                               })];
    let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>();
    let url = ::get_slack_url_for_method("chat.unfurl");
    client
        .send(&url, &params[..])
        .map_err(|err| UnfurlError::Client(err))
        .and_then(|result| {
                      serde_json::from_str::<UnfurlResponse>(&result)
                            .map_err(|e| UnfurlError::MalformedResponse(e))
                  })
        .and_then(|o| o.into())
}

#[derive(Clone, Default, Debug)]
pub struct UnfurlRequest<'a> {
    /// Channel ID of the message
    pub channel: &'a str,
    /// Timestamp of the message to add unfurl behavior to
    pub ts: &'a str,
    /// JSON mapping a set of URLs from the message to their unfurl attachments
    pub unfurls: &'a str,
    /// Set to true or 1 to indicate the user must install your Slack app to trigger unfurls for this domain
    pub user_auth_required: Option<bool>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct UnfurlResponse {
    error: Option<String>,
    #[serde(default)]
    ok: bool,
}


impl<E: Error> Into<Result<UnfurlResponse, UnfurlError<E>>> for UnfurlResponse {
    fn into(self) -> Result<UnfurlResponse, UnfurlError<E>> {
        if self.ok {
            Ok(self)
        } else {
            Err(self.error
                    .as_ref()
                    .map(String::as_ref)
                    .unwrap_or("")
                    .into())
        }
    }
}
#[derive(Debug)]
pub enum UnfurlError<E: Error> {
    /// No authentication token provided.
    NotAuthed,
    /// Invalid authentication token.
    InvalidAuth,
    /// Authentication token is for a deleted user or team.
    AccountInactive,
    /// This method cannot be called by a bot user.
    UserIsBot,
    /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.
    InvalidArgName,
    /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.
    InvalidArrayArg,
    /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.
    InvalidCharset,
    /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.
    InvalidFormData,
    /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.
    InvalidPostType,
    /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.
    MissingPostType,
    /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.
    TeamAddedToOrg,
    /// The method was called via a POST request, but the POST data was either missing or truncated.
    RequestTimeout,
    /// The response was not parseable as the expected object
    MalformedResponse(serde_json::error::Error),
    /// The response returned an error that was unknown to the library
    Unknown(String),
    /// The client had an error sending the request to Slack
    Client(E),
}

impl<'a, E: Error> From<&'a str> for UnfurlError<E> {
    fn from(s: &'a str) -> Self {
        match s {
            "not_authed" => UnfurlError::NotAuthed,
            "invalid_auth" => UnfurlError::InvalidAuth,
            "account_inactive" => UnfurlError::AccountInactive,
            "user_is_bot" => UnfurlError::UserIsBot,
            "invalid_arg_name" => UnfurlError::InvalidArgName,
            "invalid_array_arg" => UnfurlError::InvalidArrayArg,
            "invalid_charset" => UnfurlError::InvalidCharset,
            "invalid_form_data" => UnfurlError::InvalidFormData,
            "invalid_post_type" => UnfurlError::InvalidPostType,
            "missing_post_type" => UnfurlError::MissingPostType,
            "team_added_to_org" => UnfurlError::TeamAddedToOrg,
            "request_timeout" => UnfurlError::RequestTimeout,
            _ => UnfurlError::Unknown(s.to_owned()),
        }
    }
}

impl<E: Error> fmt::Display for UnfurlError<E> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.description())
    }
}

impl<E: Error> Error for UnfurlError<E> {
    fn description(&self) -> &str {
        match self {
            &UnfurlError::NotAuthed => "not_authed: No authentication token provided.",
            &UnfurlError::InvalidAuth => "invalid_auth: Invalid authentication token.",
            &UnfurlError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.",
            &UnfurlError::UserIsBot => "user_is_bot: This method cannot be called by a bot user.",
            &UnfurlError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.",
            &UnfurlError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.",
            &UnfurlError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.",
            &UnfurlError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.",
            &UnfurlError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.",
            &UnfurlError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.",
            &UnfurlError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.",
            &UnfurlError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.",
            &UnfurlError::MalformedResponse(ref e) => e.description(),
            &UnfurlError::Unknown(ref s) => s,
            &UnfurlError::Client(ref inner) => inner.description(),
        }
    }

    fn cause(&self) -> Option<&Error> {
        match self {
            &UnfurlError::MalformedResponse(ref e) => Some(e),
            &UnfurlError::Client(ref inner) => Some(inner),
            _ => None,
        }
    }
}

/// Updates a message.
///
/// Wraps https://api.slack.com/methods/chat.update

pub fn update<R>(client: &R,
                 token: &str,
                 request: &UpdateRequest)
                 -> Result<UpdateResponse, UpdateError<R::Error>>
    where R: SlackWebRequestSender
{

    let params =
        vec![Some(("token", token)),
             Some(("ts", request.ts)),
             Some(("channel", request.channel)),
             Some(("text", request.text)),
             request
                 .attachments
                 .map(|attachments| ("attachments", attachments)),
             request.parse.map(|parse| ("parse", parse)),
             request
                 .link_names
                 .map(|link_names| ("link_names", if link_names { "1" } else { "0" })),
             request
                 .as_user
                 .map(|as_user| ("as_user", if as_user { "1" } else { "0" }))];
    let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>();
    let url = ::get_slack_url_for_method("chat.update");
    client
        .send(&url, &params[..])
        .map_err(|err| UpdateError::Client(err))
        .and_then(|result| {
                      serde_json::from_str::<UpdateResponse>(&result)
                            .map_err(|e| UpdateError::MalformedResponse(e))
                  })
        .and_then(|o| o.into())
}

#[derive(Clone, Default, Debug)]
pub struct UpdateRequest<'a> {
    /// Timestamp of the message to be updated.
    pub ts: &'a str,
    /// Channel containing the message to be updated.
    pub channel: &'a str,
    /// New text for the message, using the default formatting rules.
    pub text: &'a str,
    /// Structured message attachments.
    pub attachments: Option<&'a str>,
    /// Change how messages are treated. Defaults to client, unlike chat.postMessage. See below.
    pub parse: Option<&'a str>,
    /// Find and link channel names and usernames. Defaults to none. This parameter should be used in conjunction with parse. To set link_names to 1, specify a parse mode of full.
    pub link_names: Option<bool>,
    /// Pass true to update the message as the authed user. Bot users in this context are considered authed users.
    pub as_user: Option<bool>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct UpdateResponse {
    pub channel: Option<String>,
    error: Option<String>,
    #[serde(default)]
    ok: bool,
    pub text: Option<String>,
    pub ts: Option<String>,
}


impl<E: Error> Into<Result<UpdateResponse, UpdateError<E>>> for UpdateResponse {
    fn into(self) -> Result<UpdateResponse, UpdateError<E>> {
        if self.ok {
            Ok(self)
        } else {
            Err(self.error
                    .as_ref()
                    .map(String::as_ref)
                    .unwrap_or("")
                    .into())
        }
    }
}
#[derive(Debug)]
pub enum UpdateError<E: Error> {
    /// No message exists with the requested timestamp.
    MessageNotFound,
    /// Authenticated user does not have permission to update this message.
    CantUpdateMessage,
    /// Value passed for channel was invalid.
    ChannelNotFound,
    /// The message cannot be edited due to the team message edit settings
    EditWindowClosed,
    /// Message text is too long
    MsgTooLong,
    /// Too many attachments were provided with this message. A maximum of 100 attachments are allowed on a message.
    TooManyAttachments,
    /// No message text provided
    NoText,
    /// No authentication token provided.
    NotAuthed,
    /// Invalid authentication token.
    InvalidAuth,
    /// Authentication token is for a deleted user or team.
    AccountInactive,
    /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.
    InvalidArgName,
    /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.
    InvalidArrayArg,
    /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.
    InvalidCharset,
    /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.
    InvalidFormData,
    /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.
    InvalidPostType,
    /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.
    MissingPostType,
    /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.
    TeamAddedToOrg,
    /// The method was called via a POST request, but the POST data was either missing or truncated.
    RequestTimeout,
    /// The response was not parseable as the expected object
    MalformedResponse(serde_json::error::Error),
    /// The response returned an error that was unknown to the library
    Unknown(String),
    /// The client had an error sending the request to Slack
    Client(E),
}

impl<'a, E: Error> From<&'a str> for UpdateError<E> {
    fn from(s: &'a str) -> Self {
        match s {
            "message_not_found" => UpdateError::MessageNotFound,
            "cant_update_message" => UpdateError::CantUpdateMessage,
            "channel_not_found" => UpdateError::ChannelNotFound,
            "edit_window_closed" => UpdateError::EditWindowClosed,
            "msg_too_long" => UpdateError::MsgTooLong,
            "too_many_attachments" => UpdateError::TooManyAttachments,
            "no_text" => UpdateError::NoText,
            "not_authed" => UpdateError::NotAuthed,
            "invalid_auth" => UpdateError::InvalidAuth,
            "account_inactive" => UpdateError::AccountInactive,
            "invalid_arg_name" => UpdateError::InvalidArgName,
            "invalid_array_arg" => UpdateError::InvalidArrayArg,
            "invalid_charset" => UpdateError::InvalidCharset,
            "invalid_form_data" => UpdateError::InvalidFormData,
            "invalid_post_type" => UpdateError::InvalidPostType,
            "missing_post_type" => UpdateError::MissingPostType,
            "team_added_to_org" => UpdateError::TeamAddedToOrg,
            "request_timeout" => UpdateError::RequestTimeout,
            _ => UpdateError::Unknown(s.to_owned()),
        }
    }
}

impl<E: Error> fmt::Display for UpdateError<E> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.description())
    }
}

impl<E: Error> Error for UpdateError<E> {
    fn description(&self) -> &str {
        match self {
            &UpdateError::MessageNotFound => "message_not_found: No message exists with the requested timestamp.",
            &UpdateError::CantUpdateMessage => "cant_update_message: Authenticated user does not have permission to update this message.",
            &UpdateError::ChannelNotFound => "channel_not_found: Value passed for channel was invalid.",
            &UpdateError::EditWindowClosed => "edit_window_closed: The message cannot be edited due to the team message edit settings",
            &UpdateError::MsgTooLong => "msg_too_long: Message text is too long",
            &UpdateError::TooManyAttachments => "too_many_attachments: Too many attachments were provided with this message. A maximum of 100 attachments are allowed on a message.",
            &UpdateError::NoText => "no_text: No message text provided",
            &UpdateError::NotAuthed => "not_authed: No authentication token provided.",
            &UpdateError::InvalidAuth => "invalid_auth: Invalid authentication token.",
            &UpdateError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.",
            &UpdateError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.",
            &UpdateError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.",
            &UpdateError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.",
            &UpdateError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.",
            &UpdateError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.",
            &UpdateError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.",
            &UpdateError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.",
            &UpdateError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.",
            &UpdateError::MalformedResponse(ref e) => e.description(),
            &UpdateError::Unknown(ref s) => s,
            &UpdateError::Client(ref inner) => inner.description(),
        }
    }

    fn cause(&self) -> Option<&Error> {
        match self {
            &UpdateError::MalformedResponse(ref e) => Some(e),
            &UpdateError::Client(ref inner) => Some(inner),
            _ => None,
        }
    }
}