Skip to content

Commit

Permalink
Merge pull request #77 from Keboo/codeReview
Browse files Browse the repository at this point in the history
Some thoughts and idea from code review on stream
  • Loading branch information
thomasloupe authored Jun 8, 2023
2 parents 2fa6c71 + 918337b commit db5b47e
Show file tree
Hide file tree
Showing 9 changed files with 254 additions and 148 deletions.
2 changes: 1 addition & 1 deletion Slackord/AppShell.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
xmlns:local="clr-namespace:MenuApp"
Shell.FlyoutBehavior="Disabled">

<ShellContent
<ShellContent
Title="Slackord"
ContentTemplate="{DataTemplate local:MainPage}"
Route="MainPage" />
Expand Down
78 changes: 44 additions & 34 deletions Slackord/Classes/DiscordBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,49 +4,56 @@
using Discord.Rest;
using Discord.WebSocket;
using MenuApp;
using System;

namespace Slackord.Classes
{
class DiscordBot
{
public DiscordSocketClient _discordClient;
public DiscordSocketClient DiscordClient { get; set; }
public IServiceProvider _services;

public async Task MainAsync(string discordToken)
{
Editor debugWindow = new();
MainThread.BeginInvokeOnMainThread(() =>
if (DiscordClient is not null)
{
MainPage.WriteToDebugWindow("Starting Slackord Bot..." + "\n");
});
_discordClient = new DiscordSocketClient();
throw new InvalidOperationException("DiscordClient is already initialized.");
}
//Editor debugWindow = new();
MainPage.WriteToDebugWindow("Starting Slackord Bot..." + "\n");

//DiscordClient = new DiscordSocketClient();
DiscordSocketConfig _config = new();
{
_config.GatewayIntents = GatewayIntents.DirectMessages | GatewayIntents.GuildMessages | GatewayIntents.Guilds;
}
_discordClient = new(_config);
DiscordClient = new(_config);
_services = new ServiceCollection()
.AddSingleton(_discordClient)
.AddSingleton(DiscordClient)
.BuildServiceProvider();
_discordClient.Log += DiscordClient_Log;
await _discordClient.LoginAsync(TokenType.Bot, discordToken.Trim());
await _discordClient.StartAsync();
await _discordClient.SetActivityAsync(new Game("for the Slackord command!", ActivityType.Watching));
_discordClient.Ready += ClientReady;
_discordClient.LoggedOut += OnClientDisconnect;
_discordClient.SlashCommandExecuted += SlashCommandHandler;
await Task.Delay(-1);
DiscordClient.Log += DiscordClient_Log;
await DiscordClient.LoginAsync(TokenType.Bot, discordToken.Trim());
await DiscordClient.StartAsync();
await DiscordClient.SetActivityAsync(new Game("for the Slackord command!", ActivityType.Watching));
DiscordClient.Ready += ClientReady;
DiscordClient.LoggedOut += OnClientDisconnect;
DiscordClient.SlashCommandExecuted += SlashCommandHandler;
//await Task.Delay(-1);
}

private async Task SlashCommandHandler(SocketSlashCommand command)
{
if (command.Data.Name.Equals("slackord"))
if (command.Data.Name.Equals("slackord") &&
DiscordClient.Guilds.FirstOrDefault() is { } guild)
{
var guildID = _discordClient.Guilds.FirstOrDefault().Id;
await MainPage.Current.Dispatcher.DispatchAsync(async () =>
{
await PostMessagesToDiscord(guildID, command);
});
var guildID = guild.Id;
//TODO: Do we actually need to dispatch to the UI thread here?
//await MainPage.Current.Dispatcher.DispatchAsync(async () =>
//{
// await PostMessagesToDiscord(guildID, command);
//});
await PostMessagesToDiscord(guildID, command);

}
}

Expand All @@ -61,7 +68,7 @@ private async Task ClientReady()
MainPage.BotConnectionButtonInstance.BackgroundColor = new Microsoft.Maui.Graphics.Color(0, 255, 0);
});

foreach (var guild in _discordClient.Guilds)
foreach (var guild in DiscordClient.Guilds)
{
var guildCommand = new SlashCommandBuilder();
guildCommand.WithName("slackord");
Expand Down Expand Up @@ -101,7 +108,7 @@ private Task DiscordClient_Log(LogMessage arg)
public async Task DisconectClient()
{
await MainPage.ChangeBotConnectionButton("Disconnecting", new Microsoft.Maui.Graphics.Color(255, 204, 0), new Microsoft.Maui.Graphics.Color(0, 0, 0));
await _discordClient.StopAsync();
await DiscordClient.StopAsync();
await MainPage.ToggleBotTokenEnable(true, new Microsoft.Maui.Graphics.Color(255, 69, 0));
await MainPage.ChangeBotConnectionButton("Disconnected", new Microsoft.Maui.Graphics.Color(255, 0, 0), new Microsoft.Maui.Graphics.Color(255, 255, 255));
await Task.CompletedTask;
Expand Down Expand Up @@ -131,7 +138,7 @@ public async Task PostMessagesToDiscord(ulong guildID, SocketInteraction interac

await interaction.DeferAsync();

SocketGuild guild = _discordClient.GetGuild(guildID);
SocketGuild guild = DiscordClient.GetGuild(guildID);
string categoryName = "Slackord Import";
var slackordCategory = await guild.CreateCategoryChannelAsync(categoryName);
ulong slackordCategoryId = slackordCategory.Id;
Expand All @@ -154,7 +161,7 @@ public async Task PostMessagesToDiscord(ulong guildID, SocketInteraction interac

try
{
await _discordClient.SetActivityAsync(new Game("messages...", ActivityType.Streaming));
await DiscordClient.SetActivityAsync(new Game("messages...", ActivityType.Streaming));
int messageCount = 0;

if (channels.TryGetValue(channelName, out var messages))
Expand Down Expand Up @@ -209,7 +216,7 @@ public async Task PostMessagesToDiscord(ulong guildID, SocketInteraction interac

if (sendAsThread)
{
if (_discordClient.GetChannel(createdChannelId) is SocketTextChannel textChannel)
if (DiscordClient.GetChannel(createdChannelId) is SocketTextChannel textChannel)
{
await textChannel.SendMessageAsync(messageToSend).ConfigureAwait(false);
var latestMessages = await textChannel.GetMessagesAsync(1).FlattenAsync();
Expand All @@ -228,12 +235,16 @@ public async Task PostMessagesToDiscord(ulong guildID, SocketInteraction interac
{
MainPage.WriteToDebugWindow("Caught a Slackdump thread reply exception where a JSON entry had thread_ts and wasn't actually a thread start or reply before it excepted. Sending as a normal message...");
});
await _discordClient.GetGuild(guildID).GetTextChannel(createdChannelId).SendMessageAsync(messageToSend).ConfigureAwait(false);
await DiscordClient.GetGuild(guildID).GetTextChannel(createdChannelId).SendMessageAsync(messageToSend).ConfigureAwait(false);
}
}
else if (sendAsNormalMessage)
{
await _discordClient.GetGuild(guildID).GetTextChannel(createdChannelId).SendMessageAsync(messageToSend).ConfigureAwait(false);
if (DiscordClient.GetGuild(guildID).GetTextChannel(createdChannelId) is { } channel)
{
await channel.SendMessageAsync(messageToSend).ConfigureAwait(false);
}
//TODO: else? Do we care?
}

progress += 1;
Expand Down Expand Up @@ -290,16 +301,16 @@ public async Task PostMessagesToDiscord(ulong guildID, SocketInteraction interac
}
}
}
await _discordClient.SetActivityAsync(new Game("for the Slackord command...", ActivityType.Listening));
await DiscordClient.SetActivityAsync(new Game("for the Slackord command...", ActivityType.Listening));
}
catch (Exception ex)
{
MainThread.BeginInvokeOnMainThread(() =>
{
MainPage.WriteToDebugWindow($"\n{ex.Message}\n");
});
Page page = new();
await page.DisplayAlert("Error", ex.Message, "OK");
//Page page = new();
//await page.DisplayAlert("Error", ex.Message, "OK");
}
}

Expand All @@ -309,8 +320,7 @@ public async Task PostMessagesToDiscord(ulong guildID, SocketInteraction interac
});

await interaction.FollowupAsync("All messages sent to Discord successfully!", ephemeral: true);
await _discordClient.SetActivityAsync(new Game("to some cool music!", ActivityType.Listening));
await Task.CompletedTask;
await DiscordClient.SetActivityAsync(new Game("to some cool music!", ActivityType.Listening));
}
}
}
81 changes: 55 additions & 26 deletions Slackord/Classes/ImportJson.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

namespace Slackord.Classes
{
class ImportJson
static class ImportJson
{
public static readonly Dictionary<string, List<string>> Channels = new();

Expand All @@ -21,40 +21,31 @@ public static async Task ImportJsonFolder(CancellationToken cancellationToken)
}

selectedFolder = result.Folder.Path;
subDirectories = Directory.GetDirectories(selectedFolder).ToList();
//subDirectories = Directory.GetDirectories(selectedFolder).ToList();

int folderCount = subDirectories.Count;
//int folderCount = subDirectories.Count;
int fileCount = 0;

foreach (var subDir in subDirectories)
{
var folderName = Path.GetFileName(subDir);
var files = Directory.EnumerateFiles(subDir, "*.*", SearchOption.TopDirectoryOnly)
.Where(s => s.EndsWith(".JSON", StringComparison.OrdinalIgnoreCase));

fileCount += files.Count();
}
//foreach (var subDir in subDirectories)
//{
// var folderName = Path.GetFileName(subDir);
// var files = Directory.EnumerateFiles(subDir, "*.*", SearchOption.TopDirectoryOnly)
// .Where(s => s.EndsWith(".JSON", StringComparison.OrdinalIgnoreCase));

await MainPage.Current.DisplayAlert("Information", $"Found {fileCount} JSON files in {folderCount} folders.", "OK");
// fileCount += files.Count();
//}
List<string> fileList = new();

foreach (var subDir in subDirectories)
foreach (var file in Directory.EnumerateFiles(selectedFolder, "*.json", SearchOption.AllDirectories))
{
var folderName = Path.GetFileName(subDir);
var files = Directory.EnumerateFiles(subDir, "*.*", SearchOption.TopDirectoryOnly)
.Where(s => s.EndsWith(".JSON", StringComparison.OrdinalIgnoreCase));

// Create a list to store the files for the channel
List<string> fileList = new();
fileCount++;
var folderName = Path.GetFileName(Path.GetDirectoryName(file));

foreach (var file in files)
string fileName = Path.GetFileNameWithoutExtension(file);
if (DateTime.TryParseExact(fileName, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var fileDate))
{
string fileName = Path.GetFileNameWithoutExtension(file);
if (DateTime.TryParseExact(fileName, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var fileDate))
{
fileList.Add(file);
}
fileList.Add(file);
}

if (fileList.Count > 0)
{
// Add the channel and its file list to the channels dictionary
Expand All @@ -65,10 +56,48 @@ public static async Task ImportJsonFolder(CancellationToken cancellationToken)
await parser.ParseJsonFiles(fileList, folderName, Channels);
}
}
int folderCount = Channels.Keys.Count;
await MainThread.InvokeOnMainThreadAsync(async () =>
{
await MainPage.Current.DisplayAlert("Information", $"Found {fileCount} JSON files in {folderCount} folders.", "OK");
});
MainPage.PushDebugText();

//foreach (var subDir in subDirectories)
//{
// var folderName = Path.GetFileName(subDir);
// var files = Directory.EnumerateFiles(subDir, "*.*", SearchOption.TopDirectoryOnly)
// .Where(s => s.EndsWith(".JSON", StringComparison.OrdinalIgnoreCase));
//
// // Create a list to store the files for the channel
// List<string> fileList = new();
//
// foreach (var file in files)
// {
// string fileName = Path.GetFileNameWithoutExtension(file);
// if (DateTime.TryParseExact(fileName, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var fileDate))
// {
// fileList.Add(file);
// }
// }
//
// if (fileList.Count > 0)
// {
// // Add the channel and its file list to the channels dictionary
// Channels[folderName] = fileList;
//
// // Parse JSON files for the channel
// var parser = new Parser();
// await parser.ParseJsonFiles(fileList, folderName, Channels);
// }
//}
}
catch (Exception ex)
{
//writeLog($"\n\n{ex.Message}\n\n");
MainPage.WriteToDebugWindow($"\n\n{ex.Message}\n\n");
//TODO
//MainPage.DisplayAlert
Page page = new();
await page.DisplayAlert("Error", ex.Message, "OK");
}
Expand Down
Loading

0 comments on commit db5b47e

Please sign in to comment.