Added as much gambling as possible without drawing

This commit is contained in:
Kwoth 2016-08-30 00:00:19 +02:00
parent 687fedca75
commit 5dd55bbc0a
15 changed files with 491 additions and 352 deletions

View File

@ -8,7 +8,7 @@ using NadekoBot.Services.Database.Impl;
namespace NadekoBot.Migrations namespace NadekoBot.Migrations
{ {
[DbContext(typeof(NadekoSqliteContext))] [DbContext(typeof(NadekoSqliteContext))]
[Migration("20160828153124_first")] [Migration("20160829215759_first")]
partial class first partial class first
{ {
protected override void BuildTargetModel(ModelBuilder modelBuilder) protected override void BuildTargetModel(ModelBuilder modelBuilder)

View File

@ -30,10 +30,10 @@ namespace NadekoBot.Modules.Administration
public Repeater Repeater { get; } public Repeater Repeater { get; }
public ITextChannel Channel { get; } public ITextChannel Channel { get; }
public RepeatRunner(Repeater repeater) public RepeatRunner(Repeater repeater, ITextChannel channel = null)
{ {
this.Repeater = repeater; this.Repeater = repeater;
this.Channel = NadekoBot.Client.GetGuild(repeater.GuildId)?.GetTextChannel(repeater.ChannelId); this.Channel = channel ?? NadekoBot.Client.GetGuild(repeater.GuildId)?.GetTextChannel(repeater.ChannelId);
if (Channel == null) if (Channel == null)
return; return;
Task.Run(Run); Task.Run(Run);
@ -89,22 +89,15 @@ namespace NadekoBot.Modules.Administration
return; return;
} }
rep.Reset(); rep.Reset();
await channel.SendMessageAsync("🔄 " + rep.Repeater.Message); await channel.SendMessageAsync("🔄 " + rep.Repeater.Message).ConfigureAwait(false);
} }
[LocalizedCommand, LocalizedDescription, LocalizedSummary] [LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
public async Task Repeat(IUserMessage imsg, int minutes, [Remainder] string message = null) public async Task Repeat(IUserMessage imsg)
{ {
var channel = (ITextChannel)imsg.Channel; var channel = (ITextChannel)imsg.Channel;
if (minutes < 1 || minutes > 1500)
return;
RepeatRunner rep; RepeatRunner rep;
if (string.IsNullOrWhiteSpace(message)) //turn off
{
if (repeaters.TryRemove(channel.Id, out rep)) if (repeaters.TryRemove(channel.Id, out rep))
{ {
using (var uow = DbHandler.UnitOfWork()) using (var uow = DbHandler.UnitOfWork())
@ -117,9 +110,22 @@ namespace NadekoBot.Modules.Administration
} }
else else
await channel.SendMessageAsync("`No message is repeating.`").ConfigureAwait(false); await channel.SendMessageAsync("`No message is repeating.`").ConfigureAwait(false);
return;
} }
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Repeat(IUserMessage imsg, int minutes, [Remainder] string message)
{
var channel = (ITextChannel)imsg.Channel;
if (minutes < 1 || minutes > 1500)
return;
if (string.IsNullOrWhiteSpace(message))
return;
RepeatRunner rep;
rep = repeaters.AddOrUpdate(channel.Id, (cid) => rep = repeaters.AddOrUpdate(channel.Id, (cid) =>
{ {
using (var uow = DbHandler.UnitOfWork()) using (var uow = DbHandler.UnitOfWork())
@ -133,7 +139,7 @@ namespace NadekoBot.Modules.Administration
}; };
uow.Repeaters.Add(localRep); uow.Repeaters.Add(localRep);
uow.Complete(); uow.Complete();
return new RepeatRunner(localRep); return new RepeatRunner(localRep, channel);
} }
}, (cid, old) => }, (cid, old) =>
{ {
@ -147,8 +153,9 @@ namespace NadekoBot.Modules.Administration
old.Reset(); old.Reset();
return old; return old;
}); });
}
await channel.SendMessageAsync($"Repeating \"{rep.Repeater.Message}\" every {rep.Repeater.Interval} minutes").ConfigureAwait(false);
}
} }
} }
} }

View File

@ -41,17 +41,10 @@ namespace NadekoBot.Modules.Gambling
if (amount < 0) if (amount < 0)
amount = 0; amount = 0;
//todo DB if (amount > 0)
//var userFlowers = Gambling.GetUserFlowers(umsg.Author.Id); if(!await CurrencyHandler.RemoveCurrencyAsync((IGuildUser)umsg.Author, "BetRace", amount, true).ConfigureAwait(false))
await channel.SendMessageAsync($"{umsg.Author.Mention} You don't have enough {Gambling.CurrencyName}s.").ConfigureAwait(false);
//if (userFlowers < amount)
//{
// await channel.SendMessageAsync($"{umsg.Author.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false);
// return;
//}
//if (amount > 0)
// await FlowersHandler.RemoveFlowers(umsg.Author, "BetRace", (int)amount, true).ConfigureAwait(false);
AnimalRace ar; AnimalRace ar;
if (!AnimalRaces.TryGetValue(channel.Guild.Id, out ar)) if (!AnimalRaces.TryGetValue(channel.Guild.Id, out ar))
@ -116,9 +109,9 @@ namespace NadekoBot.Modules.Gambling
{ {
await raceChannel.SendMessageAsync("🏁`Race failed to start since there was not enough participants.`"); await raceChannel.SendMessageAsync("🏁`Race failed to start since there was not enough participants.`");
var p = participants.FirstOrDefault(); var p = participants.FirstOrDefault();
//todo DB
//if (p != null) if (p != null)
// await FlowersHandler.AddFlowersAsync(p.User, "BetRace", p.AmountBet, true).ConfigureAwait(false); await CurrencyHandler.AddCurrencyAsync(p.User, "BetRace", p.AmountBet, true).ConfigureAwait(false);
End(); End();
return; return;
} }
@ -191,8 +184,8 @@ namespace NadekoBot.Modules.Gambling
if (winner.AmountBet > 0) if (winner.AmountBet > 0)
{ {
var wonAmount = winner.AmountBet * (participants.Count - 1); var wonAmount = winner.AmountBet * (participants.Count - 1);
//todo DB
//await FlowersHandler.AddFlowersAsync(winner.User, "Won a Race", wonAmount).ConfigureAwait(false); await CurrencyHandler.AddCurrencyAsync(winner.User, "Won a Race", wonAmount, false).ConfigureAwait(false);
await raceChannel.SendMessageAsync($"🏁 {winner.User.Mention} as {winner.Animal} **Won the race and {wonAmount}{CurrencySign}!**").ConfigureAwait(false); await raceChannel.SendMessageAsync($"🏁 {winner.User.Mention} as {winner.Animal} **Won the race and {wonAmount}{CurrencySign}!**").ConfigureAwait(false);
} }
else else

View File

@ -13,20 +13,21 @@ namespace NadekoBot.Modules.Gambling
public partial class Gambling public partial class Gambling
{ {
private Regex dndRegex { get; } = new Regex(@"(?<n1>\d+)d(?<n2>\d+)", RegexOptions.Compiled); private Regex dndRegex { get; } = new Regex(@"(?<n1>\d+)d(?<n2>\d+)", RegexOptions.Compiled);
////todo drawing
//[LocalizedCommand, LocalizedDescription, LocalizedSummary]
//[RequireContext(ContextType.Guild)]
//public Task Roll(IUserMessage umsg, [Remainder] string arg = null) =>
// InternalRoll(umsg, arg, true);
//[LocalizedCommand, LocalizedDescription, LocalizedSummary] [LocalizedCommand, LocalizedDescription, LocalizedSummary]
//[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
//public Task Rolluo(IUserMessage umsg, [Remainder] string arg = null) => public Task Roll(IUserMessage umsg, [Remainder] string arg = null) =>
// InternalRoll(umsg, arg, false); InternalRoll(umsg, arg, true);
//private async Task InternalRoll(IUserMessage umsg, string arg, bool ordered) { [LocalizedCommand, LocalizedDescription, LocalizedSummary]
// var channel = (ITextChannel)umsg.Channel; [RequireContext(ContextType.Guild)]
// var r = new Random(); public Task Rolluo(IUserMessage umsg, [Remainder] string arg = null) =>
InternalRoll(umsg, arg, false);
//todo drawing
private async Task InternalRoll(IUserMessage umsg, string arg, bool ordered)
{
var channel = (ITextChannel)umsg.Channel;
var r = new Random();
//if (string.IsNullOrWhiteSpace(arg)) //if (string.IsNullOrWhiteSpace(arg))
//{ //{
// var gen = r.Next(0, 101); // var gen = r.Next(0, 101);
@ -39,25 +40,25 @@ namespace NadekoBot.Modules.Gambling
// await channel.SendFileAsync(imageStream, "dice.png").ConfigureAwait(false); // await channel.SendFileAsync(imageStream, "dice.png").ConfigureAwait(false);
// return; // return;
//} //}
// Match m; Match m;
// if ((m = dndRegex.Match(arg)).Length != 0) if ((m = dndRegex.Match(arg)).Length != 0)
// { {
// int n1; int n1;
// int n2; int n2;
// if (int.TryParse(m.Groups["n1"].ToString(), out n1) && if (int.TryParse(m.Groups["n1"].ToString(), out n1) &&
// int.TryParse(m.Groups["n2"].ToString(), out n2) && int.TryParse(m.Groups["n2"].ToString(), out n2) &&
// n1 <= 50 && n2 <= 100000 && n1 > 0 && n2 > 0) n1 <= 50 && n2 <= 100000 && n1 > 0 && n2 > 0)
// { {
// var arr = new int[n1]; var arr = new int[n1];
// for (int i = 0; i < n1; i++) for (int i = 0; i < n1; i++)
// { {
// arr[i] = r.Next(1, n2 + 1); arr[i] = r.Next(1, n2 + 1);
// } }
// var elemCnt = 0; var elemCnt = 0;
// await channel.SendMessageAsync($"`Rolled {n1} {(n1 == 1 ? "die" : "dice")} 1-{n2}.`\n`Result:` " + string.Join(", ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => elemCnt++ % 2 == 0 ? $"**{x}**" : x.ToString()))).ConfigureAwait(false); await channel.SendMessageAsync($"`Rolled {n1} {(n1 == 1 ? "die" : "dice")} 1-{n2}.`\n`Result:` " + string.Join(", ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => elemCnt++ % 2 == 0 ? $"**{x}**" : x.ToString()))).ConfigureAwait(false);
// } }
// return; return;
// } }
//try //try
//{ //{
// var num = int.Parse(e.Args[0]); // var num = int.Parse(e.Args[0]);
@ -103,7 +104,7 @@ namespace NadekoBot.Modules.Gambling
//{ //{
// await channel.SendMessageAsync("Please enter a number of dice to roll.").ConfigureAwait(false); // await channel.SendMessageAsync("Please enter a number of dice to roll.").ConfigureAwait(false);
//} //}
//} }
[LocalizedCommand, LocalizedDescription, LocalizedSummary] [LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]

View File

@ -1,99 +1,30 @@
//using Discord.Commands; using Discord;
//using NadekoBot.Classes; using Discord.Commands;
//using NadekoBot.Extensions;
//using System; //todo drawing
//using System.Drawing; namespace NadekoBot.Modules.Gambling
//using System.Threading.Tasks; {
[Group]
public class FlipCoinCommands
{
public FlipCoinCommands() { }
////todo drawing ////todo drawing
//namespace NadekoBot.Modules.Gambling //[LocalizedCommand, LocalizedDescription, LocalizedSummary]
//[RequireContext(ContextType.Guild)]
//public async Task Flip(IUserMessage imsg, int count = 0)
//{ //{
// internal class FlipCoinCommand : DiscordCommand // var channel = (ITextChannel)imsg.Channel;
// { // if (count == 0)
// public FlipCoinCommand(DiscordModule module) : base(module) { }
// internal override void Init(CommandGroupBuilder cgb)
// {
// cgb.CreateCommand(Module.Prefix + "flip")
// .Description($"Flips coin(s) - heads or tails, and shows an image. | `{Prefix}flip` or `{Prefix}flip 3`")
// .Parameter("count", ParameterType.Optional)
// .Do(FlipCoinFunc());
// cgb.CreateCommand(Module.Prefix + "betflip")
// .Alias(Prefix+"bf")
// .Description($"Bet to guess will the result be heads or tails. Guessing award you double flowers you've bet. | `{Prefix}bf 5 heads` or `{Prefix}bf 3 t`")
// .Parameter("amount", ParameterType.Required)
// .Parameter("guess", ParameterType.Required)
// .Do(BetFlipCoinFunc());
// }
// private readonly Random rng = new Random();
// public Func<CommandEventArgs, Task> BetFlipCoinFunc() => async e =>
// {
// var amountstr = amount.Trim();
// var guessStr = guess.Trim().ToUpperInvariant();
// if (guessStr != "H" && guessStr != "T" && guessStr != "HEADS" && guessStr != "TAILS")
// return;
// int amount;
// if (!int.TryParse(amountstr, out amount) || amount < 1)
// return;
// var userFlowers = Gambling.GetUserFlowers(umsg.Author.Id);
// if (userFlowers < amount)
// {
// await channel.SendMessageAsync($"{umsg.Author.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false);
// return;
// }
// await FlowersHandler.RemoveFlowers(umsg.Author, "Betflip Gamble", (int)amount, true).ConfigureAwait(false);
// //heads = true
// //tails = false
// var guess = guessStr == "HEADS" || guessStr == "H";
// bool result = false;
// if (rng.Next(0, 2) == 1) {
// await e.Channel.SendFile("heads.png", Properties.Resources.heads.ToStream(System.Drawing.Imaging.ImageFormat.Png)).ConfigureAwait(false);
// result = true;
// }
// else {
// await e.Channel.SendFile("tails.png", Properties.Resources.tails.ToStream(System.Drawing.Imaging.ImageFormat.Png)).ConfigureAwait(false);
// }
// string str;
// if (guess == result)
// {
// str = $"{umsg.Author.Mention}`You guessed it!` You won {amount * 2}{NadekoBot.Config.CurrencySign}";
// await FlowersHandler.AddFlowersAsync(umsg.Author, "Betflip Gamble", amount * 2, true).ConfigureAwait(false);
// }
// else
// str = $"{umsg.Author.Mention}`More luck next time.`";
// await channel.SendMessageAsync(str).ConfigureAwait(false);
// };
// public Func<CommandEventArgs, Task> FlipCoinFunc() => async e =>
// {
// if (count == "")
// { // {
// if (rng.Next(0, 2) == 1) // if (rng.Next(0, 2) == 1)
// await e.Channel.SendFile("heads.png", Properties.Resources.heads.ToStream(System.Drawing.Imaging.ImageFormat.Png)).ConfigureAwait(false); // await channel.SendFileAsync("heads.png", ).ConfigureAwait(false);
// else // else
// await e.Channel.SendFile("tails.png", Properties.Resources.tails.ToStream(System.Drawing.Imaging.ImageFormat.Png)).ConfigureAwait(false); // await channel.SendFileAsync("tails.png", ).ConfigureAwait(false);
// return;
// } // }
// else
// {
// int result;
// if (int.TryParse(count, out result))
// {
// if (result > 10) // if (result > 10)
// result = 10; // result = 10;
// var imgs = new Image[result]; // var imgs = new Image[result];
@ -103,11 +34,60 @@
// Properties.Resources.tails : // Properties.Resources.tails :
// Properties.Resources.heads; // Properties.Resources.heads;
// } // }
// await e.Channel.SendFile($"{result} coins.png", imgs.Merge().ToStream(System.Drawing.Imaging.ImageFormat.Png)).ConfigureAwait(false); // await channel.SendFile($"{result} coins.png", imgs.Merge().ToStream(System.Drawing.Imaging.ImageFormat.Png)).ConfigureAwait(false);
// return; // return;
// }
// await channel.SendMessageAsync("Invalid number").ConfigureAwait(false); // await channel.SendMessageAsync("Invalid number").ConfigureAwait(false);
//} //}
// };
//[LocalizedCommand, LocalizedDescription, LocalizedSummary]
//[RequireContext(ContextType.Guild)]
//public async Task Betflip(IUserMessage umsg, int amount, string guess)
//{
// var channel = (ITextChannel)umsg.Channel;
// var guildUser = (IGuildUser)umsg.Author;
// var guessStr = guess.Trim().ToUpperInvariant();
// if (guessStr != "H" && guessStr != "T" && guessStr != "HEADS" && guessStr != "TAILS")
// return;
// if (amount < 1)
// return;
// var userFlowers = Gambling.GetUserFlowers(umsg.Author.Id);
// if (userFlowers < amount)
// {
// await channel.SendMessageAsync($"{umsg.Author.Mention} You don't have enough {Gambling.CurrencyName}s. You only have {userFlowers}{Gambling.CurrencySign}.").ConfigureAwait(false);
// return;
// } // }
// await CurrencyHandler.RemoveCurrencyAsync(guildUser, "Betflip Gamble", amount, false).ConfigureAwait(false);
// //heads = true
// //tails = false
// var isHeads = guessStr == "HEADS" || guessStr == "H";
// bool result = false;
// var rng = new Random();
// if (rng.Next(0, 2) == 1)
// {
// await channel.SendFileAsync("heads.png", Properties.Resources.heads.ToStream(System.Drawing.Imaging.ImageFormat.Png)).ConfigureAwait(false);
// result = true;
// } // }
// else
// {
// await channel.SendFileAsync("tails.png", Properties.Resources.tails.ToStream(System.Drawing.Imaging.ImageFormat.Png)).ConfigureAwait(false);
// }
// string str;
// if (isHeads == result)
// {
// str = $"{umsg.Author.Mention}`You guessed it!` You won {amount * 2}{Gambling.CurrencySign}";
// await CurrencyHandler.AddCurrencyAsync((IGuildUser)umsg.Author, "Betflip Gamble", amount * 2, false).ConfigureAwait(false);
// }
// else
// str = $"{umsg.Author.Mention}`More luck next time.`";
// await channel.SendMessageAsync(str).ConfigureAwait(false);
//}
}
}

View File

@ -9,6 +9,8 @@ using System.Threading.Tasks;
using NadekoBot.Services; using NadekoBot.Services;
using Discord.WebSocket; using Discord.WebSocket;
using NadekoBot.Services.Database; using NadekoBot.Services.Database;
using NadekoBot.Services.Database.Models;
using System.Collections.Generic;
//todo DB //todo DB
namespace NadekoBot.Modules.Gambling namespace NadekoBot.Modules.Gambling
@ -45,44 +47,50 @@ namespace NadekoBot.Modules.Gambling
var membersArray = members as IUser[] ?? members.ToArray(); var membersArray = members as IUser[] ?? members.ToArray();
var usr = membersArray[new Random().Next(0, membersArray.Length)]; var usr = membersArray[new Random().Next(0, membersArray.Length)];
await channel.SendMessageAsync($"**Raffled user:** {usr.Username} (id: {usr.Id})").ConfigureAwait(false); await channel.SendMessageAsync($"**Raffled user:** {usr.Username} (id: {usr.Id})").ConfigureAwait(false);
} }
////todo DB [LocalizedCommand("$$$"), LocalizedDescription("$$$"), LocalizedSummary("$$$")]
//[LocalizedCommand("$$$"), LocalizedDescription("$$$"), LocalizedSummary("$$$")] [RequireContext(ContextType.Guild)]
//[RequireContext(ContextType.Guild)] public async Task Cash(IUserMessage umsg, [Remainder] IUser user = null)
//public async Task Cash(IUserMessage umsg, [Remainder] string arg) {
//{ var channel = (ITextChannel)umsg.Channel;
// var channel = (ITextChannel)umsg.Channel;
// var usr = e.Message.MentionedUsers.FirstOrDefault() ?? umsg.Author; user = user ?? umsg.Author;
// var pts = GetUserFlowers(usr.Id); long amount;
// var str = $"{usr.Name} has {pts} {NadekoBot.Config.CurrencySign}"; BotConfig config;
// await channel.SendMessageAsync(str).ConfigureAwait(false); using (var uow = DbHandler.UnitOfWork())
//} {
amount = uow.Currency.GetUserCurrency(user.Id);
config = uow.BotConfig.GetOrCreate();
}
////todo DB await channel.SendMessageAsync($"{user.Username} has {amount} {config.CurrencySign}").ConfigureAwait(false);
//[LocalizedCommand, LocalizedDescription, LocalizedSummary] }
//[RequireContext(ContextType.Guild)]
//public async Task Give(IUserMessage umsg, long amount, [Remainder] IUser receiver)
//{
// var channel = (ITextChannel)umsg.Channel;
// if (amount <= 0)
// return;
// var userFlowers = GetUserFlowers(umsg.Author.Id);
// if (userFlowers < amount) [LocalizedCommand, LocalizedDescription, LocalizedSummary]
// { [RequireContext(ContextType.Guild)]
// await channel.SendMessageAsync($"{umsg.Author.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false); public async Task Give(IUserMessage umsg, long amount, [Remainder] IUser receiver)
// return; {
// } var channel = (ITextChannel)umsg.Channel;
if (amount <= 0)
return;
bool success = false;
using (var uow = DbHandler.UnitOfWork())
{
success = uow.Currency.TryUpdateState(umsg.Author.Id, amount);
if(success)
uow.Currency.TryUpdateState(umsg.Author.Id, amount);
// await FlowersHandler.RemoveFlowers(umsg.Author, "Gift", (int)amount, true).ConfigureAwait(false); await uow.CompleteAsync();
// await FlowersHandler.AddFlowersAsync(receiver, "Gift", (int)amount).ConfigureAwait(false); }
if (!success)
{
await channel.SendMessageAsync($"{umsg.Author.Mention} You don't have enough {Gambling.CurrencyPluralName}s.").ConfigureAwait(false);
return;
}
// await channel.SendMessageAsync($"{umsg.Author.Mention} successfully sent {amount} {NadekoBot.Config.CurrencyName}s to {receiver.Mention}!").ConfigureAwait(false); await channel.SendMessageAsync($"{umsg.Author.Mention} successfully sent {amount} {Gambling.CurrencyPluralName}s to {receiver.Mention}!").ConfigureAwait(false);
}
//}
////todo DB ////todo DB
////todo owner only ////todo owner only
@ -100,9 +108,9 @@ namespace NadekoBot.Modules.Gambling
// if (amount <= 0) // if (amount <= 0)
// return; // return;
// await FlowersHandler.AddFlowersAsync(usrId, $"Awarded by bot owner. ({umsg.Author.Username}/{umsg.Author.Id})", (int)amount).ConfigureAwait(false); // await CurrencyHandler.AddFlowersAsync(usrId, $"Awarded by bot owner. ({umsg.Author.Username}/{umsg.Author.Id})", (int)amount).ConfigureAwait(false);
// await channel.SendMessageAsync($"{umsg.Author.Mention} successfully awarded {amount} {NadekoBot.Config.CurrencyName}s to <@{usrId}>!").ConfigureAwait(false); // await channel.SendMessageAsync($"{umsg.Author.Mention} successfully awarded {amount} {Gambling.CurrencyName}s to <@{usrId}>!").ConfigureAwait(false);
//} //}
////todo owner only ////todo owner only
@ -112,6 +120,7 @@ namespace NadekoBot.Modules.Gambling
//public Task Take(IUserMessage umsg, long amount, [Remainder] IGuildUser user) => //public Task Take(IUserMessage umsg, long amount, [Remainder] IGuildUser user) =>
// Take(umsg, amount, user.Id); // Take(umsg, amount, user.Id);
//todo owner only
//[LocalizedCommand, LocalizedDescription, LocalizedSummary] //[LocalizedCommand, LocalizedDescription, LocalizedSummary]
//[RequireContext(ContextType.Guild)] //[RequireContext(ContextType.Guild)]
//public async Task Take(IUserMessage umsg, long amount, [Remainder] ulong usrId) //public async Task Take(IUserMessage umsg, long amount, [Remainder] ulong usrId)
@ -120,76 +129,85 @@ namespace NadekoBot.Modules.Gambling
// if (amount <= 0) // if (amount <= 0)
// return; // return;
// await FlowersHandler.RemoveFlowers(usrId, $"Taken by bot owner.({umsg.Author.Username}/{umsg.Author.Id})", (int)amount).ConfigureAwait(false); // await CurrencyHandler.RemoveFlowers(usrId, $"Taken by bot owner.({umsg.Author.Username}/{umsg.Author.Id})", (int)amount).ConfigureAwait(false);
// await channel.SendMessageAsync($"{umsg.Author.Mention} successfully took {amount} {NadekoBot.Config.CurrencyName}s from <@{usrId}>!").ConfigureAwait(false); // await channel.SendMessageAsync($"{umsg.Author.Mention} successfully took {amount} {Gambling.CurrencyName}s from <@{usrId}>!").ConfigureAwait(false);
//} //}
//[LocalizedCommand, LocalizedDescription, LocalizedSummary] [LocalizedCommand, LocalizedDescription, LocalizedSummary]
//[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
//public async Task BetRoll(IUserMessage umsg, int amount) public async Task BetRoll(IUserMessage umsg, long amount)
//{ {
// var channel = (ITextChannel)umsg.Channel; var channel = (ITextChannel)umsg.Channel;
// if (amount < 1) if (amount < 1)
// return; return;
// var userFlowers = GetUserFlowers(umsg.Author.Id); var guildUser = (IGuildUser)umsg.Author;
// if (userFlowers < amount) long userFlowers;
// { using (var uow = DbHandler.UnitOfWork())
// await channel.SendMessageAsync($"{umsg.Author.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false); {
// return; userFlowers = uow.Currency.GetOrCreate(umsg.Id).Amount;
// } }
// await FlowersHandler.RemoveFlowers(umsg.Author, "Betroll Gamble", (int)amount, true).ConfigureAwait(false); if (userFlowers < amount)
{
await channel.SendMessageAsync($"{guildUser.Mention} You don't have enough {Gambling.CurrencyName}s. You only have {userFlowers}{Gambling.CurrencySign}.").ConfigureAwait(false);
return;
}
// var rng = new Random().Next(0, 101); await CurrencyHandler.RemoveCurrencyAsync(guildUser, "Betroll Gamble", amount, false).ConfigureAwait(false);
// var str = $"{umsg.Author.Mention} `You rolled {rng}.` ";
// if (rng < 67)
// {
// str += "Better luck next time.";
// }
// else if (rng < 90)
// {
// str += $"Congratulations! You won {amount * 2}{NadekoBot.Config.CurrencySign} for rolling above 66";
// await FlowersHandler.AddFlowersAsync(umsg.Author, "Betroll Gamble", amount * 2, true).ConfigureAwait(false);
// }
// else if (rng < 100)
// {
// str += $"Congratulations! You won {amount * 3}{NadekoBot.Config.CurrencySign} for rolling above 90.";
// await FlowersHandler.AddFlowersAsync(umsg.Author, "Betroll Gamble", amount * 3, true).ConfigureAwait(false);
// }
// else
// {
// str += $"👑 Congratulations! You won {amount * 10}{NadekoBot.Config.CurrencySign} for rolling **100**. 👑";
// await FlowersHandler.AddFlowersAsync(umsg.Author, "Betroll Gamble", amount * 10, true).ConfigureAwait(false);
// }
// await channel.SendMessageAsync(str).ConfigureAwait(false); var rng = new Random().Next(0, 101);
//} var str = $"{guildUser.Mention} `You rolled {rng}.` ";
if (rng < 67)
{
str += "Better luck next time.";
}
else if (rng < 90)
{
str += $"Congratulations! You won {amount * 2}{Gambling.CurrencySign} for rolling above 66";
await CurrencyHandler.AddCurrencyAsync(guildUser, "Betroll Gamble", amount * 2, false).ConfigureAwait(false);
}
else if (rng < 100)
{
str += $"Congratulations! You won {amount * 3}{Gambling.CurrencySign} for rolling above 90.";
await CurrencyHandler.AddCurrencyAsync(guildUser, "Betroll Gamble", amount * 3, false).ConfigureAwait(false);
}
else
{
str += $"👑 Congratulations! You won {amount * 10}{Gambling.CurrencySign} for rolling **100**. 👑";
await CurrencyHandler.AddCurrencyAsync(guildUser, "Betroll Gamble", amount * 10, false).ConfigureAwait(false);
}
////todo DB await channel.SendMessageAsync(str).ConfigureAwait(false);
// [LocalizedCommand, LocalizedDescription, LocalizedSummary] }
// [RequireContext(ContextType.Guild)]
// public async Task Leaderboard(IUserMessage umsg)
// {
// var channel = (ITextChannel)umsg.Channel;
// var richestTemp = DbHandler.Instance.GetTopRichest(); //todo DB
// var richest = richestTemp as CurrencyState[] ?? richestTemp.ToArray(); [LocalizedCommand, LocalizedDescription, LocalizedSummary]
// if (richest.Length == 0) [RequireContext(ContextType.Guild)]
// return; public async Task Leaderboard(IUserMessage umsg)
// await channel.SendMessageAsync( {
// richest.Aggregate(new StringBuilder( var channel = (ITextChannel)umsg.Channel;
//$@"```xl
//┏━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┓ IEnumerable<Currency> richest;
//┃ Id ┃ $$$ ┃ using (var uow = DbHandler.UnitOfWork())
//"), {
// (cur, cs) => cur.AppendLine( richest = uow.Currency.GetTopRichest(10);
//$@"┣━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━┫ }
//┃{(e.Server.Users.Where(u => u.Id == (ulong)cs.UserId).FirstOrDefault()?.Name.TrimTo(18, true) ?? cs.UserId.ToString()),-20} ┃ {cs.Value,5} ┃") if (!richest.Any())
// ).ToString() + "┗━━━━━━━━━━━━━━━━━━━━━┻━━━━━━━┛```").ConfigureAwait(false); return;
//} await channel.SendMessageAsync(
richest.Aggregate(new StringBuilder(
$@"```xl
Id $$$
"),
(cur, cs) => cur.AppendLine(
$@"┣━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━┫
{(channel.Guild.GetUser(cs.UserId)?.Username.TrimTo(18, true) ?? cs.UserId.ToString()),-20} {cs,5} ")
).ToString() + "┗━━━━━━━━━━━━━━━━━━━━━┻━━━━━━━┛```").ConfigureAwait(false);
}
} }
} }

View File

@ -51,7 +51,7 @@
// var rnd = Math.Abs(rng.Next(0,101)); // var rnd = Math.Abs(rng.Next(0,101));
// if (rnd == 0) // if (rnd == 0)
// { // {
// var msgs = new[] { await e.Channel.SendFile(GetRandomCurrencyImagePath()), await channel.SendMessageAsync($"❗ A random {NadekoBot.Config.CurrencyName} appeared! Pick it up by typing `>pick`") }; // var msgs = new[] { await e.Channel.SendFile(GetRandomCurrencyImagePath()), await channel.SendMessageAsync($"❗ A random {Gambling.CurrencyName} appeared! Pick it up by typing `>pick`") };
// plantedFlowerChannels.AddOrUpdate(e.Channel.Id, msgs, (u, m) => { m.ForEach(async msgToDelete => { try { await msgToDelete.Delete(); } catch { } }); return msgs; }); // plantedFlowerChannels.AddOrUpdate(e.Channel.Id, msgs, (u, m) => { m.ForEach(async msgToDelete => { try { await msgToDelete.Delete(); } catch { } }); return msgs; });
// plantpickCooldowns.AddOrUpdate(e.Channel.Id, now, (i, d) => now); // plantpickCooldowns.AddOrUpdate(e.Channel.Id, now, (i, d) => now);
// } // }
@ -79,8 +79,8 @@
// foreach(var msgToDelete in msgs) // foreach(var msgToDelete in msgs)
// await msgToDelete.Delete().ConfigureAwait(false); // await msgToDelete.Delete().ConfigureAwait(false);
// await FlowersHandler.AddFlowersAsync(umsg.Author, "Picked a flower.", 1, true).ConfigureAwait(false); // await CurrencyHandler.AddFlowersAsync(umsg.Author, "Picked a flower.", 1, true).ConfigureAwait(false);
// var msg = await channel.SendMessageAsync($"**{umsg.Author.Username}** picked a {NadekoBot.Config.CurrencyName}!").ConfigureAwait(false); // var msg = await channel.SendMessageAsync($"**{umsg.Author.Username}** picked a {Gambling.CurrencyName}!").ConfigureAwait(false);
// ThreadPool.QueueUserWorkItem(async (state) => // ThreadPool.QueueUserWorkItem(async (state) =>
// { // {
// try // try
@ -101,24 +101,24 @@
// { // {
// if (plantedFlowerChannels.ContainsKey(e.Channel.Id)) // if (plantedFlowerChannels.ContainsKey(e.Channel.Id))
// { // {
// await channel.SendMessageAsync($"There is already a {NadekoBot.Config.CurrencyName} in this channel.").ConfigureAwait(false); // await channel.SendMessageAsync($"There is already a {Gambling.CurrencyName} in this channel.").ConfigureAwait(false);
// return; // return;
// } // }
// var removed = await FlowersHandler.RemoveFlowers(umsg.Author, "Planted a flower.", 1, true).ConfigureAwait(false); // var removed = await CurrencyHandler.RemoveFlowers(umsg.Author, "Planted a flower.", 1, true).ConfigureAwait(false);
// if (!removed) // if (!removed)
// { // {
// await channel.SendMessageAsync($"You don't have any {NadekoBot.Config.CurrencyName}s.").ConfigureAwait(false); // await channel.SendMessageAsync($"You don't have any {Gambling.CurrencyName}s.").ConfigureAwait(false);
// return; // return;
// } // }
// var file = GetRandomCurrencyImagePath(); // var file = GetRandomCurrencyImagePath();
// Message msg; // Message msg;
// if (file == null) // if (file == null)
// msg = await channel.SendMessageAsync(NadekoBot.Config.CurrencySign).ConfigureAwait(false); // msg = await channel.SendMessageAsync(Gambling.CurrencySign).ConfigureAwait(false);
// else // else
// msg = await e.Channel.SendFile(file).ConfigureAwait(false); // msg = await e.Channel.SendFile(file).ConfigureAwait(false);
// var vowelFirst = new[] { 'a', 'e', 'i', 'o', 'u' }.Contains(NadekoBot.Config.CurrencyName[0]); // var vowelFirst = new[] { 'a', 'e', 'i', 'o', 'u' }.Contains(Gambling.CurrencyName[0]);
// var msg2 = await channel.SendMessageAsync($"Oh how Nice! **{umsg.Author.Username}** planted {(vowelFirst ? "an" : "a")} {NadekoBot.Config.CurrencyName}. Pick it using {Module.Prefix}pick").ConfigureAwait(false); // var msg2 = await channel.SendMessageAsync($"Oh how Nice! **{umsg.Author.Username}** planted {(vowelFirst ? "an" : "a")} {Gambling.CurrencyName}. Pick it using {Module.Prefix}pick").ConfigureAwait(false);
// plantedFlowerChannels.TryAdd(e.Channel.Id, new[] { msg, msg2 }); // plantedFlowerChannels.TryAdd(e.Channel.Id, new[] { msg, msg2 });
// } // }
// finally { locker.Release(); } // finally { locker.Release(); }
@ -126,7 +126,7 @@
// cgb.CreateCommand(Prefix + "gencurrency") // cgb.CreateCommand(Prefix + "gencurrency")
// .Alias(Prefix + "gc") // .Alias(Prefix + "gc")
// .Description($"Toggles currency generation on this channel. Every posted message will have 2% chance to spawn a {NadekoBot.Config.CurrencyName}. Optional parameter cooldown time in minutes, 5 minutes by default. Requires Manage Messages permission. | `{Prefix}gc` or `{Prefix}gc 60`") // .Description($"Toggles currency generation on this channel. Every posted message will have 2% chance to spawn a {Gambling.CurrencyName}. Optional parameter cooldown time in minutes, 5 minutes by default. Requires Manage Messages permission. | `{Prefix}gc` or `{Prefix}gc 60`")
// .AddCheck(SimpleCheckers.ManageMessages()) // .AddCheck(SimpleCheckers.ManageMessages())
// .Parameter("cd", ParameterType.Unparsed) // .Parameter("cd", ParameterType.Unparsed)
// .Do(async e => // .Do(async e =>

View File

@ -84,7 +84,7 @@ namespace NadekoBot.Modules.Music.Classes
{ {
var filename = Path.Combine(Music.MusicDataPath, DateTime.Now.UnixTimestamp().ToString()); var filename = Path.Combine(Music.MusicDataPath, DateTime.Now.UnixTimestamp().ToString());
SongBuffer inStream = new SongBuffer(MusicPlayer, filename, SongInfo, skipTo); SongBuffer inStream = new SongBuffer(MusicPlayer, filename, SongInfo, skipTo, frameBytes * 100);
var bufferTask = inStream.BufferSong(cancelToken).ConfigureAwait(false); var bufferTask = inStream.BufferSong(cancelToken).ConfigureAwait(false);
bytesSent = 0; bytesSent = 0;
@ -118,8 +118,9 @@ namespace NadekoBot.Modules.Music.Classes
while (!cancelToken.IsCancellationRequested) while (!cancelToken.IsCancellationRequested)
{ {
//Console.WriteLine($"Read: {songBuffer.ReadPosition}\nWrite: {songBuffer.WritePosition}\nContentLength:{songBuffer.ContentLength}\n---------"); //Console.WriteLine($"Read: {songBuffer.ReadPosition}\nWrite: {songBuffer.WritePosition}\nContentLength:{songBuffer.ContentLength}\n---------");
var read = inStream.Read(buffer, 0, buffer.Length); var read = await inStream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
//await inStream.CopyToAsync(voiceClient.OutputStream); //await inStream.CopyToAsync(voiceClient.OutputStream);
if(read < frameBytes)
_log.Debug("read {0}", read); _log.Debug("read {0}", read);
unchecked unchecked
{ {
@ -155,7 +156,7 @@ namespace NadekoBot.Modules.Music.Classes
int delayMillis = unchecked(nextTime - Environment.TickCount); int delayMillis = unchecked(nextTime - Environment.TickCount);
if (delayMillis > 0) if (delayMillis > 0)
await Task.Delay(delayMillis, cancelToken).ConfigureAwait(false); await Task.Delay(delayMillis, cancelToken).ConfigureAwait(false);
await outStream.WriteAsync(buffer, 0, read); await outStream.WriteAsync(buffer, 0, read).ConfigureAwait(false);
} }
} }
finally finally

View File

@ -1,4 +1,5 @@
using NadekoBot.Extensions; using NadekoBot.Extensions;
using NLog;
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
@ -17,14 +18,15 @@ namespace NadekoBot.Modules.Music.Classes
/// </summary> /// </summary>
class SongBuffer : Stream class SongBuffer : Stream
{ {
public SongBuffer(MusicPlayer musicPlayer, string basename, SongInfo songInfo, int skipTo, int maxFileSize)
public SongBuffer(MusicPlayer musicPlayer, string basename, SongInfo songInfo, int skipTo)
{ {
MusicPlayer = musicPlayer; MusicPlayer = musicPlayer;
Basename = basename; Basename = basename;
SongInfo = songInfo; SongInfo = songInfo;
SkipTo = skipTo; SkipTo = skipTo;
MaxFileSize = maxFileSize;
CurrentFileStream = new FileStream(this.GetNextFile(), FileMode.OpenOrCreate, FileAccess.Read, FileShare.Write); CurrentFileStream = new FileStream(this.GetNextFile(), FileMode.OpenOrCreate, FileAccess.Read, FileShare.Write);
_log = LogManager.GetCurrentClassLogger();
} }
MusicPlayer MusicPlayer; MusicPlayer MusicPlayer;
@ -35,7 +37,7 @@ namespace NadekoBot.Modules.Music.Classes
private int SkipTo; private int SkipTo;
private static int MAX_FILE_SIZE = 2.MiB(); private int MaxFileSize = 2.MiB();
private long FileNumber = -1; private long FileNumber = -1;
@ -46,9 +48,10 @@ namespace NadekoBot.Modules.Music.Classes
private ulong CurrentBufferSize = 0; private ulong CurrentBufferSize = 0;
private FileStream CurrentFileStream; private FileStream CurrentFileStream;
private Logger _log;
public Task BufferSong(CancellationToken cancelToken) => public Task BufferSong(CancellationToken cancelToken) =>
Task.Factory.StartNew(async () => Task.Run(async () =>
{ {
Process p = null; Process p = null;
FileStream outStream = null; FileStream outStream = null;
@ -72,7 +75,7 @@ namespace NadekoBot.Modules.Music.Classes
while (!p.HasExited) //Also fix low bandwidth while (!p.HasExited) //Also fix low bandwidth
{ {
int bytesRead = await p.StandardOutput.BaseStream.ReadAsync(buffer, 0, buffer.Length, cancelToken).ConfigureAwait(false); int bytesRead = await p.StandardOutput.BaseStream.ReadAsync(buffer, 0, buffer.Length, cancelToken).ConfigureAwait(false);
if (currentFileSize >= MAX_FILE_SIZE) if (currentFileSize >= MaxFileSize)
{ {
try try
{ {
@ -122,7 +125,7 @@ Check the guides for your platform on how to setup ffmpeg correctly:
p.Dispose(); p.Dispose();
} }
} }
}, TaskCreationOptions.LongRunning); });
/// <summary> /// <summary>
/// Return the next file to read, and delete the old one /// Return the next file to read, and delete the old one
@ -172,18 +175,7 @@ Check the guides for your platform on how to setup ffmpeg correctly:
public override long Length => (long) CurrentBufferSize; public override long Length => (long) CurrentBufferSize;
public override long Position public override long Position { get; set; } = 0;
{
get
{
return 0;
}
set
{
}
}
public override void Flush() { } public override void Flush() { }
@ -198,6 +190,8 @@ Check the guides for your platform on how to setup ffmpeg correctly:
CurrentFileStream = new FileStream(GetNextFile(), FileMode.OpenOrCreate, FileAccess.Read, FileShare.Write); CurrentFileStream = new FileStream(GetNextFile(), FileMode.OpenOrCreate, FileAccess.Read, FileShare.Write);
read += CurrentFileStream.Read(buffer, read + offset, count - read); read += CurrentFileStream.Read(buffer, read + offset, count - read);
} }
if (read < count)
Array.Clear(buffer, read, count - read);
} }
return read; return read;
} }

View File

@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord;
using NadekoBot.Services.Database;
using NadekoBot.Extensions;
using NadekoBot.Modules.Gambling;
namespace NadekoBot.Services
{
public static class CurrencyHandler
{
public static async Task<bool> RemoveCurrencyAsync(IGuildUser author, string reason, long amount, bool sendMessage)
{
if (amount < 0)
throw new ArgumentNullException(nameof(amount));
using (var uow = DbHandler.UnitOfWork())
{
var success = uow.Currency.TryUpdateState(author.Id, amount);
if (!success)
return false;
await uow.CompleteAsync();
}
if (sendMessage)
try { await author.SendMessageAsync($"`You received:` {amount} {Gambling.CurrencySign}\n`Reason:` {reason}").ConfigureAwait(false); } catch { }
return true;
}
public static async Task AddCurrencyAsync(IGuildUser author, string reason, long amount, bool sendMessage)
{
if (amount < 0)
throw new ArgumentNullException(nameof(amount));
using (var uow = DbHandler.UnitOfWork())
{
uow.Currency.TryUpdateState(author.Id, amount);
await uow.CompleteAsync();
}
if (sendMessage)
await author.SendMessageAsync($"`You received:` {amount} {Gambling.CurrencySign}\n`Reason:` {reason}").ConfigureAwait(false);
}
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NadekoBot.Services.Database.Models
{
public class Currency : DbEntity
{
public ulong UserId { get; set; }
public long Amount { get; set; }
}
}

View File

@ -0,0 +1,17 @@
using NadekoBot.Services.Database.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NadekoBot.Services.Database.Repositories
{
public interface ICurrencyRepository : IRepository<Currency>
{
Currency GetOrCreate(ulong userId);
long GetUserCurrency(ulong userId);
bool TryUpdateState(ulong userId, long change);
IEnumerable<Currency> GetTopRichest(int count);
}
}

View File

@ -0,0 +1,60 @@
using NadekoBot.Services.Database.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace NadekoBot.Services.Database.Repositories.Impl
{
public class CurrencyRepository : Repository<Currency>, ICurrencyRepository
{
public CurrencyRepository(DbContext context) : base(context)
{
}
public Currency GetOrCreate(ulong userId)
{
var cur = _set.FirstOrDefault(c => c.UserId == userId);
if (cur == null)
{
_set.Add(cur = new Currency()
{
UserId = userId,
Amount = 0
});
_context.SaveChanges();
}
return cur;
}
public IEnumerable<Currency> GetTopRichest(int count) =>
_set.OrderByDescending(c => c.Amount).Take(count).ToList();
public long GetUserCurrency(ulong userId) =>
GetOrCreate(userId).Amount;
public bool TryUpdateState(ulong userId, long change)
{
var cur = GetOrCreate(userId);
if (change == 0)
return true;
if (change > 0)
{
cur.Amount += change;
return true;
}
//change is negative
if (cur.Amount + change >= 0)
{
cur.Amount += change;
return true;
}
return false;
}
}
}

View File

@ -36,6 +36,9 @@ namespace NadekoBot.Services.Database
private IRepeaterRepository _repeaters; private IRepeaterRepository _repeaters;
public IRepeaterRepository Repeaters => _repeaters ?? (_repeaters = new RepeaterRepository(_context)); public IRepeaterRepository Repeaters => _repeaters ?? (_repeaters = new RepeaterRepository(_context));
private ICurrencyRepository _currency;
public ICurrencyRepository Currency => _currency ?? (_currency = new CurrencyRepository(_context));
public UnitOfWork(NadekoContext context) public UnitOfWork(NadekoContext context)
{ {
_context = context; _context = context;