Slight changes. Couldn't get commandprices to work for now

This commit is contained in:
Kwoth 2017-01-14 17:37:11 +01:00
parent b2e6d6729e
commit 3d71e550ce
10 changed files with 234 additions and 27 deletions

View File

@ -4,8 +4,6 @@ using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Migrations;
using NadekoBot.Services.Database; using NadekoBot.Services.Database;
using NadekoBot.Services.Database.Models;
using NadekoBot.Modules.Music.Classes;
namespace NadekoBot.Migrations namespace NadekoBot.Migrations
{ {

View File

@ -0,0 +1,101 @@
using Discord;
using Discord.Commands;
using NadekoBot.Attributes;
using NadekoBot.Extensions;
using NadekoBot.Services;
using NadekoBot.Services.Database;
using NadekoBot.Services.Database.Models;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Permissions
{
public partial class Permissions
{
[Group]
public class CommandCostCommands : ModuleBase
{
private static readonly ConcurrentDictionary<string, int> _commandCosts = new ConcurrentDictionary<string, int>();
public static IReadOnlyDictionary<string, int> CommandCosts => _commandCosts;
static CommandCostCommands()
{
//_commandCosts = new ConcurrentDictionary<string, int>(NadekoBot.BotConfig.CommandCosts.ToDictionary(
// x => x.CommandName.Trim().ToUpperInvariant(),
// x => x.Cost));
}
[NadekoCommand, Usage, Description, Aliases]
public async Task CmdCosts(int page = 1)
{
var prices = _commandCosts.ToList();
if (!prices.Any())
{
await Context.Channel.SendConfirmAsync("No costs set.").ConfigureAwait(false);
return;
}
await Context.Channel.SendPaginatedConfirmAsync(page, (curPage) => {
var embed = new EmbedBuilder().WithOkColor()
.WithTitle("Command Costs");
var current = prices.Skip((curPage - 1) * 9)
.Take(9);
foreach (var price in current)
{
embed.AddField(efb => efb.WithName(price.Key).WithValue(price.Value.ToString()).WithIsInline(true));
}
return embed;
}, prices.Count / 9).ConfigureAwait(false);
}
//[NadekoCommand, Usage, Description, Aliases]
//public async Task CommandCost(int cost, CommandInfo cmd)
//{
// if (cost < 0)
// return;
// var cmdName = cmd.Aliases.First().ToLowerInvariant();
// var cmdPrice = new CommandCost()
// {
// CommandName = cmdName,
// Cost = cost
// };
// using (var uow = DbHandler.UnitOfWork())
// {
// var bc = uow.BotConfig.GetOrCreate();
// if (cost != 0)
// {
// var elem = bc.CommandCosts.Where(cc => cc.CommandName == cmdPrice.CommandName).FirstOrDefault();
// if (elem == null)
// bc.CommandCosts.Add(cmdPrice);
// else
// elem.Cost = cost;
// _commandCosts.AddOrUpdate(cmdName, cost, (key, old) => cost);
// }
// else
// {
// bc.CommandCosts.RemoveAt(bc.CommandCosts.IndexOf(cmdPrice));
// int throwaway;
// _commandCosts.TryRemove(cmdName, out throwaway);
// }
// await uow.CompleteAsync().ConfigureAwait(false);
// }
// if (cost == 0)
// await Context.Channel.SendConfirmAsync($"Removed the cost from the {Format.Bold(cmd.Name)} command.").ConfigureAwait(false);
// else
// await Context.Channel.SendConfirmAsync($"{Format.Bold(cmd.Name)} now costs {cost}{NadekoBot.BotConfig.CurrencySign} to run.").ConfigureAwait(false);
//}
}
}
}

View File

@ -1760,6 +1760,33 @@ namespace NadekoBot.Resources {
} }
} }
/// <summary>
/// Looks up a localized string similar to cmdcosts.
/// </summary>
public static string cmdcosts_cmd {
get {
return ResourceManager.GetString("cmdcosts_cmd", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Shows a list of command costs. Paginated with 9 command per page..
/// </summary>
public static string cmdcosts_desc {
get {
return ResourceManager.GetString("cmdcosts_desc", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to `{0}cmdcosts` or `{0}cmdcosts 2`.
/// </summary>
public static string cmdcosts_usage {
get {
return ResourceManager.GetString("cmdcosts_usage", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to color clr. /// Looks up a localized string similar to color clr.
/// </summary> /// </summary>
@ -1787,6 +1814,33 @@ namespace NadekoBot.Resources {
} }
} }
/// <summary>
/// Looks up a localized string similar to commandcost cmdcost.
/// </summary>
public static string commandcost_cmd {
get {
return ResourceManager.GetString("commandcost_cmd", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Sets a price for a command. Running that command will take currency from users. Set 0 to remove the price..
/// </summary>
public static string commandcost_desc {
get {
return ResourceManager.GetString("commandcost_desc", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to `{0}cmdcost 0 !!q` or `{0}cmdcost 1 &gt;8ball`.
/// </summary>
public static string commandcost_usage {
get {
return ResourceManager.GetString("commandcost_usage", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to commands cmds. /// Looks up a localized string similar to commands cmds.
/// </summary> /// </summary>

View File

@ -2925,4 +2925,22 @@
<data name="antispamignore_usage" xml:space="preserve"> <data name="antispamignore_usage" xml:space="preserve">
<value>`{0}antispamignore`</value> <value>`{0}antispamignore`</value>
</data> </data>
<data name="cmdcosts_cmd" xml:space="preserve">
<value>cmdcosts</value>
</data>
<data name="cmdcosts_desc" xml:space="preserve">
<value>Shows a list of command costs. Paginated with 9 command per page.</value>
</data>
<data name="cmdcosts_usage" xml:space="preserve">
<value>`{0}cmdcosts` or `{0}cmdcosts 2`</value>
</data>
<data name="commandcost_cmd" xml:space="preserve">
<value>commandcost cmdcost</value>
</data>
<data name="commandcost_desc" xml:space="preserve">
<value>Sets a price for a command. Running that command will take currency from users. Set 0 to remove the price.</value>
</data>
<data name="commandcost_usage" xml:space="preserve">
<value>`{0}cmdcost 0 !!q` or `{0}cmdcost 1 &gt;8ball`</value>
</data>
</root> </root>

View File

@ -32,9 +32,9 @@ namespace NadekoBot.Services
{ {
public const int GlobalCommandsCooldown = 1500; public const int GlobalCommandsCooldown = 1500;
private ShardedDiscordClient _client; private readonly ShardedDiscordClient _client;
private CommandService _commandService; private readonly CommandService _commandService;
private Logger _log; private readonly Logger _log;
private List<IDMChannel> ownerChannels { get; set; } private List<IDMChannel> ownerChannels { get; set; }
@ -100,8 +100,8 @@ namespace NadekoBot.Services
BlacklistCommands.BlacklistedChannels.Contains(usrMsg.Channel.Id) || BlacklistCommands.BlacklistedChannels.Contains(usrMsg.Channel.Id) ||
BlacklistCommands.BlacklistedUsers.Contains(usrMsg.Author.Id); BlacklistCommands.BlacklistedUsers.Contains(usrMsg.Author.Id);
const float oneThousandth = 1.0f / 1000;
private async Task LogSuccessfulExecution(SocketUserMessage usrMsg, ExecuteCommandResult exec, SocketTextChannel channel, Stopwatch sw) private async Task LogSuccessfulExecution(SocketUserMessage usrMsg, ExecuteCommandResult exec, SocketTextChannel channel, int ticks)
{ {
await CommandExecuted(usrMsg, exec.CommandInfo).ConfigureAwait(false); await CommandExecuted(usrMsg, exec.CommandInfo).ConfigureAwait(false);
_log.Info("Command Executed after {4}s\n\t" + _log.Info("Command Executed after {4}s\n\t" +
@ -113,10 +113,10 @@ namespace NadekoBot.Services
(channel == null ? "PRIVATE" : channel.Guild.Name + " [" + channel.Guild.Id + "]"), // {1} (channel == null ? "PRIVATE" : channel.Guild.Name + " [" + channel.Guild.Id + "]"), // {1}
(channel == null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]"), // {2} (channel == null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]"), // {2}
usrMsg.Content, // {3} usrMsg.Content, // {3}
sw.Elapsed.TotalSeconds); ticks * oneThousandth);
} }
private void LogErroredExecution(SocketUserMessage usrMsg, ExecuteCommandResult exec, SocketTextChannel channel, Stopwatch sw) private void LogErroredExecution(SocketUserMessage usrMsg, ExecuteCommandResult exec, SocketTextChannel channel, int ticks)
{ {
_log.Warn("Command Errored after {5}s\n\t" + _log.Warn("Command Errored after {5}s\n\t" +
"User: {0}\n\t" + "User: {0}\n\t" +
@ -129,7 +129,7 @@ namespace NadekoBot.Services
(channel == null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]"), // {2} (channel == null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]"), // {2}
usrMsg.Content,// {3} usrMsg.Content,// {3}
exec.Result.ErrorReason, // {4} exec.Result.ErrorReason, // {4}
sw.Elapsed.TotalSeconds // {5} ticks * oneThousandth // {5}
); );
} }
@ -187,6 +187,8 @@ namespace NadekoBot.Services
if (msg.Author.IsBot || !NadekoBot.Ready) //no bots, wait until bot connected and initialized if (msg.Author.IsBot || !NadekoBot.Ready) //no bots, wait until bot connected and initialized
return; return;
var execTime = Environment.TickCount;
var usrMsg = msg as SocketUserMessage; var usrMsg = msg as SocketUserMessage;
if (usrMsg == null) //has to be an user message, not system/other messages. if (usrMsg == null) //has to be an user message, not system/other messages.
return; return;
@ -226,17 +228,16 @@ namespace NadekoBot.Services
string messageContent = usrMsg.Content; string messageContent = usrMsg.Content;
// execute the command and measure the time it took // execute the command and measure the time it took
var sw = Stopwatch.StartNew();
var exec = await ExecuteCommand(new CommandContext(_client.MainClient, usrMsg), messageContent, DependencyMap.Empty, MultiMatchHandling.Best); var exec = await ExecuteCommand(new CommandContext(_client.MainClient, usrMsg), messageContent, DependencyMap.Empty, MultiMatchHandling.Best);
sw.Stop(); execTime = Environment.TickCount - execTime;
if (exec.Result.IsSuccess) if (exec.Result.IsSuccess)
{ {
await LogSuccessfulExecution(usrMsg, exec, channel, sw).ConfigureAwait(false); await LogSuccessfulExecution(usrMsg, exec, channel, execTime).ConfigureAwait(false);
} }
else if (!exec.Result.IsSuccess && exec.Result.Error != CommandError.UnknownCommand) else if (!exec.Result.IsSuccess && exec.Result.Error != CommandError.UnknownCommand)
{ {
LogErroredExecution(usrMsg, exec, channel, sw); LogErroredExecution(usrMsg, exec, channel, execTime);
if (guild != null && exec.CommandInfo != null && exec.Result.Error == CommandError.Exception) if (guild != null && exec.CommandInfo != null && exec.Result.Error == CommandError.Exception)
{ {
if (exec.PermissionCache != null && exec.PermissionCache.Verbose) if (exec.PermissionCache != null && exec.PermissionCache.Verbose)
@ -354,6 +355,16 @@ namespace NadekoBot.Services
return new ExecuteCommandResult(cmd, pc, SearchResult.FromError(CommandError.Exception, $"You need the **{pc.PermRole}** role in order to use permission commands.")); return new ExecuteCommandResult(cmd, pc, SearchResult.FromError(CommandError.Exception, $"You need the **{pc.PermRole}** role in order to use permission commands."));
} }
} }
int price;
if (Permissions.CommandCostCommands.CommandCosts.TryGetValue(cmd.Aliases.First().Trim().ToLowerInvariant(), out price) && price > 0)
{
var success = await CurrencyHandler.RemoveCurrencyAsync(context.User.Id, $"Running {cmd.Name} command.", price).ConfigureAwait(false);
if (!success)
{
return new ExecuteCommandResult(cmd, pc, SearchResult.FromError(CommandError.Exception, $"Insufficient funds. You need {price}{NadekoBot.BotConfig.CurrencySign} to run this command."));
}
}
} }

View File

@ -31,6 +31,11 @@ namespace NadekoBot.Services.Database.Models
public float Betroll67Multiplier { get; set; } = 2; public float Betroll67Multiplier { get; set; } = 2;
public float Betroll91Multiplier { get; set; } = 3; public float Betroll91Multiplier { get; set; } = 3;
public float Betroll100Multiplier { get; set; } = 10; public float Betroll100Multiplier { get; set; } = 10;
//public HashSet<CommandCost> CommandCosts { get; set; } = new HashSet<CommandCost>();
/// <summary>
/// I messed up, don't use
/// </summary>
public HashSet<CommandPrice> CommandPrices { get; set; } = new HashSet<CommandPrice>(); public HashSet<CommandPrice> CommandPrices { get; set; } = new HashSet<CommandPrice>();

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NadekoBot.Services.Database.Models
{
public class CommandCost : DbEntity
{
public int Cost { get; set; }
public string CommandName { get; set; }
public override int GetHashCode() =>
CommandName.GetHashCode();
public override bool Equals(object obj)
{
var instance = obj as CommandCost;
if (instance == null)
return false;
return instance.CommandName == CommandName;
}
}
}

View File

@ -11,18 +11,5 @@ namespace NadekoBot.Services.Database.Models
public int Price { get; set; } public int Price { get; set; }
//this is unique //this is unique
public string CommandName { get; set; } public string CommandName { get; set; }
public override int GetHashCode() =>
CommandName.GetHashCode();
public override bool Equals(object obj)
{
var instance = obj as CommandPrice;
if (instance == null)
return false;
return instance.CommandName == CommandName;
}
} }
} }

View File

@ -235,9 +235,14 @@ namespace NadekoBot.Services.Database
#endregion #endregion
#region CommandPrice #region CommandPrice
//well, i failed
modelBuilder.Entity<CommandPrice>() modelBuilder.Entity<CommandPrice>()
.HasIndex(cp => cp.Price) .HasIndex(cp => cp.Price)
.IsUnique(); .IsUnique();
//modelBuilder.Entity<CommandCost>()
// .HasIndex(cp => cp.CommandName)
// .IsUnique();
#endregion #endregion
} }
} }

View File

@ -17,6 +17,7 @@ namespace NadekoBot.Services.Database.Repositories.Impl
.Include(bc => bc.Blacklist) .Include(bc => bc.Blacklist)
.Include(bc => bc.EightBallResponses) .Include(bc => bc.EightBallResponses)
.Include(bc => bc.ModulePrefixes) .Include(bc => bc.ModulePrefixes)
//.Include(bc => bc.CommandCosts)
.FirstOrDefault(); .FirstOrDefault();
if (config == null) if (config == null)