示例#1
0
        private static async Task <ICommandResult> CreateReminder(DiscordUserMessageContext context, string user, string message, DateTimeOffset targetTime)
        {
            IUser targetUser;

            if (context.Message.MentionedUserIds.Count > 0)
            {
                targetUser = await context.Channel.GetUserAsync(context.Message.MentionedUserIds.First());
            }
            else if (context.Message.Tags.Count > 0 && context.Message.Tags.First().Type == TagType.UserMention && (targetUser = context.Bot.Client.GetUser(context.Message.Tags.First().Key)) != null)
            {
            }
            else
            {
                targetUser = (SocketUser)await CommandTools.GetUserByUsername(user, context.Channel);
            }

            if (targetUser == null)
            {
                return(new ErrorResult("User not found"));
            }

            context.Bot.Reminders.Reminders.Add(
                new ReminderInfo
            {
                Message    = message,
                ReceiverId = targetUser.Id,
                SenderId   = context.Message.Author.Id,
                Timestamp  = targetTime
            });

            context.Bot.Reminders.SaveConfig();

            return(new SuccessResult($"Reminder set for {TimeZoneInfo.ConvertTimeBySystemTimeZoneId(targetTime, context.Bot.DefaultTimeZone):f}"));
        }
        protected void HandleKeystroke()
        {
            if (String.IsNullOrEmpty(settings.Command))
            {
                return;
            }

            if (settings.Command.Length == 1) // 1 Character is fine
            {
                return;
            }

            string macro = CommandTools.ExtractMacro(settings.Command, 0);

            if (string.IsNullOrEmpty(macro)) // Not a macro, save only first character
            {
                settings.Command = settings.Command[0].ToString();
                SaveSettings();
            }
            else
            {
                if (settings.Command != macro) // Save only one keystroke
                {
                    settings.Command = macro;
                    SaveSettings();
                }
            }
        }
示例#3
0
        private void HandleMacro(string macro)
        {
            var keyStrokes = CommandTools.ExtractKeyStrokes(macro);

            // Actually initiate the keystrokes
            if (keyStrokes.Count > 0)
            {
                var iis     = new InputSimulator();
                var keyCode = keyStrokes.Last();
                keyStrokes.Remove(keyCode);

                if (keyStrokes.Count > 0)
                {
                    //iis.Keyboard.ModifiedKeyStroke(keyStrokes.Select(ks => ks).ToArray(), keyCode);

                    iis.Keyboard.DelayedModifiedKeyStroke(keyStrokes.Select(ks => ks), keyCode, 40);
                }
                else // Single Keycode
                {
                    //iis.Keyboard.KeyPress(keyCode);

                    iis.Keyboard.DelayedKeyPress(keyCode, 40);
                }
            }
        }
示例#4
0
        ParseParams(List <string> parameters, CommandSenderInfo senderInfo)
        {
            // Parse /all parameter
            var all = parameters.Remove("/all");

            if (parameters.Count == 0)
            {
                throw new FriendlyMessageException(Resources.ErrorParameerCountNotValid);
            }

            // Parse prefab name
            var prefabName = parameters[0];

            // Verify existence of prefab files
            const string tts = global::Constants.cExtPrefabs; // Cannot interpolate in string: https://youtrack.jetbrains.com/issue/RSRP-465524

            if (!File.Exists(Path.Combine(Constants.PrefabsFolder, prefabName + ".xml")) ||
                !File.Exists(Path.Combine(Constants.PrefabsFolder, prefabName + tts)))
            {
                throw new FriendlyMessageException($"Could not find {prefabName}.xml/{tts} in {Constants.PrefabsFolder}.");
            }

            // Verify existence and validity of tile entity file
            if (all)
            {
                var fileName = prefabName + Export.TileEntityFileExtension;
                var filePath = Path.Combine(Constants.PrefabsFolder, fileName);
                if (!File.Exists(filePath))
                {
                    throw new FriendlyMessageException($"Could not find {fileName} in prefabs folder. This prefab does not have block metadata available, so you cannot use the /all option.");
                }
            }

            // Parse coordinates
            Vector3i pos1;

            if (parameters.Count == 1 || parameters.Count == 2)
            {
                pos1 = senderInfo.GetRemoteClientInfo().GetEntityPlayer().GetServerPos().ToVector3i();
            }
            else if (parameters.Count == 4 || parameters.Count == 5)
            {
                pos1 = CommandTools.ParseXYZ(parameters, 1);
            }
            else
            {
                throw new FriendlyMessageException(Resources.ErrorParameerCountNotValid);
            }

            // Parse rotation
            var rotate = 0;

            if (parameters.Count == 2 || parameters.Count == 5)
            {
                rotate = parameters[parameters.Count - 1].ToInt()
                         ?? throw new FriendlyMessageException("Rotation value is not valid. Allowed values: 0, 1, 2, or 3");
            }

            return(prefabName, pos1, rotate, all);
        }
示例#5
0
        public override void Execute(List <string> parameters, CommandSenderInfo senderInfo)
        {
            TelemetryTools.CollectEvent("command", "execute", GetCommands()[0]);
            try
            {
                var world      = GameManager.Instance.World ?? throw new FriendlyMessageException(Resources.ErrorWorldNotReady);
                var chunkCache = world.ChunkCache ?? throw new FriendlyMessageException(Resources.ErrorChunkCacheNotReady);

                (var pos1, var pos2) = ParseParams(parameters, senderInfo);
                WorldTools.OrderAreaBounds(ref pos1, ref pos2);

                // Check if all needed chunks are in cache
                foreach (var chunkKey in GetChunksForArea(pos1, pos2, +1))
                {
                    if (!chunkCache.ContainsChunkSync(chunkKey))
                    {
                        throw new FriendlyMessageException(Resources.ErrorAreaTooFarAway);
                    }
                }

                ThreadManager.AddSingleTask(info => RegenerateChunks(pos1, pos2, senderInfo));
            }
            catch (Exception ex)
            {
                CommandTools.HandleCommandException(ex);
            }
        }
示例#6
0
        public Embed GetEmbed(DiscordMessageContext context)
        {
            var builer = new EmbedBuilder
            {
                Title       = "Poll",
                Color       = new Color(76, 175, 80),
                Description = $"Vote using `{CommandTools.GetCommandPrefix(context, context.Channel)}{(Anonymous ? $"anonvote {Id}" : "vote")} <option number|option text>`{(Anonymous ? $"\n**__ONLY VOTES FROM A DIRECT MESSAGE TO ME WILL BE COUNTED!__**\nThis is **anonymous poll number #{Id}.**" : "")}",
                Footer      = new EmbedFooterBuilder
                {
                    Text = $"The poll will end in {TimeSpan.FromMinutes(MinutesLeft).ToLongString()} unless stopped earlier with '{CommandTools.GetCommandPrefix(context, context.Channel)}endpoll'"
                },
                Author = new EmbedAuthorBuilder
                {
                    Name    = Creator.NicknameOrUsername(),
                    IconUrl = Creator.AvatarUrlOrDefaultAvatar()
                }
            };

            for (int i = 0; i < Options.Count; i++)
            {
                builer.AddField((i + 1).ToString(), Options[i].Text, true);
            }

            if (TotalVotes > 0)
            {
                builer.AddField("Already Voted", string.Join(", ", Voters.Select(voter => voter.Key.NicknameOrUsername())));
            }

            return(builer.Build());
        }
示例#7
0
        public static async Task <ICommandResult> DynamicMessage(DiscordUserMessageContext context, [DisplayName("interval (minutes)"), HelpText("How often to run the command")] ulong interval, [JoinRemainingParameters, HelpText("The command to run")] string command)
        {
            if (interval == 0)
            {
                return(new ErrorResult("Interval must be greater than zero"));
            }

            var message = await context.Channel.SendMessageAsync($"Loading dynamic message with command '{command}'");

            List <DynamicMessageInfo> dynamicMessages = context.Bot.DynamicMessages.Messages ?? new List <DynamicMessageInfo>();

            dynamicMessages.Add(new DynamicMessageInfo
            {
                GuildId        = context.Guild.Id,
                ChannelId      = message.Channel.Id,
                MessageId      = message.Id,
                UpdateInterval = interval,
                CommandText    = command
            });
            context.Bot.DynamicMessages.Messages = dynamicMessages;
            context.Bot.DynamicMessages.SaveConfig();

            await message.ModifyAsync(msg => msg.Content = "Loading complete, this message will be updated with dynamic content Soon:tm:");

            var dynamicMessageContext = new DiscordDynamicMessageContext(message, context.Bot, command);
            await CommandRunner.Run(command, dynamicMessageContext, CommandTools.GetCommandPrefix(dynamicMessageContext, message.Channel), false);

            return(new SuccessResult());
        }
示例#8
0
        public override void Execute(List <string> parameters, CommandSenderInfo senderInfo)
        {
            TelemetryTools.CollectEvent("command", "execute", GetCommands()[0]);
            try
            {
                if (parameters.Count == 0)
                {
                    SdtdConsole.Instance.Output($"Patch for {CorpseDupe.PatchName} is {(PersistentData.Instance.PatchCorpseItemDupeExploit ? "ENABLED" : "DISABLED")}.");
                    return;
                }

                if (parameters.Count == 1 || parameters.Count > 2)
                {
                    throw new FriendlyMessageException(Resources.ErrorParameerCountNotValid);
                }

                var    patchName = parameters[0];
                string mode      = parameters[1];

                if (mode != "/on" && mode != "/off")
                {
                    throw new FriendlyMessageException($"Wrong second parameter \"{parameters[1]}\". See help.");
                }

                switch (patchName)
                {
                case "corpse-dupe":
                    if (mode == "/on")
                    {
                        if (PersistentData.Instance.PatchCorpseItemDupeExploit)
                        {
                            throw new FriendlyMessageException($"Patch for {CorpseDupe.PatchName} is already enabled.");
                        }
                        PersistentData.Instance.PatchCorpseItemDupeExploit = true;
                        PatchTools.ApplyPatches();
                        PersistentData.Instance.Save();     // save after patching in case something crashes
                        SdtdConsole.Instance.Output($"Patch for {CorpseDupe.PatchName} enabled.");
                    }
                    else if (mode == "/off")
                    {
                        if (!PersistentData.Instance.PatchCorpseItemDupeExploit)
                        {
                            throw new FriendlyMessageException($"Patch for {CorpseDupe.PatchName} is already disabled.");
                        }
                        PersistentData.Instance.PatchCorpseItemDupeExploit = false;
                        PersistentData.Instance.Save();
                        SdtdConsole.Instance.Output($"Patch for {CorpseDupe.PatchName} disabled.");
                    }
                    break;

                default:
                    throw new FriendlyMessageException($"Unknown patch name \"{patchName}\". See help.");
                }
            }
            catch (Exception ex)
            {
                CommandTools.HandleCommandException(ex);
            }
        }
示例#9
0
        public static bool Prefix([NotNull] EntityAlive __instance, DamageResponse _dmResponse)
        {
            Log.Debug($"Executing patch prefix for {nameof(EntityDamaged)} ...");

            ScriptEvent eventType;

            if (__instance is EntityPlayer)
            {
                eventType = ScriptEvent.playerDamaged;
            }
            else if (__instance is EntityAnimal || __instance is EntityZombieDog || __instance is EntityEnemyAnimal || __instance is EntityHornet)
            {
                eventType = ScriptEvent.animalDamaged;
            }
            else if (__instance is EntityZombie)
            {
                eventType = ScriptEvent.zombieDamaged;
            }
            else
            {
                return(true);
            }

            CommandTools.InvokeScriptEvents(eventType, () =>
            {
                var sourceEntity     = GameManager.Instance.World?.GetEntity(_dmResponse.Source?.getEntityId() ?? -1) as EntityAlive;
                var targetClientInfo = ConnectionManager.Instance?.GetClientInfoForEntityId(__instance.entityId);
                var sourceClientInfo = ConnectionManager.Instance?.GetClientInfoForEntityId(sourceEntity?.entityId ?? -1);

                return(new EntityDamagedEventArgs
                {
                    position = __instance.GetBlockPosition(),
                    entityId = __instance.entityId,
                    entityName = __instance.EntityName,
                    entitySteamId = targetClientInfo?.playerId,
                    sourceEntityId = sourceEntity?.entityId,
                    sourceEntityName = sourceEntity?.EntityName,
                    sourceEntitySteamId = sourceClientInfo?.playerId,
                    damageType = _dmResponse.Source?.GetName().ToString(),
                    hitBodyPart = _dmResponse.HitBodyPart.ToString(),
                    hitDirection = _dmResponse.HitDirection.ToString(),
                    damage = _dmResponse.Strength,
                    armorDamage = _dmResponse.ArmorDamage,
                    armorSlot = _dmResponse.ArmorSlot.ToString(),
                    stunType = _dmResponse.Stun.ToString(),
                    stunDuration = _dmResponse.StunDuration,
                    critical = _dmResponse.Critical,
                    fatal = _dmResponse.Fatal,
                    crippleLegs = _dmResponse.CrippleLegs,
                    dismember = _dmResponse.Dismember,
                    turnIntoCrawler = _dmResponse.TurnIntoCrawler,
                    painHit = _dmResponse.PainHit,
                });
            });

            return(true);
        }
示例#10
0
        public static bool Prepare()
        {
            if (!CommandTools.IsAnyEventActive(ScriptEvent.playerDamaged, ScriptEvent.animalDamaged, ScriptEvent.zombieDamaged))
            {
                Log.Debug($"Patch {nameof(EntityDamaged)} is disabled.");
                return(false);
            }

            Log.Out($"Injecting event tracker {nameof(EntityDamaged)} ...");
            return(true);
        }
示例#11
0
        public static bool Prepare()
        {
            if (!CommandTools.IsAnyEventActive(ScriptEvent.playerLevelUp, ScriptEvent.playerExpGained))
            {
                Log.Debug($"Patch {nameof(PlayerStatsChanged)} is disabled.");
                return(false);
            }

            Log.Out($"Injecting event tracker {nameof(PlayerStatsChanged)} ...");
            return(true);
        }
示例#12
0
        public static bool Prepare()
        {
            if (!CommandTools.IsAnyEventActive(ScriptEvent.playerEnteredChunk))
            {
                Log.Debug($"Patch {nameof(PlayerEnteredChunk)} is disabled.");
                return(false);
            }

            Log.Out($"Injecting event tracker {nameof(PlayerEnteredChunk)} ...");
            return(true);
        }
        protected async void SendInput(string inputText)
        {
            if (String.IsNullOrEmpty(inputText))
            {
                return;
            }

            inputRunning = true;
            await Task.Run(() =>
            {
                InputSimulator iis = new InputSimulator();
                string text        = inputText;

                if (settings.IgnoreNewline)
                {
                    text = text.Replace("\r\n", "\n").Replace("\n", "");
                }
                else if (settings.EnterMode)
                {
                    text = text.Replace("\r\n", "\n");
                }

                for (int idx = 0; idx < text.Length && !forceStop; idx++)
                {
                    if (settings.EnterMode && text[idx] == '\n')
                    {
                        iis.Keyboard.KeyPress(WindowsInput.Native.VirtualKeyCode.RETURN);
                    }
                    else if (text[idx] == CommandTools.MACRO_START_CHAR)
                    {
                        string macro = CommandTools.ExtractMacro(text, idx);
                        if (String.IsNullOrWhiteSpace(macro)) // Not a macro, just input the character
                        {
                            InputChar(iis, text[idx]);
                        }
                        else // This is a macro, run it
                        {
                            idx  += macro.Length - 1;
                            macro = macro.Substring(1, macro.Length - 2);

                            HandleMacro(macro);
                        }
                    }
                    else
                    {
                        InputChar(iis, text[idx]);
                    }
                    Thread.Sleep(settings.Delay);
                }
            });

            inputRunning = false;
        }
 public override void Execute(List <string> _params, CommandSenderInfo _senderInfo)
 {
     TelemetryTools.CollectEvent("command", "execute", GetCommands()[0]);
     try
     {
         _action(_params, _senderInfo);
     }
     catch (Exception ex)
     {
         CommandTools.HandleCommandException(ex);
     }
 }
示例#15
0
 /// <summary>
 /// Called when the game is in the process of shutting down, after connections were closed and resources were unloaded.
 /// </summary>
 public override void GameShutdown()
 {
     try
     {
         Log.Debug("Api.GameShutdown called.");
         TelemetryTools.Shutdown();
         CommandTools.InvokeScriptEvents(ScriptEvent.gameShutdown, () => new ScriptEventArgs());
     }
     catch (Exception ex)
     {
         CommandTools.HandleEventException(ex);
     }
 }
示例#16
0
        private void SendInputUp(string inputText)
        {
            var text = inputText;

            for (var idx = 0; idx < text.Length && !ForceStop; idx++)
            {
                var macro = CommandTools.ExtractMacro(text, idx);
                idx  += macro.Length - 1;
                macro = macro.Substring(1, macro.Length - 2);

                HandleMacroUp(macro);
            }
        }
        public override void Execute(List <string> parameters, CommandSenderInfo senderInfo)
        {
            TelemetryTools.CollectEvent("command", "execute", GetCommands()[0]);
            try
            {
                if (parameters.Count == 0)
                {
                    ListWhitelist();
                }
                else if (parameters.Count == 1)
                {
                    if (parameters[0] == "clear")
                    {
                        ClearWhitelist();
                    }
                    else
                    {
                        throw new FriendlyMessageException("Could not understand parameter. See help dj-eac-whitelist.");
                    }
                }
                else if (parameters.Count == 2)
                {
                    // ParseParamPartialNameOrId already sends error message when none or too many users were found
                    if (ConsoleHelper.ParseParamPartialNameOrId(parameters[1], out string steamId, out ClientInfo clientInfo, true) != 1)
                    {
                        return;
                    }

                    if (parameters[0] == "add")
                    {
                        AddToWhitelist(steamId);
                    }
                    else if (parameters[0] == "remove")
                    {
                        RemoveFromWhitelist(steamId);
                    }
                    else
                    {
                        throw new FriendlyMessageException("Could not understand first parameter. See help dj-eac-whitelist.");
                    }
                }
                else
                {
                    throw new FriendlyMessageException(Resources.ErrorParameerCountNotValid);
                }
            }
            catch (Exception ex)
            {
                CommandTools.HandleCommandException(ex);
            }
        }
示例#18
0
        public override void Execute(List <string> parameters, CommandSenderInfo senderInfo)
        {
            TelemetryTools.CollectEvent("command", "execute", GetCommands()[0]);
            string prefabName    = null;
            bool   exportStarted = false;

            try
            {
                Vector3i pos1, pos2;
                (prefabName, pos1, pos2) = ParseParams(parameters, senderInfo);
                WorldTools.OrderAreaBounds(ref pos1, ref pos2);
                // Saving tile entities first, because that also checks if chunks are loaded
                exportStarted = true;
                SaveTileEntities(prefabName, pos1, pos2);
                SavePrefab(prefabName, pos1, pos2);

                SdtdConsole.Instance.Output($"Prefab {prefabName} with block metadata exported. Area mapped from {pos1} to {pos2}.");
            }
            catch (Exception ex)
            {
                // Clean up half-writen files. All or nothing.
                if (exportStarted && !string.IsNullOrEmpty(prefabName))
                {
                    try
                    {
                        var teFilePath = Path.Combine(Constants.PrefabsFolder, prefabName + TileEntityFileExtension);
                        if (File.Exists(teFilePath))
                        {
                            File.Delete(teFilePath);
                        }
                        var ttsFilePath = Path.Combine(Constants.PrefabsFolder, prefabName + global::Constants.cExtPrefabs);
                        if (File.Exists(ttsFilePath))
                        {
                            File.Delete(ttsFilePath);
                        }
                        var xmlFilePath = Path.Combine(Constants.PrefabsFolder, prefabName + ".xml");
                        if (File.Exists(xmlFilePath))
                        {
                            File.Delete(xmlFilePath);
                        }
                    }
                    catch (Exception)
                    {
                        Log.Warning("Exception thrown while cleaning up files because of another exception: " + ex);
                    }
                }

                CommandTools.HandleCommandException(ex);
            }
        }
示例#19
0
        public void ForwardCommand(string command, string[] args)
        {
            var fullCommand = string.Join(" ", args);
            var result      = CommandTools.ExecuteCommand(fullCommand);

            if (!string.IsNullOrEmpty(result))
            {
                Console.WriteLine(result);
            }
            else
            {
                NotRecognised();
            }
        }
示例#20
0
 public override void Execute(List <string> parameters, CommandSenderInfo senderInfo)
 {
     TelemetryTools.CollectEvent("command", "execute", GetCommands()[0]);
     try
     {
         var ci     = senderInfo.RemoteClientInfo ?? throw new FriendlyMessageException(Resources.ErrorNotRemotePlayer);
         var world  = GameManager.Instance.World ?? throw new FriendlyMessageException(Resources.ErrorWorldNotReady);
         var player = senderInfo.RemoteClientInfo.GetEntityPlayer();
     }
     catch (Exception ex)
     {
         CommandTools.HandleCommandException(ex);
     }
 }
示例#21
0
        public override void Execute(List <string> parameters, CommandSenderInfo senderInfo)
        {
            TelemetryTools.CollectEvent("command", "execute", GetCommands()[0]);
            try
            {
                ParseParams(parameters, out var tasks, out bool simulate, out bool auto, out int?timerInterval);
                timerInterval = timerInterval ?? 60 * 10; // every 10 minutes by default

                if (auto)
                {
                    if (!PersistentData.Instance.RepairAuto)
                    {
                        PersistentData.Instance.RepairAuto     = true;
                        PersistentData.Instance.RepairTasks    = tasks;
                        PersistentData.Instance.RepairSimulate = simulate;
                        PersistentData.Instance.RepairInterval = timerInterval.Value; // every 10 minutes by default;
                        PersistentData.Instance.Save();
                        RepairEngine.AutoOn();
                    }
                    else
                    {
                        RepairEngine.AutoOff();
                        PersistentData.Instance.RepairAuto    = false;
                        PersistentData.Instance.RepairCounter = 0;
                        PersistentData.Instance.Save();
                    }
                }
                else
                {
                    ThreadManager.AddSingleTask(delegate
                    {
                        try
                        {
                            var repairEngine = new RepairEngine(tasks, simulate, senderInfo);
                            repairEngine.Start();
                        }
                        catch (Exception ex)
                        {
                            Log.Exception(ex);
                            SdtdConsole.Instance.OutputAsync(senderInfo, string.Format(Resources.ErrorDuringCommand, ex.Message));
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                CommandTools.HandleCommandException(ex);
            }
        }
示例#22
0
 /// <summary>
 /// Called when a player has disconnected from the game and all associated game data is about to be unloaded.
 /// A chat message has not yet been distributed and "steamPlayerDisconnected" was not yet invoked.
 /// </summary>
 /// <param name="clientInfo"></param>
 /// <param name="shutdown"></param>
 public override void PlayerDisconnected(ClientInfo clientInfo, bool shutdown)
 {
     try
     {
         Log.Debug("Api.PlayerDisconnected called.");
         CommandTools.InvokeScriptEvents(ScriptEvent.playerDisconnected, () => new PlayerDisconnectedEventArgs()
         {
             clientInfo = clientInfo,
         });
     }
     catch (Exception ex)
     {
         CommandTools.HandleEventException(ex);
     }
 }
示例#23
0
        protected void RunCommand(string commandString)
        {
            try
            {
                if (string.IsNullOrEmpty(commandString))
                {
                    Logger.Instance.LogMessage(TracingLevel.WARN, $"Command not configured");
                    return;
                }
                counter = autoStopNum;

                if (commandString.Length == 1)
                {
                    Task.Run(() => SimulateTextEntry(commandString[0]));
                }
                else // KeyStroke
                {
                    List <VirtualKeyCodeContainer> keyStrokes = CommandTools.ExtractKeyStrokes(commandString);

                    // Actually initiate the keystrokes
                    if (keyStrokes.Count > 0)
                    {
                        VirtualKeyCodeContainer keyCode = keyStrokes.Last();
                        keyStrokes.Remove(keyCode);

                        if (keyStrokes.Count > 0)
                        {
                            Task.Run(() => SimulateKeyStroke(keyStrokes.Select(ks => ks.KeyCode).ToArray(), keyCode.KeyCode));
                        }
                        else
                        {
                            if (keyCode.IsExtended)
                            {
                                Task.Run(() => SimulateExtendedMacro(keyCode));
                            }
                            else
                            {
                                Task.Run(() => SimulateKeyDown(keyCode.KeyCode));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Instance.LogMessage(TracingLevel.ERROR, $"RunCommand Exception: {ex}");
            }
        }
示例#24
0
        public override void Execute(List <string> parameters, CommandSenderInfo senderInfo)
        {
            TelemetryTools.CollectEvent("command", "execute", GetCommands()[0]);
            try
            {
                var modInfo = Api.GetExecutingMod()?.ModInfo;
                if (modInfo == null)
                {
                    SdtdConsole.Instance.Output(Constants.ModName);
                    SdtdConsole.Instance.Output("Could not load mod infos.");
                }
                else
                {
                    // ReSharper disable once UnreachableCode
                    SdtdConsole.Instance.Output(modInfo.Name.Value + " - Version " + modInfo.Version.Value + (Log.IsDebug ? " DEBUG" : ""));
                    if (modInfo.Name.Value != Constants.ModName)
                    {
                        SdtdConsole.Instance.Output("Original mod name: " + Constants.ModName);
                    }
                    SdtdConsole.Instance.Output(modInfo.Description.Value);
                    if (!string.IsNullOrEmpty(modInfo.Website.Value))
                    {
                        SdtdConsole.Instance.Output("Website: " + modInfo.Website.Value);
                    }
                }

                SdtdConsole.Instance.Output("");

                SdtdConsole.Instance.Output("Operating System: " + Environment.OSVersion);
                SdtdConsole.Instance.Output("Unity version: " + Application.unityVersion);

                var displayName = Type.GetType("Mono.Runtime")?.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static);
                if (displayName != null)
                {
                    SdtdConsole.Instance.Output("Mono display name: " + displayName.Invoke(null, null));
                }

                var monoRuntimeVersion = Type.GetType("Mono.Runtime")?.Assembly.ImageRuntimeVersion;
                if (monoRuntimeVersion != null)
                {
                    SdtdConsole.Instance.Output("Mono runtime version: " + monoRuntimeVersion);
                }
            }
            catch (Exception ex)
            {
                CommandTools.HandleCommandException(ex);
            }
        }
示例#25
0
        public static bool Prefix(Chunk __instance, Entity _entity)
        {
            Log.Debug($"Executing patch prefix {nameof(PlayerEnteredChunk)} ...");

            if (_entity is EntityPlayer player)
            {
                CommandTools.InvokeScriptEvents(ScriptEvent.playerEnteredChunk, () => new PlayerEnteredChunkEventArgs()
                {
                    newChunk   = new Vector2xz(__instance.X, __instance.Z),
                    oldChunk   = new Vector2xz(_entity.chunkPosAddedEntityTo.x, _entity.chunkPosAddedEntityTo.z),
                    position   = player.GetBlockPosition(),
                    clientInfo = ConnectionManager.Instance?.GetClientInfoForEntityId(player.entityId),
                });
            }
            return(true);
        }
示例#26
0
 /// <summary>
 /// Called when a player has connected but before he was authenticated with Steam. Do not trust the clientInfo data!
 /// </summary>
 /// <param name="clientInfo"></param>
 /// <param name="compatibilityVersion"></param>
 public override void PlayerLogin(ClientInfo clientInfo, string compatibilityVersion)
 {
     try
     {
         Log.Debug("Api.PlayerLogin called.");
         CommandTools.InvokeScriptEvents(ScriptEvent.playerLogin, () => new PlayerLoginEventArgs()
         {
             clientInfo           = clientInfo,
             compatibilityVersion = compatibilityVersion,
         });
     }
     catch (Exception ex)
     {
         CommandTools.HandleEventException(ex);
     }
 }
示例#27
0
 /// <summary>
 /// Called when the player was authenticated and its entity was created ("entityLoaded" event) but before the player
 /// becomes visible and the loading screen disappears. During spawning all required chunks and entites are loaded.
 /// </summary>
 /// <param name="clientInfo"></param>
 /// <param name="chunkViewDim"></param>
 /// <param name="playerProfile"></param>
 public override void PlayerSpawning(ClientInfo clientInfo, int chunkViewDim, PlayerProfile playerProfile)
 {
     try
     {
         Log.Debug("Api.PlayerSpawning called.");
         CommandTools.InvokeScriptEvents(ScriptEvent.playerSpawning, () => new PlayerSpawningEventArgs()
         {
             clientInfo    = clientInfo,
             playerProfile = playerProfile,
         });
     }
     catch (Exception ex)
     {
         CommandTools.HandleEventException(ex);
     }
 }
示例#28
0
        /// <summary>
        /// Called during game start on every mod, before the World is ready (GameManager.Instance.World == null)
        /// </summary>
        public override void GameAwake()
        {
            try
            {
                Log.Debug("Api.GameAwake called.");
                Log.Out("Initializing phase 2/3 ...");
                CommandTools.InitScripts();
                PatchTools.ApplyPatches();
                CommandTools.InitScriptsMonitoring();

                CommandTools.InvokeScriptEvents(ScriptEvent.gameAwake, () => new ScriptEventArgs());
            }
            catch (Exception ex)
            {
                CommandTools.HandleEventException(ex);
            }
        }
示例#29
0
 /// <summary>
 /// Called when the map for the chunk was calculated by generating a pixel color for each of the 16x16 blocks.
 /// The map can be retrieved with chunk.GetMapColors().
 /// </summary>
 /// <param name="chunk"></param>
 public override void CalcChunkColorsDone(Chunk chunk)
 {
     try
     {
         // No logging to avoid spam
         // Log.Debug("Api.CalcChunkColorsDone called.");
         CommandTools.InvokeScriptEvents(ScriptEvent.chunkMapCalculated, () => new ChunkMapCalculatedEventArgs()
         {
             chunkKey = chunk.Key,
             chunkPos = ChunkTools.ChunkKeyToChunkXZ(chunk.Key),
         });
     }
     catch (Exception ex)
     {
         CommandTools.HandleEventException(ex);
     }
 }
示例#30
0
 /// <summary>
 /// Called when the player was made visible and the loading screen disappeared.
 /// </summary>
 /// <param name="clientInfo"></param>
 /// <param name="respawnReason"></param>
 /// <param name="pos"></param>
 public override void PlayerSpawnedInWorld(ClientInfo clientInfo, RespawnType respawnReason, Vector3i pos)
 {
     try
     {
         Log.Debug("Api.PlayerSpawnedInWorld called.");
         CommandTools.InvokeScriptEvents(ScriptEvent.playerSpawnedInWorld, () => new PlayerSpawnedInWorldEventArgs()
         {
             reason     = respawnReason.ToString(),
             position   = pos,
             clientInfo = clientInfo,
         });
     }
     catch (Exception ex)
     {
         CommandTools.HandleEventException(ex);
     }
 }