コード例 #1
0
        private NameValueCollection GetValues(SlackMessageModel model)
        {
            var    dictionary = new NameValueCollection();
            object value;

            foreach (var field in typeof(SlackMessageModel).GetFields())
            {
                foreach (var attr in field.GetCustomAttributes(true))
                {
                    if (attr.GetType().Name == "RequestFieldAttribute")
                    {
                        var request = attr as RequestFieldAttribute;

                        if ((bool)attr.GetType().GetProperty("IsJson").GetValue(attr) == true)
                        {
                            value = field.GetValue(model);
                            if (value != null)
                            {
                                dictionary.Add(request.RequestField, JsonConvert.SerializeObject(value));
                            }
                            break;
                        }

                        value = field.GetValue(model);
                        if (value != null)
                        {
                            dictionary.Add(request.RequestField, value.ToString());
                        }
                    }
                }
            }

            return(dictionary);
        }
コード例 #2
0
        public void Send(object obj)
        {
            var notificationEvent = (SlackNotificationEvent)obj;

            var model = new SlackMessageModel
            {
                Channel     = _slackBot.Channel,
                IconUrl     = _slackBot.IconUrl,
                Username    = _slackBot.Name,
                Token       = _slackBot.Token,
                Attachments = new List <AttachmentsModel>()
                {
                    new AttachmentsModel
                    {
                        Color    = notificationEvent.SlackStatus,
                        Text     = notificationEvent.Domain + "\\" + notificationEvent.Username + notificationEvent.Action,
                        Fallback = notificationEvent.Domain + "\\" + notificationEvent.Username + notificationEvent.Action
                    }
                }
            };

            var dictionary = GetValues(model);

            using (var wb = new WebClient())
            {
                var response = wb.UploadValues(_slackApiUrl, "POST", dictionary);
            }
        }
コード例 #3
0
        public async Task <IActionResult> Send([FromBody] SlackMessageModel model)
        {
            //string apiurl = "https://hooks.slack.com/services/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";
            var payload = new
            {
                text = $"{model.SensorName} has sent the value:{model.SensorValue}",
            };
            await _client.PostAsync(model.ApiUrl, new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json"));

            return(Ok());
        }
コード例 #4
0
        public void PostToSlack(string slackWebhook, SlackMessageModel payload)
        {
            var payloadJson = JsonConvert.SerializeObject(payload);

            _log.Info($"Payload JSON {payloadJson}");
            _log.Info($"Slack Webhook URL {slackWebhook}");

            using (WebClient client = new WebClient())
            {
                NameValueCollection slackData = new NameValueCollection();
                slackData["payload"] = payloadJson;

                var response = client.UploadValues(slackWebhook, "POST", slackData);
            }
        }
コード例 #5
0
ファイル: SlackService.cs プロジェクト: qls0ulp/Paradify
        public void PostMessage(string text, string username = null, string channel = null)
        {
            SlackMessageModel message = new SlackMessageModel()
            {
                Channel  = channel,
                Username = username,
                Text     = text
            };

            using (WebClient client = new WebClient())
            {
                client.Headers.Add(HttpRequestHeader.ContentType, "application/json");

                var response = client.UploadString(new Uri(Url), "POST", JsonConvert.SerializeObject(message));
            }
        }
コード例 #6
0
 public void PostToSlack(SlackMessageModel payload)
 {
     PostToSlack(_slackWebhook, payload);
 }
コード例 #7
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");
            bool simple  = !(req.Headers["format"] == "extended");
            var  channel = req.Headers["channel"];

            if (!string.IsNullOrWhiteSpace(channel))
            {
                if (!channel.ToString().StartsWith("#"))
                {
                    channel = "#" + channel;
                }
            }
            string requestBody = new StreamReader(req.Body).ReadToEnd();
            var    request     = JsonConvert.DeserializeObject <WebhookRequest>(requestBody);
            //var message = data?.message?.text;
            var detailedMessage = request.DetailedMessage.text;
            // important - get this data
            var resourceLink = request.Resource.url;
            var changesData  = await GetVstsResource($"{resourceLink}/changes");

            var changes      = JsonConvert.DeserializeObject <Changes>(changesData);
            var changesCount = changes.count;
            var changesText  = "";

            foreach (var change in changes.value)
            {
                changesText +=
                    $"<{change.displayUri}|{change.message}> by *{change.Author.displayName}*\n";
                if (!simple)
                {
                    changesText += $"{change.message}\n\n";
                }
            }
            var resource = await GetVstsResource(resourceLink);

            var resourceData   = JsonConvert.DeserializeObject <ResourceDetails>(resource);
            var projectName    = resourceData.Project.Name;
            var buildLink      = resourceData._Links.Web.Href;
            var sourceBranch   = resourceData.SourceBranch;
            var sourceVersion  = resourceData.SourceVersion;
            var repository     = resourceData.Repository.Id;
            var definitionName = request.Resource.definition.name;
            var gitUrl         = $"{repository.Replace(".git", "")}/commit/{sourceVersion}";

            var timeline = await GetVstsResource(resourceData._Links.Timeline.Href);

            var timeLineData = JsonConvert.DeserializeObject <Timeline>(timeline);
            var failingTask  = timeLineData.Records.FirstOrDefault(x => x.Result == "failed");

            var slackService = new SlackService(log, KeyManager.GetSecret("SlackWebhookUrl"));
            var model        = new SlackMessageModel
            {
                username    = "******",
                icon_emoji  = ":vsts:",
                text        = $"*{projectName}/{definitionName} - {failingTask.Name} failed*",
                channel     = channel,
                attachments = new List <SlackMessageModel.SlackAttachment>()
                {
                    new SlackMessageModel.SlackAttachment
                    {
                        color   = "#ff0000",
                        pretext = $"Repository: {repository}\nBranch: {sourceBranch}\nCommit: {sourceVersion}",
                        title   = $"{changesCount} Change(s) in the build: ",
                        text    = changesText,
                        actions = new[]
                        {
                            new SlackMessageModel.SlackAction
                            {
                                type = "button",
                                text = ":octocat: Git Repo Url",
                                url  = repository
                            },
                            new SlackMessageModel.SlackAction
                            {
                                type = "button",
                                text = ":octocat: Git Commit Url",
                                url  = gitUrl
                            },
                            new SlackMessageModel.SlackAction
                            {
                                type = "button",
                                text = ":vsts: VSTS Url",
                                url  = buildLink
                            }
                        }
                    }
                }
            };

            if (!simple)
            {
                model.attachments.Add(new SlackMessageModel.SlackAttachment
                {
                    color = "#ff0000",
                    title = "Build message",
                    text  = $"{detailedMessage}"
                });
            }


            slackService.PostToSlack(model);
            return(new OkObjectResult(""));
        }