This commit is contained in:
Kwoth 2016-12-28 07:56:44 +01:00
parent 3a68a8b4f6
commit aa49c5608b
10 changed files with 172 additions and 154 deletions

View File

@ -81,39 +81,35 @@ namespace NadekoBot.Modules.Administration
{
_log = LogManager.GetCurrentClassLogger();
NadekoBot.Client.MessageReceived += (imsg) =>
NadekoBot.Client.MessageReceived += async (imsg) =>
{
var msg = imsg as IUserMessage;
if (msg == null || msg.Author.IsBot)
return;
var channel = msg.Channel as ITextChannel;
if (channel == null)
return;
var t = Task.Run(async () =>
try
{
try
var msg = imsg as IUserMessage;
if (msg == null || msg.Author.IsBot)
return;
var channel = msg.Channel as ITextChannel;
if (channel == null)
return;
AntiSpamSetting spamSettings;
if (!antiSpamGuilds.TryGetValue(channel.Guild.Id, out spamSettings))
return;
var stats = spamSettings.UserStats.AddOrUpdate(msg.Author.Id, new UserSpamStats(msg.Content),
(id, old) => { old.ApplyNextMessage(msg.Content); return old; });
if (stats.Count >= spamSettings.MessageThreshold)
{
AntiSpamSetting spamSettings;
if (!antiSpamGuilds.TryGetValue(channel.Guild.Id, out spamSettings))
return;
var stats = spamSettings.UserStats.AddOrUpdate(msg.Author.Id, new UserSpamStats(msg.Content),
(id, old) => { old.ApplyNextMessage(msg.Content); return old; });
if (stats.Count >= spamSettings.MessageThreshold)
if (spamSettings.UserStats.TryRemove(msg.Author.Id, out stats))
{
if (spamSettings.UserStats.TryRemove(msg.Author.Id, out stats))
{
await PunishUsers(spamSettings.Action, ProtectionType.Spamming, (IGuildUser)msg.Author)
.ConfigureAwait(false);
}
await PunishUsers(spamSettings.Action, ProtectionType.Spamming, (IGuildUser)msg.Author)
.ConfigureAwait(false);
}
}
catch { }
});
return;
}
catch { }
};
NadekoBot.Client.UserJoined += async (usr) =>
@ -239,7 +235,7 @@ namespace NadekoBot.Modules.Administration
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
[RequirePermission(GuildPermission.Administrator)]
public async Task AntiSpam(IUserMessage imsg, int messageCount=3, PunishmentAction action = PunishmentAction.Mute)
public async Task AntiSpam(IUserMessage imsg, int messageCount = 3, PunishmentAction action = PunishmentAction.Mute)
{
var channel = (ITextChannel)imsg.Channel;
@ -271,7 +267,7 @@ namespace NadekoBot.Modules.Administration
Action = action,
MessageThreshold = messageCount,
}))
await channel.SendConfirmAsync("✅ **Anti-Spam feature** has been **enabled** on this server.").ConfigureAwait(false);
await channel.SendConfirmAsync("✅ **Anti-Spam feature** has been **enabled** on this server.").ConfigureAwait(false);
}
}

View File

@ -45,7 +45,8 @@ namespace NadekoBot.Modules.Administration
else
{
usr.MessageCount++;
var t = Task.Run(async () => {
var t = Task.Run(async () =>
{
try
{
await Task.Delay(PerSeconds * 1000, cancelSource.Token);
@ -61,26 +62,26 @@ namespace NadekoBot.Modules.Administration
static RatelimitCommand()
{
_log = LogManager.GetCurrentClassLogger();
_log = LogManager.GetCurrentClassLogger();
NadekoBot.Client.MessageReceived += (umsg) =>
{
var t = Task.Run(async () =>
{
var usrMsg = umsg as IUserMessage;
var channel = usrMsg.Channel as ITextChannel;
NadekoBot.Client.MessageReceived += async (umsg) =>
{
try
{
var usrMsg = umsg as IUserMessage;
var channel = usrMsg.Channel as ITextChannel;
if (channel == null || usrMsg.IsAuthor())
return;
Ratelimiter limiter;
if (!RatelimitingChannels.TryGetValue(channel.Id, out limiter))
return;
if (channel == null || usrMsg.IsAuthor())
return;
Ratelimiter limiter;
if (!RatelimitingChannels.TryGetValue(channel.Id, out limiter))
return;
if (limiter.CheckUserRatelimit(usrMsg.Author.Id))
try { await usrMsg.DeleteAsync(); } catch (Exception ex) { _log.Warn(ex); }
});
return;
};
if (limiter.CheckUserRatelimit(usrMsg.Author.Id))
await usrMsg.DeleteAsync();
}
catch (Exception ex) { _log.Warn(ex); }
};
}
[NadekoCommand, Usage, Description, Aliases]
@ -118,7 +119,7 @@ namespace NadekoBot.Modules.Administration
MaxMessages = msg,
PerSeconds = perSec,
};
if(RatelimitingChannels.TryAdd(channel.Id, toAdd))
if (RatelimitingChannels.TryAdd(channel.Id, toAdd))
{
await channel.SendConfirmAsync("Slow mode initiated",
$"Users can't send more than `{toAdd.MaxMessages} message(s)` every `{toAdd.PerSeconds} second(s)`.")

View File

@ -3,6 +3,7 @@ using Discord.Commands;
using NadekoBot.Attributes;
using NadekoBot.Extensions;
using NadekoBot.Services;
using NLog;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
@ -73,9 +74,12 @@ namespace NadekoBot.Modules.Games
//text, votes
private readonly ConcurrentDictionary<string, int> votes = new ConcurrentDictionary<string, int>();
private readonly Logger _log;
public AcrophobiaGame(ITextChannel channel, int time)
{
this._log = LogManager.GetCurrentClassLogger();
this.channel = channel;
this.time = time;
this.source = new CancellationTokenSource();
@ -253,7 +257,10 @@ namespace NadekoBot.Modules.Games
}
}
catch { }
catch (Exception ex)
{
_log.Warn(ex);
}
}
public async Task End()

View File

@ -2,6 +2,7 @@
using NadekoBot.Extensions;
using NadekoBot.Services;
using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.IO;
@ -70,6 +71,8 @@ namespace NadekoBot.Modules.Games.Commands.Hangman
public class HangmanGame
{
private readonly Logger _log;
public IMessageChannel GameChannel { get; }
public HashSet<char> Guesses { get; } = new HashSet<char>();
public HangmanObject Term { get; private set; }
@ -97,6 +100,7 @@ namespace NadekoBot.Modules.Games.Commands.Hangman
public HangmanGame(IMessageChannel channel, HangmanTermPool.HangmanTermType type)
{
_log = LogManager.GetCurrentClassLogger();
this.GameChannel = channel;
this.TermType = type;
}
@ -126,29 +130,32 @@ namespace NadekoBot.Modules.Games.Commands.Hangman
private async void PotentialGuess(IMessage msg)
{
if (msg.Channel != GameChannel)
return; // message's channel has to be the same as game's
if (msg.Content.Length != 1) // message must be 1 char long
{
if (++MessagesSinceLastPost > 10)
{
MessagesSinceLastPost = 0;
try
{
await GameChannel.SendConfirmAsync("Hangman Game",
ScrambledWord + "\n" + GetHangman(),
footer: string.Join(" ", Guesses)).ConfigureAwait(false);
}
catch { }
}
}
if (!(char.IsLetter(msg.Content[0]) || char.IsDigit(msg.Content[0])))// and a letter or a digit
return;
var guess = char.ToUpperInvariant(msg.Content[0]);
try
{
if (!(msg is IUserMessage))
return;
if (msg.Channel != GameChannel)
return; // message's channel has to be the same as game's
if (msg.Content.Length != 1) // message must be 1 char long
{
if (++MessagesSinceLastPost > 10)
{
MessagesSinceLastPost = 0;
try
{
await GameChannel.SendConfirmAsync("Hangman Game",
ScrambledWord + "\n" + GetHangman(),
footer: string.Join(" ", Guesses)).ConfigureAwait(false);
}
catch { }
}
}
if (!(char.IsLetter(msg.Content[0]) || char.IsDigit(msg.Content[0])))// and a letter or a digit
return;
var guess = char.ToUpperInvariant(msg.Content[0]);
if (Guesses.Contains(guess))
{
MessagesSinceLastPost = 0;
@ -193,7 +200,7 @@ namespace NadekoBot.Modules.Games.Commands.Hangman
}
}
catch { }
catch (Exception ex) { _log.Warn(ex); }
}
public string GetHangman() => $@"\_\_\_\_\_\_\_\_\_

View File

@ -51,7 +51,7 @@ namespace NadekoBot.Modules.Games
var conf = uow.BotConfig.GetOrCreate();
var x =
generationChannels = new ConcurrentHashSet<ulong>(NadekoBot.AllGuildConfigs
.SelectMany(c => c.GenerateCurrencyChannelIds.Select(obj=>obj.ChannelId)));
.SelectMany(c => c.GenerateCurrencyChannelIds.Select(obj => obj.ChannelId)));
chance = conf.CurrencyGenerationChance;
cooldown = conf.CurrencyGenerationCooldown;
}
@ -59,39 +59,41 @@ namespace NadekoBot.Modules.Games
private static async void PotentialFlowerGeneration(IMessage imsg)
{
var msg = imsg as IUserMessage;
if (msg == null || msg.IsAuthor() || msg.Author.IsBot)
return;
var channel = imsg.Channel as ITextChannel;
if (channel == null)
return;
if (!generationChannels.Contains(channel.Id))
return;
var lastGeneration = lastGenerations.GetOrAdd(channel.Id, DateTime.MinValue);
var rng = new NadekoRandom();
if (DateTime.Now - TimeSpan.FromSeconds(cooldown) < lastGeneration) //recently generated in this channel, don't generate again
return;
var num = rng.Next(1, 101) + chance * 100;
if (num > 100)
try
{
lastGenerations.AddOrUpdate(channel.Id, DateTime.Now, (id, old) => DateTime.Now);
try
var msg = imsg as IUserMessage;
if (msg == null || msg.IsAuthor() || msg.Author.IsBot)
return;
var channel = imsg.Channel as ITextChannel;
if (channel == null)
return;
if (!generationChannels.Contains(channel.Id))
return;
var lastGeneration = lastGenerations.GetOrAdd(channel.Id, DateTime.MinValue);
var rng = new NadekoRandom();
if (DateTime.Now - TimeSpan.FromSeconds(cooldown) < lastGeneration) //recently generated in this channel, don't generate again
return;
var num = rng.Next(1, 101) + chance * 100;
if (num > 100)
{
lastGenerations.AddOrUpdate(channel.Id, DateTime.Now, (id, old) => DateTime.Now);
var sent = await channel.SendFileAsync(
GetRandomCurrencyImagePath(),
$"❗ A random { Gambling.Gambling.CurrencyName } appeared! Pick it up by typing `{NadekoBot.ModulePrefixes[typeof(Games).Name]}pick`")
.ConfigureAwait(false);
plantedFlowers.AddOrUpdate(channel.Id, new List<IUserMessage>() { sent }, (id, old) => { old.Add(sent); return old; });
}
catch { }
}
}
catch { }
}
[NadekoCommand, Usage, Description, Aliases]

View File

@ -126,19 +126,20 @@ namespace NadekoBot.Modules.Games
private async void Vote(IMessage imsg)
{
// has to be a user message
var msg = imsg as IUserMessage;
if (msg == null || msg.Author.IsBot)
return;
// has to be an integer
int vote;
if (!int.TryParse(imsg.Content, out vote))
return;
if (vote < 1 || vote > answers.Length)
return;
try
{
// has to be a user message
var msg = imsg as IUserMessage;
if (msg == null || msg.Author.IsBot)
return;
// has to be an integer
int vote;
if (!int.TryParse(imsg.Content, out vote))
return;
if (vote < 1 || vote > answers.Length)
return;
IMessageChannel ch;
if (isPublic)
{

View File

@ -107,13 +107,14 @@ namespace NadekoBot.Modules.Games
private async void AnswerReceived(IMessage imsg)
{
if (imsg.Author.IsBot)
return;
var msg = imsg as IUserMessage;
if (msg == null)
return;
try
{
if (imsg.Author.IsBot)
return;
var msg = imsg as IUserMessage;
if (msg == null)
return;
if (this.Channel == null || this.Channel.Id != this.Channel.Id) return;
var guess = msg.Content;

View File

@ -144,14 +144,15 @@ namespace NadekoBot.Modules.Games.Trivia
private async void PotentialGuess(IMessage imsg)
{
if (imsg.Author.IsBot)
return;
var umsg = imsg as IUserMessage;
if (umsg == null)
return;
try
{
if (imsg.Author.IsBot)
return;
var umsg = imsg as IUserMessage;
if (umsg == null)
return;
var textChannel = umsg.Channel as ITextChannel;
if (textChannel == null || textChannel.Guild != guild)
return;

View File

@ -30,32 +30,32 @@ namespace NadekoBot.Modules.Searches
NadekoBot.Client.MessageReceived += async (msg) =>
{
var umsg = msg as IUserMessage;
if (umsg == null)
return;
bool autoDelete;
if (!TranslatedChannels.TryGetValue(umsg.Channel.Id, out autoDelete))
return;
var key = new UserChannelPair()
{
UserId = umsg.Author.Id,
ChannelId = umsg.Channel.Id,
};
string langs;
if (!UserLanguages.TryGetValue(key, out langs))
return;
try
{
var umsg = msg as IUserMessage;
if (umsg == null)
return;
bool autoDelete;
if (!TranslatedChannels.TryGetValue(umsg.Channel.Id, out autoDelete))
return;
var key = new UserChannelPair()
{
UserId = umsg.Author.Id,
ChannelId = umsg.Channel.Id,
};
string langs;
if (!UserLanguages.TryGetValue(key, out langs))
return;
var text = await TranslateInternal(umsg, langs, umsg.Resolve(UserMentionHandling.Ignore), true)
.ConfigureAwait(false);
if (autoDelete)
try { await umsg.DeleteAsync().ConfigureAwait(false); } catch { }
await umsg.Channel.SendConfirmAsync($"{umsg.Author.Mention} `:` " + text.Replace("<@ ", "<@").Replace("<@! ", "<@!")).ConfigureAwait(false);
}
catch { }
catch { }
};
}

View File

@ -64,20 +64,21 @@ namespace NadekoBot.Services
private async void MessageReceivedHandler(IMessage msg)
{
var usrMsg = msg as IUserMessage;
if (usrMsg == null)
return;
if (!usrMsg.IsAuthor())
UserMessagesSent.AddOrUpdate(usrMsg.Author.Id, 1, (key, old) => ++old);
if (usrMsg.Author.IsBot || !NadekoBot.Ready) //no bots
return;
var sw = new Stopwatch();
sw.Start();
try
{
var usrMsg = msg as IUserMessage;
if (usrMsg == null)
return;
if (!usrMsg.IsAuthor())
UserMessagesSent.AddOrUpdate(usrMsg.Author.Id, 1, (key, old) => ++old);
if (usrMsg.Author.IsBot || !NadekoBot.Ready) //no bots
return;
var sw = new Stopwatch();
sw.Start();
var guild = (msg.Channel as ITextChannel)?.Guild;
if (guild != null && guild.OwnerId != usrMsg.Author.Id)
@ -208,7 +209,8 @@ namespace NadekoBot.Services
}
}
public async Task<Tuple<Command, PermissionCache, IResult>> ExecuteCommand(IUserMessage message, string input, IGuild guild, IUser user, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Best) {
public async Task<Tuple<Command, PermissionCache, IResult>> ExecuteCommand(IUserMessage message, string input, IGuild guild, IUser user, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Best)
{
var searchResult = _commandService.Search(message, input);
if (!searchResult.IsSuccess)
return new Tuple<Command, PermissionCache, IResult>(null, null, searchResult);