public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status)
 {
     Match output = Regex.Match(message.Body, @"^!urban (.*)", RegexOptions.IgnoreCase);
     if (output.Success) {
         String queryString = output.Groups[1].Value;
         if (!dict.verify_key(KEY)) {
             log.Error("Invalid key used for dictionary lookup.");
             message.Chat.SendMessage("The automated Urban Dictionary lookup is down until further notice.");
         }
         else {
             log.Debug("Key verified.");
             Definition[] defs = dict.lookup(KEY, queryString);
             if (defs.Length <= 0)
                 message.Chat.SendMessage(String.Format(@"UrbanDictionary lookup of ""{0}"": No results found.", queryString));
             else {
                 message.Chat.SendMessage(String.Format(
                     "UrbanDictionary lookup of \"{0}\":\n\n{1}: {2}\n\n{3}",
                     queryString,
                     defs[0].word,
                     defs[0].definition,
                     defs[0].example
                 ));
             }
         }
     }
 }
        public async Task WarpAsync(CommandContext Context, [Remaining] string args_)
        {
            var chatMessage = IChatMessage.Simple("");
            var args        = args_.Contains(" ") ? args_.Split(" ").ToList() : new List <string> {
                args_
            };

            if (args.Count == 1)
            {
                var warp = Globals.Configs.Warps[args[0]];
                try
                {
                    await Context.Player.TeleportAsync(warp.Position.ToObsidianPosition());

                    chatMessage.AddExtra(IChatMessage.Simple($"Successfully warped to {ChatColor.BrightGreen}{warp.Name}{ChatColor.Reset}."));
                }
                catch (Exception ex)
                {
                    chatMessage.AddExtra(IChatMessage.Simple($"Cannot warp to {ChatColor.Red}{warp.Name}{ChatColor.Reset}!"));
                    if (Context.Player.IsOperator)
                    {
                        chatMessage.AddExtra(IChatMessage.Simple($" For more information, see console."));
                    }
                    Globals.Logger.LogError($"{ChatColor.Red}{Context.Player.Username}{ChatColor.Reset} cannot warp to {ChatColor.Red}{warp.Name}{ChatColor.Reset}.\n{ex.ToString()}");
                }
            }
            else
            {
                chatMessage = Globals.RenderCommandUsage("/warp <name>");
            }
            await Context.Player.SendMessageAsync(chatMessage);
        }
        public void CheckMapSwapCommands(IChatMessage message)
        {
            if (message.Message.ToLower().Contains("!gm rctts") && !Plugin.cooldowns.GetCooldown("Map Swap") && GameModifiersController.commandsLeftForMessage > 0)
            {
                //Supercharge on rctts is probably not necessary

                /*
                 * if (GameModifiersController.trySuper && GameModifiersController.charges >= ChatConfig.chargesForSuperCharge + ChatConfig.rcttsChargeCost)
                 * {
                 *  //       GameModifiersController.beepSound.Play();
                 *  Plugin.twitchPowers.StartCoroutine(TwitchPowers.RealityCheck(TwitchPowers.RealityClip.length - 1f));
                 *  Plugin.twitchPowers.StartCoroutine(TwitchPowers.CoolDown(TwitchPowers.RealityClip.length + GameObjects.songAudio.clip.length, "RCTTS", "Strimmer play Reality Check... The whole thing :)"));
                 *  GameModifiersController.trySuper = false;
                 *  GameModifiersController.charges -= ChatConfig.chargesForSuperCharge + ChatConfig.rcttsChargeCost;
                 *  GameModifiersController.commandsLeftForMessage -= 1;
                 *  globalActive = true;
                 * }
                 * else
                 */
                if (GameModifiersController.charges >= Config.rcttsChargeCost)
                {
                    Plugin.twitchPowers.StartCoroutine(Plugin.twitchPowers.RealityCheck(Mathf.Min(Config.rcttsDuration, TwitchPowers.RealityClip.length - 1f)));
                    Plugin.twitchPowers.StartCoroutine(TwitchPowers.CoolDown(Config.rcttsCooldown, "Map Swap", "Strimmer play Reality Check 🙂 "));
                    GameModifiersController.charges -= Config.rcttsChargeCost;
                    GameModifiersController.commandsLeftForMessage -= 1;
                    globalActive = true;
                }
            }
        }
Example #4
0
    private void OnChatMessageReceived(IChatMessage payload)
    {
        var msg = string.Format("[{0}]: {1}", payload.SenderId, payload.Text);

        ChatTextLabel.text += string.Format("{0}\r\n", msg);
        Debug.Log(msg);
    }
Example #5
0
 private void Service_OnTextMessageReceived(IChatService svc, IChatMessage message)
 {
     lock (_invokeLock)
     {
         _onTextMessageReceivedCallbacks.InvokeAll(Assembly.GetCallingAssembly(), svc, message, _logger);
     }
 }
Example #6
0
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status)
        {
            Match output = Regex.Match(message.Body, @"^!twitter (.+)", RegexOptions.IgnoreCase);
            if (output.Success) {
                log.Debug("It's my turn!");
                String query = output.Groups[1].Value;

                log.Debug(String.Format("Fetching tweets for {0}.", query));
                var tweets = FluentTwitter.CreateRequest()
                                          .Statuses()
                                          .OnUserTimeline()
                                          .For(query)
                                          .Request()
                                          .AsStatuses();
                log.Debug("Tweets fetched.");

                if (tweets == null || tweets.Count() == 0) {
                    message.Chat.SendMessage(
                        String.Format("I don't think \"{0}\" is a Twitter username.", query)
                    );
                } else {
                    var tweet = tweets.First();

                    message.Chat.SendMessage(
                        String.Format("{0} ({1})", tweet.Text, tweet.CreatedDate.ToRelativeTime(false))
                    );
                }
            }
        }
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status) {
            Match output = Regex.Match(message.Body, @"^!urban (.*)", RegexOptions.IgnoreCase);
            if (output.Success) {
                String query = output.Groups[1].Value;
                
                WebRequest req = (HttpWebRequest) HttpWebRequest.Create("http://api.urbandictionary.com/v0/define?page=1&term=" + System.Uri.EscapeDataString(query));
                WebResponse resp;
                try {
                    resp = req.GetResponse();
                } catch (WebException) {
                    log.Warn("UrbanDictionary appears to be unavailable at the moment.");
                    message.Chat.SendMessage("Sorry, I seem to be unable to contact UrbanDictionary.");
                    return;
                }

                String responseText = new StreamReader(resp.GetResponseStream()).ReadToEnd();
                var defs = (Hashtable) JSON.JsonDecode(responseText);

                if ((string)defs["response_type"] == "no_results") {
                    message.Chat.SendMessage(String.Format(@"UrbanDictionary lookup of ""{0}"": No results found.", query));
                } else {
                    var def = (defs["list"] as ArrayList)[0] as Hashtable;

                    message.Chat.SendMessage(String.Format(
                        "UrbanDictionary lookup of \"{0}\":\n\n{1}: {2}\n\n{3}",
                        query,
                        def["word"],
                        def["definition"],
                        def["example"]
                    ));
                }
            }
        }
        private void findRandomPage(IChatMessage message)
        {
            log.Info("Requesting random page.");
            WebRequest webReq = WebRequest.Create("http://en.wikipedia.org/w/api.php?action=query&generator=random&grnnamespace=0&prop=info&inprop=url&format=xml");

            (webReq as HttpWebRequest).UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.1.249.1021 Safari/532.5";
            webReq.Timeout = 10000;
            WebResponse response = webReq.GetResponse();

            log.Debug("Gotcha!");
            String responseText = new StreamReader(response.GetResponseStream()).ReadToEnd();

            Match getUrl = Regex.Match(responseText, @"fullurl=""([^""]+)""", RegexOptions.IgnoreCase);

            if (getUrl.Success)
            {
                message.Chat.SendMessage(String.Format(
                                             @"Random Wikipedia page: {0}",
                                             getUrl.Groups[1].Value
                                             ));
            }
            else
            {
                log.Warn("Something went wrong in finding a random page.");
            }
        }
Example #9
0
    IProcessingResult PostPotatoTagged(IBot bot, IProcessingResult pr, IChatMessage msg, string tag)
    {
        pr.ResponseOrigin = Helper.GetExecutingMethodName(this);
        pr.Respond        = true;
        pr.Solved         = true;

        // find alias
        string aliasedOriginalTag = null;

        if (tagAliasesDic.ContainsKey(tag))
        {
            aliasedOriginalTag = tagAliasesDic[tag];
        }

        // find all images with that tag

        var list = new List <TaggedImage>();

        foreach (var ti in unpostedImages)
        {
            if (ti.tag != null)
            {
                if (ti.tag == tag || ti.tag == aliasedOriginalTag)
                {
                    list.Add(ti);
                }
            }
        }

        if (list.Count < 1)
        {
            return(PostRandomPotato(bot, pr));
        }
        else
        {
            // post random pic from list and do the rest as usual

            // get a random link to post
            var n         = r.Next(list.Count);
            var nextImage = list[n];
            nextLink = nextImage;

            // set it
            pr.ResponseText = nextLink.url;
            pr.TargetRoomID = msg.RoomID;

            // move image from one list to another
            unpostedImages.Remove(nextImage);
            postedImages.Add(nextImage);

            lastPostedImage = nextLink;

            dt_LastMessageTime = DateTime.Now;
            SetLastMessageIDWhenPosted(bot, msg.RoomID);

            Save();

            return(pr);
        }
    }
Example #10
0
 public void Broadcast(IChatMessage message)
 {
     foreach (var member in GameServer.Instance.PlayerManager.Where(x => _friends.ContainsKey(x.Account.Id)))
     {
         member.ChatSession?.SendAsync(message);
     }
 }
Example #11
0
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status) {
            Match output = Regex.Match(message.Body, @"^!(high|)roll (\d+)d(\d+)(([+-])(\d+))?", RegexOptions.IgnoreCase);
            if (output.Success) {
                bool high = output.Groups[1].Value.Length > 0;

                int num = Math.Max(1, Math.Min(200, Convert.ToInt32(output.Groups[2].Value)));
                int size = Math.Max(1, Math.Min(1000000, Convert.ToInt32(output.Groups[3].Value)));

                String pm = "+";
                int mod = 0;
                if (output.Groups[4].Length > 0) {
                    pm = output.Groups[5].Value;
                    mod = Math.Max(0, Math.Min(1000000, Convert.ToInt32(output.Groups[6].Value)));
                }
                
                string roll = String.Format("{0}d{1}{2}", num, size, mod > 0 ? pm + mod : "");

                if (high) {
                    if (!PluginSettings.Default.RollScores.ContainsKey(roll)) {
                        log.Debug(String.Format("Miss for {0}.", roll));
                        message.Chat.SendMessage(String.Format("{0} has never been rolled in this chat.", roll));        
                    } else {
                        log.Debug(String.Format("Hit for {0}.", roll));
                        Roll r =  PluginSettings.Default.RollScores[roll];
                        message.Chat.SendMessage(String.Format(
                            @"{0} rolled {1} on a {2} on {3}.",
                            r.Username,
                            r.Value,
                            roll,
                            r.Time.ToString("MMMM dd, yyyy", new CultureInfo("en-US"))
                        ));
                    }
                } else {
                    int[] vals = new int[num];
                    for (int i = 0; i < num; i++)
                        vals[i] = random.Next(size) + 1;

                    int value = vals.Sum() + (pm == "+" ? 1 : -1) * mod;
                    bool highscore = false;
                    if (!PluginSettings.Default.RollScores.ContainsKey(roll) ||
                         PluginSettings.Default.RollScores[roll].Value < value) {
                        log.Info(String.Format("New high-roll for {0} on chat {1} by {3}: {2}",
                                 roll, message.Chat.Name, value, message.Sender.Handle));
                        Roll r = new Roll(value, message.Sender.Handle, message.Chat.Name, message.Timestamp);
                        PluginSettings.Default.RollScores[roll] = r;
                        PluginSettings.Default.Save();
                        highscore = true;
                    }


                    message.Chat.SendMessage(String.Format(
                        @"{0} rolled; result: {1} ({2}){3}",
                        roll,
                        value,
                        String.Join(", ", Array.ConvertAll<int, String>(vals, new Converter<int, string>(Convert.ToString))),
                        highscore ? " - new high!" : ""
                    ));
                }
            }
        }
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status)
        {
            Match output = Regex.Match(message.Body, @"^!(?:calc|eval) (.+)", RegexOptions.IgnoreCase | RegexOptions.Singleline);

            if (output.Success)
            {
                String exp = output.Groups[1].Value;
                SemanticProcessor <MathToken> processor = new SemanticProcessor <MathToken>(new StringReader(exp), actions);
                ParseMessage parseMessage = processor.ParseAll();
                if (parseMessage == ParseMessage.Accept)
                {
                    message.Chat.SendMessage(
                        String.Format(
                            "{0} = {1}",
                            exp,
                            ((Computable)processor.CurrentToken).GetValue()));
                }
                else
                {
                    IToken token = processor.CurrentToken;
                    message.Chat.SendMessage(string.Format("{0} ({1} on line {2}, column {3})",
                                                           parseMessage, token.Symbol,
                                                           token.Position.Line, token.Position.Column));
                }
            }
        }
Example #13
0
        void QuoteMessage(object sender, ChatMessageEventArgs e)
        {
            IChatMessage message = e.ChatMessage;

            switch (e.QuoteType)
            {
            case ChatMessageQuoteType.Quote:
                if (string.IsNullOrWhiteSpace(NewMessage))
                {
                    NewMessage = $"> {message.Text}\r\r@{message.FromUser.Username} ";
                }
                else if (NewMessage.EndsWith("\r") || NewMessage.EndsWith("\n"))
                {
                    NewMessage = $"{NewMessage}\r> {message.Text}\r\r@{message.FromUser.Username} ";
                }
                else
                {
                    NewMessage = $"{NewMessage}\r\r> {message.Text}\r\r@{message.FromUser.Username} ";
                }
                break;

            case ChatMessageQuoteType.Reply:
                NewMessage = $"{NewMessage} @{message.FromUser.Username} ".TrimStart();
                break;

            default:
                break;
            }
            BuildClassString(NewMessage);
            Invoke(StateHasChanged);
            Task.Delay(1);
        }
Example #14
0
 public void Broadcast(IChatMessage message)
 {
     foreach (var plr in TeamManager.Players)
     {
         plr.ChatSession.SendAsync(message);
     }
 }
Example #15
0
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status)
        {
            Match output = Regex.Match(message.Body, @"^!gis (.*)", RegexOptions.IgnoreCase);

            if (output.Success)
            {
                String queryString = output.Groups[1].Value;
                log.Info(String.Format(@"Performing Google Image Search for ""{0}""", queryString));
                log.Debug("Constructing query...");
                WebRequest webReq = WebRequest.Create("http://www.google.com/uds/GimageSearch?context=0&lstkp=0&rsz=small&hl=en&source=gsc&gss=.com&sig=ceae2b35bf374d27b9d2d55288c6b495&q=" + queryString + "&safe=off&key=ABQIAAAAIlzQlYE_XUpT2_ADo1nSfRTv5U0terELrwVCXRNUOBWU3xrL0RRPairAEpQ82pc0k6AubNWYEj1e5g&v=1.0");
                //WebRequest webReq = WebRequest.Create("http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=" + queryString);
                webReq.Timeout = 10000;
                log.Info("Sending request to Google...");
                WebResponse response = webReq.GetResponse();
                log.Info("Response received; parsing...");
                String    responseText   = new StreamReader(response.GetResponseStream()).ReadToEnd();
                Hashtable responseParsed = (Hashtable)JSON.JsonDecode(responseText);
                ArrayList resultsList    = (ArrayList)((Hashtable)responseParsed["responseData"])["results"];
                log.Info(String.Format("Got {0} images.", resultsList.Count));
                if (resultsList.Count == 0)
                {
                    message.Chat.SendMessage(String.Format(@"GIS for ""{0}"": No results found.", queryString));
                }
                else
                {
                    Hashtable imageResult = (Hashtable)resultsList[random.Next(resultsList.Count)];
                    message.Chat.SendMessage(String.Format(@"GIS for ""{0}"": {1}", queryString, imageResult["url"]));
                }
            }
        }
Example #16
0
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status)
        {
            MatchCollection outputColl = Regex.Matches(message.Body,
                                                       "p(e+)nis|c(o+)ck|d(o+)ng|clitoris|d(i+)ck|sc?(h+)l(o+)ng|p(e+)cker|j(o+)hns(o+)n|w(a+)ng|"
                                                       + "b(o+)ner|one eyed m(o+)nster|phal(l+)[uo]s|pr(i+)ck|winki(e+)|r(i+)ch(a+)rd|will(y|i+e)|j(o+)ystick"
                                                       + "lightning r(o+)d|st(i+)ck ?sh(i+)ft",
                                                       RegexOptions.IgnoreCase);

            if (outputColl.Count > 0)
            {
                String outputString = "";

                foreach (Match output in outputColl)
                {
                    String midPart = "";
                    foreach (System.Text.RegularExpressions.Group g in output.Groups)
                    {
                        if (g != output.Groups[0])
                        {
                            midPart += g.Value;
                        }
                    }

                    midPart = Regex.Replace(midPart, ".", "=");

                    outputString += (outputString == "" ? "" : " ") +
                                    "8==" +
                                    midPart +
                                    "D";
                }
                message.Chat.SendMessage(outputString);
            }
        }
 public void Broadcast(IChatMessage message)
 {
     foreach (var team in _teams.Values)
     {
         team.Broadcast(message);
     }
 }
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status)
        {
            if (!message.IsEditable)
            {
                return;
            }

            String messageText = message.Body;

            foreach (Filter filter in PluginSettings.Default.WordFilters)
            {
                if (filter.disabled)
                {
                    continue;
                }
                try {
                    if (filter.caseSensitive)
                    {
                        messageText = Regex.Replace(messageText, filter.regex, filter.replacement);
                    }
                    else
                    {
                        messageText = Regex.Replace(messageText, filter.regex, filter.replacement, RegexOptions.IgnoreCase);
                    }
                } catch {
                    log.Error("Error in filter: " + filter);
                }
            }

            if (messageText != message.Body)
            {
                message.Body = messageText;
            }
        }
Example #19
0
        public IChatMessage GetResponse(long interactionId, IChatMessage message)
        {
            using (_trace.scope())
            {
                try
                {
                    Console.WriteLine("[{0}] - GetResponse ({1})", BotName, interactionId);

                    var textMessage = message as TextChatMessage;
                    if (textMessage == null)
                    {
                        return(null);
                    }

                    var page = "http://www.google.com/search?q=" + HttpUtility.UrlEncode(textMessage.Text) + "&btnI=1";
                    return(new UrlChatMessage {
                        Uri = new Uri(GetResponseUrl(page))
                    });
                }
                catch (Exception ex)
                {
                    _trace.exception(ex);
                }
                return(null);
            }
        }
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status) {
            Match output = Regex.Match(message.Body, @"^!acro ([\w-.]+)", RegexOptions.IgnoreCase);
            if (output.Success) {
                String acronym = output.Groups[1].Value.ToLower();
                log.Info(String.Format("Got request for acronym \"{0}\".", acronym));
                char[] acroChars = acronym.ToCharArray();
                String[] outputStr = new String[acroChars.Length];
                int i = 0;

                foreach (char letter in acroChars) {
                    try {
                        List<String> letterList = wordList[letter];
                        outputStr[i] = letterList[random.Next(letterList.Count)];
                    }
                    catch (Exception) {
                        outputStr[i] = Char.ToString(letter);
                    }
                    i++;
                }

                String expansion = String.Join(" ", outputStr);

                CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
                TextInfo textInfo = cultureInfo.TextInfo;
                expansion = textInfo.ToTitleCase(expansion);

                log.Info(String.Format("Ended up with the expansion \"{0}\".", expansion));

                message.Chat.SendMessage(String.Format(@"As far as I know, the acronym ""{0}"" means ""{1}"".", acronym, expansion));
            }
        }
Example #21
0
    IProcessingResult ManualPost(IBot bot, IProcessingResult pr, IChatMessage msg, string arg)
    {
        pr.ResponseOrigin = Helper.GetExecutingMethodName(this);
        pr.Respond        = true;
        pr.Solved         = true;

        if (msg.RoomID != bot.MainRoomID)
        {
            pr.ResponseText   = "*This feature is intended to work in the [main room](" + @"http://chat.stackexchange.com/rooms/6697/maid-cafe-" + ") only.*";
            pr.ReplyMessageID = msg.MessageID;
            pr.TargetRoomID   = msg.RoomID;

            return(pr);
        }

        if (string.IsNullOrEmpty(arg))
        {
            pr = PostRandomPotato(bot, pr);
        }
        else
        {
            pr = PostPotatoTagged(bot, pr, msg, arg);
        }

        return(pr);
    }
Example #22
0
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status)
        {
            Match output = Regex.Match(message.Body, @"^!waffle", RegexOptions.IgnoreCase);
            if (output.Success) {
                WebRequest webReq = WebRequest.Create("http://waffleimages.com/random");
                webReq.Timeout = 10000;
                log.Info("Contacting server...");
                WebResponse response = webReq.GetResponse();
                log.Debug("Response received; parsing...");
                String responseText = new StreamReader(response.GetResponseStream()).ReadToEnd();

                Match imgFinder = Regex.Match(responseText, @"http://img.waffleimages.com/[0-9a-f]+/r");

                if (!imgFinder.Success) {
                    log.Warn("Couldn't find any image in the result.");
                    log.Warn("If this event s");
                    message.Chat.SendMessage(@"Error communicating with server.");
                }
                else {
                    log.Debug("Result sent to chat.");
                    message.Chat.SendMessage(String.Format(@"Random WaffleImage: {0}", imgFinder.Value));
                }

            }
        }
Example #23
0
 public void Broadcast(IChatMessage message)
 {
     foreach (var member in GameServer.Instance.PlayerManager.Where(x => x.Club == this))
     {
         member.ChatSession?.SendAsync(message);
     }
 }
Example #24
0
    public IProcessingResult Add(IBot bot, IProcessingResult pr, IChatMessage msg, string arg)
    {
        pr.ResponseOrigin = Helper.GetExecutingMethodName(this);
        pr.Respond        = true;
        pr.Solved         = true;

        if (arg == "")
        {
            pr.ResponseText = "*Argument cannot be empty.*";
            return(pr);
        }

        Log("[…] Processing argument.");

        string link = null;
        string tag  = null;

        var words = arg.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

        if (words.Length > 0)
        {
            link = words[0].Trim();
        }

        if (words.Length > 1)
        {
            tag = Helper.TextAfter(arg, link).Trim();
        }

        return(AddTextFileLinks(bot, pr, msg, link, tag));

        //pr.ResponseText = "You can only add raw text files with image links on each line. Make sure the url ends with `.txt` or contains `pastebin.com/raw.php?i=`.";
        //return pr;
    }
Example #25
0
 void RaiseGotMessageToQuoteEvent(IChatMessage message, ChatMessageQuoteType quoteType)
 {
     GotMessageToQuote?.Invoke(this, new ChatMessageEventArgs()
     {
         ChatMessage = message, QuoteType = quoteType
     });
 }
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status)
        {
            foreach (Transformation trans in PluginSettings.Default.ActiveTransformationTriggers)
            {
                Match output = Regex.Match(message.Body, "^" + trans.trigger + " (.+)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                if (output.Success)
                {
                    log.Debug("Got in with " + trans.name + ".");
                    message.Chat.SendMessage(
                        String.Format("{0}: {1}", trans.name, trans.Transform(output.Groups[1].Value))
                        );
                }
            }

            if (PluginSettings.Default.AutomaticTransformations)
            {
                if (!message.IsEditable)
                {
                    return;
                }

                String newBody = PluginSettings.Default.ActiveTransformation.Transform(message.Body);
                if (newBody != message.Body) // avoid editing if the message doesn't change
                {
                    message.Body = newBody;
                }
            }
        }
        /// <inheritdoc/>
        public override IWolfResponse Deserialize(Type responseType, SerializedMessageData responseData)
        {
            // first deserialize the json message
            ChatHistoryResponse result = (ChatHistoryResponse)base.Deserialize(responseType, responseData);

            // then assign binary data to each of the messages
            JArray responseBody = GetResponseJson(responseData)["body"] as JArray;

            if (responseBody == null)
            {
                throw new ArgumentException("Chat history response requires to have a body property that is a JSON array", nameof(responseData));
            }
            foreach (JToken responseChatMessage in responseBody)
            {
                WolfTimestamp msgTimestamp = responseChatMessage["timestamp"].ToObject <WolfTimestamp>(SerializationHelper.DefaultSerializer);
                IChatMessage  msg          = result.Messages.First(m => m.Timestamp == msgTimestamp);
                JToken        numProp      = responseChatMessage["data"]?["num"];
                if (numProp != null)
                {
                    int binaryIndex = numProp.ToObject <int>(SerializationHelper.DefaultSerializer);
                    SerializationHelper.PopulateMessageRawData(ref msg, responseData.BinaryMessages.ElementAt(binaryIndex));
                }
            }

            return(result);
        }
Example #28
0
        public IProcessingResult ProcessMessage(IBot bot, IProcessingResult pr, IChatMessage msg)
        {
            if (!CheckIfMessageShouldBeProcessed(bot, pr, msg))
            {
                pr.Solved = true;
                return(pr);
            }

            var txt = Helper.RemoveBotNamesAndTriggerSymbol(bot.Name, msg.Text, bot.TriggerSymbol);

            var w1  = Helper.FirstWord(txt);
            var cmd = w1.ToLowerInvariant();
            var arg = Helper.TextAfter(txt, w1).Trim();

            pr = InvokeExplicitCommand(bot, pr, msg, cmd, arg);

            if (pr.SolvedSet && pr.Solved)
            {
                return(pr);
            }

            pr = InvokeImplicitCommand(bot, pr, msg, cmd, arg);

            if (pr.SolvedSet && pr.Solved)
            {
                return(pr);
            }

            pr = CheckIfIProcessingResultIsOkay(bot, pr, msg);

            return(pr);
        }
Example #29
0
    // admins can rename any tags
    // uploaders can rename their own tags (warn about merging with existing tag pool)
    // remove all images uploaded by userid
    // ban userid from uploading (admin rights)

    IProcessingResult Tag(IProcessingResult pr, IChatMessage msg, string arg)
    {
        /// _______ arg1
        // #post tag ghost in the shell = gits
        // #post tag jintai += jinrui wa suitai shimashita

        // #post tag remove naruto shipuuden
        // #post tag -= kuroko basket


        if (arg.Contains(" = "))
        {
            var add1W1 = Helper.TextBefore(arg, " = ").ToLowerInvariant();
            var add1W2 = Helper.TextAfter(arg, " = ").ToLowerInvariant();

            return(TagAdd(pr, msg, add1W1, add1W2));
        }

        var arg1 = Helper.FirstWord(arg);
        var rest = Helper.TextAfter(arg, arg1).Trim();

        switch (arg1)
        {
        case "":
        case "*": return(TagPostAll(pr, msg));

        case "alias":
        case "aliases": return(TagPostAllAliases(pr, msg, rest));

        case "remove": return(TagRemove(pr, msg, rest));
        }

        pr.ResponseText = "Unexpected argument. Refer to manual for help.";
        return(pr);
    }
Example #30
0
 public void Broadcast(IChatMessage message)
 {
     foreach (var plr in _players.Values)
     {
         plr.ChatSession.SendAsync(message);
     }
 }
        public void CheckStatusCommands(IChatMessage message)
        {
            if (message.Sender.IsBroadcaster || message.Sender.IsModerator)
            {
                if (message.Message.ToLower().Contains("!gm reset") && GMPUI.chatIntegration == true)
                {
                    try
                    {
                        Plugin.cooldowns.ResetCooldowns();
                        TwitchPowers.ResetPowers(true);
                        Plugin.twitchPowers.StopAllCoroutines();
                        GameModifiersController.charges = Config.chargesPerLevel;
                        ChatMessageHandler.TryAsyncMessage("Resetting non Permanent Powers");
                    }
                    catch (System.Exception ex)
                    {
                        Plugin.log.Error("Reset Command Failed: " + ex);
                    }
                }
            }

            /*
             * if (message.Message.ToLower().Contains("!gm pp"))
             * {
             *  if (Plugin.currentpp != 0)
             *      ChatMessageHandler.TryAsyncMessage("Streamer Rank: #" + Plugin.currentRank + ". Streamer pp: " + Plugin.currentpp + "pp");
             *  else
             *      ChatMessageHandler.TryAsyncMessage("Currently do not have streamer info");
             * }
             */
            if (message.Message.ToLower().Contains("!gm status"))
            {
                string scopeMessage = "";
                int    scope        = CheckCommandScope();
                switch (scope)
                {
                case 0:
                    scopeMessage = "Everyone has access to commands";
                    break;

                case 1:
                    scopeMessage = "Subscribers have access to commands";
                    break;

                case 2:
                    scopeMessage = "Moderators have access to commands";
                    break;
                }

                GameModifiersController.beepSound.Play();
                if (GMPUI.chatIntegration)
                {
                    ChatMessageHandler.TryAsyncMessage("Chat Integration Enabled. " + scopeMessage);
                }
                else
                {
                    ChatMessageHandler.TryAsyncMessage("Chat Integration Not Enabled. " + scopeMessage);
                }
            }
        }
Example #32
0
 public void Broadcast(IChatMessage message, bool excludeRooms = false)
 {
     foreach (var plr in Players.Values.Where(plr => !excludeRooms || plr.Room == null))
     {
         plr.ChatSession?.SendAsync(message);
     }
 }
Example #33
0
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status) {
            MatchCollection outputColl = Regex.Matches(message.Body, 
                "p(e+)nis|c(o+)ck|d(o+)ng|clitoris|d(i+)ck|sc?(h+)l(o+)ng|p(e+)cker|j(o+)hns(o+)n|w(a+)ng|"
              + "b(o+)ner|one eyed m(o+)nster|phal(l+)[uo]s|pr(i+)ck|winki(e+)|r(i+)ch(a+)rd|will(y|i+e)|j(o+)ystick"
              + "lightning r(o+)d|st(i+)ck ?sh(i+)ft",
                RegexOptions.IgnoreCase);
            if (outputColl.Count > 0) {
                String outputString = "";

                foreach (Match output in outputColl) {
                    String midPart = "";
                    foreach (System.Text.RegularExpressions.Group g in output.Groups) {
                        if (g != output.Groups[0])
                            midPart += g.Value;
                    }

                    midPart = Regex.Replace(midPart, ".", "=");

                    outputString += (outputString == "" ? "" : " ") +
                                    "8==" +
                                    midPart +
                                    "D";
                }
                message.Chat.SendMessage(outputString);
            }
        }
Example #34
0
        public Notification AddNotification(IChatMessage message)
        {
            Point loc;

            if (Notifications.Count == 0)
            {
                loc = new Point(rightScreen.Bounds.Right + 438, rightScreen.Bounds.Height - 135);
            }
            else
            {
                int highest_notif_loc = rightScreen.Bounds.Height;

                foreach (Notification new_notif in Notifications)
                {
                    if (new_notif.Location.Y < highest_notif_loc)
                    {
                        highest_notif_loc = new_notif.Location.Y;
                    }
                }

                loc = new Point(rightScreen.Bounds.Right + 438, highest_notif_loc - 135);
                if (!isPointYOnscreen(loc))
                {
                    Notifications[0].CloseNotification();
                    loc = Notifications[Notifications.Count - 1].Location;
                }
            }
            Notification notif = new Notification(loc, this, message);

            notif.FormClosed += notif_FormClosed;
            Notifications.Add(notif);
            return(notif);
        }
Example #35
0
        public async Task GcAsync(CommandContext Context)
        {
            var chatMessage = IChatMessage.Simple("");

            Process currentProcess = Process.GetCurrentProcess();

            //long maxMemory = currentProcess.VirtualMemorySize64;
            //long totalMemory = currentProcess.PeakVirtualMemorySize64;
            //long freeMemory = currentProcess.PeakVirtualMemorySize64-currentProcess.VirtualMemorySize64;
            long maxMemory   = currentProcess.WorkingSet64;
            long totalMemory = currentProcess.PeakWorkingSet64;
            long freeMemory  = totalMemory - maxMemory;

            //long usedMemory = currentProcess.PrivateMemorySize64;
            //long maxMemory = currentProcess.WorkingSet64;

            chatMessage.AddExtra(IChatMessage.Simple($"{Globals.Language.TranslateMessage("gcfree", MemoryFormatter.Fancy(freeMemory, MemoryFormatter.EMemory.MB, false))}\n"));
            chatMessage.AddExtra(IChatMessage.Simple($"{Globals.Language.TranslateMessage("gcmax", MemoryFormatter.Fancy(maxMemory, MemoryFormatter.EMemory.MB, false))}\n"));
            chatMessage.AddExtra(IChatMessage.Simple($"{Globals.Language.TranslateMessage("gctotal", MemoryFormatter.Fancy(totalMemory, MemoryFormatter.EMemory.MB, false))}\n"));
            chatMessage.AddExtra(IChatMessage.Simple($"{Globals.Language.TranslateMessage("tps", Context.Server.TPS)}"));
#if DEBUG
            chatMessage.AddExtra(IChatMessage.Simple($"{ChatColor.DarkGreen}//There are a lot of things here. :o"));
#endif

            await Context.Player.SendMessageAsync(chatMessage);
        }
Example #36
0
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status)
        {
            Match output = Regex.Match(message.Body, @"^!acro ([\w-.]+)", RegexOptions.IgnoreCase);

            if (output.Success)
            {
                String acronym = output.Groups[1].Value.ToLower();
                log.Info(String.Format("Got request for acronym \"{0}\".", acronym));
                char[]   acroChars = acronym.ToCharArray();
                String[] outputStr = new String[acroChars.Length];
                int      i         = 0;

                foreach (char letter in acroChars)
                {
                    try {
                        List <String> letterList = wordList[letter];
                        outputStr[i] = letterList[random.Next(letterList.Count)];
                    }
                    catch (Exception) {
                        outputStr[i] = Char.ToString(letter);
                    }
                    i++;
                }

                String expansion = String.Join(" ", outputStr);

                CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
                TextInfo    textInfo    = cultureInfo.TextInfo;
                expansion = textInfo.ToTitleCase(expansion);

                log.Info(String.Format("Ended up with the expansion \"{0}\".", expansion));

                message.Chat.SendMessage(String.Format(@"As far as I know, the acronym ""{0}"" means ""{1}"".", acronym, expansion));
            }
        }
Example #37
0
 protected void OnNextMessage(IChatMessage item)
 {
     foreach (var observer in MessageObservers)
     {
         observer.OnNext(item);
     }
 }
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status) {
            Match output = Regex.Match(message.Body, @"(?:youtube\.\w{2,3}\S+v=|youtu\.be/)([\w-]+)", RegexOptions.IgnoreCase);
            // Use non-breaking space as a marker for when to not show info.
            if (output.Success && !message.Body.Contains(" ")) {
                String youtubeId = output.Groups[1].Value;
                log.Info("Sending request to YouTube...");

                YouTubeQuery ytq = new YouTubeQuery("http://gdata.youtube.com/feeds/api/videos/" + youtubeId);

                Feed<Video> feed = ytr.Get<Video>(ytq);
                Video vid = feed.Entries.ElementAt<Video>(0);
                String title = vid.Title;
                String user = vid.Author;
                String rating = vid.RatingAverage.ToString();

                int seconds = Int32.Parse(vid.Media.Duration.Seconds) % 60;
                int minutes = Int32.Parse(vid.Media.Duration.Seconds) / 60;
                String duration = String.Format(@"{0}:{1:00}", minutes, seconds);

                message.Chat.SendMessage(String.Format(@"YouTube: ""{0}"" (uploaded by: {1}) (avg rating: {2:F2}) (duration: {3})", title, user, rating, duration));
                return;
            }
            
            output = Regex.Match(message.Body, @"^!youtube (.+)", RegexOptions.IgnoreCase);
            if (output.Success) {
                String query = output.Groups[1].Value;

                YouTubeQuery ytq = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);
                ytq.Query = query;
                ytq.SafeSearch = YouTubeQuery.SafeSearchValues.None;
                ytq.NumberToRetrieve = 10;

                Feed<Video> feed = ytr.Get<Video>(ytq);
                int count = feed.Entries.Count<Video>();

                string url;
                if (count > 0) {
                    Video vid = feed.Entries.ElementAt<Video>(random.Next(count));
                    url = vid.WatchPage.ToString();
                } else {
                    url = "No matches found.";
                }

                message.Chat.SendMessage(String.Format(@"YouTube search for ""{0}"": {1}", query, url));
                return;
            }

            output = Regex.Match(message.Body, @"^!youtube", RegexOptions.IgnoreCase);
            if (output.Success) {
                log.Debug("Got a request for a random video.");

                String url = randomCache.Count > 0 ? randomCache.Dequeue() : generateRandomVideos(true);

                message.Chat.SendMessage(String.Format(@"Random YouTube video: {0}", url));

                generateRandomVideos(false);
                return;
            }
        }
    public new IProcessingResult Command(IBot bot, IProcessingResult pr, IChatMessage msg, string cmd, string arg, string cmdOriginal, string argOriginal)
    {
        switch (cmd)
        {
            default: return pr;

            // core commands

            case "about": return About(bot, pr, arg);
            case "help": return Help(bot, pr, arg);
            case "commands": return GetCommandList(bot, pr, arg);
            case "uptime": return Uptime(bot, pr);
            case "modules": return Modules(bot, pr);

            case "edit": return Edit(pr, bot, msg, arg);
            case "unonebox":
            case "unbox": return Unonebox(pr, bot, msg, arg);
            case "undo": return Undo(bot, pr, arg);

            case "status": return Status(bot, pr);

            case "trust": return TrustedUsers(bot, pr, arg);
            case "ignore": return BannedUsers(bot, pr, arg);

            case "say": return Say(pr, arg);
            case "tell": return Tell(pr, arg);

            case "alias": return Alias(pr, bot, msg, arg);

            case "save": return Save(bot, pr, msg.UserID);
            case "shutdown": return Shutdown(bot, pr, arg, msg.UserID);


            // hoihoi-san borrowed

            case "google": return Google(pr, msg, arg);
            case "wiki": return Wiki(pr, msg, arg);
            case "urban": return Urban(pr, msg, arg);
            case "youtube": return Youtube(pr, msg, arg);
            case "weather": return Weather(pr, msg, arg);


            // advanfaged

            case "id": return ID(bot, pr, msg, arg);
            case "isch": return Isch(bot, pr, msg, arg);

            case "whois":
            case "what":
            case "last": return LastPostedImageID(bot, pr, msg, arg);


            // bonus

            case "hats": return Hats(pr);
            case "meme": return Meme(bot, pr, msg, arg);

        }
    }
Example #40
0
 public void Add(IChatMessage command)
 {
     lock (_commands)
     {
         _commands.Enqueue(command);
     }
     _messagesAvaiable.Release();
 }
Example #41
0
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status)
        {
            Match output = Regex.Match(message.Body, @"^!overheard ?(\w*)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
            if (output.Success) {
                log.Info("It's a-me! Determining active site...");
                OverheardSite activeSite = null;

                if (output.Groups[1].Length > 0) {
                    activeSite = (from site in sites
                                  where site.command == output.Groups[1].Value.ToLower()
                                  select site).SingleOrDefault();
                }

                if (activeSite == null) {
                    log.Info("Site not found or not chosen; picking at random...");
                    activeSite = sites[random.Next(sites.Length)];
                }

                log.Info("Picked " + activeSite.prettyName + "; fetching random quote...");
                WebRequest webReq = WebRequest.Create("http://www." + activeSite.urlname + "/bin/randomentry.cgi");
                webReq.Timeout = 10000;
                WebResponse response = webReq.GetResponse();
                log.Info("Response received; parsing...");
                String responseText = new StreamReader(response.GetResponseStream()).ReadToEnd();

                Regex quoteRx = new Regex(@"
                        <h3\sclass=""title"">(.+?)</h3>
                        \s*
                        <p>(.+?)</p>
                    ",
                    RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline
                );

                Match quoteMatch = quoteRx.Match(responseText);
                if (!quoteMatch.Success) {
                    log.Warn("Regex failed to match contents. Please file a bug report about this if the problem persists.");
                    message.Chat.SendMessage("Sorry, something went wrong. :(");
                    return;
                }

                String title = quoteMatch.Groups[1].Value;
                String contents = quoteMatch.Groups[2].Value;

                title = title.Trim();

                contents = contents.Replace("<br/>", "\n");
                contents = Regex.Replace(contents, "<.+?>", "");
                contents = HttpUtility.HtmlDecode(contents);

                message.Chat.SendMessage(String.Format(
                    "{0}: {1}\n{2}",
                    activeSite.prettyName,
                    title,
                    contents
                ));
            }
        }
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status) {
            Match output = Regex.Match(message.Body, @"^!8ball", RegexOptions.IgnoreCase);
            if (output.Success) {
                String reply = PluginSettings.Default.EightBallReplies[random.Next(PluginSettings.Default.EightBallReplies.Count)];

                message.Chat.SendMessage(String.Format(
                    @"The Magic 8-ball replies: {0}",
                    reply
                ));
            }
        }
 public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status) {
     Match output = Regex.Match(message.Body, @"^!wiki ?(.*)", RegexOptions.IgnoreCase);
     if (output.Success) {
         String query = output.Groups[1].Value.Trim();
         if (query.Length > 0) {
             lookupArticle(message, query);
         } else {
             findRandomPage(message);
         }
     }
 }
Example #44
0
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status) {
            Match output = Regex.Match(message.Body, @"^!qdb ?(\d*)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
            if (output.Success) {
                WebRequest webReq;
                WebResponse response;
                String responseText;
                String quoteText;
                Quote quote;

                if (output.Groups[1].Value != "") {
                    log.Info("No cached quotes; fetching...");
                    webReq = WebRequest.Create("http://qdb.us/qdb.xml?action=quote&quote="+output.Groups[1].Value+"&fixed=0&client=Dynamic+Skype+Bot");
                    webReq.Timeout = 10000;
                    response = webReq.GetResponse();
                    responseText = new StreamReader(response.GetResponseStream()).ReadToEnd();

                    if (responseText == "no quotes were found for these parameters.") {
                        message.Chat.SendMessage("No quote exists with that id.");
                        return;
                    }

                    XDocument doc = XDocument.Parse(responseText);
                    XNamespace d = "http://purl.org/rss/1.0/";

                    XElement item = doc.Descendants(d + "item").First();
                    quote = new Quote();
                    quote.id = item.Element(d + "title").Value;

                    quoteText = item.Element(d + "description").Value;
                    quoteText = Regex.Replace(quoteText, "<br>", "\n\n");
                    quoteText = Regex.Replace(quoteText, "<.+?>", "");
                    quoteText = HttpUtility.HtmlDecode(quoteText);

                    quote.quote = quoteText;
                } else {
                    log.Info("Fetching random quote...");

                    if (randomQuotes.Count == 0) {
                        log.Info("No cached quotes; fetching...");
                        fetchRandomQuotes();
                    }

                    log.Debug("Picking a random quote...");
                    quote = randomQuotes.Dequeue();
                }

                message.Chat.SendMessage(String.Format(
                    "QDB Quote {0}:\n\n{1}",
                    quote.id,
                    quote.quote
                ));
            }
        }
Example #45
0
 public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status) {
     Match output = Regex.Match(message.Body, @"^!cypher ([^ ]+) (.*)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
     if (output.Success) {
         String cypher = output.Groups[1].Value;
         String plainText = output.Groups[2].Value;
         Match rotMatch = Regex.Match(cypher, @"^rot(\d+)$", RegexOptions.IgnoreCase);
         if (rotMatch.Success) {
             int rot = int.Parse(rotMatch.Groups[1].Value)%26;
             String code = caesar(plainText, rot);
             message.Chat.SendMessage(String.Format("ROT{0} of \"{1}\" is \"{2}\".", rot, plainText, code));
         }
     }
 }
Example #46
0
 private void _addToExchange(IChatMessage newMessage)
 {
     if (Exchange.Count > 0)
     {
         IChatMessage lastMessage = Exchange[Exchange.Count - 1];
         if (lastMessage.Speaker.Equals(newMessage.Speaker) &&
             (newMessage.SpeakTime.Ticks - lastMessage.SpeakTime.Ticks < MaxChatInterval))
         {
             lastMessage.LastWord = false;
         }
     }
     Exchange.Add(newMessage);
 }
Example #47
0
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status)
        {
            Match output = Regex.Match(message.Body, @"^!p**n", RegexOptions.IgnoreCase);
            if (output.Success) {
                log.Debug("Loading category list...");
                WebRequest webReq = WebRequest.Create("http://www.easygals.com/");
                webReq.Timeout = 10000;
                WebResponse response = webReq.GetResponse();
                String responseText = new StreamReader(response.GetResponseStream()).ReadToEnd();
                log.Debug("Picking a category...");
                Regex categoryFinderRx = new Regex(@"<a class=""catLink"" href=""([^\s]+)"".*?>(.+?)</a>");
                MatchCollection categoryFinderColl = categoryFinderRx.Matches(responseText);
                if (categoryFinderColl.Count <= 0) {
                    log.Warn("Couldn't find any p**n categories.");
                    log.Warn("Please check if http://www.easygals.com/ works okay for you.");
                    log.Warn("If it appears to work fine and the problem persists, please submit a bug report.");
                    message.Chat.SendMessage("Sorry, some kind of error occurred in trying to obtain p**n. :(");
                    return;
                }
                Match categoryFinder = categoryFinderColl[random.Next(categoryFinderColl.Count)];

                log.Info("I think I'll go for some " + categoryFinder.Groups[2].Value + " today!");

                log.Debug("Attempting to find some " + categoryFinder.Groups[2].Value + "...");

                webReq = WebRequest.Create("http://www.easygals.com/" + categoryFinder.Groups[1].Value + "&rs=1");
                webReq.Timeout = 10000;
                response = webReq.GetResponse();
                responseText = new StreamReader(response.GetResponseStream()).ReadToEnd();
                Regex pornFinderRx = new Regex(@"<a href=""/cgi-bin/atx/out.+?u=(http:.+?)""");
                MatchCollection pornFinderColl = pornFinderRx.Matches(responseText);
                if (pornFinderColl.Count <= 0) {
                    log.Warn("Couldn't find any " + categoryFinder.Groups[2].Value + " p**n.");
                    log.Warn("Either the category is empty or the format of the site has changed.");
                    log.Warn("Please check if http://www.easygals.com/" + categoryFinder.Groups[1].Value + "&rs=1 loads okay.");
                    log.Warn("If it appears to work fine and the problem persists, please submit a bug report.");
                    message.Chat.SendMessage("Argh, I couldn't find any " + categoryFinder.Groups[2].Value + "! Bummer.");
                    return;
                }
                Match pornFinder = pornFinderColl[random.Next(pornFinderColl.Count)];

                log.Info("P**n found! Linking to chat.");

                message.Chat.SendMessage(String.Format(
                    @"Random p**n link: {0}",
                    pornFinder.Groups[1].Value
                ));
            }
        }
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status) {
            Match output = Regex.Match(message.Body, @"^!notright", RegexOptions.IgnoreCase | RegexOptions.Singleline);
            if (output.Success) {
                WebRequest webReq = WebRequest.Create("http://notalwaysright.com/?random");
                webReq.Timeout = 10000;
                log.Info("Connecting to NotAlwaysRight.com...");

                WebResponse response = webReq.GetResponse();
                log.Info("Response received; parsing...");
                String responseText = new StreamReader(response.GetResponseStream()).ReadToEnd();

                Regex notRightRx = new Regex(@"
                        <h3\sclass=""storytitle""><.+?>(.+?)</a>\s*</h3>\s*     # title
                        <div\sclass=""post_header""><a .*?rel=""tag"">(.+?)</a> # job text
                        \s\|\s(.+?)\s\|                                         # location
                        .+?
                        <div\sclass=""storycontent"">(.+?)</div>       # story
                    ",
                    RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline
                );

                Match match = notRightRx.Match(responseText);
                if (!match.Success) {
                    log.Warn("Couldn't find any stories. If this problem persists, please file a bug report.");
                    message.Chat.SendMessage("Sorry, I couldn't find any stories.");
                    return;
                }

                String title = match.Groups[1].Value;
                String job = String.Format("{0} &ndash; {1}", match.Groups[2].Value, match.Groups[3].Value);
                String story = match.Groups[4].Value;

                title = HttpUtility.HtmlDecode(title);
                title = title.Trim();

                job = Regex.Replace(job, "<.+?>", "");
                job = HttpUtility.HtmlDecode(job);
                job = job.Trim();

                story = Regex.Replace(story, "<.+?>", "");
                story = HttpUtility.HtmlDecode(story);
                story = story.Trim();

                message.Chat.SendMessage(String.Format(
                    "Not Always Right: {0}\n{1}\n\n{2}",
                    title, job, story
                ));
            }
        }
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status)
        {
            Match output = Regex.Match(message.Body, @"^!link", RegexOptions.IgnoreCase);
            if (output.Success) {
                log.Info("Fetching link...");
                WebRequest webReq = WebRequest.Create("http://del.icio.us/recent?random");
                webReq.Timeout = 10000;
                WebResponse response = webReq.GetResponse();

                message.Chat.SendMessage(String.Format(
                    @"Random link: {0}",
                    response.ResponseUri
                ));
            }
        }
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status) {
            Match output = Regex.Match(message.Body, @"^!dA", RegexOptions.IgnoreCase);
            if (output.Success) {
                log.Info("Requesting random page...");
                WebRequest webReq = WebRequest.Create("http://www.deviantart.com/random/deviation");
                webReq.Timeout = 10000;
                WebResponse response = webReq.GetResponse();
                log.Debug("Gotcha!");

                message.Chat.SendMessage(String.Format(
                    @"Random deviation: {0}",
                    response.ResponseUri
                ));
            }
        }
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status) {
            Match output = Regex.Match(message.Body, @"^!4chan", RegexOptions.IgnoreCase);
            if (output.Success) {
                log.Info("Going to visit /b/ to find a thread...");
                WebRequest webReq = WebRequest.Create("http://boards.4chan.org/b/");
                webReq.Timeout = 10000;
                WebResponse response;
                try {
                    response = webReq.GetResponse();
                } catch (WebException) {
                    log.Warn("4chan.org appears to be unavailable at the moment.");
                    message.Chat.SendMessage("Sorry, some kind of error occurred in trying to contact 4chan.");
                    return;   
                }
                String responseText = new StreamReader(response.GetResponseStream()).ReadToEnd();
                Regex threadFinderRx = new Regex(@"<a href=""thread/(\d+)/[^""]+""[^>]*>Reply</a>");
                MatchCollection threadFinderColl = threadFinderRx.Matches(responseText);
                if (threadFinderColl.Count <= 0) {
                    log.Warn("4chan appears to have changed its thread-list format. Please report this on the suggestion page.");
                    message.Chat.SendMessage("Sorry, some kind of error occurred in trying to contact 4chan.");
                    return;
                }
                Match threadFinder = threadFinderColl[random.Next(threadFinderColl.Count)];
                

                log.Info("Thread located. Opening thread...");
                String threadId = threadFinder.Groups[1].Value;
                webReq = WebRequest.Create("http://boards.4chan.org/b/thread/"+threadId);
                response = webReq.GetResponse();
                responseText = new StreamReader(response.GetResponseStream()).ReadToEnd();
                log.Info("Thread opened. Locating a random picture...");
                Regex picFinderRx = new Regex(@"<a class=""fileThumb"" href=""//i\.4cdn\.org/b/(\d+\.\w+)"" target=""_blank"">");
                MatchCollection picFinderColl = picFinderRx.Matches(responseText);
                if (picFinderColl.Count <= 0) {
                    log.Warn("For some reason, we couldn't find a picture on the page. Please report this on the suggestion page.");
                    message.Chat.SendMessage("Sorry, some kind of error occurred in trying to contact 4chan.");
                    return;
                }
                Match picFinder = picFinderColl[random.Next(picFinderColl.Count)];

                log.Warn("Picture found! Linking to chat.");

                message.Chat.SendMessage(String.Format(
                    @"Random picture from 4chan: http://i.4cdn.org/b/{0}",
                    picFinder.Groups[1].Value
                ));
            }
        }
Example #52
0
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status)
        {
            Match output = Regex.Match(message.Body, @"^!rule34 (.+)", RegexOptions.IgnoreCase);
            if (output.Success) {
                String query = output.Groups[1].Value;
                String searchUri = "http://rule34.paheal.net/post/list?search=" + System.Uri.EscapeDataString(query);

                log.Info(String.Format("Searching rule34 for '{0}'", query));
                WebRequest webReq = WebRequest.Create(searchUri);
                webReq.Timeout = 20000;
                try {
                    webReq.GetResponse();
                } catch (WebException) {
                    log.Warn("rule34.paheal.net appears to be unavailable at the moment.");
                    message.Chat.SendMessage("Sorry, the website failed to respond in time. It may be down, or just slow.\nIf you want to try the search for yourself, go to http://rule34.paheal.net/post/list?search=" + System.Uri.EscapeDataString(query));
                    return;
                }
                log.Info("Search completed; looking up result...");

                webReq = WebRequest.Create("http://rule34.paheal.net/post/list/" + System.Uri.EscapeDataString(query) + "/1");
                webReq.Timeout = 20000;
                WebResponse response;
                try {
                    response = webReq.GetResponse();
                } catch (WebException) {
                    log.Warn("rule34.paheal.net appears to be unavailable at the moment.");
                    message.Chat.SendMessage("Sorry, the website failed to respond in time. It may be down, or just slow.\nIf you want to try the search for yourself, go to http://rule34.paheal.net/post/list?search=" + System.Uri.EscapeDataString(query));
                    return;
                }

                String responseText = new StreamReader(response.GetResponseStream()).ReadToEnd();
                Regex imgFinderRx = new Regex(@"(?<=id='Imagesmain-toggle'.*)<a href='([^']*?)'>Image Only</a>", RegexOptions.Singleline);
                MatchCollection imgFinderColl = imgFinderRx.Matches(responseText);
                if (imgFinderColl.Count <= 0) {
                    message.Chat.SendMessage(String.Format("Sorry, couldn't find any rule34 pictures of {0}.", query));
                    return;
                }
                Match imgFinder = imgFinderColl[random.Next(imgFinderColl.Count)];
                log.Info("Picture found! Linking to chat.");

                message.Chat.SendMessage(String.Format(
                    @"Rule 34 picture of {0}: {1}",
                    query,
                    HttpUtility.UrlPathEncode(imgFinder.Groups[1].Value)
                ));
            }
        }
Example #53
0
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status) {
            Match input = Regex.Match(message.Body, @"^!maze (.+)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
            if (input.Success) {
                Command cmd = CommandFromString(input.Groups[1].Value.ToLower());

                log.Debug("Got the command '" + cmd + "'");

                String output = "";

                switch (cmd) {
                    case Command.North:
                    case Command.South:
                    case Command.East:
                    case Command.West:
                    case Command.N:
                    case Command.E:
                    case Command.S:
                    case Command.W:
                        Direction dir = Direction.FromString(cmd.ToString());
                        if (control.Walker.CanWalk(dir)) {
                            control.Walker.Walk(dir);
                            output += reporter.ReportWalk(dir);
                        } else {
                            output += reporter.ReportCannotWalk;
                        }
                        break;
                    case Command.Down:
                        if (control.Walker.Position.HasDown) {
                            control.Descend();
                            output += reporter.ReportDescend;
                        } else {
                            output += reporter.ReportCannotDescend;
                        }
                        break;
                    case Command.Look:
                        output += reporter.ReportLook;
                        break;
                    default:
                        output += "Invalid command!";
                        break;
                }

                message.Chat.SendMessage(output);
            }
        }
Example #54
0
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status) {
            Match output = Regex.Match(message.Body, @"^!rule34 (.+)", RegexOptions.IgnoreCase);
            if (output.Success) {
                String query = output.Groups[1].Value;
                String searchUri = "http://rule34.paheal.net/post/list?search=" + System.Uri.EscapeDataString(query);

                log.Info(String.Format("Searching rule34 for '{0}'", query));
                HttpWebRequest webReq = (HttpWebRequest) HttpWebRequest.Create("http://rule34.paheal.net/post/list/" + System.Uri.EscapeDataString(query) + "/1");
                webReq.Timeout = 20000;
                webReq.AllowAutoRedirect = true;
                WebResponse response;
                try {
                    response = webReq.GetResponse();
                } catch (WebException e) {
                    if (e.Status == WebExceptionStatus.ProtocolError && e.Response != null
                        && ((HttpWebResponse) e.Response).StatusCode == HttpStatusCode.NotFound) {
                        message.Chat.SendMessage(String.Format("Sorry, couldn't find any rule34 pictures of {0}.", query));
                        return;    
                    } else {
                        log.Warn("rule34.paheal.net appears to be unavailable at the moment.");
                        message.Chat.SendMessage("Sorry, the website failed to respond in time. It may be down, or just slow.\nIf you want to try the search for yourself, go to http://rule34.paheal.net/post/list?search=" + System.Uri.EscapeDataString(query));
                        return;
                    }
                }

                String responseText = new StreamReader(response.GetResponseStream()).ReadToEnd();
                Regex imgFinderRx = new Regex(@"<a href=""([^""]*?)"">Image Only</a>", RegexOptions.Singleline);
                MatchCollection imgFinderColl = imgFinderRx.Matches(responseText);
                if (imgFinderColl.Count <= 0) {
                    message.Chat.SendMessage(String.Format("Sorry, couldn't find any rule34 pictures of {0}.", query));
                    return;
                }
                Match imgFinder = imgFinderColl[random.Next(imgFinderColl.Count)];
                log.Info("Picture found! Linking to chat.");

                message.Chat.SendMessage(String.Format(
                    @"Rule 34 picture of {0}: {1}",
                    query,
                    HttpUtility.UrlPathEncode(imgFinder.Groups[1].Value)
                ));
            }
        }
 public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status) {
     Match output = Regex.Match(message.Body, @"^!(?:calc|eval) (.+)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
     if (output.Success) {
         String exp = output.Groups[1].Value;
         SemanticProcessor<MathToken> processor = new SemanticProcessor<MathToken>(new StringReader(exp), actions);
         ParseMessage parseMessage = processor.ParseAll();
         if (parseMessage == ParseMessage.Accept) {
             message.Chat.SendMessage(
                 String.Format(
                     "{0} = {1}",
                     exp,
                     ((Computable)processor.CurrentToken).GetValue()));
         } else {
             IToken token = processor.CurrentToken;
             message.Chat.SendMessage(string.Format("{0} ({1} on line {2}, column {3})",
                                                    parseMessage, token.Symbol,
                                                    token.Position.Line, token.Position.Column));
         }
     }
 }
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status) {
            foreach (Transformation trans in PluginSettings.Default.ActiveTransformationTriggers) {
                Match output = Regex.Match(message.Body, "^" + trans.trigger + " (.+)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                if (output.Success) {
                    log.Debug("Got in with " + trans.name + ".");
                    message.Chat.SendMessage(
                        String.Format("{0}: {1}", trans.name, trans.Transform(output.Groups[1].Value))
                    );
                }
            }
            
            if (PluginSettings.Default.AutomaticTransformations) {
                if (!message.IsEditable) {
                    return;
                }

                String newBody = PluginSettings.Default.ActiveTransformation.Transform(message.Body);
                if (newBody != message.Body) // avoid editing if the message doesn't change
                    message.Body = newBody;
            }
        }
Example #57
0
        private static void WriteConsoleMessage(IChatMessage pMsg)
        {
            string chat;

            if (pMsg.Chat.Name.Contains("$63bb4364f4abbd9"))
            {
                Console.ResetColor();
                chat = "MF";
            }
            else if (pMsg.Chat.Name.Contains("$flippid;f742f5ee5cbe0c71"))
            {
                Console.ForegroundColor = ConsoleColor.White;
                chat = "GR";
            }
            else if (pMsg.Chat.Name.Contains("ed20b9c00e34dd8b"))
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                chat = "GR+";
            }
            else if (pMsg.Chat.Name.Contains("19:f87666a242fc410a8b2ad4630dd2161e"))
            {
                Console.ForegroundColor = ConsoleColor.DarkYellow;
                chat = "NiP";
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                chat = "PM";
            }

            var line = string.Format(
                "{0} <{1}><{2}> {3}",
                pMsg.Timestamp.ToString("HH:mm:ss"),
                chat,
                pMsg.FromDisplayName,
                pMsg.Body);

            Console.WriteLine(line);
        }
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status) {
            Match output = Regex.Match(message.Body, @"^!dict (.*)", RegexOptions.IgnoreCase);
            if (output.Success) {
                String queryString = output.Groups[1].Value;
                log.Info(String.Format(@"Performing dictionary lookup on ""{0}"".", queryString));

                XPathDocument response = new XPathDocument("http://www.onelook.com/?w=" + queryString + "&xml=1");
                XPathNavigator nav = response.CreateNavigator();

                XPathNodeIterator it = nav.Select("//OLQuickDef");

                String defPlural = (it.Count > 1 ? "s" : "");
                String definitions = "";
                int i = 0;
                foreach (XPathNavigator def in it) {
                    if (i >= 5) {
                        definitions += "\n\nMore than 5 matches found; only the first 5 are displayed.";
                        break;
                    }
                    definitions += Environment.NewLine + HttpUtility.HtmlDecode(def.Value.Trim());
                    i++;
                }

                if (definitions.Equals(""))
                    message.Chat.SendMessage(String.Format(@"Unable to define ""{0}"".", queryString));
                else {
                    message.Chat.SendMessage(
                        String.Format(
                            @"The word ""{0}"" has the following definition{1}:{2}",
                            queryString,
                            defPlural,
                            definitions)
                    );
                }
            }
        }
 public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status) {
     Match output = Regex.Match(message.Body, @"^!gis (.*)", RegexOptions.IgnoreCase);
     if (output.Success) {
         String queryString = output.Groups[1].Value;
         log.Info(String.Format(@"Performing Google Image Search for ""{0}""", queryString));
         log.Debug("Constructing query...");
         WebRequest webReq = WebRequest.Create("http://www.google.com/uds/GimageSearch?context=0&lstkp=0&rsz=small&hl=en&source=gsc&gss=.com&sig=ceae2b35bf374d27b9d2d55288c6b495&q=" + queryString + "&safe=off&key=ABQIAAAAIlzQlYE_XUpT2_ADo1nSfRTv5U0terELrwVCXRNUOBWU3xrL0RRPairAEpQ82pc0k6AubNWYEj1e5g&v=1.0");
         //WebRequest webReq = WebRequest.Create("http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=" + queryString);
         webReq.Timeout = 10000;
         log.Info("Sending request to Google...");
         WebResponse response = webReq.GetResponse();
         log.Info("Response received; parsing...");
         String responseText = new StreamReader(response.GetResponseStream()).ReadToEnd();
         Hashtable responseParsed = (Hashtable)JSON.JsonDecode(responseText);
         ArrayList resultsList = (ArrayList)((Hashtable)responseParsed["responseData"])["results"];
         log.Info(String.Format("Got {0} images.", resultsList.Count));
         if (resultsList.Count == 0)
             message.Chat.SendMessage(String.Format(@"GIS for ""{0}"": No results found.", queryString));
         else {
             Hashtable imageResult = (Hashtable)resultsList[random.Next(resultsList.Count)];
             message.Chat.SendMessage(String.Format(@"GIS for ""{0}"": {1}", queryString, imageResult["url"]));
         }
     }
 }
Example #60
0
        public void Skype_MessageStatus(IChatMessage message, TChatMessageStatus status)
        {
            Match output = Regex.Match(message.Body, @"^!lolcat", RegexOptions.IgnoreCase);
            if (output.Success) {
                WebRequest webReq = WebRequest.Create("http://api.cheezburger.com/xml/category/cats/lol/random");
                webReq.Timeout = 10000;
                log.Info("Contacting service...");
                WebResponse response;
                try {
                    response = webReq.GetResponse();
                } catch (Exception e) {
                    log.Warn("Failed to obtain random lolcat.", e);
                    message.Chat.SendMessage("Failed to obtain random lolcat. Please try again later.");
                    return;
                }
                log.Info("Response received; parsing...");
                String responseText = new StreamReader(response.GetResponseStream()).ReadToEnd();

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(responseText);
                XmlNode pic = xmlDoc.SelectSingleNode("/Lol/LolImageUrl");
                message.Chat.SendMessage("Random lolcat: "+pic.InnerText);
            }
        }