Fix all warnings & Trim (#2226)

* Fix AutoFishing crash
* Fix all warnings
* Remove DotNetZip.
* Fix the usage of HttpClient.
This commit is contained in:
BruceChen 2022-10-02 18:31:08 +08:00 committed by GitHub
parent 4aa6c1c99f
commit 1d52d1eadd
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
227 changed files with 2201 additions and 43564 deletions

View file

@ -1,9 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using static System.Net.WebRequestMethods;
namespace MinecraftClient.ChatBots
{
@ -12,8 +8,8 @@ namespace MinecraftClient.ChatBots
/// </summary>
public class Alerts : ChatBot
{
private string[] dictionary = new string[0];
private string[] excludelist = new string[0];
private string[] dictionary = Array.Empty<string>();
private string[] excludelist = Array.Empty<string>();
private bool logToFile = false;
/// <summary>

View file

@ -10,14 +10,14 @@ namespace MinecraftClient.ChatBots
public class AntiAFK : ChatBot
{
private int count;
private string pingparam;
private readonly string pingparam;
private int timeping = 600;
private int timepingMax = -1;
private bool useTerrainHandling = false;
private bool previousSneakState = false;
private int walkRange = 5;
private int walkRetries = 10;
private Random random = new Random();
private readonly int walkRetries = 10;
private readonly Random random = new();
/// <summary>
/// This bot sends a /ping command every X seconds in order to stay non-afk.
@ -57,7 +57,7 @@ namespace MinecraftClient.ChatBots
else
{
// Handle the random range
if (pingparam.Contains("-"))
if (pingparam.Contains('-'))
{
string[] parts = pingparam.Split("-");
@ -85,10 +85,7 @@ namespace MinecraftClient.ChatBots
if (timepingMax != -1 && timeping > timepingMax)
{
int temporary = timepingMax;
timepingMax = timeping;
timeping = temporary;
(timeping, timepingMax) = (timepingMax, timeping);
LogToConsole(Translations.TryGet("bot.antiafk.swapping"));
}

View file

@ -1,7 +1,7 @@
using MinecraftClient.Mapping;
using System;
using System;
using System.Collections.Generic;
using System.IO;
using MinecraftClient.Mapping;
namespace MinecraftClient.ChatBots
{
@ -10,22 +10,22 @@ namespace MinecraftClient.ChatBots
/// </summary>
class AutoAttack : ChatBot
{
private Dictionary<int, Entity> entitiesToAttack = new Dictionary<int, Entity>(); // mobs within attack range
private readonly Dictionary<int, Entity> entitiesToAttack = new(); // mobs within attack range
private int attackCooldown = 6;
private int attackCooldownCounter = 6;
private Double attackSpeed = 4;
private Double attackCooldownSeconds;
private bool overrideAttackSpeed = false;
private int attackRange = 4;
private readonly bool overrideAttackSpeed = false;
private readonly int attackRange = 4;
private Double serverTPS;
private float health = 100;
private bool singleMode = true;
private bool priorityDistance = true;
private InteractType interactMode;
private bool attackHostile = true;
private bool attackPassive = false;
private string listMode = "blacklist";
private List<EntityType> listedEntites = new();
private readonly bool singleMode = true;
private readonly bool priorityDistance = true;
private readonly InteractType interactMode;
private readonly bool attackHostile = true;
private readonly bool attackPassive = false;
private readonly string listMode = "blacklist";
private readonly List<EntityType> listedEntites = new();
public AutoAttack(
string mode, string priority, bool overrideAttackSpeed = false, double cooldownSeconds = 1, InteractType interaction = InteractType.Attack)
@ -53,13 +53,13 @@ namespace MinecraftClient.ChatBots
else
{
this.overrideAttackSpeed = overrideAttackSpeed;
this.attackCooldownSeconds = cooldownSeconds;
attackCooldownSeconds = cooldownSeconds;
attackCooldown = Convert.ToInt32(Math.Truncate(attackCooldownSeconds / 0.1) + 1);
}
}
this.attackHostile = Settings.AutoAttack_Attack_Hostile;
this.attackPassive = Settings.AutoAttack_Attack_Passive;
attackHostile = Settings.AutoAttack_Attack_Hostile;
attackPassive = Settings.AutoAttack_Attack_Passive;
if (Settings.AutoAttack_ListMode.Length > 0)
{
@ -140,7 +140,7 @@ namespace MinecraftClient.ChatBots
if (entitiesToAttack.ContainsKey(priorityEntity))
{
// check entity distance and health again
if (shouldAttackEntity(entitiesToAttack[priorityEntity]))
if (ShouldAttackEntity(entitiesToAttack[priorityEntity]))
{
InteractEntity(priorityEntity, interactMode); // hit the entity!
SendAnimation(Inventory.Hand.MainHand); // Arm animation
@ -152,7 +152,7 @@ namespace MinecraftClient.ChatBots
foreach (KeyValuePair<int, Entity> entity in entitiesToAttack)
{
// check that we are in range once again.
if (shouldAttackEntity(entity.Value))
if (ShouldAttackEntity(entity.Value))
{
InteractEntity(entity.Key, interactMode); // hit the entity!
}
@ -169,7 +169,7 @@ namespace MinecraftClient.ChatBots
public override void OnEntitySpawn(Entity entity)
{
shouldAttackEntity(entity);
ShouldAttackEntity(entity);
}
public override void OnEntityDespawn(Entity entity)
@ -209,7 +209,7 @@ namespace MinecraftClient.ChatBots
if (listedEntites.Count > 0)
{
bool inList = listedEntites.Contains(entity.Type);
result = listMode.Equals("blacklist") ? (inList ? false : result) : (inList ? true : false);
result = listMode.Equals("blacklist") ? (!inList && result) : (inList);
}
return result;
@ -217,7 +217,7 @@ namespace MinecraftClient.ChatBots
public override void OnEntityMove(Entity entity)
{
shouldAttackEntity(entity);
ShouldAttackEntity(entity);
}
public override void OnHealthUpdate(float health, int food)
@ -262,7 +262,7 @@ namespace MinecraftClient.ChatBots
/// </summary>
/// <param name="entity">The entity to handle</param>
/// <returns>If the entity should be attacked</returns>
public bool shouldAttackEntity(Entity entity)
public bool ShouldAttackEntity(Entity entity)
{
if (!IsAllowedToAttack(entity) || entity.Health <= 0)
return false;

View file

@ -1,8 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Linq;
using MinecraftClient.Inventory;
using MinecraftClient.Mapping;
@ -16,23 +15,23 @@ namespace MinecraftClient.ChatBots
private bool craftingFailed = false;
private int inventoryInUse = -2;
private int index = 0;
private Recipe recipeInUse;
private List<ActionStep> actionSteps = new List<ActionStep>();
private Recipe? recipeInUse;
private readonly List<ActionStep> actionSteps = new();
private Location tableLocation = new Location();
private Location tableLocation = new();
private bool abortOnFailure = true;
private int updateDebounceValue = 2;
private int updateDebounce = 0;
private int updateTimeoutValue = 10;
private readonly int updateTimeoutValue = 10;
private int updateTimeout = 0;
private string timeoutAction = "unspecified";
private string configPath = @"autocraft\config.ini";
private readonly string configPath = @"autocraft\config.ini";
private string lastRecipe = ""; // Used in parsing recipe config
private Dictionary<string, Recipe> recipes = new Dictionary<string, Recipe>();
private readonly Dictionary<string, Recipe> recipes = new();
private void resetVar()
private void ResetVar()
{
craftingFailed = false;
waitingForTable = false;
@ -123,9 +122,10 @@ namespace MinecraftClient.ChatBots
/// Materials needed and their position
/// </summary>
/// <remarks>position start with 1, from left to right, top to bottom</remarks>
public Dictionary<int, ItemType> Materials;
public Dictionary<int, ItemType>? Materials;
public Recipe() { }
public Recipe(Dictionary<int, ItemType> materials, ItemType resultItem, ContainerType type)
{
Materials = materials;
@ -141,7 +141,7 @@ namespace MinecraftClient.ChatBots
/// <remarks>so that it can be used in crafting table</remarks>
public static Recipe ConvertToCraftingTable(Recipe recipe)
{
if (recipe.CraftingAreaType == ContainerType.PlayerInventory)
if (recipe.CraftingAreaType == ContainerType.PlayerInventory && recipe.Materials != null)
{
if (recipe.Materials.ContainsKey(4))
{
@ -202,7 +202,7 @@ namespace MinecraftClient.ChatBots
string name = args[1];
if (recipes.ContainsKey(name))
{
resetVar();
ResetVar();
PrepareCrafting(recipes[name]);
return "";
}
@ -221,32 +221,26 @@ namespace MinecraftClient.ChatBots
else return GetHelp();
}
private string GetHelp()
private static string GetHelp()
{
return Translations.Get("bot.autoCraft.available_cmd", "load, list, reload, resetcfg, start, stop, help");
}
private string GetCommandHelp(string cmd)
{
switch (cmd.ToLower())
return cmd.ToLower() switch
{
case "load":
return Translations.Get("bot.autocraft.help.load");
case "list":
return Translations.Get("bot.autocraft.help.list");
case "reload":
return Translations.Get("bot.autocraft.help.reload");
case "resetcfg":
return Translations.Get("bot.autocraft.help.resetcfg");
case "start":
return Translations.Get("bot.autocraft.help.start");
case "stop":
return Translations.Get("bot.autocraft.help.stop");
case "help":
return Translations.Get("bot.autocraft.help.help");
default:
return GetHelp();
}
#pragma warning disable format // @formatter:off
"load" => Translations.Get("bot.autocraft.help.load"),
"list" => Translations.Get("bot.autocraft.help.list"),
"reload" => Translations.Get("bot.autocraft.help.reload"),
"resetcfg" => Translations.Get("bot.autocraft.help.resetcfg"),
"start" => Translations.Get("bot.autocraft.help.start"),
"stop" => Translations.Get("bot.autocraft.help.stop"),
"help" => Translations.Get("bot.autocraft.help.help"),
_ => GetHelp(),
#pragma warning restore format // @formatter:on
};
}
#region Config handling
@ -312,7 +306,7 @@ namespace MinecraftClient.ChatBots
// local variable for use in parsing config
string section = "";
Dictionary<string, Recipe> recipes = new Dictionary<string, Recipe>();
Dictionary<string, Recipe> recipes = new();
foreach (string l in content)
{
@ -323,20 +317,20 @@ namespace MinecraftClient.ChatBots
if (line.Length <= 0)
continue;
if (line[0] == '[' && line[line.Length - 1] == ']')
if (line[0] == '[' && line[^1] == ']')
{
section = line.Substring(1, line.Length - 2).ToLower();
section = line[1..^1].ToLower();
continue;
}
string key = line.Split('=')[0].ToLower();
if (!(line.Length > (key.Length + 1)))
continue;
string value = line.Substring(key.Length + 1);
string value = line[(key.Length + 1)..];
switch (section)
{
case "recipe": parseRecipe(key, value); break;
case "autocraft": parseMain(key, value); break;
case "recipe": ParseRecipe(key, value); break;
case "autocraft": ParseMain(key, value); break;
}
}
@ -358,12 +352,12 @@ namespace MinecraftClient.ChatBots
}
}
}
#region Method for parsing different section of config
private void parseMain(string key, string value)
private void ParseMain(string key, string value)
{
switch (key)
{
@ -378,7 +372,7 @@ namespace MinecraftClient.ChatBots
else throw new Exception(Translations.Get("bot.autoCraft.exception.invalid_table", key));
break;
case "onfailure":
abortOnFailure = value.ToLower() == "abort" ? true : false;
abortOnFailure = value.ToLower() == "abort";
break;
case "updatedebounce":
updateDebounceValue = Convert.ToInt32(value);
@ -386,21 +380,21 @@ namespace MinecraftClient.ChatBots
}
}
private void parseRecipe(string key, string value)
private void ParseRecipe(string key, string value)
{
if (key.StartsWith("slot"))
{
int slot = Convert.ToInt32(key[key.Length - 1].ToString());
int slot = Convert.ToInt32(key[^1].ToString());
if (slot > 0 && slot < 10)
{
if (recipes.ContainsKey(lastRecipe))
{
ItemType itemType;
if (Enum.TryParse(value, true, out itemType))
if (Enum.TryParse(value, true, out ItemType itemType))
{
if (recipes[lastRecipe].Materials != null && recipes[lastRecipe].Materials.Count > 0)
Dictionary<int, ItemType>? materials = recipes[lastRecipe].Materials;
if (materials != null && materials.Count > 0)
{
recipes[lastRecipe].Materials.Add(slot, itemType);
materials.Add(slot, itemType);
}
else
{
@ -450,8 +444,7 @@ namespace MinecraftClient.ChatBots
case "result":
if (recipes.ContainsKey(lastRecipe))
{
ItemType itemType;
if (Enum.TryParse(value, true, out itemType))
if (Enum.TryParse(value, true, out ItemType itemType))
{
recipes[lastRecipe].ResultItem = itemType;
}
@ -487,7 +480,7 @@ namespace MinecraftClient.ChatBots
// After table opened, we need to wait for server to update table inventory items
waitingForUpdate = true;
inventoryInUse = inventoryId;
PrepareCrafting(recipeInUse);
PrepareCrafting(recipeInUse!);
}
}
}
@ -562,11 +555,14 @@ namespace MinecraftClient.ChatBots
}
}
foreach (KeyValuePair<int, ItemType> slot in recipe.Materials)
if (recipe.Materials != null)
{
// Steps for moving items from inventory to crafting area
actionSteps.Add(new ActionStep(ActionType.LeftClick, inventoryInUse, slot.Value));
actionSteps.Add(new ActionStep(ActionType.LeftClick, inventoryInUse, slot.Key));
foreach (KeyValuePair<int, ItemType> slot in recipe.Materials)
{
// Steps for moving items from inventory to crafting area
actionSteps.Add(new ActionStep(ActionType.LeftClick, inventoryInUse, slot.Value));
actionSteps.Add(new ActionStep(ActionType.LeftClick, inventoryInUse, slot.Key));
}
}
if (actionSteps.Count > 0)
{
@ -626,15 +622,15 @@ namespace MinecraftClient.ChatBots
else
{
int[] slots = GetInventories()[step.InventoryID].SearchItem(step.ItemType);
if (slots.Count() > 0)
if (slots.Length > 0)
{
int ignoredSlot;
if (recipeInUse.CraftingAreaType == ContainerType.PlayerInventory)
if (recipeInUse!.CraftingAreaType == ContainerType.PlayerInventory)
ignoredSlot = 9;
else
ignoredSlot = 10;
slots = slots.Where(slot => slot >= ignoredSlot).ToArray();
if (slots.Count() > 0)
if (slots.Length > 0)
WindowAction(step.InventoryID, slots[0], WindowActionType.LeftClick);
else
craftingFailed = true;
@ -688,7 +684,6 @@ namespace MinecraftClient.ChatBots
}
HandleError();
}
}
/// <summary>

View file

@ -1,8 +1,7 @@
using MinecraftClient.Inventory;
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MinecraftClient.Inventory;
namespace MinecraftClient.ChatBots
{
@ -18,10 +17,10 @@ namespace MinecraftClient.ChatBots
private bool enable = true;
private int updateDebounce = 0;
private int updateDebounceValue = 2;
private readonly int updateDebounceValue = 2;
private int inventoryUpdated = -1;
private List<ItemType> itemList = new List<ItemType>();
private readonly List<ItemType> itemList = new();
public AutoDrop(string mode, string itemList)
{
@ -40,17 +39,11 @@ namespace MinecraftClient.ChatBots
/// <returns>Item type array</returns>
private ItemType[] ItemListParser(string itemList)
{
string trimed = new string(itemList.Where(c => !char.IsWhiteSpace(c)).ToArray());
string[] list = trimed.Split(',');
List<ItemType> result = new List<ItemType>();
foreach (string t in list)
{
ItemType item;
if (Enum.TryParse(t, true, out item))
{
string trimed = new(itemList.Where(c => !char.IsWhiteSpace(c)).ToArray());
List<ItemType> result = new();
foreach (string t in trimed.Split(','))
if (Enum.TryParse(t, true, out ItemType item))
result.Add(item);
}
}
return result.ToArray();
}
@ -71,8 +64,7 @@ namespace MinecraftClient.ChatBots
case "add":
if (args.Length >= 2)
{
ItemType item;
if (Enum.TryParse(args[1], true, out item))
if (Enum.TryParse(args[1], true, out ItemType item))
{
itemList.Add(item);
return Translations.Get("bot.autoDrop.added", item.ToString());
@ -89,8 +81,7 @@ namespace MinecraftClient.ChatBots
case "remove":
if (args.Length >= 2)
{
ItemType item;
if (Enum.TryParse(args[1], true, out item))
if (Enum.TryParse(args[1], true, out ItemType item))
{
if (itemList.Contains(item))
{
@ -109,7 +100,7 @@ namespace MinecraftClient.ChatBots
}
else
{
return Translations.Get("cmd.inventory.help.usage") + ": remove <item name>";
return Translations.Get("cmd.inventory.help.usage") + ": remove <item name>";
}
case "list":
if (itemList.Count > 0)
@ -155,7 +146,7 @@ namespace MinecraftClient.ChatBots
}
}
private string GetHelp()
private static string GetHelp()
{
return Translations.Get("general.available_cmd", "on, off, add, remove, list, mode");
}

View file

@ -1,8 +1,4 @@
using MinecraftClient.Inventory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.ChatBots
{
@ -10,7 +6,7 @@ namespace MinecraftClient.ChatBots
{
byte LastSlot = 0;
public static bool Eating = false;
private int HungerThreshold = 6;
private readonly int HungerThreshold = 6;
private int DelayCounter = 0;
public AutoEat(int Threshold)

View file

@ -1,9 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MinecraftClient.Mapping;
using MinecraftClient.Inventory;
using MinecraftClient.Mapping;
namespace MinecraftClient.ChatBots
{

View file

@ -1,6 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.ChatBots
@ -10,11 +8,11 @@ namespace MinecraftClient.ChatBots
/// </summary>
public class AutoRelog : ChatBot
{
private static Random random = new Random();
private string[] dictionary = new string[0];
private int attempts;
private int delayMin;
private int delayMax;
private static readonly Random random = new();
private string[] dictionary = Array.Empty<string>();
private readonly int attempts;
private readonly int delayMin;
private readonly int delayMax;
/// <summary>
/// This bot automatically re-join the server if kick message contains predefined string
@ -100,7 +98,7 @@ namespace MinecraftClient.ChatBots
return false;
}
private void LaunchDelayedReconnection(string msg)
private void LaunchDelayedReconnection(string? msg)
{
int delay = random.Next(delayMin, delayMax);
LogDebugToConsoleTranslated(String.IsNullOrEmpty(msg) ? "bot.autoRelog.reconnect_always" : "bot.autoRelog.reconnect", msg);
@ -113,7 +111,7 @@ namespace MinecraftClient.ChatBots
{
if (Settings.AutoRelog_Enabled)
{
AutoRelog bot = new AutoRelog(Settings.AutoRelog_Delay_Min, Settings.AutoRelog_Delay_Max, Settings.AutoRelog_Retries);
AutoRelog bot = new(Settings.AutoRelog_Delay_Min, Settings.AutoRelog_Delay_Max, Settings.AutoRelog_Retries);
bot.Initialize();
return bot.OnDisconnect(reason, message);
}

View file

@ -1,6 +1,6 @@
using System;
using System.IO;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
@ -11,9 +11,9 @@ namespace MinecraftClient.ChatBots
/// </summary>
class AutoRespond : ChatBot
{
private string matchesFile;
private bool matchColors;
private List<RespondRule> respondRules;
private readonly string matchesFile;
private readonly bool matchColors;
private List<RespondRule>? respondRules;
private enum MessageType { Public, Private, Other };
/// <summary>
@ -31,13 +31,13 @@ namespace MinecraftClient.ChatBots
/// </summary>
private class RespondRule
{
private Regex regex;
private string match;
private string actionPublic;
private string actionPrivate;
private string actionOther;
private bool ownersOnly;
private TimeSpan cooldown;
private readonly Regex? regex;
private readonly string? match;
private readonly string? actionPublic;
private readonly string? actionPrivate;
private readonly string? actionOther;
private readonly bool ownersOnly;
private readonly TimeSpan cooldown;
private DateTime cooldownExpiration;
/// <summary>
@ -49,16 +49,16 @@ namespace MinecraftClient.ChatBots
/// <param name="actionOther">Internal command to run for any other messages</param>
/// <param name="ownersOnly">Only match messages from bot owners</param>
/// <param name="cooldown">Minimal cooldown between two matches</param>
public RespondRule(Regex regex, string actionPublic, string actionPrivate, string actionOther, bool ownersOnly, TimeSpan cooldown)
public RespondRule(Regex regex, string? actionPublic, string? actionPrivate, string? actionOther, bool ownersOnly, TimeSpan cooldown)
{
this.regex = regex;
this.match = null;
match = null;
this.actionPublic = actionPublic;
this.actionPrivate = actionPrivate;
this.actionOther = actionOther;
this.ownersOnly = ownersOnly;
this.cooldown = cooldown;
this.cooldownExpiration = DateTime.MinValue;
cooldownExpiration = DateTime.MinValue;
}
/// <summary>
@ -69,16 +69,16 @@ namespace MinecraftClient.ChatBots
/// <param name="actionPrivate">Internal command to run for private messages</param>
/// <param name="ownersOnly">Only match messages from bot owners</param>
/// <param name="cooldown">Minimal cooldown between two matches</param>
public RespondRule(string match, string actionPublic, string actionPrivate, string actionOther, bool ownersOnly, TimeSpan cooldown)
public RespondRule(string? match, string? actionPublic, string? actionPrivate, string? actionOther, bool ownersOnly, TimeSpan cooldown)
{
this.regex = null;
regex = null;
this.match = match;
this.actionPublic = actionPublic;
this.actionPrivate = actionPrivate;
this.actionOther = actionOther;
this.ownersOnly = ownersOnly;
this.cooldown = cooldown;
this.cooldownExpiration = DateTime.MinValue;
cooldownExpiration = DateTime.MinValue;
}
/// <summary>
@ -89,12 +89,12 @@ namespace MinecraftClient.ChatBots
/// <param name="msgType">Type of the message public/private message, or other message</param>
/// <param name="localVars">Dictionary to populate with match variables in case of Regex match</param>
/// <returns>Internal command to run as a response to this user, or null if no match has been detected</returns>
public string Match(string username, string message, MessageType msgType, Dictionary<string, object> localVars)
public string? Match(string username, string message, MessageType msgType, Dictionary<string, object> localVars)
{
if (DateTime.Now < cooldownExpiration)
return null;
string toSend = null;
string? toSend = null;
if (ownersOnly && (String.IsNullOrEmpty(username) || !Settings.Bots_Owners.Contains(username.ToLower())))
return null;
@ -166,11 +166,11 @@ namespace MinecraftClient.ChatBots
{
if (File.Exists(matchesFile))
{
Regex matchRegex = null;
string matchString = null;
string matchAction = null;
string matchActionPrivate = null;
string matchActionOther = null;
Regex? matchRegex = null;
string? matchString = null;
string? matchAction = null;
string? matchActionPrivate = null;
string? matchActionOther = null;
bool ownersOnly = false;
TimeSpan cooldown = TimeSpan.Zero;
respondRules = new List<RespondRule>();
@ -182,9 +182,9 @@ namespace MinecraftClient.ChatBots
string line = lineRAW.Split('#')[0].Trim();
if (line.Length > 0)
{
if (line[0] == '[' && line[line.Length - 1] == ']')
if (line[0] == '[' && line[^1] == ']')
{
switch (line.Substring(1, line.Length - 2).ToLower())
switch (line[1..^1].ToLower())
{
case "match":
CheckAddMatch(matchRegex, matchString, matchAction, matchActionPrivate, matchActionOther, ownersOnly, cooldown);
@ -203,7 +203,7 @@ namespace MinecraftClient.ChatBots
string argName = line.Split('=')[0];
if (line.Length > (argName.Length + 1))
{
string argValue = line.Substring(argName.Length + 1);
string argValue = line[(argName.Length + 1)..];
switch (argName.ToLower())
{
case "regex": matchRegex = new Regex(argValue); break;
@ -236,7 +236,7 @@ namespace MinecraftClient.ChatBots
/// <param name="matchActionPrivate">Action if the matching message is private</param>
/// <param name="ownersOnly">Only match messages from bot owners</param>
/// <param name="cooldown">Minimal cooldown between two matches</param>
private void CheckAddMatch(Regex matchRegex, string matchString, string matchAction, string matchActionPrivate, string matchActionOther, bool ownersOnly, TimeSpan cooldown)
private void CheckAddMatch(Regex? matchRegex, string? matchString, string? matchAction, string? matchActionPrivate, string? matchActionOther, bool ownersOnly, TimeSpan cooldown)
{
if (matchRegex != null || matchString != null || matchAction != null || matchActionPrivate != null || matchActionOther != null || ownersOnly || cooldown != TimeSpan.Zero)
{
@ -248,7 +248,7 @@ namespace MinecraftClient.ChatBots
{
if (matchRegex != null || matchString != null)
{
respondRules.Add(rule);
respondRules!.Add(rule);
LogDebugToConsoleTranslated("bot.autoRespond.loaded_match", rule);
}
else LogDebugToConsoleTranslated("bot.autoRespond.no_trigger", rule);
@ -264,7 +264,7 @@ namespace MinecraftClient.ChatBots
public override void GetText(string text)
{
//Remove colour codes
if (!this.matchColors)
if (!matchColors)
text = GetVerbatim(text);
//Get Message type
@ -279,13 +279,13 @@ namespace MinecraftClient.ChatBots
//Do not process messages sent by the bot itself
if (msgType == MessageType.Other || sender != Settings.Username)
{
foreach (RespondRule rule in respondRules)
foreach (RespondRule rule in respondRules!)
{
Dictionary<string, object> localVars = new Dictionary<string, object>();
string toPerform = rule.Match(sender, message, msgType, localVars);
Dictionary<string, object> localVars = new();
string? toPerform = rule.Match(sender, message, msgType, localVars);
if (!String.IsNullOrEmpty(toPerform))
{
string response = null;
string? response = null;
LogToConsoleTranslated("bot.autoRespond.match_run", toPerform);
PerformInternalCommand(toPerform, ref response, localVars);
if (!String.IsNullOrEmpty(response))

View file

@ -1,7 +1,5 @@
using MinecraftClient.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Commands
@ -12,11 +10,11 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "bots [list|unload <bot name|all>]"; } }
public override string CmdDesc { get { return "cmd.bots.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars)
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{
if (hasArg(command))
if (HasArg(command))
{
string[] args = getArgs(command);
string[] args = GetArgs(command);
if (args.Length == 1)
{

View file

@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace MinecraftClient.ChatBots
@ -13,13 +10,13 @@ namespace MinecraftClient.ChatBots
public class ChatLog : ChatBot
{
public enum MessageFilter { AllText, AllMessages, OnlyChat, OnlyWhispers, OnlyInternalCommands };
private bool dateandtime;
private bool saveOther = true;
private bool saveChat = true;
private bool savePrivate = true;
private bool saveInternal = true;
private string logfile;
private object logfileLock = new object();
private readonly bool dateandtime;
private readonly bool saveOther = true;
private readonly bool saveChat = true;
private readonly bool savePrivate = true;
private readonly bool saveInternal = true;
private readonly string logfile;
private readonly object logfileLock = new();
/// <summary>
/// This bot saves the messages received in the specified file, with some filters and date/time tagging.
@ -70,15 +67,17 @@ namespace MinecraftClient.ChatBots
public static MessageFilter str2filter(string filtername)
{
switch (Settings.ToLowerIfNeed(filtername))
return Settings.ToLowerIfNeed(filtername) switch
{
case "all": return MessageFilter.AllText;
case "messages": return MessageFilter.AllMessages;
case "chat": return MessageFilter.OnlyChat;
case "private": return MessageFilter.OnlyWhispers;
case "internal": return MessageFilter.OnlyInternalCommands;
default: return MessageFilter.AllText;
}
#pragma warning disable format // @formatter:off
"all" => MessageFilter.AllText,
"messages" => MessageFilter.AllMessages,
"chat" => MessageFilter.OnlyChat,
"private" => MessageFilter.OnlyWhispers,
"internal" => MessageFilter.OnlyInternalCommands,
_ => MessageFilter.AllText,
#pragma warning restore format // @formatter:on
};
}
public override void GetText(string text)
@ -89,37 +88,37 @@ namespace MinecraftClient.ChatBots
if (saveChat && IsChatMessage(text, ref message, ref sender))
{
save("Chat " + sender + ": " + message);
Save("Chat " + sender + ": " + message);
}
else if (savePrivate && IsPrivateMessage(text, ref message, ref sender))
{
save("Private " + sender + ": " + message);
Save("Private " + sender + ": " + message);
}
else if (saveOther)
{
save("Other: " + text);
Save("Other: " + text);
}
}
public override void OnInternalCommand(string commandName,string commandParams, string result)
public override void OnInternalCommand(string commandName, string commandParams, string result)
{
if (saveInternal)
{
save(string.Format("Internal {0}({1}): {2}", commandName, commandParams, result));
Save(string.Format("Internal {0}({1}): {2}", commandName, commandParams, result));
}
}
private void save(string tosave)
private void Save(string tosave)
{
if (dateandtime)
tosave = GetTimestamp() + ' ' + tosave;
lock (logfileLock)
{
string directory = Path.GetDirectoryName(logfile);
string? directory = Path.GetDirectoryName(logfile);
if (!String.IsNullOrEmpty(directory) && !Directory.Exists(directory))
Directory.CreateDirectory(directory);
FileStream stream = new FileStream(logfile, FileMode.OpenOrCreate);
StreamWriter writer = new StreamWriter(stream);
FileStream stream = new(logfile, FileMode.OpenOrCreate);
StreamWriter writer = new(stream);
stream.Seek(0, SeekOrigin.End);
writer.WriteLine(tosave);
writer.Dispose();

View file

@ -8,8 +8,8 @@ namespace MinecraftClient.ChatBots
{
private string? _playerToFollow = null;
private int _updateCounter = 0;
private int _updateLimit;
private int _stopAtDistance;
private readonly int _updateLimit;
private readonly int _stopAtDistance;
private bool _unsafeEnabled = false;
public FollowPlayer(int updateLimit = 15, int stopAtDistance = 3)
@ -112,7 +112,7 @@ namespace MinecraftClient.ChatBots
return;
// Stop at specified distance from plater (prevents pushing player around)
double distance = Distance(entity.Location, GetCurrentLocation());
double distance = entity.Location.Distance(GetCurrentLocation());
if (distance < _stopAtDistance)
return;
@ -154,14 +154,6 @@ namespace MinecraftClient.ChatBots
}
}
private double Distance(Location location1, Location location2)
{
return Math.Sqrt(
((location1.X - location2.X) * (location1.X - location2.X)) +
((location1.Y - location2.Y) * (location1.Y - location2.Y)) +
((location1.Z - location2.Z) * (location1.Z - location2.Z)));
}
private bool CanMoveThere(Location location)
{
ChunkColumn? chunkColumn = GetWorld().GetChunkColumn(location);

View file

@ -1,6 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.ChatBots
@ -12,14 +10,14 @@ namespace MinecraftClient.ChatBots
public class HangmanGame : ChatBot
{
private int vie = 0;
private int vie_param = 10;
private readonly int vie_param = 10;
private int compteur = 0;
private int compteur_param = 3000; //5 minutes
private readonly int compteur_param = 3000; //5 minutes
private bool running = false;
private bool[] discovered;
private string word = "";
private string letters = "";
private bool English;
private readonly bool English;
/// <summary>
/// Le jeu du Pendu / Hangman Game
@ -29,6 +27,7 @@ namespace MinecraftClient.ChatBots
public HangmanGame(bool english)
{
English = english;
discovered = Array.Empty<bool>();
}
public override void Update()
@ -61,7 +60,7 @@ namespace MinecraftClient.ChatBots
switch (message)
{
case "start":
start();
Start();
break;
case "stop":
running = false;
@ -108,11 +107,11 @@ namespace MinecraftClient.ChatBots
if (running)
{
SendText(English ? ("Mysterious word: " + word_cached + " (lives : " + vie + ")")
: ("Mot mystère : " + word_cached + " (vie : " + vie + ")"));
SendText(English ? ("Mysterious word: " + WordCached + " (lives : " + vie + ")")
: ("Mot mystère : " + WordCached + " (vie : " + vie + ")"));
}
if (winner)
if (Winner)
{
SendText(English ? ("Congrats, " + username + '!') : ("Félicitations, " + username + " !"));
running = false;
@ -124,22 +123,22 @@ namespace MinecraftClient.ChatBots
}
}
private void start()
private void Start()
{
vie = vie_param;
running = true;
letters = "";
word = chooseword();
word = Chooseword();
compteur = compteur_param;
discovered = new bool[word.Length];
SendText(English ? "Hangman v1.0 - By ORelio" : "Pendu v1.0 - Par ORelio");
SendText(English ? ("Mysterious word: " + word_cached + " (lives : " + vie + ")")
: ("Mot mystère : " + word_cached + " (vie : " + vie + ")"));
SendText(English ? ("Mysterious word: " + WordCached + " (lives : " + vie + ")")
: ("Mot mystère : " + WordCached + " (vie : " + vie + ")"));
SendText(English ? ("Try some letters ... :)") : ("Proposez une lettre ... :)"));
}
private string chooseword()
private string Chooseword()
{
if (System.IO.File.Exists(English ? Settings.Hangman_FileWords_EN : Settings.Hangman_FileWords_FR))
{
@ -153,7 +152,7 @@ namespace MinecraftClient.ChatBots
}
}
private string word_cached
private string WordCached
{
get
{
@ -170,7 +169,7 @@ namespace MinecraftClient.ChatBots
}
}
private bool winner
private bool Winner
{
get
{

View file

@ -1,8 +1,8 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Collections.Generic;
namespace MinecraftClient.ChatBots
{
@ -23,7 +23,7 @@ namespace MinecraftClient.ChatBots
/// <returns>Ignore list</returns>
public static IgnoreList FromFile(string filePath)
{
IgnoreList ignoreList = new IgnoreList();
IgnoreList ignoreList = new();
foreach (string line in FileMonitor.ReadAllLinesWithRetries(filePath))
{
if (!line.StartsWith("#"))
@ -42,7 +42,7 @@ namespace MinecraftClient.ChatBots
/// <param name="filePath">Path to destination file</param>
public void SaveToFile(string filePath)
{
List<string> lines = new List<string>();
List<string> lines = new();
lines.Add("#Ignored Players");
foreach (string player in this)
lines.Add(player);
@ -62,7 +62,7 @@ namespace MinecraftClient.ChatBots
/// <returns>Mail database</returns>
public static MailDatabase FromFile(string filePath)
{
MailDatabase database = new MailDatabase();
MailDatabase database = new();
Dictionary<string, Dictionary<string, string>> iniFileDict = INIFile.ParseFile(FileMonitor.ReadAllLinesWithRetries(filePath));
foreach (KeyValuePair<string, Dictionary<string, string>> iniSection in iniFileDict)
{
@ -83,17 +83,21 @@ namespace MinecraftClient.ChatBots
/// <param name="filePath">Path to destination file</param>
public void SaveToFile(string filePath)
{
Dictionary<string, Dictionary<string, string>> iniFileDict = new Dictionary<string, Dictionary<string, string>>();
Dictionary<string, Dictionary<string, string>> iniFileDict = new();
int mailCount = 0;
foreach (Mail mail in this)
{
mailCount++;
Dictionary<string, string> iniSection = new Dictionary<string, string>();
iniSection["sender"] = mail.Sender;
iniSection["recipient"] = mail.Recipient;
iniSection["content"] = mail.Content;
iniSection["timestamp"] = mail.DateSent.ToString();
iniSection["anonymous"] = mail.Anonymous.ToString();
Dictionary<string, string> iniSection = new()
{
#pragma warning disable format // @formatter:off
["sender"] = mail.Sender,
["recipient"] = mail.Recipient,
["content"] = mail.Content,
["timestamp"] = mail.DateSent.ToString(),
["anonymous"] = mail.Anonymous.ToString()
#pragma warning restore format // @formatter:on
};
iniFileDict["mail" + mailCount] = iniSection;
}
FileMonitor.WriteAllLinesWithRetries(filePath, INIFile.Generate(iniFileDict, "Mail Database"));
@ -105,24 +109,24 @@ namespace MinecraftClient.ChatBots
/// </summary>
private class Mail
{
private string sender;
private string senderLower;
private string recipient;
private string recipientLower;
private string message;
private DateTime datesent;
private readonly string sender;
private readonly string senderLower;
private readonly string recipient;
private readonly string recipientLower;
private readonly string message;
private readonly DateTime datesent;
private bool delivered;
private bool anonymous;
private readonly bool anonymous;
public Mail(string sender, string recipient, string message, bool anonymous, DateTime datesent)
{
this.sender = sender;
this.senderLower = sender.ToLower();
senderLower = sender.ToLower();
this.recipient = recipient;
this.recipientLower = recipient.ToLower();
recipientLower = recipient.ToLower();
this.message = message;
this.datesent = datesent;
this.delivered = false;
delivered = false;
this.anonymous = anonymous;
}
@ -132,9 +136,9 @@ namespace MinecraftClient.ChatBots
public string RecipientLowercase { get { return recipientLower; } }
public string Content { get { return message; } }
public DateTime DateSent { get { return datesent; } }
public bool Delivered { get { return delivered; } }
public bool Delivered => delivered;
public bool Anonymous { get { return anonymous; } }
public void setDelivered() { delivered = true; }
public void SetDelivered() { delivered = true; }
public override string ToString()
{
@ -145,11 +149,11 @@ namespace MinecraftClient.ChatBots
// Internal variables
private int maxMessageLength = 0;
private DateTime nextMailSend = DateTime.Now;
private MailDatabase mailDatabase = new MailDatabase();
private IgnoreList ignoreList = new IgnoreList();
private FileMonitor mailDbFileMonitor;
private FileMonitor ignoreListFileMonitor;
private object readWriteLock = new object();
private MailDatabase mailDatabase = new();
private IgnoreList ignoreList = new();
private FileMonitor? mailDbFileMonitor;
private FileMonitor? ignoreListFileMonitor;
private readonly object readWriteLock = new();
/// <summary>
/// Initialization of the Mailer bot
@ -207,8 +211,8 @@ namespace MinecraftClient.ChatBots
}
//Initialize file monitors. In case the bot needs to unload for some reason in the future, do not forget to .Dispose() them
mailDbFileMonitor = new FileMonitor(Path.GetDirectoryName(Settings.Mailer_DatabaseFile), Path.GetFileName(Settings.Mailer_DatabaseFile), FileMonitorCallback);
ignoreListFileMonitor = new FileMonitor(Path.GetDirectoryName(Settings.Mailer_IgnoreListFile), Path.GetFileName(Settings.Mailer_IgnoreListFile), FileMonitorCallback);
mailDbFileMonitor = new FileMonitor(Path.GetDirectoryName(Settings.Mailer_DatabaseFile)!, Path.GetFileName(Settings.Mailer_DatabaseFile), FileMonitorCallback);
ignoreListFileMonitor = new FileMonitor(Path.GetDirectoryName(Settings.Mailer_IgnoreListFile)!, Path.GetFileName(Settings.Mailer_IgnoreListFile), FileMonitorCallback);
RegisterChatBotCommand("mailer", Translations.Get("bot.mailer.cmd"), "mailer <getmails|addignored|getignored|removeignored>", ProcessInternalCommand);
}
@ -246,7 +250,7 @@ namespace MinecraftClient.ChatBots
&& mailDatabase.Count < Settings.Mailer_MaxDatabaseSize
&& mailDatabase.Where(mail => mail.SenderLowercase == usernameLower).Count() < Settings.Mailer_MaxMailsPerPlayer)
{
Queue<string> args = new Queue<string>(Command.getArgs(message));
Queue<string> args = new(Command.GetArgs(message));
if (args.Count >= 2)
{
bool anonymous = (command == "tellonym");
@ -257,7 +261,7 @@ namespace MinecraftClient.ChatBots
{
if (message.Length <= maxMessageLength)
{
Mail mail = new Mail(username, recipient, message, anonymous, DateTime.Now);
Mail mail = new(username, recipient, message, anonymous, DateTime.Now);
LogToConsoleTranslated("bot.mailer.saving", mail.ToString());
lock (readWriteLock)
{
@ -291,12 +295,12 @@ namespace MinecraftClient.ChatBots
LogDebugToConsoleTranslated("bot.mailer.process_mails", DateTime.Now);
// Process at most 3 mails at a time to avoid spamming. Other mails will be processed on next mail send
HashSet<string> onlinePlayersLowercase = new HashSet<string>(GetOnlinePlayers().Select(name => name.ToLower()));
HashSet<string> onlinePlayersLowercase = new(GetOnlinePlayers().Select(name => name.ToLower()));
foreach (Mail mail in mailDatabase.Where(mail => !mail.Delivered && onlinePlayersLowercase.Contains(mail.RecipientLowercase)).Take(3))
{
string sender = mail.Anonymous ? "Anonymous" : mail.Sender;
SendPrivateMessage(mail.Recipient, sender + " mailed: " + mail.Content);
mail.setDelivered();
mail.SetDelivered();
LogDebugToConsoleTranslated("bot.mailer.delivered", mail.ToString());
}
@ -336,7 +340,7 @@ namespace MinecraftClient.ChatBots
switch (commandName)
{
case "getmails": // Sorry, I (ReinforceZwei) replaced "=" to "-" because it would affect the parsing of translation file (key=value)
return Translations.Get("bot.mailer.cmd.getmails", string.Join("\n", mailDatabase));
return Translations.Get("bot.mailer.cmd.getmails", string.Join("\n", mailDatabase));
case "getignored":
return Translations.Get("bot.mailer.cmd.getignored", string.Join("\n", ignoreList));

View file

@ -1,17 +1,17 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using MinecraftClient.Mapping;
using System.Drawing;
using MinecraftClient.Protocol.Handlers;
namespace MinecraftClient.ChatBots
{
class Map : ChatBot
{
private string baseDirectory = @"Rendered_Maps";
private readonly string baseDirectory = @"Rendered_Maps";
private Dictionary<int, McMap> cachedMaps = new();
private readonly Dictionary<int, McMap> cachedMaps = new();
private bool shouldResize = true;
private int resizeTo = 256;
private bool autoRenderOnUpdate = true;
@ -40,7 +40,7 @@ namespace MinecraftClient.ChatBots
{
if (deleteAllOnExit)
{
DirectoryInfo di = new DirectoryInfo(baseDirectory);
DirectoryInfo di = new(baseDirectory);
FileInfo[] files = di.GetFiles();
foreach (FileInfo file in files)
@ -101,19 +101,20 @@ namespace MinecraftClient.ChatBots
if (columnsUpdated == 0 && cachedMaps.ContainsKey(mapid))
return;
McMap map = new McMap();
map.MapId = mapid;
map.Scale = scale;
map.TrackingPosition = trackingPosition;
map.Locked = locked;
map.MapIcons = icons;
map.Width = rowsUpdated;
map.Height = columnsUpdated;
map.X = mapCoulmnX;
map.Z = mapRowZ;
map.Colors = colors;
map.LastUpdated = DateTime.Now;
McMap map = new()
{
MapId = mapid,
Scale = scale,
TrackingPosition = trackingPosition,
Locked = locked,
MapIcons = icons,
Width = rowsUpdated,
Height = columnsUpdated,
X = mapCoulmnX,
Z = mapRowZ,
Colors = colors,
LastUpdated = DateTime.Now
};
if (!cachedMaps.ContainsKey(mapid))
{
@ -139,7 +140,7 @@ namespace MinecraftClient.ChatBots
if (File.Exists(fileName))
File.Delete(fileName);
Bitmap image = new Bitmap(map.Width, map.Height);
Bitmap image = new(map.Width, map.Height);
for (int x = 0; x < map.Width; ++x)
{
@ -168,7 +169,7 @@ namespace MinecraftClient.ChatBots
}
private Bitmap ResizeBitmap(Bitmap sourceBMP, int width, int height)
{
Bitmap result = new Bitmap(width, height);
Bitmap result = new(width, height);
using (Graphics g = Graphics.FromImage(result))
g.DrawImage(sourceBMP, 0, 0, width, height);
return result;

View file

@ -1,8 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using static System.Net.Mime.MediaTypeNames;
namespace MinecraftClient.ChatBots
{
@ -13,8 +11,8 @@ namespace MinecraftClient.ChatBots
public class PlayerListLogger : ChatBot
{
private int count;
private int timeping;
private string file;
private readonly int timeping;
private readonly string file;
/// <summary>
/// This bot sends a /list command every X seconds and save the result.
@ -35,24 +33,14 @@ namespace MinecraftClient.ChatBots
count++;
if (count == timeping)
{
string[] playerList = GetOnlinePlayers();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < playerList.Length; i++)
{
sb.Append(playerList[i]);
// Do not add a comma after the last username
if (i != playerList.Length - 1)
sb.Append(", ");
}
DateTime now = DateTime.Now;
LogDebugToConsole("Saving Player List");
DateTime now = DateTime.Now;
string TimeStamp = "[" + now.Year + '/' + now.Month + '/' + now.Day + ' ' + now.Hour + ':' + now.Minute + ']';
System.IO.File.AppendAllText(file, TimeStamp + "\n" + sb.ToString() + "\n\n");
StringBuilder sb = new();
sb.AppendLine(string.Format("[{0}/{1}/{2} {3}:{4}]", now.Year, now.Month, now.Day, now.Hour, now.Minute));
sb.AppendLine(string.Join(", ", GetOnlinePlayers())).AppendLine();
System.IO.File.AppendAllText(file, sb.ToString());
count = 0;
}

View file

@ -1,8 +1,4 @@
using MinecraftClient.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.Commands
{
@ -12,7 +8,7 @@ namespace MinecraftClient.Commands
public override string CmdUsage { get { return "reload"; } }
public override string CmdDesc { get { return "cmd.reload.desc"; } }
public override string Run(McClient handler, string command, Dictionary<string, object> localVars)
public override string Run(McClient handler, string command, Dictionary<string, object>? localVars)
{
handler.Log.Info(Translations.TryGet("cmd.reload.started"));
handler.ReloadSettings();

View file

@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.ChatBots
{
@ -17,7 +14,7 @@ namespace MinecraftClient.ChatBots
string command = "", sender = "";
if (IsPrivateMessage(text, ref command, ref sender) && Settings.Bots_Owners.Contains(sender.ToLower().Trim()))
{
string response = "";
string? response = "";
PerformInternalCommand(command, ref response);
response = GetVerbatim(response);
foreach (char disallowedChar in McClient.GetDisallowedChatCharacters())

View file

@ -1,7 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MinecraftClient.Protocol;
namespace MinecraftClient.ChatBots
@ -11,15 +9,16 @@ namespace MinecraftClient.ChatBots
/// </summary>
public class ReplayCapture : ChatBot
{
private ReplayHandler replay;
private int backupInterval = 3000; // Unit: second * 10
private ReplayHandler? replay;
private readonly int backupInterval = 3000; // Unit: second * 10
private int backupCounter = -1;
public ReplayCapture(int backupInterval)
{
if (backupInterval != -1)
this.backupInterval = backupInterval * 10;
else this.backupInterval = -1;
else
this.backupInterval = -1;
}
public override void Initialize()
@ -34,12 +33,12 @@ namespace MinecraftClient.ChatBots
public override void OnNetworkPacket(int packetID, List<byte> packetData, bool isLogin, bool isInbound)
{
replay.AddPacket(packetID, packetData, isLogin, isInbound);
replay!.AddPacket(packetID, packetData, isLogin, isInbound);
}
public override void Update()
{
if (backupInterval > 0 && replay.RecordRunning)
if (backupInterval > 0 && replay!.RecordRunning)
{
if (backupCounter <= 0)
{
@ -52,7 +51,7 @@ namespace MinecraftClient.ChatBots
public override bool OnDisconnect(DisconnectReason reason, string message)
{
replay.OnShutDown();
replay!.OnShutDown();
return base.OnDisconnect(reason, message);
}
@ -60,7 +59,7 @@ namespace MinecraftClient.ChatBots
{
try
{
if (replay.RecordRunning)
if (replay!.RecordRunning)
{
if (args.Length > 0)
{

View file

@ -1,13 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
namespace MinecraftClient.ChatBots
{
@ -17,32 +14,32 @@ namespace MinecraftClient.ChatBots
public class Script : ChatBot
{
private string file;
private string[] lines = new string[0];
private string[] args = new string[0];
private string? file;
private string[] lines = Array.Empty<string>();
private string[] args = Array.Empty<string>();
private int sleepticks = 10;
private int nextline = 0;
private string owner;
private readonly string? owner;
private bool csharp;
private Thread thread;
private Dictionary<string, object> localVars;
private Thread? thread;
private readonly Dictionary<string, object>? localVars;
public Script(string filename)
{
ParseArguments(filename);
}
public Script(string filename, string ownername, Dictionary<string, object> localVars)
public Script(string filename, string? ownername, Dictionary<string, object>? localVars)
: this(filename)
{
this.owner = ownername;
owner = ownername;
this.localVars = localVars;
}
private void ParseArguments(string argstr)
{
List<string> args = new List<string>();
StringBuilder str = new StringBuilder();
List<string> args = new();
StringBuilder str = new();
bool escape = false;
bool quotes = false;
@ -115,9 +112,9 @@ namespace MinecraftClient.ChatBots
string caller = "Script";
try
{
StackFrame frame = new StackFrame(1);
MethodBase method = frame.GetMethod();
Type type = method.DeclaringType;
StackFrame frame = new(1);
MethodBase method = frame.GetMethod()!;
Type type = method.DeclaringType!;
caller = type.Name;
}
catch { }
@ -130,7 +127,7 @@ namespace MinecraftClient.ChatBots
public override void Initialize()
{
//Load the given file from the startup parameters
if (LookForScript(ref file))
if (LookForScript(ref file!))
{
lines = System.IO.File.ReadAllLines(file, Encoding.UTF8);
csharp = file.EndsWith(".cs");
@ -145,7 +142,7 @@ namespace MinecraftClient.ChatBots
if (!String.IsNullOrEmpty(owner))
SendPrivateMessage(owner, Translations.Get("bot.script.file_not_found", file));
UnloadBot(); //No need to keep the bot active
}
}
@ -171,8 +168,10 @@ namespace MinecraftClient.ChatBots
SendPrivateMessage(owner, errorMessage);
LogToConsole(e.InnerException);
}
});
thread.Name = "MCC Script - " + file;
})
{
Name = "MCC Script - " + file
};
thread.Start();
}
@ -204,7 +203,7 @@ namespace MinecraftClient.ChatBots
int ticks = 10;
try
{
ticks = Convert.ToInt32(instruction_line.Substring(5, instruction_line.Length - 5));
ticks = Convert.ToInt32(instruction_line[5..]);
}
catch { }
sleepticks = ticks;

View file

@ -1,8 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Text;
namespace MinecraftClient.ChatBots
{
@ -14,7 +13,7 @@ namespace MinecraftClient.ChatBots
{
private class TaskDesc
{
public string action = null;
public string? action = null;
public bool triggerOnFirstLogin = false;
public bool triggerOnLogin = false;
public bool triggerOnTime = false;
@ -22,17 +21,17 @@ namespace MinecraftClient.ChatBots
public int triggerOnInterval_Interval = 0;
public int triggerOnInterval_Interval_Max = 0;
public int triggerOnInterval_Interval_Countdown = 0;
public List<DateTime> triggerOnTime_Times = new List<DateTime>();
public List<DateTime> triggerOnTime_Times = new();
public bool triggerOnTime_alreadyTriggered = false;
}
private static bool firstlogin_done = false;
private string tasksfile;
private readonly string tasksfile;
private bool serverlogin_done;
private List<TaskDesc> tasks = new List<TaskDesc>();
private readonly List<TaskDesc> tasks = new();
private int verifytasks_timeleft = 10;
private int verifytasks_delay = 10;
private readonly int verifytasks_delay = 10;
public ScriptScheduler(string tasksfile)
{
@ -46,19 +45,19 @@ namespace MinecraftClient.ChatBots
if (System.IO.File.Exists(tasksfile))
{
LogDebugToConsoleTranslated("bot.scriptScheduler.loading", System.IO.Path.GetFullPath(tasksfile));
TaskDesc current_task = null;
String[] lines = System.IO.File.ReadAllLines(tasksfile, Encoding.UTF8);
TaskDesc? current_task = null;
string[] lines = System.IO.File.ReadAllLines(tasksfile, Encoding.UTF8);
foreach (string lineRAW in lines)
{
string line = lineRAW.Split('#')[0].Trim();
if (line.Length > 0)
{
if (line[0] == '[' && line[line.Length - 1] == ']')
if (line[0] == '[' && line[^1] == ']')
{
switch (line.Substring(1, line.Length - 2).ToLower())
switch (line[1..^1].ToLower())
{
case "task":
checkAddTask(current_task);
CheckAddTask(current_task);
current_task = new TaskDesc(); //Create a blank task
break;
}
@ -68,7 +67,7 @@ namespace MinecraftClient.ChatBots
string argName = line.Split('=')[0];
if (line.Length > (argName.Length + 1))
{
string argValue = line.Substring(argName.Length + 1);
string argValue = line[(argName.Length + 1)..];
switch (argName.ToLower())
{
case "triggeronfirstlogin": current_task.triggerOnFirstLogin = Settings.str2bool(argValue); break;
@ -77,21 +76,26 @@ namespace MinecraftClient.ChatBots
case "triggeroninterval": current_task.triggerOnInterval = Settings.str2bool(argValue); break;
case "timevalue": try { current_task.triggerOnTime_Times.Add(DateTime.ParseExact(argValue, "HH:mm", CultureInfo.InvariantCulture)); } catch { } break;
case "timeinterval":
int interval = 1;
int interval;
int intervalMax = 0;
if (argValue.Contains("-"))
if (argValue.Contains('-'))
{
string[] parts = argValue.Split("-");
if (parts.Length == 2)
{
int.TryParse(parts[0].Trim(), out interval);
int.TryParse(parts[1].Trim(), out intervalMax);
interval = int.Parse(parts[0].Trim());
intervalMax = int.Parse(parts[1].Trim());
}
else
{
interval = 1;
}
else interval = 1;
}
else int.TryParse(argValue, out interval);
else
{
interval = int.Parse(argValue);
}
current_task.triggerOnInterval_Interval = interval;
current_task.triggerOnInterval_Interval_Max = intervalMax;
@ -104,7 +108,7 @@ namespace MinecraftClient.ChatBots
}
}
}
checkAddTask(current_task);
CheckAddTask(current_task);
}
else
{
@ -113,7 +117,7 @@ namespace MinecraftClient.ChatBots
}
}
private void checkAddTask(TaskDesc current_task)
private void CheckAddTask(TaskDesc? current_task)
{
//Check if we built a valid task before adding it
if (current_task != null)
@ -166,7 +170,7 @@ namespace MinecraftClient.ChatBots
{
task.triggerOnTime_alreadyTriggered = true;
LogDebugToConsoleTranslated("bot.scriptScheduler.running_time", task.action);
PerformInternalCommand(task.action);
PerformInternalCommand(task.action!);
}
}
}
@ -186,7 +190,7 @@ namespace MinecraftClient.ChatBots
task.triggerOnInterval_Interval_Countdown = time;
LogDebugToConsoleTranslated("bot.scriptScheduler.running_inverval", task.action);
PerformInternalCommand(task.action);
PerformInternalCommand(task.action!);
}
else task.triggerOnInterval_Interval_Countdown--;
}
@ -199,7 +203,7 @@ namespace MinecraftClient.ChatBots
if (task.triggerOnLogin || (firstlogin_done == false && task.triggerOnFirstLogin))
{
LogDebugToConsoleTranslated("bot.scriptScheduler.running_login", task.action);
PerformInternalCommand(task.action);
PerformInternalCommand(task.action!);
}
}

View file

@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MinecraftClient.ChatBots
namespace MinecraftClient.ChatBots
{
/// <summary>
/// Example of message receiving.