public void Initialize(ExtensionConfigContext context)
        {
            context.AddConverter <JObject, SlackMessage>(ConvertSlackMessage);

            var rule = context.AddBindingRule <SlackAttribute>();

            rule.AddValidator(ValidateBinding);
            rule.BindToCollector <SlackMessage>(attribute =>
            {
                var apiKey     = Utility.FirstOrDefault(attribute.ApiKey, _options.ApiKey);
                var webHookUrl = Utility.FirstOrDefault(attribute.WebHookUrl, _options.WebHookUrl);
                var iconUrl    = attribute.IconUrl;
                var iconEmoji  = attribute.IconEmoji;
                var userName   = attribute.Username;

                var slackContext = new SlackContext
                {
                    ApiKey     = apiKey,
                    WebHookUrl = webHookUrl,
                    Channel    = attribute.Channel,
                    IconUrl    = iconUrl,
                    IconEmoji  = iconEmoji,
                    UserName   = userName
                };

                return(new SlackMessageAsyncCollector(slackContext, _slackHttpClient, _slackLogger));
            });
        }
Example #2
0
 public SlackMessageAsyncCollector(SlackContext context,
                                   ISlackHttpClient slackHttpClient,
                                   ILogger logger)
 {
     _context         = context;
     _slackHttpClient = slackHttpClient;
     _logger          = logger;
 }
 public static SlackContext AddImage(this SlackContext context, string imageUrl, string altText = default)
 {
     if (context.Elements == null)
     {
         context.Elements = new List <object>();
     }
     context.Elements.Add(new SlackImage {
         ImageUrl = imageUrl, AltText = altText
     });
     return(context);
 }
 public static SlackContext AddMarkdown(this SlackContext context, string markdown)
 {
     if (context.Elements == null)
     {
         context.Elements = new List <object>();
     }
     context.Elements.Add(new SlackMarkdown {
         Text = markdown
     });
     return(context);
 }
 public static SlackContext AddPlainText(this SlackContext context, string text, bool emoji = true)
 {
     if (context.Elements == null)
     {
         context.Elements = new List <object>();
     }
     context.Elements.Add(new SlackPlainText {
         Text = text, Emoji = emoji
     });
     return(context);
 }
Example #6
0
        public async Task collector_should_set_the_asUser_property_to_false_when_asUser_is_true_and_username_is_not_empty()
        {
            var context      = new SlackContext();
            var slackMessage = new SlackMessage();

            slackMessage.Username = "******";
            slackMessage.AsUser   = true;
            slackMessage.Channel  = "#devtest";
            slackMessage.Text     = "Hello!";

            var collector = new SlackMessageAsyncCollector(context, _httpClient, _logger);

            Func <Task> act = async() => { await collector.AddAsync(slackMessage); };

            await act();

            slackMessage.AsUser.Should().Be(false);
        }
        public async Task PostMessageAsync(SlackContext context, SlackMessage message)
        {
            var httpRequestMessage = new HttpRequestMessage();

            if (!string.IsNullOrWhiteSpace(context.ApiKey))
            {
                httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.ApiKey);
                httpRequestMessage.RequestUri            = new Uri("https://slack.com/api/chat.postMessage");
            }
            else
            {
                httpRequestMessage.RequestUri = new Uri(context.WebHookUrl);
            }

            var jsonSerializerSettings = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
                ContractResolver  = new CamelCasePropertyNamesContractResolver()
            };

#if DEBUG
            var formatting = Newtonsoft.Json.Formatting.Indented;
#else
            var formatting = Newtonsoft.Json.Formatting.None;
#endif
            var messageJson = JsonConvert.SerializeObject(message, formatting, jsonSerializerSettings);
            httpRequestMessage.Content = new StringContent(messageJson, Encoding.UTF8, "application/json");
            httpRequestMessage.Method  = HttpMethod.Post;

            _logger.LogDebug("Sending slack message {Id}", message.Id.ToString("D"));
            _logger.LogTrace("Json Message: {Message}", messageJson);
            var response = await _httpClient.SendAsync(httpRequestMessage);

            if (!response.IsSuccessStatusCode)
            {
                var body = await response.Content.ReadAsStringAsync();

                _logger.LogError("Slack message {Id} failed to send: {StatusCode} - {ResponsePhrase} - {Body}", message.Id, response.StatusCode, response.ReasonPhrase, body);
            }
            _logger.LogDebug("Sent slack message {Id}", message.Id.ToString("D"));
        }