Top down overhaul of the Quickchat Functionality

This commit is contained in:
Amrit Panesar committed 2021-04-29 05:27:21 -07:00
1 parent 08091e7456
commit 914a6ab254
4 files changed
+123 -112

No files matched your search

+1 -1
View File
@@ -344,7 +344,7 @@ namespace StarsiegeBot
"• UndeadShadow :: Flood Protection. Keepign teh bot from killing itself, and others.\r\n" +
"• Da_D_Master :: For giving me my start in my first couple bots, and being a friendly rival.\r\n" +
"• ThinkExist & Bored.com :: Quotes for the Quote Database\r\n" +
"• Hanibal, TaMeD, Liquid- :: For awlays proving the points of others.\r\n" +
"• Hanibal, TaMeD, Liquid- :: For always proving the points of others.\r\n" +
"• Neo :: For all their hard work on all the things I've ever asked about.\r\n" +
"• Alias :: For helping me learn how to make IRC bots back in the day.\r\n" +
"• Drake, Eledore :: Supporting the development of the bot and supplying code for it.\r\n" +
+1 -1
View File
@@ -129,7 +129,7 @@ namespace StarsiegeBot
// All these commands are in the STARSIEGE folder.
//if (BotName.Contains("ssp"))
//{
this.Commands.RegisterCommands<Quickchat>();
this.Commands.RegisterCommands<QuickchatHandler>();
this.Commands.RegisterCommands<Functions>();
this.Commands.RegisterCommands<DeathMessages>();
this.Commands.RegisterCommands<GameInfo>();
@@ -20,63 +20,59 @@ using Microsoft.Extensions.Logging;
namespace StarsiegeBot
{
[Aliases("qc"), Group("quickchat")]
class Quickchat : BaseCommandModule
class QuickchatHandler : BaseCommandModule
{
private List<Quickchats> Quickchats;
private Dictionary<string, Quickchat> quickchats;
private readonly Random rnd = new Random();
private bool QuickChatsEnabled;
private bool IsQuickChatEnabled;
public Quickchat()
public QuickchatHandler()
{
Console.WriteLine("Quick Chat Commands Loaded");
// Check to see if the file exists... Otherwise disable all commands.
Console.WriteLine("Quick Chat Handler Loaded");
IsQuickChatEnabled = LoadQuickChatsImpl();
}
/**
* LoadQuickChatsImpl loads the quickchats.json file from the current path,
* parses the file, and populates the private quickchats dictionary.
**/
private bool LoadQuickChatsImpl()
{
// Check to see if the file exists...
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);
json = sr.ReadToEnd();
quickchats = JsonConvert.DeserializeObject<Dictionary<string, Quickchat>>(json);
// 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;
return true;
}
// else, file not found. disable commands, leave a comment in console.
Console.WriteLine(" -- --- --- Quick Chat JSON file not found.");
return false;
}
[Command("load"), RequireOwner]
[Description("[Onwer Only] Reloads the QuickChat files. If they exist. Also enables QC's if file is found.")]
[Description("[Owner Only] Reloads the QuickChat files, if they exist. Also enables QC's if the file is found.")]
public async Task LoadQuickChats(CommandContext ctx)
{
await ctx.TriggerTypingAsync();
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;
await ctx.RespondAsync("Loading Quick Chats successul.");
}
else
{
QuickChatsEnabled = false;
await ctx.RespondAsync("Loading Quick Chats failed. File does not exist.");
}
}
IsQuickChatEnabled = LoadQuickChatsImpl();
if (IsQuickChatEnabled)
{
await ctx.RespondAsync("Loading Quick Chats successful.");
return;
}
await ctx.RespondAsync("Loading Quick Chats failed. File does not exist.");
}
[Command("script")]
[Description("Gives the `say()` for use in the Quickchat.cs file.")]
@@ -84,27 +80,28 @@ namespace StarsiegeBot
{
// trigger some typing on discord's side.
await ctx.TriggerTypingAsync();
// If we're disabled, let them know. And exit out.
if (!QuickChatsEnabled)
if (!IsQuickChatEnabled)
{
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)
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.
Quickchat chat = quickchats[index.ToString()];
await ctx.RespondAsync("```" + chat.ToString() + "```");
return;
}
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));
}
// 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));
}
[Command("check")]
@@ -113,22 +110,24 @@ namespace StarsiegeBot
{
await ctx.TriggerTypingAsync();
// If we're disabled, let them know. And exit out.
if (!QuickChatsEnabled)
if (!IsQuickChatEnabled)
{
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++)
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}"))
if (!File.Exists($"./qc/{quickchats[i.ToString()].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}");
}
@@ -138,8 +137,10 @@ namespace StarsiegeBot
public async Task QuickChat(CommandContext ctx, [Description("The ID of the quick Chat.")] int id = -1)
{
await ctx.TriggerTypingAsync();
string output;
// If we're disabled, let them know. And exit out.
if (!QuickChatsEnabled)
if (!IsQuickChatEnabled)
{
await ctx.RespondAsync("Quick Chat Commands have been disabled. Please contact the bot owners.");
return;
@@ -147,42 +148,50 @@ namespace StarsiegeBot
// 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)
{
int idnum = rnd.Next(Quickchats.Count);
chat = Quickchats[idnum];
msg.Content = $"[{idnum}] " + chat.text;
}
else
{
// we're given a number within bounds. Give them that QC.
chat = Quickchats[id];
msg.Content = id + ": " + chat.text;
Quickchat chat;
// try to get the quick chat, if it doesn't exist, return a random one
try
{
if (id < -1)
{
id = Math.Abs(id);
}
chat = quickchats[id.ToString()];
output = id + ": " + chat.text;
}
catch (Exception)
{
// find a better quick chat.
while (true)
{
try
{
id = rnd.Next(quickchats.Count);
chat = quickchats[id.ToString()];
output = $"[{id}] " + chat.text;
}
catch (Exception)
{
continue;
}
break;
}
}
// 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);
FileStream sound = new FileStream($"./qc/{chat.soundFile}", FileMode.Open, FileAccess.Read);
// 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);
}
// Send either the text QC or sound file if we have it
msg.Content = output;
await ctx.RespondAsync(msg);
}
[Command("search"), Aliases("s")]
@@ -190,55 +199,60 @@ namespace StarsiegeBot
public async Task SearchQuickChats(CommandContext ctx, [RemainingText,Description("What to search for.")] string toSearch)
{
await ctx.TriggerTypingAsync();
string output;
// If we're disabled, let them know. And exit out.
if (!QuickChatsEnabled)
if (!IsQuickChatEnabled)
{
await ctx.RespondAsync("Quick Chat Commands have been disabled. Please contact the bot owners.");
return;
}
// We're going to build a message.
using StreamWriter file = new StreamWriter("tempQC.txt");
StringBuilder sb = new StringBuilder();
DiscordMessageBuilder msg = new DiscordMessageBuilder();
int Content = 0;
// We're going to search each QC for the stuff in toSearch.
for (int i = 0; i < Quickchats.Count; i++)
foreach (KeyValuePair<string, Quickchat> qc in quickchats)
{
// do we have a match?
if (Quickchats[i].text.ToLower().Contains(toSearch.ToLower()))
if (qc.Value.text.ToLower().Contains(toSearch.ToLower()))
{
// add it to the list!
await file.WriteLineAsync($"[{i}][T] {Quickchats[i].text}\r\n");
Content++;
sb.Append($"[{qc.Key}][T] {quickchats[qc.Key].text}\r\n");
}
if (Quickchats[i].soundFile.ToLower().Contains(toSearch.ToLower()))
if (qc.Value.soundFile.ToLower().Contains(toSearch.ToLower()))
{
// add it to the list!
await file.WriteLineAsync($"[{i}][S] {Quickchats[i].text}\r\n");
Content++;
sb.Append($"[{qc.Key}][S] {quickchats[qc.Key].text}\r\n");
}
}
file.Close();
// If message content is still nothing, report we found nothing.
if (Content == 0)
// If we have a message return it
if (sb.Length > 0)
{
msg.Content = "No results found.";
await ctx.RespondAsync(msg);
output = sb.ToString();
if (sb.Length >= 2000)
{
output = "Here are your results.";
MemoryStream mr = new MemoryStream(Encoding.UTF8.GetBytes(sb.ToString()));
msg.WithFile("results.txt", mr, true);
}
}
else
{
msg.Content = "Here are your results.";
FileStream upload = new FileStream($"tempQC.txt", FileMode.Open);
msg.WithFile("tempQC.txt", upload);
await ctx.RespondAsync(msg);
upload.Close();
// If message content is still nothing, report we found nothing.
output = "No results found.";
}
msg.Content = output;
await ctx.RespondAsync(msg);
}
[Command("toggle"), Aliases("t")]
[RequireOwner]
[Description("[Onwer only] Enables or disables, or checks status of QuickChats.")]
[Description("[Owner only] Enables or disables, or checks status of QuickChats.")]
public async Task ToggleQC (CommandContext ctx, [RemainingText] string isEnabled = null)
{
await ctx.TriggerTypingAsync();
@@ -251,27 +265,24 @@ namespace StarsiegeBot
{
if (turnOn.Contains(isEnabled))
{
QuickChatsEnabled = true;
IsQuickChatEnabled = true;
}
else if (turnOff.Contains(isEnabled))
if (turnOff.Contains(isEnabled))
{
QuickChatsEnabled = false;
IsQuickChatEnabled = false;
}
else
{
// we wont do anything here.
}
output = $"Quickchats Enabled: {QuickChatsEnabled}";
output = $"Quickchats {(IsQuickChatEnabled ? "Enabled":"Disabled")}";
}
else
{
QuickChatsEnabled = false;
IsQuickChatEnabled = false;
output = "QuickChats.json file is missing, and it can not be enabled.";
}
await ctx.RespondAsync(output);
}
}
public class Quickchats
public class Quickchat
{
public string text;
public string soundFile;