From 11d12dcfb0e2324638bada299a4767b11baa31b9 Mon Sep 17 00:00:00 2001 From: Cai <13110818005@qq.com> Date: Sun, 2 Nov 2025 22:44:02 +0800 Subject: [PATCH 1/2] fix(Login): prevent duplicate login request --- CaiBotLiteMod/Moudles/TSPlayer.cs | 49 ++----------------------------- CaiBotLiteMod/Services/Login.cs | 1 + CaiBotLiteMod/Services/Packet.cs | 17 +++++++---- 3 files changed, 14 insertions(+), 53 deletions(-) diff --git a/CaiBotLiteMod/Moudles/TSPlayer.cs b/CaiBotLiteMod/Moudles/TSPlayer.cs index ee607a6..175d03b 100644 --- a/CaiBotLiteMod/Moudles/TSPlayer.cs +++ b/CaiBotLiteMod/Moudles/TSPlayer.cs @@ -262,54 +262,9 @@ protected TSPlayer(string playerName) this.AwaitingResponse = new Dictionary>(); } - /// - /// Used in preventing players from seeing the npc spawnrate permission error on join. - /// - internal bool HasReceivedNPCPermissionError { get; set; } - - /// - /// The amount of tiles that the player has killed in the last second. - /// - public int TileKillThreshold { get; set; } - - /// - /// The amount of tiles the player has placed in the last second. - /// - public int TilePlaceThreshold { get; set; } - - /// - /// The amount of liquid (in tiles) that the player has placed in the last second. - /// - public int TileLiquidThreshold { get; set; } - - /// - /// The amount of tiles that the player has painted in the last second. - /// - public int PaintThreshold { get; set; } - - /// - /// The number of projectiles created by the player in the last second. - /// - public int ProjectileThreshold { get; set; } - - /// - /// The number of HealOtherPlayer packets sent by the player in the last second. - /// - public int HealOtherThreshold { get; set; } - - /// - /// Whether to ignore packets that are SSC-relevant. - /// - public bool IgnoreSSCPackets { get; set; } - - /// - /// A queue of tiles destroyed by the player for reverting. - /// - /// - /// The player's group. - /// + public bool LoginQueue { get; set; } - public bool ReceivedInfo { get; set; } + public bool SSCLogin { get; set; } /// /// The players index in the player array( Main.players[] ). diff --git a/CaiBotLiteMod/Services/Login.cs b/CaiBotLiteMod/Services/Login.cs index ac7fb40..aefa411 100644 --- a/CaiBotLiteMod/Services/Login.cs +++ b/CaiBotLiteMod/Services/Login.cs @@ -38,6 +38,7 @@ internal static bool CheckWhitelist(string name, WhiteListResult result) case WhiteListResult.Accept: { Console.WriteLine($"[Cai白名单]玩家[{name}](IP: {player.IP})已通过白名单验证..."); + player.IsLoggedIn = true; break; } case WhiteListResult.NotInWhitelist: diff --git a/CaiBotLiteMod/Services/Packet.cs b/CaiBotLiteMod/Services/Packet.cs index 40b1ce3..11182de 100644 --- a/CaiBotLiteMod/Services/Packet.cs +++ b/CaiBotLiteMod/Services/Packet.cs @@ -29,14 +29,13 @@ public override bool HijackGetData(ref byte messageType, ref BinaryReader Reader CaiBotLiteMod.Players[playerNumber] = new TSPlayer(playerNumber); break; case MessageID.RequestWorldData: - if (Config.Settings.WhiteList && !player!.SscLogin) + if (Config.Settings.WhiteList && !player!.SSCLogin) { return true; } break; case MessageID.SyncPlayer: - - if (!Config.Settings.WhiteList || !player!.SscLogin || player.IsLoggedIn) + if (!Config.Settings.WhiteList || !player!.SSCLogin || player.LoginQueue || player.IsLoggedIn) { return false; } @@ -54,6 +53,9 @@ public override bool HijackGetData(ref byte messageType, ref BinaryReader Reader return false; } + + player.LoginQueue = true; + new PackageWriter(PackageType.Whitelist, false, null) .Write("player_name", name) .Write("player_ip", player.IP) @@ -63,7 +65,8 @@ public override bool HijackGetData(ref byte messageType, ref BinaryReader Reader case MessageID.ClientUUID: player!.UUID = reader.ReadString(); - if (!Config.Settings.WhiteList) + + if (!Config.Settings.WhiteList || player.LoginQueue || player.IsLoggedIn) { return false; } @@ -73,7 +76,7 @@ public override bool HijackGetData(ref byte messageType, ref BinaryReader Reader Netplay.Clients[player.Index].State = 2; NetMessage.SendData(MessageID.WorldData, player.Index); Main.SyncAnInvasion(player.Index); - player.SscLogin = true; + player.SSCLogin = true; player.SendWarningMessage("[CaiBotLite]服务器已开启白名单,请使用已绑定的人物名字!"); return false; } @@ -92,7 +95,9 @@ public override bool HijackGetData(ref byte messageType, ref BinaryReader Reader return false; } - + + player.LoginQueue = true; + new PackageWriter(PackageType.Whitelist, false, null) .Write("player_name", player.Name) .Write("player_ip", player.IP) From fb0a6ea60e1313993be5b2671310fc7bc0919fa4 Mon Sep 17 00:00:00 2001 From: Cai <13110818005@qq.com> Date: Sun, 2 Nov 2025 22:44:47 +0800 Subject: [PATCH 2/2] chore: clean up --- CaiBotLiteMod/CaiBotCommands.cs | 8 +- CaiBotLiteMod/CaiBotLiteMod.cs | 5 +- CaiBotLiteMod/CaiBotLiteMod.csproj | 3 + CaiBotLiteMod/Moudles/Package.cs | 4 +- CaiBotLiteMod/Moudles/TSPlayer.cs | 418 ++-------------------------- CaiBotLiteMod/Services/CaiBotApi.cs | 27 +- CaiBotLiteMod/Services/Login.cs | 9 +- CaiBotLiteMod/Services/Packet.cs | 3 +- 8 files changed, 58 insertions(+), 419 deletions(-) diff --git a/CaiBotLiteMod/CaiBotCommands.cs b/CaiBotLiteMod/CaiBotCommands.cs index 30735ad..6e092b6 100644 --- a/CaiBotLiteMod/CaiBotCommands.cs +++ b/CaiBotLiteMod/CaiBotCommands.cs @@ -12,7 +12,7 @@ public override CommandType Type public override string Command => "生成绑定码"; - + public override string Description => "生成一个CaiBot绑定码"; @@ -29,16 +29,16 @@ public override CommandType Type public override string Command => "t"; - + public override string Description => "Test"; public override void Action(CommandCaller caller, string input, string[] args) { - Console.WriteLine(JsonConvert.SerializeObject(ModLoader.Mods.Where(i=> i!=null).Select(i=> i.Name))); + Console.WriteLine(JsonConvert.SerializeObject(ModLoader.Mods.Where(i => i != null).Select(i => i.Name))); var mod = ModLoader.GetMod("MagicStorage"); var asset = mod.Assets.GetLoadedAssets(); - + Console.WriteLine(asset.Length); } } \ No newline at end of file diff --git a/CaiBotLiteMod/CaiBotLiteMod.cs b/CaiBotLiteMod/CaiBotLiteMod.cs index dd8a95e..4ed455a 100644 --- a/CaiBotLiteMod/CaiBotLiteMod.cs +++ b/CaiBotLiteMod/CaiBotLiteMod.cs @@ -12,7 +12,7 @@ public class CaiBotLiteMod : Mod { internal static int InitCode = -1; internal static bool DebugMode; - + public static readonly Version PluginVersion = ModLoader.GetMod("CaiBotLiteMod").Version; public static readonly TSPlayer?[] Players = new TSPlayer[256]; @@ -23,6 +23,7 @@ public override void Load() { return; } + DebugMode = Program.LaunchParameters.ContainsKey("-caidebug"); Config.Settings.Read(); Config.Settings.Write(); @@ -40,7 +41,7 @@ public override void Unload() WebsocketManager.WebSocket.Dispose(); ExecuteCommandHook.Dispose(); } - + public static void GenCode() { diff --git a/CaiBotLiteMod/CaiBotLiteMod.csproj b/CaiBotLiteMod/CaiBotLiteMod.csproj index fb70ea2..af370bf 100644 --- a/CaiBotLiteMod/CaiBotLiteMod.csproj +++ b/CaiBotLiteMod/CaiBotLiteMod.csproj @@ -15,6 +15,9 @@ lib\SixLabors.ImageSharp.dll + + + diff --git a/CaiBotLiteMod/Moudles/Package.cs b/CaiBotLiteMod/Moudles/Package.cs index ffa4204..f496d62 100644 --- a/CaiBotLiteMod/Moudles/Package.cs +++ b/CaiBotLiteMod/Moudles/Package.cs @@ -51,9 +51,9 @@ public T Read(string key) { if (Enum.GetNames(typeof(T)).Any(name => string.Equals(name, "Unknown", StringComparison.OrdinalIgnoreCase))) { - return (T)Enum.Parse(typeof(T), "Unknown", true); + return (T) Enum.Parse(typeof(T), "Unknown", true); } - + throw new InvalidCastException($"Cannot convert string '{stringValue}' to enum {typeof(T).Name}", ex); } } diff --git a/CaiBotLiteMod/Moudles/TSPlayer.cs b/CaiBotLiteMod/Moudles/TSPlayer.cs index 175d03b..b88a010 100644 --- a/CaiBotLiteMod/Moudles/TSPlayer.cs +++ b/CaiBotLiteMod/Moudles/TSPlayer.cs @@ -16,55 +16,21 @@ You should have received a copy of the GNU General Public License along with this program. If not, see . */ -using CaiBotLiteMod.Services; using Microsoft.Xna.Framework; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; -using System.Text.RegularExpressions; -using System.Threading; -using System.Timers; using Terraria; using Terraria.Chat; using Terraria.DataStructures; -using Terraria.GameContent.Creative; using Terraria.ID; using Terraria.Localization; -using Timer = System.Timers.Timer; using Color = System.Drawing.Color; -using Point = System.Drawing.Point; using Rectangle = System.Drawing.Rectangle; namespace CaiBotLiteMod.Moudles; -/// -/// Bitflags used with the method -/// -[Flags] -public enum DisableFlags -{ - /// - /// Disable the player and leave no messages - /// - None, - - /// - /// Write the Disable message to the console - /// - WriteToConsole, - - /// - /// Write the Disable message to the log - /// - WriteToLog, - - /// - /// Equivalent to WriteToConsole | WriteToLog - /// - WriteToLogAndConsole -} - public class TSPlayer { /// @@ -83,18 +49,6 @@ public class TSPlayer private readonly Player FakePlayer = null!; - private int _respawnTimer; - - /// - /// Whether the player is accepting whispers from other users - /// - public bool AcceptingWhispers = true; - - /// - /// Represents the ID of the chest that the player is viewing. - /// - public int ActiveChest = -1; - /// /// A list of command callbacks indexed by the command they need to do. @@ -103,146 +57,17 @@ public class TSPlayer private string CacheIP = null!; - /// - /// Players controls are inverted if using SSC - /// - public bool Confused = false; - - public string Country = "??"; - /// /// Contains data stored by plugins /// protected ConcurrentDictionary data = new (); - /// - /// Whether the player should see logs. - /// - public bool DisplayLogs = true; - - - /// - /// Whether the player has been nagged about logging in. - /// - public bool HasBeenNaggedAboutLoggingIn; /// /// Whether the player is logged in or not. /// public bool IsLoggedIn; - /// - /// Represents the current item the player is holding. - /// - public Item ItemInHand = new (); - - private DateTime LastDisableNotification = DateTime.UtcNow; - - /// - /// The last projectile type this player tried to kill. - /// - public int LastKilledProjectile = 0; - - /// - /// The player's last known position from PlayerUpdate packet. - /// - public Vector2 LastNetPosition = Vector2.Zero; - - - /// - /// The last time the player was warned for build permissions. - /// In MS, defaults to 1 (so it will warn on the first attempt). - /// - public long lastPermissionWarning = 1; - - /// - /// The last time the player changed their team or pvp status. - /// - public DateTime LastPvPTeamChange; - - /// - /// The last player that the player whispered with (to or from). - /// - public TSPlayer LastWhisper = null!; - - /// - /// Whether the player has been harrassed about logging in due to server side inventory or forced login. - /// - public bool LoginHarassed = false; - - /// - /// The time in ms when the player has logged in. - /// - public long LoginMS; - - /// - /// Whether the player is muted or not. - /// - public bool mute; - - /// - /// A timer to keep track of whether or not the player has recently thrown an explosive - /// - public int RecentFuse = 0; - - public bool RequestedSection; - - /// - /// Easy check if a player has any of IsDisabledForSSC, IsDisabledForStackDetection, IsDisabledForBannedWearable, - /// or IsDisabledPendingTrashRemoval set. Or if they're not logged in and a login is required. - /// - /// - /// If any of the checks that warrant disabling are set on this player. If true, Disable() is repeatedly called on - /// them. - /// - /// - /// Whether the player needs to specify a password upon connection( either server or user account ). - /// - public bool RequiresPassword; - - /// - /// A system to delay Remembered Position Teleports a few seconds - /// - public int RPPending = 0; - - public bool SilentJoinInProgress; - - public bool SilentKickInProgress; - - public bool SscLogin = false; - - public int sX = -1; - public int sY = -1; - - /// - /// Unused. - /// - public Vector2 TeleportCoords = new (-1, -1); - - /// - /// The player's temporary group. This overrides the user's actual group. - /// - public Group tempGroup = null!; - - public Timer tempGroupTimer = null!; - - /// - /// Temp points for use in regions and other plugins. - /// - public Point[] TempPoints = new Point[2]; - - /// - /// Whether other players can teleport to the player. - /// - public bool TPAllow = true; - - /// - /// Logs the player out of an account. - /// - /// - /// Initializes a new instance of the class. - /// - /// The player's index in the. public TSPlayer(int index) { this.Index = index; @@ -255,7 +80,7 @@ public TSPlayer(int index) /// Initializes a new instance of the class. /// /// The player's name. - protected TSPlayer(string playerName) + private TSPlayer(string playerName) { this.Index = -1; this.FakePlayer = new Player { name = playerName, whoAmI = -1 }; @@ -267,52 +92,16 @@ protected TSPlayer(string playerName) public bool SSCLogin { get; set; } /// - /// The players index in the player array( Main.players[] ). + /// The players index in the player array. /// - public int Index { get; protected set; } + public int Index { get; } - /// - /// Whether the player is waiting to place/break a tile to set as a temp point. - /// - public int AwaitingTempPoint { get; set; } - - public bool AwaitingName { get; set; } - - public string[] AwaitingNameParameters { get; set; } = null!; /// /// The last time a player broke a grief check. /// public DateTime LastThreat { get; set; } - /// - /// The number of unsuccessful login attempts. - /// - public int LoginAttempts { get; set; } - - /// - /// UserAccount object associated with the player. - /// Set when the player logs in. - /// - /// - /// Whether the player performed a valid login attempt (i.e. entered valid user name and password) but is still blocked - /// from logging in because of SSI. - /// - public bool LoginFailsBySsi { get; set; } - - /// - /// Whether the player has sent their whole inventory to the server while connecting. - /// - public bool HasSentInventory { get; set; } - - /// - /// The player's respawn timer. - /// - public int RespawnTimer - { - get => this._respawnTimer; - set => this.TPlayer.respawnTimer = (this._respawnTimer = value) * 60; - } /// /// Whether the player is dead or not. @@ -325,37 +114,9 @@ public string UUID set => UUIDs[this.Index] = value; } - /// - /// The players difficulty( normal[softcore], mediumcore, hardcore ). - /// - public int Difficulty => this.TPlayer.difficulty; - - /// - /// Controls the journey godmode - /// - public bool GodMode - { - get => - CreativePowerManager.Instance.GetPower().IsEnabledForPlayer(this.Index); - set => - CreativePowerManager.Instance.GetPower().SetEnabledState(this.Index, value); - } - /// - /// Whether the player is a real, human, player on the server. - /// public bool RealPlayer => this.Index >= 0 && this.Index < Main.maxNetPlayers && Main.player[this.Index] != null; - /// - /// Checks if the player is active and not pending termination. - /// - public bool ConnectionAlive => - this.RealPlayer && this.Client is { IsActive: true, PendingTermination: false }; - - /// - /// Gets the item that the player is currently holding. - /// - public Item SelectedItem => this.TPlayer.inventory[this.TPlayer.selectedItem]; /// /// Gets the player's Client State. @@ -374,16 +135,13 @@ public string IP { get { - if (string.IsNullOrEmpty(this.CacheIP)) - { - return this.CacheIP = (this.RealPlayer + return string.IsNullOrEmpty(this.CacheIP) + ? this.CacheIP = this.RealPlayer ? this.Client.Socket.IsConnected() ? this.Client.Socket.GetRemoteAddress().ToString()!.Split(':')[0] : "" - : "127.0.0.1")!; - } - - return this.CacheIP; + : "127.0.0.1" + : this.CacheIP; } } @@ -648,23 +406,11 @@ public object RemoveData(string key) /// Disconnects the player from the server. /// /// The reason why the player was disconnected. - public virtual void Disconnect(string reason) + public void Disconnect(string reason) { this.SendData(MessageID.Kick, reason); } - /// - /// Fired when the player's temporary group access expires. - /// - /// - /// - public void TempGroupTimerElapsed(object sender, ElapsedEventArgs args) - { - this.SendWarningMessage("Your temporary group access has expired."); - - this.tempGroup = null!; - ((Timer) sender)?.Stop(); - } /// /// Teleports the player to the given coordinates in the world. @@ -726,7 +472,7 @@ public void Heal(int health = 600) [Obsolete( "This method may not send tiles the way you would expect it to. The (x,y) coordinates are the top left corner of the tile square, switch to " + nameof(SendTileSquareCentered) + " if you wish for the coordindates to be the center of the square.")] - public virtual bool SendTileSquare(int x, int y, int size = 10) + public bool SendTileSquare(int x, int y, int size = 10) { return this.SendTileRect((short) x, (short) y, (byte) size, (byte) size); } @@ -741,7 +487,7 @@ public virtual bool SendTileSquare(int x, int y, int size = 10) /// The y coordinates of the center of the square. /// The size square set of tiles to send. /// true if the tile square was sent successfully, else false - public virtual bool SendTileSquareCentered(int x, int y, byte size = 10) + public bool SendTileSquareCentered(int x, int y, byte size = 10) { return this.SendTileRect((short) (x - (size / 2)), (short) (y - (size / 2)), size, size); } @@ -755,7 +501,7 @@ public virtual bool SendTileSquareCentered(int x, int y, byte size = 10) /// The length of the rectangle /// Optional change type. Default None /// - public virtual bool SendTileRect(short x, short y, byte width = 10, byte length = 10, + public bool SendTileRect(short x, short y, byte width = 10, byte length = 10, TileChangeType changeType = TileChangeType.None) { try @@ -815,7 +561,7 @@ public void UpdateSection(Rectangle? rectangle = null, bool isLoaded = false) /// The item ID. /// The item stack. /// The item prefix. - public virtual void GiveItem(int type, int stack, int prefix = 0) + public void GiveItem(int type, int stack, int prefix = 0) { this.GiveItemByDrop(type, stack, prefix); } @@ -859,7 +605,7 @@ private void GiveItemByDrop(int type, int stack, int prefix) /// Sends an information message to the player. /// /// The message. - public virtual void SendInfoMessage(string? msg) + public void SendInfoMessage(string? msg) { this.SendMessage(msg, Color.Yellow); } @@ -879,7 +625,7 @@ public void SendInfoMessage(string format, params object[] args) /// Sends a success message to the player. /// /// The message. - public virtual void SendSuccessMessage(string? msg) + public void SendSuccessMessage(string? msg) { this.SendMessage(msg, Color.LimeGreen); } @@ -899,7 +645,7 @@ public void SendSuccessMessage(string format, params object[] args) /// Sends a warning message to the player. /// /// The message. - public virtual void SendWarningMessage(string? msg) + public void SendWarningMessage(string? msg) { this.SendMessage(msg, Color.OrangeRed); } @@ -919,7 +665,7 @@ public void SendWarningMessage(string format, params object[] args) /// Sends an error message to the player. /// /// The message. - public virtual void SendErrorMessage(string? msg) + public void SendErrorMessage(string? msg) { this.SendMessage(msg, Color.Red); } @@ -940,7 +686,7 @@ public void SendErrorMessage(string format, params object[] args) /// /// The message. /// The message color. - public virtual void SendMessage(string? msg, Color color) + public void SendMessage(string? msg, Color color) { this.SendMessage(msg!, color.R, color.G, color.B); } @@ -952,7 +698,7 @@ public virtual void SendMessage(string? msg, Color color) /// The amount of red color to factor in. Max: 255. /// The amount of green color to factor in. Max: 255 /// The amount of blue color to factor in. Max: 255 - public virtual void SendMessage(string msg, byte red, byte green, byte blue) + public void SendMessage(string msg, byte red, byte green, byte blue) { if (msg.Contains("\n")) { @@ -985,7 +731,7 @@ public virtual void SendMessage(string msg, byte red, byte green, byte blue) /// The amount of green color to factor in. Max: 255. /// The amount of blue color to factor in. Max: 255. /// The player who receives the message. - public virtual void SendMessageFromPlayer(string msg, byte red, byte green, byte blue, int ply) + public void SendMessageFromPlayer(string msg, byte red, byte green, byte blue, int ply) { if (msg.Contains("\n")) { @@ -1007,7 +753,7 @@ public virtual void SendMessageFromPlayer(string msg, byte red, byte green, byte /// Wounds the player with the given damage. /// /// The amount of damage the player will take. - public virtual void DamagePlayer(int damage) + public void DamagePlayer(int damage) { this.DamagePlayer(damage, PlayerDeathReason.LegacyDefault()); } @@ -1017,7 +763,7 @@ public virtual void DamagePlayer(int damage) /// /// The amount of damage the player will take. /// The reason for causing damage to player. - public virtual void DamagePlayer(int damage, PlayerDeathReason reason) + public void DamagePlayer(int damage, PlayerDeathReason reason) { NetMessage.SendPlayerHurt(this.Index, new Player.HurtInfo { Damage = damage, DamageSource = reason }); } @@ -1025,7 +771,7 @@ public virtual void DamagePlayer(int damage, PlayerDeathReason reason) /// /// Kills the player. /// - public virtual void KillPlayer() + public void KillPlayer() { this.KillPlayer(PlayerDeathReason.LegacyDefault()); } @@ -1034,7 +780,7 @@ public virtual void KillPlayer() /// Kills the player. /// /// Reason for killing a player. - public virtual void KillPlayer(PlayerDeathReason reason) + public void KillPlayer(PlayerDeathReason reason) { NetMessage.SendPlayerDeath(this.Index, reason, 99999, new Random().Next(-1, 1), false); } @@ -1043,7 +789,7 @@ public virtual void KillPlayer(PlayerDeathReason reason) /// Sets the player's team. /// /// The team color index. - public virtual void SetTeam(int team) + public void SetTeam(int team) { if (team < 0 || team >= Main.teamColor.Length) { @@ -1059,7 +805,7 @@ public virtual void SetTeam(int team) /// /// The state of the pvp mode. /// Whether a chat message about the change should be sent. - public virtual void SetPvP(bool mode, bool withMsg = false) + public void SetPvP(bool mode, bool withMsg = false) { Main.player[this.Index].hostile = mode; NetMessage.SendData(MessageID.TogglePVP, -1, -1, NetworkText.Empty, this.Index); @@ -1088,29 +834,13 @@ public void SendMultipleMatchError(IEnumerable matches) } - /// - /// Annoys the player for a specified amount of time. - /// - /// The - public virtual void Whoopie(object time) - { - var time2 = (int) time; - var launch = DateTime.UtcNow; - var startname = this.Name; - while ((DateTime.UtcNow - launch).TotalSeconds < time2 && startname == this.Name) - { - this.SendData(MessageID.MiscDataSync, number: this.Index, number2: 2f); - Thread.Sleep(50); - } - } - /// /// Applies a buff to the player. /// /// The buff type. /// The buff duration. /// - public virtual void SetBuff(int type, int time = 3600, bool bypass = false) + public void SetBuff(int type, int time = 3600, bool bypass = false) { if ((DateTime.UtcNow - this.LastThreat).TotalMilliseconds < 5000 && !bypass) { @@ -1131,10 +861,10 @@ public virtual void SetBuff(int type, int time = 3600, bool bypass = false) /// /// /// - public virtual void SendData(byte msgType, string text = "", int number = 0, float number2 = 0f, + public void SendData(byte msgType, string? text = "", int number = 0, float number2 = 0f, float number3 = 0f, float number4 = 0f, int number5 = 0) { - if (this.RealPlayer && !this.ConnectionAlive) + if (this.RealPlayer) { return; } @@ -1143,35 +873,13 @@ public virtual void SendData(byte msgType, string text = "", int number = 0, flo number2, number3, number4, number5); } - /// - /// Sends data from the given player. - /// - /// The sent packet. - /// The packet sender. - /// The packet text. - /// - /// - /// - /// - public virtual void SendDataFromPlayer(byte msgType, int ply, string text = "", float number2 = 0f, - float number3 = 0f, float number4 = 0f, int number5 = 0) - { - if (this.RealPlayer && !this.ConnectionAlive) - { - return; - } - - NetMessage.SendData((int) msgType, this.Index, -1, NetworkText.FromFormattable(text), ply, number2, number3, number4, - number5); - } - /// /// Sends raw data to the player's socket object. /// /// The data to send. - public virtual void SendRawData(byte[] data) + public void SendRawData(byte[] data) { - if (!this.RealPlayer || !this.ConnectionAlive) + if (!this.RealPlayer) { return; } @@ -1179,75 +887,9 @@ public virtual void SendRawData(byte[] data) this.Client.Socket.AsyncSend(data, 0, data.Length, this.Client.ServerWriteCallBack); } - /// - /// Adds a command callback to a specified command string. - /// - /// The string representing the command i.e "yes" == /yes - /// The method that will be executed on confirmation ie user accepts - public void AddResponse(string name, Action callback) - { - if (this.AwaitingResponse.ContainsKey(name)) - { - this.AwaitingResponse.Remove(name); - } - - this.AwaitingResponse.Add(name, callback); - } public void Kick(string reason) { NetMessage.SendData(MessageID.Kick, this.Index, -1, NetworkText.FromLiteral(reason)); } - - private enum BuildPermissionFailPoint - { - GeneralBuild, - SpawnProtect, - Regions - } -} - -public class TSRestPlayer : TSPlayer -{ - internal List CommandOutput = []; - - public TSRestPlayer(string playerName, Group playerGroup) : base(playerName) - { - this.AwaitingResponse = new Dictionary>(); - } - - public override void SendMessage(string? msg, Color color) - { - this.SendMessage(msg, color.R, color.G, color.B); - } - - public override void SendMessage(string? msg, byte red, byte green, byte blue) - { - this.CommandOutput.Add(msg); - } - - public override void SendInfoMessage(string? msg) - { - this.SendMessage(msg, Color.Yellow); - } - - public override void SendSuccessMessage(string? msg) - { - this.SendMessage(msg, Color.Green); - } - - public override void SendWarningMessage(string? msg) - { - this.SendMessage(msg, Color.OrangeRed); - } - - public override void SendErrorMessage(string? msg) - { - this.SendMessage(msg, Color.Red); - } - - public List GetCommandOutput() - { - return this.CommandOutput; - } } \ No newline at end of file diff --git a/CaiBotLiteMod/Services/CaiBotApi.cs b/CaiBotLiteMod/Services/CaiBotApi.cs index c6956b8..d3eaca8 100644 --- a/CaiBotLiteMod/Services/CaiBotApi.cs +++ b/CaiBotLiteMod/Services/CaiBotApi.cs @@ -39,7 +39,7 @@ public static async Task HandleMessageAsync(string receivedData) case PackageType.CallCommand: var command = package.Read("command"); var userOpenId = package.Read("user_open_id"); - var groupOpenId = package.Read("group_open_id"); + var groupOpenId = package.Read("group_open_id"); var caller = new CaiBotCommandCaller(); ExecuteCommandHook.StartHook = true; @@ -63,7 +63,7 @@ public static async Task HandleMessageAsync(string receivedData) .Write("output", ExecuteCommandHook.GetCommandOutput()) .Send(); break; - + case PackageType.PlayerList: var bigBossList = BossCheckList.GetBossList().Where(x => x is { IsBoss: true, IsMiniboss: false }).OrderByDescending(x => x.Progression).ToList(); var onlineProcess = "不可用"; @@ -72,7 +72,6 @@ public static async Task HandleMessageAsync(string receivedData) if (bigBossList[0].Downed()) { onlineProcess = "已毕业"; - } else if (!bigBossList[^1].Downed()) { @@ -89,19 +88,19 @@ public static async Task HandleMessageAsync(string receivedData) } } } - } + packetWriter .Write("server_name", string.IsNullOrEmpty(Main.worldName) ? "地图还没加载捏~" : Main.worldName) - .Write("player_list",Main.player.Where(x => x is { active: true }).Select(x => x.name)) + .Write("player_list", Main.player.Where(x => x is { active: true }).Select(x => x.name)) .Write("current_online", Main.player.Count(x => x is { active: true })) .Write("max_online", Main.maxNetPlayers) - .Write("process",Config.Settings.ShowProcessInPlayerList?onlineProcess:"") + .Write("process", Config.Settings.ShowProcessInPlayerList ? onlineProcess : "") .Send(); break; case PackageType.Progress: - var bossList = BossCheckList.GetBossList().Where(x => x.IsBoss && !x.IsMiniboss).OrderBy(x => x.Progression).ToList(); + var bossList = BossCheckList.GetBossList().Where(x => x is { IsBoss: true, IsMiniboss: false }).OrderBy(x => x.Progression).ToList(); var eventList = BossCheckList.GetBossList().Where(x => x.IsEvent || x.IsMiniboss).OrderBy(x => x.Progression).ToList(); if (bossList.Count == 0) { @@ -126,7 +125,7 @@ public static async Task HandleMessageAsync(string receivedData) var whitelistResult = package.Read("whitelist_result"); Login.CheckWhitelist(name, whitelistResult); break; - + case PackageType.SelfKick: var selfKickName = package.Read("name"); var kickPlr = CaiBotLiteMod.Players.FirstOrDefault(x => x?.Name == selfKickName); @@ -145,7 +144,7 @@ public static async Task HandleMessageAsync(string receivedData) var imageBytes = ms.ToArray(); var base64 = Convert.ToBase64String(imageBytes); packetWriter - .Write("result",Utils.CompressBase64(base64)) + .Write("result", Utils.CompressBase64(base64)) .Send(); } @@ -181,16 +180,15 @@ public static async Task HandleMessageAsync(string receivedData) .Send(); break; - } case PackageType.LookBag: var lookBagName = package.Read("player_name"); var playerList3 = TSPlayer.FindByNameOrID("tsn:" + lookBagName); - + packetWriter .Write("is_text", true) .Write("name", lookBagName); - + if (playerList3.Count != 0) { var plr = playerList3[0].TPlayer; @@ -222,9 +220,8 @@ public static async Task HandleMessageAsync(string receivedData) catch (Exception ex) { Console.WriteLine($"[CaiBotLite] 处理BOT数据包时出错:\n" + - $"{ex}\n" + - $"源数据包: {receivedData}"); + $"{ex}\n" + + $"源数据包: {receivedData}"); } - } } \ No newline at end of file diff --git a/CaiBotLiteMod/Services/Login.cs b/CaiBotLiteMod/Services/Login.cs index aefa411..0302129 100644 --- a/CaiBotLiteMod/Services/Login.cs +++ b/CaiBotLiteMod/Services/Login.cs @@ -44,7 +44,6 @@ internal static bool CheckWhitelist(string name, WhiteListResult result) case WhiteListResult.NotInWhitelist: { Console.WriteLine($"[Cai白名单]玩家[{name}](IP: {player.IP})没有添加白名单..."); - player.SilentKickInProgress = true; player.Disconnect($"[Cai白名单]没有添加白名单!\n" + $"请在群{groupId}内发送\"/添加白名单 角色名字\""); return false; @@ -52,7 +51,6 @@ internal static bool CheckWhitelist(string name, WhiteListResult result) case WhiteListResult.InGroupBlacklist: { Console.WriteLine($"[Cai白名单]玩家[{name}](IP: {player.IP})被屏蔽,处于群黑名单中..."); - player.SilentKickInProgress = true; player.Disconnect("[Cai白名单]你已被服务器屏蔽\n" + "你处于本群黑名单中!"); return false; @@ -60,7 +58,6 @@ internal static bool CheckWhitelist(string name, WhiteListResult result) case WhiteListResult.InBotBlacklist: { Console.WriteLine($"[Cai白名单]玩家[{name}](IP: {player.IP})被屏蔽,处于全局黑名单中..."); - player.SilentKickInProgress = true; player.Disconnect("[Cai白名单]你已被Bot屏蔽\n" + "你处于全局黑名单中!"); return false; @@ -68,7 +65,6 @@ internal static bool CheckWhitelist(string name, WhiteListResult result) case WhiteListResult.NeedLogin: { Console.WriteLine($"[Cai白名单]玩家[{name}](IP: {player.IP})使用未授权的设备..."); - player.SilentKickInProgress = true; player.Disconnect($"[Cai白名单]未授权设备!\n" + $"在群{groupId}内发送'/登录'\n" + $"以批准此设备登录"); @@ -78,7 +74,6 @@ internal static bool CheckWhitelist(string name, WhiteListResult result) default: { Console.WriteLine($"[Cai白名单]玩家[{name}](IP: {player.IP})无效登录结果[{result}], 可能是适配插件版本过低..."); - player.SilentKickInProgress = true; player.Disconnect($"[Cai白名单]登录出错!" + $"无法处理登录结果: {result}"); @@ -90,7 +85,7 @@ internal static bool CheckWhitelist(string name, WhiteListResult result) { Console.WriteLine($"[Cai白名单]玩家[{name}](IP: {player.IP})验证白名单时出现错误...\n" + $"{ex}"); - player.SilentKickInProgress = true; + player.Disconnect($"[Cai白名单]服务器发生错误无法处理该请求!\n" + $"请尝试重新加入游戏或者联系服务器群{groupId}管理员"); return false; @@ -98,4 +93,4 @@ internal static bool CheckWhitelist(string name, WhiteListResult result) return true; } -} +} \ No newline at end of file diff --git a/CaiBotLiteMod/Services/Packet.cs b/CaiBotLiteMod/Services/Packet.cs index 11182de..c7b9b51 100644 --- a/CaiBotLiteMod/Services/Packet.cs +++ b/CaiBotLiteMod/Services/Packet.cs @@ -33,6 +33,7 @@ public override bool HijackGetData(ref byte messageType, ref BinaryReader Reader { return true; } + break; case MessageID.SyncPlayer: if (!Config.Settings.WhiteList || !player!.SSCLogin || player.LoginQueue || player.IsLoggedIn) @@ -86,7 +87,7 @@ public override bool HijackGetData(ref byte messageType, ref BinaryReader Reader player.Kick("[Cai白名单]玩家名获取失败!"); return false; } - + if (!WebsocketManager.IsWebsocketConnected) { Console.WriteLine("[CaiBotLite]机器人处于未连接状态, 玩家无法加入。\n" +