public bool Post(SlackMessage slackMessage)
        {
            if(_messageCallback != null)
            {
                _messageCallback(slackMessage);
            }

            Debug.WriteLine("Slack message posted.");
            Debug.WriteLine(string.Format("	  Channel: {0}", slackMessage.Channel));
            Debug.WriteLine(string.Format("	IconEmoji: {0}", slackMessage.IconEmoji));
            Debug.WriteLine(string.Format("	   Mrkdwn: {0}", slackMessage.Mrkdwn));
            Debug.WriteLine(string.Format("	     Text: {0}", slackMessage.Text));
            Debug.WriteLine(string.Format("	 Username: {0}", slackMessage.Username));
            //foreach(var slackAttachment in slackMessage.Attachments)
            //{
            //    Debug.WriteLine(string.Format("	 Attachment: {0}", slackAttachment.Username));

            //}

            //if(_shouldThrowError)
            //{
            //    throw new MockClientException("Mock slack client thrown exception.");
            //}

            return _returnValue;
        }
示例#2
0
        public async Task <Tuple <bool, string> > SendMessage(SlackMessage message)
        {
            try
            {
                SlackAPI.SlackMessage slackMessage = new SlackAPI.SlackMessage
                {
                    Username = message.Username,
                    Channel  = message.Channel,
                    Text     = message.Message
                };

                if (!string.IsNullOrWhiteSpace(message.Emoji) && Enum.TryParse(message.Emoji, out SlackAPI.Emoji emoji))
                {
                    slackMessage.IconEmoji = emoji;
                }

                SlackAPI.SlackClient slackClient = new SlackAPI.SlackClient(message.WebHookURL);
                bool sendResult = await slackClient.PostAsync(slackMessage);

                return(new Tuple <bool, string>(sendResult, null));
            }
            catch (Exception ex)
            {
                return(new Tuple <bool, string>(false, $"Failed to send message to slack ({ex.Message})."));
            }
        }
        public void CreateDefaultMessage_CreatesExpectedMessage(SlackAttribute attribute, SlackConfiguration config, Dictionary<string, object> bindingData, INameResolver nameResolver,SlackMessage targetMessage, String targetUrl)
        {
            ParameterInfo parameter = GetType().GetMethod("TestMethod", BindingFlags.Static | BindingFlags.NonPublic).GetParameters().First();
            Dictionary<string, Type> contract = new Dictionary<string, Type>
            {
                {"ChannelParam", typeof(string) },
                {"IconParam", typeof(string) },
                {"TextParam", typeof(string) },
                {"UsernameParam", typeof(string) },
                {"WebHookUrlParam", typeof(string) }
            };

            BindingProviderContext context = new BindingProviderContext(parameter, contract, CancellationToken.None);
            SlackBinding binding = new SlackBinding(parameter, attribute, config, nameResolver, context);
            
            // Generate message with input data
            SlackMessage message = binding.CreateDefaultMessage(bindingData);

            // Check that the right values were used to initialize the funtion
            Assert.Equal(targetMessage.Channel, message.Channel);
            Assert.Equal(targetMessage.IconEmoji, message.IconEmoji);
            Assert.Equal(targetMessage.Text, message.Text);
            Assert.Equal(targetMessage.Username, message.Username);
            Assert.Equal(targetMessage.Mrkdwn, message.Mrkdwn);
            Assert.Equal(targetUrl, binding._client.BaseUrl);
        }
        public bool ReportException(Exception ex, WebHookOptions options)
        {
            if(options == null)
            {
                throw new NullReferenceException(
                    "An instance of WebHookOptions must be provided as it contains the details for connecting to the Slack web hook.");
            }
            if(string.IsNullOrEmpty(options.WebhookUrl))
            {
                throw new ArgumentException(
                    "WebHookOptions.WebhookUrl must contain a value. Please provide the URL to your Slack team webhook.");
            }

            var message = new WebHooks.SlackMessage();
            if(!string.IsNullOrEmpty(options.ChannelName))
            {
                message.Channel = options.ChannelName;
            }
            if(!string.IsNullOrEmpty(options.UserName))
            {
                message.Username = options.UserName;
            }

            message.IconEmoji = options.IconEmoji ?? WebHooks.Emoji.HeavyExclamationMark;

            message.Text = options.Text ?? DEFAULT_TEXT;

            var attachment = new WebHooks.SlackAttachment();
            // simple message for unformatted and notification views
            attachment.Fallback = string.Format("Web app exception: {0}", ex.Message);
            attachment.Color = options.AttachmentColor ?? DEFAULT_COLOR;

            if(!string.IsNullOrEmpty(options.AttachmentTitle))
            {
                attachment.Title = options.AttachmentTitle;
            }
            if(!string.IsNullOrEmpty(options.AttachmentTitleLink))
            {
                attachment.TitleLink = options.AttachmentTitleLink;
            }
            attachment.MrkdwnIn = new List<string> { "text" };
            var textFormat = !string.IsNullOrWhiteSpace(options.ExceptionTextFormat) ? options.ExceptionTextFormat : DEFAULT_FORMAT;

            var requestUrl = HttpContext.Current != null ? HttpContext.Current.Request.Url.ToString() : "[no HttpContext available]";

            attachment.Text = textFormat
                .Replace("%%url%%", requestUrl)
                .Replace("%%hostname%%", Environment.MachineName)
                .Replace("%%ex:type%%", ex.GetType().ToString())
                .Replace("%%ex:message%%", ex.Message)
                .Replace("%%ex:site%%", ex.TargetSite != null ? ex.TargetSite.ToString() : "")
                .Replace("%%ex:stackTrace%%", ex.StackTrace);

            message.Attachments = new List<WebHooks.SlackAttachment>();
            message.Attachments.Add(attachment);

            return _client.Post(message);
        }
示例#5
0
		private void SlackPost(string message)
		{
			var client = new SlackClient(ConfigurationManager.AppSettings["SlackWebHookUrl"]);
			var slackMessage = new SlackMessage
			{
				Channel = "#test",
				Text = message,
				IconEmoji = Emoji.Octocat,
				Username = "******"
			};
			client.Post(slackMessage);
		}
示例#6
0
		private void SlackPost(string message)
		{
			var client = new SlackClient(ConfigurationManager.AppSettings["SlackWebHookUrl"]);
			var channel = ConfigurationManager.AppSettings["PostChannel"];
			var slackMessage = new SlackMessage
			{
				Channel = channel,
				Text = message,
				IconEmoji = ":slack:",
				Username = "******"
			};
			client.Post(slackMessage);
		}
 public bool Post(SlackMessage slackMessage)
 {
     var request = new RestRequest(_webhookUri.PathAndQuery, Method.POST);
     request.AddParameter("payload", slackMessage.ToJson());
     try
     {
         var response = _restClient.Execute(request);
         return response.StatusCode == HttpStatusCode.OK && response.Content == POST_SUCCESS;
     }
     catch (Exception)
     {
         return false;
     }
 }
示例#8
0
        public virtual bool Post(SlackMessage slackMessage)
        {
            var request = new RestRequest(_webhookUri.PathAndQuery, Method.POST);
            using (var scope = JsConfig.BeginScope())
            {
                scope.EmitLowercaseUnderscoreNames = true;
                scope.IncludeNullValues = false;
                SetPropertyConvention(scope);
                
                request.AddParameter("payload", JsonSerializer.SerializeToString(slackMessage));

                try
                {
                    var response = _restClient.Execute(request);
                    return response.StatusCode == HttpStatusCode.OK && response.Content == POST_SUCCESS;
                }
                catch (Exception)
                {
                    return false;
                }
            }
        }
 private async Task<IRestResponse> ExecuteRequest(RestClient client, SlackMessage message, CancellationToken cancellationToken)
 {
     RestRequest req = new RestRequest(Method.POST);
     req.RequestFormat = DataFormat.Json;
     req.AddBody(message);
     var config = new JsonSerializerSettings();
     config.NullValueHandling = NullValueHandling.Ignore;
     config.ContractResolver = new SlackJsonNameContractResolver();
     req.Parameters[0].Value = JsonConvert.SerializeObject(message, config);
     return await Task.Run(
         () => {
             var results = client.Execute(req);
             return results;
         }, 
         cancellationToken);
 }
 public SlackValueBinder(RestClient client, SlackMessage message)
 {
     _client = client;
     _message = message;
 }
示例#11
0
 public IEnumerable <Task <bool> > PostToChannelsAsync(SlackMessage message, IEnumerable <string> channels)
 {
     return(channels.DefaultIfEmpty(message.Channel)
            .Select(message.Clone)
            .Select(PostAsync));
 }
示例#12
0
 public bool PostToChannels(SlackMessage message, IEnumerable <string> channels)
 {
     return(channels.DefaultIfEmpty(message.Channel)
            .Select(message.Clone)
            .Select(Post).All(r => r));
 }
示例#13
0
 public async Task <bool> PostAsync(SlackMessage slackMessage)
 {
     return(await PostAsync(slackMessage, true));
 }
示例#14
0
 public virtual bool Post(SlackMessage slackMessage)
 {
     return(PostAsync(slackMessage, false).Result);
 }
示例#15
0
 public bool Post(Webhooks.SlackMessage slackMessage)
 {
     return(_slackClient.Post(slackMessage));
 }
        public SlackMessage CreateDefaultMessage(IReadOnlyDictionary<string, object> bindingData)
        {
            SlackMessage message = new SlackMessage();

            // Set message
            if(_textBindingTemplate != null)
            {
                message.Text = _textBindingTemplate.Bind(bindingData);
            }

            // Set channel
            if(_channelBindingTemplate != null)
            {
                message.Channel = _channelBindingTemplate.Bind(bindingData);
            }
            else if(!string.IsNullOrEmpty(_config.Channel))
            {
                message.Channel = _config.Channel;
            }

            // Set icon emoji
            if(_iconEmojiBindingTemplate != null)
            {
                message.IconEmoji = _iconEmojiBindingTemplate.Bind(bindingData);
            }
            else if(!string.IsNullOrEmpty(_config.IconEmoji))
            {
                message.IconEmoji = _config.IconEmoji;
            }

            // Set markdown
            if (_iconEmojiBindingTemplate != null)
            {
                message.Mrkdwn = _attribute.IsMarkdown;
            }
            else if (!string.IsNullOrEmpty(_config.IconEmoji))
            {
                message.Mrkdwn = _config.IsMarkdown;
            }

            // Set username
            if (_usernameBindingTemplate != null)
            {
                message.Username = _usernameBindingTemplate.Bind(bindingData);
            }
            else if(!string.IsNullOrEmpty(_config.Username))
            {
                message.Username = _config.Username;
            }

            if(_webHookUrlBindingTemplate != null)
            {
                _client = new RestClient(_webHookUrlBindingTemplate.Bind(bindingData));
            }
            else if(!string.IsNullOrEmpty(_config.WebHookUrl))
            {
                _client = new RestClient(_config.WebHookUrl);
            }

            return message;
        }
示例#17
0
 public IEnumerable<Task<IRestResponse>> PostToChannelsAsync(SlackMessage message, IEnumerable<string> channels)
 {
     return channels.DefaultIfEmpty(message.Channel)
                         .Select(message.Clone)
                         .Select(PostAsync);
 }
 private void SendError(bool logToSlack, string package, string exception)
 {
     Trace.TraceError("Unable to create package {0}, {1}", package, exception);
     if (logToSlack && _slackUrl!=null)
     {
         try
         {
             var slackClient = new SlackClient(_slackUrl);
             var slackMessage = new SlackMessage
             {
                 Channel = _slackChannel,
                 Text = $"*Upload for {package} failed*\n{exception}",
                 Username = _slackUsername
             };
             slackClient.Post(slackMessage);
         }
         catch (Exception slackException)
         {
             Trace.TraceError($"Unable to send message to slack {slackException.Message}");
         }
     }
 }
 public SlackValueBinderTests()
 {
     RestClient client = new RestClient("1234");
     _message = new SlackMessage();
     _valueBinder = new SlackValueBinder(client, _message);
 }
示例#20
0
		public bool PostToChannels(SlackMessage message, IEnumerable<string> channels)
		{
			return channels.DefaultIfEmpty(message.Channel)
					.Select(message.Clone)
					.Select(Post).All(r => r);
		}
示例#21
0
        public virtual bool Post(SlackMessage slackMessage)
        {
            var result = PostAsync(slackMessage).GetAwaiter().GetResult();

            return(result);
        }
示例#22
0
        public Task<IRestResponse> PostAsync(SlackMessage slackMessage)
        {
            var request = new RestRequest(_webhookUri.PathAndQuery, Method.POST);

            request.AddParameter("payload", JsonSerializer.SerializeToString(slackMessage));

            return ExecuteTaskAsync(request);
        }
示例#23
0
        public virtual bool Post(SlackMessage slackMessage)
        {
            var result = PostAsync(slackMessage);

            return(result.Result);
        }
示例#24
0
        private void CheckFeed()
        {
            var atomUrl = ConfigurationManager.AppSettings["atom-url"];

            Console.WriteLine("Checking feed {0}", atomUrl);
            WebRequest atomRequest = WebRequest.Create(atomUrl);

            using (WebResponse atomResponse = atomRequest.GetResponse())
            using (XmlReader reader = XmlReader.Create(atomResponse.GetResponseStream()))
            {
                SyndicationFeed feed = SyndicationFeed.Load(reader);

                if (feed != null)
                {
                    if (!_lastPostTime.HasValue) _lastPostTime = feed.Items.First().LastUpdatedTime;

                    foreach (var item in feed.Items.Where(i => i.LastUpdatedTime > _lastPostTime))
                    {
                        Console.WriteLine("{0} is new posting", item.Id);
                        var imgUrl = Regex.Match(item.Summary.Text, _srcRegex, RegexOptions.IgnoreCase).Groups[1].Value;
                        var title = Regex.Match(item.Summary.Text, _titleRegex, RegexOptions.IgnoreCase).Groups[1].Value;
                        Console.WriteLine("Image Url: {0}", imgUrl);
                        Console.WriteLine("Image Title: {0}", title);
                        var message = new SlackMessage
                        {
                            Username = "******",
                            IconUrl = new Uri("http://cdn.androidpolice.com/wp-content/uploads/2013/02/nexusae0_image59.png"),
                            Attachments = new List<SlackAttachment>
                            {
                                new SlackAttachment
                                {
                                    ImageUrl = imgUrl,
                                    Title = title
                                }
                            }
                        };
                        _client.Post(message);

                    }
                }
            }
            if (!_cts.IsCancellationRequested)
            {
                Task.Delay(_interval, _cts.Token).ContinueWith(_ => CheckFeed(), _cts.Token);
            }
        }
示例#25
0
        public bool ReportException(Exception ex, WebHookOptions options)
        {
            if (options == null)
            {
                throw new NullReferenceException(
                          "An instance of WebHookOptions must be provided as it contains the details for connecting to the Slack web hook.");
            }
            if (string.IsNullOrEmpty(options.WebhookUrl))
            {
                throw new ArgumentException(
                          "WebHookOptions.WebhookUrl must contain a value. Please provide the URL to your Slack team webhook.");
            }

            var message = new WebHooks.SlackMessage();

            if (!string.IsNullOrEmpty(options.ChannelName))
            {
                message.Channel = options.ChannelName;
            }
            if (!string.IsNullOrEmpty(options.UserName))
            {
                message.Username = options.UserName;
            }

            message.IconEmoji = options.IconEmoji ?? WebHooks.Emoji.HeavyExclamationMark;

            message.Text = options.Text ?? DEFAULT_TEXT;

            var attachment = new WebHooks.SlackAttachment();

            // simple message for unformatted and notification views
            attachment.Fallback = string.Format("Web app exception: {0}", ex.Message);
            attachment.Color    = options.AttachmentColor ?? DEFAULT_COLOR;

            if (!string.IsNullOrEmpty(options.AttachmentTitle))
            {
                attachment.Title = options.AttachmentTitle;
            }
            if (!string.IsNullOrEmpty(options.AttachmentTitleLink))
            {
                attachment.TitleLink = options.AttachmentTitleLink;
            }
            attachment.MrkdwnIn = new List <string> {
                "text"
            };
            var textFormat = !string.IsNullOrWhiteSpace(options.ExceptionTextFormat) ? options.ExceptionTextFormat : DEFAULT_FORMAT;

            var requestUrl = HttpContext.Current != null?HttpContext.Current.Request.Url.ToString() : "[no HttpContext available]";

            attachment.Text = textFormat
                              .Replace("%%url%%", requestUrl)
                              .Replace("%%hostname%%", Environment.MachineName)
                              .Replace("%%ex:type%%", ex.GetType().ToString())
                              .Replace("%%ex:message%%", ex.Message)
                              .Replace("%%ex:site%%", ex.TargetSite != null ? ex.TargetSite.ToString() : "")
                              .Replace("%%ex:stackTrace%%", ex.StackTrace);

            message.Attachments = new List <WebHooks.SlackAttachment>();
            message.Attachments.Add(attachment);

            return(_client.Post(message));
        }