diff --git a/StarsiegeBot/.editorconfig b/StarsiegeBot/.editorconfig new file mode 100644 index 0000000..827c77d --- /dev/null +++ b/StarsiegeBot/.editorconfig @@ -0,0 +1,201 @@ +# editorconfig.org + +# top-most EditorConfig file +root = true + +# Default settings: +# A newline ending every file +# Use 4 spaces as indentation +[*] +insert_final_newline = true +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true + +[project.json] +indent_size = 2 + +# Generated code +[*{_AssemblyInfo.cs,.notsupported.cs}] +generated_code = true + +# C# files +[*.cs] +# New line preferences +csharp_new_line_before_open_brace = all +csharp_new_line_before_else = true +csharp_new_line_before_catch = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_between_query_expression_clauses = true + +# Indentation preferences +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_switch_labels = true +csharp_indent_labels = one_less_than_current + +# Modifier preferences +csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion + +# avoid this. unless absolutely necessary +dotnet_style_qualification_for_field = false:suggestion +dotnet_style_qualification_for_property = false:suggestion +dotnet_style_qualification_for_method = false:suggestion +dotnet_style_qualification_for_event = false:suggestion + +# Types: use keywords instead of BCL types, and permit var only when the type is clear +csharp_style_var_for_built_in_types = false:suggestion +csharp_style_var_when_type_is_apparent = false:none +csharp_style_var_elsewhere = false:suggestion +dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion +dotnet_style_predefined_type_for_member_access = true:suggestion + +# name all constant fields using PascalCase +dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields +dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style +dotnet_naming_symbols.constant_fields.applicable_kinds = field +dotnet_naming_symbols.constant_fields.required_modifiers = const +dotnet_naming_style.pascal_case_style.capitalization = pascal_case + +# static fields should have s_ prefix +dotnet_naming_rule.static_fields_should_have_prefix.severity = suggestion +dotnet_naming_rule.static_fields_should_have_prefix.symbols = static_fields +dotnet_naming_rule.static_fields_should_have_prefix.style = static_prefix_style +dotnet_naming_symbols.static_fields.applicable_kinds = field +dotnet_naming_symbols.static_fields.required_modifiers = static +dotnet_naming_symbols.static_fields.applicable_accessibilities = private, internal, private_protected +dotnet_naming_style.static_prefix_style.required_prefix = s_ +dotnet_naming_style.static_prefix_style.capitalization = camel_case + +# internal and private fields should be _camelCase +dotnet_naming_rule.camel_case_for_private_internal_fields.severity = suggestion +dotnet_naming_rule.camel_case_for_private_internal_fields.symbols = private_internal_fields +dotnet_naming_rule.camel_case_for_private_internal_fields.style = camel_case_underscore_style +dotnet_naming_symbols.private_internal_fields.applicable_kinds = field +dotnet_naming_symbols.private_internal_fields.applicable_accessibilities = private, internal +dotnet_naming_style.camel_case_underscore_style.required_prefix = _ +dotnet_naming_style.camel_case_underscore_style.capitalization = camel_case + +# Code style defaults +csharp_using_directive_placement = outside_namespace:suggestion +dotnet_sort_system_directives_first = true +csharp_prefer_braces = true:silent +csharp_preserve_single_line_blocks = true:none +csharp_preserve_single_line_statements = false:none +csharp_prefer_static_local_function = true:suggestion +csharp_prefer_simple_using_statement = false:none +csharp_style_prefer_switch_expression = true:suggestion + +# Code quality +dotnet_style_readonly_field = true:suggestion +dotnet_code_quality_unused_parameters = non_public:suggestion + +# Expression-level preferences +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_auto_properties = true:suggestion +dotnet_style_prefer_conditional_expression_over_assignment = true:silent +dotnet_style_prefer_conditional_expression_over_return = true:silent +csharp_prefer_simple_default_expression = true:suggestion + +# Expression-bodied members +csharp_style_expression_bodied_methods = true:silent +csharp_style_expression_bodied_constructors = true:silent +csharp_style_expression_bodied_operators = true:silent +csharp_style_expression_bodied_properties = true:silent +csharp_style_expression_bodied_indexers = true:silent +csharp_style_expression_bodied_accessors = true:silent +csharp_style_expression_bodied_lambdas = true:silent +csharp_style_expression_bodied_local_functions = true:silent + +# Pattern matching +csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_pattern_matching_over_as_with_null_check = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion + +# Null checking preferences +csharp_style_throw_expression = true:suggestion +csharp_style_conditional_delegate_call = true:suggestion + +# Other features +csharp_style_prefer_index_operator = false:none +csharp_style_prefer_range_operator = false:none +csharp_style_pattern_local_over_anonymous_function = false:none + +# Space preferences +csharp_space_after_cast = false +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_comma = true +csharp_space_after_dot = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_after_semicolon_in_for_statement = true +csharp_space_around_binary_operators = before_and_after +csharp_space_around_declaration_statements = do_not_ignore +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_before_comma = false +csharp_space_before_dot = false +csharp_space_before_open_square_brackets = false +csharp_space_before_semicolon_in_for_statement = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_between_square_brackets = false + +# Analyzers +dotnet_code_quality.CA1052.api_surface = private, internal +dotnet_code_quality.CA1802.api_surface = private, internal +dotnet_code_quality.CA1822.api_surface = private, internal +dotnet_code_quality.CA2208.api_surface = public + +# License header +file_header_template = Licensed to the .NET Foundation under one or more agreements.\nThe .NET Foundation licenses this file to you under the MIT license. + +# C++ Files +[*.{cpp,h,in}] +curly_bracket_next_line = true +indent_brace_style = Allman + +# Xml project files +[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,nativeproj,locproj}] +indent_size = 2 + +[*.{csproj,vbproj,proj,nativeproj,locproj}] +charset = utf-8 + +# Xml build files +[*.builds] +indent_size = 2 + +# Xml files +[*.{xml,stylecop,resx,ruleset}] +indent_size = 2 + +# Xml config files +[*.{props,targets,config,nuspec}] +indent_size = 2 + +# YAML config files +[*.{yml,yaml}] +indent_size = 2 + +# Shell scripts +[*.sh] +end_of_line = lf +[*.{cmd,bat}] +end_of_line = crlf diff --git a/StarsiegeBot/BotSettings.cs b/StarsiegeBot/BotSettings.cs index db71765..99284c3 100644 --- a/StarsiegeBot/BotSettings.cs +++ b/StarsiegeBot/BotSettings.cs @@ -18,8 +18,8 @@ namespace StarsiegeBot class BotSettings : BaseCommandModule { public static Dictionary GuildSettings; - private readonly string fileName = "Json/guildsettings.json"; - private readonly CancellationTokenSource cancelToken; + private readonly string _fileName = "Json/guildsettings.json"; + private readonly CancellationTokenSource _cancelToken; public BotSettings() { Console.WriteLine("Bot Setting Commands Loaded"); @@ -30,7 +30,7 @@ namespace StarsiegeBot return; } // Check for guild settings file. If it doesnt exist, create it. - if (!File.Exists(fileName)) + if (!File.Exists(_fileName)) { // Since we need to creat it, we're going to set some default stuff. Console.Write("Guild Settings Config File Not Found. Creating One..."); @@ -57,28 +57,28 @@ namespace StarsiegeBot // Now that we have the initial stuff in memory, write it to file. string output = JsonConvert.SerializeObject(GuildSettings); - File.WriteAllTextAsync(fileName, output); + File.WriteAllTextAsync(_fileName, output); // in form the console reader that we're done making the initial config. Console.WriteLine(" Done!"); } else { // load the config file to memory. - var json = ""; - using (var fs = File.OpenRead(fileName)) - using (var sr = new StreamReader(fs, new UTF8Encoding(false))) + string json = ""; + using (FileStream fs = File.OpenRead(_fileName)) + using (StreamReader sr = new StreamReader(fs, new UTF8Encoding(false))) json = sr.ReadToEnd(); GuildSettings = JsonConvert.DeserializeObject>(json); } - cancelToken = new CancellationTokenSource(); - _ = StartTimer(cancelToken.Token); + _cancelToken = new CancellationTokenSource(); + _ = StartTimer(_cancelToken.Token); } [GroupCommand] [Description("Reports simplified data about the server settings.")] public async Task BaseItem(CommandContext ctx) { await ctx.TriggerTypingAsync(); - var guild = GuildSettings[ctx.Guild.Id.ToString()]; + GuildSettings guild = GuildSettings[ctx.Guild.Id.ToString()]; DiscordEmbedBuilder embed = StartEmbed(ctx.Guild.Name + " Server settings."); embed.AddField("On/Off Items", "_ _"); embed.AddField("Global Prefix", (guild.UseGlobalPrefix ? "On" : "Off"), true); @@ -96,10 +96,10 @@ namespace StarsiegeBot [Command("status"), RequireOwner] [Description("Sets the bot's nickname on this server.")] - public async Task SetStatus (CommandContext ctx, string type, [RemainingText] string newStatus = null) + public async Task SetStatus(CommandContext ctx, string type, [RemainingText] string newStatus = null) { await ctx.TriggerTypingAsync(); - var aType = type.ToLower() switch + ActivityType aType = type.ToLower() switch { "competing" => ActivityType.Competing, "listening" => ActivityType.ListeningTo, @@ -114,7 +114,7 @@ namespace StarsiegeBot } [Command("username"), RequireOwner] - public async Task SetUsername (CommandContext ctx, [RemainingText] string newName) + public async Task SetUsername(CommandContext ctx, [RemainingText] string newName) { await ctx.TriggerTypingAsync(); await ctx.Client.UpdateCurrentUserAsync(newName); @@ -128,7 +128,7 @@ namespace StarsiegeBot while (true) { string output = JsonConvert.SerializeObject(GuildSettings); - await File.WriteAllTextAsync(fileName, output); + await File.WriteAllTextAsync(_fileName, output); await Task.Delay(TimeSpan.FromSeconds(120), cancellationToken); if (cancellationToken.IsCancellationRequested) { diff --git a/StarsiegeBot/EventTriggers.cs b/StarsiegeBot/EventTriggers.cs index 1db33d8..d92f926 100644 --- a/StarsiegeBot/EventTriggers.cs +++ b/StarsiegeBot/EventTriggers.cs @@ -1,6 +1,7 @@ #pragma warning disable IDE0060 // Remove unused parameter using DSharpPlus; using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.CommandsNext.Exceptions; using DSharpPlus.Entities; using DSharpPlus.EventArgs; @@ -17,7 +18,7 @@ namespace StarsiegeBot public readonly EventId BotEventId; public static DiscordMember notify; // protected string BotName { get; set; } - private readonly BotSettings Guilds = new BotSettings(); + private readonly BotSettings _guilds = new BotSettings(); public Triggers(EventId botEventId) => BotEventId = botEventId; public Task CommandExecuted(CommandsNextExtension ext, CommandExecutionEventArgs e) @@ -77,14 +78,14 @@ namespace StarsiegeBot if (cmdStart == -1) return Task.CompletedTask; // Retrieve prefix. - var prefix = msg.Content.Substring(0, cmdStart); - var cmdString = msg.Content[cmdStart..]; + string prefix = msg.Content.Substring(0, cmdStart); + string cmdString = msg.Content[cmdStart..]; // Retrieve full command string. - var command = cnext.FindCommand(cmdString, out var args); + Command command = cnext.FindCommand(cmdString, out string args); if (command == null) return Task.CompletedTask; - var ctx = cnext.CreateContext(msg, prefix, command, args); + CommandContext ctx = cnext.CreateContext(msg, prefix, command, args); Task.Run(async () => await cnext.ExecuteCommandAsync(ctx)); return Task.CompletedTask; @@ -96,7 +97,7 @@ namespace StarsiegeBot if (e.Exception is ChecksFailedException ex) { string output = "---\r\n"; - foreach (var item in ex.FailedChecks) + foreach (CheckBaseAttribute item in ex.FailedChecks) { output += item.ToString() + "\r\n"; } @@ -232,10 +233,10 @@ namespace StarsiegeBot //if(e.Guilds[376937422010974209].Members.ContainsKey(139548200099905536)) //notify = e.Guilds[376937422010974209].Members[139548200099905536]; ulong desiredKey = 139548200099905536; - foreach (KeyValuePair item in e.Guilds) + foreach (KeyValuePair item in e.Guilds) { DiscordGuild curr = item.Value; - if(curr.Members.ContainsKey(desiredKey)) + if (curr.Members.ContainsKey(desiredKey)) { notify = curr.Members[desiredKey]; break; @@ -245,7 +246,7 @@ namespace StarsiegeBot // notify the *primary bot owner if the Guild count is above 75. So we can start bot verification process. if (e.Guilds.Count > 75) notify.SendMessageAsync("**__WARNING__: BOT IS IN OVER 75 SERVERS."); - + return Task.CompletedTask; } public Task GuildEmojisUpdated(DiscordClient d, GuildEmojisUpdateEventArgs e) diff --git a/StarsiegeBot/ExperiemntalCommands.cs b/StarsiegeBot/ExperiemntalCommands.cs index fca794e..ab6b903 100644 --- a/StarsiegeBot/ExperiemntalCommands.cs +++ b/StarsiegeBot/ExperiemntalCommands.cs @@ -20,14 +20,14 @@ namespace StarsiegeBot class ExperiemntalCommands : BaseCommandModule { [Command("exit"), RequireOwner] - public async Task ExitProgram (CommandContext ctx) + public async Task ExitProgram(CommandContext ctx) { await ctx.RespondAsync("Attempting a shutdown..."); System.Environment.Exit(0); } [Command("Report")] - public async Task Report (CommandContext ctx) + public async Task Report(CommandContext ctx) { await ctx.RespondAsync("Report not generated"); } diff --git a/StarsiegeBot/GameCommands.cs b/StarsiegeBot/GameCommands.cs index 2424e8a..1c45380 100644 --- a/StarsiegeBot/GameCommands.cs +++ b/StarsiegeBot/GameCommands.cs @@ -13,25 +13,25 @@ namespace StarsiegeBot class GameCommands : BaseCommandModule { // Master insult list. - private readonly string[] InsultMaster = { + private readonly string[] _insultMaster = { "{0} slaps {1} around a bit with a large trout.", "{0} puts a jellyfish on {1}'s head.", "{0} slaps {1} around a bit with the mustache of Caanon.", "{0} slaps {1} around a bit with a questionable rubber object.", "{0} slaps {1} around a bit with a rubber chicken." }; - private List InsultCopy; + private List _insultCopy; public GameCommands() { // Let the console know we've loaded basic commands. Console.WriteLine("Basic Commands Loaded"); - InsultCopy = InsultMaster.ToList(); + _insultCopy = _insultMaster.ToList(); } - [Command("8ball"), Aliases(new String[] { "ball", "8" })] + [Command("8ball"), Aliases(new string[] { "ball", "8" })] [Description("The Magic 8-Ball is a fortune-telling or seeking advice")] - public async Task Eightball(CommandContext ctx, [RemainingText, Description("Your question to the 8 ball")] String remainingText = "") + public async Task Eightball(CommandContext ctx, [RemainingText, Description("Your question to the 8 ball")] string remainingText = "") { await ctx.TriggerTypingAsync(); // Load all the traditional 8-Ball answers into an array. @@ -99,7 +99,7 @@ namespace StarsiegeBot [Command("dice"), Aliases("r", "d", "roll")] [Description("A classic dice throwing command. Limited to 1 use per 2 seconds. Format: d ")] [Cooldown(1, 2, CooldownBucketType.Guild)] - public async Task Dice(CommandContext ctx, [RemainingText, Description("XdY")] String throwing = "d") + public async Task Dice(CommandContext ctx, [RemainingText, Description("XdY")] string throwing = "d") { // let the end user know the bot is doing something... await ctx.TriggerTypingAsync(); @@ -109,7 +109,7 @@ namespace StarsiegeBot int totalResult = 0; int totalDie = 0; // set the results to an empty string. - string overallResults = String.Empty; + string overallResults = string.Empty; // Prep the regex statement. Regex regex = new Regex("(\\d{0,})(d)(-{0,1}\\d{0,})"); // Get a collection of regex matches from the dice we're through. @@ -121,7 +121,7 @@ namespace StarsiegeBot if (m.Success) { // set an empty string, set a counter. - string dieResults = String.Empty; + string dieResults = string.Empty; int dieResult = 0; // attempt to get the number of dice being "thrown" and the number of sides those die have. bool volTest = int.TryParse(m.Groups[1].ToString(), out int volume); @@ -143,7 +143,7 @@ namespace StarsiegeBot // since the rnd.Next is inclusive, exclusive, we have to adjust for that. int roll = Program.rnd.Next(Math.Min(1, sides), Math.Max(sides + 1, 0)); // do we have our first result? No, make it! Store the results in a string to show the end user. - if (dieResults.Equals(String.Empty)) + if (dieResults.Equals(string.Empty)) dieResults = roll.ToString(); else dieResults += $", {roll}"; @@ -247,7 +247,7 @@ namespace StarsiegeBot } else { - result = "Please pick a valid option! Options: " + String.Join(", ", choices); + result = "Please pick a valid option! Options: " + string.Join(", ", choices); } await ctx.RespondAsync(StartEmbed(result)); } @@ -324,7 +324,7 @@ namespace StarsiegeBot else { // the end user didn't pick something that is within the choice set... Tell them they need to play better. - result = "Please pick a valid option! Options: " + String.Join(", ", choices); + result = "Please pick a valid option! Options: " + string.Join(", ", choices); } // Actually send out all our info now. await ctx.RespondAsync(StartEmbed(result)); @@ -368,13 +368,13 @@ namespace StarsiegeBot user2 = user.Mention; } // pick a random insult, and populate the names correctly. - int randInt = Program.rnd.Next(0, InsultCopy.Count); + int randInt = Program.rnd.Next(0, _insultCopy.Count); - await ctx.RespondAsync(StartEmbed(string.Format(InsultCopy[randInt], user1, user2))); - InsultCopy.RemoveAt(randInt); - if (InsultCopy.Count == 0) + await ctx.RespondAsync(StartEmbed(string.Format(_insultCopy[randInt], user1, user2))); + _insultCopy.RemoveAt(randInt); + if (_insultCopy.Count == 0) { - InsultCopy = InsultMaster.ToList(); + _insultCopy = _insultMaster.ToList(); } } diff --git a/StarsiegeBot/Phoenix/GroupRoleManagement.cs b/StarsiegeBot/Phoenix/GroupRoleManagement.cs index 93f088d..e485942 100644 --- a/StarsiegeBot/Phoenix/GroupRoleManagement.cs +++ b/StarsiegeBot/Phoenix/GroupRoleManagement.cs @@ -27,9 +27,9 @@ namespace StarsiegeBot [Command("add")] [Description("Work in progress. Does nothing yet.")] - public async Task AddSelfRole(CommandContext ctx, - [Description("The role to add.")] DiscordRole role, - [Description("The price of the role for buyable roles. 0 for no cost. Free free to leave blank if not using Buyable roles.")] int price = 0, + public async Task AddSelfRole(CommandContext ctx, + [Description("The role to add.")] DiscordRole role, + [Description("The price of the role for buyable roles. 0 for no cost. Free free to leave blank if not using Buyable roles.")] int price = 0, [Description("What group to put the role in. If not using groups, you can leave blank."), RemainingText] string groupName = null) { await ctx.TriggerTypingAsync(); @@ -56,8 +56,8 @@ namespace StarsiegeBot [Command("delete")] [Description("Work in progress. Does nothing yet.")] - public async Task DeleteSelfRole(CommandContext ctx, - [Description("The role to delete.")] DiscordRole role, + public async Task DeleteSelfRole(CommandContext ctx, + [Description("The role to delete.")] DiscordRole role, [Description("The group to remove the role from. If left blank, will remove from all groups."), RemainingText] string group = null) { await ctx.TriggerTypingAsync(); diff --git a/StarsiegeBot/PrefixManagement.cs b/StarsiegeBot/PrefixManagement.cs index 994608d..7dce9c5 100644 --- a/StarsiegeBot/PrefixManagement.cs +++ b/StarsiegeBot/PrefixManagement.cs @@ -31,7 +31,7 @@ namespace StarsiegeBot else { // we have server settings... why does this give so much info? it should only show only prefix(es) - var server = GuildSettings[guild]; + GuildSettings server = GuildSettings[guild]; DiscordEmbedBuilder embed = new DiscordEmbedBuilder { Description = $"{ctx.Guild.Name} Prefixes." diff --git a/StarsiegeBot/Program.cs b/StarsiegeBot/Program.cs index 6c8f091..5a6a04b 100644 --- a/StarsiegeBot/Program.cs +++ b/StarsiegeBot/Program.cs @@ -70,12 +70,12 @@ namespace StarsiegeBot }; // then we want to instantiate our client - this.Client = new DiscordClient(cfg); + Client = new DiscordClient(cfg); // next, let's hook some events, so we know // what's going on - this.Client.UseInteractivity(new InteractivityConfiguration() + Client.UseInteractivity(new InteractivityConfiguration() { PollBehaviour = PollBehaviour.KeepEmojis, Timeout = TimeSpan.FromSeconds(15) @@ -97,92 +97,92 @@ namespace StarsiegeBot }; // and hook them up - this.Commands = this.Client.UseCommandsNext(ccfg); + Commands = Client.UseCommandsNext(ccfg); // up next, let's register our commands - this.Commands.RegisterCommands(); // Main Folder. Test Items. - this.Commands.RegisterCommands(); // Experimental commands file. - this.Commands.RegisterCommands(); - this.Commands.RegisterCommands(); // Main Folder. Test Items. - this.Commands.RegisterCommands(); // Main Folder. Test Items. - this.Commands.RegisterCommands(); // Main Folder. Test Items. - this.Commands.RegisterCommands(); // Main Folder. Test Items. - this.Commands.RegisterCommands(); // Raven Folder. - this.Commands.RegisterCommands(); - this.Commands.RegisterCommands(); // Main Folder. Test Items. - this.Commands.RegisterCommands(); // Raven folder. - this.Commands.RegisterCommands(); // Main Folder. Test Items. + Commands.RegisterCommands(); // Main Folder. Test Items. + Commands.RegisterCommands(); // Experimental commands file. + Commands.RegisterCommands(); + Commands.RegisterCommands(); // Main Folder. Test Items. + Commands.RegisterCommands(); // Main Folder. Test Items. + Commands.RegisterCommands(); // Main Folder. Test Items. + Commands.RegisterCommands(); // Main Folder. Test Items. + Commands.RegisterCommands(); // Raven Folder. + Commands.RegisterCommands(); + Commands.RegisterCommands(); // Main Folder. Test Items. + Commands.RegisterCommands(); // Raven folder. + Commands.RegisterCommands(); // Main Folder. Test Items. // All these commands are in the STARSIEGE folder. //if (BotName.Contains("ssp")) //{ - this.Commands.RegisterCommands(); - this.Commands.RegisterCommands(); - this.Commands.RegisterCommands(); - this.Commands.RegisterCommands(); + Commands.RegisterCommands(); + Commands.RegisterCommands(); + Commands.RegisterCommands(); + Commands.RegisterCommands(); //} // let's enable voice - this.Voice = this.Client.UseVoiceNext(); + Voice = Client.UseVoiceNext(); // Hook all possible Event Handlers in the system. - this.Client.ChannelCreated += Events.ChannelCreated; - this.Client.ChannelDeleted += Events.ChannelDeleted; - this.Client.ChannelPinsUpdated += Events.ChannelPinsUpdated; - this.Client.ChannelUpdated += Events.ChannelUpdated; - this.Client.ClientErrored += Events.ClientErrored; - this.Client.DmChannelDeleted += Events.DmChannelDeleted; - this.Client.GuildAvailable += Events.GuildAvailable; - this.Client.GuildBanAdded += Events.GuildBanAdded; - this.Client.GuildBanRemoved += Events.GuildBanRemoved; - this.Client.GuildCreated += Events.GuildCreated; - this.Client.GuildDeleted += Events.GuildDeleted; - this.Client.GuildDownloadCompleted += Events.GuildDownloadCompleted; - this.Client.GuildEmojisUpdated += Events.GuildEmojisUpdated; - this.Client.GuildIntegrationsUpdated += Events.GuildIntegrationsUpdated; - this.Client.GuildMemberAdded += Events.GuildMemberAdded; - this.Client.GuildMemberRemoved += Events.GuildMemberRemoved; - this.Client.GuildMembersChunked += Events.GuildMembersChunked; - this.Client.GuildMemberUpdated += Events.GuildMemberUpdated; - this.Client.GuildRoleCreated += Events.GuildRoleCreated; - this.Client.GuildRoleDeleted += Events.GuildRoleDeleted; - this.Client.GuildRoleUpdated += Events.GuildRoleUpdated; - this.Client.GuildUnavailable += Events.GuildUnavailable; - this.Client.GuildUpdated += Events.GuildUpdated; - this.Client.Heartbeated += Events.Heartbeated; - this.Client.InviteCreated += Events.InviteCreated; - this.Client.InviteDeleted += Events.InviteDeleted; - this.Client.MessageAcknowledged += Events.MessageAcknowledged; - this.Client.MessageCreated += Events.MessageCreated; - this.Client.MessageDeleted += Events.MessageDeleted; - this.Client.MessageReactionAdded += Events.MessageReactionAdded; - this.Client.MessageReactionRemoved += Events.MessageReactionRemoved; - this.Client.MessageReactionRemovedEmoji += Events.MessageReactionRemovedEmoji; - this.Client.MessageReactionsCleared += Events.MessageReactionsCleared; - this.Client.MessagesBulkDeleted += Events.MessagesBulkDeleted; - this.Client.MessageUpdated += Events.MessageUpdated; - this.Client.PresenceUpdated += Events.PresenceUpdated; - this.Client.Ready += Events.Ready; - this.Client.Resumed += Events.Resumed; - this.Client.SocketClosed += Events.SocketClosed; - this.Client.SocketErrored += Events.SocketErrored; - this.Client.SocketOpened += Events.SocketOpened; - this.Client.TypingStarted += Events.TypingStarted; - this.Client.UnknownEvent += Events.UnknownEvent; - this.Client.UserSettingsUpdated += Events.UserSettingsUpdated; - this.Client.UserUpdated += Events.UserUpdated; - this.Client.VoiceServerUpdated += Events.VoiceServerUpdated; - this.Client.VoiceStateUpdated += Events.VoiceStateUpdated; - this.Client.WebhooksUpdated += Events.WebhooksUpdated; - this.Client.ApplicationCommandCreated += Events.ApplicationCommandCreated; - this.Client.ApplicationCommandDeleted += Events.ApplicationCommandDeleted; - this.Client.ApplicationCommandUpdated += Events.ApplicationCommandUpdated; - this.Client.InteractionCreated += Events.InteractionCreated; - this.Commands.CommandExecuted += Events.CommandExecuted; - this.Commands.CommandErrored += Events.CommandErrored; + Client.ChannelCreated += Events.ChannelCreated; + Client.ChannelDeleted += Events.ChannelDeleted; + Client.ChannelPinsUpdated += Events.ChannelPinsUpdated; + Client.ChannelUpdated += Events.ChannelUpdated; + Client.ClientErrored += Events.ClientErrored; + Client.DmChannelDeleted += Events.DmChannelDeleted; + Client.GuildAvailable += Events.GuildAvailable; + Client.GuildBanAdded += Events.GuildBanAdded; + Client.GuildBanRemoved += Events.GuildBanRemoved; + Client.GuildCreated += Events.GuildCreated; + Client.GuildDeleted += Events.GuildDeleted; + Client.GuildDownloadCompleted += Events.GuildDownloadCompleted; + Client.GuildEmojisUpdated += Events.GuildEmojisUpdated; + Client.GuildIntegrationsUpdated += Events.GuildIntegrationsUpdated; + Client.GuildMemberAdded += Events.GuildMemberAdded; + Client.GuildMemberRemoved += Events.GuildMemberRemoved; + Client.GuildMembersChunked += Events.GuildMembersChunked; + Client.GuildMemberUpdated += Events.GuildMemberUpdated; + Client.GuildRoleCreated += Events.GuildRoleCreated; + Client.GuildRoleDeleted += Events.GuildRoleDeleted; + Client.GuildRoleUpdated += Events.GuildRoleUpdated; + Client.GuildUnavailable += Events.GuildUnavailable; + Client.GuildUpdated += Events.GuildUpdated; + Client.Heartbeated += Events.Heartbeated; + Client.InviteCreated += Events.InviteCreated; + Client.InviteDeleted += Events.InviteDeleted; + Client.MessageAcknowledged += Events.MessageAcknowledged; + Client.MessageCreated += Events.MessageCreated; + Client.MessageDeleted += Events.MessageDeleted; + Client.MessageReactionAdded += Events.MessageReactionAdded; + Client.MessageReactionRemoved += Events.MessageReactionRemoved; + Client.MessageReactionRemovedEmoji += Events.MessageReactionRemovedEmoji; + Client.MessageReactionsCleared += Events.MessageReactionsCleared; + Client.MessagesBulkDeleted += Events.MessagesBulkDeleted; + Client.MessageUpdated += Events.MessageUpdated; + Client.PresenceUpdated += Events.PresenceUpdated; + Client.Ready += Events.Ready; + Client.Resumed += Events.Resumed; + Client.SocketClosed += Events.SocketClosed; + Client.SocketErrored += Events.SocketErrored; + Client.SocketOpened += Events.SocketOpened; + Client.TypingStarted += Events.TypingStarted; + Client.UnknownEvent += Events.UnknownEvent; + Client.UserSettingsUpdated += Events.UserSettingsUpdated; + Client.UserUpdated += Events.UserUpdated; + Client.VoiceServerUpdated += Events.VoiceServerUpdated; + Client.VoiceStateUpdated += Events.VoiceStateUpdated; + Client.WebhooksUpdated += Events.WebhooksUpdated; + Client.ApplicationCommandCreated += Events.ApplicationCommandCreated; + Client.ApplicationCommandDeleted += Events.ApplicationCommandDeleted; + Client.ApplicationCommandUpdated += Events.ApplicationCommandUpdated; + Client.InteractionCreated += Events.InteractionCreated; + Commands.CommandExecuted += Events.CommandExecuted; + Commands.CommandErrored += Events.CommandErrored; // finally, let's connect and log in - await this.Client.ConnectAsync(); + await Client.ConnectAsync(); // and this is to prevent premature quitting await Task.Delay(-1); diff --git a/StarsiegeBot/Raven/NotFacts.cs b/StarsiegeBot/Raven/NotFacts.cs index 46676f0..06607fe 100644 --- a/StarsiegeBot/Raven/NotFacts.cs +++ b/StarsiegeBot/Raven/NotFacts.cs @@ -14,31 +14,31 @@ namespace StarsiegeBot [Group("notfact")] class NotFacts : BaseCommandModule { - private List notfacts; - private bool IsEnabled; - private readonly string fileName = "Json/notfacts.json"; + private List _notfacts; + private bool _isEnabled; + private static readonly string s_fileName = "Json/notfacts.json"; public NotFacts() { Console.WriteLine("NotFacts Command Loaded"); - IsEnabled = Load(); + _isEnabled = Load(); } [GroupCommand, Description("Get a NotFact")] public async Task NotFact(CommandContext ctx, [Description("[Optional] A NotFact ID")] int notFactID = 0) { - if (!IsEnabled) + if (!_isEnabled) return; await ctx.TriggerTypingAsync(); string output; notFactID--; try { - output = notfacts[notFactID]; + output = _notfacts[notFactID]; } catch (Exception) { - output = notfacts[Program.rnd.Next(0, notfacts.Count)]; + output = _notfacts[Program.rnd.Next(0, _notfacts.Count)]; } await ctx.RespondAsync(StartEmbed(output)); } @@ -46,10 +46,10 @@ namespace StarsiegeBot [Command("count"), Aliases("c"), Description("Get a count of the NotFacts")] public async Task NotFactCount(CommandContext ctx) { - if (!IsEnabled) + if (!_isEnabled) return; await ctx.TriggerTypingAsync(); - await ctx.RespondAsync(StartEmbed(notfacts.Count + " NotFacts in the NotFacts Bank")); + await ctx.RespondAsync(StartEmbed(_notfacts.Count + " NotFacts in the NotFacts Bank")); } [Command("load"), RequireOwner, Aliases("l")] @@ -60,14 +60,14 @@ namespace StarsiegeBot // start the response. DiscordEmbedBuilder embed = StartEmbed("Reloading NotFacts"); // our old setting... - embed.AddField("Old", (IsEnabled ? "Enabled" : "Disabled")); + embed.AddField("Old", (_isEnabled ? "Enabled" : "Disabled")); // run this, we dont care about its actual results. _ = Load(); // report our new setting. - embed.AddField("New", (IsEnabled ? "Enabled" : "Disabled")); + embed.AddField("New", (_isEnabled ? "Enabled" : "Disabled")); // since the only thing that *should* go wrong is a missing file, report it if thats the case. - if (!File.Exists(fileName)) - embed.WithFooter($":warning: {fileName} file is missing."); + if (!File.Exists(s_fileName)) + embed.WithFooter($":warning: {s_fileName} file is missing."); // send our results. await ctx.RespondAsync(embed); } @@ -83,34 +83,34 @@ namespace StarsiegeBot string[] turnOff = { "off", "false", "0" }; //start our response. DiscordEmbedBuilder embed = StartEmbed("NotFact Toggle"); - embed.AddField("Old", (IsEnabled ? "Enabled" : "Disabled")); + embed.AddField("Old", (_isEnabled ? "Enabled" : "Disabled")); // check for file. - if (File.Exists(fileName)) + if (File.Exists(s_fileName)) { // compare desired input against on or off values. if (turnOn.Contains(isEnabled)) { - IsEnabled = true; - embed.AddField("New", (IsEnabled ? "Enabled" : "Disabled")); + _isEnabled = true; + embed.AddField("New", (_isEnabled ? "Enabled" : "Disabled")); } else if (turnOff.Contains(isEnabled)) { - IsEnabled = false; - embed.AddField("New", (IsEnabled ? "Enabled" : "Disabled")); + _isEnabled = false; + embed.AddField("New", (_isEnabled ? "Enabled" : "Disabled")); } else { // we dont know what they were trying to do, throw an error in the footer with a :warning: emote. - embed.AddField("New", (IsEnabled ? "Enabled" : "Disabled")); + embed.AddField("New", (_isEnabled ? "Enabled" : "Disabled")); embed.WithFooter(":warning: Invalid command given?"); } } else { // file is missing, disable this, regardless of their desires. Report the file is missing in the footer with a :warning: - IsEnabled = false; - embed.AddField("New", (IsEnabled ? "Enabled" : "Disabled")); - embed.WithFooter($":warning: {fileName} file is missing, and it can not be enabled."); + _isEnabled = false; + embed.AddField("New", (_isEnabled ? "Enabled" : "Disabled")); + embed.WithFooter($":warning: {s_fileName} file is missing, and it can not be enabled."); } await ctx.RespondAsync(embed); } @@ -129,17 +129,17 @@ namespace StarsiegeBot private bool Load() { bool ret; - if (File.Exists(fileName)) + if (File.Exists(s_fileName)) { - string json = File.ReadAllText(fileName); - notfacts = JsonConvert.DeserializeObject>(json); + string json = File.ReadAllText(s_fileName); + _notfacts = JsonConvert.DeserializeObject>(json); ret = true; } else { ret = false; } - IsEnabled = ret; + _isEnabled = ret; return ret; } } diff --git a/StarsiegeBot/Raven/SnappleFacts.cs b/StarsiegeBot/Raven/SnappleFacts.cs index 0fe91fe..4df305a 100644 --- a/StarsiegeBot/Raven/SnappleFacts.cs +++ b/StarsiegeBot/Raven/SnappleFacts.cs @@ -14,21 +14,21 @@ namespace StarsiegeBot [Group("snapple"), Aliases("snap")] class SnappleFacts : BaseCommandModule { - private List facts; - private bool IsEnabled; - private readonly string fileName = "Json/snapple.json"; + private List _facts; + private bool _isEnabled; + private static readonly string s_fileName = "Json/snapple.json"; public SnappleFacts() { Console.WriteLine("Snapple Commands Loaded"); - IsEnabled = Load(); + _isEnabled = Load(); } [GroupCommand, Description("Get a Snapple \"Real Fact\".")] public async Task Snapplefact(CommandContext ctx, [Description("[Optional] A Snapple Fact ID")] int snapId = 0) { // if we're not enabled, exit out. - if (!IsEnabled) + if (!_isEnabled) return; // trigger typing. await ctx.TriggerTypingAsync(); @@ -39,12 +39,12 @@ namespace StarsiegeBot try { // attempt to get the desired fact. - output = facts[snapId]; + output = _facts[snapId]; } catch (Exception) { // we couldn't find the exact one, give them a random one. - output = facts[Program.rnd.Next(0, facts.Count)]; + output = _facts[Program.rnd.Next(0, _facts.Count)]; } // give them what they want. await ctx.RespondAsync(StartEmbed(output)); @@ -53,11 +53,11 @@ namespace StarsiegeBot [Command("count"), Description("Get a Snapple \"Real Fact\"."), Aliases("c")] public async Task SnappleCount(CommandContext ctx) { - if (!IsEnabled) + if (!_isEnabled) return; await ctx.TriggerTypingAsync(); // trigger the typing, and report how many facts are in teh bank. - await ctx.RespondAsync(StartEmbed(facts.Count + " facts in the Snapple \"Real Facts\" Bank")); + await ctx.RespondAsync(StartEmbed(_facts.Count + " facts in the Snapple \"Real Facts\" Bank")); } [Command("load"), RequireOwner, Aliases("l")] @@ -68,20 +68,20 @@ namespace StarsiegeBot // start the response. DiscordEmbedBuilder embed = StartEmbed("Reloading Snapple Facts"); // our old setting... - embed.AddField("Old", (IsEnabled ? "Enabled" : "Disabled")); + embed.AddField("Old", (_isEnabled ? "Enabled" : "Disabled")); // run this, we dont care about its actual results. _ = Load(); // report our new setting. - embed.AddField("New", (IsEnabled ? "Enabled" : "Disabled")); + embed.AddField("New", (_isEnabled ? "Enabled" : "Disabled")); // since the only thing that *should* go wrong is a missing file, report it if thats the case. - if (!File.Exists(fileName)) - embed.WithFooter($":warning: {fileName} file is missing."); + if (!File.Exists(s_fileName)) + embed.WithFooter($":warning: {s_fileName} file is missing."); // send our results. await ctx.RespondAsync(embed); } [Command("toggle"), RequireOwner, Aliases("t")] - public async Task Enable (CommandContext ctx, [RemainingText]string isEnabled = null) + public async Task Enable(CommandContext ctx, [RemainingText] string isEnabled = null) { // trigger the typing. await ctx.TriggerTypingAsync(); @@ -91,34 +91,34 @@ namespace StarsiegeBot string[] turnOff = { "off", "false", "0" }; //start our response. DiscordEmbedBuilder embed = StartEmbed("Snapple Toggle"); - embed.AddField("Old", (IsEnabled ? "Enabled" : "Disabled")); + embed.AddField("Old", (_isEnabled ? "Enabled" : "Disabled")); // check for file. - if (File.Exists(fileName)) + if (File.Exists(s_fileName)) { // compare desired input against on or off values. if (turnOn.Contains(isEnabled)) { - IsEnabled = true; - embed.AddField("New", (IsEnabled ? "Enabled" : "Disabled")); + _isEnabled = true; + embed.AddField("New", (_isEnabled ? "Enabled" : "Disabled")); } else if (turnOff.Contains(isEnabled)) { - IsEnabled = false; - embed.AddField("New", (IsEnabled ? "Enabled" : "Disabled")); + _isEnabled = false; + embed.AddField("New", (_isEnabled ? "Enabled" : "Disabled")); } else { // we dont know what they were trying to do, throw an error in the footer with a :warning: emote. - embed.AddField("New", (IsEnabled ? "Enabled" : "Disabled")); + embed.AddField("New", (_isEnabled ? "Enabled" : "Disabled")); embed.WithFooter(":warning: Invalid command given?"); } } else { // file is missing, disable this, regardless of their desires. Report the file is missing in the footer with a :warning: - IsEnabled = false; - embed.AddField("New", (IsEnabled ? "Enabled" : "Disabled")); - embed.WithFooter($":warning: {fileName} file is missing, and it can not be enabled."); + _isEnabled = false; + embed.AddField("New", (_isEnabled ? "Enabled" : "Disabled")); + embed.WithFooter($":warning: {s_fileName} file is missing, and it can not be enabled."); } await ctx.RespondAsync(embed); } @@ -136,17 +136,17 @@ namespace StarsiegeBot private bool Load() { bool ret; - if (File.Exists(fileName)) + if (File.Exists(s_fileName)) { - string json = File.ReadAllText(fileName); - facts = JsonConvert.DeserializeObject>(json); + string json = File.ReadAllText(s_fileName); + _facts = JsonConvert.DeserializeObject>(json); ret = true; } else { ret = false; } - IsEnabled = ret; + _isEnabled = ret; return ret; } } diff --git a/StarsiegeBot/Raven/TriviaHandler.cs b/StarsiegeBot/Raven/TriviaHandler.cs index 91594d0..b3d00c0 100644 --- a/StarsiegeBot/Raven/TriviaHandler.cs +++ b/StarsiegeBot/Raven/TriviaHandler.cs @@ -15,17 +15,17 @@ namespace StarsiegeBot.Raven { class TriviaHandler : BaseCommandModule { - private readonly List QuizQuestions; - private readonly Random rnd = new Random(); + private readonly List _quizQuestions; + private static readonly string s_fileName = "Json/trivia.json"; public TriviaHandler() { // Load all the Quick Chat texts and sound wav file info. - var json = ""; - using (var fs = File.OpenRead("Json/questions.json")) - using (var sr = new StreamReader(fs, new UTF8Encoding(false))) + string json = ""; + using (FileStream fs = File.OpenRead(s_fileName)) + using (StreamReader sr = new StreamReader(fs, new UTF8Encoding(false))) json = sr.ReadToEnd(); Dictionary tempQC = JsonConvert.DeserializeObject>(json); - QuizQuestions = Enumerable.ToList(tempQC.Values); + _quizQuestions = Enumerable.ToList(tempQC.Values); } [Command("quiz")] @@ -36,25 +36,25 @@ namespace StarsiegeBot.Raven await ctx.TriggerTypingAsync(); DiscordEmbedBuilder embed = new DiscordEmbedBuilder(); - int[] ids = { rnd.Next(QuizQuestions.Count), rnd.Next(QuizQuestions.Count), rnd.Next(QuizQuestions.Count), rnd.Next(QuizQuestions.Count) }; - int selection = rnd.Next(ids.Length); + int[] ids = { Program.rnd.Next(_quizQuestions.Count), Program.rnd.Next(_quizQuestions.Count), Program.rnd.Next(_quizQuestions.Count), Program.rnd.Next(_quizQuestions.Count) }; + int selection = Program.rnd.Next(ids.Length); int mainId = ids[selection]; string[] options = { "a", "b", "c", "d" }; var correctAnswer = DiscordEmoji.FromName(ctx.Client, $":regional_indicator_{options[selection]}:"); - Questions myQuestion = QuizQuestions[mainId]; + Questions myQuestion = _quizQuestions[mainId]; embed.Description = myQuestion.Question; - embed.AddField($":regional_indicator_{options[0]}:", QuizQuestions[ids[0]].Answers[rnd.Next(QuizQuestions[ids[0]].Answers.Length)], true); - embed.AddField($":regional_indicator_{options[1]}:", QuizQuestions[ids[1]].Answers[rnd.Next(QuizQuestions[ids[1]].Answers.Length)], true); + embed.AddField($":regional_indicator_{options[0]}:", _quizQuestions[ids[0]].Answers[Program.rnd.Next(_quizQuestions[ids[0]].Answers.Length)], true); + embed.AddField($":regional_indicator_{options[1]}:", _quizQuestions[ids[1]].Answers[Program.rnd.Next(_quizQuestions[ids[1]].Answers.Length)], true); embed.AddField("_ _", "_ _", false); - embed.AddField($":regional_indicator_{options[2]}:", QuizQuestions[ids[2]].Answers[rnd.Next(QuizQuestions[ids[2]].Answers.Length)], true); - embed.AddField($":regional_indicator_{options[3]}:", QuizQuestions[ids[3]].Answers[rnd.Next(QuizQuestions[ids[3]].Answers.Length)], true); + embed.AddField($":regional_indicator_{options[2]}:", _quizQuestions[ids[2]].Answers[Program.rnd.Next(_quizQuestions[ids[2]].Answers.Length)], true); + embed.AddField($":regional_indicator_{options[3]}:", _quizQuestions[ids[3]].Answers[Program.rnd.Next(_quizQuestions[ids[3]].Answers.Length)], true); - var message = await ctx.RespondAsync(embed); - foreach (var item in options) + DiscordMessage message = await ctx.RespondAsync(embed); + foreach (string item in options) { var itemEmote = DiscordEmoji.FromName(ctx.Client, $":regional_indicator_{item}:"); await message.CreateReactionAsync(itemEmote); @@ -72,16 +72,16 @@ namespace StarsiegeBot.Raven [Hidden] public async Task CollectionCommand(CommandContext ctx) { - var message = await ctx.RespondAsync("React here!"); + DiscordMessage message = await ctx.RespondAsync("React here!"); var reactions = await message.CollectReactionsAsync(); var strBuilder = new StringBuilder(); Dictionary winners = new Dictionary(); Dictionary losers = new Dictionary(); - var correctEmote = reactions[0].Emoji; + DiscordEmoji correctEmote = reactions[0].Emoji; foreach (var reaction in reactions) { - foreach (var person in reaction.Users) + foreach (DiscordUser person in reaction.Users) { if (!correctEmote.Equals(reaction.Emoji)) { diff --git a/StarsiegeBot/Starsiege/DeathMessages.cs b/StarsiegeBot/Starsiege/DeathMessages.cs index 0f60b44..b2dd345 100644 --- a/StarsiegeBot/Starsiege/DeathMessages.cs +++ b/StarsiegeBot/Starsiege/DeathMessages.cs @@ -19,32 +19,32 @@ namespace StarsiegeBot [Cooldown(1, 2, CooldownBucketType.Guild)] class DeathMessages : BaseCommandModule { - private DeathMessageLines dmLines; - private bool DeathMessagesEnabled; - private static readonly string fileName = "Json/deathmessages.json"; + private DeathMessageLines _dmLines; + private bool _deathMessagesEnabled; + private static readonly string s_fileName = "Json/deathmessages.json"; public DeathMessages() { Console.WriteLine("Death Message Commands Loaded."); // If the DeathMessages file exists, load it. And enable the commands. // Otherwise disable all the commands. - if (File.Exists(fileName)) + if (File.Exists(s_fileName)) { // set some JSON text to blank. - var json = ""; - using (var fs = File.OpenRead(fileName)) - using (var sr = new StreamReader(fs, new UTF8Encoding(false))) + string json = ""; + using (FileStream fs = File.OpenRead(s_fileName)) + using (StreamReader sr = new StreamReader(fs, new UTF8Encoding(false))) json = sr.ReadToEnd(); // Decode the JSON and set it to dmLines. - dmLines = JsonConvert.DeserializeObject(json); + _dmLines = JsonConvert.DeserializeObject(json); // Enable all the commands. - DeathMessagesEnabled = true; + _deathMessagesEnabled = true; } else { // Echo out that we're missing a file. Disable the commands due to that. - Console.WriteLine($" --- --- --- --- {fileName} is missing"); - DeathMessagesEnabled = false; + Console.WriteLine($" --- --- --- --- {s_fileName} is missing"); + _deathMessagesEnabled = false; } } @@ -53,24 +53,24 @@ namespace StarsiegeBot public async Task LoadDeathMessages(CommandContext ctx) { await ctx.TriggerTypingAsync(); - if (File.Exists(fileName)) + if (File.Exists(s_fileName)) { // set some JSON text to blank. - var json = ""; - using (var fs = File.OpenRead(fileName)) - using (var sr = new StreamReader(fs, new UTF8Encoding(false))) + string json = ""; + using (FileStream fs = File.OpenRead(s_fileName)) + using (StreamReader sr = new StreamReader(fs, new UTF8Encoding(false))) json = sr.ReadToEnd(); // Decode the JSON and set it to dmLines. - dmLines = JsonConvert.DeserializeObject(json); + _dmLines = JsonConvert.DeserializeObject(json); // Enable all the commands. - DeathMessagesEnabled = true; + _deathMessagesEnabled = true; await ctx.RespondAsync("Loading Death Messages successul."); } else { // Echo out that we're missing a file. Disable the commands due to that. await ctx.RespondAsync("Can't load Death Messages. File missing."); - DeathMessagesEnabled = false; + _deathMessagesEnabled = false; } } @@ -87,26 +87,26 @@ namespace StarsiegeBot string[] turnOn = { "on", "true", "1" }; string[] turnOff = { "off", "false", "0" }; - if (File.Exists(fileName)) + if (File.Exists(s_fileName)) { if (turnOn.Contains(isEnabled)) { - DeathMessagesEnabled = true; + _deathMessagesEnabled = true; } else if (turnOff.Contains(isEnabled)) { - DeathMessagesEnabled = false; + _deathMessagesEnabled = false; } else { } - output = $"DeathMessages Enabled: {DeathMessagesEnabled}"; + output = $"DeathMessages Enabled: {_deathMessagesEnabled}"; } else { - DeathMessagesEnabled = false; - output = $"{fileName} file is missing, and it can not be enabled."; + _deathMessagesEnabled = false; + output = $"{s_fileName} file is missing, and it can not be enabled."; } await ctx.RespondAsync(output); } @@ -119,7 +119,7 @@ namespace StarsiegeBot // IF we're missing the Death Messages dot JSON file, we're going to get disabled... Check for that. // If disabled, let the person know the command set is disabled, and return. - if (!DeathMessagesEnabled) + if (!_deathMessagesEnabled) { await ctx.RespondAsync("Death Messages Commands have been disabled. Please contact the bot owners."); return; @@ -130,8 +130,8 @@ namespace StarsiegeBot // if there is no target, we're going to "kill" the author. if (target == null) { - int choice = Program.rnd.Next(0, dmLines.Generic.Length); - line = dmLines.Generic[choice]; + int choice = Program.rnd.Next(0, _dmLines.Generic.Length); + line = _dmLines.Generic[choice]; await ctx.RespondAsync(string.Format(line, ctx.Message.Author.Mention)); } // we have a valid target... Have the bot kill them. @@ -143,14 +143,14 @@ namespace StarsiegeBot if (opt == 1) { // Pick an Active death message at random, and set our output to it. - int choice = Program.rnd.Next(0, dmLines.Active.Length); - line = dmLines.Active[choice]; + int choice = Program.rnd.Next(0, _dmLines.Active.Length); + line = _dmLines.Active[choice]; } else if (opt == 2) { // We picked a Passive death message type. Pick the exact line at random. Set it to the output. - int choice = Program.rnd.Next(0, dmLines.Passive.Length); - line = dmLines.Passive[choice]; + int choice = Program.rnd.Next(0, _dmLines.Passive.Length); + line = _dmLines.Passive[choice]; } // Give the selected death message to the user. await ctx.RespondAsync(string.Format(line, ctx.Message.Author.Mention, target.Mention)); @@ -163,7 +163,7 @@ namespace StarsiegeBot { // IF we're missing the Death Messages dot JSON file, we're going to get disabled... Check for that. // If disabled, let the person know the command set is disabled, and return. - if (!DeathMessagesEnabled) + if (!_deathMessagesEnabled) { await ctx.RespondAsync("Death Messages Commands have been disabled. Please contact the bot owners."); return; @@ -171,7 +171,7 @@ namespace StarsiegeBot // We're typing here! await ctx.TriggerTypingAsync(); // List all the types of Death Message types, and how many we have of each one. - await ctx.RespondAsync($"\r\nActive: {dmLines.Active.Length}\r\nPassive: {dmLines.Passive.Length}\r\nGeneric: {dmLines.Generic.Length}"); + await ctx.RespondAsync($"\r\nActive: {_dmLines.Active.Length}\r\nPassive: {_dmLines.Passive.Length}\r\nGeneric: {_dmLines.Generic.Length}"); } [Command("Add")] @@ -181,7 +181,7 @@ namespace StarsiegeBot { // IF we're missing the Death Messages dot JSON file, we're going to get disabled... Check for that. // If disabled, let the person know the command set is disabled, and return. - if (!DeathMessagesEnabled) + if (!_deathMessagesEnabled) { await ctx.RespondAsync("Death Messages Commands have been disabled. Please contact the bot owners."); return; @@ -191,10 +191,10 @@ namespace StarsiegeBot // Message the owner know some one wants to add a new death message, along with a code block to that message. // if the Queue is null, make it exist. - if (dmLines.Queue is null) - dmLines.Queue = new List(); + if (_dmLines.Queue is null) + _dmLines.Queue = new List(); // add the message to the queue list. - dmLines.Queue.Add(msg); + _dmLines.Queue.Add(msg); // Store the new stuff to file... await StoreDeathMessages(); // Tell the person that the message has been added to a 'queue'. @@ -208,7 +208,7 @@ namespace StarsiegeBot await ctx.TriggerTypingAsync(); // IF we're missing the Death Messages dot JSON file, we're going to get disabled... Check for that. // If disabled, let the person know the command set is disabled, and return. - if (!DeathMessagesEnabled) + if (!_deathMessagesEnabled) { await ctx.RespondAsync("Death Messages Commands have been disabled. Please contact the bot owners."); return; @@ -224,27 +224,27 @@ namespace StarsiegeBot using StreamWriter file = new StreamWriter("deathmessages.cs"); // Write out the total lines for each. Requirement for Starsiege. - await file.WriteLineAsync($"$deathMessage::genericCount = {dmLines.Generic.Length};"); - await file.WriteLineAsync($"$deathMessage::activeCount = {dmLines.Active.Length};"); - await file.WriteLineAsync($"$deathMessage::passiveCount = {dmLines.Passive.Length};\r\n"); + await file.WriteLineAsync($"$deathMessage::genericCount = {_dmLines.Generic.Length};"); + await file.WriteLineAsync($"$deathMessage::activeCount = {_dmLines.Active.Length};"); + await file.WriteLineAsync($"$deathMessage::passiveCount = {_dmLines.Passive.Length};\r\n"); // Set count to 0. Iterate over each type of Death Message, and put it into the file. int count = 0; - foreach (string death in dmLines.Generic) + foreach (string death in _dmLines.Generic) { await file.WriteLineAsync(string.Format($"$deathMessage::generic{count} = \"{death}\";", "%s", "%s")); count++; } // Reset the count... count = 0; - foreach (string death in dmLines.Active) + foreach (string death in _dmLines.Active) { await file.WriteLineAsync(string.Format($"$deathMessage::active{count} = \"{death}\";", "%s", "%s")); count++; } // Reset the count one last time... count = 0; - foreach (string death in dmLines.Passive) + foreach (string death in _dmLines.Passive) { await file.WriteLineAsync(string.Format($"$deathMessage::passive{count} = \"{death}\";", "%s", "%s")); count++; @@ -269,8 +269,8 @@ namespace StarsiegeBot private async Task StoreDeathMessages() { - string output = JsonConvert.SerializeObject(dmLines); - await File.WriteAllTextAsync(fileName, output); + string output = JsonConvert.SerializeObject(_dmLines); + await File.WriteAllTextAsync(s_fileName, output); return; } } @@ -283,8 +283,8 @@ namespace StarsiegeBot [JsonProperty("generic")] public string[] Generic { get; set; } [JsonProperty("flagged")] - public List Flagged { get; set; } + public List Flagged { get; set; } [JsonProperty("queue")] - public List Queue { get; set; } + public List Queue { get; set; } } } diff --git a/StarsiegeBot/Starsiege/Functions.cs b/StarsiegeBot/Starsiege/Functions.cs index 6c63b8c..c4d0903 100644 --- a/StarsiegeBot/Starsiege/Functions.cs +++ b/StarsiegeBot/Starsiege/Functions.cs @@ -16,27 +16,27 @@ namespace StarsiegeBot [Group("functions"), Aliases("func")] class Functions : BaseCommandModule { - private Dictionary ssFunctions; - private bool FunctionsEnabled; - private static readonly string fileName = "Json/functions.json"; + private Dictionary _ssFunctions; + private bool _functionsEnabled; + private static readonly string s_fileName = "Json/functions.json"; public Functions() { Console.WriteLine("Starsiege Function Commands Loaded"); // Check for file, if not there, disable commands. - if (File.Exists(fileName)) + if (File.Exists(s_fileName)) { // Load the Functions JSON file. Has all information regarding Starsiege in-game Functions. - var json = ""; - using (var fs = File.OpenRead(fileName)) - using (var sr = new StreamReader(fs, new UTF8Encoding(false))) + string json = ""; + using (FileStream fs = File.OpenRead(s_fileName)) + using (StreamReader sr = new StreamReader(fs, new UTF8Encoding(false))) json = sr.ReadToEnd(); - ssFunctions = JsonConvert.DeserializeObject>(json); - FunctionsEnabled = true; + _ssFunctions = JsonConvert.DeserializeObject>(json); + _functionsEnabled = true; } else { - FunctionsEnabled = false; + _functionsEnabled = false; Console.WriteLine(" --- --- --- Functions JSON not found."); } } @@ -46,7 +46,7 @@ namespace StarsiegeBot public async Task StarsiegeFunctions(CommandContext ctx, [RemainingText, Description("The function to attempt to look up.")] string command = "") { await ctx.TriggerTypingAsync(); - if (!FunctionsEnabled) + if (!_functionsEnabled) { await ctx.RespondAsync("Function Commands have been disabled. Please contact the bot owners."); return; @@ -56,7 +56,7 @@ namespace StarsiegeBot if (command.Equals(string.Empty)) { // Get a list of the Keys. - List keys = new List(ssFunctions.Keys); + List keys = new List(_ssFunctions.Keys); // get a new output. string output = string.Empty; // loop over the keys. @@ -78,7 +78,7 @@ namespace StarsiegeBot } // we have a command the want to try to find. - else if (ssFunctions.TryGetValue(command.ToLower(), out SSFunction outItem)) + else if (_ssFunctions.TryGetValue(command.ToLower(), out SSFunction outItem)) { // New Message Embed! DiscordEmbedBuilder embed = new DiscordEmbedBuilder(); @@ -113,13 +113,13 @@ namespace StarsiegeBot await ctx.TriggerTypingAsync(); // check ot make sure these commands are enabled. if disabled, report it. - if (!FunctionsEnabled) + if (!_functionsEnabled) { await ctx.RespondAsync("Function Commands have been disabled. Please contact the bot owners."); return; } // they wanted to know how many functions were documented... so tell them! - await ctx.RespondAsync($"There are {ssFunctions.Count} functions in the known list."); + await ctx.RespondAsync($"There are {_ssFunctions.Count} functions in the known list."); } [Command("toggle"), Aliases("t")] @@ -135,26 +135,26 @@ namespace StarsiegeBot string[] turnOn = { "on", "true", "1" }; string[] turnOff = { "off", "false", "0" }; - if (File.Exists(fileName)) + if (File.Exists(s_fileName)) { if (turnOn.Contains(isEnabled)) { - FunctionsEnabled = true; + _functionsEnabled = true; } else if (turnOff.Contains(isEnabled)) { - FunctionsEnabled = false; + _functionsEnabled = false; } else { } - output = $"Functions Enabled: {FunctionsEnabled}"; + output = $"Functions Enabled: {_functionsEnabled}"; } else { - FunctionsEnabled = false; - output = $"{fileName} file is missing, and it can not be enabled."; + _functionsEnabled = false; + output = $"{s_fileName} file is missing, and it can not be enabled."; } await ctx.RespondAsync(output); } @@ -164,20 +164,20 @@ namespace StarsiegeBot await ctx.TriggerTypingAsync(); // Check for file, if not there, disable commands. - if (File.Exists(fileName)) + if (File.Exists(s_fileName)) { // Load the Functions JSON file. Has all information regarding Starsiege in-game Functions. - var json = ""; - using (var fs = File.OpenRead(fileName)) - using (var sr = new StreamReader(fs, new UTF8Encoding(false))) + string json = ""; + using (FileStream fs = File.OpenRead(s_fileName)) + using (StreamReader sr = new StreamReader(fs, new UTF8Encoding(false))) json = sr.ReadToEnd(); - ssFunctions = JsonConvert.DeserializeObject>(json); - FunctionsEnabled = true; + _ssFunctions = JsonConvert.DeserializeObject>(json); + _functionsEnabled = true; await ctx.RespondAsync("Loading Quick Chats successul."); } else { - FunctionsEnabled = false; + _functionsEnabled = false; await ctx.RespondAsync("Loading Functions failed. File does not exist."); } } diff --git a/StarsiegeBot/Starsiege/GameInfo.cs b/StarsiegeBot/Starsiege/GameInfo.cs index 2d7c853..f184a38 100644 --- a/StarsiegeBot/Starsiege/GameInfo.cs +++ b/StarsiegeBot/Starsiege/GameInfo.cs @@ -14,7 +14,7 @@ namespace StarsiegeBot [Description("Gives various reports on the game or master servers.")] class GameInfo : BaseCommandModule { - private WebServerItems gameData; + private WebServerItems _gameData; public GameInfo() { Update(); @@ -22,20 +22,20 @@ namespace StarsiegeBot } private void Update() { - if (gameData is null) + if (_gameData is null) { using WebClient wc = new WebClient(); - var json = wc.DownloadString("https://alpha.starsiegeplayers.com/api/v1/multiplayer/servers"); - gameData = JsonConvert.DeserializeObject(json); + string json = wc.DownloadString("https://alpha.starsiegeplayers.com/api/v1/multiplayer/servers"); + _gameData = JsonConvert.DeserializeObject(json); } else { using WebClient wc = new WebClient(); - var json = wc.DownloadString("https://alpha.starsiegeplayers.com/api/v1/multiplayer/servers"); + string json = wc.DownloadString("https://alpha.starsiegeplayers.com/api/v1/multiplayer/servers"); WebServerItems temp = JsonConvert.DeserializeObject(json); - if (temp.RequestTime != gameData.RequestTime) + if (temp.RequestTime != _gameData.RequestTime) { - gameData = temp; + _gameData = temp; } } } @@ -47,7 +47,7 @@ namespace StarsiegeBot // setup an exit point check. bool exit = false; // if its null, we're going to exit. - if (gameData is null || gameData.Errors is null) + if (_gameData is null || _gameData.Errors is null) { exit = true; } @@ -60,9 +60,9 @@ namespace StarsiegeBot Title = "Master|Game Server Overview", Description = "Number of Master, and Game servers. Along with number of errors." }; - embed.AddField("Masters", gameData.Masters.Length.ToString(), true); - embed.AddField("Games", gameData.Games.Length.ToString(), true); - embed.AddField("Errors", gameData.Errors.Length.ToString(), true); + embed.AddField("Masters", _gameData.Masters.Length.ToString(), true); + embed.AddField("Games", _gameData.Games.Length.ToString(), true); + embed.AddField("Errors", _gameData.Errors.Length.ToString(), true); await ctx.RespondAsync(embed); } @@ -75,7 +75,7 @@ namespace StarsiegeBot // setup an exit point check. bool exit = false; // if its null, we're going to exit. - if (gameData is null || gameData.Errors is null) + if (_gameData is null || _gameData.Errors is null) { exit = true; } @@ -87,7 +87,7 @@ namespace StarsiegeBot { Content = "Server Listing Errors:\r\n" }; - foreach (var item in gameData.Errors) + foreach (string item in _gameData.Errors) { msg.Content += $"{item}\r\n"; } @@ -103,7 +103,7 @@ namespace StarsiegeBot // setup an exit point check. bool exit = false; // if its null, we're going to exit. - if (gameData is null || gameData.Masters is null) + if (_gameData is null || _gameData.Masters is null) { exit = true; } @@ -116,7 +116,7 @@ namespace StarsiegeBot Content = "```csharp\r\n" }; int count = 0; - foreach (var item in gameData.Masters) + foreach (MasterServer item in _gameData.Masters) { count++; msg.Content += $"$Inet::Master{count} = \"IP:{item.Address}\";\r\n"; @@ -135,7 +135,7 @@ namespace StarsiegeBot // setup an exit point check. bool exit = false; // if its null, we're going to exit. - if (gameData is null || gameData.Games is null) + if (_gameData is null || _gameData.Games is null) { exit = true; } @@ -147,7 +147,7 @@ namespace StarsiegeBot DiscordMessageBuilder msg = new DiscordMessageBuilder(); // we're on our way to greatness! int count = 0; - foreach (var item in gameData.Games) + foreach (GameServer item in _gameData.Games) { // if (item.PlayerCount > playerCount) if (item.GameStatus["Started"]) diff --git a/StarsiegeBot/Starsiege/QuickchatHandler.cs b/StarsiegeBot/Starsiege/QuickchatHandler.cs index 34e499b..da15575 100644 --- a/StarsiegeBot/Starsiege/QuickchatHandler.cs +++ b/StarsiegeBot/Starsiege/QuickchatHandler.cs @@ -16,15 +16,15 @@ namespace StarsiegeBot [Aliases("qc"), Group("quickchat")] class QuickchatHandler : BaseCommandModule { - private Dictionary quickchats; - private bool IsEnabled; - private readonly string fileName = "Json/quickchats.json"; + private Dictionary _quickchats; + private bool _isEnabled; + private readonly string _fileName = "Json/quickchats.json"; public QuickchatHandler() { Console.WriteLine("Quick Chat Handler Loaded"); - IsEnabled = LoadQuickChatsImpl(); + _isEnabled = LoadQuickChatsImpl(); } /** @@ -34,14 +34,14 @@ namespace StarsiegeBot private bool LoadQuickChatsImpl() { // Check to see if the file exists... - if (File.Exists(fileName)) + if (File.Exists(_fileName)) { // Load the JSON file. - var json = ""; - using (var fs = File.OpenRead(fileName)) - using (var sr = new StreamReader(fs, new UTF8Encoding(false))) + string json = ""; + using (FileStream fs = File.OpenRead(_fileName)) + using (StreamReader sr = new StreamReader(fs, new UTF8Encoding(false))) json = sr.ReadToEnd(); - quickchats = JsonConvert.DeserializeObject>(json); + _quickchats = JsonConvert.DeserializeObject>(json); // enable the commands. return true; } @@ -57,8 +57,8 @@ namespace StarsiegeBot { await ctx.TriggerTypingAsync(); string output; - IsEnabled = LoadQuickChatsImpl(); - if (IsEnabled) + _isEnabled = LoadQuickChatsImpl(); + if (_isEnabled) { output = "Loading Quick Chats successful."; } @@ -74,7 +74,7 @@ namespace StarsiegeBot public async Task GetQuickChatScript(CommandContext ctx, [Description("ID of Quick chat to get script for.")] int index) { // If we're disabled, let them know. And exit out. - if (!IsEnabled) + if (!_isEnabled) { return; } @@ -85,16 +85,16 @@ namespace StarsiegeBot index = Math.Abs(index); // is our index within bounds? - if (index < quickchats.Count) + if (index < _quickchats.Count) { // yes it is, give the script to them. - Quickchat chat = quickchats[index.ToString()]; + Quickchat chat = _quickchats[index.ToString()]; await ctx.RespondAsync("```" + chat.ToString() + "```"); return; } // we couldn't find it... Oh well, let the end user know. - await ctx.RespondAsync("The ID specified is out of bounds. 0-" + (quickchats.Count - 1)); + await ctx.RespondAsync("The ID specified is out of bounds. 0-" + (_quickchats.Count - 1)); } [Command("check")] @@ -102,7 +102,7 @@ namespace StarsiegeBot public async Task QuickChatCheck(CommandContext ctx) { // If we're disabled, let them know. And exit out. - if (!IsEnabled) + if (!_isEnabled) { return; } @@ -110,10 +110,10 @@ namespace StarsiegeBot // Start a count int missingFiles = 0; - for (int i = 0; i < quickchats.Count; i++) + for (int i = 0; i < _quickchats.Count; i++) { // If this file doesnt exist, log the ID in the console, and add to the count. - if (!File.Exists($"./qc/{quickchats[i.ToString()].SoundFile}")) + if (!File.Exists($"./qc/{_quickchats[i.ToString()].SoundFile}")) { missingFiles++; Console.Write($"{i}, "); @@ -129,7 +129,7 @@ namespace StarsiegeBot public async Task QuickChat(CommandContext ctx, [Description("The ID of the quick Chat.")] int id = -1) { // If we're disabled, let them know. And exit out. - if (!IsEnabled) + if (!_isEnabled) { return; } @@ -148,7 +148,7 @@ namespace StarsiegeBot { id = Math.Abs(id); } - chat = quickchats[id.ToString()]; + chat = _quickchats[id.ToString()]; output = id + ": " + chat.Text; } catch (Exception) @@ -158,8 +158,8 @@ namespace StarsiegeBot { try { - id = Program.rnd.Next(quickchats.Count); - chat = quickchats[id.ToString()]; + id = Program.rnd.Next(_quickchats.Count); + chat = _quickchats[id.ToString()]; output = $"[{id}] " + chat.Text; } catch (Exception) @@ -195,7 +195,7 @@ namespace StarsiegeBot string output; // If we're disabled, let them know. And exit out. - if (!IsEnabled) + if (!_isEnabled) { await ctx.RespondAsync("Quick Chat Commands have been disabled. Please contact the bot owners."); return; @@ -207,19 +207,19 @@ namespace StarsiegeBot int count = 0; // We're going to search each QC for the stuff in toSearch. - foreach (KeyValuePair qc in quickchats) + foreach (KeyValuePair qc in _quickchats) { // do we have a match? if (qc.Value.Text.ToLower().Contains(toSearch.ToLower())) { // add it to the list! - sb.Append($"[{qc.Key}][T] {quickchats[qc.Key].Text}\r\n"); + sb.Append($"[{qc.Key}][T] {_quickchats[qc.Key].Text}\r\n"); count++; } if (qc.Value.SoundFile.ToLower().Contains(toSearch.ToLower())) { // add it to the list! - sb.Append($"[{qc.Key}][S] {quickchats[qc.Key].Text}\r\n"); + sb.Append($"[{qc.Key}][S] {_quickchats[qc.Key].Text}\r\n"); count++; } } @@ -243,16 +243,37 @@ namespace StarsiegeBot [Command("flag")] [Description("Flags a Quick Chat for moderator checking.")] - public async Task FlagQC(CommandContext ctx, [Description("ID of QC to flag.")] int id, [RemainingText, Description("The reason you believe it needs flagged.")] string flagRerason = "") + public async Task FlagQC(CommandContext ctx, [Description("ID of QC to flag.")] int id, [RemainingText, Description("The reason you believe it needs flagged.")] string flagReason = "") { await ctx.TriggerTypingAsync(); - Quickchat chat = quickchats[id.ToString()]; + Quickchat chat = _quickchats[id.ToString()]; DiscordEmbedBuilder embed; - chat.FlagCount++; - embed = StartEmbed($"Flagging QC ID `{id}` with reason of `{flagRerason}`. (F{chat.FlagCount})"); + + + foreach (FlagEvent item in chat.Flags) + { + if (item.UserId == ctx.Member.Id) + { + item.Reason = flagReason; + embed = StartEmbed($"Each user can only flag an item once. Updating your reason to `{flagReason}`"); + string dateReason = DateTime.UtcNow.ToString(); + embed.WithFooter(dateReason); + await ctx.RespondAsync(embed); + //return; + } + } + //if (chat.Flags.ContainsKey(ctx.Member.Id)) + //{ + // chat.Flags[ctx.Member.Id] = flagReason; + // await ctx.RespondAsync(StartEmbed($"Each user can only flag an item once. Updating your reason to `{flagReason}`")); + //} + // chat.Flags.Add(ctx.Member.Id, flagReason); + //FlagEvent event = new FlagEvent(); + embed = StartEmbed($"Flagging QC ID `{id}` with reason of `{flagReason}`. (F{chat.Flags.Count})"); chat.IsFlagged = true; - string output = JsonConvert.SerializeObject(quickchats); - await File.WriteAllTextAsync(fileName, output); + string output = JsonConvert.SerializeObject(_quickchats); + await File.WriteAllTextAsync(_fileName, output); + await ctx.RespondAsync(embed); } @@ -261,7 +282,7 @@ namespace StarsiegeBot { await ctx.TriggerTypingAsync(); int count = 0; - foreach (var chat in quickchats) + foreach (KeyValuePair chat in _quickchats) { if (chat.Value.IsFlagged) { @@ -271,7 +292,6 @@ namespace StarsiegeBot await ctx.RespondAsync(StartEmbed($"There are {count} flagged Quick Chats.")); } - [Command("toggle"), Aliases("t")] [RequireOwner] [Description("[Owner only] Enables or disables, or checks status of QuickChats.\r\nTo turn the feature on, use `TRUE`, `ON`, or `1`\r\nTo turn off, use `FALSE`, `OFF`, or `0`")] @@ -283,23 +303,23 @@ namespace StarsiegeBot string[] turnOn = { "on", "true", "1" }; string[] turnOff = { "off", "false", "0" }; - if (File.Exists(fileName)) + if (File.Exists(_fileName)) { if (turnOn.Contains(isEnabled)) { - IsEnabled = true; + _isEnabled = true; } if (turnOff.Contains(isEnabled)) { - IsEnabled = false; + _isEnabled = false; } - output = $"Quickchats {(IsEnabled ? "Enabled" : "Disabled")}"; + output = $"Quickchats {(_isEnabled ? "Enabled" : "Disabled")}"; } else { - IsEnabled = false; - output = $"{fileName} file is missing, and it can not be enabled."; + _isEnabled = false; + output = $"{_fileName} file is missing, and it can not be enabled."; } await ctx.RespondAsync(StartEmbed(output)); } @@ -322,11 +342,40 @@ namespace StarsiegeBot [JsonProperty("soundFile")] public string SoundFile { get; protected set; } public bool IsFlagged { get; set; } - public int FlagCount { get; set; } + [JsonProperty("flags")] + public List Flags { get; set; } public override string ToString() { return $"say(0,0, \"{Text}\", \"{SoundFile}\");"; } } + public class FlagEvent : IEquatable + { + public ulong UserId { get; set; } + public string Reason { get; set; } + public string Timestamp { get; set; } + public FlagEvent(ulong UserId, string Reason, string Timestamp) + { + this.UserId = UserId; + this.Reason = Reason; + this.Timestamp = Timestamp; + } + public bool Equals(FlagEvent e) + { + return UserId == e.UserId; + } + public bool Equals(ulong s) + { + return UserId == s; + } + public override bool Equals(object o) + { + return false; + } + public override int GetHashCode() + { + return UserId.GetHashCode(); + } + } } diff --git a/StarsiegeBot/WelcomeMessage.cs b/StarsiegeBot/WelcomeMessage.cs index ca13b80..56deaf1 100644 --- a/StarsiegeBot/WelcomeMessage.cs +++ b/StarsiegeBot/WelcomeMessage.cs @@ -12,7 +12,7 @@ namespace StarsiegeBot [Group("welcome")] [RequireGuild, RequirePermissions(Permissions.ManageChannels), - Cooldown(1,10,CooldownBucketType.Global), + Cooldown(1, 10, CooldownBucketType.Global), RequireNsfw, RequireBotPermissions(Permissions.AccessChannels) //RequireBotPermissions(Permissions.AddReactions),