using System.Text;
namespace RegexBot.Modules.EntryRole;
///
/// Automatically sets a role onto users entering the guild after a predefined amount of time.
///
[RegexbotModule]
internal sealed class EntryRole : RegexbotModule, IDisposable {
readonly Task _workerTask;
readonly CancellationTokenSource _workerTaskToken;
public EntryRole(RegexbotClient bot) : base(bot) {
DiscordClient.GuildMembersDownloaded += DiscordClient_GuildMembersDownloaded;
DiscordClient.UserJoined += DiscordClient_UserJoined;
DiscordClient.UserLeft += DiscordClient_UserLeft;
_workerTaskToken = new CancellationTokenSource();
_workerTask = Task.Factory.StartNew(RoleApplyWorker, _workerTaskToken.Token,
TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
void IDisposable.Dispose() {
_workerTaskToken.Cancel();
_workerTask.Wait(2000);
_workerTask.Dispose();
}
private Task DiscordClient_GuildMembersDownloaded(SocketGuild arg) {
var data = GetGuildState(arg.Id);
if (data == null) return Task.CompletedTask;
var rolecheck = data.TargetRole.FindRoleIn(arg);
if (rolecheck == null) {
Log(arg, "Unable to find target role to be applied. Initial check has been skipped.");
return Task.CompletedTask;
}
foreach (var user in arg.Users.Where(u => !u.Roles.Contains(rolecheck))) {
data.WaitlistAdd(user.Id);
}
return Task.CompletedTask;
}
private Task DiscordClient_UserJoined(SocketGuildUser arg) {
GetGuildState(arg.Guild.Id)?.WaitlistAdd(arg.Id);
return Task.CompletedTask;
}
private Task DiscordClient_UserLeft(SocketGuild guild, SocketUser user) {
GetGuildState(guild.Id)?.WaitlistRemove(user.Id);
return Task.CompletedTask;
}
public override Task