Added in fail checks on files existing for all the JSON files in the project. Minus questions.json since that file doesn't exist quite yet.

This commit is contained in:
Christopher Darnell committed 2021-04-18 00:43:18 -07:00
1 parent 9af84c3e62
commit f1ac028c35
4 files changed
+216 -26

No files matched your search

+9 -1
View File
@@ -201,6 +201,12 @@ namespace StarsiegeBot
{
d.Logger.LogDebug(BotEventId, "Event_MessageCreated.");
// Ignore all bots. We don't care.
if (e.Author.IsBot)
{
return Task.CompletedTask;
}
CommandsNextExtension cnext = d.GetCommandsNext();
DiscordMessage msg = e.Message;
@@ -208,7 +214,7 @@ namespace StarsiegeBot
// json file loaded...
int cmdStart = msg.GetStringPrefixLength("!");
// e.
// if Guild is null, do nothing for now.
if (e.Guild is null)
{
@@ -223,10 +229,12 @@ namespace StarsiegeBot
// see if the guild wants global prefixes.
if (BotSettings.GuildSettings[gId].UseGlobalPrefix)
{
// add the Guild prefixes to the list of others.
prefixes = prefixes.Concat(BotSettings.GuildSettings[gId].Prefixes).ToList();
}
else
{
// dont use defaults? reset list to just the guild prefixes.
prefixes = BotSettings.GuildSettings[gId].Prefixes;
}
}
+80 -6
View File
@@ -26,41 +26,75 @@ namespace StarsiegeBot
{
private readonly Random rnd = new Random();
private readonly DeathMessageLines dmLines;
private bool DeathMessagesEnabled;
public DeathMessages()
{
Console.WriteLine("Death Message Commands Loaded.");
var json = "";
using (var fs = File.OpenRead("DeathMessages.json"))
using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
json = sr.ReadToEnd();
dmLines = JsonConvert.DeserializeObject<DeathMessageLines>(json);
// If the DeathMessages file exists, load it. And enable the commands.
// Otherwise disable all the commands.
if (File.Exists("DeathMessages.json"))
{
// set some JSON text to blank.
var json = "";
using (var fs = File.OpenRead("DeathMessages.json"))
using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
json = sr.ReadToEnd();
// Decode the JSON and set it to dmLines.
dmLines = JsonConvert.DeserializeObject<DeathMessageLines>(json);
// Enable all the commands.
DeathMessagesEnabled = true;
}
else
{
// Echo out that we're missing a file. Disable the commands due to that.
Console.WriteLine(" --- --- --- --- DeathMessages.json is missing");
DeathMessagesEnabled = false;
}
}
[GroupCommand]
public async Task DeathMessage(CommandContext ctx, [Description("Optional. Person you want to see kill you. If blank, will show generic death message.")]DiscordMember target = null)
{
// We're typing! (In all honesty, this is just used to avoid the 'async task not using await' messages I get.
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)
{
await ctx.RespondAsync("Death Messages Commands have been disabled. Please contact the bot owners.");
return;
}
// set some basic output incase something goes south.
string line = "Something went wrong.";
// if there is no target, we're going to "kill" the author.
if (target == null)
{
int choice = 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.
else
{
// Pick a death message type at random.
int opt = rnd.Next(1, 3);
// If we picked active death messages...
if (opt == 1)
{
// Pick an Active death message at random, and set our output to it.
int choice = 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 = 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));
}
}
@@ -69,7 +103,16 @@ namespace StarsiegeBot
[Description("Gets the total of each type of death message")]
public async Task DeathMessageCount(CommandContext ctx)
{
// 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)
{
await ctx.RespondAsync("Death Messages Commands have been disabled. Please contact the bot owners.");
return;
}
// 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}");
}
@@ -77,8 +120,18 @@ namespace StarsiegeBot
[Description("Adds a message to the Pending Death Message Queue. Generic Death Messages require just a [Killed] while any other death message requires both a [Killed] and a [Killer] tags. These will be replaced with the correct information in game, and in the usage of random DM generation.")]
public async Task DeathMessageNew(CommandContext ctx, [RemainingText,Description("The Death Message you want added. See help section.")] string msg)
{
// 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)
{
await ctx.RespondAsync("Death Messages Commands have been disabled. Please contact the bot owners.");
return;
}
// Let Discord know we're typing.
await ctx.TriggerTypingAsync();
// Message the owner know some one wants to add a new death message, along with a code block to that message.
await Program.notify.SendMessageAsync($"{ctx.Message.Author.Username} wantes to add the death messages. ```{msg}```");
// Tell the person that the message has been added to a 'queue'.
await ctx.RespondAsync("Your request has been added to the pending queue of requests.");
}
@@ -88,30 +141,43 @@ namespace StarsiegeBot
public async Task DeathMessagesScript(CommandContext ctx)
{
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)
{
await ctx.RespondAsync("Death Messages Commands have been disabled. Please contact the bot owners.");
return;
}
// If this file exists... We could do one of two things. Delete it and remake it, or serve it up.
if (File.Exists("deathmessages.cs"))
{
File.Delete("deathmessages.cs");
}
// We're going to remake it. Open it.
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");
// 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)
{
await file.WriteLineAsync(string.Format($"$deathMessage::generic{count} = \"{death}\";", "%s", "%s"));
count++;
}
// Reset the count...
count = 0;
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)
{
@@ -119,13 +185,21 @@ namespace StarsiegeBot
count++;
}
DiscordMessageBuilder msg = new DiscordMessageBuilder();
// We're done writing to it... So close the file.
file.Close();
// We're going to Message Build the response.
DiscordMessageBuilder msg = new DiscordMessageBuilder();
// Open the file to upload.
FileStream sound = new FileStream($"deathmessages.cs", FileMode.Open);
// Tell DSharp that we want to upload this file.
msg.WithFile(sound);
// Add some content so its not a blank file.
msg.Content ="Here is your request for a death message script.";
// send that message.
await ctx.RespondAsync(msg);
// We're done with the file, so close access to it.
sound.Close();
}
}
class DeathMessageLines
+49 -9
View File
@@ -31,16 +31,28 @@ namespace StarsiegeBot
DiscordColor.Violet, DiscordColor.Wheat, DiscordColor.White, DiscordColor.Yellow };
private readonly Random rnd = new Random();
private readonly Dictionary<string, SSFunction> ssFunctions;
private readonly bool FunctionsEnabled;
public Functions()
{
Console.WriteLine("Starsiege Function Commands Loaded");
// Load the Functions JSON file. Has all information regarding Starsiege in-game Functions.
var json = "";
using (var fs = File.OpenRead("functions.json"))
using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
json = sr.ReadToEnd();
ssFunctions = JsonConvert.DeserializeObject<Dictionary<string, SSFunction>>(json);
// Check for file, if not there, disable commands.
if (File.Exists("functions.json"))
{
// Load the Functions JSON file. Has all information regarding Starsiege in-game Functions.
var json = "";
using (var fs = File.OpenRead("functions.json"))
using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
json = sr.ReadToEnd();
ssFunctions = JsonConvert.DeserializeObject<Dictionary<string, SSFunction>>(json);
FunctionsEnabled = true;
}
else
{
FunctionsEnabled = false;
Console.WriteLine(" --- --- --- Functions JSON not found.");
}
}
[GroupCommand]
@@ -48,39 +60,61 @@ namespace StarsiegeBot
public async Task StarsiegeFunctions(CommandContext ctx, [RemainingText, Description("The function to attempt to look up.")] string command = "")
{
await ctx.TriggerTypingAsync();
if (!FunctionsEnabled)
{
await ctx.RespondAsync("Function Commands have been disabled. Please contact the bot owners.");
return;
}
// If the function command is empty make a list of commands in Starsiege.
if (command.Equals(string.Empty))
{
// Get a list of the Keys.
List<string> keys = new List<string>(ssFunctions.Keys);
// get a new output.
string output = string.Empty;
// loop over the keys.
foreach (string item in keys)
{
// if our output is empty, add the first time.
if (output.Equals(string.Empty))
{
output = $"`{item}`";
}
// output is nto empty, add second or further item with a comma.
else
{
output += $", `{item}`";
}
}
// send the output.
await ctx.RespondAsync("List of known Functions in Starsiege: " + output);
}
// we have a command the want to try to find.
else if (ssFunctions.TryGetValue(command.ToLower(), out SSFunction outItem))
{
// New Message Embed!
DiscordEmbedBuilder embed = new DiscordEmbedBuilder();
// Set the title to the name of this function.
embed.WithTitle(outItem.title);
// set the timestamp to now... why, idk, its not really needed actually.
embed.WithTimestamp(DateTime.Now);
// add a random color to the left side bar of the embed.
embed.WithColor(colours[rnd.Next(0, colours.Length)]);
// Message Description, I dont remember what it is any more, sorry!
embed.WithDescription(outItem.description);
// iterate over each field item, and add them to the embed.
foreach (Fields item in outItem.fields)
{
embed.AddField(item.name, item.value, true);
}
// Build the Embed.
DiscordEmbed em = embed.Build();
// send the embed.
await ctx.RespondAsync(embed: em);
}
// we couldn't find that exact command... let them know.
else
{
await ctx.RespondAsync("That command wasn't food, pot-head.");
@@ -91,6 +125,14 @@ namespace StarsiegeBot
public async Task FunctionCount(CommandContext ctx)
{
await ctx.TriggerTypingAsync();
// check ot make sure these commands are enabled. if disabled, report it.
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.");
}
@@ -124,6 +166,4 @@ namespace StarsiegeBot
return $"Name: {name} || Value: {value}";
}
}
}
+78 -10
View File
@@ -24,31 +24,58 @@ namespace StarsiegeBot
{
private readonly List<Quickchats> Quickchats;
private readonly Random rnd = new Random();
private readonly bool QuickChatsEnabled;
public Quickchat()
{
Console.WriteLine("Quick Chat Commands Loaded");
// Load all the Quick Chat texts and sound wav file info.
var json = "";
using (var fs = File.OpenRead("quickchats.json"))
using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
json = sr.ReadToEnd();
Dictionary<string, Quickchats> tempQC = JsonConvert.DeserializeObject<Dictionary<string, Quickchats>>(json);
Quickchats = Enumerable.ToList(tempQC.Values);
// Check to see if the file exists... Otherwise disable all commands.
if (File.Exists("quickchats.json"))
{
// Load the JSON file.
var json = "";
using (var fs = File.OpenRead("quickchats.json"))
using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
json = sr.ReadToEnd();
Dictionary<string, Quickchats> tempQC = JsonConvert.DeserializeObject<Dictionary<string, Quickchats>>(json);
// set the Quick Chat object.
Quickchats = Enumerable.ToList(tempQC.Values);
// enable the commands.
QuickChatsEnabled = true;
}
else
{
// file not found. disable commands, leave a comment in console.
Console.WriteLine(" -- --- --- Quick Chat JSON file not found.");
QuickChatsEnabled = false;
}
}
[Command("script")]
[Description("Gives the `say()` for use in the Quickchat.cs file.")]
public async Task GetQuickChatScript(CommandContext ctx, [Description("ID of Quick chat to get script for.")] int index)
{
// trigger some typing on discord's side.
await ctx.TriggerTypingAsync();
if (index < Quickchats.Count || index >= 0)
// If we're disabled, let them know. And exit out.
if (!QuickChatsEnabled)
{
await ctx.RespondAsync("Quick Chat Commands have been disabled. Please contact the bot owners.");
return;
}
// We're good to go... If we have an index, pull it up.
index = Math.Abs(index);
// is our index within bounds?
if (index < Quickchats.Count)
{
// yes it is, give the script to them.
Quickchats chat = Quickchats[index];
// why does this look broken, yet works? maybe its the ToString() function. I unno.
await ctx.RespondAsync("```" + chat.ToString() + "```");
}
else
{
// 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));
}
}
@@ -57,15 +84,25 @@ namespace StarsiegeBot
[Description("Runs a check to see how many WAV files are missing from all QC's.")]
public async Task QuickChatCheck(CommandContext ctx)
{
await ctx.TriggerTypingAsync();
// If we're disabled, let them know. And exit out.
if (!QuickChatsEnabled)
{
await ctx.RespondAsync("Quick Chat Commands have been disabled. Please contact the bot owners.");
return;
}
// Start a count
int missingFiles = 0;
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].soundFile}"))
{
missingFiles++;
Console.Write($"{i}, ");
}
}
// Reply to the message and let the user know we're missing X files.
await ctx.RespondAsync($"Missing files: {missingFiles}");
}
@@ -74,10 +111,18 @@ namespace StarsiegeBot
public async Task QuickChat(CommandContext ctx, [Description("The ID of the quick Chat.")] int id = -1)
{
await ctx.TriggerTypingAsync();
// If we're disabled, let them know. And exit out.
if (!QuickChatsEnabled)
{
await ctx.RespondAsync("Quick Chat Commands have been disabled. Please contact the bot owners.");
return;
}
// Start a new Message Build.
DiscordMessageBuilder msg = new DiscordMessageBuilder();
Quickchats chat;
// Make an absolute value out of what was given to us.
// -1 lets us know that we're doing random. A number out of bounds will also give a random number.
if (id != -1)
id = Math.Abs(id);
if (id == -1 || id > Quickchats.Count)
@@ -88,19 +133,27 @@ namespace StarsiegeBot
}
else
{
// we're given a number within bounds. Give them that QC.
chat = Quickchats[id];
msg.Content = id + ": " + chat.text;
}
// If the sound file to the select QC exists, upload it as well.
if (File.Exists($"./qc/{chat.soundFile}"))
{
// Open the file.
FileStream sound = new FileStream($"./qc/{chat.soundFile}", FileMode.Open);
// feed it to the Message Builder.
msg.WithFile(chat.soundFile, sound);
// Send the message.
await ctx.RespondAsync(msg);
// Close the file.
sound.Close();
}
else
{
// No file to upload, just send the the text QC.
await ctx.RespondAsync(msg);
}
}
@@ -109,19 +162,34 @@ namespace StarsiegeBot
public async Task SearchQuickChats(CommandContext ctx, [RemainingText] string toSearch)
{
await ctx.TriggerTypingAsync();
// If we're disabled, let them know. And exit out.
if (!QuickChatsEnabled)
{
await ctx.RespondAsync("Quick Chat Commands have been disabled. Please contact the bot owners.");
return;
}
// We're going to build a message.
DiscordMessageBuilder msg = new DiscordMessageBuilder();
msg.Content = "";
// We're going to search each QC for the stuff in toSearch.
for (int i = 0; i < Quickchats.Count; i++)
{
// do we have a match?
if (Quickchats[i].text.ToLower().Contains(toSearch.ToLower()))
{
// add it to the list!
msg.Content += $"[{i}] {Quickchats[i].text}\r\n";
}
}
// If message content is still nothing, report we found nothing.
if (msg.Content == "")
{
msg.Content = "No results found.";
}
// Tell the end user our results, or lack of.
await ctx.RespondAsync(msg);
}
}