This commit is contained in:
Master Kwoth 2016-04-14 23:20:47 +02:00
parent eeaf4c4920
commit fe67591081
3 changed files with 83 additions and 49 deletions

View File

@ -1,29 +1,31 @@
using System; using Discord;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Discord;
using Discord.Commands; using Discord.Commands;
using NadekoBot.Classes; using NadekoBot.Classes;
using NadekoBot.Classes.Permissions; using NadekoBot.Classes.Permissions;
using NadekoBot.Modules; using NadekoBot.Modules;
using System;
using System.Text.RegularExpressions;
using ServerPermissions = NadekoBot.Classes.Permissions.ServerPermissions; using ServerPermissions = NadekoBot.Classes.Permissions.ServerPermissions;
namespace NadekoBot.Commands { namespace NadekoBot.Commands
internal class FilterInvitesCommand : DiscordCommand { {
internal class FilterInvitesCommand : DiscordCommand
{
private readonly Regex filterRegex = new Regex(@"(?:discord(?:\.gg|app\.com\/invite)\/(?<id>([\w]{16}|(?:[\w]+-?){3})))"); private readonly Regex filterRegex = new Regex(@"(?:discord(?:\.gg|app\.com\/invite)\/(?<id>([\w]{16}|(?:[\w]+-?){3})))");
public FilterInvitesCommand(DiscordModule module) : base(module) { public FilterInvitesCommand(DiscordModule module) : base(module)
NadekoBot.Client.MessageReceived += async (sender, args) => { {
NadekoBot.Client.MessageReceived += async (sender, args) =>
{
if (args.Channel.IsPrivate || args.User.Id == NadekoBot.Client.CurrentUser.Id) return; if (args.Channel.IsPrivate || args.User.Id == NadekoBot.Client.CurrentUser.Id) return;
try { try
{
ServerPermissions serverPerms; ServerPermissions serverPerms;
if (!IsChannelOrServerFiltering(args.Channel, out serverPerms)) return; if (!IsChannelOrServerFiltering(args.Channel, out serverPerms)) return;
if (filterRegex.IsMatch(args.Message.RawText)) { if (filterRegex.IsMatch(args.Message.RawText))
{
await args.Message.Delete(); await args.Message.Delete();
IncidentsHandler.Add(args.Server.Id, $"User [{args.User.Name}/{args.User.Id}] posted " + IncidentsHandler.Add(args.Server.Id, $"User [{args.User.Name}/{args.User.Id}] posted " +
$"INVITE LINK in [{args.Channel.Name}/{args.Channel.Id}] channel. " + $"INVITE LINK in [{args.Channel.Name}/{args.Channel.Id}] channel. " +
@ -32,11 +34,13 @@ namespace NadekoBot.Commands {
await args.Channel.SendMessage($"{args.User.Mention} Invite links are not " + await args.Channel.SendMessage($"{args.User.Mention} Invite links are not " +
$"allowed on this channel."); $"allowed on this channel.");
} }
} catch { } }
catch { }
}; };
} }
private static bool IsChannelOrServerFiltering(Channel channel, out ServerPermissions serverPerms) { private static bool IsChannelOrServerFiltering(Channel channel, out ServerPermissions serverPerms)
{
if (!PermissionsHandler.PermissionsDict.TryGetValue(channel.Server.Id, out serverPerms)) return false; if (!PermissionsHandler.PermissionsDict.TryGetValue(channel.Server.Id, out serverPerms)) return false;
if (serverPerms.Permissions.FilterInvites) if (serverPerms.Permissions.FilterInvites)
@ -46,7 +50,8 @@ namespace NadekoBot.Commands {
return serverPerms.ChannelPermissions.TryGetValue(channel.Id, out perms) && perms.FilterInvites; return serverPerms.ChannelPermissions.TryGetValue(channel.Id, out perms) && perms.FilterInvites;
} }
internal override void Init(CommandGroupBuilder cgb) { internal override void Init(CommandGroupBuilder cgb)
{
cgb.CreateCommand(Module.Prefix + "cfi") cgb.CreateCommand(Module.Prefix + "cfi")
.Alias(Module.Prefix + "channelfilterinvites") .Alias(Module.Prefix + "channelfilterinvites")
.Description("Enables or disables automatic deleting of invites on the channel." + .Description("Enables or disables automatic deleting of invites on the channel." +
@ -54,12 +59,15 @@ namespace NadekoBot.Commands {
"\n**Usage**: ;cfi enable #general-chat") "\n**Usage**: ;cfi enable #general-chat")
.Parameter("bool") .Parameter("bool")
.Parameter("channel", ParameterType.Optional) .Parameter("channel", ParameterType.Optional)
.Do(async e => { .Do(async e =>
try { {
try
{
var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
var chanStr = e.GetArg("channel"); var chanStr = e.GetArg("channel");
if (chanStr?.ToLowerInvariant().Trim() != "all") { if (chanStr?.ToLowerInvariant().Trim() != "all")
{
var chan = string.IsNullOrWhiteSpace(chanStr) var chan = string.IsNullOrWhiteSpace(chanStr)
? e.Channel ? e.Channel
@ -70,12 +78,15 @@ namespace NadekoBot.Commands {
} }
//all channels //all channels
foreach (var curChannel in e.Server.TextChannels) { foreach (var curChannel in e.Server.TextChannels)
{
PermissionsHandler.SetChannelFilterInvitesPermission(curChannel, state); PermissionsHandler.SetChannelFilterInvitesPermission(curChannel, state);
} }
await e.Channel.SendMessage($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for **ALL** channels."); await e.Channel.SendMessage($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for **ALL** channels.");
} catch (Exception ex) { }
catch (Exception ex)
{
await e.Channel.SendMessage($"💢 Error: {ex.Message}"); await e.Channel.SendMessage($"💢 Error: {ex.Message}");
} }
}); });
@ -84,13 +95,17 @@ namespace NadekoBot.Commands {
.Alias(Module.Prefix + "serverfilterinvites") .Alias(Module.Prefix + "serverfilterinvites")
.Description("Enables or disables automatic deleting of invites on the server.\n**Usage**: ;sfi disable") .Description("Enables or disables automatic deleting of invites on the server.\n**Usage**: ;sfi disable")
.Parameter("bool") .Parameter("bool")
.Do(async e => { .Do(async e =>
try { {
try
{
var state = PermissionHelper.ValidateBool(e.GetArg("bool")); var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
PermissionsHandler.SetServerFilterInvitesPermission(e.Server, state); PermissionsHandler.SetServerFilterInvitesPermission(e.Server, state);
await e.Channel.SendMessage($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for this server."); await e.Channel.SendMessage($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for this server.");
} catch (Exception ex) { }
catch (Exception ex)
{
await e.Channel.SendMessage($"💢 Error: {ex.Message}"); await e.Channel.SendMessage($"💢 Error: {ex.Message}");
} }
}); });

View File

@ -1,28 +1,34 @@
using System; using Discord;
using Discord.Commands;
using NadekoBot.Modules;
using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using NadekoBot.Modules;
namespace NadekoBot.Commands { namespace NadekoBot.Commands
internal class PollCommand : DiscordCommand { {
internal class PollCommand : DiscordCommand
{
public static ConcurrentDictionary<Server, Poll> ActivePolls = new ConcurrentDictionary<Server, Poll>(); public static ConcurrentDictionary<Server, Poll> ActivePolls = new ConcurrentDictionary<Server, Poll>();
public Func<CommandEventArgs, Task> DoFunc() { public Func<CommandEventArgs, Task> DoFunc()
{
throw new NotImplementedException(); throw new NotImplementedException();
} }
internal override void Init(CommandGroupBuilder cgb) { internal override void Init(CommandGroupBuilder cgb)
{
cgb.CreateCommand(Module.Prefix + "poll") cgb.CreateCommand(Module.Prefix + "poll")
.Description("Creates a poll, only person who has manage server permission can do it.\n**Usage**: >poll Question?;Answer1;Answ 2;A_3") .Description("Creates a poll, only person who has manage server permission can do it.\n**Usage**: >poll Question?;Answer1;Answ 2;A_3")
.Parameter("allargs", ParameterType.Unparsed) .Parameter("allargs", ParameterType.Unparsed)
.Do(async e => { .Do(async e =>
await Task.Run(async () => { {
await Task.Run(async () =>
{
if (!e.User.ServerPermissions.ManageChannels) if (!e.User.ServerPermissions.ManageChannels)
return; return;
if (ActivePolls.ContainsKey(e.Server)) if (ActivePolls.ContainsKey(e.Server))
@ -35,14 +41,16 @@ namespace NadekoBot.Commands {
return; return;
var poll = new Poll(e, data[0], data.Skip(1)); var poll = new Poll(e, data[0], data.Skip(1));
if (PollCommand.ActivePolls.TryAdd(e.Server, poll)) { if (PollCommand.ActivePolls.TryAdd(e.Server, poll))
{
await poll.StartPoll(); await poll.StartPoll();
} }
}); });
}); });
cgb.CreateCommand(Module.Prefix + "pollend") cgb.CreateCommand(Module.Prefix + "pollend")
.Description("Stops active poll on this server and prints the results in this channel.") .Description("Stops active poll on this server and prints the results in this channel.")
.Do(async e => { .Do(async e =>
{
if (!e.User.ServerPermissions.ManageChannels) if (!e.User.ServerPermissions.ManageChannels)
return; return;
if (!ActivePolls.ContainsKey(e.Server)) if (!ActivePolls.ContainsKey(e.Server))
@ -51,10 +59,11 @@ namespace NadekoBot.Commands {
}); });
} }
public PollCommand(DiscordModule module) : base(module) {} public PollCommand(DiscordModule module) : base(module) { }
} }
internal class Poll { internal class Poll
{
private readonly CommandEventArgs e; private readonly CommandEventArgs e;
private readonly string[] answers; private readonly string[] answers;
private ConcurrentDictionary<User, int> participants = new ConcurrentDictionary<User, int>(); private ConcurrentDictionary<User, int> participants = new ConcurrentDictionary<User, int>();
@ -62,13 +71,15 @@ namespace NadekoBot.Commands {
private DateTime started; private DateTime started;
private CancellationTokenSource pollCancellationSource = new CancellationTokenSource(); private CancellationTokenSource pollCancellationSource = new CancellationTokenSource();
public Poll(CommandEventArgs e, string question, IEnumerable<string> enumerable) { public Poll(CommandEventArgs e, string question, IEnumerable<string> enumerable)
{
this.e = e; this.e = e;
this.question = question; this.question = question;
this.answers = enumerable as string[] ?? enumerable.ToArray(); this.answers = enumerable as string[] ?? enumerable.ToArray();
} }
public async Task StartPoll() { public async Task StartPoll()
{
started = DateTime.Now; started = DateTime.Now;
NadekoBot.Client.MessageReceived += Vote; NadekoBot.Client.MessageReceived += Vote;
var msgToSend = var msgToSend =
@ -80,17 +91,20 @@ namespace NadekoBot.Commands {
await e.Channel.SendMessage(msgToSend); await e.Channel.SendMessage(msgToSend);
} }
public async Task StopPoll(Channel ch) { public async Task StopPoll(Channel ch)
{
NadekoBot.Client.MessageReceived -= Vote; NadekoBot.Client.MessageReceived -= Vote;
Poll throwaway; Poll throwaway;
PollCommand.ActivePolls.TryRemove(e.Server, out throwaway); PollCommand.ActivePolls.TryRemove(e.Server, out throwaway);
try { try
{
var results = participants.GroupBy(kvp => kvp.Value) var results = participants.GroupBy(kvp => kvp.Value)
.ToDictionary(x => x.Key, x => x.Sum(kvp => 1)) .ToDictionary(x => x.Key, x => x.Sum(kvp => 1))
.OrderBy(kvp => kvp.Value); .OrderBy(kvp => kvp.Value);
var totalVotesCast = results.Sum(kvp => kvp.Value); var totalVotesCast = results.Sum(kvp => kvp.Value);
if (totalVotesCast == 0) { if (totalVotesCast == 0)
{
await ch.SendMessage("📄 **No votes have been cast.**"); await ch.SendMessage("📄 **No votes have been cast.**");
return; return;
} }
@ -98,16 +112,20 @@ namespace NadekoBot.Commands {
$"📄 , here are the results:\n"; $"📄 , here are the results:\n";
closeMessage = results.Aggregate(closeMessage, (current, kvp) => current + $"`{kvp.Key}.` **[{answers[kvp.Key - 1]}]**" + closeMessage = results.Aggregate(closeMessage, (current, kvp) => current + $"`{kvp.Key}.` **[{answers[kvp.Key - 1]}]**" +
$" has {kvp.Value} votes." + $" has {kvp.Value} votes." +
$"({kvp.Value*1.0f/totalVotesCast*100}%)\n"); $"({kvp.Value * 1.0f / totalVotesCast * 100}%)\n");
await ch.SendMessage($"📄 **Total votes cast**: {totalVotesCast}\n{closeMessage}"); await ch.SendMessage($"📄 **Total votes cast**: {totalVotesCast}\n{closeMessage}");
} catch (Exception ex) { }
catch (Exception ex)
{
Console.WriteLine($"Error in poll game {ex}"); Console.WriteLine($"Error in poll game {ex}");
} }
} }
private async void Vote(object sender, MessageEventArgs e) { private async void Vote(object sender, MessageEventArgs e)
try { {
try
{
if (!e.Channel.IsPrivate) if (!e.Channel.IsPrivate)
return; return;
if (participants.ContainsKey(e.User)) if (participants.ContainsKey(e.User))
@ -117,7 +135,8 @@ namespace NadekoBot.Commands {
if (!int.TryParse(e.Message.Text, out vote)) return; if (!int.TryParse(e.Message.Text, out vote)) return;
if (vote < 1 || vote > answers.Length) if (vote < 1 || vote > answers.Length)
return; return;
if (participants.TryAdd(e.User, vote)) { if (participants.TryAdd(e.User, vote))
{
await e.User.SendMessage($"Thanks for voting **{e.User.Name}**."); await e.User.SendMessage($"Thanks for voting **{e.User.Name}**.");
} }
} }

View File

@ -161,6 +161,7 @@
<Compile Include="Classes\_DataModels\TypingArticleModel.cs" /> <Compile Include="Classes\_DataModels\TypingArticleModel.cs" />
<Compile Include="Classes\_DataModels\UserQuoteModel.cs" /> <Compile Include="Classes\_DataModels\UserQuoteModel.cs" />
<Compile Include="Commands\BetrayGame.cs" /> <Compile Include="Commands\BetrayGame.cs" />
<Compile Include="Commands\DiscordCommand.cs" />
<Compile Include="Commands\PlantPick.cs" /> <Compile Include="Commands\PlantPick.cs" />
<Compile Include="Modules\Administration\Commands\CrossServerTextChannel.cs" /> <Compile Include="Modules\Administration\Commands\CrossServerTextChannel.cs" />
<Compile Include="Modules\Administration\Commands\InfoCommands.cs" /> <Compile Include="Modules\Administration\Commands\InfoCommands.cs" />
@ -185,7 +186,6 @@
<Compile Include="Classes\Extensions.cs" /> <Compile Include="Classes\Extensions.cs" />
<Compile Include="Commands\CopyCommand.cs" /> <Compile Include="Commands\CopyCommand.cs" />
<Compile Include="Modules\Gambling\DiceRollCommand.cs" /> <Compile Include="Modules\Gambling\DiceRollCommand.cs" />
<Compile Include="Commands\IDiscordCommand.cs" />
<Compile Include="Modules\Gambling\DrawCommand.cs" /> <Compile Include="Modules\Gambling\DrawCommand.cs" />
<Compile Include="Modules\Gambling\FlipCoinCommand.cs" /> <Compile Include="Modules\Gambling\FlipCoinCommand.cs" />
<Compile Include="Commands\HelpCommand.cs" /> <Compile Include="Commands\HelpCommand.cs" />