public ISlackMessageBuilder AddAttachement(
            string title,
            string color = "good",
            Func <List <SlackField> > slackFieldsFunc = null,
            string footer      = null,
            DateTime?timestamp = null)
        {
            if (m_slackMessage.Attachments == null)
            {
                m_slackMessage.Attachments = new List <SlackAttachment>();
            }

            var slackAttachment = new SlackAttachment {
                Title = title, Color = color
            };

            if (slackFieldsFunc != null)
            {
                slackAttachment.Fields = slackFieldsFunc();
            }

            slackAttachment.Footer = footer;

            if (timestamp != null)
            {
                var epocTimeStamp = (long)(timestamp.Value - new DateTime(1970, 1, 1)).TotalSeconds;
                slackAttachment.TimeStamp = epocTimeStamp.ToString();
            }

            m_slackMessage.Attachments.Add(slackAttachment);

            return(this);
        }
示例#2
0
        protected override SlackMessage CreateMessage()
        {
            var message = base.CreateMessage();

            var slackAttachment = new SlackAttachment
            {
                Color    = "#0000FF",
                Fallback = String.Format("Gym, {0}, is now neutral.", gymDetails.Name),

                AuthorName = String.Format("Gym, {0}, is now neutral.", gymDetails.Name),

                ThumbUrl = gymDetails.ImageURL,
            };

            if (!String.IsNullOrWhiteSpace(configuration.MainConfiguration.MapURLFormat))
            {
                slackAttachment.Title     = "View on map";
                slackAttachment.TitleLink = String.Format(configuration.MainConfiguration.MapURLFormat, gymDetails.Latitude.ToString().Replace(",", "."), gymDetails.Longitude.ToString().Replace(",", "."));
            }

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

            return(message);
        }
        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);
        }
示例#4
0
        public SlackMessage FormatMsg(string author, string message, string recieverFN, string recieverLN)
        {
            var slackMessage = new SlackMessage
            {
                Channel   = "#general",
                Text      = "Congratulation:",
                IconEmoji = Emoji.Cake,
                Username  = "******"
            };

            slackMessage.Mrkdwn = false;
            var slackAttachment = new SlackAttachment
            {
                Fallback = recieverFN + " " + recieverLN + " is celebrating birthday!",
                Text     = recieverFN + " " + recieverLN + " is celebrating birthday!",
                Color    = "#D00000",
                Fields   =
                    new List <SlackField>
                {
                    new SlackField
                    {
                        Title = author + " says to you:",
                        Value = message
                    }
                }
            };

            slackMessage.Attachments = new List <SlackAttachment> {
                slackAttachment
            };
            return(slackMessage);
        }
        public BotMessage ToBotMessage(RemoteIDEModel model)
        {
            var message = new BotMessage()
            {
                Text = $"{model.IDEUserIdentity.DisplayName} is doing some coding!"
            };

            var attachment = new SlackAttachment()
            {
                ThumbUrl   = model.IDEUserIdentity.ImageUrl,
                AuthorName = model.IDEUserIdentity.DisplayName,
                AuthorLink = model.IDEUserIdentity.Id,
                AuthorIcon = model.IDEUserIdentity.ImageUrl,
                ColorHex   = new System.Windows.Media.ColorConverter().ConvertToString(model.IDEUserIdentity.GetUserColour()),
                Fallback   = model.OpenFiles.Count == 0 ?
                             $"{ model.IDEUserIdentity.DisplayName} has no files open." :
                             $"{model.IDEUserIdentity.DisplayName} has {model.OpenFiles.Count} files open in {model.OpenFiles.FirstOrDefault()?.RepoUrl}"
            };

            foreach (var field in GetSlackFields(model).OrderBy(f => f.Title.Count(c => c == '.')).ThenBy(f => f.Title))
            {
                attachment.Fields.Add(field);
            }

            message.Attachments.Add(attachment);

            return(message);
        }
示例#6
0
        private void btn_SlackAttachmentAdd_Click(object sender, EventArgs e)
        {
            SlackAttachment attachment = new SlackAttachment {
            };

            //needed params
            string fallback = tbox_SlackAttachmentFallback.Text;
            string value    = tbox_SlackAttachmentText.Text;
            string color    = tbox_SlackAttachmentColor.Text;
            string title    = tbox_SlackAttachmentTitle.Text;

            //optional params
            string pretext    = tbox_SlackAttachmentPretext.Text;
            string titleLink  = tbox_SlackAttachmentTitleLink.Text; //must start with https://
            string authorName = tbox_SlackAttachmentAuthorName.Text;
            string authorIcon = tbox_SlackAttachmentAuthorLink.Text;
            string authorLink = tbox_SlackAttachmentAuthorLink.Text; //must start with https://
            string imageURL   = tbox_SlackAttachmentImageURL.Text;
            string thumbURL   = tbox_SlackAttachmentThumbURL.Text;
            string footer     = textbox_Footer.Text;
            string footerURL  = textbox_FooterURL.Text;

            attachment = client.CreateSlackAttachment(fallback, value, color, title, slackFields, pretext, titleLink, authorName, authorIcon, authorLink, imageURL, thumbURL, footer, footerURL);

            slackAttachments.Add(attachment);
            slackFields.Clear(); //clear the fields for the next attachment
        }
示例#7
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);
        }
        public static SlackMessage ToSlackMessage(this LogEntry logEntry)
        {
            var logAttachment = new SlackAttachment
            {
                AuthorName = logEntry.Source,
                Color      = logEntry.Level.GetLogLevelColor(),
                Text       = logEntry.Message,
                Fields     = new List <SlackField>(logEntry.GetDataFields()),
                Footer     = $"{logEntry.Level} - {logEntry.HostName} - PID {logEntry.ProcessId} thread {logEntry.ThreadId}",
                Timestamp  = (int)logEntry.Timestamp.ToUnixTimeSeconds()
            };

            if (string.IsNullOrEmpty(logEntry.Message) && logEntry.Data != null)
            {
                logAttachment.Fallback = $"{logEntry.Data}";
            }

            return(new SlackMessage
            {
                Attachments = new List <SlackAttachment> {
                    logAttachment
                },
                Markdown = true
            });
        }
        private async Task <List <SlackAttachment> > CreateSlackAttachment(IEnumerable <string> meals)
        {
            var attachments = new List <SlackAttachment>();

            foreach (var meal in meals)
            {
                var att = new SlackAttachment {
                    text = meal
                };
                if (meal.StartsWith("Varmrett"))
                {
                    var hotdish = meal.Replace("Varmrett", string.Empty).Replace(":", string.Empty).Trim();
                    if (!string.IsNullOrWhiteSpace(hotdish))
                    {
                        var url = await _imageSearcher.SearchForMeal(hotdish);

                        if (url != null)
                        {
                            att.image_url = url;
                        }
                    }
                }
                attachments.Add(att);
            }
            return(attachments);
        }
示例#10
0
        async Task INotifyService.Notify(string eventXml, string tfsIdentityXml)
        {
            if (string.IsNullOrEmpty(eventXml))
            {
                throw new ArgumentException(nameof(eventXml));
            }

            var changedItem = new ChangedItem(eventXml);
            var link        = new SlackAttachment {
                Title     = changedItem.UrlTitle,
                TitleLink = changedItem.Url
            };

            Console.WriteLine(changedItem.Title + " - " + changedItem.UrlTitle);
            var slackHub = new SlackChatHub {
                Id = user
            };
            var policyResult = await Policy
                               .Handle <Exception>()
                               .WaitAndRetryAsync(new[] {
                TimeSpan.FromSeconds(2),
                TimeSpan.FromSeconds(4),
                TimeSpan.FromSeconds(8)
            })
                               .ExecuteAndCaptureAsync(
                () => slackIntegration.SendMessageToChannel(slackHub, changedItem.Title, link));

            if (policyResult.FinalException != null)
            {
                Console.WriteLine($"Could not post to Slack {policyResult.FinalException}");
            }
        }
示例#11
0
        private SlackMessageData GenerateSlackMessagePR(string repoURL, string owner, string repo, string requestedBy, List <dynamic> summary)
        {
            var payload = new SlackMessageData();

            payload.Text = string.Format("Responding to Request for PR status of <{0}/{1}/{2}|{1}/{2}> by @{3}\n\n\n", repoURL, owner, repo, requestedBy);

            if (summary.Count <= 0)
            {
                var attachment = new SlackAttachment
                {
                    Color   = "good",
                    Pretext = "No PR statuses exist in repo"
                };
                payload.Attachments.Add(attachment);
            }

            foreach (var entry in summary)
            {
                var attachment = new SlackAttachment
                {
                    Color   = entry.State.ToString().ToLower() == "success" ? "good" : "danger",
                    Pretext = string.Format("<{0}|Pull Request #{1}> - {2}\n\n", entry.URL, entry.Number, entry.State)
                };
                attachment.Text += String.Format("Pending: {0}\t", entry.Pending);
                attachment.Text += String.Format("Error:   {0}\t", entry.Error);
                attachment.Text += String.Format("Failure: {0}\t", entry.Failure);
                attachment.Text += String.Format("Success: {0}\n", entry.Success);

                payload.Attachments.Add(attachment);
            }

            return(payload);
        }
示例#12
0
        private void TestPostMessage(StringBuilder MerchantServicesOutput, List <ProductStatusSummary> listOfProductStatuses, string WebHook)
        {
            string       str          = "Summary of data Merchant Services Products " + DateTime.UtcNow.ToLongDateString();
            SlackMessage slackMessage = new SlackMessage
            {
                Channel   = "#platformnotifications",
                Text      = str,
                IconEmoji = Emoji.Bread,
                Username  = "******"
            };
            string        str2 = MerchantServicesOutput.ToString();
            List <string> list = new List <string>();
            string        item = "text";

            list.Add(item);
            SlackAttachment attachment = new SlackAttachment
            {
                Text     = str2,
                Color    = "#D00000",
                MrkdwnIn = list
            };
            List <SlackAttachment> list1 = new List <SlackAttachment> {
                attachment
            };

            slackMessage.Attachments = list1;
            new SlackClient(WebHook, 100).Post(slackMessage);
        }
示例#13
0
        public void should_return_expected_json_when_serialised()
        {
            // given
            string expectedJson = Resources.ResourceManager.GetAttachmentsJson();

            expectedJson = RemoveLinesAndStuffFromJson(expectedJson);

            var attachment =
                new SlackAttachment
            {
                Fallback   = "Required plain-text summary of the attachment.",
                ColorHex   = "#36a64f",
                PreText    = "Optional text that appears above the attachment block",
                AuthorName = "Bobby Tables",
                AuthorLink = "http://flickr.com/bobby/",
                AuthorIcon = "http://flickr.com/icons/bobby.jpg",
                Title      = "Slack API Documentation",
                TitleLink  = "https://api.slack.com/",
                Text       = "Optional text that appears within the attachment",
                CallbackId = "mycallbackid",
                MarkdownIn = SlackAttachment.GetAllMarkdownInTypes(),
                Fields     = new[]
                {
                    new SlackAttachmentField
                    {
                        IsShort = true,
                        Title   = "Priority",
                        Value   = "High"
                    }
                },
                Actions = new[]
                {
                    new SlackAttachmentAction
                    {
                        Name  = "yes",
                        Value = "yep",
                        Text  = "Yes",
                        Style = SlackActionStyle.Primary
                    },
                    new SlackAttachmentAction
                    {
                        Name  = "no",
                        Value = "nop",
                        Text  = "No"
                    }
                },
                ImageUrl   = "http://my-website.com/path/to/image.jpg",
                ThumbUrl   = "http://example.com/path/to/thumb.png",
                Footer     = "Brief text to help contextualize an attachment",
                FooterIcon = "http://flickr.com/icons/footer.jpg"
            };

            // when
            string resultJson = JsonConvert.SerializeObject(attachment);

            resultJson = RemoveLinesAndStuffFromJson(resultJson);

            // then
            resultJson.ShouldBe(expectedJson);
        }
        public override string GenerateAttachment(IEnumerable <Note> notes)
        {
            int maxNumberOfNotes = AdjustReturnCount(notes.Count(), Constants.Constants.ReturnedNotesMaxFind);

            List <SlackAttachment> listOfAttachments = new List <SlackAttachment>();

            string colour = GetRandomHexColour();

            foreach (int i in Enumerable.Range(0, maxNumberOfNotes))
            {
                SlackAttachmentField slackAttachmentField = new SlackAttachmentField()
                {
                    Value = notes.ElementAt(i).Text
                };

                SlackAttachment slackAttachment = new SlackAttachment()
                {
                    Color  = colour,
                    Fields = new SlackAttachmentField[] { slackAttachmentField },
                    Footer = "<@" + notes.ElementAt(i).Author + ">",
                    Ts     = notes.ElementAt(i).Timestamp
                };

                listOfAttachments.Add(slackAttachment);
            }

            return(JsonConvert.SerializeObject(listOfAttachments));
        }
示例#15
0
 public static SlackAttachment SetAuthor(this SlackAttachment attachment, string authorName, string authorLink = default, string authorIcon = default)
 {
     attachment.AuthorName = authorName;
     attachment.AuthorLink = authorLink;
     attachment.AuthorIcon = authorIcon;
     return(attachment);
 }
示例#16
0
        private void AddHealthAttachments(
            HealthCheckStatus checkStatus,
            IReadOnlyCollection <HealthCheck.Result> checks,
            SlackPayload slackMessage,
            bool reFailure = false)
        {
            var checkOrChecks = checks.Count > 1 ? "checks" : "check";
            var textEnd       = string.Empty;
            var color         = string.Empty;

            if (checkStatus == HealthCheckStatus.Unhealthy)
            {
                textEnd = reFailure ? "still failing" : "failing";
                color   = FailingColor;
            }

            if (checkStatus == HealthCheckStatus.Degraded)
            {
                textEnd = reFailure ? "still degrading" : "degrading";
                color   = DegradingColor;
            }

            if (checkStatus == HealthCheckStatus.Healthy)
            {
                textEnd = "recovered";
                color   = SuccessColor;
            }

            var attachment = new SlackAttachment
            {
                Text  = $"*_{checks.Count} {checkOrChecks} {textEnd}_ on server {Environment.MachineName}*\n\n",
                Color = color,
                Ts    = (DateTime.UtcNow - Epoch).TotalSeconds
            };

            foreach (var result in checks)
            {
                if (result.Check.Status == HealthCheckStatus.Unhealthy)
                {
                    LastDegradedCheckCache.Remove(result.Name);
                    LastUnhealthyCheckCache.Add(result.Name);
                }
                else if (result.Check.Status == HealthCheckStatus.Degraded)
                {
                    LastUnhealthyCheckCache.Remove(result.Name);
                    LastDegradedCheckCache.Add(result.Name);
                }

                attachment.Fields.Add(
                    new SlackAttachmentFields
                {
                    Title = $"{result.Name}",
                    Value = $"```{result.Check.Message}```",
                    Short = true
                });
            }

            slackMessage.Attachments.Add(attachment);
        }
示例#17
0
        public IActionResult SlackForCommand(string @event, IFormCollection data)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _logger.LogInformation(
                0,
                "{ControllerName} / '{ReceiverId}' received {Count} properties with event '{EventName}').",
                nameof(SlackController),
                "command",
                data.Count,
                @event);

            string channel = data[SlackConstants.ChannelRequestFieldName];
            string command = data[SlackConstants.CommandRequestFieldName];
            string trigger = data[SlackConstants.TriggerRequestFieldName];

            _logger.LogInformation(
                1,
                "Data contains channel '{ChannelName}', command '{Command}', and trigger '{Trigger}'.",
                channel,
                command,
                trigger);

            string text    = data[SlackConstants.TextRequestFieldName];
            string subtext = data[SlackConstants.SubtextRequestFieldName];

            _logger.LogInformation(
                2,
                "Data contains text '{Text}' and subtext '{Subtext}'.",
                text,
                subtext);

            // Create the response.
            var slashCommand = SlackCommand.ParseActionWithParameters(command);
            var reply        = string.Format(
                "Received slash command '{0}' with action '{1}' and value '{2}'",
                command,
                slashCommand.Key,
                slashCommand.Value.ToString());

            // Slash responses can be augmented with attachments containing data, images, and more.
            var attachment = new SlackAttachment("Attachment Text", "Fallback description")
            {
                Color   = "#439FE0",
                Pretext = "Hello from ASP.NET WebHooks!",
                Title   = "Attachment title",
            };

            // Slash attachments can contain tabular data as well
            attachment.Fields.Add(new SlackField("Field1", "1234"));
            attachment.Fields.Add(new SlackField("Field2", "5678"));

            return(new JsonResult(new SlackSlashResponse(reply, attachment)));
        }
示例#18
0
 public void Setup()
 {
     _slackMessage = new SlackMessage();
     _attachment   = new SlackAttachment();
     _slackMessage.Attach(_attachment);
     settings = new JsonSerializerSettings {
         ContractResolver = new LowerCaseContractResolver()
     };
 }
            public void AddsToAttachments()
            {
                var attachment = new SlackAttachment();
                int initial    = _sut.Attachments.Count;

                _result = _sut.Attach(attachment);

                Assert.AreEqual(initial + 1, _sut.Attachments.Count);
            }
示例#20
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();
        }
        private static void FlattenAuthorProperty(JObject o, SlackAttachment attachment)
        {
            var authorProp = o.Children <JProperty>().FirstOrDefault(z => z.Name == "author");

            if (authorProp != null && attachment.Author != null)
            {
                authorProp.AddAfterSelf(new JProperty("author_name", attachment.Author.Name));
                authorProp.AddAfterSelf(new JProperty("author_link", attachment.Author.Link));
                authorProp.AddAfterSelf(new JProperty("author_icon", attachment.Author.Icon));
                authorProp.Remove();
            }
        }
示例#22
0
        protected override SlackMessage CreateMessage()
        {
            var message = base.CreateMessage();

            var slackAttachment = new SlackAttachment
            {
                Color    = "#36a64f",
                Fallback = String.Format("Wild {0} has spawned!", spawnedPokemon.PokemonID),

                AuthorName = String.Format("Wild {0} has spawned!", spawnedPokemon.PokemonID),

                Fields = new List <SlackField>()
            };

            if (!String.IsNullOrWhiteSpace(configuration.MainConfiguration.ImageURLFormat))
            {
                slackAttachment.ThumbUrl = String.Format(configuration.MainConfiguration.ImageURLFormat, spawnedPokemon.PokemonID.ToString().ToLower());
            }

            if (!String.IsNullOrWhiteSpace(configuration.MainConfiguration.MapURLFormat))
            {
                slackAttachment.Title     = "View on map";
                slackAttachment.TitleLink = String.Format(configuration.MainConfiguration.MapURLFormat, spawnedPokemon.Latitude.ToString().Replace(",", "."), spawnedPokemon.Longitude.ToString().Replace(",", "."));
            }

            if (configuration.HomePosition != null)
            {
                slackAttachment.Fields.Add(new SlackField
                {
                    Title = "Distance",
                    Value = $"{configuration.HomePosition.DistanceTo(spawnedPokemon.Latitude, spawnedPokemon.Longitude)}m",
                    Short = true
                });
            }

            // TODO: add logic to caclulate this from the database
            //if (true)
            //{
            //    slackAttachment.Fields.Add(new SlackField
            //    {
            //        Title = "Despawning",
            //        Value = spawnedPokemon.Despawn.ToString(),
            //        Short = true
            //    });
            //}

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

            return(message);
        }
        private static void FlattenTitleProperty(JObject o, SlackAttachment attachment)
        {
            var titleProp = o.Children <JProperty>().FirstOrDefault(z => z.Name == "title");

            if (titleProp != null && attachment.Title != null)
            {
                titleProp.Value = attachment.Title.Name;
                if (attachment.Title.Link != null)
                {
                    titleProp.AddAfterSelf(new JProperty("title_link", attachment.Title.Link.OriginalString));
                }
            }
        }
            public void SetsAttachmentTextWhenPossible()
            {
                var randomMessage = Helpers.Random;
                var attachment    = new SlackAttachment {
                };
                var sut           = new SlackMessage();

                sut.Attach(attachment);

                sut.WithMessageText(randomMessage);

                Assert.AreEqual(randomMessage, attachment.Text);
            }
        protected override SlackMessage CreateMessage()
        {
            var message = base.CreateMessage();

            var slackAttachment = new SlackAttachment
            {
                Color    = "#36a64f",
                Fallback = String.Format("Wild {0} has spawned!", spawnedPokemon.PokemonID),

                AuthorName = String.Format("Wild {0} has spawned!", spawnedPokemon.PokemonID),

                Title     = "View on map",
                TitleLink = String.Format("http://maps.google.com/?q={0},{1}", spawnedPokemon.Latitude.ToString().Replace(",", "."), spawnedPokemon.Longitude.ToString().Replace(",", ".")),
                Fields    = new List <SlackField>
                {
                    new SlackField
                    {
                        Title = "Despawning",
                        Value = spawnedPokemon.Despawn.ToString(),
                        Short = true
                    }
                }
            };

            if (!String.IsNullOrWhiteSpace(configuration.MainConfiguration.ImageURLFormat))
            {
                slackAttachment.ThumbUrl = String.Format(configuration.MainConfiguration.ImageURLFormat, spawnedPokemon.PokemonID.ToString().ToLower());
            }

            if (!String.IsNullOrWhiteSpace(configuration.MainConfiguration.MapURLFormat))
            {
                slackAttachment.Title     = "View on map";
                slackAttachment.TitleLink = String.Format(configuration.MainConfiguration.MapURLFormat, spawnedPokemon.Latitude.ToString().Replace(",", "."), spawnedPokemon.Longitude.ToString().Replace(",", "."));
            }

            if (configuration.ProcessNearbyPokemon)
            {
                slackAttachment.Fields.Add(new SlackField
                {
                    Title = "Was nearby",
                    Value = wasNearby ? "Yes" : "No",
                    Short = true
                });
            }

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

            return(message);
        }
示例#26
0
        /// <summary>
        /// This function is used to create Slack Attachments
        /// </summary>
        /// <param name="fallback">This shows if the message cannot be shown</param>
        /// <param name="text">Main text of the attachment</param>
        /// <param name="color">Hex color of the bar beside the attachment</param>
        /// <param name="title">Title of the attachment</param>
        /// <param name="fields">Slack fields</param>
        /// <param name="pretext">Optional pretext on the message</param>
        /// <param name="title_link">Optional link on the title of the message</param>
        /// <param name="author_name">Optional Author's name</param>
        /// <param name="author_icon">Optional Author's icon (can be a url)</param>
        /// <param name="author_link">Optional link on the Author's name</param>
        /// <param name="pretext">Optional text to show before the main text</param>
        /// <param name="image_url">Optional image URL</param>
        /// <param name="thumb_url">Optional thumb URL</param>
        /// <param name="footer">Optional footer</param>
        /// <param name="footer_url">Optional footer url</param>
        /// <returns>A finished Slack Attachment to attach to a message</returns>
        public SlackAttachment CreateSlackAttachment(string fallback, string text, string color, string title, List <SlackField> fields = null, string pretext = null, string title_link = null, string author_name = null, string author_icon = null, string author_link = null, string image_url = null, string thumb_url = null, string footer = null, string footer_url = null)
        {
            SlackAttachment slackAttachment = new SlackAttachment {
            };

            if (fields != null)
            {
                slackAttachment = new SlackAttachment
                {
                    Fallback   = fallback,
                    Text       = text,
                    Color      = color,
                    Pretext    = pretext,
                    AuthorName = author_name,
                    AuthorIcon = author_icon,
                    AuthorLink = author_link,
                    Title      = title,
                    TitleLink  = title_link,
                    Fields     = new List <SlackField> {
                    },
                    ImageUrl   = image_url,
                    ThumbUrl   = thumb_url,
                    Footer     = footer,
                    FooterIcon = footer_url
                };

                slackAttachment.Fields.AddRange(fields);
            }
            else
            {
                slackAttachment = new SlackAttachment
                {
                    Fallback   = fallback,
                    Text       = text,
                    Color      = color,
                    Pretext    = pretext,
                    AuthorName = author_name,
                    AuthorIcon = author_icon,
                    AuthorLink = author_link,
                    Title      = title,
                    TitleLink  = title_link,
                    ImageUrl   = image_url,
                    ThumbUrl   = thumb_url,
                    Footer     = footer,
                    FooterIcon = footer_url
                };
            }


            return(slackAttachment);
        }
示例#27
0
 public static SlackAttachment AddField(this SlackAttachment attachment, string title, string value, bool isShort = false)
 {
     if (attachment.Fields == null)
     {
         attachment.Fields = new List <SlackField>();
     }
     attachment.Fields.Add(new SlackField
     {
         Title = title,
         Value = value,
         Short = isShort
     });
     return(attachment);
 }
示例#28
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="identify"></param>
 /// <param name="message"></param>
 /// <param name="attachment"></param>
 /// <returns></returns>
 public SlackPool Emit(string identify, SlackMessage message, SlackAttachment attachment)
 {
     if (_slacks.TryGetValue(identify, out SlackClient client))
     {
         if (attachment != null)
         {
             message.Attachments = new List <SlackAttachment> {
                 attachment
             };
         }
         client.Post(message);
     }
     return(this);
 }
        private void SendMainIncidentChannelMessage(string title, string messageText, string messageColor)
        {
            var chatHub = new SlackChatHub {
                Id = this.mainIncidentChannel
            };
            var attachement = new SlackAttachment {
                Title = title, Text = messageText, ColorHex = messageColor
            };
            var message = new BotMessage {
                ChatHub = chatHub, Attachments = new List <SlackAttachment> {
                    attachement
                }
            };

            this.SlackConnection.Say(message);
        }
示例#30
0
        static void Main(string[] args)
        {
            while (true)
            {
                Console.WriteLine("Please enter your message to send by slack");
                string message = Console.ReadLine();
                Console.WriteLine("Please mention which channel you want to add this message");
                var channelss = Console.ReadLine();

                //Regex reg = new Regex(@"/([#&][^\x07\x2C\s]{,200})/");
                //Match match;
                //var results = new List<string>();
                //for (match=reg.Match(channelss); match.Success; match=match.NextMatch())
                //{
                //    if (!results.Contains(match.Value))
                //    {
                //        results.Add(match.Value);
                //    }
                //}

                Console.WriteLine($"Your message '{message}' is sent!");
                SlackClient client   = new SlackClient("https://hooks.slack.com/services/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");
                var         channels = new List <string>();
                if (channelss.Count() != 0 && channelss.Any())
                {
                    foreach (var channel in channelss.Split(','))
                    {
                        channels.Add("#" + channel);
                    }
                }
                var slackMessage = new SlackMessage()
                {
                    Username  = "******",
                    IconEmoji = ":umbrella:",
                    Channel   = "#general",
                    Text      = message
                };
                var a = new SlackAttachment();
                a.AuthorLink = @"C:\temp\data.txt";
                // slackMessage.Attachments.Add(a);
                // client.PostToChannels(slackMessage, channels);
                client.PostToChannels(slackMessage, channels);
            }


            //Console.ReadLine();
        }