Private message reply is now configurable in Config.json, closes #201, other small changes

This commit is contained in:
Master Kwoth 2016-04-10 02:38:46 +02:00
parent cf5e89d6a2
commit 59a373a14f
5 changed files with 112 additions and 74 deletions

View File

@ -16,7 +16,7 @@ namespace NadekoBot.Classes.JSONModels
[JsonIgnore] [JsonIgnore]
public List<PokemonType> PokemonTypes { get; set; } = new List<PokemonType>(); public List<PokemonType> PokemonTypes { get; set; } = new List<PokemonType>();
public List<string> RotatingStatuses { get; set; } = new List<string>(); public List<string> RotatingStatuses { get; set; } = new List<string>();
public CommandPrefixesModel CommandPrefixes { get; set; } = new CommandPrefixesModel(); public CommandPrefixesModel CommandPrefixes { get; set; } = new CommandPrefixesModel();
@ -29,7 +29,7 @@ namespace NadekoBot.Classes.JSONModels
143515953525817344 143515953525817344
}; };
public string[] _8BallResponses { get; set; } = public string[] _8BallResponses { get; set; } =
{ {
"Most definitely yes", "Most definitely yes",
@ -83,7 +83,7 @@ namespace NadekoBot.Classes.JSONModels
public string CurrencySign { get; set; } = "🌸"; public string CurrencySign { get; set; } = "🌸";
public string CurrencyName { get; set; } = "NadekoFlower"; public string CurrencyName { get; set; } = "NadekoFlower";
public string DMHelpString { get; set; } = "Type `-h` for help.";
} }
public class CommandPrefixesModel public class CommandPrefixesModel
@ -133,5 +133,5 @@ namespace NadekoBot.Classes.JSONModels
public override string ToString() => public override string ToString() =>
$"{Text}\n\t*-{Author}*"; $"{Text}\n\t*-{Author}*";
} }
} }

View File

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

View File

@ -1,14 +1,17 @@
using System; using Discord.Commands;
using NadekoBot.Extensions;
using NadekoBot.Modules;
using System;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord.Commands;
using NadekoBot.Extensions;
using NadekoBot.Modules;
namespace NadekoBot.Commands { namespace NadekoBot.Commands
internal class HelpCommand : DiscordCommand { {
public Func<CommandEventArgs, Task> DoFunc() => async e => { internal class HelpCommand : DiscordCommand
{
public Func<CommandEventArgs, Task> DoFunc() => async e =>
{
#region OldHelp #region OldHelp
/* /*
string helpstr = "**COMMANDS DO NOT WORK IN PERSONAL MESSAGES**\nOfficial repo: **github.com/Kwoth/NadekoBot/**"; string helpstr = "**COMMANDS DO NOT WORK IN PERSONAL MESSAGES**\nOfficial repo: **github.com/Kwoth/NadekoBot/**";
@ -35,11 +38,13 @@ namespace NadekoBot.Commands {
*/ */
#endregion OldHelp #endregion OldHelp
if (string.IsNullOrWhiteSpace(e.GetArg("command"))) { if (string.IsNullOrWhiteSpace(e.GetArg("command")))
{
await e.User.Send(HelpString); await e.User.Send(HelpString);
return; return;
} }
await Task.Run(async () => { await Task.Run(async () =>
{
var comToFind = e.GetArg("command"); var comToFind = e.GetArg("command");
var com = NadekoBot.Client.GetService<CommandService>().AllCommands var com = NadekoBot.Client.GetService<CommandService>().AllCommands
@ -55,7 +60,10 @@ namespace NadekoBot.Commands {
$"For a specific command help, use `{NadekoBot.Config.CommandPrefixes.Help}h \"Command name\"` (for example `-h \"!m q\"`)\n" + $"For a specific command help, use `{NadekoBot.Config.CommandPrefixes.Help}h \"Command name\"` (for example `-h \"!m q\"`)\n" +
"**LIST OF COMMANDS CAN BE FOUND ON THIS LINK**\n\n <https://github.com/Kwoth/NadekoBot/blob/master/commandlist.md>"; "**LIST OF COMMANDS CAN BE FOUND ON THIS LINK**\n\n <https://github.com/Kwoth/NadekoBot/blob/master/commandlist.md>";
public Action<CommandEventArgs> DoGitFunc() => e => { public static string DMHelpString => NadekoBot.Config.DMHelpString;
public Action<CommandEventArgs> DoGitFunc() => e =>
{
string helpstr = string helpstr =
$@"######For more information and how to setup your own NadekoBot, go to: **http://github.com/Kwoth/NadekoBot/** $@"######For more information and how to setup your own NadekoBot, go to: **http://github.com/Kwoth/NadekoBot/**
######You can donate on paypal: `nadekodiscordbot@gmail.com` or Bitcoin `17MZz1JAqME39akMLrVT4XBPffQJ2n1EPa` ######You can donate on paypal: `nadekodiscordbot@gmail.com` or Bitcoin `17MZz1JAqME39akMLrVT4XBPffQJ2n1EPa`
@ -65,8 +73,10 @@ Version: `{NadekoStats.Instance.BotVersion}`";
string lastCategory = ""; string lastCategory = "";
foreach (var com in NadekoBot.Client.GetService<CommandService>().AllCommands) { foreach (var com in NadekoBot.Client.GetService<CommandService>().AllCommands)
if (com.Category != lastCategory) { {
if (com.Category != lastCategory)
{
helpstr += "\n### " + com.Category + " \n"; helpstr += "\n### " + com.Category + " \n";
helpstr += "Command and aliases | Description | Usage\n"; helpstr += "Command and aliases | Description | Usage\n";
helpstr += "----------------|--------------|-------\n"; helpstr += "----------------|--------------|-------\n";
@ -83,7 +93,8 @@ Version: `{NadekoStats.Instance.BotVersion}`";
#endif #endif
}; };
internal override void Init(CommandGroupBuilder cgb) { internal override void Init(CommandGroupBuilder cgb)
{
cgb.CreateCommand(Module.Prefix + "h") cgb.CreateCommand(Module.Prefix + "h")
.Alias(Module.Prefix + "help", NadekoBot.BotMention + " help", NadekoBot.BotMention + " h", "~h") .Alias(Module.Prefix + "help", NadekoBot.BotMention + " help", NadekoBot.BotMention + " h", "~h")
.Description("Either shows a help for a single command, or PMs you help link if no arguments are specified.\n**Usage**: '-h !m q' or just '-h' ") .Description("Either shows a help for a single command, or PMs you help link if no arguments are specified.\n**Usage**: '-h !m q' or just '-h' ")
@ -107,7 +118,8 @@ Version: `{NadekoStats.Instance.BotVersion}`";
cgb.CreateCommand(Module.Prefix + "donate") cgb.CreateCommand(Module.Prefix + "donate")
.Alias("~donate") .Alias("~donate")
.Description("Instructions for helping the project!") .Description("Instructions for helping the project!")
.Do(async e => { .Do(async e =>
{
await e.Channel.SendMessage( await e.Channel.SendMessage(
@"I've created a **paypal** email for nadeko, so if you wish to support the project, you can send your donations to `nadekodiscordbot@gmail.com` @"I've created a **paypal** email for nadeko, so if you wish to support the project, you can send your donations to `nadekodiscordbot@gmail.com`
Don't forget to leave your discord name or id in the message, so that I can reward people who help out. Don't forget to leave your discord name or id in the message, so that I can reward people who help out.
@ -118,7 +130,8 @@ You can join nadekobot server by simply private messaging NadekoBot, and you wil
}); });
} }
private static string PrintCommandHelp(Command com) { private static string PrintCommandHelp(Command com)
{
var str = "`" + com.Text + "`"; var str = "`" + com.Text + "`";
str = com.Aliases.Aggregate(str, (current, a) => current + (", `" + a + "`")); str = com.Aliases.Aggregate(str, (current, a) => current + (", `" + a + "`"));
str += " **Description:** " + com.Description + "\n"; str += " **Description:** " + com.Description + "\n";

View File

@ -27,6 +27,7 @@ namespace NadekoBot
public static Configuration Config { get; set; } public static Configuration Config { get; set; }
public static LocalizedStrings Locale { get; set; } = new LocalizedStrings(); public static LocalizedStrings Locale { get; set; } = new LocalizedStrings();
public static string BotMention { get; set; } = ""; public static string BotMention { get; set; } = "";
public static bool Ready { get; set; } = false;
private static Channel OwnerPrivateChannel { get; set; } private static Channel OwnerPrivateChannel { get; set; }
@ -167,7 +168,7 @@ namespace NadekoBot
modules.Add(new Conversations(), "Conversations", ModuleFilter.None); modules.Add(new Conversations(), "Conversations", ModuleFilter.None);
modules.Add(new GamblingModule(), "Gambling", ModuleFilter.None); modules.Add(new GamblingModule(), "Gambling", ModuleFilter.None);
modules.Add(new GamesModule(), "Games", ModuleFilter.None); modules.Add(new GamesModule(), "Games", ModuleFilter.None);
modules.Add(new Music(), "Music", ModuleFilter.None); //modules.Add(new Music(), "Music", ModuleFilter.None);
modules.Add(new Searches(), "Searches", ModuleFilter.None); modules.Add(new Searches(), "Searches", ModuleFilter.None);
modules.Add(new NSFW(), "NSFW", ModuleFilter.None); modules.Add(new NSFW(), "NSFW", ModuleFilter.None);
modules.Add(new ClashOfClans(), "ClashOfClans", ModuleFilter.None); modules.Add(new ClashOfClans(), "ClashOfClans", ModuleFilter.None);
@ -209,8 +210,6 @@ namespace NadekoBot
Console.WriteLine("Failed creating private channel with the first owner listed in credentials.json"); Console.WriteLine("Failed creating private channel with the first owner listed in credentials.json");
} }
Classes.Permissions.PermissionsHandler.Initialize();
Client.ClientAPI.SendingRequest += (s, e) => Client.ClientAPI.SendingRequest += (s, e) =>
{ {
var request = e.Request as Discord.API.Client.Rest.SendMessageRequest; var request = e.Request as Discord.API.Client.Rest.SendMessageRequest;
@ -219,6 +218,10 @@ namespace NadekoBot
if (string.IsNullOrWhiteSpace(request.Content)) if (string.IsNullOrWhiteSpace(request.Content))
e.Cancel = true; e.Cancel = true;
}; };
//await Task.Delay(90000);
Classes.Permissions.PermissionsHandler.Initialize();
NadekoBot.Ready = true;
}); });
Console.WriteLine("Exiting..."); Console.WriteLine("Exiting...");
Console.ReadKey(); Console.ReadKey();
@ -260,13 +263,14 @@ namespace NadekoBot
} }
} }
if (Config.ForwardMessages && OwnerPrivateChannel != null) if (Config.ForwardMessages && !NadekoBot.Creds.OwnerIds.Contains(e.User.Id) && OwnerPrivateChannel != null)
await OwnerPrivateChannel.SendMessage(e.User + ": ```\n" + e.Message.Text + "\n```"); await OwnerPrivateChannel.SendMessage(e.User + ": ```\n" + e.Message.Text + "\n```");
if (repliedRecently) return; if (repliedRecently) return;
repliedRecently = true; repliedRecently = true;
await e.Channel.SendMessage(HelpCommand.HelpString); if (e.Message.RawText != "-h")
await e.Channel.SendMessage(HelpCommand.DMHelpString);
await Task.Delay(2000); await Task.Delay(2000);
repliedRecently = false; repliedRecently = false;
} }

View File

@ -72,5 +72,6 @@
"https://49.media.tumblr.com/8e8a099c4eba22abd3ec0f70fd087cce/tumblr_nxovj9oY861ur1mffo1_500.gif " "https://49.media.tumblr.com/8e8a099c4eba22abd3ec0f70fd087cce/tumblr_nxovj9oY861ur1mffo1_500.gif "
], ],
"CurrencySign": "🌸", "CurrencySign": "🌸",
"CurrencyName": "NadekoFlower" "CurrencyName": "NadekoFlower",
"DMHelpString": "Type `-h` for help."
} }