예제 #1
0
        public static void AwardViewersCoins(int setamount = 0)
        {
            List <string> usernames = ParseViewersFromJsonAndFindActiveViewers();

            if (usernames != null)
            {
                foreach (string username in usernames)
                {
                    Viewer viewer = GetViewer(username);

                    if (viewer.IsBanned)
                    {
                        continue;
                    }

                    if (setamount > 0)
                    {
                        viewer.GiveViewerCoins(setamount);
                    }
                    else
                    {
                        int   baseCoins      = ToolkitSettings.CoinAmount;
                        float baseMultiplier = (float)viewer.GetViewerKarma() / 100f;

                        if (viewer.IsSub)
                        {
                            baseCoins      += ToolkitSettings.SubscriberExtraCoins;
                            baseMultiplier *= ToolkitSettings.SubscriberCoinMultiplier;
                        }
                        else if (viewer.IsVIP)
                        {
                            baseCoins      += ToolkitSettings.VIPExtraCoins;
                            baseMultiplier *= ToolkitSettings.VIPCoinMultiplier;
                        }
                        else if (viewer.mod)
                        {
                            baseCoins      += ToolkitSettings.ModExtraCoins;
                            baseMultiplier *= ToolkitSettings.ModCoinMultiplier;
                        }

                        // check if viewer is active in chat
                        int minutesSinceViewerWasActive = TimeHelper.MinutesElapsed(viewer.last_seen);

                        if (ToolkitSettings.ChatReqsForCoins)
                        {
                            if (minutesSinceViewerWasActive > ToolkitSettings.TimeBeforeHalfCoins)
                            {
                                baseMultiplier *= 0.5f;
                            }

                            if (minutesSinceViewerWasActive > ToolkitSettings.TimeBeforeNoCoins)
                            {
                                baseMultiplier *= 0f;
                            }
                        }

                        double coinsToReward = (double)baseCoins * baseMultiplier;

                        Store_Logger.LogString($"{viewer.username} gets {baseCoins} * {baseMultiplier} coins, total {(int)Math.Ceiling(coinsToReward)}");

                        viewer.GiveViewerCoins((int)Math.Ceiling(coinsToReward));
                    }
                }
            }
        }
예제 #2
0
        public static void CheckCommand(TwitchIRCMessage msg)
        {
            if (msg == null)
            {
                return;
            }

            if (msg.Message == null)
            {
                return;
            }

            Viewer viewer = msg.Viewer;

            viewer.WasSeen();


            if (viewer.IsBanned)
            {
                return;
            }

            if (!msg.Message.StartsWith("!"))
            {
                IRCMessageLog.AddNewMessage(msg);
            }

            Command commandDef = DefDatabase <Command> .AllDefs.ToList().Find(s => msg.Message.StartsWith("!" + s.command));

            if (commandDef != null)
            {
                bool runCommand = true;

                if (commandDef.requiresMod && (!viewer.Mod && viewer.UsernameLower != ToolkitSettings.Channel.ToLower()))
                {
                    runCommand = false;
                }

                if (commandDef.requiresAdmin && msg.User.ToLower() != ToolkitSettings.Channel.ToLower())
                {
                    runCommand = false;
                }

                if (!commandDef.enabled)
                {
                    runCommand = false;
                }

                if (commandDef.shouldBeInSeparateRoom && !AllowCommand(msg))
                {
                    runCommand = false;
                }

                if (runCommand)
                {
                    commandDef.RunCommand(msg);
                }
            }

            List <TwitchInterfaceBase> modExtensions = Current.Game.components.OfType <TwitchInterfaceBase>().ToList();

            if (modExtensions == null)
            {
                return;
            }

            foreach (TwitchInterfaceBase parser in modExtensions)
            {
                parser.ParseCommand(msg);
            }
        }
예제 #3
0
 public static int GetViewerPoints(Viewer viewer)
 {
     string[] args = { "http://192.168.0.20:6779", $"{{\"method\":\"get\",\"username\":\"{viewer.username}\"}}" };
     return(Convert.ToInt32(WebClientHelper.UploadString(args)));
 }
예제 #4
0
        public static void CheckCommand(IRCMessage msg)
        {
            if (msg == null)
            {
                return;
            }

            if (msg.Message == null)
            {
                return;
            }

            string message = msg.Message;
            string user    = msg.User;

            if (message.Split(' ')[0] == "/w")
            {
                List <string> messagewhisper = message.Split(' ').ToList();
                messagewhisper.RemoveAt(0);
                message = string.Join(" ", messagewhisper.ToArray());
                Helper.Log(message);
            }

            Viewer viewer = Viewers.GetViewer(user);

            viewer.last_seen = DateTime.Now;

            if (viewer.IsBanned)
            {
                return;
            }

            Command commandDef = DefDatabase <Command> .AllDefs.ToList().Find(s => msg.Message.StartsWith("!" + s.command));

            if (commandDef != null)
            {
                bool runCommand = true;

                if (commandDef.requiresMod && (!viewer.mod && viewer.username.ToLower() != ToolkitSettings.Channel.ToLower()))
                {
                    runCommand = false;
                }

                if (commandDef.requiresAdmin && msg.User.ToLower() != ToolkitSettings.Channel.ToLower())
                {
                    runCommand = false;
                }

                if (!commandDef.enabled)
                {
                    runCommand = false;
                }

                if (commandDef.shouldBeInSeparateRoom && !AllowCommand(msg))
                {
                    runCommand = false;
                }

                if (runCommand)
                {
                    commandDef.RunCommand(msg);
                }
            }

            List <TwitchInterfaceBase> modExtensions = Current.Game.components.OfType <TwitchInterfaceBase>().ToList();

            if (modExtensions == null)
            {
                return;
            }

            foreach (TwitchInterfaceBase parser in modExtensions)
            {
                parser.ParseCommand(msg);
            }
        }
예제 #5
0
        public void CheckCommand(string message, string user)
        {
            if (message.Split(' ')[0] == "/w")
            {
                List <string> messagewhisper = message.Split(' ').ToList();
                messagewhisper.RemoveAt(0);
                message = string.Join(" ", messagewhisper.ToArray());
                Helper.Log(message);
            }

            //admin commands
            if (user.ToLower() == Settings.Channel.ToLower())
            {
                if (message.StartsWith("!resetviewers"))
                {
                    if (resetWarning == 0)
                    {
                        _mod._client.SendMessage($"@{user} " + "TwitchToolkitResetViewersWarningOne".Translate());
                        resetWarning = 1;
                    }
                    else if (resetWarning == 1)
                    {
                        _mod._client.SendMessage($"@{user} " + "TwitchToolkitResetViewersWarningTwo".Translate());
                        resetWarning = 2;
                    }
                    else if (resetWarning == 2)
                    {
                        _mod._client.SendMessage($"@{user} " + "TwitchToolkitResetViewersWarningThree".Translate());
                        Settings.ViewerIds     = null;
                        Settings.ViewerCoins   = null;
                        Settings.ViewerKarma   = null;
                        Settings.listOfViewers = new List <Viewer>();
                        _mod.WriteSettings();
                        resetWarning = 0;
                    }
                }

                if (message.StartsWith("!addtoolkitmod"))
                {
                    string[] command = message.Split(' ');

                    if (command.Length < 2)
                    {
                        return;
                    }

                    string mod = command[1].Replace("@", "").ToLower();

                    if (Viewer.IsModerator(mod))
                    {
                        _mod._client.SendMessage($"@{user} " + Helper.ReplacePlaceholder("TwitchToolkitAlreadyMod".Translate(), mod: mod));
                        return;
                    }

                    Viewer modviewer = Viewer.GetViewer(mod);

                    modviewer.SetAsModerator();
                    _mod._client.SendMessage($"@{user} " + Helper.ReplacePlaceholder("TwitchToolkitAddedMod".Translate(), mod: mod));
                }

                if (message.StartsWith("!removetoolkitmod"))
                {
                    string[] command = message.Split(' ');

                    if (command.Length < 2)
                    {
                        return;
                    }

                    string mod = command[1].Replace("@", "").ToLower();

                    if (!Viewer.IsModerator(mod))
                    {
                        return;
                    }

                    Viewer modviewer = Viewer.GetViewer(mod);

                    modviewer.RemoveAsModerator();
                    _mod._client.SendMessage($"@{user} " + Helper.ReplacePlaceholder("TwitchToolkitRemovedMod".Translate(), mod: mod));
                }
            }

            //moderator commands
            if (user.ToLower() == Settings.Channel.ToLower() || Viewer.IsModerator(user))
            {
                if (message.StartsWith("!refreshviewers"))
                {
                    TwitchToolkitDev.WebRequest_BeginGetResponse.Main("https://tmi.twitch.tv/group/user/" + Settings.Channel.ToLower() + "/chatters", new Func <TwitchToolkitDev.RequestState, bool>(Settings.viewers.SaveUsernamesFromJsonResponse));
                }

                if (message.StartsWith("!karmaround"))
                {
                    Settings.viewers.AwardViewersCoins();
                }

                if (message.StartsWith("!giveallcoins"))
                {
                    try
                    {
                        string[] command = message.Split(' ');

                        if (command.Length < 2)
                        {
                            return;
                        }

                        bool isNumeric = int.TryParse(command[1], out int amount);

                        if (isNumeric)
                        {
                            foreach (Viewer viewer in Settings.listOfViewers)
                            {
                                viewer.GiveViewerCoins(amount);
                            }
                            _mod._client.SendMessage($"@{user} " + Helper.ReplacePlaceholder("TwitchToolkitGiveAllCoins".Translate(), amount: amount.ToString()));
                        }
                    }
                    catch (InvalidCastException e)
                    {
                        Helper.Log("Give All Coins Syntax Error " + e.Message);
                    }
                }

                if (message.StartsWith("!givecoins"))
                {
                    try
                    {
                        string[] command = message.Split(' ');

                        if (command.Length < 3)
                        {
                            return;
                        }

                        string giftee = command[1].Replace("@", "");

                        if (user.ToLower() != Settings.Channel.ToLower() && giftee.ToLower() == user.ToLower())
                        {
                            _mod._client.SendMessage($"@{user} " + "TwitchToolkitModCannotGiveCoins".Translate());
                            return;
                        }

                        int  amount;
                        bool isNumeric = int.TryParse(command[2], out amount);
                        if (isNumeric)
                        {
                            Viewer viewer = Viewer.GetViewer(giftee);
                            Helper.Log($"Giving viewer {viewer.username} {amount} coins");
                            viewer.GiveViewerCoins(amount);
                            _mod._client.SendMessage($"@{user} " + Helper.ReplacePlaceholder("TwitchToolkitGivingCoins".Translate(), viewer: viewer.username, amount: amount.ToString(), newbalance: viewer.GetViewerCoins().ToString()));
                        }
                    }
                    catch (InvalidCastException e)
                    {
                        Helper.Log("Invalid Give Viewer Coins Command " + e.Message);
                    }
                }

                if (message.StartsWith("!checkuser"))
                {
                    try
                    {
                        string[] command = message.Split(' ');

                        if (command.Length < 2)
                        {
                            return;
                        }

                        string target = command[1].Replace("@", "");

                        Viewer viewer = Viewer.GetViewer(target);
                        _mod._client.SendMessage($"@{user} " + Helper.ReplacePlaceholder("TwitchToolkitCheckUser".Translate(), viewer: viewer.username, amount: viewer.GetViewerCoins().ToString(), karma: viewer.GetViewerKarma().ToString()));
                    }
                    catch (InvalidCastException e)
                    {
                        Helper.Log("Invalid Check User Command " + e.Message);
                    }
                }

                if (message.StartsWith("!setkarma"))
                {
                    try
                    {
                        string[] command = message.Split(' ');

                        if (command.Length < 3)
                        {
                            return;
                        }

                        string target = command[1].Replace("@", "");
                        int    amount;
                        bool   isNumeric = int.TryParse(command[2], out amount);
                        if (isNumeric)
                        {
                            Viewer viewer = Viewer.GetViewer(target);
                            viewer.SetViewerKarma(amount);
                            _mod._client.SendMessage($"@{user}" + Helper.ReplacePlaceholder("TwitchToolkitSetKarma".Translate(), viewer: viewer.username, karma: amount.ToString()));
                        }
                    }
                    catch (InvalidCastException e)
                    {
                        Helper.Log("Invalid Check User Command " + e.Message);
                    }
                }

                if (message.StartsWith("!togglecoins"))
                {
                    if (Settings.EarningCoins)
                    {
                        Settings.EarningCoins = false;
                        _mod._client.SendMessage($"@{user} " + "TwitchToolkitEarningCoinsMessage".Translate() + " " + "TwitchToolkitOff".Translate());
                    }
                    else
                    {
                        Settings.EarningCoins = true;
                        _mod._client.SendMessage($"@{user} " + "TwitchToolkitEarningCoinsMessage".Translate() + " " + "TwitchToolkitOn".Translate());
                    }
                }

                if (message.StartsWith("!togglestore"))
                {
                    if (Settings.StoreOpen)
                    {
                        Settings.StoreOpen = false;
                        _mod._client.SendMessage($"@{user} " + "TwitchToolkitStorePurchasesMessage".Translate() + " " + "TwitchToolkitOn".Translate());
                    }
                    else
                    {
                        Settings.StoreOpen = true;
                        _mod._client.SendMessage($"@{user} " + "TwitchToolkitStorePurchasesMessage".Translate() + " " + "TwitchToolkitOn".Translate());
                    }
                }
            }

            // commands are suppressed when not earning coins
            if (Settings.EarningCoins)
            {
                if (message.StartsWith(Settings.BalanceCmd))
                {
                    Helper.Log("Trying to find User");
                    Viewer viewer = Viewer.GetViewer(user);
                    _mod._client.SendMessage($"@{viewer.username} " + Helper.ReplacePlaceholder("TwitchToolkitBalanceMessage".Translate(), amount: viewer.GetViewerCoins().ToString(), karma: viewer.GetViewerKarma().ToString()));
                }

                if (message.StartsWith(Settings.KarmaCmd) && !message.Contains("!karmaround"))
                {
                    Viewer viewer = Viewer.GetViewer(user);
                    _mod._client.SendMessage($"@{viewer.username} " + "TwitchToolkitWhatIsKarma".Translate() + $" { viewer.GetViewerKarma()}%");
                }

                if (message.StartsWith(Settings.InstructionsCmd))
                {
                    _mod._client.SendMessage($"@{user} " + "TwitchToolkitInstructions".Translate() + $" { Settings.CustomPricingSheetLink}");
                }

                if (message.StartsWith(Settings.PurchaselistCmd))
                {
                    _mod._client.SendMessage($"@{user} " + "TwitchToolkitPurchaseList".Translate() + $" {Settings.CustomPricingSheetLink}");
                }

                if (message.StartsWith(Settings.GiftCmd) && Settings.GiftingCoins)
                {
                    string[] command = message.Split(' ');

                    if (command.Count() < 3)
                    {
                        return;
                    }

                    string target = command[1].Replace("@", "");

                    bool isNumeric = int.TryParse(command[2], out int amount);
                    if (isNumeric && amount > 0)
                    {
                        Viewer giftee = Viewer.GetViewer(target);
                        Viewer gifter = Viewer.GetViewer(user);
                        if (gifter.GetViewerCoins() >= amount)
                        {
                            gifter.TakeViewerCoins(amount);
                            giftee.GiveViewerCoins(amount);
                            _mod._client.SendMessage($"@{giftee.username} " + Helper.ReplacePlaceholder("TwitchToolkitGiftCoins".Translate(), amount: amount.ToString(), from: gifter.username));
                        }
                    }
                }
            }

            if (message.StartsWith(Settings.ModinfoCmd))
            {
                _mod._client.SendMessage($"@{user} " + "TwitchToolkitModInfo".Translate() + " https://discord.gg/qrtg224 !");
            }

            if (Settings.StoreOpen)
            {
                if (message.StartsWith(Settings.BuyeventCmd))
                {
                    if (message.Split(' ').Count() < 2 || (message.Split(' ')[1] == "carepackage"))
                    {
                        return;
                    }

                    ShopCommand command = new ShopCommand(message, Viewer.GetViewer(user));
                    if (command.errormessage != null)
                    {
                        _mod._client.SendMessage(command.errormessage);
                    }
                    else if (command.successmessage != null && Settings.PurchaseConfirmations)
                    {
                        _mod._client.SendMessage(command.successmessage);

                        //TTS BuyeventCmd
                        Helper.Log($"Attempting to say {message}");
                        TTSHelper.Speech.SpeakAsync(message);
                    }
                }

                if (message.StartsWith(Settings.BuyitemCmd))
                {
                    string[] command = message.Split(' ');

                    if (command.Length < 2)
                    {
                        return;
                    }

                    string item = command[1];
                    command[1] = "TwitchToolkitCarepackage".Translate();
                    command[0] = item.ToLower();

                    string newcommand = string.Join(" ", command);
                    Helper.Log("Attemping item purchase " + newcommand);
                    ShopCommand command2 = new ShopCommand(newcommand, Viewer.GetViewer(user));
                    if (command2.errormessage != null)
                    {
                        _mod._client.SendMessage(command2.errormessage);
                    }
                    else if (command2.successmessage != null && Settings.PurchaseConfirmations)
                    {
                        _mod._client.SendMessage(command2.successmessage);

                        //TTS BuyItemCMD
                        Helper.Log($"Attempting to say {message}");
                        TTSHelper.Speech.SpeakAsync(message);
                    }
                }
            }

            if (message.StartsWith(Settings.ModsettingsCmd))
            {
                string minutess     = Settings.CoinInterval > 1 ? "s" : "";
                string storeon      = Settings.StoreOpen ? "TwitchToolkitOn".Translate() : "TwitchToolkitOff".Translate();
                string earningcoins = Settings.EarningCoins ? "TwitchToolkitOn".Translate() : "TwitchToolkitOff".Translate();

                string stats_message = Helper.ReplacePlaceholder("TwitchToolkitModSettings".Translate(),
                                                                 amount: Settings.CoinAmount.ToString(),
                                                                 first: Settings.CoinInterval.ToString(),
                                                                 second: storeon,
                                                                 third: earningcoins,
                                                                 karma: Settings.KarmaCap.ToString()
                                                                 );

                _mod._client.SendMessage(stats_message);
            }

            if (message.StartsWith(Settings.CommandHelpCmd))
            {
                string commands = " " +
                                  Settings.BalanceCmd + ", " +
                                  Settings.BuyeventCmd + ", " +
                                  Settings.BuyitemCmd + ", " +
                                  Settings.InstructionsCmd + ", " +
                                  Settings.PurchaselistCmd + ", " +
                                  Settings.ModinfoCmd + ", " +
                                  Settings.ModsettingsCmd + ", " +
                                  Settings.KarmaCmd + ", " +
                                  Settings.GiftCmd;

                _mod._client.SendMessage("TwitchToolkitUserCommands".Translate() + commands);
            }



            if (Settings.CommandsAliveEnabled && message.StartsWith("!alive", StringComparison.InvariantCultureIgnoreCase) && (DateTime.Now - _mod._aliveCommand).TotalSeconds >= 10)
            {
                _mod._aliveCommand = DateTime.Now;
                _mod._client.SendMessage(
                    "TwitchStoriesChatMessageColonyAlive".Translate() + " " + Current.Game.tickManager.TicksGame.ToReadableRimworldTimeString() +
                    ", " +
                    "TwitchStoriesChatMessageGamePlayed".Translate() + " " + Current.Game.Info.RealPlayTimeInteracting.ToReadableTimeString()
                    );
                return;
            }

            if (Settings.CommandsModsEnabled && message.Contains("!installedmods") && (DateTime.Now - _mod._modsCommand).TotalSeconds >= 10)
            {
                _mod._modsCommand = DateTime.Now;
                string   msg  = "Version: " + _mod.Version + ", Mods: ";
                string[] mods = LoadedModManager.RunningMods.Select((m) => m.Name).ToArray();

                for (int i = 0; i < mods.Length; i++)
                {
                    msg += mods[i] + ", ";

                    if (i == (mods.Length - 1) || msg.Length > 256)
                    {
                        msg = msg.Substring(0, msg.Length - 2);
                        _mod._client.SendMessage(msg);
                        msg = "";
                    }
                }
                return;
            }
        }
예제 #6
0
        public override void ExposeData()
        {
            base.ExposeData();
            Scribe_Values.Look(ref Channel, "Channel", "", true);
            Scribe_Values.Look(ref Username, "Username", "", true);
            Scribe_Values.Look(ref OAuth, "OAuth", "", true);
            Scribe_Values.Look(ref ChannelID, "ChannelID", "", true);
            Scribe_Values.Look(ref ChatroomUUID, "ChatroomUUID", "", true);

            Scribe_Values.Look(ref VoteTime, "VoteTime", 1, true);
            Scribe_Values.Look(ref VoteOptions, "VoteOptions", 3, true);
            Scribe_Values.Look(ref VoteEnabled, "VoteEnabled", false, true);
            Scribe_Values.Look(ref AutoConnect, "AutoConnect", false, true);
            Scribe_Values.Look(ref OtherStorytellersEnabled, "OtherStorytellersEnabled", false, true);
            Scribe_Values.Look(ref CommandsModsEnabled, "CommandsModsEnabled", true, true);
            Scribe_Values.Look(ref CommandsAliveEnabled, "CommandsAliveEnabled", true, true);
            Scribe_Values.Look(ref QuotesEnabled, "QuotesEnabled", true, true);

            Scribe_Values.Look(ref CoinInterval, "CoinInterval", 2, true);
            Scribe_Values.Look(ref CoinAmount, "CoinAmount", 30, true);
            Scribe_Values.Look(ref KarmaCap, "KarmaCap", 140, true);
            Scribe_Values.Look(ref MinimumPurchasePrice, "MinimumPurchasePrice", 60, true);
            Scribe_Values.Look(ref EventCooldownInterval, "EventCooldownInterval", 15, true);
            Scribe_Values.Look(ref StartingBalance, "StartingBalance", 150, true);
            Scribe_Values.Look(ref StartingKarma, "StartingKarma", 100, true);

            Scribe_Values.Look(ref CustomPricingSheetLink, "CustomPricingSheetLink", "https://bit.ly/2GT5daR", true);

            Scribe_Values.Look(ref EarningCoins, "EarningCoins", true, true);
            Scribe_Values.Look(ref StoreOpen, "StoreOpen", false, true);
            Scribe_Values.Look(ref GiftingCoins, "GiftingCoins", false, true);
            Scribe_Values.Look(ref WhisperCmdsAllowed, "WhisperCmdsAllowed", true, true);
            Scribe_Values.Look(ref WhisperCmdsOnly, "WhisperCmdsOnly", false, true);
            Scribe_Values.Look(ref PurchaseConfirmations, "PurchaseConfirmations", true, true);

            Scribe_Values.Look(ref JWTToken, "JWTToken", "", true);
            Scribe_Values.Look(ref AccountID, "AccountID", "", true);

            Scribe_Values.Look(ref MinifiableBuildings, "MinifiableBuildings", false, true);
            Scribe_Values.Look(ref UnlimitedCoins, "UnlimitedCoins", false, true);
            Scribe_Values.Look(ref EventsHaveCooldowns, "EventsHaveCooldowns", true, true);
            Scribe_Values.Look(ref RepeatViewerNames, "RepeatViewerNames", false, true);
            Scribe_Values.Look(ref LargeVotingWindow, "LargeVotingWindow", false, true);

            Scribe_Values.Look(ref BalanceCmd, "BalanceCmd", "!bal", true);
            Scribe_Values.Look(ref BuyeventCmd, "BuyeventCmd", "!buyevent", true);
            Scribe_Values.Look(ref BuyitemCmd, "BuyitemCmd", "!buyitem", true);
            Scribe_Values.Look(ref InstructionsCmd, "InstructionsCmd", "!instructions", true);
            Scribe_Values.Look(ref PurchaselistCmd, "PurchaselistCmd", "!purchaselist", true);
            Scribe_Values.Look(ref ModinfoCmd, "ModinfoCmd", "!modinfo", true);
            Scribe_Values.Look(ref ModsettingsCmd, "ModsettingsCmd", "!modsettings", true);
            Scribe_Values.Look(ref KarmaCmd, "KarmaCmd", "!whatiskarma", true);
            Scribe_Values.Look(ref GiftCmd, "GiftCmd", "!giftcoins", true);
            Scribe_Values.Look(ref CommandHelpCmd, "CommandHelpCmd", "!toolkitcmds", true);

            Scribe_Values.Look(ref VoteInterval, "VoteInterval", 5, true);

            Scribe_Collections.Look(ref ViewerIds, "ViewerIds", LookMode.Value, LookMode.Value);
            Scribe_Collections.Look(ref ViewerCoins, "ViewerCoins", LookMode.Value, LookMode.Value);
            Scribe_Collections.Look(ref ViewerKarma, "ViewerKarma", LookMode.Value, LookMode.Value);
            Scribe_Collections.Look(ref ViewerModerators, "ViewerModerators", LookMode.Value, LookMode.Value);

            Scribe_Collections.Look(ref ItemIds, "ItemIds", LookMode.Value, LookMode.Value);
            Scribe_Collections.Look(ref ItemPrices, "ItemPrices", LookMode.Value, LookMode.Value);
            Scribe_Collections.Look(ref ItemDefnames, "ItemDefnames", LookMode.Value, LookMode.Value);
            Scribe_Collections.Look(ref ItemStuffnames, "ItemStuffnames", LookMode.Value, LookMode.Value);

            Scribe_Collections.Look(ref ProductIds, "ProductIds", LookMode.Value, LookMode.Value);
            Scribe_Collections.Look(ref ProductTypes, "ProductTypes", LookMode.Value, LookMode.Value);
            Scribe_Collections.Look(ref ProductNames, "ProductNames", LookMode.Value, LookMode.Value);
            Scribe_Collections.Look(ref ProductKarmaTypes, "ProductKarmaTypes", LookMode.Value, LookMode.Value);
            Scribe_Collections.Look(ref ProductAmounts, "ProductAmounts", LookMode.Value, LookMode.Value);
            Scribe_Collections.Look(ref ProductEventIds, "ProductEventIds", LookMode.Value, LookMode.Value);
            Scribe_Collections.Look(ref ProductMaxEvents, "ProductMaxEvents", LookMode.Value, LookMode.Value);

            Scribe_Collections.Look(ref CategoryWeights, "CategoryWeights", LookMode.Value);


            if (ViewerIds == null)
            {
                ViewerIds   = new Dictionary <string, int>();
                ViewerCoins = new Dictionary <int, int>();
                ViewerKarma = new Dictionary <int, int>();
            }


            if (CategoryWeights == null)
            {
                CategoryWeights = Enumerable.Repeat <int>(100, _Categories.Count).ToList();
            }

            Scribe_Collections.Look(ref EventWeights, "EventWeights", LookMode.Value);
            if (EventWeights == null)
            {
                EventWeights = Events.GetEvents().ToDictionary(e => e.Id, e => 100);
            }

            if (listOfViewers == null)
            {
                listOfViewers = new List <Viewer>();
                foreach (KeyValuePair <string, int> viewer in ViewerIds)
                {
                    int    viewerkarma = ViewerKarma[viewer.Value];
                    int    viewercoins = ViewerCoins[viewer.Value];
                    Viewer newviewer   = new Viewer(viewer.Key, viewer.Value);
                    listOfViewers.Add(newviewer);
                }
            }

            if (products == null)
            {
                if (ProductIds == null || ProductMaxEvents == null)
                {
                    Helper.Log("Ressetting Products");
                    ResetProductData();
                    this.Write();
                }
                else
                {
                    Helper.Log("Loading Product Settings");
                    products = new List <Product>();
                    // load products from settings, then load them into settings class
                    foreach (KeyValuePair <string, int> product in ProductIds)
                    {
                        int       id        = product.Value;
                        string    abr       = product.Key;
                        int       type      = ProductTypes[id];
                        string    name      = ProductNames[id];
                        KarmaType karmatype = (KarmaType)ProductKarmaTypes[id];
                        int       amount    = ProductAmounts[id];
                        int       evtId     = ProductEventIds[id];
                        int       maxEvents = ProductMaxEvents[id];
                        products.Add(new Product(id, type, name, abr, karmatype, amount, evtId, maxEvents));
                    }
                }
            }

            if (items == null)
            {
                if (ItemIds == null)
                {
                    Helper.Log("Creating all items");
                    ResetItemData();
                    this.Write();
                }
                else
                {
                    Helper.Log("Loading items from settings");
                    items = new List <Item>();

                    foreach (KeyValuePair <string, int> item in ItemIds)
                    {
                        int    id        = item.Value;
                        string abr       = item.Key;
                        int    price     = ItemPrices[id];
                        string defname   = ItemDefnames[id];
                        string stuffname = ItemStuffnames[id];
                        items.Add(new Item(price, abr, defname, id, stuffname));
                    }
                }
            }
        }
예제 #7
0
        public ShopCommand(string message, Viewer viewer)
        {
            string[] command    = message.Split(' ');
            string   productabr = command[1];

            this.message = message;
            this.viewer  = viewer;

            Helper.Log($"debug {productabr.ToLower()}");
            this.product = Products.GetProduct(productabr.ToLower());

            if (this.product == null)
            {
                Helper.Log("Product is null");
                return;
            }

            Helper.Log("Configuring purchase");
            if (product.type == 0)
            { //event
                Helper.Log("Calculating price for event");
                if (this.product.amount < 0)
                {
                    return;
                }

                this.calculatedprice = this.product.amount;
                string[] chatmessage = command;
                craftedmessage = $"{this.viewer.username}: ";
                for (int i = 2; i < chatmessage.Length; i++)
                {
                    craftedmessage += chatmessage[i] + " ";
                }
                this.product.evt.chatmessage = craftedmessage;
            }
            else if (product.type == 1)
            { //item
                try
                {
                    Helper.Log("Trying ItemEvent Checks");

                    Item itemtobuy = Item.GetItemFromAbr(command[0]);

                    if (itemtobuy == null)
                    {
                        return;
                    }

                    if (itemtobuy.price < 0)
                    {
                        return;
                    }

                    int itemPrice       = itemtobuy.price;
                    int messageStartsAt = 3;

                    // check if 2nd index of command is a number
                    if (command.Count() > 2 && int.TryParse(command[2], out this.quantity))
                    {
                        messageStartsAt = 3;
                    }
                    else if (command.Count() == 2)
                    {
                        // short command
                        this.quantity   = 1;
                        messageStartsAt = 2;
                    }
                    else if (command[2] == "*")
                    {
                        Helper.Log("Getting max");
                        this.quantity   = this.viewer.GetViewerCoins() / itemtobuy.price;
                        messageStartsAt = 3;
                        Helper.Log(this.quantity);
                    }
                    else
                    {
                        this.quantity   = 1;
                        messageStartsAt = 2;
                        Helper.Log("Quantity not calculated");
                    }

                    string[] chatmessage = command;
                    craftedmessage = $"{this.viewer.username}: ";
                    for (int i = messageStartsAt; i < chatmessage.Length; i++)
                    {
                        craftedmessage += chatmessage[i] + " ";
                    }

                    try
                    {
                        if (itemPrice > 0)
                        {
                            Helper.Log($"item: {this.item} - price: {itemPrice} - quantity{this.quantity}");
                            this.calculatedprice = checked (itemtobuy.CalculatePrice(this.quantity));
                            this.itemtobuy       = itemtobuy;
                        }
                    }
                    catch (OverflowException e)
                    {
                        Helper.Log("overflow in calculated price " + e.Message);
                    }
                }
                catch (InvalidCastException e)
                {
                    Helper.Log("Invalid product or quantity - " + e.Message);
                }
            }

            if (this.calculatedprice <= 0)
            {
                // invalid price
                Helper.Log("Invalid price detected?");
            }
            else if (viewer.GetViewerCoins() < this.calculatedprice && !Settings.UnlimitedCoins)
            {
                // send message not enough coins
                this.errormessage = Helper.ReplacePlaceholder("TwitchToolkitNotEnoughCoins".Translate(), viewer: viewer.username, amount: this.calculatedprice.ToString(), first: viewer.GetViewerCoins().ToString());
            }
            else if (calculatedprice < Settings.MinimumPurchasePrice)
            {
                // does not meet minimum purchase price
                this.errormessage = Helper.ReplacePlaceholder("TwitchToolkitMinPurchaseNotMet".Translate(), viewer: this.viewer.username, amount: this.calculatedprice.ToString(), first: Settings.MinimumPurchasePrice.ToString());
            }
            else if (this.product.type == 0 && !this.product.evt.IsPossible())
            {
                this.errormessage = $"@{this.viewer.username} " + "TwitchToolkitEventNotPossible".Translate();
            }
            else if (this.product.maxEvents < 1 && Settings.EventsHaveCooldowns)
            {
                this.errormessage = $"@{this.viewer.username} " + "TwitchToolkitEventOnCooldown".Translate();
            }
            else
            {
                this.ExecuteCommand();
            }
        }