Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions wow2.Bot/BotService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ public static class BotService

public static CommandService CommandService { get; set; }

public static IDataManager DataManager { get; set; }

public static IServiceProvider Services { get; set; }

public static bool IsDisabled { get; set; } = false;
Expand Down Expand Up @@ -75,6 +77,7 @@ public static async Task InstallCommandsAsync()
}

Services = new ServiceCollection()
.AddSingleton(DataManager)
.AddSingleton<IYoutubeModuleService>(new YoutubeModuleService(DataManager.Secrets.GoogleApiKey))
.AddSingleton<IOsuModuleService>(new OsuModuleService(DataManager.Secrets.OsuClientId, DataManager.Secrets.OsuClientSecret))
.AddSingleton<ISpotifyModuleService>(new SpotifyModuleService(DataManager.Secrets.SpotifyClientId, DataManager.Secrets.SpotifyClientSecret))
Expand Down Expand Up @@ -166,8 +169,7 @@ public static async Task JoinedGuildAsync(SocketGuild guild)
// Only set if it's the first time the bot has joined this guild.
if (guildData.DateTimeJoinedBinary == 0)
{
DataManager.AllGuildData[guild.Id]
.DateTimeJoinedBinary = DateTime.Now.ToBinary();
DataManager.AllGuildData[guild.Id].DateTimeJoinedBinary = DateTime.Now.ToBinary();
}

// This could take a while.
Expand Down Expand Up @@ -325,7 +327,7 @@ public static async Task<IResult> ExecuteCommandAsync(SocketCommandContext conte

public static async Task SendErrorMessageToChannel(CommandError? commandError, SocketCommandContext context)
{
string commandPrefix = context.Guild.GetCommandPrefix();
string commandPrefix = DataManager.AllGuildData[context.Guild.Id].Main.CommandPrefix;

var matchingCommands = await SearchCommandsAsync(
context, context.Message.Content.MakeCommandInput(commandPrefix));
Expand Down Expand Up @@ -406,7 +408,7 @@ private static async Task ActOnMessageAsync(SocketCommandContext context)
}

if (message.Content.StartsWithWord(
context.Guild.GetCommandPrefix(), true))
DataManager.AllGuildData[context.Guild.Id].Main.CommandPrefix, true))
{
// The message starts with the command prefix and the prefix is not part of another word.
await ActOnMessageAsCommandAsync(context);
Expand All @@ -422,7 +424,7 @@ private static async Task ActOnMessageAsync(SocketCommandContext context)

private static async Task ActOnMessageAsCommandAsync(SocketCommandContext context)
{
string commandPrefix = context.Guild.GetCommandPrefix();
string commandPrefix = DataManager.AllGuildData[context.Guild.Id].Main.CommandPrefix;

if (context.Message.Content == commandPrefix)
{
Expand Down
31 changes: 16 additions & 15 deletions wow2.Bot/Data/DataManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,25 +10,26 @@

namespace wow2.Bot.Data
{
public static class DataManager
public class DataManager : IDataManager
{
public static readonly string AppDataDirPath = Environment.GetEnvironmentVariable("WOW2_APPDATA_FOLDER") ?? $"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}/wow2";
private static readonly JsonSerializerOptions SerializerOptions = new()
{
WriteIndented = true,
ReferenceHandler = ReferenceHandler.Preserve,
};

public static Dictionary<ulong, GuildData> AllGuildData { get; set; } = new Dictionary<ulong, GuildData>();
public string AppDataDirPath { get; } = Environment.GetEnvironmentVariable("WOW2_APPDATA_FOLDER") ?? $"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}/wow2";

public static Secrets Secrets { get; set; } = new Secrets();
public Secrets Secrets { get; set; } = new Secrets();

public static string GuildDataDirPath => $"{AppDataDirPath}/GuildData";
public string GuildDataDirPath => $"{AppDataDirPath}/GuildData";

public static string LogsDirPath => $"{AppDataDirPath}/Logs";
public string LogsDirPath => $"{AppDataDirPath}/Logs";

public Dictionary<ulong, GuildData> AllGuildData { get; } = new();

/// <summary>Creates required directories if necessary and loads all guild data.</summary>
public static async Task InitializeAsync()
public async Task InitializeAsync()
{
try
{
Expand All @@ -50,7 +51,7 @@ public static async Task InitializeAsync()
}

/// <summary>Deserializes the secrets.json file into the Secrets property. If it doesn't exist, creates one and stops the program.</summary>
public static async Task LoadSecretsFromFileAsync()
public async Task LoadSecretsFromFileAsync()
{
string fullPath = AppDataDirPath + "/secrets.json";
if (!File.Exists(fullPath))
Expand All @@ -68,7 +69,7 @@ public static async Task LoadSecretsFromFileAsync()
}

/// <summary>Load all guild data from all files, excluding the guilds the client is not in.</summary>
public static async Task LoadGuildDataFromFileAsync()
public async Task LoadGuildDataFromFileAsync()
{
Logger.Log("About to load all guild data.", LogSeverity.Verbose);
foreach (FileInfo fileInfo in new DirectoryInfo(GuildDataDirPath).EnumerateFiles())
Expand All @@ -92,7 +93,7 @@ public static async Task LoadGuildDataFromFileAsync()
}

/// <summary>Load guild data from the corresponding file.</summary>
public static async Task LoadGuildDataFromFileAsync(ulong guildId)
public async Task LoadGuildDataFromFileAsync(ulong guildId)
{
try
{
Expand All @@ -107,7 +108,7 @@ public static async Task LoadGuildDataFromFileAsync(ulong guildId)
}

/// <summary>Write all guild data to corresponding files.</summary>
public static async Task SaveGuildDataToFileAsync()
public async Task SaveGuildDataToFileAsync()
{
Logger.Log("About to save all guild data.", LogSeverity.Verbose);
foreach (ulong guildId in AllGuildData.Keys)
Expand All @@ -124,7 +125,7 @@ public static async Task SaveGuildDataToFileAsync()
}

/// <summary>Write guild data to file for a specific guild.</summary>
public static async Task SaveGuildDataToFileAsync(ulong guildId)
public async Task SaveGuildDataToFileAsync(ulong guildId)
{
if (!AllGuildData.TryGetValue(guildId, out GuildData guildData))
throw new KeyNotFoundException($"The guild ID {guildId} was not found in the dictionary");
Expand All @@ -137,7 +138,7 @@ await File.WriteAllTextAsync(

/// <summary>If the GuildData for the specified guild does not exist, one will be created.</summary>
/// <returns>The GuildData for the guild.</returns>
public static async Task<GuildData> EnsureGuildDataExistsAsync(ulong guildId)
public async Task<GuildData> EnsureGuildDataExistsAsync(ulong guildId)
{
if (File.Exists($"{GuildDataDirPath}/{guildId}.json"))
{
Expand All @@ -155,14 +156,14 @@ public static async Task<GuildData> EnsureGuildDataExistsAsync(ulong guildId)
return AllGuildData[guildId];
}

public static async Task UnloadGuildDataAsync(ulong guildId)
public async Task UnloadGuildDataAsync(ulong guildId)
{
await SaveGuildDataToFileAsync(guildId);
AllGuildData.Remove(guildId);
Logger.Log($"Unloaded guild data for {guildId}", LogSeverity.Verbose);
}

public static void EnsureGuildNameExists(ulong guildId)
public void EnsureGuildNameExists(ulong guildId)
{
var guildData = AllGuildData[guildId];
if (guildData?.NameOfGuild == null)
Expand Down
34 changes: 34 additions & 0 deletions wow2.Bot/Data/IDataManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using System.Collections.Generic;
using System.Threading.Tasks;

namespace wow2.Bot.Data
{
public interface IDataManager
{
string GuildDataDirPath { get; }

string AppDataDirPath { get; }

string LogsDirPath { get; }

Dictionary<ulong, GuildData> AllGuildData { get; }

Secrets Secrets { get; set; }

Task InitializeAsync();

Task LoadSecretsFromFileAsync();

Task LoadGuildDataFromFileAsync();

Task LoadGuildDataFromFileAsync(ulong guildId);

Task SaveGuildDataToFileAsync();

Task SaveGuildDataToFileAsync(ulong guildId);

Task UnloadGuildDataAsync(ulong guildId);

Task<GuildData> EnsureGuildDataExistsAsync(ulong guildId);
}
}
3 changes: 0 additions & 3 deletions wow2.Bot/Extensions/DiscordExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,6 @@ public static SocketGuild GetGuild(this IMessage userMessage)
public static SocketGuild GetGuild(this ISocketMessageChannel messageChannel)
=> ((SocketGuildChannel)messageChannel).Guild;

public static string GetCommandPrefix(this IGuild guild) =>
DataManager.AllGuildData[guild.Id].Main.CommandPrefix;

/// <summary>Creates a string from a list of commands, with newlines placed between each command.</summary>
/// <returns>A string representing the list of commands.</returns>
public static string MakeReadableString(this IEnumerable<CommandInfo> commands, string commandPrefix)
Expand Down
4 changes: 3 additions & 1 deletion wow2.Bot/Modules/Dev/DevModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ namespace wow2.Bot.Modules.Dev
[Summary("Boring stuff for developers.")]
public class DevModule : Module
{
public IDataManager DataManager { get; set; }

[Command("load-guild-data")]
[Alias("load")]
[Summary("Loads guild data from file to memory, discarding any unsaved changes.")]
Expand Down Expand Up @@ -94,7 +96,7 @@ public async Task GuildListAsync()
public async Task GetGuildDataAsync(ulong id = 0)
{
await Context.Channel.SendFileAsync(
filePath: $"{DataManager.AppDataDirPath}/GuildData/{(id != 0 ? id : Context.Guild.Id)}.json");
filePath: $"{DataManager.GuildDataDirPath}/{(id != 0 ? id : Context.Guild.Id)}.json");
}

[Command("set-status")]
Expand Down
5 changes: 3 additions & 2 deletions wow2.Bot/Modules/Dev/Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ static Tests()
}
}

[Test("messages")]
// TODO: uncomment (or honestly just nuke this)
/*[Test("messages")]
public static async Task MessagesTest(SocketCommandContext context)
{
await new SuccessMessage("This is a success message.", "Success").SendAsync(context.Channel);
Expand Down Expand Up @@ -295,6 +296,6 @@ private static async Task AssertAsync(SocketCommandContext context, Dictionary<s
{
foreach (var assert in asserts)
await AssertAsync(context, assert.Key, assert.Value);
}
}*/
}
}
2 changes: 1 addition & 1 deletion wow2.Bot/Modules/Keywords/KeywordsModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ async Task delete()
onConfirm: delete,
onDeny: async () =>
{
await new InfoMessage($"You can do that by typing `{Context.Guild.GetCommandPrefix()} keywords remove {keyword} [VALUE]`", "Just want to remove one value?")
await new InfoMessage($"You can do that by typing `{CommandPrefix} keywords remove {keyword} [VALUE]`", "Just want to remove one value?")
.SendAsync(Context.Channel);
})
.SendAsync(Context.Channel);
Expand Down
4 changes: 4 additions & 0 deletions wow2.Bot/Modules/Module.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ namespace wow2.Bot.Modules
{
public abstract class Module : ModuleBase<SocketCommandContext>
{
public IDataManager DataManager { get; set; }

public string CommandPrefix => DataManager.AllGuildData[Context.Guild.Id].Main.CommandPrefix;

public async Task SendToggleQuestionAsync(
bool currentState,
Action<bool> setter,
Expand Down
1 change: 0 additions & 1 deletion wow2.Bot/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ private async Task MainAsync(string[] args)
IsDebug = true;
#endif
await Logger.LogInitialize();
await DataManager.LoadSecretsFromFileAsync();

Options.Parse(args);

Expand Down