A lot of namespace changes

This commit is contained in:
Master Kwoth
2016-04-15 00:17:29 +02:00
parent ba0cc29bd3
commit a0f14c9cd9
53 changed files with 282 additions and 197 deletions

View File

@ -3,9 +3,9 @@ using Discord.Commands;
using Discord.Modules;
using NadekoBot.Classes;
using NadekoBot.Classes._DataModels;
using NadekoBot.Classes.Permissions;
using NadekoBot.Extensions;
using NadekoBot.Modules.Administration.Commands;
using NadekoBot.Modules.Permissions.Classes;
using Newtonsoft.Json.Linq;
using System;
using System.IO;

View File

@ -1,7 +1,7 @@
using Discord;
using Discord.Commands;
using NadekoBot.Classes.Permissions;
using NadekoBot.Commands;
using NadekoBot.Classes;
using NadekoBot.Modules.Permissions.Classes;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;

View File

@ -1,6 +1,6 @@
using Discord;
using Discord.Commands;
using NadekoBot.Commands;
using NadekoBot.Classes;
using NadekoBot.Extensions;
using System;
using System.Linq;

View File

@ -1,8 +1,8 @@
using Discord;
using Discord.Commands;
using NadekoBot.Classes;
using NadekoBot.Classes.Permissions;
using NadekoBot.Commands;
using NadekoBot.Classes;
using NadekoBot.Modules.Permissions.Classes;
using System;
using System.Collections.Concurrent;
using System.Linq;

View File

@ -1,7 +1,7 @@
using Discord;
using Discord.Commands;
using NadekoBot.Classes.Permissions;
using NadekoBot.Commands;
using NadekoBot.Classes;
using NadekoBot.Modules.Permissions.Classes;
using System;
using System.Collections.Concurrent;
using System.Timers;

View File

@ -1,8 +1,8 @@
using Discord.Commands;
using NadekoBot.Classes.JSONModels;
using NadekoBot.Commands;
using NadekoBot.Modules.Games.Commands;
using NadekoBot.Classes;
using NadekoBot.Modules.Music;
using NadekoBot.Modules.Permissions.Classes;
using System;
using System.Collections.Generic;
using System.Linq;
@ -33,7 +33,7 @@ namespace NadekoBot.Modules.Administration.Commands
}
},
{"%queued%", () => MusicModule.MusicPlayers.Sum(kvp => kvp.Value.Playlist.Count).ToString()},
{"%trivia%", () => Trivia.RunningTrivias.Count.ToString()}
{"%trivia%", () => Games.Commands.TriviaCommands.RunningTrivias.Count.ToString()}
};
private readonly object playingPlaceholderLock = new object();
@ -89,7 +89,7 @@ namespace NadekoBot.Modules.Administration.Commands
cgb.CreateCommand(Module.Prefix + "rotateplaying")
.Alias(Module.Prefix + "ropl")
.Description("Toggles rotation of playing status of the dynamic strings you specified earlier.")
.AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly())
.AddCheck(SimpleCheckers.OwnerOnly())
.Do(DoFunc());
cgb.CreateCommand(Module.Prefix + "addplaying")
@ -97,7 +97,7 @@ namespace NadekoBot.Modules.Administration.Commands
.Description("Adds a specified string to the list of playing strings to rotate. " +
"Supported placeholders: " + string.Join(", ", PlayingPlaceholders.Keys))
.Parameter("text", ParameterType.Unparsed)
.AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly())
.AddCheck(SimpleCheckers.OwnerOnly())
.Do(async e =>
{
var arg = e.GetArg("text");
@ -114,7 +114,7 @@ namespace NadekoBot.Modules.Administration.Commands
cgb.CreateCommand(Module.Prefix + "listplaying")
.Alias(Module.Prefix + "lipl")
.Description("Lists all playing statuses with their corresponding number.")
.AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly())
.AddCheck(SimpleCheckers.OwnerOnly())
.Do(async e =>
{
if (NadekoBot.Config.RotatingStatuses.Count == 0)
@ -132,7 +132,7 @@ namespace NadekoBot.Modules.Administration.Commands
.Alias(Module.Prefix + "repl", Module.Prefix + "rmpl")
.Description("Removes a playing string on a given number.")
.Parameter("number", ParameterType.Required)
.AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly())
.AddCheck(SimpleCheckers.OwnerOnly())
.Do(async e =>
{
var arg = e.GetArg("number");

View File

@ -1,6 +1,6 @@
using Discord.Commands;
using NadekoBot.Classes.Permissions;
using NadekoBot.Commands;
using NadekoBot.Classes;
using NadekoBot.Modules.Permissions.Classes;
using System;
using System.Collections.Concurrent;

View File

@ -2,7 +2,7 @@
using Discord.Commands;
using NadekoBot.Classes;
using NadekoBot.Classes._DataModels;
using NadekoBot.Commands;
using NadekoBot.Classes;
using System;
using System.Collections.Generic;
using System.Linq;

View File

@ -1,7 +1,7 @@
using Discord.Commands;
using NadekoBot.Classes;
using NadekoBot.Classes.Permissions;
using NadekoBot.Commands;
using NadekoBot.Classes;
using NadekoBot.Modules.Permissions.Classes;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -27,7 +27,8 @@ namespace NadekoBot.Modules.Administration.Commands
var role = e.Server.FindRoles(arg.Trim()).FirstOrDefault();
if (role == null)
msg.AppendLine($":anger:Role **{arg}** not found.");
else {
else
{
if (config.ListOfSelfAssignableRoles.Contains(role.Id))
{
msg.AppendLine($":anger:Role **{role.Name}** is already in the list.");
@ -81,7 +82,8 @@ namespace NadekoBot.Modules.Administration.Commands
msg.Append($"`{roleId} not found. Cleaned up.`, ");
toRemove.Add(roleId);
}
else {
else
{
msg.Append($"**{role.Name}**, ");
}
}

View File

@ -1,6 +1,6 @@
using Discord;
using Discord.Commands;
using NadekoBot.Commands;
using NadekoBot.Classes;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading.Tasks;

View File

@ -1,6 +1,6 @@
using Discord;
using Discord.Commands;
using NadekoBot.Commands;
using NadekoBot.Classes;
using System;
using System.Collections.Concurrent;
using System.Linq;

View File

@ -1,8 +1,8 @@
using Discord;
using Discord.Commands;
using NadekoBot.Classes;
using NadekoBot.Classes.Permissions;
using NadekoBot.Commands;
using NadekoBot.Classes;
using NadekoBot.Modules.Permissions.Classes;
using System;
using System.Linq;
using ChPermOverride = Discord.ChannelPermissionOverrides;

View File

@ -4,7 +4,7 @@ using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace NadekoBot.Commands.Conversations.Commands
namespace NadekoBot.Classes.Conversations.Commands
{
internal class CopyCommand : DiscordCommand
{

View File

@ -4,7 +4,7 @@ using NadekoBot.Modules;
using System;
using System.Threading.Tasks;
namespace NadekoBot.Commands.Conversations.Commands
namespace NadekoBot.Classes.Conversations.Commands
{
internal class RequestsCommand : DiscordCommand
{

View File

@ -2,8 +2,9 @@ using Discord;
using Discord.Commands;
using Discord.Modules;
using NadekoBot.Classes;
using NadekoBot.Commands.Conversations.Commands;
using NadekoBot.Classes.Conversations.Commands;
using NadekoBot.Extensions;
using NadekoBot.Modules.Permissions.Classes;
using NadekoBot.Properties;
using System;
using System.Diagnostics;
@ -32,7 +33,7 @@ namespace NadekoBot.Modules.Conversations
manager.CreateCommands("", cgb =>
{
cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance);
cgb.AddCheck(PermissionChecker.Instance);
cgb.CreateCommand("e")
.Description("You did it. Or someone else!")
@ -123,7 +124,7 @@ namespace NadekoBot.Modules.Conversations
{
var client = manager.Client;
cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance);
cgb.AddCheck(PermissionChecker.Instance);
commands.ForEach(cmd => cmd.Init(cgb));

View File

@ -1,6 +1,6 @@
using Discord.Modules;
using System.Collections.Generic;
using NadekoBot.Commands;
using NadekoBot.Classes;
namespace NadekoBot.Modules {
internal abstract class DiscordModule : IModule {

View File

@ -1,5 +1,5 @@
using Discord.Commands;
using NadekoBot.Commands;
using NadekoBot.Classes;
using NadekoBot.Extensions;
using System;
using System.Collections.Generic;

View File

@ -1,5 +1,5 @@
using Discord.Commands;
using NadekoBot.Commands;
using NadekoBot.Classes;
using NadekoBot.Extensions;
using NadekoBot.Modules.Gambling.Helpers;
using System;

View File

@ -1,5 +1,5 @@
using Discord.Commands;
using NadekoBot.Commands;
using NadekoBot.Classes;
using NadekoBot.Extensions;
using System;
using System.Drawing;

View File

@ -3,6 +3,7 @@ using Discord.Commands;
using Discord.Modules;
using NadekoBot.Classes;
using NadekoBot.Extensions;
using NadekoBot.Modules.Permissions.Classes;
using System;
using System.Linq;
using System.Threading.Tasks;
@ -25,7 +26,7 @@ namespace NadekoBot.Modules.Gambling
{
manager.CreateCommands("", cgb =>
{
cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance);
cgb.AddCheck(PermissionChecker.Instance);
commands.ForEach(com => com.Init(cgb));
@ -72,7 +73,7 @@ namespace NadekoBot.Modules.Gambling
cgb.CreateCommand(Prefix + "award")
.Description("Gives someone a certain amount of flowers. **Owner only!**")
.AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly())
.AddCheck(SimpleCheckers.OwnerOnly())
.Parameter("amount", ParameterType.Required)
.Parameter("receiver", ParameterType.Unparsed)
.Do(async e =>
@ -94,7 +95,7 @@ namespace NadekoBot.Modules.Gambling
cgb.CreateCommand(Prefix + "take")
.Description("Takes a certain amount of flowers from someone. **Owner only!**")
.AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly())
.AddCheck(SimpleCheckers.OwnerOnly())
.Parameter("amount", ParameterType.Required)
.Parameter("rektperson", ParameterType.Unparsed)
.Do(async e =>
@ -144,9 +145,9 @@ namespace NadekoBot.Modules.Gambling
await e.Channel.SendMessage("💢 Role not found.");
return;
}
var members = role.Members.Where(u => u.Status == Discord.UserStatus.Online); // only online
var members = role.Members.Where(u => u.Status == UserStatus.Online); // only online
var membersArray = members as User[] ?? members.ToArray();
var usr = membersArray[new System.Random().Next(0, membersArray.Length)];
var usr = membersArray[new Random().Next(0, membersArray.Length)];
await e.Channel.SendMessage($"**Raffled user:** {usr.Name} (id: {usr.Id})");
};
}

View File

@ -1,5 +1,5 @@
using Discord.Commands;
using NadekoBot.Commands;
using NadekoBot.Classes;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

View File

@ -1,6 +1,6 @@
using Discord;
using Discord.Commands;
using NadekoBot.Commands;
using NadekoBot.Classes;
using System.Text;
using System.Timers;
using static NadekoBot.Modules.Games.Commands.Bomberman;

View File

@ -1,7 +1,7 @@
using Discord;
using Discord.Commands;
using NadekoBot.Classes;
using NadekoBot.Commands;
using NadekoBot.Classes;
using System;
using System.Collections.Concurrent;
using System.IO;

View File

@ -1,6 +1,6 @@
using Discord;
using Discord.Commands;
using NadekoBot.Commands;
using NadekoBot.Classes;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;

View File

@ -2,7 +2,7 @@
using Discord.Commands;
using NadekoBot.Classes;
using NadekoBot.Classes._DataModels;
using NadekoBot.Commands;
using NadekoBot.Classes;
using NadekoBot.Extensions;
using System;
using System.Collections.Concurrent;

View File

@ -0,0 +1,156 @@
using Discord;
using Discord.Commands;
using NadekoBot.Classes;
using NadekoBot.Extensions;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Games.Commands.Trivia
{
internal class TriviaGame
{
private readonly object _guessLock = new object();
private Server server { get; }
private Channel channel { get; }
private int QuestionDurationMiliseconds { get; } = 30000;
private int HintTimeoutMiliseconds { get; } = 6000;
public bool ShowHints { get; set; } = true;
private CancellationTokenSource triviaCancelSource { get; set; }
public TriviaQuestion CurrentQuestion { get; private set; }
public HashSet<TriviaQuestion> oldQuestions { get; } = new HashSet<TriviaQuestion>();
public ConcurrentDictionary<User, int> Users { get; } = new ConcurrentDictionary<User, int>();
public bool GameActive { get; private set; } = false;
public bool ShouldStopGame { get; private set; }
public int WinRequirement { get; } = 10;
public TriviaGame(CommandEventArgs e, bool showHints)
{
ShowHints = showHints;
server = e.Server;
channel = e.Channel;
Task.Run(StartGame);
}
private async Task StartGame()
{
while (!ShouldStopGame)
{
// reset the cancellation source
triviaCancelSource = new CancellationTokenSource();
var token = triviaCancelSource.Token;
// load question
CurrentQuestion = TriviaQuestionPool.Instance.GetRandomQuestion(oldQuestions);
if (CurrentQuestion == null)
{
await channel.SendMessage($":exclamation: Failed loading a trivia question");
await End();
return;
}
oldQuestions.Add(CurrentQuestion); //add it to exclusion list so it doesn't show up again
//sendquestion
await channel.SendMessage($":question: **{CurrentQuestion.Question}**");
//receive messages
NadekoBot.Client.MessageReceived += PotentialGuess;
//allow people to guess
GameActive = true;
try
{
//hint
await Task.Delay(HintTimeoutMiliseconds, token);
if (ShowHints)
await channel.SendMessage($":exclamation:**Hint:** {CurrentQuestion.GetHint()}");
//timeout
await Task.Delay(QuestionDurationMiliseconds - HintTimeoutMiliseconds, token);
}
catch (TaskCanceledException)
{
Console.WriteLine("Trivia cancelled");
}
GameActive = false;
if (!triviaCancelSource.IsCancellationRequested)
await channel.Send($":clock2: :question: **Time's up!** The correct answer was **{CurrentQuestion.Answer}**");
NadekoBot.Client.MessageReceived -= PotentialGuess;
// load next question if game is still running
await Task.Delay(2000);
}
await End();
}
private async Task End()
{
ShouldStopGame = true;
await channel.SendMessage("**Trivia game ended**\n" + GetLeaderboard());
TriviaGame throwAwayValue;
TriviaCommands.RunningTrivias.TryRemove(server.Id, out throwAwayValue);
}
public async Task StopGame()
{
if (!ShouldStopGame)
await channel.SendMessage(":exclamation: Trivia will stop after this question.");
ShouldStopGame = true;
}
private async void PotentialGuess(object sender, MessageEventArgs e)
{
try
{
if (e.Channel.IsPrivate) return;
if (e.Server != server) return;
if (e.User.Id == NadekoBot.Client.CurrentUser.Id) return;
var guess = false;
lock (_guessLock)
{
if (GameActive && CurrentQuestion.IsAnswerCorrect(e.Message.Text) && !triviaCancelSource.IsCancellationRequested)
{
Users.TryAdd(e.User, 0); //add if not exists
Users[e.User]++; //add 1 point to the winner
guess = true;
}
}
if (!guess) return;
triviaCancelSource.Cancel();
await channel.SendMessage($"☑️ {e.User.Mention} guessed it! The answer was: **{CurrentQuestion.Answer}**");
if (Users[e.User] != WinRequirement) return;
ShouldStopGame = true;
await channel.Send($":exclamation: We have a winner! Its {e.User.Mention}.");
// add points to the winner
await FlowersHandler.AddFlowersAsync(e.User, "Won Trivia", 2);
}
catch { }
}
public string GetLeaderboard()
{
if (Users.Count == 0)
return "";
var sb = new StringBuilder();
sb.Append("**Leaderboard:**\n-----------\n");
foreach (var kvp in Users.OrderBy(kvp => kvp.Value))
{
sb.AppendLine($"**{kvp.Key.Name}** has {kvp.Value} points".ToString().SnPl(kvp.Value));
}
return sb.ToString();
}
}
}

View File

@ -0,0 +1,84 @@
using NadekoBot.Extensions;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
// THANKS @ShoMinamimoto for suggestions and coding help
namespace NadekoBot.Modules.Games.Commands.Trivia
{
public class TriviaQuestion
{
//represents the min size to judge levDistance with
private static readonly HashSet<Tuple<int, int>> strictness = new HashSet<Tuple<int, int>> {
new Tuple<int, int>(9, 0),
new Tuple<int, int>(14, 1),
new Tuple<int, int>(19, 2),
new Tuple<int, int>(22, 3),
};
public static int maxStringLength = 22;
public string Category;
public string Question;
public string Answer;
public TriviaQuestion(string q, string a, string c)
{
this.Question = q;
this.Answer = a;
this.Category = c;
}
public string GetHint() => Answer.Scramble();
public bool IsAnswerCorrect(string guess)
{
guess = CleanGuess(guess);
if (Answer.Equals(guess))
{
return true;
}
Answer = CleanGuess(Answer);
guess = CleanGuess(guess);
if (Answer.Equals(guess))
{
return true;
}
int levDistance = Answer.LevenshteinDistance(guess);
return JudgeGuess(Answer.Length, guess.Length, levDistance);
}
private bool JudgeGuess(int guessLength, int answerLength, int levDistance)
{
foreach (Tuple<int, int> level in strictness)
{
if (guessLength <= level.Item1 || answerLength <= level.Item1)
{
if (levDistance <= level.Item2)
return true;
else
return false;
}
}
return false;
}
private string CleanGuess(string str)
{
str = " " + str.ToLower() + " ";
str = Regex.Replace(str, "\\s+", " ");
str = Regex.Replace(str, "[^\\w\\d\\s]", "");
//Here's where custom modification can be done
str = Regex.Replace(str, "\\s(a|an|the|of|in|for|to|as|at|be)\\s", " ");
//End custom mod and cleanup whitespace
str = Regex.Replace(str, "^\\s+", "");
str = Regex.Replace(str, "\\s+$", "");
//Trim the really long answers
str = str.Length <= maxStringLength ? str : str.Substring(0, maxStringLength);
return str;
}
public override string ToString() =>
"Question: **" + this.Question + "?**";
}
}

View File

@ -0,0 +1,44 @@
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace NadekoBot.Modules.Games.Commands.Trivia
{
public class TriviaQuestionPool
{
public static TriviaQuestionPool Instance { get; } = new TriviaQuestionPool();
public HashSet<TriviaQuestion> pool = new HashSet<TriviaQuestion>();
private Random rng { get; } = new Random();
static TriviaQuestionPool() { }
private TriviaQuestionPool()
{
Reload();
}
public TriviaQuestion GetRandomQuestion(IEnumerable<TriviaQuestion> exclude)
{
var list = pool.Except(exclude).ToList();
var rand = rng.Next(0, list.Count);
return list[rand];
}
internal void Reload()
{
var arr = JArray.Parse(File.ReadAllText("data/questions.json"));
foreach (var item in arr)
{
var tq = new TriviaQuestion(item["Question"].ToString(), item["Answer"].ToString(), item["Category"]?.ToString());
pool.Add(tq);
}
var r = new Random();
pool = new HashSet<TriviaQuestion>(pool.OrderBy(x => r.Next()));
}
}
}

View File

@ -1,15 +1,19 @@
using Discord.Commands;
using NadekoBot.Commands;
using NadekoBot.Classes;
using NadekoBot.Modules.Games.Commands.Trivia;
using System.Collections.Concurrent;
using System.Linq;
using TriviaGame = NadekoBot.Classes.Trivia.TriviaGame;
namespace NadekoBot.Modules.Games.Commands
{
internal class Trivia : DiscordCommand
internal class TriviaCommands : DiscordCommand
{
public static ConcurrentDictionary<ulong, TriviaGame> RunningTrivias = new ConcurrentDictionary<ulong, TriviaGame>();
public TriviaCommands(DiscordModule module) : base(module)
{
}
internal override void Init(CommandGroupBuilder cgb)
{
cgb.CreateCommand(Module.Prefix + "t")
@ -57,7 +61,5 @@ namespace NadekoBot.Modules.Games.Commands
await e.Channel.SendMessage("No trivia is running on this server.");
});
}
public Trivia(DiscordModule module) : base(module) { }
}
}

View File

@ -1,8 +1,8 @@
using Discord.Commands;
using Discord.Modules;
using NadekoBot.Commands;
using NadekoBot.Extensions;
using NadekoBot.Modules.Games.Commands;
using NadekoBot.Modules.Permissions.Classes;
using System;
using System.Linq;
@ -14,7 +14,7 @@ namespace NadekoBot.Modules.Games
public GamesModule()
{
commands.Add(new Trivia(this));
commands.Add(new TriviaCommands(this));
commands.Add(new SpeedTyping(this));
commands.Add(new PollCommand(this));
commands.Add(new PlantPick(this));
@ -30,7 +30,7 @@ namespace NadekoBot.Modules.Games
manager.CreateCommands("", cgb =>
{
cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance);
cgb.AddCheck(PermissionChecker.Instance);
commands.ForEach(cmd => cmd.Init(cgb));

View File

@ -1,12 +1,13 @@
using Discord.Commands;
using NadekoBot.Extensions;
using NadekoBot.Modules;
using NadekoBot.Modules.Permissions.Classes;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace NadekoBot.Commands.Help.Commands
namespace NadekoBot.Classes.Help.Commands
{
internal class HelpCommand : DiscordCommand
{
@ -104,7 +105,7 @@ Version: `{NadekoStats.Instance.BotVersion}`";
.Do(DoFunc());
cgb.CreateCommand(Module.Prefix + "hgit")
.Description("Generates the commandlist.md file. **Owner Only!**")
.AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly())
.AddCheck(SimpleCheckers.OwnerOnly())
.Do(DoGitFunc());
cgb.CreateCommand(Module.Prefix + "readme")
.Alias(Module.Prefix + "guide")

View File

@ -1,7 +1,8 @@
using Discord.Commands;
using Discord.Modules;
using NadekoBot.Commands.Help.Commands;
using NadekoBot.Classes.Help.Commands;
using NadekoBot.Extensions;
using NadekoBot.Modules.Permissions.Classes;
using System.Linq;
namespace NadekoBot.Modules.Help
@ -20,7 +21,7 @@ namespace NadekoBot.Modules.Help
{
manager.CreateCommands("", cgb =>
{
cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance);
cgb.AddCheck(PermissionChecker.Instance);
commands.ForEach(com => com.Init(cgb));
cgb.CreateCommand(Prefix + "modules")

View File

@ -4,8 +4,8 @@ using Discord.Modules;
using NadekoBot.Classes;
using NadekoBot.Classes._DataModels;
using NadekoBot.Classes.Music;
using NadekoBot.Classes.Permissions;
using NadekoBot.Extensions;
using NadekoBot.Modules.Permissions.Classes;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;

View File

@ -1,6 +1,7 @@
using Discord.Commands;
using Discord.Modules;
using NadekoBot.Classes;
using NadekoBot.Modules.Permissions.Classes;
using Newtonsoft.Json.Linq;
using System;
@ -18,7 +19,7 @@ namespace NadekoBot.Modules.NSFW
manager.CreateCommands("", cgb =>
{
cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance);
cgb.AddCheck(PermissionChecker.Instance);
cgb.CreateCommand(Prefix + "hentai")
.Description("Shows a random NSFW hentai image from gelbooru and danbooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +)\n**Usage**: ~hentai yuri+kissing")

View File

@ -0,0 +1,136 @@
using Discord;
using Discord.Commands;
using Discord.Commands.Permissions;
using NadekoBot.Classes.JSONModels;
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Permissions.Classes
{
internal class PermissionChecker : IPermissionChecker
{
public static PermissionChecker Instance { get; } = new PermissionChecker();
private ConcurrentDictionary<User, DateTime> timeBlackList { get; } = new ConcurrentDictionary<User, DateTime>();
static PermissionChecker() { }
private PermissionChecker()
{
Task.Run(async () =>
{
while (true)
{
//blacklist is cleared every 1.75 seconds. That is the most time anyone will be blocked
await Task.Delay(1750);
timeBlackList.Clear();
}
});
}
public bool CanRun(Command command, User user, Channel channel, out string error)
{
error = String.Empty;
if (!NadekoBot.Ready)
return false;
if (channel.IsPrivate || channel.Server == null)
return command.Category == "Help";
if (ConfigHandler.IsUserBlacklisted(user.Id) ||
(!channel.IsPrivate &&
(ConfigHandler.IsServerBlacklisted(channel.Server.Id) || ConfigHandler.IsChannelBlacklisted(channel.Id))))
{
return false;
}
if (timeBlackList.ContainsKey(user))
return false;
timeBlackList.TryAdd(user, DateTime.Now);
try
{
//is it a permission command?
// if it is, check if the user has the correct role
// if yes return true, if no return false
if (command.Category == "Permissions")
{
Discord.Role role = null;
try
{
role = PermissionHelper.ValidateRole(user.Server,
PermissionsHandler.GetServerPermissionsRoleName(user.Server));
}
catch { }
if (user.Server.Owner.Id == user.Id || (role != null && user.HasRole(role)))
return true;
ServerPermissions perms;
PermissionsHandler.PermissionsDict.TryGetValue(user.Server.Id, out perms);
throw new Exception($"You don't have the necessary role (**{(perms?.PermissionsControllerRole ?? "Nadeko")}**) to change permissions.");
}
var permissionType = PermissionsHandler.GetPermissionBanType(command, user, channel);
string msg;
if (permissionType == PermissionsHandler.PermissionBanType.ServerBanModule &&
command.Category.ToLower() == "nsfw")
msg = $"**{command.Category}** module has been banned from use on this **server**.\nNSFW module is disabled by default. Server owner can type `;sm nsfw enable` to enable it.";
else
switch (permissionType)
{
case PermissionsHandler.PermissionBanType.None:
return true;
case PermissionsHandler.PermissionBanType.ServerBanCommand:
msg = $"**{command.Text}** command has been banned from use on this **server**.";
break;
case PermissionsHandler.PermissionBanType.ServerBanModule:
msg = $"**{command.Category}** module has been banned from use on this **server**.";
break;
case PermissionsHandler.PermissionBanType.ChannelBanCommand:
msg = $"**{command.Text}** command has been banned from use on this **channel**.";
break;
case PermissionsHandler.PermissionBanType.ChannelBanModule:
msg = $"**{command.Category}** module has been banned from use on this **channel**.";
break;
case PermissionsHandler.PermissionBanType.RoleBanCommand:
msg = $"You do not have a **role** which permits you the usage of **{command.Text}** command.";
break;
case PermissionsHandler.PermissionBanType.RoleBanModule:
msg = $"You do not have a **role** which permits you the usage of **{command.Category}** module.";
break;
case PermissionsHandler.PermissionBanType.UserBanCommand:
msg = $"{user.Mention}, You have been banned from using **{command.Text}** command.";
break;
case PermissionsHandler.PermissionBanType.UserBanModule:
msg = $"{user.Mention}, You have been banned from using **{command.Category}** module.";
break;
default:
return true;
}
if (PermissionsHandler.PermissionsDict[user.Server.Id].Verbose) //if verbose - print errors
error = msg;
return false;
}
catch (Exception ex)
{
Console.WriteLine($"Exception in canrun: {ex}");
try
{
ServerPermissions perms;
if (PermissionsHandler.PermissionsDict.TryGetValue(user.Server.Id, out perms) && perms.Verbose)
//if verbose - print errors
error = ex.Message;
}
catch (Exception ex2)
{
Console.WriteLine($"SERIOUS PERMISSION ERROR {ex2}\n\nUser:{user} Server: {user?.Server?.Name}/{user?.Server?.Id}");
}
return false;
}
}
}
}

View File

@ -0,0 +1,99 @@
using Discord;
using Discord.Commands;
using Discord.Modules;
using System;
using System.Linq;
namespace NadekoBot.Modules.Permissions.Classes
{
internal static class PermissionHelper
{
public static bool ValidateBool(string passedArg)
{
if (string.IsNullOrWhiteSpace(passedArg))
{
throw new ArgumentException("No value supplied! Missing argument");
}
switch (passedArg.ToLower())
{
case "1":
case "t":
case "true":
case "enable":
case "enabled":
case "allow":
case "unban":
return true;
case "0":
case "f":
case "false":
case "disable":
case "disabled":
case "disallow":
case "ban":
return false;
default:
throw new ArgumentException("Did not receive a valid boolean value");
}
}
internal static string ValidateModule(string mod)
{
if (string.IsNullOrWhiteSpace(mod))
throw new ArgumentNullException(nameof(mod));
foreach (var m in NadekoBot.Client.GetService<ModuleService>().Modules)
{
if (m.Name.ToLower().Equals(mod.Trim().ToLower()))
return m.Name;
}
throw new ArgumentException("That module does not exist.");
}
internal static string ValidateCommand(string commandText)
{
if (string.IsNullOrWhiteSpace(commandText))
throw new ArgumentNullException(nameof(commandText));
foreach (var com in NadekoBot.Client.GetService<CommandService>().AllCommands)
{
if (com.Text.ToLower().Equals(commandText.Trim().ToLower()))
return com.Text;
}
throw new NullReferenceException("That command does not exist.");
}
internal static Role ValidateRole(Server server, string roleName)
{
if (string.IsNullOrWhiteSpace(roleName))
throw new ArgumentNullException(nameof(roleName));
if (roleName.Trim() == "everyone")
roleName = "@everyone";
var role = server.FindRoles(roleName.Trim()).FirstOrDefault();
if (role == null)
throw new NullReferenceException("That role does not exist.");
return role;
}
internal static Channel ValidateChannel(Server server, string channelName)
{
if (string.IsNullOrWhiteSpace(channelName))
throw new ArgumentNullException(nameof(channelName));
var channel = server.FindChannels(channelName.Trim(), ChannelType.Text).FirstOrDefault();
if (channel == null)
throw new NullReferenceException("That channel does not exist.");
return channel;
}
internal static User ValidateUser(Server server, string userName)
{
if (string.IsNullOrWhiteSpace(userName))
throw new ArgumentNullException(nameof(userName));
var user = server.FindUsers(userName.Trim()).FirstOrDefault();
if (user == null)
throw new NullReferenceException("That user does not exist.");
return user;
}
}
}

View File

@ -0,0 +1,489 @@
using Discord;
using Discord.Commands;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Permissions.Classes
{
public static class PermissionsHandler
{
public static ConcurrentDictionary<ulong, ServerPermissions> PermissionsDict =
new ConcurrentDictionary<ulong, ServerPermissions>();
public enum PermissionBanType
{
None, ServerBanCommand, ServerBanModule,
ChannelBanCommand, ChannelBanModule, RoleBanCommand,
RoleBanModule, UserBanCommand, UserBanModule
}
public static void Initialize()
{
Console.WriteLine("Reading from the permission files.");
Directory.CreateDirectory("data/permissions");
foreach (var file in Directory.EnumerateFiles("data/permissions/"))
{
try
{
var strippedFileName = Path.GetFileNameWithoutExtension(file);
if (string.IsNullOrWhiteSpace(strippedFileName)) continue;
var id = ulong.Parse(strippedFileName);
var data = Newtonsoft.Json.JsonConvert.DeserializeObject<ServerPermissions>(File.ReadAllText(file));
PermissionsDict.TryAdd(id, data);
}
catch { }
}
Console.WriteLine("Permission initialization complete.");
}
internal static Permissions GetRolePermissionsById(Server server, ulong id)
{
ServerPermissions serverPerms;
if (!PermissionsDict.TryGetValue(server.Id, out serverPerms))
return null;
Permissions toReturn;
serverPerms.RolePermissions.TryGetValue(id, out toReturn);
return toReturn;
}
internal static Permissions GetUserPermissionsById(Server server, ulong id)
{
ServerPermissions serverPerms;
if (!PermissionsDict.TryGetValue(server.Id, out serverPerms))
return null;
Permissions toReturn;
serverPerms.UserPermissions.TryGetValue(id, out toReturn);
return toReturn;
}
internal static Permissions GetChannelPermissionsById(Server server, ulong id)
{
ServerPermissions serverPerms;
if (!PermissionsDict.TryGetValue(server.Id, out serverPerms))
return null;
Permissions toReturn;
serverPerms.ChannelPermissions.TryGetValue(id, out toReturn);
return toReturn;
}
internal static Permissions GetServerPermissions(Server server)
{
ServerPermissions serverPerms;
return !PermissionsDict.TryGetValue(server.Id, out serverPerms) ? null : serverPerms.Permissions;
}
internal static PermissionBanType GetPermissionBanType(Command command, User user, Channel channel)
{
var server = user.Server;
ServerPermissions serverPerms = PermissionsDict.GetOrAdd(server.Id, id => new ServerPermissions(id, server.Name));
bool val;
Permissions perm;
//server
if (serverPerms.Permissions.Modules.TryGetValue(command.Category, out val) && val == false)
return PermissionBanType.ServerBanModule;
if (serverPerms.Permissions.Commands.TryGetValue(command.Text, out val) && val == false)
return PermissionBanType.ServerBanCommand;
//channel
if (serverPerms.ChannelPermissions.TryGetValue(channel.Id, out perm) &&
perm.Modules.TryGetValue(command.Category, out val) && val == false)
return PermissionBanType.ChannelBanModule;
if (serverPerms.ChannelPermissions.TryGetValue(channel.Id, out perm) &&
perm.Commands.TryGetValue(command.Text, out val) && val == false)
return PermissionBanType.ChannelBanCommand;
//ROLE PART - TWO CASES
// FIRST CASE:
// IF EVERY ROLE USER HAS IS BANNED FROM THE MODULE,
// THAT MEANS USER CANNOT RUN THIS COMMAND
// IF AT LEAST ONE ROLE EXIST THAT IS NOT BANNED,
// USER CAN RUN THE COMMAND
var foundNotBannedRole = false;
foreach (var role in user.Roles)
{
//if every role is banned from using the module -> rolebanmodule
if (serverPerms.RolePermissions.TryGetValue(role.Id, out perm) &&
perm.Modules.TryGetValue(command.Category, out val) && val == false)
continue;
foundNotBannedRole = true;
break;
}
if (!foundNotBannedRole)
return PermissionBanType.RoleBanModule;
// SECOND CASE:
// IF EVERY ROLE USER HAS IS BANNED FROM THE COMMAND,
// THAT MEANS USER CANNOT RUN THAT COMMAND
// IF AT LEAST ONE ROLE EXISTS THAT IS NOT BANNED,
// USER CAN RUN THE COMMAND
foundNotBannedRole = false;
foreach (var role in user.Roles)
{
//if every role is banned from using the module -> rolebanmodule
if (serverPerms.RolePermissions.TryGetValue(role.Id, out perm) &&
perm.Commands.TryGetValue(command.Text, out val) && val == false)
continue;
else
{
foundNotBannedRole = true;
break;
}
}
if (!foundNotBannedRole)
return PermissionBanType.RoleBanCommand;
//user
if (serverPerms.UserPermissions.TryGetValue(user.Id, out perm) &&
perm.Modules.TryGetValue(command.Category, out val) && val == false)
return PermissionBanType.UserBanModule;
if (serverPerms.UserPermissions.TryGetValue(user.Id, out perm) &&
perm.Commands.TryGetValue(command.Text, out val) && val == false)
return PermissionBanType.UserBanCommand;
return PermissionBanType.None;
}
private static void WriteServerToJson(ServerPermissions serverPerms)
{
string pathToFile = $"data/permissions/{serverPerms.Id}.json";
File.WriteAllText(pathToFile,
Newtonsoft.Json.JsonConvert.SerializeObject(serverPerms, Newtonsoft.Json.Formatting.Indented));
}
public static void WriteToJson()
{
Directory.CreateDirectory("data/permissions/");
foreach (var kvp in PermissionsDict)
{
WriteServerToJson(kvp.Value);
}
}
public static string GetServerPermissionsRoleName(Server server)
{
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
new ServerPermissions(server.Id, server.Name));
return serverPerms.PermissionsControllerRole;
}
internal static void SetPermissionsRole(Server server, string roleName)
{
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
new ServerPermissions(server.Id, server.Name));
serverPerms.PermissionsControllerRole = roleName;
Task.Run(() => WriteServerToJson(serverPerms));
}
internal static void SetVerbosity(Server server, bool val)
{
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
new ServerPermissions(server.Id, server.Name));
serverPerms.Verbose = val;
Task.Run(() => WriteServerToJson(serverPerms));
}
public static void SetServerModulePermission(Server server, string moduleName, bool value)
{
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
new ServerPermissions(server.Id, server.Name));
var modules = serverPerms.Permissions.Modules;
if (modules.ContainsKey(moduleName))
modules[moduleName] = value;
else
modules.TryAdd(moduleName, value);
Task.Run(() => WriteServerToJson(serverPerms));
}
public static void SetServerCommandPermission(Server server, string commandName, bool value)
{
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
new ServerPermissions(server.Id, server.Name));
var commands = serverPerms.Permissions.Commands;
if (commands.ContainsKey(commandName))
commands[commandName] = value;
else
commands.TryAdd(commandName, value);
Task.Run(() => WriteServerToJson(serverPerms));
}
public static void SetChannelModulePermission(Channel channel, string moduleName, bool value)
{
var server = channel.Server;
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
new ServerPermissions(server.Id, server.Name));
if (!serverPerms.ChannelPermissions.ContainsKey(channel.Id))
serverPerms.ChannelPermissions.Add(channel.Id, new Permissions(channel.Name));
var modules = serverPerms.ChannelPermissions[channel.Id].Modules;
if (modules.ContainsKey(moduleName))
modules[moduleName] = value;
else
modules.TryAdd(moduleName, value);
Task.Run(() => WriteServerToJson(serverPerms));
}
public static void SetChannelCommandPermission(Channel channel, string commandName, bool value)
{
var server = channel.Server;
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
new ServerPermissions(server.Id, server.Name));
if (!serverPerms.ChannelPermissions.ContainsKey(channel.Id))
serverPerms.ChannelPermissions.Add(channel.Id, new Permissions(channel.Name));
var commands = serverPerms.ChannelPermissions[channel.Id].Commands;
if (commands.ContainsKey(commandName))
commands[commandName] = value;
else
commands.TryAdd(commandName, value);
Task.Run(() => WriteServerToJson(serverPerms));
}
public static void SetRoleModulePermission(Role role, string moduleName, bool value)
{
var server = role.Server;
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
new ServerPermissions(server.Id, server.Name));
if (!serverPerms.RolePermissions.ContainsKey(role.Id))
serverPerms.RolePermissions.Add(role.Id, new Permissions(role.Name));
var modules = serverPerms.RolePermissions[role.Id].Modules;
if (modules.ContainsKey(moduleName))
modules[moduleName] = value;
else
modules.TryAdd(moduleName, value);
Task.Run(() => WriteServerToJson(serverPerms));
}
public static void SetRoleCommandPermission(Role role, string commandName, bool value)
{
var server = role.Server;
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
new ServerPermissions(server.Id, server.Name));
if (!serverPerms.RolePermissions.ContainsKey(role.Id))
serverPerms.RolePermissions.Add(role.Id, new Permissions(role.Name));
var commands = serverPerms.RolePermissions[role.Id].Commands;
if (commands.ContainsKey(commandName))
commands[commandName] = value;
else
commands.TryAdd(commandName, value);
Task.Run(() => WriteServerToJson(serverPerms));
}
public static void SetUserModulePermission(User user, string moduleName, bool value)
{
var server = user.Server;
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
new ServerPermissions(server.Id, server.Name));
if (!serverPerms.UserPermissions.ContainsKey(user.Id))
serverPerms.UserPermissions.Add(user.Id, new Permissions(user.Name));
var modules = serverPerms.UserPermissions[user.Id].Modules;
if (modules.ContainsKey(moduleName))
modules[moduleName] = value;
else
modules.TryAdd(moduleName, value);
Task.Run(() => WriteServerToJson(serverPerms));
}
public static void SetUserCommandPermission(User user, string commandName, bool value)
{
var server = user.Server;
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
new ServerPermissions(server.Id, server.Name));
if (!serverPerms.UserPermissions.ContainsKey(user.Id))
serverPerms.UserPermissions.Add(user.Id, new Permissions(user.Name));
var commands = serverPerms.UserPermissions[user.Id].Commands;
if (commands.ContainsKey(commandName))
commands[commandName] = value;
else
commands.TryAdd(commandName, value);
Task.Run(() => WriteServerToJson(serverPerms));
}
public static void SetServerWordPermission(Server server, bool value)
{
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
new ServerPermissions(server.Id, server.Name));
serverPerms.Permissions.FilterWords = value;
Task.Run(() => WriteServerToJson(serverPerms));
}
public static void SetChannelWordPermission(Channel channel, bool value)
{
var server = channel.Server;
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
new ServerPermissions(server.Id, server.Name));
if (!serverPerms.ChannelPermissions.ContainsKey(channel.Id))
serverPerms.ChannelPermissions.Add(channel.Id, new Permissions(channel.Name));
serverPerms.ChannelPermissions[channel.Id].FilterWords = value;
Task.Run(() => WriteServerToJson(serverPerms));
}
public static void SetServerFilterInvitesPermission(Server server, bool value)
{
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
new ServerPermissions(server.Id, server.Name));
serverPerms.Permissions.FilterInvites = value;
Task.Run(() => WriteServerToJson(serverPerms));
}
public static void SetChannelFilterInvitesPermission(Channel channel, bool value)
{
var server = channel.Server;
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
new ServerPermissions(server.Id, server.Name));
if (!serverPerms.ChannelPermissions.ContainsKey(channel.Id))
serverPerms.ChannelPermissions.Add(channel.Id, new Permissions(channel.Name));
serverPerms.ChannelPermissions[channel.Id].FilterInvites = value;
Task.Run(() => WriteServerToJson(serverPerms));
}
public static void AddFilteredWord(Server server, string word)
{
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
new ServerPermissions(server.Id, server.Name));
if (serverPerms.Words.Contains(word))
throw new InvalidOperationException("That word is already banned.");
serverPerms.Words.Add(word);
Task.Run(() => WriteServerToJson(serverPerms));
}
public static void RemoveFilteredWord(Server server, string word)
{
var serverPerms = PermissionsDict.GetOrAdd(server.Id,
new ServerPermissions(server.Id, server.Name));
if (!serverPerms.Words.Contains(word))
throw new InvalidOperationException("That word is not banned.");
serverPerms.Words.Remove(word);
Task.Run(() => WriteServerToJson(serverPerms));
}
}
/// <summary>
/// Holds a permission list
/// </summary>
public class Permissions
{
/// <summary>
/// Name of the parent object whose permissions these are
/// </summary>
public string Name { get; set; }
/// <summary>
/// Module name with allowed/disallowed
/// </summary>
public ConcurrentDictionary<string, bool> Modules { get; set; }
/// <summary>
/// Command name with allowed/disallowed
/// </summary>
public ConcurrentDictionary<string, bool> Commands { get; set; }
/// <summary>
/// Should the bot filter invites to other discord servers (and ref links in the future)
/// </summary>
public bool FilterInvites { get; set; }
/// <summary>
/// Should the bot filter words which are specified in the Words hashset
/// </summary>
public bool FilterWords { get; set; }
public Permissions(string name)
{
Name = name;
Modules = new ConcurrentDictionary<string, bool>();
Commands = new ConcurrentDictionary<string, bool>();
FilterInvites = false;
FilterWords = false;
}
public override string ToString()
{
var toReturn = "";
var bannedModules = Modules.Where(kvp => kvp.Value == false);
var bannedModulesArray = bannedModules as KeyValuePair<string, bool>[] ?? bannedModules.ToArray();
if (bannedModulesArray.Any())
{
toReturn += "`Banned Modules:`\n";
toReturn = bannedModulesArray.Aggregate(toReturn, (current, m) => current + $"\t`[x] {m.Key}`\n");
}
var bannedCommands = Commands.Where(kvp => kvp.Value == false);
var bannedCommandsArr = bannedCommands as KeyValuePair<string, bool>[] ?? bannedCommands.ToArray();
if (bannedCommandsArr.Any())
{
toReturn += "`Banned Commands:`\n";
toReturn = bannedCommandsArr.Aggregate(toReturn, (current, c) => current + $"\t`[x] {c.Key}`\n");
}
return toReturn;
}
}
public class ServerPermissions
{
/// <summary>
/// The guy who can edit the permissions
/// </summary>
public string PermissionsControllerRole { get; set; }
/// <summary>
/// Does it print the error when a restriction occurs
/// </summary>
public bool Verbose { get; set; }
/// <summary>
/// The id of the thing (user/server/channel)
/// </summary>
public ulong Id { get; set; } //a string because of the role name.
/// <summary>
/// Permission object bound to the id of something/role name
/// </summary>
public Permissions Permissions { get; set; }
/// <summary>
/// Banned words, usually profanities, like word "java"
/// </summary>
public HashSet<string> Words { get; set; }
public Dictionary<ulong, Permissions> UserPermissions { get; set; }
public Dictionary<ulong, Permissions> ChannelPermissions { get; set; }
public Dictionary<ulong, Permissions> RolePermissions { get; set; }
public ServerPermissions(ulong id, string name)
{
Id = id;
PermissionsControllerRole = "Nadeko";
Verbose = true;
Permissions = new Permissions(name);
Permissions.Modules.TryAdd("NSFW", false);
UserPermissions = new Dictionary<ulong, Permissions>();
ChannelPermissions = new Dictionary<ulong, Permissions>();
RolePermissions = new Dictionary<ulong, Permissions>();
Words = new HashSet<string>();
}
}
}

View File

@ -0,0 +1,36 @@
using Discord;
using Discord.Commands;
using Discord.Commands.Permissions;
using System;
namespace NadekoBot.Modules.Permissions.Classes
{
public static class SimpleCheckers
{
public static ManageRoles CanManageRoles { get; } = new ManageRoles();
public static Func<Command, User, Channel, bool> OwnerOnly() =>
(com, user, ch) => NadekoBot.IsOwner(user.Id);
public static Func<Command, User, Channel, bool> ManageMessages() =>
(com, user, ch) => user.ServerPermissions.ManageMessages;
public static Func<Command, User, Channel, bool> ManageChannels() =>
(com, user, ch) => user.ServerPermissions.ManageChannels;
public static Func<Command, User, Channel, bool> ManageServer() =>
(com, user, ch) => user.ServerPermissions.ManageServer;
public class ManageRoles : IPermissionChecker
{
public bool CanRun(Command command, User user, Channel channel, out string error)
{
error = string.Empty;
if (user.ServerPermissions.ManageRoles)
return true;
error = "You do not have a permission to manage roles.";
return false;
}
}
}
}

View File

@ -1,11 +1,10 @@
using Discord;
using Discord.Commands;
using NadekoBot.Classes;
using NadekoBot.Classes.Permissions;
using NadekoBot.Commands;
using NadekoBot.Classes;
using NadekoBot.Modules.Permissions.Classes;
using System;
using System.Text.RegularExpressions;
using ServerPermissions = NadekoBot.Classes.Permissions.ServerPermissions;
namespace NadekoBot.Modules.Permissions.Commands
{
@ -21,7 +20,7 @@ namespace NadekoBot.Modules.Permissions.Commands
if (args.Channel.IsPrivate || args.User.Id == NadekoBot.Client.CurrentUser.Id) return;
try
{
ServerPermissions serverPerms;
Classes.ServerPermissions serverPerms;
if (!IsChannelOrServerFiltering(args.Channel, out serverPerms)) return;
if (filterRegex.IsMatch(args.Message.RawText))
@ -39,14 +38,14 @@ namespace NadekoBot.Modules.Permissions.Commands
};
}
private static bool IsChannelOrServerFiltering(Channel channel, out ServerPermissions serverPerms)
private static bool IsChannelOrServerFiltering(Channel channel, out Classes.ServerPermissions serverPerms)
{
if (!PermissionsHandler.PermissionsDict.TryGetValue(channel.Server.Id, out serverPerms)) return false;
if (serverPerms.Permissions.FilterInvites)
return true;
Classes.Permissions.Permissions perms;
Classes.Permissions perms;
return serverPerms.ChannelPermissions.TryGetValue(channel.Id, out perms) && perms.FilterInvites;
}

View File

@ -1,11 +1,10 @@
using Discord;
using Discord.Commands;
using NadekoBot.Classes;
using NadekoBot.Classes.Permissions;
using NadekoBot.Commands;
using NadekoBot.Classes;
using NadekoBot.Modules.Permissions.Classes;
using System;
using System.Linq;
using ServerPermissions = NadekoBot.Classes.Permissions.ServerPermissions;
namespace NadekoBot.Modules.Permissions.Commands
{
@ -18,7 +17,7 @@ namespace NadekoBot.Modules.Permissions.Commands
if (args.Channel.IsPrivate || args.User.Id == NadekoBot.Client.CurrentUser.Id) return;
try
{
ServerPermissions serverPerms;
Classes.ServerPermissions serverPerms;
if (!IsChannelOrServerFiltering(args.Channel, out serverPerms)) return;
var wordsInMessage = args.Message.RawText.ToLowerInvariant().Split(' ');
@ -37,14 +36,14 @@ namespace NadekoBot.Modules.Permissions.Commands
};
}
private static bool IsChannelOrServerFiltering(Channel channel, out ServerPermissions serverPerms)
private static bool IsChannelOrServerFiltering(Channel channel, out Classes.ServerPermissions serverPerms)
{
if (!PermissionsHandler.PermissionsDict.TryGetValue(channel.Server.Id, out serverPerms)) return false;
if (serverPerms.Permissions.FilterWords)
return true;
Classes.Permissions.Permissions perms;
Classes.Permissions perms;
return serverPerms.ChannelPermissions.TryGetValue(channel.Id, out perms) && perms.FilterWords;
}
@ -139,7 +138,7 @@ namespace NadekoBot.Modules.Permissions.Commands
{
try
{
ServerPermissions serverPerms;
Classes.ServerPermissions serverPerms;
if (!PermissionsHandler.PermissionsDict.TryGetValue(e.Server.Id, out serverPerms))
return;
await e.Channel.SendMessage($"There are `{serverPerms.Words.Count}` filtered words.\n" +

View File

@ -1,14 +1,13 @@
using Discord.Commands;
using Discord.Modules;
using NadekoBot.Classes.JSONModels;
using NadekoBot.Classes.Permissions;
using NadekoBot.Extensions;
using NadekoBot.Modules.Games.Commands;
using NadekoBot.Modules.Permissions.Classes;
using NadekoBot.Modules.Permissions.Commands;
using System;
using System.Linq;
using System.Threading.Tasks;
using PermsHandler = NadekoBot.Classes.Permissions.PermissionsHandler;
namespace NadekoBot.Modules.Permissions
{
@ -39,7 +38,7 @@ namespace NadekoBot.Modules.Permissions
{
if (string.IsNullOrWhiteSpace(e.GetArg("role")))
{
await e.Channel.SendMessage($"Current permissions role is `{PermsHandler.GetServerPermissionsRoleName(e.Server)}`");
await e.Channel.SendMessage($"Current permissions role is `{PermissionsHandler.GetServerPermissionsRoleName(e.Server)}`");
return;
}
@ -55,7 +54,7 @@ namespace NadekoBot.Modules.Permissions
await e.Channel.SendMessage($"Role `{arg}` probably doesn't exist. Create the role with that name first.");
return;
}
PermsHandler.SetPermissionsRole(e.Server, role.Name);
PermissionsHandler.SetPermissionsRole(e.Server, role.Name);
await e.Channel.SendMessage($"Role `{role.Name}` is now required in order to change permissions.");
});
@ -67,7 +66,7 @@ namespace NadekoBot.Modules.Permissions
{
var arg = e.GetArg("arg");
var val = PermissionHelper.ValidateBool(arg);
PermsHandler.SetVerbosity(e.Server, val);
PermissionsHandler.SetVerbosity(e.Server, val);
await e.Channel.SendMessage($"Verbosity set to {val}.");
});
@ -76,7 +75,7 @@ namespace NadekoBot.Modules.Permissions
.Description("Shows banned permissions for this server.")
.Do(async e =>
{
var perms = PermsHandler.GetServerPermissions(e.Server);
var perms = PermissionsHandler.GetServerPermissions(e.Server);
if (string.IsNullOrWhiteSpace(perms?.ToString()))
await e.Channel.SendMessage("No permissions set for this server.");
await e.Channel.SendMessage(perms.ToString());
@ -101,7 +100,7 @@ namespace NadekoBot.Modules.Permissions
return;
}
var perms = PermsHandler.GetRolePermissionsById(e.Server, role.Id);
var perms = PermissionsHandler.GetRolePermissionsById(e.Server, role.Id);
if (string.IsNullOrWhiteSpace(perms?.ToString()))
await e.Channel.SendMessage($"No permissions set for **{role.Name}** role.");
@ -127,7 +126,7 @@ namespace NadekoBot.Modules.Permissions
return;
}
var perms = PermsHandler.GetChannelPermissionsById(e.Server, channel.Id);
var perms = PermissionsHandler.GetChannelPermissionsById(e.Server, channel.Id);
if (string.IsNullOrWhiteSpace(perms?.ToString()))
await e.Channel.SendMessage($"No permissions set for **{channel.Name}** channel.");
await e.Channel.SendMessage(perms.ToString());
@ -151,7 +150,7 @@ namespace NadekoBot.Modules.Permissions
return;
}
var perms = PermsHandler.GetUserPermissionsById(e.Server, user.Id);
var perms = PermissionsHandler.GetUserPermissionsById(e.Server, user.Id);
if (string.IsNullOrWhiteSpace(perms?.ToString()))
await e.Channel.SendMessage($"No permissions set for user **{user.Name}**.");
await e.Channel.SendMessage(perms.ToString());
@ -168,7 +167,7 @@ namespace NadekoBot.Modules.Permissions
var module = PermissionHelper.ValidateModule(e.GetArg("module"));
var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
PermsHandler.SetServerModulePermission(e.Server, module, state);
PermissionsHandler.SetServerModulePermission(e.Server, module, state);
await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on this server.");
}
catch (ArgumentException exArg)
@ -192,7 +191,7 @@ namespace NadekoBot.Modules.Permissions
var command = PermissionHelper.ValidateCommand(e.GetArg("command"));
var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
PermsHandler.SetServerCommandPermission(e.Server, command, state);
PermissionsHandler.SetServerCommandPermission(e.Server, command, state);
await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on this server.");
}
catch (ArgumentException exArg)
@ -221,7 +220,7 @@ namespace NadekoBot.Modules.Permissions
{
foreach (var role in e.Server.Roles)
{
PermsHandler.SetRoleModulePermission(role, module, state);
PermissionsHandler.SetRoleModulePermission(role, module, state);
}
await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles.");
}
@ -229,7 +228,7 @@ namespace NadekoBot.Modules.Permissions
{
var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role"));
PermsHandler.SetRoleModulePermission(role, module, state);
PermissionsHandler.SetRoleModulePermission(role, module, state);
await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.");
}
}
@ -259,7 +258,7 @@ namespace NadekoBot.Modules.Permissions
{
foreach (var role in e.Server.Roles)
{
PermsHandler.SetRoleCommandPermission(role, command, state);
PermissionsHandler.SetRoleCommandPermission(role, command, state);
}
await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles.");
}
@ -267,7 +266,7 @@ namespace NadekoBot.Modules.Permissions
{
var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role"));
PermsHandler.SetRoleCommandPermission(role, command, state);
PermissionsHandler.SetRoleCommandPermission(role, command, state);
await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.");
}
}
@ -297,7 +296,7 @@ namespace NadekoBot.Modules.Permissions
{
foreach (var channel in e.Server.TextChannels)
{
PermsHandler.SetChannelModulePermission(channel, module, state);
PermissionsHandler.SetChannelModulePermission(channel, module, state);
}
await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels.");
}
@ -305,7 +304,7 @@ namespace NadekoBot.Modules.Permissions
{
var channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel"));
PermsHandler.SetChannelModulePermission(channel, module, state);
PermissionsHandler.SetChannelModulePermission(channel, module, state);
await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.");
}
}
@ -335,7 +334,7 @@ namespace NadekoBot.Modules.Permissions
{
foreach (var channel in e.Server.TextChannels)
{
PermsHandler.SetChannelCommandPermission(channel, command, state);
PermissionsHandler.SetChannelCommandPermission(channel, command, state);
}
await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels.");
}
@ -343,7 +342,7 @@ namespace NadekoBot.Modules.Permissions
{
var channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel"));
PermsHandler.SetChannelCommandPermission(channel, command, state);
PermissionsHandler.SetChannelCommandPermission(channel, command, state);
await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.");
}
}
@ -370,7 +369,7 @@ namespace NadekoBot.Modules.Permissions
var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
var user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user"));
PermsHandler.SetUserModulePermission(user, module, state);
PermissionsHandler.SetUserModulePermission(user, module, state);
await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.");
}
catch (ArgumentException exArg)
@ -396,7 +395,7 @@ namespace NadekoBot.Modules.Permissions
var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
var user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user"));
PermsHandler.SetUserCommandPermission(user, command, state);
PermissionsHandler.SetUserCommandPermission(user, command, state);
await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.");
}
catch (ArgumentException exArg)
@ -420,7 +419,7 @@ namespace NadekoBot.Modules.Permissions
foreach (var module in NadekoBot.Client.GetService<ModuleService>().Modules)
{
PermsHandler.SetServerModulePermission(e.Server, module.Name, state);
PermissionsHandler.SetServerModulePermission(e.Server, module.Name, state);
}
await e.Channel.SendMessage($"All modules have been **{(state ? "enabled" : "disabled")}** on this server.");
}
@ -447,7 +446,7 @@ namespace NadekoBot.Modules.Permissions
foreach (var command in NadekoBot.Client.GetService<CommandService>().AllCommands.Where(c => c.Category == module))
{
PermsHandler.SetServerCommandPermission(e.Server, command.Text, state);
PermissionsHandler.SetServerCommandPermission(e.Server, command.Text, state);
}
await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** on this server.");
}
@ -473,7 +472,7 @@ namespace NadekoBot.Modules.Permissions
var channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel"));
foreach (var module in NadekoBot.Client.GetService<ModuleService>().Modules)
{
PermsHandler.SetChannelModulePermission(channel, module.Name, state);
PermissionsHandler.SetChannelModulePermission(channel, module.Name, state);
}
await e.Channel.SendMessage($"All modules have been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.");
@ -502,7 +501,7 @@ namespace NadekoBot.Modules.Permissions
var channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel"));
foreach (var command in NadekoBot.Client.GetService<CommandService>().AllCommands.Where(c => c.Category == module))
{
PermsHandler.SetChannelCommandPermission(channel, command.Text, state);
PermissionsHandler.SetChannelCommandPermission(channel, command.Text, state);
}
await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.");
}
@ -528,7 +527,7 @@ namespace NadekoBot.Modules.Permissions
var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role"));
foreach (var module in NadekoBot.Client.GetService<ModuleService>().Modules)
{
PermsHandler.SetRoleModulePermission(role, module.Name, state);
PermissionsHandler.SetRoleModulePermission(role, module.Name, state);
}
await e.Channel.SendMessage($"All modules have been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.");
@ -557,7 +556,7 @@ namespace NadekoBot.Modules.Permissions
var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("channel"));
foreach (var command in NadekoBot.Client.GetService<CommandService>().AllCommands.Where(c => c.Category == module))
{
PermsHandler.SetRoleCommandPermission(role, command.Text, state);
PermissionsHandler.SetRoleCommandPermission(role, command.Text, state);
}
await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.");
}
@ -662,8 +661,8 @@ namespace NadekoBot.Modules.Permissions
NadekoBot.Config.ServerBlacklist.Add(serverId);
ConfigHandler.SaveConfig();
//cleanup trivias and typeracing
Classes.Trivia.TriviaGame trivia;
Trivia.RunningTrivias.TryRemove(serverId, out trivia);
Modules.Games.Commands.Trivia.TriviaGame trivia;
TriviaCommands.RunningTrivias.TryRemove(serverId, out trivia);
TypingGame typeracer;
SpeedTyping.RunningContests.TryRemove(serverId, out typeracer);

View File

@ -3,8 +3,8 @@ using Discord.Modules;
using NadekoBot.Classes;
using NadekoBot.Classes._DataModels;
using NadekoBot.Classes.JSONModels;
using NadekoBot.Classes.Permissions;
using NadekoBot.Extensions;
using NadekoBot.Modules.Permissions.Classes;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;

View File

@ -1,5 +1,5 @@
using Discord.Commands;
using NadekoBot.Commands;
using NadekoBot.Classes;
using ScaredFingers.UnitsConversion;
using System;
using System.Collections.Generic;

View File

@ -1,6 +1,6 @@
using Discord.Commands;
using NadekoBot.Classes;
using NadekoBot.Commands;
using NadekoBot.Classes;
using NadekoBot.Extensions;
using Newtonsoft.Json.Linq;
using System;

View File

@ -1,5 +1,5 @@
using Discord.Commands;
using NadekoBot.Commands;
using NadekoBot.Classes;
using System;
namespace NadekoBot.Modules.Searches.Commands

View File

@ -1,8 +1,8 @@
using Discord.Commands;
using NadekoBot.Classes;
using NadekoBot.Classes.JSONModels;
using NadekoBot.Classes.Permissions;
using NadekoBot.Commands;
using NadekoBot.Classes;
using NadekoBot.Modules.Permissions.Classes;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Concurrent;

View File

@ -4,6 +4,7 @@ using NadekoBot.Classes;
using NadekoBot.Classes.IMDB;
using NadekoBot.Classes.JSONModels;
using NadekoBot.Extensions;
using NadekoBot.Modules.Permissions.Classes;
using NadekoBot.Modules.Searches.Commands;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
@ -35,7 +36,7 @@ namespace NadekoBot.Modules.Searches
manager.CreateCommands("", cgb =>
{
cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance);
cgb.AddCheck(PermissionChecker.Instance);
commands.ForEach(cmd => cmd.Init(cgb));

View File

@ -1,5 +1,5 @@
using Discord.Commands;
using NadekoBot.Commands;
using NadekoBot.Classes;
using NadekoBot.Modules.Translator.Helpers;
using System;
using System.Threading.Tasks;

View File

@ -1,5 +1,6 @@
using Discord.Modules;
using NadekoBot.Extensions;
using NadekoBot.Modules.Permissions.Classes;
namespace NadekoBot.Modules.Translator
{
@ -17,7 +18,7 @@ namespace NadekoBot.Modules.Translator
{
manager.CreateCommands("", cgb =>
{
cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance);
cgb.AddCheck(PermissionChecker.Instance);
commands.ForEach(cmd => cmd.Init(cgb));
});
}

View File

@ -1,5 +1,5 @@
using Discord.Commands;
using NadekoBot.Commands;
using NadekoBot.Classes;
using NadekoBot.Modules.Translator.Helpers;
using System;
using System.Threading.Tasks;

View File

@ -2,6 +2,7 @@
using Manatee.Trello;
using Manatee.Trello.ManateeJson;
using NadekoBot.Extensions;
using NadekoBot.Modules.Permissions.Classes;
using System;
using System.Collections.Generic;
using System.Linq;
@ -65,7 +66,7 @@ namespace NadekoBot.Modules.Trello
manager.CreateCommands("trello ", cgb =>
{
cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance);
cgb.AddCheck(PermissionChecker.Instance);
cgb.CreateCommand("join")
.Alias("j")