NadekoBot/NadekoBot.Core/Modules/Administration/Services/RatelimitService.cs

68 lines
2.5 KiB
C#
Raw Normal View History

2017-07-17 19:42:36 +00:00
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
2017-07-17 19:42:36 +00:00
using Discord;
using Discord.WebSocket;
using NadekoBot.Common.ModuleBehaviors;
using NadekoBot.Extensions;
using NadekoBot.Modules.Administration.Common;
using NadekoBot.Services;
using NadekoBot.Services.Database.Models;
using NLog;
2017-07-17 19:42:36 +00:00
namespace NadekoBot.Modules.Administration.Services
{
public class SlowmodeService : IEarlyBlocker, INService
{
public ConcurrentDictionary<ulong, Ratelimiter> RatelimitingChannels = new ConcurrentDictionary<ulong, Ratelimiter>();
public ConcurrentDictionary<ulong, HashSet<ulong>> IgnoredRoles = new ConcurrentDictionary<ulong, HashSet<ulong>>();
public ConcurrentDictionary<ulong, HashSet<ulong>> IgnoredUsers = new ConcurrentDictionary<ulong, HashSet<ulong>>();
private readonly Logger _log;
private readonly DiscordSocketClient _client;
public SlowmodeService(DiscordSocketClient client, NadekoBot bot)
{
_log = LogManager.GetCurrentClassLogger();
2017-05-30 00:05:11 +00:00
_client = client;
IgnoredRoles = new ConcurrentDictionary<ulong, HashSet<ulong>>(
bot.AllGuildConfigs.ToDictionary(x => x.GuildId,
x => new HashSet<ulong>(x.SlowmodeIgnoredRoles.Select(y => y.RoleId))));
IgnoredUsers = new ConcurrentDictionary<ulong, HashSet<ulong>>(
bot.AllGuildConfigs.ToDictionary(x => x.GuildId,
x => new HashSet<ulong>(x.SlowmodeIgnoredUsers.Select(y => y.UserId))));
}
2017-05-30 00:05:11 +00:00
public async Task<bool> TryBlockEarly(IGuild guild, IUserMessage usrMsg)
{
if (guild == null)
return false;
try
{
var channel = usrMsg?.Channel as SocketTextChannel;
2017-05-30 00:05:11 +00:00
if (channel == null || usrMsg == null || usrMsg.IsAuthor(_client))
return false;
if (!RatelimitingChannels.TryGetValue(channel.Id, out Ratelimiter limiter))
return false;
if (limiter.CheckUserRatelimit(usrMsg.Author.Id, channel.Guild.Id, usrMsg.Author as SocketGuildUser))
{
await usrMsg.DeleteAsync();
return true;
}
}
catch (Exception ex)
{
_log.Warn(ex);
}
return false;
}
}
}