public override void HandleRequest(Request request) { if (request.RequestFrom.AccessLevel >= AccessLevel.Public) { Match expressionMatch = _youtubeRegex.Match(request.Message); if (expressionMatch.Success) { string videoId = expressionMatch.Groups[1].Value; VideoResponse videoResponse = YouTubeService.GetVideo(new VideoRequest() {VideoId = videoId}); if(videoResponse.Video != null) { Response response = request.CreateResponse(ResponseType.Public, videoResponse.Video.Title + " (Views: " + videoResponse.Video.ViewCount.ToString("#,##0") + ")"); ModuleManagementContainer.HandleResponse(response); } else { Response response = request.CreateResponse(ResponseType.Public, "I had a problem fetching the title of that youtube video, sorry dude."); ModuleManagementContainer.HandleResponse(response); } } } }
public override void HandleRequest(Request request) { var messageArray = request.Message.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (request.RequestSourceType == RequestSourceType.Private && request.RequestFrom.AccessLevel >= AccessLevel.Root && messageArray[0].Equals("~puppet", StringComparison.OrdinalIgnoreCase) && messageArray.Length >= 4) { var target = messageArray[2].Trim(); var message = string.Empty; for (var i = 3; i < messageArray.Length; i++) { message += messageArray[i]; message += " "; } if (messageArray[1].Equals("say", StringComparison.OrdinalIgnoreCase)) { var response = request.CreateResponse(ResponseTargetType.Public, ResponseType.Message, false, message); response.Channel = target; ModuleManagementContainer.HandleResponse(response); } else if (messageArray[1].Equals("do", StringComparison.OrdinalIgnoreCase)) { var response = request.CreateResponse(ResponseTargetType.Public, ResponseType.Action, false, message); response.Channel = target; ModuleManagementContainer.HandleResponse(response); } } }
public override void HandleRequest(Request request) { if (request.Message.StartsWith("~geoip") && request.RequestFrom.AccessLevel >= AccessLevel.Public) { Match expressionMatch = GeoIpRegex.Match(request.Message); if (expressionMatch.Success) { try { ExecuteSearch(expressionMatch.Groups[1].Value, request); } catch (Exception ex) { ModuleManagementContainer.HandleResponse(request.CreateResponse(ResponseType.Public, "{0}, The service is currently b00rked, please try again in a few minutes.", request.Nick)); Logger.WarnFormat("Search threw an exception. Nick: {0}, terms: \"{1}\", stack message: {2}", request.Nick, expressionMatch.Groups[1].Value, ex.StackTrace); } } else { // If the message format isn't correct, notify the user. ModuleManagementContainer.HandleResponse(request.CreateResponse(ResponseType.Public, String.Format("{0}, invalid geoip syntax, please try again.", request.Nick))); } } }
public override void HandleRequest(Request request) { if (request.RequestFrom.AccessLevel >= AccessLevel.Public && request.Message.StartsWith("~AccessToken", StringComparison.OrdinalIgnoreCase)) { var splitMessage = request.Message.Split(' '); // We've got an operation. if (splitMessage.Length > 1) { // TODO [Kog 07/23/2011] : We need to fix looking up who requested the token. This mechanism is pretty bad. // Look up the user who sent the message. var userToken = AuthenticationManager.ExchangeTokenForConcreteType<IrcUserToken>(request.RequestFrom.User); var user = AuthenticationManager.FindHostByCloak(userToken.HostMask); // Handle a user requesting a new access token. if (splitMessage[1].Equals("request", StringComparison.InvariantCultureIgnoreCase)) { // Try and pull the TTL for the token out of the args. var timeToLive = 1; if (splitMessage.Length > 2) { int.TryParse(splitMessage[2], out timeToLive); } var accessTokenExpiration = timeToLive == 0 ? DateTime.MaxValue : DateTime.Now.ToUniversalTime().AddDays(timeToLive); // Generate a new GUID. var accessToken = Guid.NewGuid(); var accessTokenCreationTime = DateTime.Now.ToUniversalTime(); // Slap it on the user's account. user.AccessToken = accessToken.ToString(); user.AccessTokenIssueTime = accessTokenCreationTime; user.AccessTokenExpiration = accessTokenExpiration; // Update the account. AuthenticationManager.UpdateHost(user); // Hand it back. Reply(request, ResponseTargetType.Private, "Your new access token is {0}.", accessToken); } // Handle a user asking for their current access token. if (splitMessage[1].Equals("display", StringComparison.InvariantCultureIgnoreCase)) { ModuleManagementContainer.HandleResponse(request.CreateResponse(ResponseTargetType.Private, user.AccessToken == null ? "You have no access token. Please request one." : String.Format("Your access token is {0} and was generated at {1} UTC. The token will expire at {2} UTC.", user.AccessToken, user.AccessTokenIssueTime, user.AccessTokenExpiration))); } } else { // The user used the command incorrectly. Reply(request, ResponseTargetType.Private, "Invalid access token request, please consult the help for details."); } } }
public override void HandleRequest(Request request) { if (request.RequestFrom.AccessLevel >= AccessLevel.Public && request.Message.StartsWith("~email", StringComparison.OrdinalIgnoreCase)) { var splitMessage = request.Message.Split(' '); // We've got an operation. if (splitMessage.Length > 1) { // Look up the user who sent the message. var userToken = AuthenticationManager.ExchangeTokenForConcreteType<IrcUserToken>(request.RequestFrom.User); var user = AuthenticationManager.FindHostByCloak(userToken.HostMask); // Handle the case when the user wants to set their email. if (splitMessage[1].Equals("set", StringComparison.InvariantCultureIgnoreCase)) { // Make sure the user has given us an email. if (splitMessage.Length > 2) { var email = splitMessage[2]; try { user.EmailAddress = email; AuthenticationManager.UpdateHost(user); Reply(request, ResponseTargetType.Private, "Your email has been set to {0}", email); } catch (Exception ex) { // Ruh roh, they've violated our unique constraint. Logger.Warn("Caught an exception trying to set someone's email.", ex); Reply(request, ResponseTargetType.Private, "Email {0} is already in use.", email); } } else { // User hasn't given us an email, barf. Reply(request, ResponseTargetType.Private, "No email specified, cannot set email address."); } } // Handle the case when the user wants to check their email. if (splitMessage[1].Equals("display", StringComparison.InvariantCultureIgnoreCase)) { ModuleManagementContainer.HandleResponse(request.CreateResponse(ResponseTargetType.Private, String.IsNullOrEmpty(user.EmailAddress) ? "You have no email address set." : String.Format("Your currently set email is {0}.", user.EmailAddress))); } } else { // User has given us an invalid request, barf. Reply(request, ResponseTargetType.Private, "Invalid request, please read the help for email."); } } }
/// <summary> /// Handles responding to a user IFF they have proper access, and the trigger is ~name. /// </summary> /// /// <param name="request">A <see cref="Request"/> representing a message sent to the bot.</param> public override void HandleRequest(Request request) { string[] messageArray = request.Message.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (request.RequestFrom.AccessLevel >= AccessLevel.Public && request.RequestType == RequestType.Public && messageArray[0].Equals("~"+Name, StringComparison.OrdinalIgnoreCase)) { ModuleManagementContainer.HandleResponse(request.CreateResponse(ResponseType.Public, Phrase)); } }
public override void HandleRequest(Request request) { if (request.RequestFrom.AccessLevel >= AccessLevel.Public) { Match expressionMatch = _urbanRegex.Match(request.Message); if (expressionMatch.Success) { bool urlRequested = expressionMatch.Groups[1].Value.Equals("nu", StringComparison.InvariantCultureIgnoreCase); string term = expressionMatch.Groups[2].Value; UrbanResponse urbanResponse = UrbanService.Search(new UrbanRequest() {Term = term}); if(urbanResponse != null) { if(urbanResponse.Definition.HasValue()) { Response response = request.CreateResponse(ResponseType.Public, "Definition: " + urbanResponse.Definition.Replace('\r', ' ').Replace('\n', ' ')); ModuleManagementContainer.HandleResponse(response); } if(urbanResponse.Example.HasValue()) { Response response = request.CreateResponse(ResponseType.Public, "Example: " + urbanResponse.Example.Replace('\r', ' ').Replace('\n', ' ')); ModuleManagementContainer.HandleResponse(response); } if (urlRequested && urbanResponse.Url.HasValue()) { Response response = request.CreateResponse(ResponseType.Public, "Url: " + urbanResponse.Url); ModuleManagementContainer.HandleResponse(response); } } else { Response response = request.CreateResponse(ResponseType.Public, "I couldn't find anything with the term '" + term + "', sorry dude."); ModuleManagementContainer.HandleResponse(response); } } } }
/// <summary> /// Sends a help response for a given module. /// </summary> /// /// <param name="module">The module to send information about.</param> /// <param name="request">The incoming message to respond to.</param> private void SendHelpResponses(IModule module, Request request) { Response response = request.CreateResponse(ResponseType.Private); response.Message = "Module Name: " + module.Name; ModuleManagementContainer.HandleResponse(response); response.Message = "Module Description: " + module.Description; ModuleManagementContainer.HandleResponse(response); response.Message = "Module Instructions: " + module.Instructions; ModuleManagementContainer.HandleResponse(response); }
/// <summary> /// See if we want to digest this message, and if so take action. /// </summary> /// /// <param name="request">A message</param> public override void HandleRequest(Request request) { if (request.RequestFrom.AccessLevel >= AccessLevel.Public) { var expressionMatch = _karmaRegex.Match(request.Message); if (expressionMatch.Success) { var nick = expressionMatch.Groups[1].Value; var op = expressionMatch.Groups[2].Value; Response response; // Make sure the sender isn't messing with their own karma. if (nick.Equals(request.Nick, StringComparison.OrdinalIgnoreCase) && !String.IsNullOrEmpty(op)) { response = request.CreateResponse(ResponseTargetType.Public, string.Format("{0}, toggling your own karma is very uncool.", request.Nick)); ModuleManagementContainer.HandleResponse(response); } else { // Attempt to look the user up. var karma = KarmaDao.FindKarma(nick.ToLower()) ?? new KarmaItem {KarmaLevel = 0, UserName = nick.ToLower()}; // If they're doing anything more than looking... if (!String.IsNullOrEmpty(op)) { if (op.Equals("--")) { karma.KarmaLevel--; } else if (op.Equals("++")) { karma.KarmaLevel++; } KarmaDao.SaveKarma(karma); } response = request.CreateResponse(ResponseTargetType.Public, String.Format("{0} has a karma of {1}", nick, karma.KarmaLevel)); ModuleManagementContainer.HandleResponse(response); } } } }
private void SendResponse(Request request) { string message = string.Format("{0} (V{1}) is the ##csharp irc bot on freenode.net", NetworkConnectionInformation.BotNickname, Assembly.GetEntryAssembly().GetName().Version.ToString(2)); Response response = request.CreateResponse(ResponseType.Private, message); ModuleManagementContainer.HandleResponse(response); response.Message = "===================================="; ModuleManagementContainer.HandleResponse(response); response.Message = "IRC: To get help with the bot type '~Help' in private message with the bot."; ModuleManagementContainer.HandleResponse(response); response.Message = "Wiki: http://wiki.freenode-csharp.net/wiki/"; ModuleManagementContainer.HandleResponse(response); response.Message = "===================================="; ModuleManagementContainer.HandleResponse(response); response.Message = "But there's no sense crying over every mistake. You just keep on trying till you run out of cake."; ModuleManagementContainer.HandleResponse(response); }
private void SendResponse(Request request) { var message = string.Format("{0} (V{1}) is the ##csharp irc bot on freenode.net", NetworkConnectionInformation.BotNickname, Assembly.GetEntryAssembly().GetName().Version.ToString(2)); var response = request.CreateResponse(ResponseTargetType.Private, message); ModuleManagementContainer.HandleResponse(response); response.Message = "===================================="; ModuleManagementContainer.HandleResponse(response); response.Message = "IRC: To get help with the bot type '~Help' in private message with the bot."; ModuleManagementContainer.HandleResponse(response); response.Message = "Wiki: http://wiki.freenode-csharp.net/wiki/"; ModuleManagementContainer.HandleResponse(response); response.Message = "===================================="; ModuleManagementContainer.HandleResponse(response); response.Message = "But there's no sense crying over every mistake. You just keep on trying till you run out of cake."; ModuleManagementContainer.HandleResponse(response); response.Message = "Go make some new disaster. That's what I'm counting on. You're someone else's problem. Now I only want you gone."; ModuleManagementContainer.HandleResponse(response); }
public override void HandleRequest(Request request) { if (request.RequestFrom.AccessLevel >= AccessLevel.Public) { Match expressionMatch = _weatherRegex.Match(request.Message); if (expressionMatch.Success) { string command = expressionMatch.Groups[1].Value; string location = expressionMatch.Groups[2].Value; WeatherResponse weatherResponse = WeatherProvider.WeatherRequest(new WeatherRequest() {Command = command, Location = location}); foreach (var message in weatherResponse.Response) { Response response = request.CreateResponse(ResponseType.Public, message); ModuleManagementContainer.HandleResponse(response); } } } }
/// <summary> /// Attempts to add the given hostmask, if it doesn't already exist. /// </summary> /// /// <param name="hostmask">The hostmask to add.</param> /// <param name="level">The level to add: either <code>ADMIN</code> or <code>PUBLIC</code>. </param> /// <param name="request">Our incoming <see cref="Request"/> object, which we use for creating our response.</param> /// /// <remarks> /// At present we only add <see cref="HostMatchType.Start"/> type users, and if a proper level is not specified, it is assumed that the user wants /// a <see cref="AccessLevel.Public"/>. There is also currently no way to add a <see cref="AccessLevel.Root"/> user, which is by design. /// </remarks> private void AddUser(string hostmask, string level, Request request) { if (AuthenticationManager.KnowsHost(hostmask)) { SendResponse(String.Format("The hostmask {0} already has an entry.", hostmask), request); } else { var host = new KnownHost { AccessLevel = GetAccessLevelByName(level), HostMask = hostmask, HostMatchType = HostMatchType.Start, }; AuthenticationManager.RememberHost(host); ModuleManagementContainer.HandleResponse(request.CreateResponse(ResponseType.Private, String.Format("Learned host {0}", TranslateHostToString(host)))); } }
/// <summary> /// Tell the user their help request was phrased in an invalid manner. /// </summary> /// /// <param name="request">The incoming message to respond to.</param> private void SendIncorrectRequestSyntaxResponse(Request request) { Response response = request.CreateResponse(ResponseType.Private); response.Message = "Request was not in the correct syntax."; ModuleManagementContainer.HandleResponse(response); }
public override void HandleRequest(Request request) { // Make sure they have access and the message is meant for us. if (request.RequestFrom.AccessLevel >= AccessLevel.Public && request.Message.StartsWith(Trigger, true, CultureInfo.InvariantCulture)) { // Parse what they sent us, make sure it's valid. var expressionMatch = _regex.Match(request.Message); // If they just passed us one atom (ie ~warn) - we won't even match. We'll just fall through to the next block. if (expressionMatch.Success) { var command = expressionMatch.Groups[1].Value.Substring(1); var name = expressionMatch.Groups[2].Value; var normalizedName = name.ToUpperInvariant(); var description = expressionMatch.Groups[3].Value; // OK, so we know we've at least got a person. Let's look them up. var target = PersonDao.CreateOrFindPerson(normalizedName); var response = request.CreateResponse(ResponseTargetType.Public, String.Format("No factoids of type {0} found for {1}.", command, name)); // If we've got a description, they're added to said person. if (description.Length > 0) { var factoid = new PersonFactoid { Description = description, CreationDate = DateTime.UtcNow, Person = target, Type = command, CreatedBy = request.Nick }; target.Factoids.Add(factoid); PersonDao.SaveFactoids(target); response = request.CreateResponse(ResponseTargetType.Public, "Factoid saved."); } else { const int maxFactCount = 5; var matchingFacts = target.Factoids.Where(x => x.Type.Equals(command, StringComparison.InvariantCultureIgnoreCase)); var factCount = matchingFacts.Count(); if (factCount > 0) { response = request.CreateResponse(ResponseTargetType.Public, String.Format("Found {0} factoid{1} of type {2} for {3}{4}: {5}", factCount, (factCount == 1) ? String.Empty : "s", command, name, (factCount > maxFactCount) ? String.Format(" (showing the first {0})", Math.Min(factCount, maxFactCount)) : string.Empty, matchingFacts.Reverse() .Take(maxFactCount) .Select(x => String.Format("[{0} at {1} by {2}]", x.Description, x.CreationDate.ToString("MM/dd/yyyy H:mm:ss UTC"), x.CreatedBy)) .Implode(", "))); } } ModuleManagementContainer.HandleResponse(response); } else { var response = request.CreateResponse(ResponseTargetType.Public, string.Format("Invalid request, please try ~help {0}", Name)); ModuleManagementContainer.HandleResponse(response); } } }
private void HandleResults(IEnumerable<string> results, Request request, string searchTerms) { // Not every search provider returns us our query strings, so do a quick token substitution for the services that don't. foreach (string result in results) { string resultWithQuery = result.Replace("%query%", searchTerms.Trim()); ModuleManagementContainer.HandleResponse( request.CreateResponse(ResponseType.Public, "{0}, {1} {2}", request.Addressee ?? request.Nick, Name, resultWithQuery)); } }
private void HandleResults(ICollection<string> results, Request request, string searchTerms) { if (results.Count == 0) { string noResult = string.Format("'{0}': No results.", searchTerms.Trim()); ModuleManagementContainer.HandleResponse( request.CreateResponse("{0}, {1} {2}", request.Addressee ?? request.Nick, Name, noResult)); } else { // Not every search provider returns us our query strings, so do a quick token substitution for the services that don't. foreach (var result in results) { var resultWithQuery = result.Replace("%query%", searchTerms.Trim()); ModuleManagementContainer.HandleResponse( request.CreateResponse("{0}, {1} {2}", request.Addressee ?? request.Nick, Name, resultWithQuery)); } } }
/// <summary> /// Provides a utility method for responding to users, cutting down on copy/paste. /// </summary> /// /// <param name="request">The request that triggered the message.</param> /// <param name="responseType">The type of response to return: whether the message is public or private.<see cref="ResponseTargetType"/></param> /// <param name="responseMessage">The literal text of the response message.</param> /// <param name="formatObjects">An optional set of format objects. Will be passed along to String.format.</param> /// /// <returns></returns> protected void Reply(Request request, ResponseTargetType responseTargetType, ResponseType responseType, string responseMessage, params object[] formatObjects) { ModuleManagementContainer.HandleResponse(request.CreateResponse(responseTargetType, responseType, responseMessage, formatObjects)); }
/// <summary> /// Sends a list of all module names loaded. /// </summary> /// /// <param name="request">The incoming message to respond to.</param> private void SendModulesListResponse(Request request) { // TODO: Kog 07/06/2009 - This is a quick hack to get the help system working. Make it more awesome after the next commit. StringBuilder modulesList = new StringBuilder(); ModuleManagementContainer.Modules.Where(module => module.Name != "Help" && module.RequiredAccessLevel <= request.RequestFrom.AccessLevel). ForEach(x => { modulesList.Append(x.Name); modulesList.Append(", "); }); Response response = request.CreateResponse(ResponseType.Private); response.Message = "Modules list: " + modulesList.ToString().Trim().Trim(','); ModuleManagementContainer.HandleResponse(response); }
/// <summary> /// A conveninence method to cut down on the repetitive chatter of sending a response through our module subsystem. /// </summary> /// /// <param name="message">The message to send back out.</param> /// <param name="request">Our incoming <see cref="Request"/> object, which we use for creating our response.</param> public void SendResponse(string message, Request request) { ModuleManagementContainer.HandleResponse(request.CreateResponse(ResponseType.Private, message)); }
protected void Reply(Request request, ResponseType responseType, string responseMessage) { ModuleManagementContainer.HandleResponse(request.CreateResponse(ResponseTargetType.Public, responseType, responseMessage)); }
/// <summary> /// Tell the user that we have not found the specific module requested. /// </summary> /// /// <param name="moduleName">The name of the module the user wishes help for.</param> /// <param name="request">The incoming message to respond to.</param> private void SendModuleNotFoundResponse(string moduleName, Request request) { Response response = request.CreateResponse(ResponseType.Private); response.Message = string.Format("Module '{0}' could not be found.", moduleName); ModuleManagementContainer.HandleResponse(response); }