$give added

This commit is contained in:
Master Kwoth 2016-03-26 03:25:03 +01:00
parent 2bf5cca125
commit 6ca49dca49
3 changed files with 109 additions and 32 deletions

View File

@ -1,22 +1,43 @@
using System.Threading.Tasks; using System.Threading.Tasks;
namespace NadekoBot.Classes { namespace NadekoBot.Classes
internal static class FlowersHandler { {
public static async Task AddFlowersAsync(Discord.User u, string reason, int amount) { internal static class FlowersHandler
{
public static async Task AddFlowersAsync(Discord.User u, string reason, int amount)
{
if (amount <= 0) if (amount <= 0)
return; return;
await Task.Run(() => { await Task.Run(() =>
DbHandler.Instance.InsertData(new _DataModels.CurrencyTransaction { {
DbHandler.Instance.InsertData(new _DataModels.CurrencyTransaction
{
Reason = reason, Reason = reason,
UserId = (long)u.Id, UserId = (long)u.Id,
Value = amount, Value = amount,
}); });
}); });
var flows = ""; var flows = "";
for (var i = 0; i < amount; i++) { for (var i = 0; i < amount; i++)
{
flows += "🌸"; flows += "🌸";
} }
await u.SendMessage("👑Congratulations!👑\nYou got: "+flows); await u.SendMessage("👑Congratulations!👑\nYou received: " + flows);
}
public static async Task RemoveFlowersAsync(Discord.User u, string reason, int amount)
{
if (amount <= 0)
return;
await Task.Run(() =>
{
DbHandler.Instance.InsertData(new _DataModels.CurrencyTransaction
{
Reason = reason,
UserId = (long)u.Id,
Value = -amount,
});
});
} }
} }
} }

View File

@ -9,8 +9,10 @@ using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace NadekoBot.Classes.Trivia { namespace NadekoBot.Classes.Trivia
internal class TriviaGame { {
internal class TriviaGame
{
private readonly object _guessLock = new object(); private readonly object _guessLock = new object();
private Server server { get; } private Server server { get; }
@ -30,20 +32,24 @@ namespace NadekoBot.Classes.Trivia {
public int WinRequirement { get; } = 10; public int WinRequirement { get; } = 10;
public TriviaGame(CommandEventArgs e) { public TriviaGame(CommandEventArgs e)
{
server = e.Server; server = e.Server;
channel = e.Channel; channel = e.Channel;
Task.Run(StartGame); Task.Run(StartGame);
} }
private async Task StartGame() { private async Task StartGame()
while (!ShouldStopGame) { {
while (!ShouldStopGame)
{
// reset the cancellation source // reset the cancellation source
triviaCancelSource = new CancellationTokenSource(); triviaCancelSource = new CancellationTokenSource();
var token = triviaCancelSource.Token; var token = triviaCancelSource.Token;
// load question // load question
CurrentQuestion = TriviaQuestionPool.Instance.GetRandomQuestion(oldQuestions); CurrentQuestion = TriviaQuestionPool.Instance.GetRandomQuestion(oldQuestions);
if (CurrentQuestion == null) { if (CurrentQuestion == null)
{
await channel.SendMessage($":exclamation: Failed loading a trivia question"); await channel.SendMessage($":exclamation: Failed loading a trivia question");
await End(); await End();
return; return;
@ -58,7 +64,8 @@ namespace NadekoBot.Classes.Trivia {
//allow people to guess //allow people to guess
GameActive = true; GameActive = true;
try { try
{
//hint //hint
await Task.Delay(HintTimeoutMiliseconds, token); await Task.Delay(HintTimeoutMiliseconds, token);
await channel.SendMessage($":exclamation:**Hint:** {CurrentQuestion.GetHint()}"); await channel.SendMessage($":exclamation:**Hint:** {CurrentQuestion.GetHint()}");
@ -66,7 +73,9 @@ namespace NadekoBot.Classes.Trivia {
//timeout //timeout
await Task.Delay(QuestionDurationMiliseconds - HintTimeoutMiliseconds, token); await Task.Delay(QuestionDurationMiliseconds - HintTimeoutMiliseconds, token);
} catch (TaskCanceledException) { }
catch (TaskCanceledException)
{
Console.WriteLine("Trivia cancelled"); Console.WriteLine("Trivia cancelled");
} }
GameActive = false; GameActive = false;
@ -79,28 +88,34 @@ namespace NadekoBot.Classes.Trivia {
await End(); await End();
} }
private async Task End() { private async Task End()
{
ShouldStopGame = true; ShouldStopGame = true;
await channel.SendMessage("**Trivia game ended**\n" + GetLeaderboard()); await channel.SendMessage("**Trivia game ended**\n" + GetLeaderboard());
TriviaGame throwAwayValue; TriviaGame throwAwayValue;
Commands.Trivia.RunningTrivias.TryRemove(server.Id, out throwAwayValue); Commands.Trivia.RunningTrivias.TryRemove(server.Id, out throwAwayValue);
} }
public async Task StopGame() { public async Task StopGame()
{
if (!ShouldStopGame) if (!ShouldStopGame)
await channel.SendMessage(":exclamation: Trivia will stop after this question."); await channel.SendMessage(":exclamation: Trivia will stop after this question.");
ShouldStopGame = true; ShouldStopGame = true;
} }
private async void PotentialGuess(object sender, MessageEventArgs e) { private async void PotentialGuess(object sender, MessageEventArgs e)
try { {
try
{
if (e.Channel.IsPrivate) return; if (e.Channel.IsPrivate) return;
if (e.Server != server) return; if (e.Server != server) return;
if (e.User.Id == NadekoBot.Client.CurrentUser.Id) return; if (e.User.Id == NadekoBot.Client.CurrentUser.Id) return;
var guess = false; var guess = false;
lock (_guessLock) { lock (_guessLock)
if (GameActive && CurrentQuestion.IsAnswerCorrect(e.Message.Text) && !triviaCancelSource.IsCancellationRequested) { {
if (GameActive && CurrentQuestion.IsAnswerCorrect(e.Message.Text) && !triviaCancelSource.IsCancellationRequested)
{
Users.TryAdd(e.User, 0); //add if not exists Users.TryAdd(e.User, 0); //add if not exists
Users[e.User]++; //add 1 point to the winner Users[e.User]++; //add 1 point to the winner
guess = true; guess = true;
@ -114,17 +129,20 @@ namespace NadekoBot.Classes.Trivia {
await channel.Send($":exclamation: We have a winner! Its {e.User.Mention}."); await channel.Send($":exclamation: We have a winner! Its {e.User.Mention}.");
// add points to the winner // add points to the winner
await FlowersHandler.AddFlowersAsync(e.User, "Won Trivia", 2); await FlowersHandler.AddFlowersAsync(e.User, "Won Trivia", 2);
} catch { } }
catch { }
} }
public string GetLeaderboard() { public string GetLeaderboard()
{
if (Users.Count == 0) if (Users.Count == 0)
return ""; return "";
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.Append("**Leaderboard:**\n-----------\n"); sb.Append("**Leaderboard:**\n-----------\n");
foreach (var kvp in Users.OrderBy(kvp => kvp.Value)) { foreach (var kvp in Users.OrderBy(kvp => kvp.Value))
{
sb.AppendLine($"**{kvp.Key.Name}** has {kvp.Value} points".ToString().SnPl(kvp.Value)); sb.AppendLine($"**{kvp.Key.Name}** has {kvp.Value} points".ToString().SnPl(kvp.Value));
} }

View File

@ -1,8 +1,11 @@
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.Modules; using Discord.Modules;
using NadekoBot.Classes;
using NadekoBot.Extensions; using NadekoBot.Extensions;
using System;
using System.Linq; using System.Linq;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Gambling namespace NadekoBot.Modules.Gambling
{ {
@ -33,14 +36,46 @@ namespace NadekoBot.Modules.Gambling
cgb.CreateCommand(Prefix + "$$") cgb.CreateCommand(Prefix + "$$")
.Description("Check how many NadekoFlowers you have.") .Description("Check how many NadekoFlowers you have.")
.Do(NadekoFlowerCheckFunc()); .Do(NadekoFlowerCheckFunc());
cgb.CreateCommand(Prefix + "give")
.Description("Give someone a certain amount of flowers")
.Parameter("amount", ParameterType.Required)
.Parameter("receiver", ParameterType.Unparsed)
.Do(async e =>
{
var amountStr = e.GetArg("amount")?.Trim();
long amount;
if (!long.TryParse(amountStr, out amount) || amount < 0)
return;
var mentionedUser = e.Message.MentionedUsers.FirstOrDefault(u =>
u.Id != NadekoBot.Client.CurrentUser.Id &&
u.Id != e.User.Id);
if (mentionedUser == null)
return;
var userFlowers = GetUserFlowers(e.User.Id);
if (userFlowers < amount)
{
await e.Channel.SendMessage($"{e.User.Mention} You don't have enough flowers. You have only {userFlowers}🌸.");
return;
}
await FlowersHandler.RemoveFlowersAsync(e.User, "Gift", (int)amount);
await FlowersHandler.AddFlowersAsync(mentionedUser, "Gift", (int)amount);
await e.Channel.SendMessage($"{e.User.Mention} successfully sent {amount}🌸 to {mentionedUser.Mention}!");
});
}); });
} }
private static System.Func<CommandEventArgs, System.Threading.Tasks.Task> NadekoFlowerCheckFunc() private static Func<CommandEventArgs, Task> NadekoFlowerCheckFunc()
{ {
return async e => return async e =>
{ {
var pts = Classes.DbHandler.Instance.GetStateByUserId((long)e.User.Id)?.Value ?? 0; var pts = GetUserFlowers(e.User.Id);
var str = $"`You have {pts} NadekoFlowers".SnPl((int)pts) + "`\n"; var str = $"`You have {pts} NadekoFlowers".SnPl((int)pts) + "`\n";
for (var i = 0; i < pts; i++) for (var i = 0; i < pts; i++)
{ {
@ -50,7 +85,10 @@ namespace NadekoBot.Modules.Gambling
}; };
} }
private static System.Func<CommandEventArgs, System.Threading.Tasks.Task> RaffleFunc() private static long GetUserFlowers(ulong userId) =>
Classes.DbHandler.Instance.GetStateByUserId((long)userId)?.Value ?? 0;
private static Func<CommandEventArgs, Task> RaffleFunc()
{ {
return async e => return async e =>
{ {