Slowmode whitelists done, need testing

This commit is contained in:
Kwoth
2017-04-01 21:40:13 +02:00
parent 3a5aed213b
commit 2b65518649
11 changed files with 2020 additions and 48 deletions

View File

@@ -1,13 +1,17 @@
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using Microsoft.EntityFrameworkCore;
using NadekoBot.Attributes;
using NadekoBot.Extensions;
using NadekoBot.Services;
using NadekoBot.Services.Database;
using NadekoBot.Services.Database.Models;
using NLog;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -23,6 +27,9 @@ namespace NadekoBot.Modules.Administration
public class Ratelimiter
{
public HashSet<ulong> IgnoreUsers { get; set; } = new HashSet<ulong>();
public HashSet<ulong> IgnoreRoles { get; set; } = new HashSet<ulong>();
public class RatelimitedUser
{
public ulong UserId { get; set; }
@@ -38,10 +45,14 @@ namespace NadekoBot.Modules.Administration
public ConcurrentDictionary<ulong, RatelimitedUser> Users { get; set; } = new ConcurrentDictionary<ulong, RatelimitedUser>();
public bool CheckUserRatelimit(ulong id)
public bool CheckUserRatelimit(ulong id, SocketGuildUser optUser)
{
if (IgnoreUsers.Contains(id) ||
(optUser != null && optUser.RoleIds.Any(x => IgnoreRoles.Contains(x))))
return false;
var usr = Users.GetOrAdd(id, (key) => new RatelimitedUser() { UserId = id });
if (usr.MessageCount == MaxMessages)
if (usr.MessageCount >= MaxMessages)
{
return true;
}
@@ -67,8 +78,8 @@ namespace NadekoBot.Modules.Administration
{
try
{
var usrMsg = umsg as IUserMessage;
var channel = usrMsg?.Channel as ITextChannel;
var usrMsg = umsg as SocketUserMessage;
var channel = usrMsg?.Channel as SocketTextChannel;
if (channel == null || usrMsg.IsAuthor())
return;
@@ -76,7 +87,7 @@ namespace NadekoBot.Modules.Administration
if (!RatelimitingChannels.TryGetValue(channel.Id, out limiter))
return;
if (limiter.CheckUserRatelimit(usrMsg.Author.Id))
if (limiter.CheckUserRatelimit(usrMsg.Author.Id, usrMsg.Author as SocketGuildUser))
await usrMsg.DeleteAsync();
}
catch (Exception ex) { _log.Warn(ex); }
@@ -122,29 +133,76 @@ namespace NadekoBot.Modules.Administration
}
}
//[NadekoCommand, Usage, Description, Aliases]
//[RequireContext(ContextType.Guild)]
//[RequireUserPermission(GuildPermission.ManageMessages)]
//public async Task SlowmodeWhitelist(IUser user)
//{
// Ratelimiter throwaway;
// if (RatelimitingChannels.TryRemove(Context.Channel.Id, out throwaway))
// {
// throwaway.cancelSource.Cancel();
// await ReplyConfirmLocalized("slowmode_disabled").ConfigureAwait(false);
// }
//}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
[RequireUserPermission(GuildPermission.ManageMessages)]
[Priority(1)]
public async Task SlowmodeWhitelist(IUser user)
{
var siu = new SlowmodeIgnoredUser
{
UserId = user.Id
};
//[NadekoCommand, Usage, Description, Aliases]
//[RequireContext(ContextType.Guild)]
//[RequireUserPermission(GuildPermission.ManageMessages)]
//public async Task SlowmodeWhitelist(IRole role)
//{
// using (var uow = DbHandler.UnitOfWork())
// {
// uow.GuildConfigs.For(Context.Guild.Id, set => set.Include(x => x.SlowmodeWhitelists)).
// }
//}
HashSet<SlowmodeIgnoredUser> usrs;
bool removed;
using (var uow = DbHandler.UnitOfWork())
{
usrs = uow.GuildConfigs.For(Context.Guild.Id, set => set.Include(x => x.SlowmodeIgnoredUsers))
.SlowmodeIgnoredUsers;
if (!(removed = usrs.Remove(siu)))
usrs.Add(siu);
await uow.CompleteAsync().ConfigureAwait(false);
}
Ratelimiter rl;
if (RatelimitingChannels.TryGetValue(Context.Guild.Id, out rl))
{
rl.IgnoreUsers = new HashSet<ulong>(usrs.Select(x => x.UserId));
}
if(removed)
await ReplyConfirmLocalized("slowmodewl_user_stop", Format.Bold(user.ToString())).ConfigureAwait(false);
else
await ReplyConfirmLocalized("slowmodewl_user_start", Format.Bold(user.ToString())).ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
[RequireUserPermission(GuildPermission.ManageMessages)]
[Priority(0)]
public async Task SlowmodeWhitelist(IRole role)
{
var sir = new SlowmodeIgnoredRole
{
RoleId = role.Id
};
HashSet<SlowmodeIgnoredRole> roles;
bool removed;
using (var uow = DbHandler.UnitOfWork())
{
roles = uow.GuildConfigs.For(Context.Guild.Id, set => set.Include(x => x.SlowmodeIgnoredRoles))
.SlowmodeIgnoredRoles;
if (!(removed = roles.Remove(sir)))
roles.Add(sir);
await uow.CompleteAsync().ConfigureAwait(false);
}
Ratelimiter rl;
if (RatelimitingChannels.TryGetValue(Context.Guild.Id, out rl))
{
rl.IgnoreRoles = new HashSet<ulong>(roles.Select(x => x.RoleId));
}
if (removed)
await ReplyConfirmLocalized("slowmodewl_role_stop", Format.Bold(role.ToString())).ConfigureAwait(false);
else
await ReplyConfirmLocalized("slowmodewl_role_start", Format.Bold(role.ToString())).ConfigureAwait(false);
}
}
}
}

View File

@@ -9,6 +9,9 @@
//using System.Threading;
//using System;
//using System.Collections.Immutable;
//using NadekoBot.Services;
//using NadekoBot.Services.Database.Models;
//using NadekoBot.Extensions;
//namespace NadekoBot.Modules.Utility
//{
@@ -17,20 +20,45 @@
// [Group]
// public class PatreonCommands : NadekoSubmodule
// {
// private static readonly PatreonThingy patreon;
// static PatreonCommands()
// {
// patreon = PatreonThingy.Instance;
// }
// [NadekoCommand, Usage, Description, Aliases]
// public async Task ClaimPatreonRewards()
// {
// var patreon = PatreonThingy.Instance;
// var pledges = (await patreon.GetPledges().ConfigureAwait(false))
// .OrderByDescending(x => x.Reward.attributes.amount_cents);
// if (pledges == null)
// if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.PatreonAccessToken))
// return;
// if (DateTime.UtcNow.Day < 5)
// {
// await ReplyErrorLocalized("pledges_loading").ConfigureAwait(false);
// await ReplyErrorLocalized("claimpatreon_too_early").ConfigureAwait(false);
// }
// int amount = 0;
// try
// {
// amount = await patreon.ClaimReward(Context.User.Id).ConfigureAwait(false);
// }
// catch (Exception ex)
// {
// _log.Warn(ex);
// }
// if (amount > 0)
// {
// await ReplyConfirmLocalized("claimpatreon_success", amount).ConfigureAwait(false);
// return;
// }
// await Context.Channel.EmbedAsync(new Discord.EmbedBuilder().WithOkColor()
// .WithDescription(GetText("claimpatreon_fail"))
// .AddField(efb => efb.WithName("").WithValue(""))
// .AddField(efb => efb.WithName("").WithValue(""))
// .AddField(efb => efb.WithName("").WithValue("")))
// .ConfigureAwait(false);
// await ReplyErrorLocalized("claimpatreon_fail").ConfigureAwait(false);
// }
// }
@@ -41,21 +69,16 @@
// private readonly SemaphoreSlim getPledgesLocker = new SemaphoreSlim(1, 1);
// private ImmutableArray<PatreonUserAndReward> pledges;
// public ImmutableArray<PatreonUserAndReward> Pledges { get; private set; }
// static PatreonThingy() { }
// private readonly Timer update;
// private readonly SemaphoreSlim claimLockJustInCase = new SemaphoreSlim(1, 1);
// public async Task<ImmutableArray<PatreonUserAndReward>> GetPledges()
// private PatreonThingy()
// {
// try
// {
// await LoadPledges().ConfigureAwait(false);
// return pledges;
// }
// catch (OperationCanceledException)
// {
// return pledges;
// }
// if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.PatreonAccessToken))
// return;
// update = new Timer(async (_) => await LoadPledges(), null, TimeSpan.Zero, TimeSpan.FromHours(3));
// }
// public async Task LoadPledges()
@@ -89,7 +112,7 @@
// .Select(x => JsonConvert.DeserializeObject<PatreonUser>(x.ToString())));
// } while (!string.IsNullOrWhiteSpace(data.Links.next));
// }
// pledges = rewards.Join(users, (r) => r.relationships?.patron?.data?.id, (u) => u.id, (x, y) => new PatreonUserAndReward()
// Pledges = rewards.Join(users, (r) => r.relationships?.patron?.data?.id, (u) => u.id, (x, y) => new PatreonUserAndReward()
// {
// User = y,
// Reward = x,
@@ -102,7 +125,55 @@
// await Task.Delay(TimeSpan.FromMinutes(5)).ConfigureAwait(false);
// getPledgesLocker.Release();
// });
// }
// }
// public async Task<int> ClaimReward(ulong userId)
// {
// await claimLockJustInCase.WaitAsync();
// try
// {
// var data = Pledges.FirstOrDefault(x => x.User.id == userId.ToString());
// if (data == null)
// return 0;
// var amount = data.Reward.attributes.amount_cents;
// using (var uow = DbHandler.UnitOfWork())
// {
// var users = uow._context.Set<RewardedUser>();
// var usr = users.FirstOrDefault(x => x.UserId == userId);
// if (usr == null)
// {
// users.Add(new RewardedUser()
// {
// UserId = userId,
// LastReward = DateTime.UtcNow,
// AmountRewardedThisMonth = amount,
// });
// await uow.CompleteAsync().ConfigureAwait(false);
// return amount;
// }
// if (usr.AmountRewardedThisMonth < amount)
// {
// var toAward = amount - usr.AmountRewardedThisMonth;
// usr.LastReward = DateTime.UtcNow;
// usr.AmountRewardedThisMonth = amount;
// await uow.CompleteAsync().ConfigureAwait(false);
// return toAward;
// }
// }
// return 0;
// }
// finally
// {
// claimLockJustInCase.Release();
// }
// }
// }