Exemplo n.º 1
0
        public void ProcessMessage(Message msg, ref Room rm)
        {
            var up = msg.Content.Remove(0, 1);
            ulong upInt = 0;

            if (!ulong.TryParse(up, out upInt) || upInt == 0)
            {
                rm.PostReplyLight(msg, string.Format(errorPhrases.PickRandom(), msg.Author.Name));
                return;
            }

            var nBytes = new byte[8];
            Extensions.RNG.GetBytes(nBytes);
            var n = (BitConverter.ToUInt64(nBytes, 0) % upInt) + 1;

            if (n % 25 == 0)
            {
                rm.PostReplyLight(msg, "http://imgs.xkcd.com/comics/random_number.png");
                return;
            }

            if (upInt == 100)
            {
                rm.PostReplyLight(msg, n == 1 ? "**CRITICAL SUCCESS**" : n == 100 ? "**CRITICAL FAILURE**" : n.ToString());
            }
            else
            {
                rm.PostReplyLight(msg, n);
            }
        }
Exemplo n.º 2
0
 public void ProcessMessage(Message msg, ref Room rm)
 {
     if (!quotaReached || (quotaReached && (DateTime.UtcNow - lastTry).TotalHours > 1))
     {
         var message = GetMessageNewMethod(msg);
         rm.PostReplyLight(msg, message);
     }
 }
Exemplo n.º 3
0
 public override void RunAction(Message incommingChatMessage, Room chatRoom, InstallationSettings roomSettings)
 {
     var message = "This is a chat bot for the SO Close Vote Reviewers chat room, developed by [gunr2171](http://stackoverflow.com/users/1043380/gunr2171) and the other members of the SO Close Vote Reviewers chat room. " +
         "For more information see the [github page](https://github.com/SO-Close-Vote-Reviewers/SOCVR-Chatbot). " +
         "Reply with `{0}` to see a list of commands."
             .FormatInline(ChatbotActionRegister.GetChatBotActionUsage<Commands>());
     chatRoom.PostMessageOrThrow(message);
 }
Exemplo n.º 4
0
 public ChatEventArgs(EventType t, Message m, User u, Room r, string rawData)
 {
     this.Type = t;
     this.Message = m;
     this.User = u;
     this.Room = r;
     this.Handled = false;
 }
Exemplo n.º 5
0
        public void ProcessMessage(Message msg, ref Room rm)
        {
            var users = rm.GetCurrentUsers();
            var userX = users.PickRandom().GetChatFriendlyUsername();
            var userY = users.PickRandom().GetChatFriendlyUsername();
            while (userX == userY)
            {
                userY = users.PickRandom().GetChatFriendlyUsername();
            }
            var message = string.Format(phrases.PickRandom(), userX, userY);

            rm.PostReplyFast(msg, message);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Determines if the incoming chat message activates this action.
        /// </summary>
        /// <param name="incomingMessage">The message said in the chat room.</param>
        /// <param name="isMessageAReplyToChatbot">A precomputed value indicating if the message is a directly reply to the chatbot.</param>
        /// <returns></returns>
        public bool DoesChatMessageActiveAction(Message incomingMessage, bool isMessageAReplyToChatbot)
        {
            // First, check if the message is a reply or not and if the Action accepts that.
            var requiredIsReplyValue = GetMessageIsReplyToChatbotRequiredValue();

            if (isMessageAReplyToChatbot != requiredIsReplyValue)
                return false;

            // Now regex test it.
            var formattedContents = GetMessageContentsReadyForRegexParsing(incomingMessage);
            var regex = GetRegexMatchingObject();

            return regex.IsMatch(formattedContents);
        }
Exemplo n.º 7
0
        public void ProcessMessage(Message msg, ref Room rm)
        {
            var cmdsMsg = new MessageBuilder(MultiLineMessageType.Code, false);
            cmdsMsg.AppendPing(msg.Author);

            foreach (var cmd in commands)
            {
                cmdsMsg.AppendText("\n" + cmd.Usage + " - " + cmd.Description);
            }

            cmdsMsg.AppendText("\n" + Usage + " - " + Description);

            rm.PostMessageFast(cmdsMsg);
        }
        /// <summary>
        /// Main entry point for the class.
        /// Takes a message revived from chat, determines what action should be taken, then performs that action.
        /// </summary>
        /// <param name="incommingChatMessage">The chat message that was said.</param>
        /// <param name="chatRoom">The room the chat message was said in.</param>
        public void ProcessChatMessage(Message incommingChatMessage, Room chatRoom)
        {
            // Do this first so I only have to find the result once per chat message.
            bool isReplyToChatbot = MessageIsReplyToChatbot(incommingChatMessage, chatRoom);

            // Determine the list of possible actions that work from the message.
            var possibleChatbotActionsToRun = ChatbotActionRegister.AllChatActions
                .Where(x => x.DoesChatMessageActiveAction(incommingChatMessage, isReplyToChatbot))
                .ToList();

            if (possibleChatbotActionsToRun.Count > 1)
                throw new Exception("More than one possible chat bot action to run for the input '{0}'"
                    .FormatSafely(incommingChatMessage.Content));

            if (!possibleChatbotActionsToRun.Any())
            {
                // Didn't find an action to run, what to do next depends of if the message was
                // a reply to the chatbot or not.
                if (isReplyToChatbot)
                {
                    // User was trying to make a command.
                    SendUnrecognizedCommandToDatabase(incommingChatMessage.GetContentsWithStrippedMentions());
                    chatRoom.PostReplyOrThrow(incommingChatMessage, "Sorry, I don't understand that. Use `{0}` for a list of commands."
                        .FormatInline(ChatbotActionRegister.GetChatBotActionUsage<Commands>()));
                }
                // Else it's a trigger, do nothing.

                return;
            }

            // You have a single item to run.
            var chatbotActionToRun = possibleChatbotActionsToRun.Single();

            // Now, do you have permission to run it? If you are a mod the answer is yes, else you need to check.
            if (incommingChatMessage.Author.IsMod || DoesUserHavePermissionToRunAction(chatbotActionToRun, incommingChatMessage.Author.ID))
            {
                // Have permission, run it.
                RunChatbotAction(chatbotActionToRun, incommingChatMessage, chatRoom);
            }
            else
            {
                // Don't have permission, tell the user only if it's a command.
                if (isReplyToChatbot)
                {
                    chatRoom.PostReplyOrThrow(incommingChatMessage, "Sorry, you need more permissions to run that command.");
                }
                // Don't do anything for triggers.
            }
        }
Exemplo n.º 9
0
        public void ProcessMessage(Message msg, ref Room rm)
        {
            if (au == null) { return; }

            rm.PostReplyFast(msg, "Updating, one sec...");

            if (!au.Update())
            {
                rm.PostReplyFast(msg, "I'm already up to date.");
            }
            else
            {
                rm.PostReplyFast(msg, "Update successful, starting new version...");

                au.StartNewVersion();

                Process.GetCurrentProcess().CloseMainWindow();
            }
        }
Exemplo n.º 10
0
        private string GetMessageNewMethod(Message msg)
        {
            lastTry = DateTime.UtcNow;
            string message = null;

            try
            {
                while (true)
                {
                    message = WebUtility.HtmlDecode(botSession.Think(msg.Content));

                    if (badMessages.IsMatch(message))
                    {
                        Console.WriteLine("Skipped thought: " + message);
                    }
                    else
                    {
                        quotaReached = false;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("403"))
                {
                    Console.WriteLine("API quota reached.");
                    quotaReached = true;
                }
                else
                {
                    Console.WriteLine(ex);
                }
                return null;
            }

            return message;
        }
Exemplo n.º 11
0
        /// <summary>
        /// Records the end of a review session for a user. Returns true if the session was successfully marked as finished.
        /// </summary>
        /// <param name="userMessage"></param>
        /// <param name="chatRoom"></param>
        /// <param name="itemsReviewed"></param>
        /// <returns></returns>
        protected bool EndSession(Message userMessage, Room chatRoom, int? itemsReviewed, InstallationSettings settings)
        {
            var da = new DatabaseAccessor(settings.DatabaseConnectionString);

            // Find the latest session by that user.
            var latestSession = da.GetLatestOpenSessionForUser(userMessage.Author.ID);

            // First, check if there is a session.
            if (latestSession == null)
            {
                chatRoom.PostReplyOrThrow(userMessage, "I don't seem to have the start of your review session on record. I might have not been running when you started, or some error happened.");
                return false;
            }

            // Check if session is greater than [MAX_REVIEW_TIME].
            var maxReviewTimeHours = settings.MaxReviewLengthHours;

            var timeThreshold = DateTimeOffset.Now.AddHours(-maxReviewTimeHours);

            if (latestSession.SessionStart < timeThreshold)
            {
                var timeDelta = DateTimeOffset.Now - latestSession.SessionStart;

                var message = "Your last uncompleted review session was {0} ago. Because it has exceeded my threshold ({1} hours), I can't mark that session with this information. "
                    .FormatInline(timeDelta.ToUserFriendlyString(), maxReviewTimeHours) +
                    "Use the command '{0}' to forcefully end that session."
                    .FormatInline(ChatbotActionRegister.GetChatBotActionUsage<EndSession>());

                chatRoom.PostReplyOrThrow(userMessage, message);
                return false;
            }

            // It's all good, mark the info as done.
            da.EndReviewSession(latestSession.Id, itemsReviewed);
            return true;
        }
Exemplo n.º 12
0
        public void ProcessMessage(Message msg, ref Room rm)
        {
            var users = rm.CurrentUsers;
            var userX = users.PickRandom().Name;
            var userY = users.PickRandom().Name;
            while (userX == userY)
            {
                userY = users.PickRandom().Name;
            }

            if (userX == rm.Me.Name)
            {
                userX = "me";
            }

            if (userY == rm.Me.Name)
            {
                userY = "me";
            }

            var message = string.Format(phrases.PickRandom(), userX, userY);

            rm.PostReplyLight(msg, message);
        }
Exemplo n.º 13
0
        private static bool HandleOwnerCommand(Room room, Message command)
        {
            var cmd = command.Content.Trim().ToUpperInvariant();

            if (cmd == "STOP")
            {
                shutdownMre.Set();
                return true;
            }
            if (cmd.StartsWith("SET THRESHOLD"))
            {
                var th = 0F;

                if (!float.TryParse(cmd.Remove(0, 14), out th))
                {
                    room.PostReplyFast(command, "Try using your hands to type a valid number between 0 and 1.");
                    return true;
                }

                if (th < 0 || th > 1)
                {
                    room.PostReplyFast(command, "Threshold must be between 0 and 1 (and *don't* include the % sign).");
                    return true;
                }

                cvClassifier.Threshold = th;
                qdvClassifier.Threshold = th;
                advClassifier.Threshold = th;

                room.PostReplyFast(command, "Threshold updated.");

                return true;
            }

            //case "UPDATE":
            //{
            //    UpdateBot(room, command);
            //    return true;
            //}

            return false;
        }
Exemplo n.º 14
0
        private static bool HandleNormalUserCommand(Room room, Message command)
        {
            var cmd = command.Content.Trim().ToUpperInvariant();

            switch (cmd)
            {
                case "ALIVE":
                {
                    var statusReport = $"Yes, I'm alive (`{DateTime.UtcNow - startTime}`).";
                    room.PostMessageFast(statusReport);
                    return true;
                }
                case "COMMANDS":
                {
                    var msg = $"See [here]({wikiCmdsLink} \"Chat Commands Wiki\").";
                    room.PostReplyFast(command, msg);
                    return true;
                }
                case "THRESHOLD":
                {
                    var msg = $"My current threshold is: `{cvClassifier.Threshold * 100}`%.";
                    room.PostMessageFast(msg);
                    return true;
                }
                //case "VERSION":
                //{
                //    var msg = $"My current version is: `{updater.CurrentVersion}`.";
                //    room.PostReplyFast(command, msg);
                //    return true;
                //}
                default:
                {
                    return false;
                }
            }
        }
Exemplo n.º 15
0
        private static bool HandlePrivilegedUserCommand(Room room, Message command)
        {
            var cmd = command.Content.Trim().ToUpperInvariant();

            switch (cmd)
            {
                case "DEL":
                {
                    room.DeleteMessage(command.ParentID);
                    return true;
                }
                default:
                {
                    return false;
                }
            }
        }
Exemplo n.º 16
0
 public bool TogglePin(Message message)
 {
     return TogglePin(message.ID);
 }
Exemplo n.º 17
0
        private static void HandleChatCommand(Room room, Message command)
        {
            try
            {
                if (UserAccess.Owners.Any(id => id == command.Author.ID) ||
                    command.Author.IsRoomOwner || command.Author.IsMod)
                {
                    var cmdMatches = HandleOwnerCommand(room, command);

                    if (!cmdMatches)
                    {
                        cmdMatches = HandlePrivilegedUserCommand(room, command);

                        if (!cmdMatches)
                        {
                            HandleNormalUserCommand(room, command);
                        }
                    }
                }
                else if (command.Author.Reputation >= 3000)
                {
                    var cmdMatches = HandlePrivilegedUserCommand(room, command);

                    if (!cmdMatches)
                    {
                        HandleNormalUserCommand(room, command);
                    }
                }
                else
                {
                    HandleNormalUserCommand(room, command);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                room.PostReplyFast(command, $"`Unable to execute command: {ex.Message}`");
            }
        }
Exemplo n.º 18
0
 public bool ToggleStar(Message message)
 {
     return ToggleStar(message.ID);
 }
Exemplo n.º 19
0
 public bool ClearMessageStars(Message message)
 {
     return ClearMessageStars(message.ID);
 }
Exemplo n.º 20
0
 public bool EditMessage(Message oldMessage, object newMessage)
 {
     return EditMessage(oldMessage.ID, newMessage);
 }
Exemplo n.º 21
0
 public bool DeleteMessage(Message message)
 {
     return DeleteMessage(message.ID);
 }
Exemplo n.º 22
0
 /// <summary>
 /// Takes the contents from the message, strips out any "mentions", and trims the sides of the string.
 /// </summary>
 /// <param name="incommingMessage"></param>
 /// <returns></returns>
 protected override sealed string GetMessageContentsReadyForRegexParsing(Message incommingMessage)
 {
     return incommingMessage
         .GetContentsWithStrippedMentions()
         .Trim();
 }
Exemplo n.º 23
0
 public void ProcessMessage(Message msg, ref Room rm)
 {
     rm.PostReplyFast(msg, faces.PickRandom());
 }
Exemplo n.º 24
0
        internal void TrackMessage(Message message)
        {
            if (message == null) { throw new ArgumentNullException("message"); }

            ConnectListener(EventType.MessageEdited, new Action<Message>(m =>
            {
                if (m.ID == message.ID)
                {
                    message.Content = m.Content;
                    message.EditCount++;
                }
            }));

            ConnectListener(EventType.MessageDeleted, new Action<User, int>((u, mID) =>
            {
                if (mID == message.ID)
                {
                    message.IsDeleted = true;
                }
            }));

            ConnectListener(EventType.MessageStarToggled, new Action<Message, int, int>((m, s, p) =>
            {
                if (m.ID == message.ID)
                {
                    message.StarCount = s;
                    message.PinCount = p;
                }
            }));
        }
Exemplo n.º 25
0
        private void PrintCommandListReply(Message m, Room r)
        {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < router.Commands.Count; i++)
            {
                sb.AppendFormat("{0}. ({1}) {2}\n", i + 1, router.CommandStates[router.Commands[i]] ? "Enabled" : "Disabled", router.Commands[i].Usage);
            }
            r.PostReplyLight(m, sb.ToString());
        }
Exemplo n.º 26
0
        private async void cvChatRoom_NewMessage(Message newMessage)
        {
            try
            {
                if (InformationMessageBroadcasted != null)
                    InformationMessageBroadcasted(newMessage.Content, newMessage.Author.Name);

                await Task.Run(() => cmp.ProcessChatMessage(newMessage, cvChatRoom));
            }
            catch (Exception ex)
            {
                // Something happened outside of an action's RunAction method. attempt to tell chat about it
                // this line will throw an exception if it fails, moving it further up the line.
                cvChatRoom.PostMessageOrThrow("error happened!\n" + ex.FullErrorMessage(Environment.NewLine)); // For now, more verbose later.
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Retrieves a message from the room.
        /// </summary>
        /// <param name="messageID">The ID of the message to fetch.</param>
        /// <returns>A Message object representing the requested message, or null if the message could not be found.</returns>
        public Message GetMessage(int messageID)
        {
            string resContent;

            try
            {
                resContent = RequestManager.Get(cookieKey, chatRoot + "/messages/" + messageID + "/history");
            }
            catch (WebException ex)
            {
                // If the input is valid, we've probably hit a deleted message.
                if (ex.Response != null && ((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotFound)
                {
                    throw new MessageNotFoundException();
                }
                else
                {
                    throw ex;
                }
            }

            if (string.IsNullOrEmpty(resContent))
            {
                throw new Exception("Unable to fetch data for message " + messageID + ".");
            }

            var lastestDom = CQ.Create(resContent).Select(".monologue").Last();
            var content = Message.GetMessageContent(Host, messageID);

            if (content == null) { throw new MessageNotFoundException(); }

            var parentID = content.IsReply() ? int.Parse(content.Substring(1, content.IndexOf(' '))) : -1;
            var authorName = lastestDom[".username a"].First().Text();
            var authorID = int.Parse(lastestDom[".username a"].First().Attr("href").Split('/')[2]);

            var message = new Message(this, messageID, GetUser(authorID), parentID);

            evMan.TrackMessage(message);

            return message;
        }
Exemplo n.º 28
0
 public bool PostReplyFast(Message targatMessage, object message)
 {
     return PostMessageFast(":" + targatMessage.ID + " " + message);
 }
Exemplo n.º 29
0
 public void ProcessMessage(Message msg, ref Room rm) => rm.PostReplyLight(msg, pics.PickRandom());
Exemplo n.º 30
0
 public Message PostReply(Message targetMessage, object message)
 {
     return PostMessage(":" + targetMessage.ID + " " + message);
 }