Modified the Flag sub command of QuickChatHandler. Added '.editorconfig' and conformed majority of files to fit within it's scopes.

This commit is contained in:
Christopher Darnell authored and cmd276 committed 2021-05-06 13:53:56 -07:00
1 parent 990aca3e41
commit 1e3e8eb69b
16 files changed
+581 -330

No files matched your search

+201
View File
@@ -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
+14 -14
View File
@@ -18,8 +18,8 @@ namespace StarsiegeBot
class BotSettings : BaseCommandModule class BotSettings : BaseCommandModule
{ {
public static Dictionary<string, GuildSettings> GuildSettings; public static Dictionary<string, GuildSettings> GuildSettings;
private readonly string fileName = "Json/guildsettings.json"; private readonly string _fileName = "Json/guildsettings.json";
private readonly CancellationTokenSource cancelToken; private readonly CancellationTokenSource _cancelToken;
public BotSettings() public BotSettings()
{ {
Console.WriteLine("Bot Setting Commands Loaded"); Console.WriteLine("Bot Setting Commands Loaded");
@@ -30,7 +30,7 @@ namespace StarsiegeBot
return; return;
} }
// Check for guild settings file. If it doesnt exist, create it. // 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. // Since we need to creat it, we're going to set some default stuff.
Console.Write("Guild Settings Config File Not Found. Creating One..."); 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. // Now that we have the initial stuff in memory, write it to file.
string output = JsonConvert.SerializeObject(GuildSettings); 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. // in form the console reader that we're done making the initial config.
Console.WriteLine(" Done!"); Console.WriteLine(" Done!");
} }
else else
{ {
// load the config file to memory. // load the config file to memory.
var json = ""; string json = "";
using (var fs = File.OpenRead(fileName)) using (FileStream fs = File.OpenRead(_fileName))
using (var sr = new StreamReader(fs, new UTF8Encoding(false))) using (StreamReader sr = new StreamReader(fs, new UTF8Encoding(false)))
json = sr.ReadToEnd(); json = sr.ReadToEnd();
GuildSettings = JsonConvert.DeserializeObject<Dictionary<string, GuildSettings>>(json); GuildSettings = JsonConvert.DeserializeObject<Dictionary<string, GuildSettings>>(json);
} }
cancelToken = new CancellationTokenSource(); _cancelToken = new CancellationTokenSource();
_ = StartTimer(cancelToken.Token); _ = StartTimer(_cancelToken.Token);
} }
[GroupCommand] [GroupCommand]
[Description("Reports simplified data about the server settings.")] [Description("Reports simplified data about the server settings.")]
public async Task BaseItem(CommandContext ctx) public async Task BaseItem(CommandContext ctx)
{ {
await ctx.TriggerTypingAsync(); 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."); DiscordEmbedBuilder embed = StartEmbed(ctx.Guild.Name + " Server settings.");
embed.AddField("On/Off Items", "_ _"); embed.AddField("On/Off Items", "_ _");
embed.AddField("Global Prefix", (guild.UseGlobalPrefix ? "On" : "Off"), true); embed.AddField("Global Prefix", (guild.UseGlobalPrefix ? "On" : "Off"), true);
@@ -96,10 +96,10 @@ namespace StarsiegeBot
[Command("status"), RequireOwner] [Command("status"), RequireOwner]
[Description("Sets the bot's nickname on this server.")] [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(); await ctx.TriggerTypingAsync();
var aType = type.ToLower() switch ActivityType aType = type.ToLower() switch
{ {
"competing" => ActivityType.Competing, "competing" => ActivityType.Competing,
"listening" => ActivityType.ListeningTo, "listening" => ActivityType.ListeningTo,
@@ -114,7 +114,7 @@ namespace StarsiegeBot
} }
[Command("username"), RequireOwner] [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.TriggerTypingAsync();
await ctx.Client.UpdateCurrentUserAsync(newName); await ctx.Client.UpdateCurrentUserAsync(newName);
@@ -128,7 +128,7 @@ namespace StarsiegeBot
while (true) while (true)
{ {
string output = JsonConvert.SerializeObject(GuildSettings); string output = JsonConvert.SerializeObject(GuildSettings);
await File.WriteAllTextAsync(fileName, output); await File.WriteAllTextAsync(_fileName, output);
await Task.Delay(TimeSpan.FromSeconds(120), cancellationToken); await Task.Delay(TimeSpan.FromSeconds(120), cancellationToken);
if (cancellationToken.IsCancellationRequested) if (cancellationToken.IsCancellationRequested)
{ {
+10 -9
View File
@@ -1,6 +1,7 @@
#pragma warning disable IDE0060 // Remove unused parameter #pragma warning disable IDE0060 // Remove unused parameter
using DSharpPlus; using DSharpPlus;
using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.CommandsNext.Exceptions; using DSharpPlus.CommandsNext.Exceptions;
using DSharpPlus.Entities; using DSharpPlus.Entities;
using DSharpPlus.EventArgs; using DSharpPlus.EventArgs;
@@ -17,7 +18,7 @@ namespace StarsiegeBot
public readonly EventId BotEventId; public readonly EventId BotEventId;
public static DiscordMember notify; public static DiscordMember notify;
// protected string BotName { get; set; } // protected string BotName { get; set; }
private readonly BotSettings Guilds = new BotSettings(); private readonly BotSettings _guilds = new BotSettings();
public Triggers(EventId botEventId) => BotEventId = botEventId; public Triggers(EventId botEventId) => BotEventId = botEventId;
public Task CommandExecuted(CommandsNextExtension ext, CommandExecutionEventArgs e) public Task CommandExecuted(CommandsNextExtension ext, CommandExecutionEventArgs e)
@@ -77,14 +78,14 @@ namespace StarsiegeBot
if (cmdStart == -1) return Task.CompletedTask; if (cmdStart == -1) return Task.CompletedTask;
// Retrieve prefix. // Retrieve prefix.
var prefix = msg.Content.Substring(0, cmdStart); string prefix = msg.Content.Substring(0, cmdStart);
var cmdString = msg.Content[cmdStart..]; string cmdString = msg.Content[cmdStart..];
// Retrieve full command string. // 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; 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)); Task.Run(async () => await cnext.ExecuteCommandAsync(ctx));
return Task.CompletedTask; return Task.CompletedTask;
@@ -96,7 +97,7 @@ namespace StarsiegeBot
if (e.Exception is ChecksFailedException ex) if (e.Exception is ChecksFailedException ex)
{ {
string output = "---\r\n"; string output = "---\r\n";
foreach (var item in ex.FailedChecks) foreach (CheckBaseAttribute item in ex.FailedChecks)
{ {
output += item.ToString() + "\r\n"; output += item.ToString() + "\r\n";
} }
@@ -232,10 +233,10 @@ namespace StarsiegeBot
//if(e.Guilds[376937422010974209].Members.ContainsKey(139548200099905536)) //if(e.Guilds[376937422010974209].Members.ContainsKey(139548200099905536))
//notify = e.Guilds[376937422010974209].Members[139548200099905536]; //notify = e.Guilds[376937422010974209].Members[139548200099905536];
ulong desiredKey = 139548200099905536; ulong desiredKey = 139548200099905536;
foreach (KeyValuePair<ulong,DiscordGuild> item in e.Guilds) foreach (KeyValuePair<ulong, DiscordGuild> item in e.Guilds)
{ {
DiscordGuild curr = item.Value; DiscordGuild curr = item.Value;
if(curr.Members.ContainsKey(desiredKey)) if (curr.Members.ContainsKey(desiredKey))
{ {
notify = curr.Members[desiredKey]; notify = curr.Members[desiredKey];
break; 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. // notify the *primary bot owner if the Guild count is above 75. So we can start bot verification process.
if (e.Guilds.Count > 75) if (e.Guilds.Count > 75)
notify.SendMessageAsync("**__WARNING__: BOT IS IN OVER 75 SERVERS."); notify.SendMessageAsync("**__WARNING__: BOT IS IN OVER 75 SERVERS.");
return Task.CompletedTask; return Task.CompletedTask;
} }
public Task GuildEmojisUpdated(DiscordClient d, GuildEmojisUpdateEventArgs e) public Task GuildEmojisUpdated(DiscordClient d, GuildEmojisUpdateEventArgs e)
+2 -2
View File
@@ -20,14 +20,14 @@ namespace StarsiegeBot
class ExperiemntalCommands : BaseCommandModule class ExperiemntalCommands : BaseCommandModule
{ {
[Command("exit"), RequireOwner] [Command("exit"), RequireOwner]
public async Task ExitProgram (CommandContext ctx) public async Task ExitProgram(CommandContext ctx)
{ {
await ctx.RespondAsync("Attempting a shutdown..."); await ctx.RespondAsync("Attempting a shutdown...");
System.Environment.Exit(0); System.Environment.Exit(0);
} }
[Command("Report")] [Command("Report")]
public async Task Report (CommandContext ctx) public async Task Report(CommandContext ctx)
{ {
await ctx.RespondAsync("Report not generated"); await ctx.RespondAsync("Report not generated");
} }
+16 -16
View File
@@ -13,25 +13,25 @@ namespace StarsiegeBot
class GameCommands : BaseCommandModule class GameCommands : BaseCommandModule
{ {
// Master insult list. // Master insult list.
private readonly string[] InsultMaster = { private readonly string[] _insultMaster = {
"{0} slaps {1} around a bit with a large trout.", "{0} slaps {1} around a bit with a large trout.",
"{0} puts a jellyfish on {1}'s head.", "{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 the mustache of Caanon.",
"{0} slaps {1} around a bit with a questionable rubber object.", "{0} slaps {1} around a bit with a questionable rubber object.",
"{0} slaps {1} around a bit with a rubber chicken." "{0} slaps {1} around a bit with a rubber chicken."
}; };
private List<string> InsultCopy; private List<string> _insultCopy;
public GameCommands() public GameCommands()
{ {
// Let the console know we've loaded basic commands. // Let the console know we've loaded basic commands.
Console.WriteLine("Basic Commands Loaded"); Console.WriteLine("Basic Commands Loaded");
InsultCopy = InsultMaster.ToList<string>(); _insultCopy = _insultMaster.ToList<string>();
} }
[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")] [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(); await ctx.TriggerTypingAsync();
// Load all the traditional 8-Ball answers into an array. // Load all the traditional 8-Ball answers into an array.
@@ -99,7 +99,7 @@ namespace StarsiegeBot
[Command("dice"), Aliases("r", "d", "roll")] [Command("dice"), Aliases("r", "d", "roll")]
[Description("A classic dice throwing command. Limited to 1 use per 2 seconds. Format: <NumberOfDice>d<SidesOnDie> ")] [Description("A classic dice throwing command. Limited to 1 use per 2 seconds. Format: <NumberOfDice>d<SidesOnDie> ")]
[Cooldown(1, 2, CooldownBucketType.Guild)] [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... // let the end user know the bot is doing something...
await ctx.TriggerTypingAsync(); await ctx.TriggerTypingAsync();
@@ -109,7 +109,7 @@ namespace StarsiegeBot
int totalResult = 0; int totalResult = 0;
int totalDie = 0; int totalDie = 0;
// set the results to an empty string. // set the results to an empty string.
string overallResults = String.Empty; string overallResults = string.Empty;
// Prep the regex statement. // Prep the regex statement.
Regex regex = new Regex("(\\d{0,})(d)(-{0,1}\\d{0,})"); Regex regex = new Regex("(\\d{0,})(d)(-{0,1}\\d{0,})");
// Get a collection of regex matches from the dice we're through. // Get a collection of regex matches from the dice we're through.
@@ -121,7 +121,7 @@ namespace StarsiegeBot
if (m.Success) if (m.Success)
{ {
// set an empty string, set a counter. // set an empty string, set a counter.
string dieResults = String.Empty; string dieResults = string.Empty;
int dieResult = 0; int dieResult = 0;
// attempt to get the number of dice being "thrown" and the number of sides those die have. // 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); 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. // 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)); 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. // 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(); dieResults = roll.ToString();
else else
dieResults += $", {roll}"; dieResults += $", {roll}";
@@ -247,7 +247,7 @@ namespace StarsiegeBot
} }
else 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)); await ctx.RespondAsync(StartEmbed(result));
} }
@@ -324,7 +324,7 @@ namespace StarsiegeBot
else else
{ {
// the end user didn't pick something that is within the choice set... Tell them they need to play better. // 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. // Actually send out all our info now.
await ctx.RespondAsync(StartEmbed(result)); await ctx.RespondAsync(StartEmbed(result));
@@ -368,13 +368,13 @@ namespace StarsiegeBot
user2 = user.Mention; user2 = user.Mention;
} }
// pick a random insult, and populate the names correctly. // 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))); await ctx.RespondAsync(StartEmbed(string.Format(_insultCopy[randInt], user1, user2)));
InsultCopy.RemoveAt(randInt); _insultCopy.RemoveAt(randInt);
if (InsultCopy.Count == 0) if (_insultCopy.Count == 0)
{ {
InsultCopy = InsultMaster.ToList<string>(); _insultCopy = _insultMaster.ToList<string>();
} }
} }
+5 -5
View File
@@ -27,9 +27,9 @@ namespace StarsiegeBot
[Command("add")] [Command("add")]
[Description("Work in progress. Does nothing yet.")] [Description("Work in progress. Does nothing yet.")]
public async Task AddSelfRole(CommandContext ctx, public async Task AddSelfRole(CommandContext ctx,
[Description("The role to add.")] DiscordRole role, [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("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) [Description("What group to put the role in. If not using groups, you can leave blank."), RemainingText] string groupName = null)
{ {
await ctx.TriggerTypingAsync(); await ctx.TriggerTypingAsync();
@@ -56,8 +56,8 @@ namespace StarsiegeBot
[Command("delete")] [Command("delete")]
[Description("Work in progress. Does nothing yet.")] [Description("Work in progress. Does nothing yet.")]
public async Task DeleteSelfRole(CommandContext ctx, public async Task DeleteSelfRole(CommandContext ctx,
[Description("The role to delete.")] DiscordRole role, [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) [Description("The group to remove the role from. If left blank, will remove from all groups."), RemainingText] string group = null)
{ {
await ctx.TriggerTypingAsync(); await ctx.TriggerTypingAsync();
+1 -1
View File
@@ -31,7 +31,7 @@ namespace StarsiegeBot
else else
{ {
// we have server settings... why does this give so much info? it should only show only prefix(es) // 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 DiscordEmbedBuilder embed = new DiscordEmbedBuilder
{ {
Description = $"{ctx.Guild.Name} Prefixes." Description = $"{ctx.Guild.Name} Prefixes."
+75 -75
View File
@@ -70,12 +70,12 @@ namespace StarsiegeBot
}; };
// then we want to instantiate our client // 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 // next, let's hook some events, so we know
// what's going on // what's going on
this.Client.UseInteractivity(new InteractivityConfiguration() Client.UseInteractivity(new InteractivityConfiguration()
{ {
PollBehaviour = PollBehaviour.KeepEmojis, PollBehaviour = PollBehaviour.KeepEmojis,
Timeout = TimeSpan.FromSeconds(15) Timeout = TimeSpan.FromSeconds(15)
@@ -97,92 +97,92 @@ namespace StarsiegeBot
}; };
// and hook them up // and hook them up
this.Commands = this.Client.UseCommandsNext(ccfg); Commands = Client.UseCommandsNext(ccfg);
// up next, let's register our commands // up next, let's register our commands
this.Commands.RegisterCommands<BotSettings>(); // Main Folder. Test Items. Commands.RegisterCommands<BotSettings>(); // Main Folder. Test Items.
this.Commands.RegisterCommands<ExperiemntalCommands>(); // Experimental commands file. Commands.RegisterCommands<ExperiemntalCommands>(); // Experimental commands file.
this.Commands.RegisterCommands<GameCommands>(); Commands.RegisterCommands<GameCommands>();
this.Commands.RegisterCommands<GroupManagement>(); // Main Folder. Test Items. Commands.RegisterCommands<GroupManagement>(); // Main Folder. Test Items.
this.Commands.RegisterCommands<GroupRoleManagement>(); // Main Folder. Test Items. Commands.RegisterCommands<GroupRoleManagement>(); // Main Folder. Test Items.
this.Commands.RegisterCommands<LevelManagement>(); // Main Folder. Test Items. Commands.RegisterCommands<LevelManagement>(); // Main Folder. Test Items.
this.Commands.RegisterCommands<LevelRoleManagement>(); // Main Folder. Test Items. Commands.RegisterCommands<LevelRoleManagement>(); // Main Folder. Test Items.
this.Commands.RegisterCommands<NotFacts>(); // Raven Folder. Commands.RegisterCommands<NotFacts>(); // Raven Folder.
this.Commands.RegisterCommands<PrefixManagement>(); Commands.RegisterCommands<PrefixManagement>();
this.Commands.RegisterCommands<RoleManagement>(); // Main Folder. Test Items. Commands.RegisterCommands<RoleManagement>(); // Main Folder. Test Items.
this.Commands.RegisterCommands<SnappleFacts>(); // Raven folder. Commands.RegisterCommands<SnappleFacts>(); // Raven folder.
this.Commands.RegisterCommands<WelcomeMessage>(); // Main Folder. Test Items. Commands.RegisterCommands<WelcomeMessage>(); // Main Folder. Test Items.
// All these commands are in the STARSIEGE folder. // All these commands are in the STARSIEGE folder.
//if (BotName.Contains("ssp")) //if (BotName.Contains("ssp"))
//{ //{
this.Commands.RegisterCommands<QuickchatHandler>(); Commands.RegisterCommands<QuickchatHandler>();
this.Commands.RegisterCommands<Functions>(); Commands.RegisterCommands<Functions>();
this.Commands.RegisterCommands<DeathMessages>(); Commands.RegisterCommands<DeathMessages>();
this.Commands.RegisterCommands<GameInfo>(); Commands.RegisterCommands<GameInfo>();
//} //}
// let's enable voice // let's enable voice
this.Voice = this.Client.UseVoiceNext(); Voice = Client.UseVoiceNext();
// Hook all possible Event Handlers in the system. // Hook all possible Event Handlers in the system.
this.Client.ChannelCreated += Events.ChannelCreated; Client.ChannelCreated += Events.ChannelCreated;
this.Client.ChannelDeleted += Events.ChannelDeleted; Client.ChannelDeleted += Events.ChannelDeleted;
this.Client.ChannelPinsUpdated += Events.ChannelPinsUpdated; Client.ChannelPinsUpdated += Events.ChannelPinsUpdated;
this.Client.ChannelUpdated += Events.ChannelUpdated; Client.ChannelUpdated += Events.ChannelUpdated;
this.Client.ClientErrored += Events.ClientErrored; Client.ClientErrored += Events.ClientErrored;
this.Client.DmChannelDeleted += Events.DmChannelDeleted; Client.DmChannelDeleted += Events.DmChannelDeleted;
this.Client.GuildAvailable += Events.GuildAvailable; Client.GuildAvailable += Events.GuildAvailable;
this.Client.GuildBanAdded += Events.GuildBanAdded; Client.GuildBanAdded += Events.GuildBanAdded;
this.Client.GuildBanRemoved += Events.GuildBanRemoved; Client.GuildBanRemoved += Events.GuildBanRemoved;
this.Client.GuildCreated += Events.GuildCreated; Client.GuildCreated += Events.GuildCreated;
this.Client.GuildDeleted += Events.GuildDeleted; Client.GuildDeleted += Events.GuildDeleted;
this.Client.GuildDownloadCompleted += Events.GuildDownloadCompleted; Client.GuildDownloadCompleted += Events.GuildDownloadCompleted;
this.Client.GuildEmojisUpdated += Events.GuildEmojisUpdated; Client.GuildEmojisUpdated += Events.GuildEmojisUpdated;
this.Client.GuildIntegrationsUpdated += Events.GuildIntegrationsUpdated; Client.GuildIntegrationsUpdated += Events.GuildIntegrationsUpdated;
this.Client.GuildMemberAdded += Events.GuildMemberAdded; Client.GuildMemberAdded += Events.GuildMemberAdded;
this.Client.GuildMemberRemoved += Events.GuildMemberRemoved; Client.GuildMemberRemoved += Events.GuildMemberRemoved;
this.Client.GuildMembersChunked += Events.GuildMembersChunked; Client.GuildMembersChunked += Events.GuildMembersChunked;
this.Client.GuildMemberUpdated += Events.GuildMemberUpdated; Client.GuildMemberUpdated += Events.GuildMemberUpdated;
this.Client.GuildRoleCreated += Events.GuildRoleCreated; Client.GuildRoleCreated += Events.GuildRoleCreated;
this.Client.GuildRoleDeleted += Events.GuildRoleDeleted; Client.GuildRoleDeleted += Events.GuildRoleDeleted;
this.Client.GuildRoleUpdated += Events.GuildRoleUpdated; Client.GuildRoleUpdated += Events.GuildRoleUpdated;
this.Client.GuildUnavailable += Events.GuildUnavailable; Client.GuildUnavailable += Events.GuildUnavailable;
this.Client.GuildUpdated += Events.GuildUpdated; Client.GuildUpdated += Events.GuildUpdated;
this.Client.Heartbeated += Events.Heartbeated; Client.Heartbeated += Events.Heartbeated;
this.Client.InviteCreated += Events.InviteCreated; Client.InviteCreated += Events.InviteCreated;
this.Client.InviteDeleted += Events.InviteDeleted; Client.InviteDeleted += Events.InviteDeleted;
this.Client.MessageAcknowledged += Events.MessageAcknowledged; Client.MessageAcknowledged += Events.MessageAcknowledged;
this.Client.MessageCreated += Events.MessageCreated; Client.MessageCreated += Events.MessageCreated;
this.Client.MessageDeleted += Events.MessageDeleted; Client.MessageDeleted += Events.MessageDeleted;
this.Client.MessageReactionAdded += Events.MessageReactionAdded; Client.MessageReactionAdded += Events.MessageReactionAdded;
this.Client.MessageReactionRemoved += Events.MessageReactionRemoved; Client.MessageReactionRemoved += Events.MessageReactionRemoved;
this.Client.MessageReactionRemovedEmoji += Events.MessageReactionRemovedEmoji; Client.MessageReactionRemovedEmoji += Events.MessageReactionRemovedEmoji;
this.Client.MessageReactionsCleared += Events.MessageReactionsCleared; Client.MessageReactionsCleared += Events.MessageReactionsCleared;
this.Client.MessagesBulkDeleted += Events.MessagesBulkDeleted; Client.MessagesBulkDeleted += Events.MessagesBulkDeleted;
this.Client.MessageUpdated += Events.MessageUpdated; Client.MessageUpdated += Events.MessageUpdated;
this.Client.PresenceUpdated += Events.PresenceUpdated; Client.PresenceUpdated += Events.PresenceUpdated;
this.Client.Ready += Events.Ready; Client.Ready += Events.Ready;
this.Client.Resumed += Events.Resumed; Client.Resumed += Events.Resumed;
this.Client.SocketClosed += Events.SocketClosed; Client.SocketClosed += Events.SocketClosed;
this.Client.SocketErrored += Events.SocketErrored; Client.SocketErrored += Events.SocketErrored;
this.Client.SocketOpened += Events.SocketOpened; Client.SocketOpened += Events.SocketOpened;
this.Client.TypingStarted += Events.TypingStarted; Client.TypingStarted += Events.TypingStarted;
this.Client.UnknownEvent += Events.UnknownEvent; Client.UnknownEvent += Events.UnknownEvent;
this.Client.UserSettingsUpdated += Events.UserSettingsUpdated; Client.UserSettingsUpdated += Events.UserSettingsUpdated;
this.Client.UserUpdated += Events.UserUpdated; Client.UserUpdated += Events.UserUpdated;
this.Client.VoiceServerUpdated += Events.VoiceServerUpdated; Client.VoiceServerUpdated += Events.VoiceServerUpdated;
this.Client.VoiceStateUpdated += Events.VoiceStateUpdated; Client.VoiceStateUpdated += Events.VoiceStateUpdated;
this.Client.WebhooksUpdated += Events.WebhooksUpdated; Client.WebhooksUpdated += Events.WebhooksUpdated;
this.Client.ApplicationCommandCreated += Events.ApplicationCommandCreated; Client.ApplicationCommandCreated += Events.ApplicationCommandCreated;
this.Client.ApplicationCommandDeleted += Events.ApplicationCommandDeleted; Client.ApplicationCommandDeleted += Events.ApplicationCommandDeleted;
this.Client.ApplicationCommandUpdated += Events.ApplicationCommandUpdated; Client.ApplicationCommandUpdated += Events.ApplicationCommandUpdated;
this.Client.InteractionCreated += Events.InteractionCreated; Client.InteractionCreated += Events.InteractionCreated;
this.Commands.CommandExecuted += Events.CommandExecuted; Commands.CommandExecuted += Events.CommandExecuted;
this.Commands.CommandErrored += Events.CommandErrored; Commands.CommandErrored += Events.CommandErrored;
// finally, let's connect and log in // finally, let's connect and log in
await this.Client.ConnectAsync(); await Client.ConnectAsync();
// and this is to prevent premature quitting // and this is to prevent premature quitting
await Task.Delay(-1); await Task.Delay(-1);
+27 -27
View File
@@ -14,31 +14,31 @@ namespace StarsiegeBot
[Group("notfact")] [Group("notfact")]
class NotFacts : BaseCommandModule class NotFacts : BaseCommandModule
{ {
private List<string> notfacts; private List<string> _notfacts;
private bool IsEnabled; private bool _isEnabled;
private readonly string fileName = "Json/notfacts.json"; private static readonly string s_fileName = "Json/notfacts.json";
public NotFacts() public NotFacts()
{ {
Console.WriteLine("NotFacts Command Loaded"); Console.WriteLine("NotFacts Command Loaded");
IsEnabled = Load(); _isEnabled = Load();
} }
[GroupCommand, Description("Get a NotFact")] [GroupCommand, Description("Get a NotFact")]
public async Task NotFact(CommandContext ctx, [Description("[Optional] A NotFact ID")] int notFactID = 0) public async Task NotFact(CommandContext ctx, [Description("[Optional] A NotFact ID")] int notFactID = 0)
{ {
if (!IsEnabled) if (!_isEnabled)
return; return;
await ctx.TriggerTypingAsync(); await ctx.TriggerTypingAsync();
string output; string output;
notFactID--; notFactID--;
try try
{ {
output = notfacts[notFactID]; output = _notfacts[notFactID];
} }
catch (Exception) catch (Exception)
{ {
output = notfacts[Program.rnd.Next(0, notfacts.Count)]; output = _notfacts[Program.rnd.Next(0, _notfacts.Count)];
} }
await ctx.RespondAsync(StartEmbed(output)); await ctx.RespondAsync(StartEmbed(output));
} }
@@ -46,10 +46,10 @@ namespace StarsiegeBot
[Command("count"), Aliases("c"), Description("Get a count of the NotFacts")] [Command("count"), Aliases("c"), Description("Get a count of the NotFacts")]
public async Task NotFactCount(CommandContext ctx) public async Task NotFactCount(CommandContext ctx)
{ {
if (!IsEnabled) if (!_isEnabled)
return; return;
await ctx.TriggerTypingAsync(); 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")] [Command("load"), RequireOwner, Aliases("l")]
@@ -60,14 +60,14 @@ namespace StarsiegeBot
// start the response. // start the response.
DiscordEmbedBuilder embed = StartEmbed("Reloading NotFacts"); DiscordEmbedBuilder embed = StartEmbed("Reloading NotFacts");
// our old setting... // our old setting...
embed.AddField("Old", (IsEnabled ? "Enabled" : "Disabled")); embed.AddField("Old", (_isEnabled ? "Enabled" : "Disabled"));
// run this, we dont care about its actual results. // run this, we dont care about its actual results.
_ = Load(); _ = Load();
// report our new setting. // 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. // since the only thing that *should* go wrong is a missing file, report it if thats the case.
if (!File.Exists(fileName)) if (!File.Exists(s_fileName))
embed.WithFooter($":warning: {fileName} file is missing."); embed.WithFooter($":warning: {s_fileName} file is missing.");
// send our results. // send our results.
await ctx.RespondAsync(embed); await ctx.RespondAsync(embed);
} }
@@ -83,34 +83,34 @@ namespace StarsiegeBot
string[] turnOff = { "off", "false", "0" }; string[] turnOff = { "off", "false", "0" };
//start our response. //start our response.
DiscordEmbedBuilder embed = StartEmbed("NotFact Toggle"); DiscordEmbedBuilder embed = StartEmbed("NotFact Toggle");
embed.AddField("Old", (IsEnabled ? "Enabled" : "Disabled")); embed.AddField("Old", (_isEnabled ? "Enabled" : "Disabled"));
// check for file. // check for file.
if (File.Exists(fileName)) if (File.Exists(s_fileName))
{ {
// compare desired input against on or off values. // compare desired input against on or off values.
if (turnOn.Contains(isEnabled)) if (turnOn.Contains(isEnabled))
{ {
IsEnabled = true; _isEnabled = true;
embed.AddField("New", (IsEnabled ? "Enabled" : "Disabled")); embed.AddField("New", (_isEnabled ? "Enabled" : "Disabled"));
} }
else if (turnOff.Contains(isEnabled)) else if (turnOff.Contains(isEnabled))
{ {
IsEnabled = false; _isEnabled = false;
embed.AddField("New", (IsEnabled ? "Enabled" : "Disabled")); embed.AddField("New", (_isEnabled ? "Enabled" : "Disabled"));
} }
else else
{ {
// we dont know what they were trying to do, throw an error in the footer with a :warning: emote. // 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?"); embed.WithFooter(":warning: Invalid command given?");
} }
} }
else else
{ {
// file is missing, disable this, regardless of their desires. Report the file is missing in the footer with a :warning: // file is missing, disable this, regardless of their desires. Report the file is missing in the footer with a :warning:
IsEnabled = false; _isEnabled = false;
embed.AddField("New", (IsEnabled ? "Enabled" : "Disabled")); embed.AddField("New", (_isEnabled ? "Enabled" : "Disabled"));
embed.WithFooter($":warning: {fileName} file is missing, and it can not be enabled."); embed.WithFooter($":warning: {s_fileName} file is missing, and it can not be enabled.");
} }
await ctx.RespondAsync(embed); await ctx.RespondAsync(embed);
} }
@@ -129,17 +129,17 @@ namespace StarsiegeBot
private bool Load() private bool Load()
{ {
bool ret; bool ret;
if (File.Exists(fileName)) if (File.Exists(s_fileName))
{ {
string json = File.ReadAllText(fileName); string json = File.ReadAllText(s_fileName);
notfacts = JsonConvert.DeserializeObject<List<string>>(json); _notfacts = JsonConvert.DeserializeObject<List<string>>(json);
ret = true; ret = true;
} }
else else
{ {
ret = false; ret = false;
} }
IsEnabled = ret; _isEnabled = ret;
return ret; return ret;
} }
} }
+28 -28
View File
@@ -14,21 +14,21 @@ namespace StarsiegeBot
[Group("snapple"), Aliases("snap")] [Group("snapple"), Aliases("snap")]
class SnappleFacts : BaseCommandModule class SnappleFacts : BaseCommandModule
{ {
private List<string> facts; private List<string> _facts;
private bool IsEnabled; private bool _isEnabled;
private readonly string fileName = "Json/snapple.json"; private static readonly string s_fileName = "Json/snapple.json";
public SnappleFacts() public SnappleFacts()
{ {
Console.WriteLine("Snapple Commands Loaded"); Console.WriteLine("Snapple Commands Loaded");
IsEnabled = Load(); _isEnabled = Load();
} }
[GroupCommand, Description("Get a Snapple \"Real Fact\".")] [GroupCommand, Description("Get a Snapple \"Real Fact\".")]
public async Task Snapplefact(CommandContext ctx, [Description("[Optional] A Snapple Fact ID")] int snapId = 0) public async Task Snapplefact(CommandContext ctx, [Description("[Optional] A Snapple Fact ID")] int snapId = 0)
{ {
// if we're not enabled, exit out. // if we're not enabled, exit out.
if (!IsEnabled) if (!_isEnabled)
return; return;
// trigger typing. // trigger typing.
await ctx.TriggerTypingAsync(); await ctx.TriggerTypingAsync();
@@ -39,12 +39,12 @@ namespace StarsiegeBot
try try
{ {
// attempt to get the desired fact. // attempt to get the desired fact.
output = facts[snapId]; output = _facts[snapId];
} }
catch (Exception) catch (Exception)
{ {
// we couldn't find the exact one, give them a random one. // 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. // give them what they want.
await ctx.RespondAsync(StartEmbed(output)); await ctx.RespondAsync(StartEmbed(output));
@@ -53,11 +53,11 @@ namespace StarsiegeBot
[Command("count"), Description("Get a Snapple \"Real Fact\"."), Aliases("c")] [Command("count"), Description("Get a Snapple \"Real Fact\"."), Aliases("c")]
public async Task SnappleCount(CommandContext ctx) public async Task SnappleCount(CommandContext ctx)
{ {
if (!IsEnabled) if (!_isEnabled)
return; return;
await ctx.TriggerTypingAsync(); await ctx.TriggerTypingAsync();
// trigger the typing, and report how many facts are in teh bank. // 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")] [Command("load"), RequireOwner, Aliases("l")]
@@ -68,20 +68,20 @@ namespace StarsiegeBot
// start the response. // start the response.
DiscordEmbedBuilder embed = StartEmbed("Reloading Snapple Facts"); DiscordEmbedBuilder embed = StartEmbed("Reloading Snapple Facts");
// our old setting... // our old setting...
embed.AddField("Old", (IsEnabled ? "Enabled" : "Disabled")); embed.AddField("Old", (_isEnabled ? "Enabled" : "Disabled"));
// run this, we dont care about its actual results. // run this, we dont care about its actual results.
_ = Load(); _ = Load();
// report our new setting. // 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. // since the only thing that *should* go wrong is a missing file, report it if thats the case.
if (!File.Exists(fileName)) if (!File.Exists(s_fileName))
embed.WithFooter($":warning: {fileName} file is missing."); embed.WithFooter($":warning: {s_fileName} file is missing.");
// send our results. // send our results.
await ctx.RespondAsync(embed); await ctx.RespondAsync(embed);
} }
[Command("toggle"), RequireOwner, Aliases("t")] [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. // trigger the typing.
await ctx.TriggerTypingAsync(); await ctx.TriggerTypingAsync();
@@ -91,34 +91,34 @@ namespace StarsiegeBot
string[] turnOff = { "off", "false", "0" }; string[] turnOff = { "off", "false", "0" };
//start our response. //start our response.
DiscordEmbedBuilder embed = StartEmbed("Snapple Toggle"); DiscordEmbedBuilder embed = StartEmbed("Snapple Toggle");
embed.AddField("Old", (IsEnabled ? "Enabled" : "Disabled")); embed.AddField("Old", (_isEnabled ? "Enabled" : "Disabled"));
// check for file. // check for file.
if (File.Exists(fileName)) if (File.Exists(s_fileName))
{ {
// compare desired input against on or off values. // compare desired input against on or off values.
if (turnOn.Contains(isEnabled)) if (turnOn.Contains(isEnabled))
{ {
IsEnabled = true; _isEnabled = true;
embed.AddField("New", (IsEnabled ? "Enabled" : "Disabled")); embed.AddField("New", (_isEnabled ? "Enabled" : "Disabled"));
} }
else if (turnOff.Contains(isEnabled)) else if (turnOff.Contains(isEnabled))
{ {
IsEnabled = false; _isEnabled = false;
embed.AddField("New", (IsEnabled ? "Enabled" : "Disabled")); embed.AddField("New", (_isEnabled ? "Enabled" : "Disabled"));
} }
else else
{ {
// we dont know what they were trying to do, throw an error in the footer with a :warning: emote. // 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?"); embed.WithFooter(":warning: Invalid command given?");
} }
} }
else else
{ {
// file is missing, disable this, regardless of their desires. Report the file is missing in the footer with a :warning: // file is missing, disable this, regardless of their desires. Report the file is missing in the footer with a :warning:
IsEnabled = false; _isEnabled = false;
embed.AddField("New", (IsEnabled ? "Enabled" : "Disabled")); embed.AddField("New", (_isEnabled ? "Enabled" : "Disabled"));
embed.WithFooter($":warning: {fileName} file is missing, and it can not be enabled."); embed.WithFooter($":warning: {s_fileName} file is missing, and it can not be enabled.");
} }
await ctx.RespondAsync(embed); await ctx.RespondAsync(embed);
} }
@@ -136,17 +136,17 @@ namespace StarsiegeBot
private bool Load() private bool Load()
{ {
bool ret; bool ret;
if (File.Exists(fileName)) if (File.Exists(s_fileName))
{ {
string json = File.ReadAllText(fileName); string json = File.ReadAllText(s_fileName);
facts = JsonConvert.DeserializeObject<List<string>>(json); _facts = JsonConvert.DeserializeObject<List<string>>(json);
ret = true; ret = true;
} }
else else
{ {
ret = false; ret = false;
} }
IsEnabled = ret; _isEnabled = ret;
return ret; return ret;
} }
} }
+18 -18
View File
@@ -15,17 +15,17 @@ namespace StarsiegeBot.Raven
{ {
class TriviaHandler : BaseCommandModule class TriviaHandler : BaseCommandModule
{ {
private readonly List<Questions> QuizQuestions; private readonly List<Questions> _quizQuestions;
private readonly Random rnd = new Random(); private static readonly string s_fileName = "Json/trivia.json";
public TriviaHandler() public TriviaHandler()
{ {
// Load all the Quick Chat texts and sound wav file info. // Load all the Quick Chat texts and sound wav file info.
var json = ""; string json = "";
using (var fs = File.OpenRead("Json/questions.json")) using (FileStream fs = File.OpenRead(s_fileName))
using (var sr = new StreamReader(fs, new UTF8Encoding(false))) using (StreamReader sr = new StreamReader(fs, new UTF8Encoding(false)))
json = sr.ReadToEnd(); json = sr.ReadToEnd();
Dictionary<string, Questions> tempQC = JsonConvert.DeserializeObject<Dictionary<string, Questions>>(json); Dictionary<string, Questions> tempQC = JsonConvert.DeserializeObject<Dictionary<string, Questions>>(json);
QuizQuestions = Enumerable.ToList(tempQC.Values); _quizQuestions = Enumerable.ToList(tempQC.Values);
} }
[Command("quiz")] [Command("quiz")]
@@ -36,25 +36,25 @@ namespace StarsiegeBot.Raven
await ctx.TriggerTypingAsync(); await ctx.TriggerTypingAsync();
DiscordEmbedBuilder embed = new DiscordEmbedBuilder(); DiscordEmbedBuilder embed = new DiscordEmbedBuilder();
int[] ids = { rnd.Next(QuizQuestions.Count), rnd.Next(QuizQuestions.Count), rnd.Next(QuizQuestions.Count), rnd.Next(QuizQuestions.Count) }; int[] ids = { Program.rnd.Next(_quizQuestions.Count), Program.rnd.Next(_quizQuestions.Count), Program.rnd.Next(_quizQuestions.Count), Program.rnd.Next(_quizQuestions.Count) };
int selection = rnd.Next(ids.Length); int selection = Program.rnd.Next(ids.Length);
int mainId = ids[selection]; int mainId = ids[selection];
string[] options = { "a", "b", "c", "d" }; string[] options = { "a", "b", "c", "d" };
var correctAnswer = DiscordEmoji.FromName(ctx.Client, $":regional_indicator_{options[selection]}:"); var correctAnswer = DiscordEmoji.FromName(ctx.Client, $":regional_indicator_{options[selection]}:");
Questions myQuestion = QuizQuestions[mainId]; Questions myQuestion = _quizQuestions[mainId];
embed.Description = myQuestion.Question; 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[0]}:", _quizQuestions[ids[0]].Answers[Program.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[1]}:", _quizQuestions[ids[1]].Answers[Program.rnd.Next(_quizQuestions[ids[1]].Answers.Length)], true);
embed.AddField("_ _", "_ _", false); 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[2]}:", _quizQuestions[ids[2]].Answers[Program.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[3]}:", _quizQuestions[ids[3]].Answers[Program.rnd.Next(_quizQuestions[ids[3]].Answers.Length)], true);
var message = await ctx.RespondAsync(embed); DiscordMessage message = await ctx.RespondAsync(embed);
foreach (var item in options) foreach (string item in options)
{ {
var itemEmote = DiscordEmoji.FromName(ctx.Client, $":regional_indicator_{item}:"); var itemEmote = DiscordEmoji.FromName(ctx.Client, $":regional_indicator_{item}:");
await message.CreateReactionAsync(itemEmote); await message.CreateReactionAsync(itemEmote);
@@ -72,16 +72,16 @@ namespace StarsiegeBot.Raven
[Hidden] [Hidden]
public async Task CollectionCommand(CommandContext ctx) 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 reactions = await message.CollectReactionsAsync();
var strBuilder = new StringBuilder(); var strBuilder = new StringBuilder();
Dictionary<DiscordUser, bool> winners = new Dictionary<DiscordUser, bool>(); Dictionary<DiscordUser, bool> winners = new Dictionary<DiscordUser, bool>();
Dictionary<DiscordUser, bool> losers = new Dictionary<DiscordUser, bool>(); Dictionary<DiscordUser, bool> losers = new Dictionary<DiscordUser, bool>();
var correctEmote = reactions[0].Emoji; DiscordEmoji correctEmote = reactions[0].Emoji;
foreach (var reaction in reactions) foreach (var reaction in reactions)
{ {
foreach (var person in reaction.Users) foreach (DiscordUser person in reaction.Users)
{ {
if (!correctEmote.Equals(reaction.Emoji)) if (!correctEmote.Equals(reaction.Emoji))
{ {
+48 -48
View File
@@ -19,32 +19,32 @@ namespace StarsiegeBot
[Cooldown(1, 2, CooldownBucketType.Guild)] [Cooldown(1, 2, CooldownBucketType.Guild)]
class DeathMessages : BaseCommandModule class DeathMessages : BaseCommandModule
{ {
private DeathMessageLines dmLines; private DeathMessageLines _dmLines;
private bool DeathMessagesEnabled; private bool _deathMessagesEnabled;
private static readonly string fileName = "Json/deathmessages.json"; private static readonly string s_fileName = "Json/deathmessages.json";
public DeathMessages() public DeathMessages()
{ {
Console.WriteLine("Death Message Commands Loaded."); Console.WriteLine("Death Message Commands Loaded.");
// If the DeathMessages file exists, load it. And enable the commands. // If the DeathMessages file exists, load it. And enable the commands.
// Otherwise disable all the commands. // Otherwise disable all the commands.
if (File.Exists(fileName)) if (File.Exists(s_fileName))
{ {
// set some JSON text to blank. // set some JSON text to blank.
var json = ""; string json = "";
using (var fs = File.OpenRead(fileName)) using (FileStream fs = File.OpenRead(s_fileName))
using (var sr = new StreamReader(fs, new UTF8Encoding(false))) using (StreamReader sr = new StreamReader(fs, new UTF8Encoding(false)))
json = sr.ReadToEnd(); json = sr.ReadToEnd();
// Decode the JSON and set it to dmLines. // Decode the JSON and set it to dmLines.
dmLines = JsonConvert.DeserializeObject<DeathMessageLines>(json); _dmLines = JsonConvert.DeserializeObject<DeathMessageLines>(json);
// Enable all the commands. // Enable all the commands.
DeathMessagesEnabled = true; _deathMessagesEnabled = true;
} }
else else
{ {
// Echo out that we're missing a file. Disable the commands due to that. // Echo out that we're missing a file. Disable the commands due to that.
Console.WriteLine($" --- --- --- --- {fileName} is missing"); Console.WriteLine($" --- --- --- --- {s_fileName} is missing");
DeathMessagesEnabled = false; _deathMessagesEnabled = false;
} }
} }
@@ -53,24 +53,24 @@ namespace StarsiegeBot
public async Task LoadDeathMessages(CommandContext ctx) public async Task LoadDeathMessages(CommandContext ctx)
{ {
await ctx.TriggerTypingAsync(); await ctx.TriggerTypingAsync();
if (File.Exists(fileName)) if (File.Exists(s_fileName))
{ {
// set some JSON text to blank. // set some JSON text to blank.
var json = ""; string json = "";
using (var fs = File.OpenRead(fileName)) using (FileStream fs = File.OpenRead(s_fileName))
using (var sr = new StreamReader(fs, new UTF8Encoding(false))) using (StreamReader sr = new StreamReader(fs, new UTF8Encoding(false)))
json = sr.ReadToEnd(); json = sr.ReadToEnd();
// Decode the JSON and set it to dmLines. // Decode the JSON and set it to dmLines.
dmLines = JsonConvert.DeserializeObject<DeathMessageLines>(json); _dmLines = JsonConvert.DeserializeObject<DeathMessageLines>(json);
// Enable all the commands. // Enable all the commands.
DeathMessagesEnabled = true; _deathMessagesEnabled = true;
await ctx.RespondAsync("Loading Death Messages successul."); await ctx.RespondAsync("Loading Death Messages successul.");
} }
else else
{ {
// Echo out that we're missing a file. Disable the commands due to that. // Echo out that we're missing a file. Disable the commands due to that.
await ctx.RespondAsync("Can't load Death Messages. File missing."); 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[] turnOn = { "on", "true", "1" };
string[] turnOff = { "off", "false", "0" }; string[] turnOff = { "off", "false", "0" };
if (File.Exists(fileName)) if (File.Exists(s_fileName))
{ {
if (turnOn.Contains(isEnabled)) if (turnOn.Contains(isEnabled))
{ {
DeathMessagesEnabled = true; _deathMessagesEnabled = true;
} }
else if (turnOff.Contains(isEnabled)) else if (turnOff.Contains(isEnabled))
{ {
DeathMessagesEnabled = false; _deathMessagesEnabled = false;
} }
else else
{ {
} }
output = $"DeathMessages Enabled: {DeathMessagesEnabled}"; output = $"DeathMessages Enabled: {_deathMessagesEnabled}";
} }
else else
{ {
DeathMessagesEnabled = false; _deathMessagesEnabled = false;
output = $"{fileName} file is missing, and it can not be enabled."; output = $"{s_fileName} file is missing, and it can not be enabled.";
} }
await ctx.RespondAsync(output); 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 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 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."); await ctx.RespondAsync("Death Messages Commands have been disabled. Please contact the bot owners.");
return; return;
@@ -130,8 +130,8 @@ namespace StarsiegeBot
// if there is no target, we're going to "kill" the author. // if there is no target, we're going to "kill" the author.
if (target == null) if (target == null)
{ {
int choice = Program.rnd.Next(0, dmLines.Generic.Length); int choice = Program.rnd.Next(0, _dmLines.Generic.Length);
line = dmLines.Generic[choice]; line = _dmLines.Generic[choice];
await ctx.RespondAsync(string.Format(line, ctx.Message.Author.Mention)); await ctx.RespondAsync(string.Format(line, ctx.Message.Author.Mention));
} }
// we have a valid target... Have the bot kill them. // we have a valid target... Have the bot kill them.
@@ -143,14 +143,14 @@ namespace StarsiegeBot
if (opt == 1) if (opt == 1)
{ {
// Pick an Active death message at random, and set our output to it. // Pick an Active death message at random, and set our output to it.
int choice = Program.rnd.Next(0, dmLines.Active.Length); int choice = Program.rnd.Next(0, _dmLines.Active.Length);
line = dmLines.Active[choice]; line = _dmLines.Active[choice];
} }
else if (opt == 2) else if (opt == 2)
{ {
// We picked a Passive death message type. Pick the exact line at random. Set it to the output. // 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); int choice = Program.rnd.Next(0, _dmLines.Passive.Length);
line = dmLines.Passive[choice]; line = _dmLines.Passive[choice];
} }
// Give the selected death message to the user. // Give the selected death message to the user.
await ctx.RespondAsync(string.Format(line, ctx.Message.Author.Mention, target.Mention)); 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 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 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."); await ctx.RespondAsync("Death Messages Commands have been disabled. Please contact the bot owners.");
return; return;
@@ -171,7 +171,7 @@ namespace StarsiegeBot
// We're typing here! // We're typing here!
await ctx.TriggerTypingAsync(); await ctx.TriggerTypingAsync();
// List all the types of Death Message types, and how many we have of each one. // 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")] [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 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 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."); await ctx.RespondAsync("Death Messages Commands have been disabled. Please contact the bot owners.");
return; 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. // 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 the Queue is null, make it exist.
if (dmLines.Queue is null) if (_dmLines.Queue is null)
dmLines.Queue = new List<string>(); _dmLines.Queue = new List<string>();
// add the message to the queue list. // add the message to the queue list.
dmLines.Queue.Add(msg); _dmLines.Queue.Add(msg);
// Store the new stuff to file... // Store the new stuff to file...
await StoreDeathMessages(); await StoreDeathMessages();
// Tell the person that the message has been added to a 'queue'. // Tell the person that the message has been added to a 'queue'.
@@ -208,7 +208,7 @@ namespace StarsiegeBot
await ctx.TriggerTypingAsync(); await ctx.TriggerTypingAsync();
// IF we're missing the Death Messages dot JSON file, we're going to get disabled... Check for that. // 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 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."); await ctx.RespondAsync("Death Messages Commands have been disabled. Please contact the bot owners.");
return; return;
@@ -224,27 +224,27 @@ namespace StarsiegeBot
using StreamWriter file = new StreamWriter("deathmessages.cs"); using StreamWriter file = new StreamWriter("deathmessages.cs");
// Write out the total lines for each. Requirement for Starsiege. // Write out the total lines for each. Requirement for Starsiege.
await file.WriteLineAsync($"$deathMessage::genericCount = {dmLines.Generic.Length};"); await file.WriteLineAsync($"$deathMessage::genericCount = {_dmLines.Generic.Length};");
await file.WriteLineAsync($"$deathMessage::activeCount = {dmLines.Active.Length};"); await file.WriteLineAsync($"$deathMessage::activeCount = {_dmLines.Active.Length};");
await file.WriteLineAsync($"$deathMessage::passiveCount = {dmLines.Passive.Length};\r\n"); 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. // Set count to 0. Iterate over each type of Death Message, and put it into the file.
int count = 0; 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")); await file.WriteLineAsync(string.Format($"$deathMessage::generic{count} = \"{death}\";", "%s", "%s"));
count++; count++;
} }
// Reset the count... // Reset the count...
count = 0; 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")); await file.WriteLineAsync(string.Format($"$deathMessage::active{count} = \"{death}\";", "%s", "%s"));
count++; count++;
} }
// Reset the count one last time... // Reset the count one last time...
count = 0; 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")); await file.WriteLineAsync(string.Format($"$deathMessage::passive{count} = \"{death}\";", "%s", "%s"));
count++; count++;
@@ -269,8 +269,8 @@ namespace StarsiegeBot
private async Task StoreDeathMessages() private async Task StoreDeathMessages()
{ {
string output = JsonConvert.SerializeObject(dmLines); string output = JsonConvert.SerializeObject(_dmLines);
await File.WriteAllTextAsync(fileName, output); await File.WriteAllTextAsync(s_fileName, output);
return; return;
} }
} }
@@ -283,8 +283,8 @@ namespace StarsiegeBot
[JsonProperty("generic")] [JsonProperty("generic")]
public string[] Generic { get; set; } public string[] Generic { get; set; }
[JsonProperty("flagged")] [JsonProperty("flagged")]
public List<String> Flagged { get; set; } public List<string> Flagged { get; set; }
[JsonProperty("queue")] [JsonProperty("queue")]
public List<String> Queue { get; set; } public List<string> Queue { get; set; }
} }
} }
+28 -28
View File
@@ -16,27 +16,27 @@ namespace StarsiegeBot
[Group("functions"), Aliases("func")] [Group("functions"), Aliases("func")]
class Functions : BaseCommandModule class Functions : BaseCommandModule
{ {
private Dictionary<string, SSFunction> ssFunctions; private Dictionary<string, SSFunction> _ssFunctions;
private bool FunctionsEnabled; private bool _functionsEnabled;
private static readonly string fileName = "Json/functions.json"; private static readonly string s_fileName = "Json/functions.json";
public Functions() public Functions()
{ {
Console.WriteLine("Starsiege Function Commands Loaded"); Console.WriteLine("Starsiege Function Commands Loaded");
// Check for file, if not there, disable commands. // 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. // Load the Functions JSON file. Has all information regarding Starsiege in-game Functions.
var json = ""; string json = "";
using (var fs = File.OpenRead(fileName)) using (FileStream fs = File.OpenRead(s_fileName))
using (var sr = new StreamReader(fs, new UTF8Encoding(false))) using (StreamReader sr = new StreamReader(fs, new UTF8Encoding(false)))
json = sr.ReadToEnd(); json = sr.ReadToEnd();
ssFunctions = JsonConvert.DeserializeObject<Dictionary<string, SSFunction>>(json); _ssFunctions = JsonConvert.DeserializeObject<Dictionary<string, SSFunction>>(json);
FunctionsEnabled = true; _functionsEnabled = true;
} }
else else
{ {
FunctionsEnabled = false; _functionsEnabled = false;
Console.WriteLine(" --- --- --- Functions JSON not found."); 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 = "") public async Task StarsiegeFunctions(CommandContext ctx, [RemainingText, Description("The function to attempt to look up.")] string command = "")
{ {
await ctx.TriggerTypingAsync(); await ctx.TriggerTypingAsync();
if (!FunctionsEnabled) if (!_functionsEnabled)
{ {
await ctx.RespondAsync("Function Commands have been disabled. Please contact the bot owners."); await ctx.RespondAsync("Function Commands have been disabled. Please contact the bot owners.");
return; return;
@@ -56,7 +56,7 @@ namespace StarsiegeBot
if (command.Equals(string.Empty)) if (command.Equals(string.Empty))
{ {
// Get a list of the Keys. // Get a list of the Keys.
List<string> keys = new List<string>(ssFunctions.Keys); List<string> keys = new List<string>(_ssFunctions.Keys);
// get a new output. // get a new output.
string output = string.Empty; string output = string.Empty;
// loop over the keys. // loop over the keys.
@@ -78,7 +78,7 @@ namespace StarsiegeBot
} }
// we have a command the want to try to find. // 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! // New Message Embed!
DiscordEmbedBuilder embed = new DiscordEmbedBuilder(); DiscordEmbedBuilder embed = new DiscordEmbedBuilder();
@@ -113,13 +113,13 @@ namespace StarsiegeBot
await ctx.TriggerTypingAsync(); await ctx.TriggerTypingAsync();
// check ot make sure these commands are enabled. if disabled, report it. // 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."); await ctx.RespondAsync("Function Commands have been disabled. Please contact the bot owners.");
return; return;
} }
// they wanted to know how many functions were documented... so tell them! // 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")] [Command("toggle"), Aliases("t")]
@@ -135,26 +135,26 @@ namespace StarsiegeBot
string[] turnOn = { "on", "true", "1" }; string[] turnOn = { "on", "true", "1" };
string[] turnOff = { "off", "false", "0" }; string[] turnOff = { "off", "false", "0" };
if (File.Exists(fileName)) if (File.Exists(s_fileName))
{ {
if (turnOn.Contains(isEnabled)) if (turnOn.Contains(isEnabled))
{ {
FunctionsEnabled = true; _functionsEnabled = true;
} }
else if (turnOff.Contains(isEnabled)) else if (turnOff.Contains(isEnabled))
{ {
FunctionsEnabled = false; _functionsEnabled = false;
} }
else else
{ {
} }
output = $"Functions Enabled: {FunctionsEnabled}"; output = $"Functions Enabled: {_functionsEnabled}";
} }
else else
{ {
FunctionsEnabled = false; _functionsEnabled = false;
output = $"{fileName} file is missing, and it can not be enabled."; output = $"{s_fileName} file is missing, and it can not be enabled.";
} }
await ctx.RespondAsync(output); await ctx.RespondAsync(output);
} }
@@ -164,20 +164,20 @@ namespace StarsiegeBot
await ctx.TriggerTypingAsync(); await ctx.TriggerTypingAsync();
// Check for file, if not there, disable commands. // 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. // Load the Functions JSON file. Has all information regarding Starsiege in-game Functions.
var json = ""; string json = "";
using (var fs = File.OpenRead(fileName)) using (FileStream fs = File.OpenRead(s_fileName))
using (var sr = new StreamReader(fs, new UTF8Encoding(false))) using (StreamReader sr = new StreamReader(fs, new UTF8Encoding(false)))
json = sr.ReadToEnd(); json = sr.ReadToEnd();
ssFunctions = JsonConvert.DeserializeObject<Dictionary<string, SSFunction>>(json); _ssFunctions = JsonConvert.DeserializeObject<Dictionary<string, SSFunction>>(json);
FunctionsEnabled = true; _functionsEnabled = true;
await ctx.RespondAsync("Loading Quick Chats successul."); await ctx.RespondAsync("Loading Quick Chats successul.");
} }
else else
{ {
FunctionsEnabled = false; _functionsEnabled = false;
await ctx.RespondAsync("Loading Functions failed. File does not exist."); await ctx.RespondAsync("Loading Functions failed. File does not exist.");
} }
} }
+17 -17
View File
@@ -14,7 +14,7 @@ namespace StarsiegeBot
[Description("Gives various reports on the game or master servers.")] [Description("Gives various reports on the game or master servers.")]
class GameInfo : BaseCommandModule class GameInfo : BaseCommandModule
{ {
private WebServerItems gameData; private WebServerItems _gameData;
public GameInfo() public GameInfo()
{ {
Update(); Update();
@@ -22,20 +22,20 @@ namespace StarsiegeBot
} }
private void Update() private void Update()
{ {
if (gameData is null) if (_gameData is null)
{ {
using WebClient wc = new WebClient(); 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");
gameData = JsonConvert.DeserializeObject<WebServerItems>(json); _gameData = JsonConvert.DeserializeObject<WebServerItems>(json);
} }
else else
{ {
using WebClient wc = new WebClient(); 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<WebServerItems>(json); WebServerItems temp = JsonConvert.DeserializeObject<WebServerItems>(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. // setup an exit point check.
bool exit = false; bool exit = false;
// if its null, we're going to exit. // 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; exit = true;
} }
@@ -60,9 +60,9 @@ namespace StarsiegeBot
Title = "Master|Game Server Overview", Title = "Master|Game Server Overview",
Description = "Number of Master, and Game servers. Along with number of errors." Description = "Number of Master, and Game servers. Along with number of errors."
}; };
embed.AddField("Masters", gameData.Masters.Length.ToString(), true); embed.AddField("Masters", _gameData.Masters.Length.ToString(), true);
embed.AddField("Games", gameData.Games.Length.ToString(), true); embed.AddField("Games", _gameData.Games.Length.ToString(), true);
embed.AddField("Errors", gameData.Errors.Length.ToString(), true); embed.AddField("Errors", _gameData.Errors.Length.ToString(), true);
await ctx.RespondAsync(embed); await ctx.RespondAsync(embed);
} }
@@ -75,7 +75,7 @@ namespace StarsiegeBot
// setup an exit point check. // setup an exit point check.
bool exit = false; bool exit = false;
// if its null, we're going to exit. // 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; exit = true;
} }
@@ -87,7 +87,7 @@ namespace StarsiegeBot
{ {
Content = "Server Listing Errors:\r\n" Content = "Server Listing Errors:\r\n"
}; };
foreach (var item in gameData.Errors) foreach (string item in _gameData.Errors)
{ {
msg.Content += $"{item}\r\n"; msg.Content += $"{item}\r\n";
} }
@@ -103,7 +103,7 @@ namespace StarsiegeBot
// setup an exit point check. // setup an exit point check.
bool exit = false; bool exit = false;
// if its null, we're going to exit. // 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; exit = true;
} }
@@ -116,7 +116,7 @@ namespace StarsiegeBot
Content = "```csharp\r\n" Content = "```csharp\r\n"
}; };
int count = 0; int count = 0;
foreach (var item in gameData.Masters) foreach (MasterServer item in _gameData.Masters)
{ {
count++; count++;
msg.Content += $"$Inet::Master{count} = \"IP:{item.Address}\";\r\n"; msg.Content += $"$Inet::Master{count} = \"IP:{item.Address}\";\r\n";
@@ -135,7 +135,7 @@ namespace StarsiegeBot
// setup an exit point check. // setup an exit point check.
bool exit = false; bool exit = false;
// if its null, we're going to exit. // 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; exit = true;
} }
@@ -147,7 +147,7 @@ namespace StarsiegeBot
DiscordMessageBuilder msg = new DiscordMessageBuilder(); DiscordMessageBuilder msg = new DiscordMessageBuilder();
// we're on our way to greatness! // we're on our way to greatness!
int count = 0; int count = 0;
foreach (var item in gameData.Games) foreach (GameServer item in _gameData.Games)
{ {
// if (item.PlayerCount > playerCount) // if (item.PlayerCount > playerCount)
if (item.GameStatus["Started"]) if (item.GameStatus["Started"])
+90 -41
View File
@@ -16,15 +16,15 @@ namespace StarsiegeBot
[Aliases("qc"), Group("quickchat")] [Aliases("qc"), Group("quickchat")]
class QuickchatHandler : BaseCommandModule class QuickchatHandler : BaseCommandModule
{ {
private Dictionary<string, Quickchat> quickchats; private Dictionary<string, Quickchat> _quickchats;
private bool IsEnabled; private bool _isEnabled;
private readonly string fileName = "Json/quickchats.json"; private readonly string _fileName = "Json/quickchats.json";
public QuickchatHandler() public QuickchatHandler()
{ {
Console.WriteLine("Quick Chat Handler Loaded"); Console.WriteLine("Quick Chat Handler Loaded");
IsEnabled = LoadQuickChatsImpl(); _isEnabled = LoadQuickChatsImpl();
} }
/** /**
@@ -34,14 +34,14 @@ namespace StarsiegeBot
private bool LoadQuickChatsImpl() private bool LoadQuickChatsImpl()
{ {
// Check to see if the file exists... // Check to see if the file exists...
if (File.Exists(fileName)) if (File.Exists(_fileName))
{ {
// Load the JSON file. // Load the JSON file.
var json = ""; string json = "";
using (var fs = File.OpenRead(fileName)) using (FileStream fs = File.OpenRead(_fileName))
using (var sr = new StreamReader(fs, new UTF8Encoding(false))) using (StreamReader sr = new StreamReader(fs, new UTF8Encoding(false)))
json = sr.ReadToEnd(); json = sr.ReadToEnd();
quickchats = JsonConvert.DeserializeObject<Dictionary<string, Quickchat>>(json); _quickchats = JsonConvert.DeserializeObject<Dictionary<string, Quickchat>>(json);
// enable the commands. // enable the commands.
return true; return true;
} }
@@ -57,8 +57,8 @@ namespace StarsiegeBot
{ {
await ctx.TriggerTypingAsync(); await ctx.TriggerTypingAsync();
string output; string output;
IsEnabled = LoadQuickChatsImpl(); _isEnabled = LoadQuickChatsImpl();
if (IsEnabled) if (_isEnabled)
{ {
output = "Loading Quick Chats successful."; 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) 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 we're disabled, let them know. And exit out.
if (!IsEnabled) if (!_isEnabled)
{ {
return; return;
} }
@@ -85,16 +85,16 @@ namespace StarsiegeBot
index = Math.Abs(index); index = Math.Abs(index);
// is our index within bounds? // is our index within bounds?
if (index < quickchats.Count) if (index < _quickchats.Count)
{ {
// yes it is, give the script to them. // yes it is, give the script to them.
Quickchat chat = quickchats[index.ToString()]; Quickchat chat = _quickchats[index.ToString()];
await ctx.RespondAsync("```" + chat.ToString() + "```"); await ctx.RespondAsync("```" + chat.ToString() + "```");
return; return;
} }
// we couldn't find it... Oh well, let the end user know. // 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")] [Command("check")]
@@ -102,7 +102,7 @@ namespace StarsiegeBot
public async Task QuickChatCheck(CommandContext ctx) public async Task QuickChatCheck(CommandContext ctx)
{ {
// If we're disabled, let them know. And exit out. // If we're disabled, let them know. And exit out.
if (!IsEnabled) if (!_isEnabled)
{ {
return; return;
} }
@@ -110,10 +110,10 @@ namespace StarsiegeBot
// Start a count // Start a count
int missingFiles = 0; 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 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++; missingFiles++;
Console.Write($"{i}, "); 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) 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 we're disabled, let them know. And exit out.
if (!IsEnabled) if (!_isEnabled)
{ {
return; return;
} }
@@ -148,7 +148,7 @@ namespace StarsiegeBot
{ {
id = Math.Abs(id); id = Math.Abs(id);
} }
chat = quickchats[id.ToString()]; chat = _quickchats[id.ToString()];
output = id + ": " + chat.Text; output = id + ": " + chat.Text;
} }
catch (Exception) catch (Exception)
@@ -158,8 +158,8 @@ namespace StarsiegeBot
{ {
try try
{ {
id = Program.rnd.Next(quickchats.Count); id = Program.rnd.Next(_quickchats.Count);
chat = quickchats[id.ToString()]; chat = _quickchats[id.ToString()];
output = $"[{id}] " + chat.Text; output = $"[{id}] " + chat.Text;
} }
catch (Exception) catch (Exception)
@@ -195,7 +195,7 @@ namespace StarsiegeBot
string output; string output;
// If we're disabled, let them know. And exit out. // 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."); await ctx.RespondAsync("Quick Chat Commands have been disabled. Please contact the bot owners.");
return; return;
@@ -207,19 +207,19 @@ namespace StarsiegeBot
int count = 0; int count = 0;
// We're going to search each QC for the stuff in toSearch. // We're going to search each QC for the stuff in toSearch.
foreach (KeyValuePair<string, Quickchat> qc in quickchats) foreach (KeyValuePair<string, Quickchat> qc in _quickchats)
{ {
// do we have a match? // do we have a match?
if (qc.Value.Text.ToLower().Contains(toSearch.ToLower())) if (qc.Value.Text.ToLower().Contains(toSearch.ToLower()))
{ {
// add it to the list! // 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++; count++;
} }
if (qc.Value.SoundFile.ToLower().Contains(toSearch.ToLower())) if (qc.Value.SoundFile.ToLower().Contains(toSearch.ToLower()))
{ {
// add it to the list! // 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++; count++;
} }
} }
@@ -243,16 +243,37 @@ namespace StarsiegeBot
[Command("flag")] [Command("flag")]
[Description("Flags a Quick Chat for moderator checking.")] [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(); await ctx.TriggerTypingAsync();
Quickchat chat = quickchats[id.ToString()]; Quickchat chat = _quickchats[id.ToString()];
DiscordEmbedBuilder embed; 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; chat.IsFlagged = true;
string output = JsonConvert.SerializeObject(quickchats); string output = JsonConvert.SerializeObject(_quickchats);
await File.WriteAllTextAsync(fileName, output); await File.WriteAllTextAsync(_fileName, output);
await ctx.RespondAsync(embed); await ctx.RespondAsync(embed);
} }
@@ -261,7 +282,7 @@ namespace StarsiegeBot
{ {
await ctx.TriggerTypingAsync(); await ctx.TriggerTypingAsync();
int count = 0; int count = 0;
foreach (var chat in quickchats) foreach (KeyValuePair<string, Quickchat> chat in _quickchats)
{ {
if (chat.Value.IsFlagged) if (chat.Value.IsFlagged)
{ {
@@ -271,7 +292,6 @@ namespace StarsiegeBot
await ctx.RespondAsync(StartEmbed($"There are {count} flagged Quick Chats.")); await ctx.RespondAsync(StartEmbed($"There are {count} flagged Quick Chats."));
} }
[Command("toggle"), Aliases("t")] [Command("toggle"), Aliases("t")]
[RequireOwner] [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`")] [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[] turnOn = { "on", "true", "1" };
string[] turnOff = { "off", "false", "0" }; string[] turnOff = { "off", "false", "0" };
if (File.Exists(fileName)) if (File.Exists(_fileName))
{ {
if (turnOn.Contains(isEnabled)) if (turnOn.Contains(isEnabled))
{ {
IsEnabled = true; _isEnabled = true;
} }
if (turnOff.Contains(isEnabled)) if (turnOff.Contains(isEnabled))
{ {
IsEnabled = false; _isEnabled = false;
} }
output = $"Quickchats {(IsEnabled ? "Enabled" : "Disabled")}"; output = $"Quickchats {(_isEnabled ? "Enabled" : "Disabled")}";
} }
else else
{ {
IsEnabled = false; _isEnabled = false;
output = $"{fileName} file is missing, and it can not be enabled."; output = $"{_fileName} file is missing, and it can not be enabled.";
} }
await ctx.RespondAsync(StartEmbed(output)); await ctx.RespondAsync(StartEmbed(output));
} }
@@ -322,11 +342,40 @@ namespace StarsiegeBot
[JsonProperty("soundFile")] [JsonProperty("soundFile")]
public string SoundFile { get; protected set; } public string SoundFile { get; protected set; }
public bool IsFlagged { get; set; } public bool IsFlagged { get; set; }
public int FlagCount { get; set; } [JsonProperty("flags")]
public List<FlagEvent> Flags { get; set; }
public override string ToString() public override string ToString()
{ {
return $"say(0,0, \"{Text}\", \"{SoundFile}\");"; return $"say(0,0, \"{Text}\", \"{SoundFile}\");";
} }
} }
public class FlagEvent : IEquatable<FlagEvent>
{
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();
}
}
} }
+1 -1
View File
@@ -12,7 +12,7 @@ namespace StarsiegeBot
[Group("welcome")] [Group("welcome")]
[RequireGuild, [RequireGuild,
RequirePermissions(Permissions.ManageChannels), RequirePermissions(Permissions.ManageChannels),
Cooldown(1,10,CooldownBucketType.Global), Cooldown(1, 10, CooldownBucketType.Global),
RequireNsfw, RequireNsfw,
RequireBotPermissions(Permissions.AccessChannels) RequireBotPermissions(Permissions.AccessChannels)
//RequireBotPermissions(Permissions.AddReactions), //RequireBotPermissions(Permissions.AddReactions),