예제 #1
0
        /// <summary>
        /// Realiza a postagem de uma mensagem no Slack
        /// </summary>
        /// <param name="mensagem">Mensagem que será postada.</param>
        /// <param name="anexos">Anexos da mensagem</param>
        private bool Postar(SlackMensagem mensagem, List <SlackAttachment> anexos = null)
        {
            if (_slackClient == null)
            {
                return(false);
            }

            var slackMessage = new SlackMessage
            {
                Channel      = !mensagem.Canal.StartsWith("#") ? "#" + mensagem.Canal : mensagem.Canal,
                IconEmoji    = (Emoji)mensagem.TipoEmoji,
                Username     = mensagem.UserName,
                Markdown     = true,
                ResponseType = mensagem.TipoVisibilidade == TipoVisibilidadeSlackMensagem.NoCanal ? "in-channel" : "ephemeral"
            };

            if (anexos?.Any() == true)
            {
                slackMessage.Attachments = anexos;
            }

            try
            {
                return(_slackClient.Post(slackMessage));
            }
            catch
            {
                return(false);
            }
        }
예제 #2
0
        /// <summary>
        /// Post userstory notification to Slack upon successful creation of user story
        /// </summary>
        private void PostSlackUserStoryNotification()
        {
            _objectId              = Ref.GetOidFromRef(_createUserStory.Reference);
            _userStoryUrl          = String.Concat(SLACK.UserStoryUrlFormat, _objectId);
            _slackAttachmentString = String.Format("User Story: <{0} | {1} >", _userStoryUrl, _message.Subject);

            SlackMessage message = new SlackMessage
            {
                Channel  = SLACK.ChannelGeneral,
                Text     = SLACK.SlackNotificationBanner,
                Username = SLACK.SlackUser
            };

            SlackAttachment slackAttachment = new SlackAttachment
            {
                Fallback = _slackAttachmentString,
                Text     = _slackAttachmentString,
                Color    = SLACK.HexColor
            };

            message.Attachments = new List <SlackAttachment> {
                slackAttachment
            };
            _slackClient.Post(message);
        }
예제 #3
0
        /// <summary>
        /// This function is used to send a message through Slack based on the webhook provided.
        /// </summary>
        /// <param name="uri">Webhook</param>
        /// <param name="username">User you want the bot to show up as</param>
        /// <param name="message">The actual message</param>
        /// <param name="slackAttachments">Slack attachments</param>
        public void SendSlackMessage(string uri, string username, string message, Uri IconURL = null, List <SlackAttachment> slackAttachments = null)
        {
            SlackClient  slackClient  = new SlackClient(uri);
            SlackMessage slackMessage = new SlackMessage {
            };

            if (IconURL == null)
            {
                slackMessage = new SlackMessage
                {
                    Username = username,
                    Text     = message
                };
            }
            else
            {
                slackMessage = new SlackMessage
                {
                    Username = username,
                    Text     = message,
                    IconUrl  = IconURL
                };
            }

            if (slackAttachments != null)
            {
                slackMessage.Attachments = new List <SlackAttachment> {
                };
                slackMessage.Attachments.AddRange(slackAttachments);
            }

            slackClient.Post(slackMessage);
        }
예제 #4
0
        public string Post([FromBody] SlackEventWrapper value)
        {
            if (ValidateToken(value.Token))
            {
                if (!string.IsNullOrEmpty(value.Challenge))
                {
                    return(value.Challenge);
                }

                if (value.Event.Type.Equals("message") && !string.IsNullOrEmpty(value.Event.User))
                {
                    var slackClient = new SlackClient("https://hooks.slack.com/services/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");

                    var slackMessage = new SlackMessage
                    {
                        Channel   = value.Event.Channel,
                        Text      = $"I\'m sorry, I don\'t understand! Sometimes I have an easier time with a few simple keywords.",
                        IconEmoji = Emoji.Pizza,
                        Username  = "******"
                    };

                    slackClient.Post(slackMessage);
                }
            }

            return(string.Empty);
        }
        public static void ShowBids(SlackClient agentClient)
        {
            using (var db = new SlackLeadsBidderContext())
            {
                var agentBids = db.Agents.Select(e => new
                {
                    e.Name,
                    e.NextBid
                })
                                .ToList()
                                .GroupBy(e => e.NextBid)
                                .OrderByDescending(e => e.Key)
                                .Select((e, i) => $"[{e.Key}] {string.Join(", ", e.Select(f => f.Name).ToArray())}" + (i == 0 && e.Count() > 1 ? " (winner will selected by random)" : ""))
                                .ToArray();

                var message = new SlackMessage()
                {
                    Attachments = new List <SlackAttachment>()
                    {
                        new SlackAttachment()
                        {
                            Pretext = "Current Bids:",
                            Text    = string.Join("\n", agentBids),
                            Color   = "good"
                        }
                    }
                };

                agentClient.Post(message);
            }
        }
        public static void ShowBalance(SlackClient agentClient)
        {
            using (var db = new SlackLeadsBidderContext())
            {
                var agentCredits = db.Transactions
                                   .GroupBy(e => e.Agent.Name)
                                   .Select(e => new
                {
                    Name    = e.Key,
                    Credits = e.Sum(f => (int?)f.Amount)
                })
                                   .OrderBy(e => e.Name)
                                   .ToArray()
                                   .Select(e => $"[{e.Credits}] {e.Name}")
                                   .ToArray();

                var message = new SlackMessage()
                {
                    Attachments = new List <SlackAttachment>()
                    {
                        new SlackAttachment()
                        {
                            Pretext = "Current Balance:",
                            Text    = string.Join("\n", agentCredits),
                            Color   = "good"
                        }
                    }
                };

                agentClient.Post(message);
            }
        }
        public static void SetAgentNextBid(string slackUser, int amount, SlackClient agentClient)
        {
            lock (ServiceLock)
            {
                using (var db = new SlackLeadsBidderContext())
                {
                    var agent = db.Agents.FirstOrDefault(e => e.SlackId == slackUser);

                    if (agent == null)
                    {
                        agentClient.PostError($"No agent configured for '{slackUser}'");
                        return;
                    }

                    var availableCredits = db.Transactions
                                           .Where(e => e.Agent.SlackId == slackUser)
                                           .Sum(e => (int?)e.Amount) ?? 0;

                    if (availableCredits < amount)
                    {
                        agentClient.PostError($"You don't have enough credits. You're balance is {availableCredits}.");
                        return;
                    }

                    agent.NextBid = amount;
                    db.SaveChanges();

                    var slackClient = new SlackClient(SlackLeadsBidderSettings.Settings.SlackOutgoingWebhook);
                    slackClient.Post(new SlackMessage()
                    {
                        Text = $"Agent @{slackUser} changed bid to {amount}."
                    });
                }
            }
        }
예제 #8
0
        static void Main(string[] args)
        {
            SlackClient  client  = new SlackClient(SlackConstant.webhookURL);
            SlackMessage message = new SlackMessage
            {
                Channel   = "#random",
                Text      = SlackConstant.title,
                IconEmoji = Emoji.SmallRedTriangle,
                Username  = SlackConstant.username
            };

            SlackAttachment attachment = new SlackAttachment
            {
                Fallback = "New open task [Urgent]: <http://url_to_task|Test out Slack message attachments>",
                Text     = "Userstory US667: <https://rally1.rallydev.com/#/36903994832ud/detail/userstory/96328719420 | User Story Title >",
                Color    = "#4ef442",
                Fields   = new List <SlackField>
                {
                    new SlackField
                    {
                        Value = "User Story Description"
                    }
                }
            };

            message.Attachments = new List <SlackAttachment> {
                attachment
            };
            client.Post(message);

            Console.ReadLine();
        }
        public void PostMessageToSlackIfAuthenticated()
        {
            bool isSlackAuthenticated = false;

            SlackClient client =
                new SlackClient("https://hooks.slack.com/services/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", 100);

            isSlackAuthenticated = true;

            SlackMessage message = new SlackMessage
            {
                Channel  = "#general",
                Text     = "*Rally Notification*",
                Username = "******"
            };

            var slackAttachment = new SlackAttachment
            {
                Text = "Slack Unit Test",
            };

            message.Attachments = new List <SlackAttachment> {
                slackAttachment
            };

            if (isSlackAuthenticated == true)
            {
                client.Post(message);
            }

            Assert.IsTrue(isSlackAuthenticated);
        }
예제 #10
0
        public Slack(SlackModel slackConfig, VeeamSession veeamSession)
        {
            // Create a new client
            var client = new SlackClient(slackConfig.WebHook);

            // Set the Veeam Session Data
            _veeamSession = veeamSession;

            // Build the message
            if (!string.IsNullOrEmpty(slackConfig.IconUrl))
            {
                _message.IconUrl = new Uri(slackConfig.IconUrl);
            }
            if (!string.IsNullOrEmpty(slackConfig.Channel))
            {
                _message.Channel = slackConfig.Channel;
            }
            if (!string.IsNullOrEmpty(slackConfig.BotName))
            {
                _message.Username = slackConfig.BotName;
            }

            // Build the rich format with an attachment
            _message.Attachments = new List <SlackAttachment> {
                FormAttachment()
            };

            //Enable TLS 1.2
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            // Post the message
            client.Post(_message);
            Console.WriteLine("Slack message sent.");
        }
예제 #11
0
        public void ShouldContainSerializedMessage()
        {
            //arrange
            const string hookUrl            = "https://hooks.slack.com/invalid";
            SlackMessage postedMessage      = null;
            var          httpMessageHandler = GetMockHttpMessageHandler(callback: (req, token) =>
            {
                var json      = req.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                postedMessage = SlackClient.DeserializeObject(json);
            });

            var httpClient   = new HttpClient(httpMessageHandler.Object, false);
            var client       = new SlackClient(hookUrl, httpClient: httpClient);
            var slackMessage = GetSlackMessage();

            //act
            client.Post(slackMessage);

            //assert
            Assert.NotNull(postedMessage);
            Assert.Equal(slackMessage.Text, postedMessage.Text);
            Assert.Equal(slackMessage.Channel, postedMessage.Channel);
            Assert.Equal(slackMessage.Username, postedMessage.Username);
            Assert.Equal(slackMessage.IconEmoji, postedMessage.IconEmoji);
        }
예제 #12
0
        public bool PostMessage(string message, string iconName)
        {
            var iconEmoji = _config.Icons.FirstOrDefault(x => x.Name == iconName)?.EmojiName;

            var slackMessage = new SlackMessage()
            {
                Channel = _config.Channel, IconEmoji = iconEmoji, Username = _config.Username, Text = message
            };

            return(_client.Post(slackMessage));
        }
예제 #13
0
 public static void SendMessage(SlackMessage slackMessage)
 {
     if (slackClient != null)
     {
         slackClient.Post(slackMessage);
     }
     else
     {
         throw new ArgumentNullException("Slack has not been initialize. Please use slack.initialize first.");
     }
 }
예제 #14
0
        public void Handle()
        {
            var birthdaynotifications = from bn in _context.BirthdayNotifications select bn;
            var workers = from w in _context.Worker select w;

            foreach (var w in workers)
            {
                var bn = _context.BirthdayNotifications.SingleOrDefault(m => m.ID == w.ID);
                if (
                    ((DateTime.Today.Year > bn.LastNotification.Year) && (DateTime.Today.Month == bn.LastNotification.Month) && (DateTime.Today.Day >= bn.LastNotification.Day))
                    ||
                    ((DateTime.Today.Year > bn.LastNotification.Year) && (DateTime.Today.Month > bn.LastNotification.Month))
                    ||
                    ((DateTime.Today.Month == w.BirthdayDate.Month) && (DateTime.Today.Day == w.BirthdayDate.Day))
                    )
                {
                    var slackMessage = new SlackMessage
                    {
                        Channel   = "#general",
                        Text      = "Congratulation:",
                        IconEmoji = Emoji.Cake,
                        Username  = "******"
                    };
                    slackMessage.Mrkdwn = false;
                    var slackAttachment = new SlackAttachment
                    {
                        Fallback = w.FirstName + " " + w.SecondName + Message(w),
                        Text     = w.FirstName + " " + w.SecondName + Message(w),
                        Color    = "#D00000",
                        Fields   =
                            new List <SlackField>
                        {
                            new SlackField
                            {
                                Title = "",
                                Value = ""
                            }
                        }
                    };
                    slackMessage.Attachments = new List <SlackAttachment> {
                        slackAttachment
                    };
                    _slackClient.Post(slackMessage);

                    bn.LastNotification = DateTime.Today;
                    if (bn.FirstNotification == w.BirthdayDate)
                    {
                        bn.FirstNotification = DateTime.Today;
                    }
                    _context.BirthdayNotifications.Update(bn);
                }
            }
            _context.SaveChanges();
        }
예제 #15
0
        public SlackService(string slackWebhookUrl, string projectName)
        {
            var slackClient  = new SlackClient(slackWebhookUrl);
            var slackMessage = new SlackMessage
            {
                Text     = $"{projectName} was just published!",
                Username = "******"
            };

            slackClient.Post(slackMessage);
        }
예제 #16
0
        public void SendMessage(string channel, string text, Emoji icon, string username)
        {
            var slackMessage = new SlackMessage
            {
                Channel   = channel,
                Text      = text,
                IconEmoji = icon,
                Username  = username
            };

            _client.Post(slackMessage);
        }
예제 #17
0
        private void NotifyToSlack()
        {
            var slackMessage = new SlackMessage
            {
                Channel   = slackConfig["Channel"],
                Text      = $"{System.Environment.MachineName} - {CacheIP}",
                IconEmoji = Emoji.RobotFace,
                Username  = "******"
            };

            slackClient.Post(slackMessage);
        }
 public static bool SendToSlack(this System.Exception ex, ExtraInfo extraInfo = null)
 {
     try
     {
         var slackMessage = GetExceptionText(ex, extraInfo);
         return(SlackClient.Post(slackMessage));
     }
     catch (System.Exception e)
     {
         throw e;
     }
 }
예제 #19
0
        /// <summary>
        /// Creates a client to send a Message.
        /// </summary>
        /// <param name="data">Information needed to crate a Message</param>
        /// <param name="message">Will be posted.</param>
        public void SendMessage(Data data, string message)
        {
            var client = new SlackClient(data.SlackWebHookUrl, 100);

            var slackMessage = new SlackMessage()
            {
                Channel  = data.SlackChannelName,
                Text     = message,
                Username = data.SlackUsername
            };

            client.Post(slackMessage);
        }
예제 #20
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);
        }
 public static void PostOk(this SlackClient client, string message)
 {
     client.Post(new SlackMessage()
     {
         Attachments = new List <SlackAttachment>()
         {
             new SlackAttachment()
             {
                 Text  = $"{message}",
                 Color = "good"
             }
         }
     });
 }
예제 #22
0
        public void ShouldReturnFalseIfPostFails()
        {
            //arrange
            const string hookUrl            = "https://hooks.slack.com/invalidhook";
            var          httpMessageHandler = GetMockHttpMessageHandler("NOK");
            var          client             = new SlackClient(hookUrl, httpClient: new HttpClient(httpMessageHandler.Object, false));
            var          slackMessage       = GetSlackMessage();

            //act
            var result = client.Post(slackMessage);

            //assert
            Assert.False(result);
        }
예제 #23
0
        public void ShouldReturnTrueIfPostSucceeds()
        {
            //arrange
            const string hookUrl            = "https://hooks.slack.com/mygreathook";
            var          httpMessageHandler = GetMockHttpMessageHandler("OK");
            var          client             = new SlackClient(hookUrl, httpClient: new HttpClient(httpMessageHandler.Object, false));
            var          slackMessage       = GetSlackMessage();

            //act
            var result = client.Post(slackMessage);

            //assert
            Assert.True(result);
        }
 public static void PostError(this SlackClient client, string message)
 {
     client.Post(new SlackMessage()
     {
         Attachments = new List <SlackAttachment>()
         {
             new SlackAttachment()
             {
                 Text  = $"Failed:{message}",
                 Color = "danger"
             }
         }
     });
 }
예제 #25
0
        /// <summary>
        /// Creates a Slack Client to send a message to Slack.
        /// </summary>
        /// <param name="settings">Contains information to send a valid Message</param>
        /// <param name="message">Message that will be send to slack.</param>^
        public static void SendSlackMessage(SlackSettings settings, string message)
        {
            var slackClient =
                new SlackClient(settings.WebHookUrl);

            var slackMessage = new SlackMessage
            {
                Channel  = settings.ChannelName,
                Text     = message,
                Username = settings.Username
            };

            slackClient.Post(slackMessage);
        }
예제 #26
0
        public void SendMessage(string channel, string text, Emoji icon, string username, ILog logger, List <SlackAttachment> attachments = null)
        {
            try
            {
                if (_sendMessagesToSlack)
                {
                    var slackMessage = new SlackMessage
                    {
                        //Channel = channel,
                        Text      = text,
                        IconEmoji = icon,
                        Username  = "******"
                    };

                    _client.Post(slackMessage);
                }
                Console.WriteLine(text);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }
예제 #27
0
        public void ShouldReuseHttpClient()
        {
            //arrange
            const string hookUrl            = "https://hooks.slack.com/invalid";
            var          httpMessageHandler = GetMockHttpMessageHandler("OK");
            var          httpClient         = new HttpClient(httpMessageHandler.Object, false);
            var          client             = new SlackClient(hookUrl, httpClient: httpClient);
            var          slackMessage       = GetSlackMessage();

            //act
            client.Post(slackMessage);
            client.Post(slackMessage);

            //assert
            httpMessageHandler.Protected().Verify(
                "SendAsync",
                Times.Exactly(2),
                ItExpr.Is <HttpRequestMessage>(req =>
                                               req.Method == HttpMethod.Post &&
                                               req.RequestUri == new Uri(hookUrl)
                                               ),
                ItExpr.IsAny <CancellationToken>()
                );
        }
예제 #28
0
 public bool sendslack(string message)
 {
     try
     {
         var slackClient  = new SlackClient("https://hooks.slack.com/services/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");
         var slackMessage = new SlackMessage
         {
             Text = message
         };
         slackClient.Post(slackMessage);
         return(true);
     }
     catch (Exception ex)
     {
         return(false);
     }
 }
예제 #29
0
        private void LeaveSlackLog(string url, string channel, string userName, string appName, string log)
        {
            if (string.IsNullOrEmpty(url))
            {
                return;
            }

            var message = new SlackMessage()
            {
                Channel  = channel,
                Text     = string.Format("{0} -  {1}", appName, log),
                Username = userName,
            };
            var client = new SlackClient(url);

            client.Post(message);
        }
예제 #30
0
        public virtual void Send()
        {
            var message = CreateMessage();

            if (message != null)
            {
                try
                {
                    var slackClient = new SlackClient(configuration.SlackWebHookURL);
                    slackClient.Post(message);
                }
                catch (Exception ex)
                {
                    log.Error(ex, "Unable to send message to slack");
                }
            }
        }
예제 #31
0
        public void SlackClient_returns_false_if_post_fails()
        {
            //arrange
            const string webserviceurl = "https://hooks.slack.com/invalid";
            var client = new SlackClient(webserviceurl);

            //act
            var slackMessage = new SlackMessage
            {
                Text = "Test Message",
                Channel = "#test",
                Username = "******",
                IconEmoji = Emoji.Ghost
            };
            var result = client.Post(slackMessage);

            //assert
            Assert.False(result);
        }