Skip to content

Commit

Permalink
add dryrun option to resync
Browse files Browse the repository at this point in the history
  • Loading branch information
loukylor committed Dec 19, 2024
1 parent 8a2e82f commit 1dd90c0
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 19 deletions.
12 changes: 12 additions & 0 deletions TrickFireDiscordBot/Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,22 @@ public class Config
/// </summary>
public string TeamsPropertyName { get; set; } = "";

/// <summary>
/// The id of the technical lead role.
/// </summary>
public ulong TechnicalLeadRoleId { get; set; } = 0;

/// <summary>
/// A regex determining if the club position listed in notion makes a
/// member a technical lead.
/// </summary>
public string TechnicalLeadRegex { get; set; } = "";

/// <summary>
/// The id of the inactive role.
/// </summary>
public ulong InactiveRoleId { get; set; } = 0;

/// <summary>
/// Returns a config object loaded from the file at <paramref name="path"/>.
/// </summary>
Expand Down
9 changes: 7 additions & 2 deletions TrickFireDiscordBot/Discord/Commands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,15 @@ public static ValueTask Ping(SlashCommandContext context)
[Command("resyncall")]
[Description("Resyncs all members' roles with their Notion page")]
[InteractionAllowedContexts(DiscordInteractionContextType.Guild)]
public static async Task ResyncAllRoles(SlashCommandContext context)
[RequirePermissions([], [DiscordPermission.Administrator])]
public static async Task ResyncAllRoles(
SlashCommandContext context,
[Parameter("dryRun")]
[Description("Set to false to actually affect roles")]
bool dryRun = true)
{
await context.DeferResponseAsync();
await context.ServiceProvider.GetRequiredService<RoleSyncer>().SyncAllMemberRoles();
await context.ServiceProvider.GetRequiredService<RoleSyncer>().SyncAllMemberRoles(dryRun);
await context.RespondAsync("Finished");
}

Expand Down
2 changes: 1 addition & 1 deletion TrickFireDiscordBot/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ static async Task Main(string[] args)
await bot.Start();

// Start the role syncer
await bot.Client.ServiceProvider.GetRequiredService<RoleSyncer>().Start(bot.Client);
await bot.Client.ServiceProvider.GetRequiredService<RoleSyncer>().Start();
}
catch (Exception e)
{
Expand Down
45 changes: 29 additions & 16 deletions TrickFireDiscordBot/RoleSyncer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,26 @@

namespace TrickFireDiscordBot
{
public class RoleSyncer(ILogger<RoleSyncer> logger, INotionClient notionClient, WebhookListener listener)
public class RoleSyncer(ILogger<RoleSyncer> logger, INotionClient notionClient, DiscordClient discordClient, WebhookListener listener)
{
public const string WebhookEndpoint = "/members";

private static readonly Regex _technicalLeadRegex = new(Config.Instance.TechnicalLeadRegex);

public ILogger Logger { get; } = logger;
public INotionClient NotionClient { get; } = notionClient;
public DiscordClient DiscordClient { get; } = discordClient;
public WebhookListener WebhookListener { get; } = listener;

private DiscordGuild? _trickFireGuild;
private readonly Dictionary<string, DiscordRole> _discordRoleCache = [];
private string? _teamPageNamePropertyId = null;

public async Task Start(DiscordClient discordClient)
public async Task Start()
{
WebhookListener.OnWebhookReceived += OnWebhook;

_trickFireGuild = await discordClient.GetGuildAsync(Config.Instance.TrickfireGuildId);
_trickFireGuild = await DiscordClient.GetGuildAsync(Config.Instance.TrickfireGuildId);
foreach (DiscordRole role in _trickFireGuild.Roles.Values)
{
_discordRoleCache.Add(role.Name, role);
Expand All @@ -39,7 +40,7 @@ public void Stop()
WebhookListener.OnWebhookReceived -= OnWebhook;
}

public async Task SyncAllMemberRoles()
public async Task SyncAllMemberRoles(bool dryRun = true)
{
if (_trickFireGuild is null)
{
Expand All @@ -59,17 +60,23 @@ Task<PaginatedList<Page>> nextPageQuery(string? cursor) =>
await foreach (Page page in PaginatedListHelper.GetEnumerable(nextPageQuery))
{
await Task.Delay(333);
processedMembers.Add(await SyncRoles(page));
processedMembers.Add(await SyncRoles(page, dryRun));
Logger.LogInformation("\n");
}

Logger.LogInformation("\nNo notion page users:");
DiscordRole inactiveRole = _discordRoleCache.Values.First(role => role.Id == Config.Instance.InactiveRoleId);
await foreach (DiscordMember member in _trickFireGuild.GetAllMembersAsync())
{
if (processedMembers.Contains(member))
{
continue;
}
if (!dryRun && !member.Roles.Contains(inactiveRole))
{
await member.GrantRoleAsync(inactiveRole);
await Task.Delay(333);
}
Logger.LogInformation("{}, ({})", member.DisplayName, member.Username);
}
}
Expand All @@ -95,7 +102,7 @@ private void OnWebhook(HttpListenerRequest request)
Console.WriteLine(JsonConvert.SerializeObject(page, Formatting.Indented));
}

private async Task<DiscordMember?> SyncRoles(Page notionPage)
private async Task<DiscordMember?> SyncRoles(Page notionPage, bool dryRun = true)
{
if (_trickFireGuild is null)
{
Expand All @@ -120,16 +127,21 @@ private void OnWebhook(HttpListenerRequest request)
Logger.LogInformation(role!.Name);
}

//int highestRole = _trickFireGuild.CurrentMember.Roles.Max(role => role.Position);
//await member.ModifyAsync(model =>
//{
// List<DiscordRole> rolesWithLeadership = [];
// foreach (DiscordRole role in member.Roles.Where(role => role.Position >= highestRole))
// {
// rolesWithLeadership.Add(role);
// }
// model.Roles = rolesWithLeadership;
//});
if (!dryRun)
{
DiscordMember botMember = await _trickFireGuild.GetMemberAsync(DiscordClient.CurrentUser.Id, true);
int highestRole = botMember.Roles.Max(role => role.Position);
await member.ModifyAsync(model =>
{
List<DiscordRole> rolesWithLeadership = [];
foreach (DiscordRole role in member.Roles.Where(role => role.Position >= highestRole))
{
rolesWithLeadership.Add(role);
}
model.Roles = rolesWithLeadership;
});
await Task.Delay(333);
}

return member;
}
Expand Down Expand Up @@ -167,6 +179,7 @@ private void OnWebhook(HttpListenerRequest request)
{
member = search[0];
}
await Task.Delay(333);
}
return member;
}
Expand Down

0 comments on commit 1dd90c0

Please sign in to comment.