public bool Execute(SlackBotCommand command) { try { string name = string.IsNullOrWhiteSpace(command.Text) ? "The Great Ranzuoni" : command.Text; HttpWebRequest request = (HttpWebRequest) WebRequest.Create("http://api.icndb.com/jokes/random"); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string json = reader.ReadToEnd(); response.Dispose(); JObject joResponse = JObject.Parse(json); if (joResponse["value"] != null) { string joke = joResponse["value"]["joke"].ToString(); joke = joke.Replace("Chuck Norris", name); slackBot.Reply(command, HttpUtility.HtmlDecode(joke)); } else { slackBot.Reply(command, "Crap. I forgot to handle that case."); } return(false); } catch (Exception) { slackBot.Reply(command, "Stop trying to break slackbot"); return(false); } }
public bool Execute(SlackBotCommand command) { string userToCheck; if (string.IsNullOrWhiteSpace(command.Text)) { userToCheck = command.User.name; } else { userToCheck = command.Text; } PrivilegeLevel privilege = slackBot.GetUserPrivilege(userToCheck); string response; switch (privilege) { case PrivilegeLevel.Super: response = "Your privelege level is Super, that makes you in the 1% of privilege levels"; break; case PrivilegeLevel.Admin: response = "You got some privilege but not a lot. You're an admin which is kind of like the guy in the factory that watches the other guys work." + "On the one hand you're not the lowest level, but you're still in the factory son."; break; case PrivilegeLevel.Normal: default: response = "You're just a regular joe, p'ting. But not like our Joe because he's actually kind of a big deal."; break; } slackBot.Reply(command, response); return(false); }
public bool Execute(SlackBotCommand command) { string size = string.Empty; int sizeInt = 0; try { if (!int.TryParse(command.Text, out sizeInt)) { slackBot.Reply(command, "You disappoint your family"); return(false); } if (sizeInt > 33) { slackBot.Reply(command, "The count is too high. Heck now its " + sizeInt * 9000 + "/9000"); return(false); } slackBot.Reply(command, printGlass(sizeInt)); } catch (Exception) { slackBot.Reply(command, "You done gone broke the Nexus"); return(false); } return(false); }
private bool Initialize(SlackBotCommand command) { m_Players = new string[2]; m_Moves = new Dictionary <string, string>(); m_Players[0] = command.User.id; string opponentId; if (command.Text.StartsWith("<@") && command.Text.EndsWith(">")) { opponentId = command.Text.Substring(2, command.Text.Length - 3); if (Array.Find(command.Channel.members, userId => opponentId == userId) == null) { return(false); } } else { opponentId = Array.Find(command.Channel.members, userId => slackBot.GetUser(userId) != null && slackBot.GetUser(userId).name == command.Text); if (opponentId == null) { return(false); } } m_Players[1] = opponentId; m_FalseStartCount = new Dictionary <string, int>() { { m_Players[0], 0 }, { m_Players[1], 0 } }; return(true); }
private bool WaitForTimePeriod(double totalTimeToWait, SlackBotCommand command) { _message = null; foreach (double displayTime in DISPLAY_TIMES) { if (totalTimeToWait <= displayTime && totalTimeToWait > (displayTime - SECOND_IN_MILLISECONDS)) { _message = FormatTimeRemaining(totalTimeToWait); } } if (_message != null) { slackBot.Reply(command, _message); } lock (purposes) purposes[_purpose] = totalTimeToWait - SECOND_IN_MILLISECONDS; Thread.Sleep((int)SECOND_IN_MILLISECONDS); if (totalTimeToWait <= 0) { lock (purposes) purposes.Remove(_purpose); return(false); } return(true); }
public bool Execute(SlackBotCommand command) { if (!(command.Channel.name == "the-bureau-of-anarchy" || command.Channel.name == "slackbot-test" || command.Channel.name == "the-anarchy")) { return(true); } return((command.Name == "featureList" || command.Name == "fl") ? ReadFeatures(command) : WriteFeature(command)); }
private void ReplyMessages(object parameters) { Parameter parameter = (Parameter)parameters; SlackBotCommand command = parameter.command; for (int i = 0; i < parameter.messages.Count; i++) { slackBot.Reply(command, parameter.messages[i]); Thread.Sleep(300); } }
private void Run(SlackBotCommand command) { m_Moves.Clear(); foreach (string shout in new string[] { "Rock!", "Paper!", "Scissors!", "Shoot!" }) { System.Threading.Thread.Sleep(1000); slackBot.Reply(command, shout); } m_ShootTime = DateTime.Now; }
public bool Execute(SlackBotCommand command) { Random random = new Random(); int die1 = random.Next(6) + 1; int die2 = random.Next(6) + 1; int roll = die1 + die2; slackBot.Reply(command, string.Format("{0} rolled a {1}", command.User.name, roll), iconUrl: "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c4/2-Dice-Icon.svg/2000px-2-Dice-Icon.svg.png"); return(false); }
public bool Execute(SlackBotCommand command) { if (string.IsNullOrWhiteSpace(command.Text)) { slackBot.Reply(command, "You did not specify a new name"); } else { slackBot.RenameBot(command.Text); } return(false); }
public bool Execute(SlackBotCommand command) { try { slackBot.Reply(command, "This feature is temporarily out of order."); //System.Diagnostics.Process.Start(@"C:\Users\plafata\Documents\SlackbotProd\reboot.bat"); } catch (Exception) { slackBot.Reply(command, "Something went wrong restarting the bot"); } return(false); }
public bool Execute(SlackBotCommand command) { Random random = new Random(); int slicesX = random.Next(5) + 1; int slicesY = random.Next(5) + 1; int slicesZ = random.Next(5) + 1; int pieces = slicesX * slicesY * slicesZ; slackBot.Reply(command, string.Format("{0} diced the rolls into {1} pieces", command.User.name, pieces), iconUrl: "https://upload.wikimedia.org/wikipedia/commons/2/28/13-08-31-wien-redaktionstreffen-EuT-by-Bi-frie-134.jpg"); return(false); }
private void RunProcess(object parameters) { SlackBotCommand command = ((Parameter)parameters).command; bool keepGoing = true; while (keepGoing) { double time; lock (purposes) time = purposes[_purpose]; keepGoing = WaitForTimePeriod(time, command); } slackBot.Reply(command, ":shark: TIME'S UP :shark:\n" + _purpose.ToUpper() + "!!!!!"); }
public bool Execute(SlackBotCommand command) { string output = ""; foreach (string part in command.Text.Split(' ')) { string searchTerm = part.NormalizeSpace(); if (searchTerm.Length >= 3 && searchTerm.Length <= 15) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Format("http://acronym-maker.com/generate/?w={0}&wl=", System.Uri.EscapeDataString(searchTerm))); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string xml = reader.ReadToEnd(); response.Dispose(); XmlDocument doc = new XmlDocument(); if (request.Address.ToString().Contains("index.php")) { slackBot.Reply(command, "You dun sumthin real bad with them thar characters..."); return(true); } doc.LoadXml(xml.Substring(xml.IndexOf("<table"), xml.IndexOf("</table>") - xml.IndexOf("<table")) + "</table>"); XmlNode documentNode = doc.DocumentElement; try { foreach (XmlNode acronymRow in documentNode.SelectNodes("//*[local-name() = 'table']//*[local-name()='tr']")) { output += acronymRow.SelectSingleNode(".//*[local-name()='th']").InnerText.Trim() + ": " + acronymRow.SelectSingleNode(".//*[local-name()='a' or local-name()='td']").InnerText.Trim() + "\n"; } } catch (Exception e) { slackBot.Reply(command, e.Message); return(true); } output += "\n"; } else { slackBot.Reply(command, String.Format("The word has to be 3-15 characters. Violator: \"{0}\"", searchTerm)); return(true); } } slackBot.Reply(command, output); return(false); }
public bool Execute(SlackBotCommand command) { bool initializeFailed = Initialize(command); slackBot.Reply(command, _message); if (initializeFailed) { return(true); } Thread processThread = new Thread(new ParameterizedThreadStart(RunProcess)); processThread.Start(new Parameter(command)); return(false); }
public bool Execute(SlackBotCommand command) { if (string.IsNullOrWhiteSpace(command.Text)) { string response = ""; foreach (string commandName in slackBot.GetCommandNames().OrderBy(x => x)) { response += commandName + ": "; response += slackBot.GetHelp(commandName) + "\n"; } slackBot.Reply(command, response); } else { slackBot.Reply(command, slackBot.GetHelp(command.Text)); } return(true); }
private bool WriteFeature(SlackBotCommand command) { Random random = new Random(); int responseNum = random.Next(ResponseStrings.Length); try { using (StreamWriter sw = File.AppendText(GetRelFilePath(RequestListFileName))) { sw.WriteLine(DateTime.Now + "," + command.User.name + "," + command.Text); } } catch (Exception) { slackBot.Reply(command, "Whoops, someone did something with the feature list file :("); return(true); } slackBot.Reply(command, String.Format(ResponseStrings[responseNum], command.Text)); return(false); }
public bool Execute(SlackBotCommand command) { User userToMock; if (string.IsNullOrWhiteSpace(command.Text)) { userToMock = command.User; } else { string userId = command.Text; userToMock = slackBot.GetUsers().Find(user => user.name == userId); if (userToMock == null) { userToMock = slackBot.GetUsers().Find(user => user.profile.real_name == userId); } if (userToMock == null) { userId = userId.Replace("\"", ""); userId = "\"" + userId + "\""; slackBot.Reply(command, string.Format("Sorry {0}, I cannot find user {1}", command.User.name, userId)); return(false);; } } string userName; if (!string.IsNullOrWhiteSpace(userToMock.profile.real_name)) { userName = userToMock.profile.real_name; } else { userName = userToMock.name; } slackBot.Reply(command, string.Format("I'm {0} and I'm dumb", userName), userName, userToMock.profile.image_32); return(false); }
private string GetUsername(SlackBotCommand command, string name) { string opponentId; if (name.StartsWith("<@") && name.EndsWith(">")) { opponentId = name.Substring(2, name.Length - 3); if (Array.Find(command.Channel.members, userId => opponentId == userId) == null) { return(null); } } else { opponentId = Array.Find(command.Channel.members, userId => slackBot.GetUser(userId) != null && slackBot.GetUser(userId).name == name); if (opponentId == null) { return(null); } } return(slackBot.GetUser(opponentId).name); }
public bool Execute(SlackBotCommand command) { try { string city = String.IsNullOrWhiteSpace(command.Text) ? "Conshohocken" : command.Text; HttpWebRequest request = (HttpWebRequest) WebRequest.Create( String.Format("http://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=bd82977b86bf27fb59a04b61b657fb6f")); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string json = reader.ReadToEnd(); response.Dispose(); JObject joResponse = JObject.Parse(json); if (joResponse["main"] != null) { string kelvinTemp = joResponse["main"]["temp"].ToString(); string farentheitTemp = ((Double.Parse(kelvinTemp) - 273) * 9 / 5 + 32).ToString(); city = joResponse["name"].ToString(); string emoji; switch (((int)Double.Parse(farentheitTemp)) / 10) { case 0: case 1: case 2: case 3: emoji = ":snowman:"; break; case 4: case 5: case 6: emoji = ":partly_sunny:"; break; case 7: case 8: case 9: emoji = ":sunny:"; break; default: emoji = ":skull:"; break; } slackBot.Reply(command, city + " : " + farentheitTemp + "F " + emoji); } else { slackBot.Reply(command, "Are you some kind of stupid? " + city + " is not a city..."); } return(false); } catch (Exception) { slackBot.Reply(command, "Stop trying to break slackbot"); return(false); } }
public bool Execute(SlackBotCommand command) { slackBot.Reply(command, "http://www.sadtrombone.com/"); return(false); }
private bool Initialize(SlackBotCommand command) { string[] waitTimeAndPurpose = command.Text.Split(' '); string waitTime = waitTimeAndPurpose[0]; string purpose = ""; for (int i = 1; i < waitTimeAndPurpose.Length; i++) { purpose += " " + waitTimeAndPurpose[i]; } bool goodFormat; double timeInMinutes = 0; if (waitTime.Contains(":")) { string[] timeComponents = waitTime.Split(':'); if (timeComponents.Length != 3) { goodFormat = false; } else { int hours, minutes, seconds; goodFormat = true; goodFormat &= int.TryParse(timeComponents[0], out hours); goodFormat &= int.TryParse(timeComponents[1], out minutes) && minutes < 60; goodFormat &= int.TryParse(timeComponents[2], out seconds) && seconds < 60; if (goodFormat) { timeInMinutes = ((double)(hours * 3600 + minutes * 60 + seconds)) / 60; } } } else { goodFormat = double.TryParse(waitTime, out timeInMinutes); } if (!goodFormat) { _message = "Failed to parse countdown time :( pls don't do bad format"; return(true); } DateTime startTime = DateTime.Now, endTime = startTime.AddMinutes(timeInMinutes); if (endTime.Hour > 18 || startTime.Day != endTime.Day || startTime.Month != endTime.Month || startTime.Year != endTime.Year || timeInMinutes <= 0) { _message = "Ain't nobody got time for that!"; return(true); } lock (purposes) { if (purposes.ContainsKey(purpose)) { this._purpose = purpose; _message = "Already waiting for" + purpose + "!\n" + FormatTimeRemaining(purposes[purpose]); return(true); } else { this._purpose = purpose; purposes.Add(purpose, Math.Floor(timeInMinutes * MINUTE_IN_MILLISECONDS)); _message = FormatTimeRemaining(purposes[purpose]); return(false); } } }
public Parameter(SlackBotCommand comm) { command = comm; }
public bool Execute(SlackBotCommand command) { slackBot.Reply(command, "http://www.urbandictionary.com/define.php?term=" + System.Uri.EscapeDataString(command.Text)); return(false); }
public bool Execute(SlackBotCommand command) { if (!(command.Channel.name == "the-bureau-of-anarchy" || command.Channel.name == "slackbot-test" || command.Channel.name == "the-anarchy")) { return(false); } string[] commandSplit = command.Text.Split(' '); string username = ""; if (commandSplit.Length >= 1 && !String.IsNullOrEmpty(commandSplit[0])) { username = GetUsername(command, commandSplit[0]); if (username == null) { slackBot.Reply(command, String.Format("You messed up, {0}. You get a bad job.", command.User.name)); if (!JobMatrix.ContainsKey(command.User.name)) { JobMatrix.Add(command.User.name, new[] { 0, 0 }); } JobMatrix[command.User.name][BadJobIndex]++; WriteJobMatrix(GetRelFilePath(JobMatrixFileName)); return(false); } } if (command.Name == "checkjobs") { Random ran = new Random(); string userToLookup = string.IsNullOrWhiteSpace(username) ? command.User.name : username; if (JobMatrix.ContainsKey(userToLookup)) { slackBot.Reply(command, String.Format("{2}\nGood jobs: {0}\nBad jobs:{1}\n{3}", FormatJobs(JobMatrix[userToLookup][GoodJobIndex], GoodJobIndex), FormatJobs(JobMatrix[userToLookup][BadJobIndex], BadJobIndex), userToLookup, Responses[ran.Next(Responses.Length)])); } else { slackBot.Reply(command, "No jobs yet, get working!"); } return(false); } if (!JobMatrix.ContainsKey(username)) { JobMatrix.Add(username, new[] { 0, 0 }); } bool goodJob; if (command.Name == "goodjob" || command.Name == "gj") { JobMatrix[username][GoodJobIndex]++; goodJob = true; } else { JobMatrix[username][BadJobIndex]++; goodJob = false; } if (!JobMatrix.ContainsKey(command.User.name)) { JobMatrix.Add(command.User.name, new[] { 0, 0 }); } JobMatrix[command.User.name][GoodJobIndex]++; WriteJobMatrix(GetRelFilePath(JobMatrixFileName)); slackBot.Reply(command, String.Format("You've given a {0} to {1} for {2}. Good job on giving out jobs.", goodJob ? "good job" : "bad job", username, GetJobDescription(commandSplit))); return(false); }
public bool Execute(SlackBotCommand command) { if (command.Name == "rps") { if (m_Players != null) { return(true); } if (!Initialize(command)) { slackBot.Reply(command, "Sorry, could not find user " + command.Text); return(false); } Run(command); return(true); } else { if (m_Players == null) { slackBot.Reply(command, "There is no game going on currently."); return(false); } if (!new HashSet <string> { "rock", "paper", "scissors" }.Contains(command.Name)) { slackBot.Reply(command, command.Text + " is not a valid move"); return(true); } if (!new HashSet <string>(m_Players).Contains(command.User.id)) { return(true); } if (command.Timestamp < m_ShootTime.AddSeconds(-3)) //If the command was sent more than three seconds before the shoot time then { return(true); //it most likely was meant for the previous round. Just ignore it } bool earlyStart = command.Timestamp < m_ShootTime; bool lateStart = command.Timestamp > m_ShootTime.AddMilliseconds(800); bool falseStart = earlyStart || lateStart; if (falseStart) { m_FalseStartCount[command.User.id]++; System.Threading.Thread.Sleep(1000); if (m_FalseStartCount[command.User.id] >= 3) { if (earlyStart) { slackBot.Reply(command, command.User.name + " went too early and is disqualified"); } else { slackBot.Reply(command, command.User.name + " went too late and is disqualified"); } return(false); } else { if (earlyStart) { slackBot.Reply(command, command.User.name + " went too early. Trying again."); } else { slackBot.Reply(command, command.User.name + " went too late. Trying again."); } Run(command); return(true); } } m_Moves[command.User.id] = command.Name; if (m_Moves.Count == 2) { if (m_Moves[m_Players[0]] == m_Moves[m_Players[1]]) { Run(command); return(true); } int winner = 0; if (m_ObjectBeats[m_Moves[m_Players[0]]] == m_Moves[m_Players[1]]) { winner = 0; } else { winner = 1; } slackBot.Reply(command, m_Moves[m_Players[winner]] + " beats " + m_Moves[m_Players[(winner + 1) % 2]] + ". " + slackBot.GetUser(m_Players[winner]).name + " is the winner."); return(false); } return(true); } }
public bool Execute(SlackBotCommand command) { slackBot.Reply(command, "http://lmgtfy.com/?q=" + System.Uri.EscapeDataString(command.Text)); return(false); }
public bool Execute(SlackBotCommand command) { string commandText = command.Text; if (string.IsNullOrWhiteSpace(commandText)) { slackBot.Reply(command, "Please supply some text to emojify."); } string[] commandSplit = commandText.Split(' '); Regex emojiRegex = new Regex(":.+:"); int startOutput = 0; string emojiFront = ":filled:"; string emojiBack = ":blank:"; if (emojiRegex.IsMatch(commandSplit[0])) { emojiFront = commandSplit[0]; startOutput++; } if (commandSplit.Length > 1 && emojiRegex.IsMatch(commandSplit[1])) { emojiBack = commandSplit[1]; startOutput++; } List <string> messages = new List <string>(); for (int wordIndex = startOutput; wordIndex < commandSplit.Length; wordIndex++) { char[] letters = commandSplit[wordIndex].ToLower().ToCharArray(); StringBuilder output = new StringBuilder(); for (int i = 0; i < 8; i++) { for (int j = 0; j < letters.Length; j++) { if (letters[j] == '\n') { output.AppendLine(); } else { if (LetterMap.ContainsKey(letters[j])) { output.Append(String.Format(LetterMap[letters[j]][i], emojiBack, emojiFront)); } else { output.Append(letters[j] + emojiBack); } if (j + 1 < letters.Length) { output.Append(emojiBack); } } if (output.Length > 4000) { slackBot.Reply(command, "Message has word that is too large: " + commandSplit[wordIndex]); return(true); } } output.AppendLine(); } messages.Add(output.ToString()); } Thread processThread = new Thread(ReplyMessages); processThread.Start(new Parameter(command, messages)); return(false); }
public Parameter(SlackBotCommand command, List <string> messages) { this.command = command; this.messages = messages; }
private bool ReadFeatures(SlackBotCommand command) { int noOfLines = 0; bool returnStatus = false; string newline = "\n"; //Environment.NewLine;?? int charSize = encoding.IsSingleByte ? 1 : 2; byte[] buffer = null; bool printed = false; string temp = string.Empty; FileStream stream = null; try { stream = new FileStream(GetRelFilePath(RequestListFileName), FileMode.Open, FileAccess.Read, FileShare.Write); long endPos = stream.Length / charSize, oldPos = 0; long posLength; printed = false; noOfLines = 0; buffer = new byte[charSize]; endPos = stream.Length / charSize; if (endPos <= oldPos) { oldPos = endPos; // if file's content is } //deleted, reset position posLength = endPos - oldPos; for (long pos = charSize; pos <= posLength; pos += charSize) { stream.Seek(-pos, SeekOrigin.End); stream.Read(buffer, 0, charSize); temp = encoding.GetString(buffer); if (temp == newline) { noOfLines++; } if (noOfLines == 11) { buffer = new byte[endPos - stream.Position]; stream.Read(buffer, 0, buffer.Length); slackBot.Reply(command, FormatRequestList(encoding.GetString(buffer))); printed = true; oldPos = endPos; break; } } if (!printed) { buffer = new byte[endPos - oldPos]; stream.Seek(-1, SeekOrigin.Current); stream.Read(buffer, 0, buffer.Length); slackBot.Reply(command, FormatRequestList(encoding.GetString(buffer))); oldPos = endPos; } } catch (Exception) { slackBot.Reply(command, "Whoops, someone did something with the feature list file :("); returnStatus = true; } finally { if (stream != null) { stream.Close(); } } return(returnStatus); }