public static void SendMessage(string messageText)
        {
            SlackClient client = new SlackClient(_SlackUrlWithAccessToken);

            client.PostMessage(username: _SlackWebHookName,
                        text: messageText,
                        channel: _SlackChannelName);
        }
Exemplo n.º 2
0
        public void DoIt()
        {
            string urlWithAccessToken = "https://hooks.slack.com/services/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"; 
 	 
 	        SlackClient client = new SlackClient(urlWithAccessToken); 
 	        client.PostMessage(username: "******",
                text: "Message from Mmap man, step complete", 
 			    channel: "#shipitday-mmapman"); 

        } 
Exemplo n.º 3
0
        private void appDocSynched(object sender, Autodesk.Revit.DB.Events.DocumentSynchronizedWithCentralEventArgs e)
        {
            Variables.logSyncEnd      = DateTime.Now;
            Variables.logSyncDuration = Variables.logSyncEnd - Variables.logSyncStart;
            Document doc = e.Document;

            #region Settings: Reload from Extensible Storage
            ParameterCommands.Load(doc);
            #endregion

            #region Extra: Tracking-Report Differences after Sync
            IEnumerable <Element>    a         = TrackChanges.Command.GetTrackedElements(doc);
            Dictionary <int, string> end_state = TrackChanges.Command.GetSnapshot(a);
            string results = TrackChanges.Command.ReportDifferences(doc, _start_state, end_state);
            _start_state = TrackChanges.Command.GetSnapshot(a);

            #endregion

            #region Post: Worksharing Info-Synchronized to Central

            if (Variables.slackOn && Variables.slackWSInfo)
            {
                string gif_lg_url = null;
                string gif_sm_url = null;

                if (Variables.giphySet > 0)
                {
                    var    giphyClient = new GiphyClient();
                    string gif_msg     = giphyClient.GetRandomGif("ThumbsUp").Content;
                    var    gif_resp    = JsonConvert.DeserializeObject <Giphy.Response>(gif_msg);

                    if (Variables.giphySet == 1)
                    {
                        gif_sm_url = gif_resp.data.fixed_height_small_url;
                    }
                    if (Variables.giphySet == 2)
                    {
                        gif_lg_url = gif_resp.data.image_url;
                    }
                }
                var slackClient = new SlackClient(Variables.slackToken);

                //Delete previous synching message, if enabled
                if (Variables.tidySet > 0)
                {
                    slackClient.DeleteMessage(msgts_synching, Variables.slackChId);
                    msgts_synching.Clear();
                }

                //Post synched message
                string text     = "";
                string channel  = Variables.slackChId;
                string botname  = "Synching Info";
                string icon_url = Variables.icon_revit;

                var attachments = new Attachments
                {
                    fallback = Variables.logUsername + "has synched",
                    color    = "good",
                    fields   =
                        new Fields[]
                    {
                        new Fields
                        {
                            title  = "Status",
                            value  = Variables.logUsername + " has synched to central.\n[" + Variables.logFileCentralName + " (Size: " + Variables.logFileSize.ToString() + "MB) ]",
                            @short = true
                        },
                        new Fields
                        {
                            title  = "Duration",
                            value  = string.Format("{0:hh\\:mm\\:ss}", Variables.logSyncDuration),
                            @short = true
                        }
                    },
                    image_url = gif_lg_url,
                    thumb_url = gif_sm_url
                };

                string msg_response = slackClient.PostMessage(text, channel: channel, botName: botname, attachments: attachments, icon_url: icon_url).Content;
                var    resp         = JsonConvert.DeserializeObject <ChatPostMessageResponse>(msg_response);
                msgts_synching.Add(resp.ts);
            }
            #endregion
        }
Exemplo n.º 4
0
        public void SlackErrorReport(string message)
        {
            SlackClient client = new SlackClient();

            client.PostMessage($"ERROR: {message}");
        }
Exemplo n.º 5
0
 public void PostMessageToAdageTracker(string text, string botName)
 {
     slackClient.PostMessage(null, "#adage-tracker", text, botName);
 }
 public void PostMessageToSlack(SlackMessage message)
 {
     SlackClient.PostMessage(message);
     ConnectionManager.GetHubContext <SlackHub>().Clients.All.addMessage(message.UserName, message.Text);
     SlackMessageStore.SaveMessage(message);
 }
Exemplo n.º 7
0
        private static async Task postaMessagetoSlack()
        {
            TFSBuildService        bs = new TFSBuildService(tfsserverKey);
            List <BuildDefinition> buildsDefn;
            BuildDefinition        psi = null;;
            BuildDefinition        psv = null;
            BuildDefinition        oc  = null;

            buildsDefn = bs.GetAllbuildsOnServer(teamProjectName);
            foreach (var buildDefinition in buildsDefn)
            {
                if (buildDefinition.DefinitionName.Equals(psibuildName))

                {
                    psi = buildDefinition;
                }
                if (buildDefinition.DefinitionName.Equals(psvbuildName))
                {
                    psv = buildDefinition;
                }
                if (buildDefinition.DefinitionName.Equals(ocbuildName))
                {
                    oc = buildDefinition;
                }
            }
            BuildStatus psibuildStatus = BuildStatus.None;
            BuildStatus psvbuildStatus = BuildStatus.None;
            BuildStatus ocbuildStatus  = BuildStatus.None;

            if (psi != null)
            {
                IBuildDetail[] bd = bs.GetLatestBuild(new BuildDefinition(psi.TeamProject, psi.DefinitionName));
                if (bd != null && bd.Length > 0)
                {
                    psibuildStatus = bs.GetLatestBuildStatusForProject(bd[0]);
                }
            }
            if (psv != null)
            {
                IBuildDetail[] bd = bs.GetLatestBuild(new BuildDefinition(psv.TeamProject, psv.DefinitionName));
                if (bd != null && bd.Length > 0)
                {
                    psvbuildStatus = bs.GetLatestBuildStatusForProject(bd[0]);
                }
            }
            if (oc != null)
            {
                IBuildDetail[] bd = bs.GetLatestBuild(new BuildDefinition(oc.TeamProject, oc.DefinitionName));
                if (bd != null && bd.Length > 0)
                {
                    ocbuildStatus = bs.GetLatestBuildStatusForProject(bd[0]);
                }
            }

            StringBuilder sb1 = new StringBuilder();

            sb1.Append("Time:" + DateTime.Now);
            sb1.Append("\n");
            sb1.Append("PSI status:");
            sb1.Append(psibuildStatus.ToString());
            sb1.Append("\n");
            sb1.Append("PSV status:");
            sb1.Append(psvbuildStatus.ToString());
            sb1.Append("\n");
            sb1.Append("OC status:");
            sb1.Append(ocbuildStatus.ToString());
            SlackClient client = new SlackClient(incomingwebhookurl);

            var response = await client.PostMessage(username : "******", text : sb1.ToString(), channel : "#localtfs");

            var isValid = response.IsSuccessStatusCode ? "valid" : "invalid";

            Console.WriteLine($"Received {isValid} response.");
        }
        public void Send(string accountId)
        {
            var slackClient = new SlackClient("my api token");

            slackClient.PostMessage(response1 => { }, "my channel", $"{accountId} try to login failed", "my bot name");
        }
Exemplo n.º 9
0
        static void ScrapeKrubbstugan(SlackClient client, List <Resturante> resturangList, int day, bool send)
        {
            HtmlAgilityPack.HtmlWeb      web = new HtmlAgilityPack.HtmlWeb();
            HtmlAgilityPack.HtmlDocument doc = web.Load("http://www.krubbstugan.se/2.html");
            Resturante krubbstugan           = new Resturante("Krubbstugan");

            resturangList.Add(krubbstugan);
            string id       = "t3";
            var    matsedel = doc.GetElementbyId(id);

            string food             = matsedel.InnerText;
            var    vecka            = new List <Veckodag>();
            var    innerScrapedText = new List <string>();



            //Get the whole meny
            innerScrapedText.AddRange(food.Split("\n"));

            //Remove the first to lines, they are irrilevant
            innerScrapedText.RemoveAt(0);
            innerScrapedText.RemoveAt(0);



            //Gather the names of the week days.
            for (int i = 0; i < innerScrapedText.Count; i += 3)
            {
                Veckodag veckodag = new Veckodag();


                innerScrapedText[i] = innerScrapedText[i].Replace("&nbsp;", " ");
                innerScrapedText[i] = innerScrapedText[i].Replace(" ", "");


                veckodag.Name = innerScrapedText[i];
                vecka.Add(veckodag);
            }

            int y = 0;
            int x = 1;

            //Gather the food of each days
            for (int i = 0; i < vecka.Count + 2; i++)
            {
                innerScrapedText[x] = innerScrapedText[x].Replace("&nbsp;", " ");
                innerScrapedText[x] = innerScrapedText[x].Replace("&amp;", " ");

                if (i == 0 || i == 3 || i == 6 || i == 9 || i == 12)
                {
                    continue;
                }

                vecka[y].FoodAlternativ.Add(innerScrapedText[x]);
                x++;
                vecka[y].FoodAlternativ.Add(innerScrapedText[x]);
                x += 2;

                y++;
            }

            //Get the right day of the week

            if (send == true)
            {
                client.PostMessage(username: "******", text: $"{vecka[day].Name} Alternativ 1 {vecka[day].FoodAlternativ[0]}", channel: "#foodchannel");
                client.PostMessage(username: "******", text: $"{vecka[day].Name} Alternativ 2 {vecka[day].FoodAlternativ[1]}", channel: "#foodchannel");
            }
            Console.WriteLine($"{vecka[day].Name} Alternativ 1 {vecka[day].FoodAlternativ[0]}");
            Console.WriteLine($"{vecka[day].Name} Alternativ 2 {vecka[day].FoodAlternativ[1]}");
        }
        public void PushMessage(string accountId)
        {
            var slackClient = new SlackClient("my api token");

            slackClient.PostMessage(responseMessage => { }, "my channel", $"my message : {accountId}", "my bot name");
        }
Exemplo n.º 11
0
        public async override Task <UpdateStepRequest> HandleStep(Step step)
        {
            var updateRequest = new UpdateStepRequest()
            {
                Id = step.Id
            };

            switch (step.StepTemplateId)
            {
            case "_GenerateSystemReport:0":
                var totalStepCount = (await _mediator.Send(new GetEntitiesQuery <Step>
                {
                    Page = 0,
                    Size = 0,
                })).Count;

                var totalUnassignedStepCount = (await _mediator.Send(new GetEntitiesQuery <Step>
                {
                    Page = 0,
                    Size = 0,
                    Expression = e => e.Status == StepStatuses.Unassigned
                })).Count;

                var totalActiveBotCount = (await _mediator.Send(new GetEntitiesQuery <BotKey>
                {
                    Page = 0,
                    Size = 0,
                    Expression = e => e.IsDisabled == false
                })).Count;

                updateRequest.Outputs = new Dictionary <string, object>()
                {
                    { "report", "Total Steps: " + totalStepCount + ", Total Unassigned Steps:" + totalUnassignedStepCount + ", Total Active Bots: " + totalActiveBotCount },
                    { "slack_report", JsonConvert.SerializeObject(new[]
                        {
                            new
                            {
                                type   = "section",
                                fields = new[] {
                                    new {
                                        text = "Total Unassigned Steps: " + totalUnassignedStepCount,
                                        type = "mrkdwn"
                                    }
                                }
                            },
                            new
                            {
                                type   = "section",
                                fields = new[] {
                                    new {
                                        text = "Total Steps: " + totalStepCount,
                                        type = "mrkdwn"
                                    }
                                }
                            },
                            new
                            {
                                type   = "section",
                                fields = new[] {
                                    new {
                                        text = "Total Active Bots: " + totalActiveBotCount,
                                        type = "mrkdwn"
                                    }
                                }
                            }
                        }) },
                    { "markdown", "" }
                };

                updateRequest.Status     = StepStatuses.Successful;
                updateRequest.StatusCode = 0;
                return(updateRequest);

            case "_SendSlackMessage:0":
                var client = new SlackClient(_clientFactory);
                await client.PostMessage((string)DynamicDataUtility.GetData(step.Inputs, "webhook_url").Value, new
                {
                    username   = (string)DynamicDataUtility.GetData(step.Inputs, "from").Value,
                    icon_emoji = step.Inputs.ContainsKey("icon_emoji") ? (string)DynamicDataUtility.GetData(step.Inputs, "icon_emoji").Value : null,
                    icon_url   = step.Inputs.ContainsKey("icon_url") ? (string)DynamicDataUtility.GetData(step.Inputs, "icon_url").Value : null,
                    channel    = step.Inputs.ContainsKey("channel") ? (string)DynamicDataUtility.GetData(step.Inputs, "channel").Value : null,
                    blocks     = step.Inputs.ContainsKey("blocks") ? JsonConvert.DeserializeObject((string)DynamicDataUtility.GetData(step.Inputs, "blocks").Value) : null,
                    text       = step.Inputs.ContainsKey("text") ? (string)DynamicDataUtility.GetData(step.Inputs, "text").Value : null
                });

                updateRequest.Status = StepStatuses.Successful;
                return(updateRequest);
            }

            updateRequest.Status = StepStatuses.Error;
            updateRequest.Log    = "Bot does not have a catch for " + step.StepTemplateId;
            return(updateRequest);
        }
        public void Process(Dictionary <string, object> parameters)
        {
            IsComplete = false;
            Message       message       = null;
            List <string> botParameters = null;
            Stats         stats         = null;
            SlackClient   slackClient   = null;
            string        userName      = null;

            foreach (var item in parameters)
            {
                switch (item.Key)
                {
                case "stats": stats = (Stats)item.Value; break;

                case "userName": userName = (string)item.Value; break;

                case "message": message = (Message)item.Value; break;

                case "parameters": botParameters = (List <string>)item.Value; break;

                case "_slackClient": slackClient = (SlackClient)item.Value; break;

                default:
                    break;
                }
            }

            if (botParameters.Count == 4 && botParameters[1] == "weather" && botParameters[2] == "now")
            {
                stats.MessageDelivered();

                Models.Attachment attachment = new Models.Attachment
                {
                    Footer = "BordaBot",
                    Ts     = Extension.ToProperTimeStamp(DateTime.Now)
                };

                RestClient  restClient  = new RestClient("https://api.openweathermap.org/data/2.5");
                RestRequest restRequest = new RestRequest("weather", Method.GET);
                restRequest.AddParameter("q", botParameters[3]);
                restRequest.AddParameter("units", "metric");
                restRequest.AddParameter("appid", ConfigurationManager.AppSettings["WeatherApiKey"]);
                var      response   = JsonConvert.DeserializeObject <WeatherData>(restClient.Execute(restRequest).Content);
                TextInfo textInfo   = new CultureInfo("en-US", false).TextInfo;
                var      querryName = char.ToUpper(botParameters[3][0]) + botParameters[3].Substring(1, botParameters[3].Length - 1);

                attachment.Color    = "#00CEE9";
                attachment.Text     = "Weather now in " + querryName + " is " + textInfo.ToTitleCase(response.Weather[0].Description);
                attachment.ThumbUrl = "http://openweathermap.org/img/w/" + response.Weather[0].Icon + ".png";

                Field temp = new Field {
                    Title = "Temperature", Value = response.Main.Temp + " ℃", Short = true
                };
                Field hum = new Field {
                    Title = "Humidity", Value = response.Main.Humidity + "%", Short = true
                };
                Field pres = new Field {
                    Title = "Pressure Level", Value = response.Main.Pressure + " hPa", Short = true
                };
                Field windsp = new Field {
                    Title = "Wind Speed", Value = response.Wind.Speed + " meter/sec", Short = true
                };

                attachment.Fields = new List <Field>
                {
                    temp, hum, pres, windsp
                };

                string attachments = "[" + JsonConvert.SerializeObject(attachment) + "]";

                slackClient.PostMessage(message.Channel, "@" + userName + ", here is the weather in " + querryName + ":", false, attachments);
            }

            else if (botParameters.Count == 4 && botParameters[1] == "weather" && botParameters[2] == "forecast")
            {
                stats.MessageDelivered();
                List <Models.Attachment> attachments = new List <Models.Attachment>();

                RestClient  restClient  = new RestClient("https://api.openweathermap.org/data/2.5");
                RestRequest restRequest = new RestRequest("forecast", Method.GET);
                restRequest.AddParameter("q", botParameters[3]);
                restRequest.AddParameter("units", "metric");
                restRequest.AddParameter("appid", ConfigurationManager.AppSettings["WeatherApiKey"]);
                var response   = JsonConvert.DeserializeObject <WeatherForecast>(restClient.Execute(restRequest).Content);
                var querryName = char.ToUpper(botParameters[3][0]) + botParameters[3].Substring(1, botParameters[3].Length - 1);

                foreach (var item in response.List)
                {
                    if (item.DtTxt.Hour == 12)
                    {
                        Models.Attachment attachment = new Models.Attachment();

                        TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;

                        attachment.Color = "#00CEE9";
                        attachment.Text  = "Weather in " + querryName + " on " + item.DtTxt.ToString("dd/MM/yyyy hh:mm") + " is "
                                           + textInfo.ToTitleCase(item.Weather[0].Description);
                        attachment.ThumbUrl = "http://openweathermap.org/img/w/" + item.Weather[0].Icon + ".png";

                        Field temp = new Field {
                            Title = "Temperature", Value = item.Main.Temp + " ℃", Short = true
                        };
                        Field hum = new Field {
                            Title = "Humidity", Value = item.Main.Humidity + "%", Short = true
                        };
                        Field pres = new Field {
                            Title = "Pressure Level", Value = item.Main.Pressure + " hPa", Short = true
                        };
                        Field windsp = new Field {
                            Title = "Wind Speed", Value = item.Wind.Speed + " meter/sec", Short = true
                        };

                        attachment.Fields = new List <Field>
                        {
                            temp, hum, pres, windsp
                        };
                        attachments.Add(attachment);
                    }
                }

                attachments.Last().Footer = "BordaBot";
                attachments.Last().Ts     = Extension.ToProperTimeStamp(DateTime.Now);

                string attachmentString = JsonConvert.SerializeObject(attachments);

                slackClient.PostMessage(message.Channel, "@" + userName + ", here is the weather forecast for 5 days in " + querryName
                                        + ":", false, attachmentString);
            }
        }
Exemplo n.º 13
0
        public async Task <IActionResult> Post()
        {
            var file = await client.Files.DownloadAsync("/Documents/Employee Birthday List.xlsx");

            var birthdays = new List <Birthday>();
            var stream    = await file.GetContentAsStreamAsync();

            IWorkbook workbook = new XSSFWorkbook(stream);
            var       sheet    = workbook.GetSheet("Sheet1");

            for (var i = 2; i < sheet.LastRowNum; i++)
            {
                var row        = sheet.GetRow(i);
                var name       = row.GetCell(0).StringCellValue;
                var dateString = row.GetCell(1).StringCellValue;

                if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(dateString))
                {
                    continue;
                }

                try
                {
                    var formattedDateString = $@"{
                                   dateString
                                        .TrimEnd()
                                        .TrimEnd("nd", StringComparison.InvariantCulture)
                                        .Replace("Autust", "August")
                                        .Replace("Spetember", "September")
                                        .TrimEnd("th", StringComparison.InvariantCulture)
                                        .TrimEnd("rd", StringComparison.InvariantCulture)
                                        .TrimEnd("st", StringComparison.InvariantCulture)
                                        .Trim()
                              } 2010".Trim();

                    var date = DateTime.ParseExact(formattedDateString, "MMMM d yyyy",
                                                   CultureInfo.InvariantCulture);
                    birthdays.Add(new Birthday {
                        Name = name, Date = date
                    });
                }
                catch (FormatException)
                {
                    // TODO: log error when I actually have an error logger
                    // throw new Exception($"{dateString} is not recognized as a valid date", ex);
                }
            }

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

            var lastNight = new DateTime(2010, DateTime.Now.Month, DateTime.Now.Day)
                            .Subtract(TimeSpan.FromDays(1).Subtract(TimeSpan.FromSeconds(1)));
            var nextSundayNight = lastNight.AddDays(7);

            var thisWeeksBdays = birthdays.Where(bday => bday.Date > lastNight && bday.Date <= nextSundayNight);

            var messageString =
                ":tada: :birthday: We wish the following team members a very Happy Birthday :tada: :birthday:" +
                Environment.NewLine;

            foreach (var personBirthday in thisWeeksBdays)
            {
                messageString += personBirthday.Name + " - " + personBirthday.Date.ToString("MM/dd") +
                                 Environment.NewLine;
            }

            slackClient.PostMessage(new Payload {
                Text = messageString
            });

            return(this.Ok(birthdays));
        }
Exemplo n.º 14
0
        public void PushMessage(string accountId)
        {
            var slackClient = new SlackClient("my Api token");

            slackClient.PostMessage(r => { }, "mychannel", $"message {accountId}");
        }
Exemplo n.º 15
0
        private void appDocClosing(object sender, Autodesk.Revit.DB.Events.DocumentClosingEventArgs e)
        {
            BasicFileInfo fileInfo = BasicFileInfo.Extract(Variables.logFilePath);

            #region Post: Worksharing Warning-Close without saving

            if (Variables.slackOn && Variables.slackWSWarn)
            {
                if (fileInfo.AllLocalChangesSavedToCentral == false)
                {
                    string gif_lg_url = null;
                    string gif_sm_url = null;

                    if (Variables.giphySet > 0)
                    {
                        var    giphyClient = new GiphyClient();
                        string gif_msg     = giphyClient.GetRandomGif("Disappointed").Content;
                        var    gif_resp    = JsonConvert.DeserializeObject <Giphy.Response>(gif_msg);
                        if (Variables.giphySet == 1)
                        {
                            gif_sm_url = gif_resp.data.fixed_height_small_url;
                        }
                        if (Variables.giphySet == 2)
                        {
                            gif_lg_url = gif_resp.data.image_url;
                        }
                    }
                    var slackClient = new SlackClient(Variables.slackToken);

                    string text     = "";
                    string channel  = Variables.slackChId;
                    string botname  = "Worksharing Warning";
                    string icon_url = Variables.icon_revit;

                    var attachments = new Attachments
                    {
                        fallback = Variables.logUsername + "did not save to central before closing",
                        color    = "danger",
                        fields   =
                            new Fields[]
                        {
                            new Fields
                            {
                                title  = "Description",
                                value  = "The user has closed the model without saving their changes back to the central model. Open the model and save changes back to the central model.",
                                @short = false
                            },
                            new Fields
                            {
                                title  = "User",
                                value  = Variables.logUsername,
                                @short = true
                            },
                            new Fields
                            {
                                title  = "File",
                                value  = Variables.logFileCentralName,
                                @short = true
                            }
                        },
                        image_url = gif_lg_url,
                        thumb_url = gif_sm_url
                    };

                    string msg_response = slackClient.PostMessage(text, channel: channel, botName: botname, attachments: attachments, icon_url: icon_url).Content;
                    var    resp         = JsonConvert.DeserializeObject <ChatPostMessageResponse>(msg_response);
                    msgts_ws.Add(resp.ts);
                }
            }
            #endregion
        }
Exemplo n.º 16
0
        private void appDocOpened(object sender, Autodesk.Revit.DB.Events.DocumentOpenedEventArgs e)
        {
            Variables.logOpenEnd      = DateTime.Now;
            Variables.logOpenDuration = Variables.logOpenEnd - Variables.logOpenStart;

            Autodesk.Revit.ApplicationServices.Application app = sender as Autodesk.Revit.ApplicationServices.Application;
            Document doc = e.Document;

            #region Variables: Document & Application Variables
            string path = GetUNCPath(doc.PathName);

            BasicFileInfo fileInfo = BasicFileInfo.Extract(path);
            FileInfo      f        = new FileInfo(path);

            Variables.logComputerName    = Environment.MachineName;
            Variables.logChangesSaved    = fileInfo.AllLocalChangesSavedToCentral;
            Variables.logFileCentral     = GetUNCPath(fileInfo.CentralPath);
            Variables.logFileCentralName = Path.GetFileName(Variables.logFileCentral);
            Variables.logIsCentral       = fileInfo.IsCentral;
            Variables.logIsWorkshared    = fileInfo.IsWorkshared;
            Variables.logCreatedLocal    = fileInfo.IsCreatedLocal;

            Variables.logFileName = doc.Title;
            Variables.logFilePath = GetUNCPath(doc.PathName);
            Variables.logFileSize = Convert.ToInt32(f.Length / 1000000);

            Variables.logUsername      = app.Username;
            Variables.logVersionBuild  = app.VersionBuild;
            Variables.logVersionName   = app.VersionName;
            Variables.logVersionNumber = app.VersionNumber;
            #endregion

            #region Tracking: Start Logging Pinned Elements
            IEnumerable <Element> a = TrackChanges.Command.GetTrackedElements(doc);
            _start_state = TrackChanges.Command.GetSnapshot(a);
            #endregion


            #region Settings: Load settings if they exist (Extensible Storage)
            ParameterCommands.Load(doc);
            #endregion

            #region Post: Worksharing Warning-Opened Central Model
            bool patheq = string.Equals(Variables.logFileCentral, Variables.logFilePath);

            if (Variables.slackOn && Variables.slackWSWarn)
            {
                if (patheq && Variables.logIsWorkshared)
                {
                    string gif_lg_url = null;
                    string gif_sm_url = null;

                    if (Variables.giphySet > 0)
                    {
                        var    giphyClient = new GiphyClient();
                        string gif_msg     = giphyClient.GetRandomGif("Alarm").Content;
                        var    gif_resp    = JsonConvert.DeserializeObject <Giphy.Response>(gif_msg);

                        if (Variables.giphySet == 1)
                        {
                            gif_sm_url = gif_resp.data.fixed_height_small_url;
                        }

                        if (Variables.giphySet == 2)
                        {
                            gif_lg_url = gif_resp.data.image_url;
                        }
                    }

                    var slackClient = new SlackClient(Variables.slackToken);

                    string text     = "";
                    string channel  = Variables.slackChId;
                    string botname  = "Worksharing Warning";
                    string icon_url = Variables.icon_revit;

                    var attachments = new Attachments
                    {
                        fallback = Variables.logUsername + "has opened the central model",
                        color    = "danger",
                        fields   =
                            new Fields[]
                        {
                            new Fields
                            {
                                title  = "Description",
                                value  = "The user has opened the central model. Close the central model and create a new local file> to work from.",
                                @short = false
                            },
                            new Fields
                            {
                                title  = "User",
                                value  = Variables.logUsername,
                                @short = true
                            },
                            new Fields
                            {
                                title  = "File",
                                value  = Variables.logFileCentralName,
                                @short = true
                            }
                        },
                        image_url = gif_lg_url,
                        thumb_url = gif_sm_url
                    };

                    string msg_response = slackClient.PostMessage(text, channel: channel, botName: botname, attachments: attachments, icon_url: icon_url).Content;
                    var    resp         = JsonConvert.DeserializeObject <ChatPostMessageResponse>(msg_response);
                    msgts_ws.Add(resp.ts);
                }
            }
            #endregion

            #region Post: Model Warning-File Size > 300MB
            if (Variables.slackOn && Variables.slackModelWarn)
            {
                string gif_lg_url = null;
                string gif_sm_url = null;

                if (Variables.logFileSize > 300)
                {
                    if (Variables.giphySet > 0)
                    {
                        var    giphyClient = new GiphyClient();
                        string gif_msg     = giphyClient.GetRandomGif("Gasp").Content;
                        var    gif_resp    = JsonConvert.DeserializeObject <Giphy.Response>(gif_msg);

                        if (Variables.giphySet == 1)
                        {
                            gif_sm_url = gif_resp.data.fixed_height_small_url;
                        }

                        if (Variables.giphySet == 2)
                        {
                            gif_lg_url = gif_resp.data.image_url;
                        }

                        var slackClient = new SlackClient(Variables.slackToken);

                        string text     = "";
                        string channel  = Variables.slackChId;
                        string botname  = "Model Warning";
                        string icon_url = Variables.icon_revit;

                        var attachments = new Attachments
                        {
                            fallback = "The file size has gone above 300MB, time to do some model file size management.",
                            color    = "danger",
                            fields   =
                                new Fields[]
                            {
                                new Fields
                                {
                                    title  = "Description",
                                    value  = "The file size is above 300MB, time to do some model maintenance",
                                    @short = false
                                },
                                new Fields
                                {
                                    title  = "File Size",
                                    value  = Variables.logFileSize.ToString() + "MB",
                                    @short = true
                                },
                                new Fields
                                {
                                    title  = "File",
                                    value  = Variables.logFileCentralName,
                                    @short = true
                                }
                            },
                            image_url = gif_lg_url,
                            thumb_url = gif_sm_url
                        };

                        string msg_response = slackClient.PostMessage(text, channel: channel, botName: botname, attachments: attachments, icon_url: icon_url).Content;
                        var    resp         = JsonConvert.DeserializeObject <ChatPostMessageResponse>(msg_response);

                        msgts_model.Add(resp.ts);
                    }
                }
                #endregion

                #region Post: Tracking-Pinned Element-Started

                if (Variables.slackOn && Variables.slackExtraTrackPin)
                {
                    var slackClient = new SlackClient(Variables.slackToken);

                    //Post pinned elements message
                    string text     = "";
                    string channel  = Variables.slackChId;
                    string botname  = "Pinning Info";
                    string icon_url = Variables.icon_revit;


                    var attachments = new Attachments
                    {
                        fallback = Variables.logUsername + "has started tracking pinned elements.",
                        color    = "good",
                        fields   =
                            new Fields[]
                        {
                            new Fields
                            {
                                title  = "Status",
                                value  = Variables.logUsername + " has started tracking pinned elements.\n[" + Variables.logFileCentralName + "]",
                                @short = true
                            }
                        }
                    };

                    string msg_response = slackClient.PostMessage(text, channel: channel, botName: botname, attachments: attachments, icon_url: icon_url).Content;
                    var    resp         = JsonConvert.DeserializeObject <ChatPostMessageResponse>(msg_response);
                    msgts_extra.Add(resp.ts);
                }
                #endregion
            }
        }
        public void Notify()
        {
            var slackClient = new SlackClient("my api token");

            slackClient.PostMessage(response1 => { }, "my channel", "my message", "my bot name");
        }
Exemplo n.º 18
0
        public void ReportMe(Exception xception)
        {
            string test1 = default(string);
            string test2 = default(string);
            string test3 = default(string);
            string gpu   = default(string);
            string cpu   = "CPU Model: ";
            string clr   = "CLR Version: " + System.Runtime.InteropServices.RuntimeEnvironment.GetSystemVersion();
            string space = Environment.NewLine;

            ManagementObjectSearcher mos = new ManagementObjectSearcher("select * from Win32_OperatingSystem");

            foreach (ManagementObject managementObject in mos.Get())
            {
                if (managementObject["Caption"] != null)
                {
                    test1 = "Operating System Name  :  " + managementObject["Caption"].ToString();
                }
                if (managementObject["OSArchitecture"] != null)
                {
                    test2 = "Operating System Architecture  :  " + managementObject["OSArchitecture"].ToString();
                }
                if (managementObject["CSDVersion"] != null)
                {
                    test3 = "Operating System Service Pack   :  " + managementObject["CSDVersion"].ToString() + space;
                }
            }

            ManagementObjectSearcher myVideoObject = new ManagementObjectSearcher("select * from Win32_VideoController");

            foreach (ManagementObject obj in myVideoObject.Get())
            {
                gpu = "GPU Model: " + obj["Name"] + space;
            }

            RegistryKey processor_name = Registry.LocalMachine.OpenSubKey(@"Hardware\Description\System\CentralProcessor\0", RegistryKeyPermissionCheck.ReadSubTree);   //This registry entry contains entry for processor info.
            string      test4          = (string)processor_name.GetValue("ProcessorNameString");

            string divider = "----------SOMEBODY SOMEWHERE BROKE SYNTHESIS----------" + space;

            osDetails    = space + space + test1 + space + test2 + space + test3 + space + clr + space + space + cpu + test4 + space + gpu + space;
            errorDetails = "Exception Message: " + xception.Message + space + "Exception Data: " + xception.Data + space + "Exception Source: " + xception.Source + space + space + "Stack Trace:" + "```" + xception.StackTrace + "```";
            userDetails  = space + "User Email: " + textBox1.Text + space + "User Error Details: " + textBox2.Text + space;
            File.WriteAllText(@"Synthesis Crash Report.txt", errorDetails + space + osDetails + space + userDetails);

            if (DontSend == false)
            {
                try
                {
                    //ulong toalRam = cinfo.TotalPhysicalMemory;
                    //double toal = Convert.ToDouble(toalRam / (1024 * 1024));
                    //int t = Convert.ToInt32(Math.Ceiling(toal / 1024).ToString());
                    //label6.Text = t.ToString() + " GB";// ram detail

                    string urlWithAccessToken = "INSERT WEBHOOK LINK HERE";

                    SlackClient client = new SlackClient(urlWithAccessToken);

                    client.PostMessage(username: "******",
                                       text: divider + errorDetails + osDetails + userDetails,
                                       channel: "#failures");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                Environment.Exit(0);
            }
        }
Exemplo n.º 19
0
        public static void TestPostMessage()
        {
            SlackClient client = new SlackClient();

            client.PostMessage("THIS IS A TEST MESSAGE! SQUEEDLYBAMBLYFEEDLYMEEDLYMOWWWWWWWW!");
        }
        public void Notify(string accountId)
        {
            var slackClient = new SlackClient("my api token");

            slackClient.PostMessage(response1 => { }, "my channel", accountId, "my bot name");
        }
Exemplo n.º 21
0
        public void Process(Dictionary <string, object> parameters)
        {
            Message       message       = null;
            List <string> botParameters = null;
            Stats         stats         = null;
            SlackClient   slackClient   = null;
            TimerPipeline timerPipeline = null;
            string        userName      = null;
            string        userId        = null;

            foreach (var item in parameters)
            {
                switch (item.Key)
                {
                case "stats": stats = (Stats)item.Value; break;

                case "userName": userName = (string)item.Value; break;

                case "userId": userId = (string)item.Value; break;

                case "message": message = (Message)item.Value; break;

                case "parameters": botParameters = (List <string>)item.Value; break;

                case "_timerPipeline": timerPipeline = (TimerPipeline)item.Value; break;

                case "_slackClient": slackClient = (SlackClient)item.Value; break;

                default:
                    break;
                }
            }

            if (botParameters[1] == "stayhydrated" && botParameters[2] == "subscribe" && botParameters.Count == 4)
            {
                foreach (var item in timerPipeline._pipelineElemets)
                {
                    if (item.GetType() == typeof(StayHydratedTimerMiddleware))
                    {
                        if (!item.SubscribersList.Exists(obj => obj.UserId == userId))
                        {
                            Pair newPair = new Pair
                            {
                                UserId           = userId,
                                SubscriptionDate = DateTime.Now,
                                LastReminded     = DateTime.Now,
                                Interval         = Int32.Parse(botParameters[3]),
                                UserName         = userName
                            };
                            item.SubscribersList.Add(newPair);

                            Models.Attachment attachment = new Models.Attachment
                            {
                                Color = "#04DF00",
                                Text  = "You are added to subscription list of Stay Hydrated. You will be notified every " + Int32.Parse(botParameters[3]) +
                                        " minute(s) to drink water. Wish you a nice day.",
                                Footer = "BordaBot",
                                Ts     = Extension.ToProperTimeStamp(DateTime.Now)
                            };
                            string attachments = "[" + JsonConvert.SerializeObject(attachment) + "]";
                            slackClient.PostMessage(message.Channel, "@" + userName + ":", false, attachments);
                        }
                        else
                        {
                            slackClient.PostMessage(message.Channel, "@" + userName + ", you have already subscribed for this service.");
                        }
                    }
                }
            }
            else if (botParameters[1] == "stayhydrated" && botParameters[2] == "unsubscribe")
            {
                foreach (var item in timerPipeline._pipelineElemets)
                {
                    if (item.GetType() == typeof(StayHydratedTimerMiddleware))
                    {
                        if (item.SubscribersList.Exists(obj => obj.UserId == userId))
                        {
                            item.SubscribersList.RemoveAll(obj => obj.UserId == userId);

                            Models.Attachment attachment = new Models.Attachment
                            {
                                Color  = "danger",
                                Text   = "You are removed from subscription list of Stay Hydrated.",
                                Footer = "BordaBot",
                                Ts     = Extension.ToProperTimeStamp(DateTime.Now)
                            };
                            string attachments = "[" + JsonConvert.SerializeObject(attachment) + "]";
                            slackClient.PostMessage(message.Channel, "@" + userName + ":", false, attachments);
                        }
                        else
                        {
                            slackClient.PostMessage(message.Channel, "@" + userName + ", you are not subscribed for this service.");
                        }
                    }
                }
            }
        }
Exemplo n.º 22
0
        static void Main(string[] args)
        {
            try
            {
                var clientId     = "PUT CLIENT ID FROM SLACK APPLICATION REGISTATION HERE";
                var clientSecret = "PUT CLIENT SECRET FROM SLACK APPLICATION REGISTATION HERE";
                var redirectUri  = "PUT REDIRECT FROM SLACK APPLICATION REGISTATION HERE";

                Console.WriteLine("------------------------------------------------------------------");
                Console.WriteLine("This app will open your web browser pointing at an authentication");
                Console.WriteLine("page. When you complete authentication, you'll be sent back to ");
                Console.WriteLine("whatever 'redirectUri' is above, plus some query-string values. ");
                Console.WriteLine("Paste the URI into the console window when prompted.");
                Console.WriteLine();
                Console.WriteLine("In a proper web application, the user experience will obviously");
                Console.WriteLine("be more sensible...");
                Console.WriteLine("------------------------------------------------------------------");

                // start...
                var state = Guid.NewGuid().ToString();
                var uri   = SlackClient.GetAuthorizeUri(clientId, SlackScope.Identify | SlackScope.Read | SlackScope.Post, redirectUri, state, "socialsaleslounge");
                Console.WriteLine("Directing to: " + uri);
                Process.Start(uri.ToString());

                // read the result -- in a web application you can pick this up directly, here we're fudging it...
                Console.WriteLine("Paste in the URL of the authentication result...");
                var asString = Console.ReadLine();
                var index    = asString.IndexOf('?');
                if (index != -1)
                {
                    asString = asString.Substring(index + 1);
                }

                // parse...
                var qs       = HttpUtility.ParseQueryString(asString);
                var code     = qs["code"];
                var newState = qs["state"];

                // validate the state. this isn't required, but it's makes sure the request and response line up...
                if (state != newState)
                {
                    throw new InvalidOperationException("State mismatch.");
                }

                // then get the token...
                Console.WriteLine("Requesting access token...");
                SlackClient.GetAccessToken((response) =>
                {
                    var accessToken = response.access_token;
                    Console.WriteLine("Got access token '{0}'...", accessToken);

                    // post...
                    var client = new SlackClient(accessToken);
                    client.PostMessage(null, "#registrations", "Test", "Jo the Robot");
                }, clientId, clientSecret, redirectUri, code);

                // finished...
                Console.WriteLine("Done.");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                Console.ReadLine();
            }
        }
Exemplo n.º 23
0
        public void PushMessage(string account)
        {
            var slackClient = new SlackClient("my api token");

            slackClient.PostMessage(slackResponse => { }, "my channel", $"{account} message", "my bot name");
        }
Exemplo n.º 24
0
        public void PushMessage(string message)
        {
            var slackClient = new SlackClient("my api token");

            slackClient.PostMessage(resp => { }, "my channel", message, "my bot name");
        }
Exemplo n.º 25
0
 private static void PushMessage()
 {
     var slackClient = new SlackClient("my api token");
     slackClient.PostMessage(postMessageResponse => { }, "my channel", "my message", "my bot name");
 }