protected override void Load(ContainerBuilder builder) { base.Load(builder); var slackClient = new SlackClient(slackWebhookURL); builder.RegisterInstance(slackClient).As<SlackClient>(); }
public void SlackClient_should_remember_timeout() { const string webserviceurl = "https://hooks.slack.com/invalid"; var timeoutSeconds = 2; var client = new SlackClient(webserviceurl, timeoutSeconds); Assert.Equal(timeoutSeconds * 1000, client.TimeoutMs); }
public static void SendMessage(string messageText) { SlackClient client = new SlackClient(_SlackUrlWithAccessToken); client.PostMessage(username: _SlackWebHookName, text: messageText, channel: _SlackChannelName); }
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"); }
public void SlackClient_returns_false_if_post_fails() { //arrange const string webserviceurl = "https://hooks.slack.com/invalid"; var client = new SlackClient(webserviceurl); //act var slackMessage = new SlackMessage { Text = "Test Message", Channel = "#test", Username = "******", IconEmoji = Emoji.Ghost }; var result = client.Post(slackMessage); //assert Assert.False(result); }
/// <summary> /// Initializes a new instance of the <see cref="SlackTraceListener"/> /// class using the specified webhook address. /// </summary> /// <param name="webhookAddress"> /// The address of the Slack Incoming Webhook to post messages to. /// </param> public SlackTraceListener(Uri webhookAddress) { Client = new SlackClient(webhookAddress.ToString()); }
public static void Run([TimerTrigger("0 0 15 * * *")] TimerInfo myTimer, TraceWriter log) // 10:00AM eastern { log.Info($"{DateTime.Now} : Function starting..."); int sqlOffenses = 0; string botToken = Environment.GetEnvironmentVariable("botToken"); string ruleChange = Environment.GetEnvironmentVariable("UpdateRules"); string whiteList = Environment.GetEnvironmentVariable("WhiteList"); if (string.IsNullOrEmpty(botToken)) { log.Error($"{DateTime.Now} : One or more of the required app settings is missing, check the Azure portal to verify all parameters."); return; } var slackClient = new SlackClient(new HttpClient(), botToken); var slackPost = new SlackPost { Channel = Environment.GetEnvironmentVariable("channel"), Text = "Azure SQL FW Auditor findings" }; if (!bool.TryParse(ruleChange, out bool updateFwSetting)) { updateFwSetting = false; log.Info($"{DateTime.Now} : Unable to parse 'UpdateRules' setting {ruleChange}. Defaulting to False"); } else { log.Info($"{DateTime.Now} : UpdateRules variable set to {updateFwSetting}"); } AzureCredentialsFactory credFactorty = new AzureCredentialsFactory(); var msi = new MSILoginInformation(MSIResourceType.AppService); var msiCred = credFactorty.FromMSI(msi, AzureEnvironment.AzureGlobalCloud); var azureAuth = Azure.Configure() .WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders) .Authenticate(msiCred); var approvedRanges = string.IsNullOrEmpty(whiteList) ? ipRanges.ToList() : ipRanges.Union(whiteList.Split(',')).ToList(); log.Info($"{DateTime.Now} : Authenticated into tenant... Pulling subscriptions"); var fields = new List <SlackField>(); foreach (var sub in azureAuth.Subscriptions.List()) { log.Verbose($"{DateTime.Now} : Logging into subscription : {sub.SubscriptionId.ToString()}"); var azure = Azure.Configure() .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .Authenticate(msiCred).WithSubscription(sub.SubscriptionId.ToString()); // loop through the sql servers in the subscription foreach (var server in azure.SqlServers.List()) { var outOfRangeRules = server.FirewallRules.List().Where(ruleDef => IsIpInRange(ruleDef.StartIPAddress, approvedRanges) == false || IsIpInRange(ruleDef.EndIPAddress, approvedRanges) == false); // process all the rules that are deemed bad foreach (var firewallRule in outOfRangeRules) { var field = new SlackField { Short = false, Title = " ", }; // The appsetting is set to true, so we try and delete the rule. if (updateFwSetting) { try { firewallRule.Delete(); field.Value = $"Server - {server.Name}, Firewall Rule(s) : \r\n>{firewallRule.Name} : {firewallRule.StartIPAddress} - {firewallRule.EndIPAddress} *Deleted : YES*"; } catch (Exception e) { field.Value = $"Server - {server.Name}, Firewall Rule(s) : \r\n>{firewallRule.Name} : {firewallRule.StartIPAddress} - {firewallRule.EndIPAddress} *Deleted : NO, encountered exception*"; log.Warning($"{DateTime.Now} : {e.Message}"); } } else { field.Value = $"{server.Name}, Firewall Rule(s) : \r\n>{firewallRule.Name} : {firewallRule.StartIPAddress} - {firewallRule.EndIPAddress} *Deleted : NO, deletion not enabled.*"; log.Info($"{DateTime.Now} : FW setting {updateFwSetting} firewall rule {firewallRule.Name} will be left to fester here"); } sqlOffenses++; } // Once its clean we add in missing ranges AddInMissingIpRanges(log, server); } } if (fields.Any()) { slackPost.Attachments = new List <SlackAttachment>() { new SlackAttachment { Fields = fields, Color = "ok", Title = " ", } }; _ = slackClient.PostToSlackAsync(slackPost); } }
public static async Task <SlackBaseResponse> DeleteFileAsync(SlackClient slackClient, string channelName) { var uploadFileResponse = await UploadFileAsync(slackClient, channelName); return(await slackClient.Files.DeleteAsync(uploadFileResponse.File.Id)); }
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(); } }
private static async Task Main(string[] args) { var configuration = new ConfigurationBuilder() .AddJsonFile("settings.json", false) .AddUserSecrets(Assembly.GetEntryAssembly()) .Build(); var queues = configuration.GetSection("Queues").Get <List <string> >(); var messageCounts = queues.ToDictionary(q => q, _ => (uint)0); var connectionFactory = CreateConnectionFactory(configuration); var cts = new CancellationTokenSource(); var runningTask = Task.Run(async() => { using var connection = connectionFactory.CreateConnection(); using var channel = connection.CreateModel(); foreach (var q in queues) { messageCounts[q] = channel.MessageCount(q); } while (!cts.IsCancellationRequested) { foreach (var queueName in queues) { var count = channel.MessageCount(queueName); Log($"Queue {queueName} contains {count} messages."); messageCounts.TryGetValue(queueName, out var oldCount); if (count > oldCount) { Log($"{queueName} contains {count - oldCount} more message(s) than before."); if (IsSlackConfigured()) { await SendWebHookAsync(queueName, oldCount, count); } } messageCounts[queueName] = count; } await Task.Delay(TimeSpan.FromMinutes(1), cts.Token); } }, cts.Token); Log("Monitoring RabbitMQ. Hit return to stop."); Console.ReadLine(); cts.Cancel(); try { await runningTask; } catch (OperationCanceledException) { } async Task SendWebHookAsync(string queueName, uint oldCount, uint newCount) { var slackClient = new SlackClient(configuration["Slack:WebHookEndPoint"]); var channelName = configuration["Slack:ChannelName"]; Log($"-- Sending message to channel {channelName}.."); await slackClient.PostAsync(new SlackMessage { Channel = channelName, Text = $"Queue {queueName} contains {newCount} messages, up from {oldCount}.", IconEmoji = Emoji.Ghost }); } bool IsSlackConfigured() => !string.IsNullOrWhiteSpace(configuration["Slack:WebHookEndPoint"]) && !string.IsNullOrWhiteSpace(configuration["Slack:ChannelName"]);
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 WebHookUrl() { var sut = new SlackClient(Helpers.Random); Assert.IsNotNull(sut.WebHookUrl); }
public AquariumMonitor(Store store, IHubContext <DashboardHub> hubContext, IConfiguration configuration) { this._store = store; this._hubContext = hubContext; this._aquaWebHookUrl = configuration.GetSection("WebHookUrl").GetSection("AquariumSlack").Get <string>(); this._errorWebHookUrl = configuration.GetSection("WebHookUrl").GetSection("ErrorSlack").Get <string>(); var slackClient = new SlackClient(this._aquaWebHookUrl).AddTo(this._compositeDisposable); var errorSlackClient = new SlackClient(this._errorWebHookUrl).AddTo(this._compositeDisposable); // 更新値通知 this._store .Aquarium .LatestTimeStamp .CombineLatest( this._store.Aquarium.LatestWaterTemperature, this._store.Aquarium.LatestHumidity, this._store.Aquarium.LatestTemperature, (time, water, humidity, temp) => new { time, water, humidity, temp }) .Throttle(TimeSpan.FromMilliseconds(10)) .Subscribe(async x => { await this._hubContext.Clients.All.SendAsync( DashboardHub.GetMethodName(DashboardHub.Method.AquaStateChanged), x.time, x.water, x.humidity, x.temp); }).AddTo(this._compositeDisposable); // 室温警告 store .Aquarium .LatestTemperature .Where(x => x >= 30 && x >= this._store.Aquarium.LastWarnedTemperature.Value + 0.5) .Subscribe(async x => { this._store.Aquarium.LastWarnedTemperature.Value = x; await slackClient.PostAsync(new SlackMessage { Text = $"室温警告 : {x:##.000}℃", Username = "******" }); }).AddTo(this._compositeDisposable); // 室温警告解除 store .Aquarium .LatestTemperature .Where(_ => this._store.Aquarium.LastWarnedTemperature.Value >= 29) .Where(x => x < 29 || x <= this._store.Aquarium.LastWarnedTemperature.Value - 0.5) .Subscribe(async x => { this._store.Aquarium.LastWarnedTemperature.Value = x; if (x < 29) { await slackClient.PostAsync(new SlackMessage { Text = $"室温警告解除 : {x:##.000}℃", Username = "******" }); } else { await slackClient.PostAsync(new SlackMessage { Text = $"室温が{x:##.000}℃まで下がりました。", Username = "******" }); } }).AddTo(this._compositeDisposable); // 水温警告 store .Aquarium .LatestWaterTemperature .Where(x => x >= 29 && x >= this._store.Aquarium.LastWarnedWaterTemperature.Value + 0.5) .Subscribe(async x => { this._store.Aquarium.LastWarnedWaterTemperature.Value = x; await slackClient.PostAsync(new SlackMessage { Text = $"水温警告 : {x:##.000}℃", Username = "******" }); }).AddTo(this._compositeDisposable); // 水温警告解除 store .Aquarium .LatestWaterTemperature .Where(_ => this._store.Aquarium.LastWarnedWaterTemperature.Value >= 28) .Where(x => x < 28 || x <= this._store.Aquarium.LastWarnedWaterTemperature.Value - 0.5) .Subscribe(async x => { this._store.Aquarium.LastWarnedWaterTemperature.Value = x; if (x < 28) { await slackClient.PostAsync(new SlackMessage { Text = $"水温警告解除 : {x:##.000}℃", Username = "******" }); } else { await slackClient.PostAsync(new SlackMessage { Text = $"水温が{x:##.000}℃まで下がりました。", Username = "******" }); } }).AddTo(this._compositeDisposable); store.Aquarium .LatestWaterTemperature .Throttle(TimeSpan.FromMinutes(10)) .Subscribe(async _ => { await errorSlackClient.PostAsync(new SlackMessage { Text = "10分間水温を受信していません。" }); }); }
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"); }
public void Setup() { Target = new SlackClient(); TestMessage = "Integration Test Message"; }
public void Notify(string message) { var slackClient = new SlackClient("my api token"); slackClient.PostMessage(response1 => { }, "my channel", message, "my bot name"); }
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); } }
public void TestMessage() { var client = new SlackClient(""); client.SendMessage("", "", "", ""); }
public static async Task <FileInfoResponse> GetFileInfoAsync(SlackClient slackClient, string channelName) { var uploadFileResponse = await UploadFileAsync(slackClient, channelName); return(await slackClient.Files.InfoAsync(uploadFileResponse.File.Id)); }
public GroupAdapter(Channel info, ConnectedInterface connected, SlackClient client) { this.info = info; this.connected = connected; this.client = client; }
static void TestPostMessage(SlackMessage message, LogLevel level = LogLevel.Info, ConsoleColor color = ConsoleColor.Black, bool force = false) { var slackClient = new SlackClient(webhookURL); slackClient.Post(message); }
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."); }
static void TestPostMessage(string message, LogLevel level = LogLevel.Info, ConsoleColor color = ConsoleColor.Black, bool force = false) { //var context = parseLogContext(level); var slackMessage = new SlackMessage { Channel = channel, Text = message, IconEmoji = ":nerd_face:", Username = botName + "Info" }; SlackAttachment slackAttachment; switch (level) { case LogLevel.Error: slackMessage.Text = "uh oh! I'm in trouble!"; slackMessage.IconEmoji = Emoji.Scream; slackMessage.Username = botName + "Error"; slackAttachment = new SlackAttachment { Text = message, Color = "#C0392B" }; slackMessage.Attachments = new List <SlackAttachment> { slackAttachment }; break; case LogLevel.Warning: slackMessage.Text = "this is a warning..."; slackMessage.IconEmoji = ":thinking_face:"; slackMessage.Username = botName + "Warning"; slackAttachment = new SlackAttachment { Text = message, Color = "#F4D03F" }; slackMessage.Attachments = new List <SlackAttachment> { slackAttachment }; break; case LogLevel.Info: //Console.ForegroundColor = color == ConsoleColor.Black ? ConsoleColor.DarkCyan : color; //Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({LoggingStrings.Info}) {message}"); break; case LogLevel.Pokestop: slackMessage.Text = "made it to another pokestop!"; slackMessage.IconEmoji = Emoji.Blush; slackMessage.Username = botName + "LootingStop"; slackAttachment = new SlackAttachment { Text = message, Color = "#3498DB" }; slackMessage.Attachments = new List <SlackAttachment> { slackAttachment }; break; case LogLevel.Farming: //Console.ForegroundColor = color == ConsoleColor.Black ? ConsoleColor.Magenta : color; //Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({LoggingStrings.Farming}) {message}"); break; case LogLevel.Sniper: //Console.ForegroundColor = color == ConsoleColor.Black ? ConsoleColor.White : color; //Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({LoggingStrings.Sniper}) {message}"); break; case LogLevel.Recycling: slackMessage.Text = ""; slackMessage.IconEmoji = ":recycle:"; slackMessage.Username = botName + "Recycling"; slackAttachment = new SlackAttachment { Text = message, Color = "#8E44AD" }; slackMessage.Attachments = new List <SlackAttachment> { slackAttachment }; break; case LogLevel.Caught: slackMessage.Text = "I caught the guy!"; slackMessage.IconEmoji = Emoji.Laughing; slackMessage.Username = botName + "Caught"; slackAttachment = new SlackAttachment { Text = message, Color = "#2ECC71" }; slackMessage.Attachments = new List <SlackAttachment> { slackAttachment }; break; case LogLevel.Flee: slackMessage.Text = "he's getting away from me!"; slackMessage.IconEmoji = ":anguished:"; slackMessage.Username = botName + "Struggling"; slackAttachment = new SlackAttachment { Text = message, Color = "#F4D03F" }; slackMessage.Attachments = new List <SlackAttachment> { slackAttachment }; break; case LogLevel.Transfer: slackMessage.Text = @"I'm /'transfering/' pokemon. Not putting them in a blender"; slackMessage.IconEmoji = Emoji.Smirk; slackMessage.Username = botName + "Transfering"; slackAttachment = new SlackAttachment { Text = message, Color = "#186A3B" }; slackMessage.Attachments = new List <SlackAttachment> { slackAttachment }; break; case LogLevel.Evolve: slackMessage.Text = @"Oh shit dat evolve"; slackMessage.IconEmoji = Emoji.Frog; slackMessage.Username = botName + "Evolving"; slackAttachment = new SlackAttachment { Text = message, Color = "#186A3B" }; slackMessage.Attachments = new List <SlackAttachment> { slackAttachment }; break; case LogLevel.Berry: slackMessage.Text = "Deploying tasty berries"; slackMessage.IconEmoji = Emoji.Cherries; slackMessage.Username = botName + "Berries"; slackAttachment = new SlackAttachment { Text = message, Color = "#F4D03F" }; slackMessage.Attachments = new List <SlackAttachment> { slackAttachment }; break; case LogLevel.Egg: slackMessage.Text = "I <3 eggs"; slackMessage.IconEmoji = Emoji.KissingSmilingEyes; slackMessage.Username = botName + "EggKeeping"; slackAttachment = new SlackAttachment { Text = message, Color = "#F4D03F" }; slackMessage.Attachments = new List <SlackAttachment> { slackAttachment }; break; case LogLevel.Debug: //Console.ForegroundColor = color == ConsoleColor.Black ? ConsoleColor.Gray : color; //Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({LoggingStrings.Debug}) {message}"); break; case LogLevel.Update: //Console.ForegroundColor = color == ConsoleColor.Black ? ConsoleColor.White : color; //Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({LoggingStrings.Update}) {message}"); break; case LogLevel.New: //Console.ForegroundColor = color == ConsoleColor.Black ? ConsoleColor.Green : color; //Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({LoggingStrings.New}) {message}"); break; case LogLevel.SoftBan: slackMessage.Text = "SOFT BAN DETECTED"; slackMessage.IconEmoji = Emoji.Confounded; slackMessage.Username = botName + "SoftBanned"; slackAttachment = new SlackAttachment { Text = message, Color = "#C0392B" }; slackMessage.Attachments = new List <SlackAttachment> { slackAttachment }; break; case LogLevel.LevelUp: slackMessage.Text = "The XP must flow"; slackMessage.IconEmoji = Emoji.Star; slackMessage.Username = botName + "LeveledUp"; slackAttachment = new SlackAttachment { Text = message, Color = "#186A3B" }; slackMessage.Attachments = new List <SlackAttachment> { slackAttachment }; break; default: //Console.ForegroundColor = color == ConsoleColor.Black ? ConsoleColor.White : color; //Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] ({LoggingStrings.Error}) {message}"); break; } var slackClient = new SlackClient(webhookURL); slackClient.Post(slackMessage); }
public SetVacationCommandHandler(VacationsApp vacationsApp, MessageSender messageSender, AppConfig appConfig) { _vacationsApp = vacationsApp; _messageSender = messageSender; _slackClient = new SlackClient(appConfig.SlackToken); }
public static Task <UserPresenceResponse> GetUserPresenceAsync(SlackClient slackClient, string userId) => slackClient.Users.GetPresenceAsync(userId);
public void Setup() { messageString = Helpers.Random; sut = new SlackClient(Helpers.RandomUri.OriginalString); _JsonPathAndValues = new Dictionary <string, string> { { "attachments[0].fallback", Helpers.Random } , { "attachments[0].color", Color.Gold.ToHex() } , { "attachments[0].pretext", Helpers.Random } , { "attachments[0].text", messageString } , { "attachments[0].author_name", Helpers.Random } , { "attachments[0].author_icon", Helpers.RandomUri.OriginalString } , { "attachments[0].author_link", Helpers.RandomUri.OriginalString } , { "attachments[0].title", Helpers.Random } , { "attachments[0].title_link", Helpers.RandomUri.OriginalString } , { "attachments[0].fields[0].title", Helpers.Random } , { "attachments[0].fields[0].value", Helpers.Random } , { "attachments[0].fields[0].short", "True" } , { "attachments[0].image_url", Helpers.RandomUri.OriginalString } , { "attachments[0].thumb_url", Helpers.RandomUri.OriginalString } , { "username", Helpers.Random } , { "text", messageString } }; _fallback = _JsonPathAndValues["attachments[0].fallback"]; _pretext = _JsonPathAndValues["attachments[0].pretext"]; _color = _JsonPathAndValues["attachments[0].color"].ToColor(); _authorIcon = new Uri(_JsonPathAndValues["attachments[0].author_icon"]); _authorName = _JsonPathAndValues["attachments[0].author_name"]; _authorLink = new Uri(_JsonPathAndValues["attachments[0].author_link"]);; _titleName = _JsonPathAndValues["attachments[0].title"]; _titleLink = new Uri(_JsonPathAndValues["attachments[0].title_link"]); _text = _JsonPathAndValues["attachments[0].text"]; _fieldTitle = _JsonPathAndValues["attachments[0].fields[0].title"]; _fieldValue = _JsonPathAndValues["attachments[0].fields[0].value"]; _fieldShort = bool.Parse(_JsonPathAndValues["attachments[0].fields[0].short"]); _thumbUrl = new Uri(_JsonPathAndValues["attachments[0].thumb_url"]); _imageUrl = new Uri(_JsonPathAndValues["attachments[0].image_url"]); _username = _JsonPathAndValues["username"]; _attachment = new SlackAttachment { Fallback = _fallback , Author = new SlackAuthor { Icon = _authorIcon, Link = _authorLink, Name = _authorName } , Color = _color , Pretext = _pretext , Title = new LinkedElement { Link = _titleLink, Name = _titleName } , Text = _text , ImageUri = _imageUrl , ThumbUri = _thumbUrl }; _attachment.AddField(_fieldTitle, _fieldValue, _fieldShort); _message = new SlackMessage { }; _message.WithMessageText(_text); _message.Attach(_attachment); _message.AsUser(_username); _json = sut.GetJson(_message); }
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(" ", " "); 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(" ", " "); innerScrapedText[x] = innerScrapedText[x].Replace("&", " "); 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 PostMessageToSlack(SlackMessage message) { SlackClient.PostMessage(message); ConnectionManager.GetHubContext <SlackHub>().Clients.All.addMessage(message.UserName, message.Text); SlackMessageStore.SaveMessage(message); }
public static async Task <UserGroupObjectResponse> UpdateUsersInUserGroupAsync(SlackClient slackClient, string channelName, string userId) { var createUserGroupResponse = await UserGroupsClientMethods.CreateUserGroupAsync(slackClient, channelName); var updateUsersInUserGroupRequest = new UpdateUsersInUserGroupRequest { UserGroupId = createUserGroupResponse.UserGroup.Id, UserIds = userId }; return(await slackClient.UserGroupsUsers.UpdateAsync(updateUsersInUserGroupRequest)); }
public void PushMessage(string myMessage) { var slackClient = new SlackClient("my api token"); slackClient.PostMessage(resp => { }, "my channel", myMessage, "my bot name"); }
public static async Task <UserGroupUserListResponse> GetUserGroupUserListAsync(SlackClient slackClient, string channelName, string userId) { var updateUsersInUserGroupResponse = await UpdateUsersInUserGroupAsync(slackClient, channelName, userId); return(await slackClient.UserGroupsUsers.ListAsync(updateUsersInUserGroupResponse.UserGroup.Id)); }
public static Task <UserProfileResponse> GetUserProfileAsync(SlackClient slackClient, string userId) => slackClient.UsersProfile.GetAsync(userId, true);
public EditDialogResponder(DatabaseRepo databaseRepo, LangResponse langResponse, SlackClient slackClient, ImageUtility imageUtility, ConfigService configService) : base(databaseRepo) { _langResponse = langResponse; _slackClient = slackClient; _imageUtility = imageUtility; _configService = configService; }
public static Task <UserResponse> GetUserInfoAsync(SlackClient slackClient, string userId) => slackClient.Users.InfoAsync(userId);
public HealthController(DatabaseRepo databaseRepo, ILogger <HealthController> logger, SlackClient slackClient) { _databaseRepo = databaseRepo; _logger = logger; _slackClient = slackClient; }