Exemplo n.º 1
0
        public async Task Pingbot_Alert_Website_Up_Example_Async()
        {
            var client = new SbmClient(WebHookUrl);

            var message = new Message
            {
                Username    = "******",
                IconUrl     = "https://a.slack-edge.com/7f1a0/plugins/pingdom/assets/service_36.png",
                Attachments = new List <Attachment>
                {
                    new Attachment
                    {
                        Color    = "good",
                        Fallback = "Google is up (Incident #12345)",
                        Fields   = new List <Field>
                        {
                            new Field
                            {
                                Title = "Google is up (Incident #12345)",
                                Value =
                                    "<https://google.com> • <https://my.pingbot.com/reports/responsetime#check=12345|View details>"
                            }
                        }
                    }
                }
            };

            var response = await client.SendAsync(message).ConfigureAwait(false);

            Assert.AreEqual("ok", response);
        }
Exemplo n.º 2
0
        public async Task GetStanLee(SlackCommandRequest slackCommandRequest)
        {
            var client  = new SbmClient(slackCommandRequest.ResponseUrl);
            var message = new Message
            {
                UnfurlLinks = false,
                UnfurlMedia = false,
                Text        = slackCommandRequest.Text switch
                {
                    "help" => BuildHelpText(slackCommandRequest.UserName),
                    "support" => "Sure, if you want to reach out go to https://stanleebot.com/Support",
                    _ => "Unfortunately, I only know how to respond to help and support right now."
                }
            };

            message.SetResponseType(ResponseType.Ephemeral);
            var response = await client.SendAsync(message).ConfigureAwait(false);

            if (response == "ok")
            {
                _logger.LogInformation("GetStanLee: Responded to {MessageText} and sent message {@Message}", slackCommandRequest.Text, message);
            }
            else
            {
                _logger.LogError("GetStanLee: Tried responding to {MessageText} but received an error sending {@Message}", slackCommandRequest.Text, message);
            }
        }
Exemplo n.º 3
0
        public async Task Notification_To_Everyone_Async()
        {
            var client = new SbmClient(WebHookUrl);

            var message = new Message("<!everyone> this is cool");

            var response = await client.SendAsync(message).ConfigureAwait(false);

            Assert.AreEqual("ok", response);
        }
Exemplo n.º 4
0
        public async Task GetMrvlCoLink(SlackCommandRequest slackCommandRequest)
        {
            var client        = new SbmClient(slackCommandRequest.ResponseUrl);
            var firstResponse = new Message();

            firstResponse.SetResponseType(ResponseType.Ephemeral);
            firstResponse.Text = "Sure thing! Let me get to work!";
            await client.SendAsync(firstResponse).ConfigureAwait(false);

            var message = new Message();

            message.SetResponseType(ResponseType.Ephemeral);
            message.UnfurlLinks = false;
            message.UnfurlMedia = false;

            var response = string.Empty;
            var textList = slackCommandRequest.Text.Split(" ").ToList();

            if (textList.Count() == 2)
            {
                var longUrl      = textList[0];
                var emailAddress = textList[1];

                var shortenerMessage = await _urlShorteningService.Shorten(longUrl, Constants.UrlShortenerDomains.MrvlCo, emailAddress, OriginSources.Slack, slackCommandRequest.TriggerId);

                message.Text = shortenerMessage;
                response     = await client.SendAsync(message);
            }
            else
            {
                message.Text = "Please verify that your message is in the format of URL<space>EmailAddress";
                response     = await client.SendAsync(message).ConfigureAwait(false);
            }

            if (response == "ok")
            {
                _logger.LogInformation("GetMrvlCoLink: Responded to {MessageText} and sent message {@Message}", slackCommandRequest.Text, message);
            }
            else
            {
                _logger.LogError("GetMrvlCoLink: Tried responding to {MessageText} but received an error sending {@Message}", slackCommandRequest.Text, message);
            }
        }
Exemplo n.º 5
0
        public async Task GetMarvel(SlackCommandRequest slackCommandRequest)
        {
            var marvelGoogleCx = _appSettings.GoogleCustomSearch.MarvelCx;
            var gsr            = await _googleSearchService.GetResponse(slackCommandRequest.Text, marvelGoogleCx);

            if (gsr != null)
            {
                var client  = new SbmClient(slackCommandRequest.ResponseUrl);
                var message = new Message();

                var gsrMetaTags = gsr.Items.ElementAtOrDefault(0)?.PageMap.MetaTags.ElementAtOrDefault(0) ?? new GoogleSearchResponse.MetaTag();

                var snippet = gsrMetaTags.OgDescription;
                if (snippet.IsNullOrWhiteSpace())
                {
                    snippet = gsr.Items.ElementAtOrDefault(0)?.Snippet.CleanString() ?? string.Empty;
                }

                var title = gsr.Items.ElementAtOrDefault(0)?.Title.Split("|").ElementAtOrDefault(0)?.Trim();

                var website = gsrMetaTags.OgUrl;
                if (website.IsNullOrWhiteSpace())
                {
                    website = gsr.Items.ElementAtOrDefault(0)?.Link;
                }

                var attachment = new Attachment()
                {
                    Fallback = snippet,
                    Pretext  = $"Excelsior! I found {title} :star-struck:!"
                }
                .AddField("Name", title, true)
                .AddField("Website", website, true)
                .AddField("Bio", snippet)
                .SetImage(gsr.Items[0].PageMap.CseImage[0].Src)
                .SetColor(Color.Green);

                message.SetResponseType(ResponseType.InChannel);
                message.AddAttachment(attachment);
                var response = await client.SendAsync(message).ConfigureAwait(false);

                if (response == "ok")
                {
                    _logger.LogInformation("GetMarvel: Sent message {@Message}", message);
                }
                else
                {
                    _logger.LogError("GetMarvel: Error sending {@Message}", message);
                }
            }
            else
            {
                _logger.LogError("GetMarvel: GetGoogleSearchSlackResponseJson is null. {@SlackCommandRequest}", slackCommandRequest);
            }
        }
Exemplo n.º 6
0
        public async Task Response_In_Ephemeral_Async()
        {
            var client = new SbmClient(WebHookUrl);

            var message = new Message("This is an ephemeral response type.");

            message.SetResponseType(ResponseType.ephemeral);
            var response = await client.SendAsync(message);

            Assert.AreEqual("ok", response);
        }
Exemplo n.º 7
0
        public async Task Custom_Icon_Url_Example_Async()
        {
            var client = new SbmClient(WebHookUrl);

            var message = new Message
            {
                Username = "******",
                Text     = "Hello from Paul",
                IconUrl  = "https://s3-us-west-2.amazonaws.com/slack-files2/bot_icons/2019-06-17/669285832007_48.png"
            };

            var response = await client.SendAsync(message).ConfigureAwait(false);

            Assert.AreEqual("ok", response);
        }
Exemplo n.º 8
0
        public async Task Emoji_Icon_Example_Async()
        {
            var client = new SbmClient(WebHookUrl);

            var message = new Message
            {
                Username  = "******",
                Text      = "Hello from an Alien",
                IconEmoji = Emoji.Alien
            };

            var response = await client.SendAsync(message).ConfigureAwait(false);

            Assert.AreEqual("ok", response);
        }
Exemplo n.º 9
0
        public async Task Pingbot_Alert_Website_Up_Fluent_Example_Async()
        {
            var client = new SbmClient(WebHookUrl);

            var message = new Message().SetUserWithIconUrl("Pingbot",
                                                           "https://a.slack-edge.com/7f1a0/plugins/pingdom/assets/service_36.png")
                          .AddAttachment(
                new Attachment("Google is up (Incident #12345)")
                .SetColor(Color.Green)
                .AddField("Google is up (Incident #12345)",
                          "<https://google.com> • <https://my.pingbot.com/reports/responsetime#check=12345|View details>")
                );

            var response = await client.SendAsync(message).ConfigureAwait(false);

            Assert.AreEqual("ok", response);
        }
Exemplo n.º 10
0
        public async Task Short_Fields_Example_Async()
        {
            var client = new SbmClient(WebHookUrl);

            var message = new Message();

            message.AddAttachment(new Attachment()
                                  .AddField("Lorem", "Ipsum Dolor", true)
                                  .AddField("Sit", "Amet", true)
                                  .AddField("Consectetur", "Adipiscing elit", true)
                                  .AddField("Eiusmod", "Tempor incididunt", true)
                                  .AddField("A love story",
                                            "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Fames ac turpis egestas integer eget aliquet nibh praesent tristique. Ac feugiat sed lectus vestibulum mattis ullamcorper velit sed ullamcorper. Ultrices tincidunt arcu non sodales neque sodales. Ac auctor augue mauris augue neque gravida in fermentum et. Facilisi nullam vehicula ipsum a. Ac turpis egestas integer eget aliquet nibh praesent tristique. Vitae ultricies leo integer malesuada nunc vel risus commodo. Justo nec ultrices dui sapien eget mi proin sed. At auctor urna nunc id cursus metus aliquam eleifend. Purus sit amet luctus venenatis. Cursus in hac habitasse platea dictumst quisque. Pharetra sit amet aliquam id diam. In vitae turpis massa sed. Massa massa ultricies mi quis.")
                                  );

            var response = await client.SendAsync(message).ConfigureAwait(false);

            Assert.AreEqual("ok", response);
        }
Exemplo n.º 11
0
        public async Task GetDcComics(SlackCommandRequest slackCommandRequest)
        {
            var dcComicsCx = _appSettings.GoogleCustomSearch.DcComicsCx;
            var gsr        = await _googleSearchService.GetResponse(slackCommandRequest.Text, dcComicsCx);

            if (gsr != null)
            {
                var client  = new SbmClient(slackCommandRequest.ResponseUrl);
                var message = new Message();

                var gsrMetaTags   = gsr.Items.ElementAtOrDefault(0)?.PageMap.MetaTags.ElementAtOrDefault(0) ?? new GoogleSearchResponse.MetaTag();
                var snippet       = gsr.Items.ElementAtOrDefault(0)?.Snippet.CleanString() ?? string.Empty;
                var characterName = gsrMetaTags.OgTitle;

                var attachment = new Attachment()
                {
                    Fallback = snippet,
                    Pretext  = $"Excelsior! I found {characterName} :star-struck:!"
                }
                .AddField("Name", characterName, true)
                .AddField("Website", gsrMetaTags.OgUrl, true)
                .AddField("Bio", snippet)
                .SetThumbUrl(gsr.Items[0].PageMap.CseThumbnail.ElementAtOrDefault(0)?.Src)
                .SetColor(Color.Green);

                message.SetResponseType(ResponseType.InChannel);
                message.AddAttachment(attachment);
                var response = await client.SendAsync(message).ConfigureAwait(false);

                if (response == "ok")
                {
                    _logger.LogInformation("GetDCComics: Sent message {@Message}", message);
                }
                else
                {
                    _logger.LogError("GetDCComics: Error sending {@Message}", message);
                }
            }
            else
            {
                _logger.LogError("GetDCComics: GetGoogleSearchSlackResponseJson is null. {@SlackCommandRequest}", slackCommandRequest);
            }
        }
Exemplo n.º 12
0
        private async Task GetMarvel(SlackCommandRequest slackCommandRequest)
        {
            var marvelGoogleCx = Environment.GetEnvironmentVariable("MARVEL_GOOGLE_CX", EnvironmentVariableTarget.Process);
            var gsr            = await GetGoogleSearchSlackResponseJson(slackCommandRequest.Text, marvelGoogleCx);

            if (gsr != null)
            {
                var client  = new SbmClient(slackCommandRequest.ResponseUrl);
                var message = new Message();

                var gsrMetaTags = gsr.Items.ElementAtOrDefault(0)?.PageMap.MetaTags.ElementAtOrDefault(0) ?? new MetaTag();
                var snippet     = gsr.Items.ElementAtOrDefault(0)?.Snippet.CleanString() ?? string.Empty;

                var title = gsr.Items.ElementAtOrDefault(0)?.Title.Split("|").ElementAtOrDefault(0)?.Trim();

                var attachment = new Attachment()
                {
                    Fallback = snippet,
                    Pretext  = $"Excelsior! I found {title} :star-struck:!"
                }
                .AddField("Name", title, true)
                .AddField("Website", gsrMetaTags.OgUrl, true)
                .AddField("Bio", snippet)
                .SetImage(gsr.Items[0].PageMap.CseImage[0].Src)
                .SetColor(Color.Green);

                message.AddAttachment(attachment);
                var response = await client.SendAsync(message);

                if (response == "ok")
                {
                    _logger.LogInformation("GetMarvel: Sent message {@Message}", message);
                }
                else
                {
                    _logger.LogError("GetMarvel: Error sending {@Message}", message);
                }
            }
            else
            {
                _logger.LogError("GetMarvel: GetGoogleSearchSlackResponseJson is null. {@SlackCommandRequest}", slackCommandRequest);
            }
        }
Exemplo n.º 13
0
        public async Task Article_Link_Example_Async()
        {
            var client = new SbmClient(WebHookUrl);

            var message = new Message("https://dev.to/")
                          .SetUserWithIconUrl("Slack Bot Messages", "https://codeshare.co.uk/media/1505/sbmlogo.jpg")
                          .AddAttachment(
                new Attachment("Sorting the tools")
                .SetAuthor("dev.to",
                           authorIcon:
                           "https://slack-imgs.com/?c=1&o1=wi32.he32.si&url=https%3A%2F%2Fpracticaldev-herokuapp-com.freetls.fastly.net%2Fassets%2Fapple-icon-e9a036e0385d6e1e4ddef50be5e583800c0b5ca325d4998a640c38602d23b26c.png")
                .SetColor("#DDDDDD")
                .AddField("The DEV Community", "Where programmers share ideas and help each other grow.")
                .SetImage("https://thepracticaldev.s3.amazonaws.com/i/6hqmcjaxbgbon8ydw93z.png")
                );

            var response = await client.SendAsync(message).ConfigureAwait(false);

            Assert.AreEqual("ok", response);
        }
Exemplo n.º 14
0
        public async Task Thumb_Example_Async()
        {
            var client = new SbmClient(WebHookUrl);

            var message = new Message()
                          .SetChannel("general")
                          .SetUserWithIconUrl("SlackBotMessages", "https://codeshare.co.uk/media/1505/sbmlogo.jpg")
                          .AddAttachment(
                new Attachment("Lorem ipsum dolor sit amet ...")
                .SetColor("#0000ff")
                .AddField("A love story with a thumbnail",
                          "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Fames ac turpis egestas integer eget aliquet nibh praesent tristique. Ac feugiat sed lectus vestibulum mattis ullamcorper velit sed ullamcorper. Ultrices tincidunt arcu non sodales neque sodales. Ac auctor augue mauris augue neque gravida in fermentum et. Facilisi nullam vehicula ipsum a. Ac turpis egestas integer eget aliquet nibh praesent tristique. Vitae ultricies leo integer malesuada nunc vel risus commodo. Justo nec ultrices dui sapien eget mi proin sed. At auctor urna nunc id cursus metus aliquam eleifend. Purus sit amet luctus venenatis. Cursus in hac habitasse platea dictumst quisque. Pharetra sit amet aliquam id diam. In vitae turpis massa sed. Massa massa ultricies mi quis.")
                .SetThumbUrl(
                    "https://s3-us-west-2.amazonaws.com/slack-files2/bot_icons/2019-06-19/658365479699_48.png")
                );

            var response = await client.SendAsync(message).ConfigureAwait(false);

            Assert.AreEqual("ok", response);
        }
Exemplo n.º 15
0
        private async Task GetTest(SlackCommandRequest slackCommandRequest)
        {
            var client  = new SbmClient(slackCommandRequest.ResponseUrl);
            var message = new Message();

            const string bio = @"I’m a techie inside and out. If it involves technology, chances are I’ve at least dabbled with it. "
                               + "I enjoy helping people and organizations learn how to leverage technology to level up their lives or organization. "
                               + "I’ve worn many hats from having my own businesses, helping startups launch, and developing small to large scale web applications & APIs utilizing .NET & C# as the backend for many of my projects."
                               + "\n\nCombining my interests in technology and sociology, I’m simply passionate about the human side of technology… and Marvel Comics.";

            var attachment = new Attachment()
            {
                Fallback = $"Testing for {slackCommandRequest.Text}",
                Pretext  = $"Testing for {slackCommandRequest.Text}"
            }
            .AddField("Name", "AJ Tatum", true)
            .AddField("Website", "https://ajt.io", true)
            .AddField("Bio", bio)
            .SetThumbUrl("https://ajtatum.com/wp-content/uploads/2014/08/AJ-Tatum-120x120.png")
            .SetColor(Color.Green);

            message.AddAttachment(attachment);
            await client.SendAsync(message);
        }
Exemplo n.º 16
0
        public async Task Send_Rich_Message_Success_Async()
        {
            var client = new SbmClient(WebHookUrl);

            var msg = new Message
            {
                Text        = "You are using Slack Bot Messages by Paul Seal from codeshare.co.uk",
                Channel     = "general",
                Username    = "******",
                IconUrl     = "https://codeshare.co.uk/media/1505/sbmlogo.jpg",
                Attachments = new List <Attachment>
                {
                    new Attachment
                    {
                        Fallback = "This is for slack clients which choose not to display the attachment.",
                        Pretext  = "This line appears before the attachment",
                        Text     = "This line of text appears inside the attachment",
                        Color    = "good",
                        Fields   = new List <Field>
                        {
                            new Field
                            {
                                Title = Emoji.HeavyCheckMark + " Success",
                                Value = "You can add multiple lines to an attachment\n\nLike this\n\nAnd this."
                            }
                        }
                    },
                    new Attachment
                    {
                        Fallback =
                            "Required text summary of the attachment that is shown by clients that understand attachments but choose not to show them.",
                        Pretext = "Optional text that should appear above the formatted attachment",
                        Text    = "Optional text that should appear within the attachment",
                        Color   = "warning",
                        Fields  = new List <Field>
                        {
                            new Field
                            {
                                Title = Emoji.Warning + " Warning",
                                Value = "This is a warning."
                            }
                        }
                    },
                    new Attachment
                    {
                        Fallback =
                            "Required text summary of the attachment that is shown by clients that understand attachments but choose not to show them.",
                        Pretext = "Optional text that should appear above the formatted data",
                        Text    = "Check out my blog " + new SlackLink("https://codeshare.co.uk", "codeshare.co.uk"),
                        Color   = "danger",
                        Fields  = new List <Field>
                        {
                            new Field
                            {
                                Title = Emoji.X + " Error",
                                Value =
                                    "You can use emojis in the text too.\n\nWe've added nearly 900 of them already that you can use with intellisense.\n\nJust start typing `Emoji.` and you will see the available list."
                            }
                        }
                    }
                }
            };

            var response = await client.SendAsync(msg).ConfigureAwait(false);

            Assert.AreEqual("ok", response);
        }
Exemplo n.º 17
0
        public async Task <IActionResult> SignInSlack()
        {
            try
            {
                var clientId     = _appSettings.Slack.ClientId;
                var clientSecret = _appSettings.Slack.ClientSecret;
                var slackCode    = Request.Query["code"].ToString();
                var slackState   = Request.Query["state"].ToString();
                var cookieValue  = Request.Cookies[Constants.StanLeeSlackStateCookieName];

                if (slackState != null && cookieValue != null && slackState == cookieValue)
                {
                    SlackAuthRequest.AuthRequest authRequest;
                    string responseMessage;

                    var requestUrl = $"https://slack.com/api/oauth.access?client_id={clientId}&client_secret={clientSecret}&code={slackCode}";
                    var request    = new HttpRequestMessage(HttpMethod.Post, requestUrl);
                    using (var client = new HttpClient())
                    {
                        var response = await client.SendAsync(request).ConfigureAwait(false);

                        var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                        authRequest = JsonConvert.DeserializeObject <SlackAuthRequest.AuthRequest>(result);
                    }

                    if (authRequest != null && !authRequest.IncomingWebhook.Url.IsNullOrWhiteSpace())
                    {
                        _logger.LogInformation("New installation of StanLeeBot for {TeamName} in {Channel}", authRequest.TeamName, authRequest.IncomingWebhook.Channel);

                        var webhookUrl = authRequest.IncomingWebhook.Url;

                        var sbmClient = new SbmClient(webhookUrl);
                        var message   = new Message
                        {
                            Text = "Hi there from StanLeeBot! Checkout what I can do by typing /stanlee help"
                        };
                        await sbmClient.SendAsync(message).ConfigureAwait(false);

                        Response.Cookies.Delete(Constants.StanLeeSlackStateCookieName);

                        responseMessage = $"Congrats! StanLeeBot has been successfully added to {authRequest.TeamName} {authRequest.IncomingWebhook.Channel}";
                        return(RedirectToPage("/Index", new { message = responseMessage }));
                    }

                    Response.Cookies.Delete(Constants.StanLeeSlackStateCookieName);

                    _logger.LogError("Something went wrong making a request to {RequestUrl}", requestUrl);

                    responseMessage = "Error: Something went wrong and we were unable to add StanLeeBot to your Slack.";
                    return(RedirectToPage("/Index", new { message = responseMessage }));
                }

                throw new Exception("State values and Cookie Values do not match.");
            }
            catch (Exception ex)
            {
                Response.Cookies.Delete(Constants.StanLeeSlackStateCookieName);

                _logger.LogError(ex, "There was an error with the signin-slack method");
                var responseMessage = "Error: Something went wrong and we were unable to add StanLeeBot to your Slack.";
                return(RedirectToPage("/Index", new { message = responseMessage }));
            }
        }