internal override void Init(CommandGroupBuilder cgb) { cgb.CreateCommand(Module.Prefix + "pick") .Description("Picks a flower planted in this channel.") .Do(async e => { Message msg; await e.Message.Delete().ConfigureAwait(false); if (!plantedFlowerChannels.TryRemove(e.Channel.Id, out msg)) { return; } await msg.Delete().ConfigureAwait(false); await FlowersHandler.AddFlowersAsync(e.User, "Picked a flower.", 1, true).ConfigureAwait(false); msg = await e.Channel.SendMessage($"**{e.User.Name}** picked a {WizBot.Config.CurrencyName}!").ConfigureAwait(false); await Task.Delay(10000).ConfigureAwait(false); await msg.Delete().ConfigureAwait(false); }); cgb.CreateCommand(Module.Prefix + "plant") .Description("Spend a flower to plant it in this channel. (If bot is restarted or crashes, flower will be lost)") .Do(async e => { lock (locker) { if (plantedFlowerChannels.ContainsKey(e.Channel.Id)) { e.Channel.SendMessage($"There is already a {WizBot.Config.CurrencyName} in this channel."); return; } var removed = FlowersHandler.RemoveFlowers(e.User, "Planted a flower.", 1); if (!removed) { e.Channel.SendMessage($"You don't have any {WizBot.Config.CurrencyName}s.").Wait(); return; } var rng = new Random(); var file = Directory.GetFiles("data/currency_images").OrderBy(s => rng.Next()).FirstOrDefault(); Message msg; //todo send message after, not in lock if (file == null) { msg = e.Channel.SendMessage(WizBot.Config.CurrencySign).GetAwaiter().GetResult(); } else { msg = e.Channel.SendFile(file).GetAwaiter().GetResult(); } plantedFlowerChannels.TryAdd(e.Channel.Id, msg); } var vowelFirst = new[] { 'a', 'e', 'i', 'o', 'u' }.Contains(WizBot.Config.CurrencyName[0]); var msg2 = await e.Channel.SendMessage($"Oh how Nice! **{e.User.Name}** planted {(vowelFirst ? "an" : "a")} {WizBot.Config.CurrencyName}. Pick it using {Module.Prefix}pick"); await Task.Delay(20000).ConfigureAwait(false); await msg2.Delete().ConfigureAwait(false); }); }
public Func <CommandEventArgs, Task> BetFlipCoinFunc() => async e => { var amountstr = e.GetArg("amount").Trim(); var guessStr = e.GetArg("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 = GamblingModule.GetUserFlowers(e.User.Id); if (userFlowers < amount) { await e.Channel.SendMessage($"{e.User.Mention} You don't have enough {WizBot.Config.CurrencyName}s. You only have {userFlowers}{WizBot.Config.CurrencySign}.").ConfigureAwait(false); return; } await FlowersHandler.RemoveFlowers(e.User, "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 = $"{e.User.Mention}`You guessed it!` You won {amount * 2}{WizBot.Config.CurrencySign}"; await FlowersHandler.AddFlowersAsync(e.User, "Betflip Gamble", amount * 2, true).ConfigureAwait(false); } else { str = $"{e.User.Mention}`More luck next time.`"; } await e.Channel.SendMessage(str).ConfigureAwait(false); };
private async void PotentialGuess(object sender, MessageEventArgs e) { try { if (e.Channel.IsPrivate) { return; } if (e.Server != server) { return; } if (e.User.Id == WizBot.Client.CurrentUser.Id) { return; } var guess = false; await _guessLock.WaitAsync().ConfigureAwait(false); try { 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; } } finally { _guessLock.Release(); } if (!guess) { return; } triviaCancelSource.Cancel(); await channel.SendMessage($"☑️ {e.User.Mention} guessed it! The answer was: **{CurrentQuestion.Answer}**").ConfigureAwait(false); if (Users[e.User] != WinRequirement) { return; } ShouldStopGame = true; await channel.Send($":exclamation: We have a winner! It's {e.User.Mention}.").ConfigureAwait(false); // add points to the winner await FlowersHandler.AddFlowersAsync(e.User, "Won Trivia", 2).ConfigureAwait(false); } catch { } }
public AnimalRace(ulong serverId, Channel ch) { this.serverId = serverId; this.raceChannel = ch; if (!AnimalRaces.TryAdd(serverId, this)) { Fail = true; return; } var cancelSource = new CancellationTokenSource(); var token = cancelSource.Token; var fullgame = CheckForFullGameAsync(token); Task.Run(async() => { try { await raceChannel.SendMessage($"🏁`Race is starting in 20 seconds or when the room is full. Type {NadekoBot.Config.CommandPrefixes.Gambling}jr to join the race.`"); var t = await Task.WhenAny(Task.Delay(20000, token), fullgame); Started = true; cancelSource.Cancel(); if (t == fullgame) { await raceChannel.SendMessage("🏁`Race full, starting right now!`"); } else if (participants.Count > 1) { await raceChannel.SendMessage("🏁`Game starting with " + participants.Count + " participants.`"); } else { await raceChannel.SendMessage("🏁`Race failed to start since there was not enough participants.`"); var p = participants.FirstOrDefault(); if (p != null) { await FlowersHandler.AddFlowersAsync(p.User, "BetRace", p.AmountBet, true).ConfigureAwait(false); } End(); return; } await Task.Run(StartRace); End(); } catch { } }); }
public AnimalRace(ulong serverId, Channel ch) { this.serverId = serverId; this.raceChannel = ch; if (!AnimalRaces.TryAdd(serverId, this)) { Fail = true; return; } var cancelSource = new CancellationTokenSource(); var token = cancelSource.Token; var fullgame = CheckForFullGameAsync(token); Task.Run(async() => { try { await raceChannel.SendMessage($"🏁`Rennen startet in 20 Sekunden oder wenn der Raum voll ist. Gib {MidnightBot.Config.CommandPrefixes.Gambling}jr ein, um dem Rennen beizutreten.`"); var t = await Task.WhenAny(Task.Delay(20000, token), fullgame); Started = true; cancelSource.Cancel(); if (t == fullgame) { await raceChannel.SendMessage("🏁`Rennen ist voll, wird gestartet!`"); } else if (participants.Count > 1) { await raceChannel.SendMessage("🏁`Spiel startet mit " + participants.Count + " Teilnehmern.`"); } else { await raceChannel.SendMessage("🏁`Rennen konnte nicht starten da es nicht genug Teilnehmer gab.`"); var p = participants.FirstOrDefault(); if (p != null) { await FlowersHandler.AddFlowersAsync(p.User, "BetRace", p.AmountBet, true).ConfigureAwait(false); } End(); return; } await Task.Run(StartRace); End(); } catch { } }); }
private async void PotentialGuess(object sender, MessageEventArgs e) { try { if (e.Channel.IsPrivate) { return; } if (e.Server != _server) { return; } bool 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) { triviaCancelSource.Cancel(); await _channel.SendMessage($"☑️ {e.User.Mention} guessed it! The answer was: **{CurrentQuestion.Answer}**"); if (users[e.User] == WinRequirement) { 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 Func <CommandEventArgs, Task> BetFlipCoinFunc() => async e => { var amountstr = e.GetArg("amount").Trim(); var guessStr = e.GetArg("guess").Trim().ToUpperInvariant(); if (guessStr != "K" && guessStr != "Z" && guessStr != "KOPF" && guessStr != "ZAHL") { return; } int amount; if (!int.TryParse(amountstr, out amount) || amount < 1) { return; } var userFlowers = GamblingModule.GetUserFlowers(e.User.Id); if (userFlowers < amount) { await e.Channel.SendMessage($"{e.User.Mention} Du hast nicht genug {MidnightBot.Config.CurrencyName}s. Du hast nur {userFlowers}{MidnightBot.Config.CurrencySign}.").ConfigureAwait(false); return; } await FlowersHandler.RemoveFlowers(e.User, "Betflip Gamble", (int)amount, true).ConfigureAwait(false); //kopf = true //zahl = false if (guessStr == "KOPF" || guessStr == "K") { var guess = guessStr == "KOPF" || guessStr == "K"; bool result = false; if (rng.Next(0, 3) == 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 = $"{e.User.Mention}`Du hast richtig geraten!` Du hast {amount * 2}{MidnightBot.Config.CurrencySign} gewonnen."; await FlowersHandler.AddFlowersAsync(e.User, "Betflip Gamble", amount * 2, true).ConfigureAwait(false); } else { str = $"{e.User.Mention}`Viel Glück beim nächsten Mal.`"; } await e.Channel.SendMessage(str).ConfigureAwait(false); } else { var guess = guessStr == "ZAHL" || guessStr == "Z"; bool result = false; if (rng.Next(0, 3) == 1) { await e.Channel.SendFile("tails.png", Properties.Resources.tails.ToStream(System.Drawing.Imaging.ImageFormat.Png)).ConfigureAwait(false); result = true; } else { await e.Channel.SendFile("heads.png", Properties.Resources.heads.ToStream(System.Drawing.Imaging.ImageFormat.Png)).ConfigureAwait(false); } string str; if (guess == result) { str = $"{e.User.Mention}`Du hast richtig geraten!` Du hast {amount * 2}{MidnightBot.Config.CurrencySign} gewonnen."; await FlowersHandler.AddFlowersAsync(e.User, "Betflip Gamble", amount * 2, true).ConfigureAwait(false); } else { str = $"{e.User.Mention}`Viel Glück beim nächsten Mal.`"; } await e.Channel.SendMessage(str).ConfigureAwait(false); } };
public override void Install(ModuleManager manager) { manager.CreateCommands("", cgb => { cgb.AddCheck(PermissionChecker.Instance); commands.ForEach(com => com.Init(cgb)); cgb.CreateCommand(Prefix + "raffle") .Description("Prints a name and ID of a random user from the online list from the (optional) role.") .Parameter("role", ParameterType.Optional) .Do(async e => { var arg = string.IsNullOrWhiteSpace(e.GetArg("role")) ? "@everyone" : e.GetArg("role"); var role = e.Server.FindRoles(arg).FirstOrDefault(); if (role == null) { await e.Channel.SendMessage("💢 Role not found.").ConfigureAwait(false); return; } var members = role.Members.Where(u => u.Status == UserStatus.Online); // only online var membersArray = members as User[] ?? members.ToArray(); var usr = membersArray[new Random().Next(0, membersArray.Length)]; await e.Channel.SendMessage($"**Raffled user:** {usr.Name} (id: {usr.Id})").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "$$") .Description(string.Format("Check how much {0}s a person has. (Defaults to yourself)\n**Usage**:`{1}$$` or `{1}$$ @Someone`", NadekoBot.Config.CurrencyName, Prefix)) .Parameter("all", ParameterType.Unparsed) .Do(async e => { var usr = e.Message.MentionedUsers.FirstOrDefault() ?? e.User; var pts = GetUserFlowers(usr.Id); var str = $"{usr.Name} has {pts} {NadekoBot.Config.CurrencySign}"; await e.Channel.SendMessage(str).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "give") .Description(string.Format("Give someone a certain amount of {0}s", NadekoBot.Config.CurrencyName)) .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 {NadekoBot.Config.CurrencyName}s. You have only {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false); return; } FlowersHandler.RemoveFlowers(e.User, "Gift", (int)amount); await FlowersHandler.AddFlowersAsync(mentionedUser, "Gift", (int)amount).ConfigureAwait(false); await e.Channel.SendMessage($"{e.User.Mention} successfully sent {amount} {NadekoBot.Config.CurrencyName}s to {mentionedUser.Mention}!").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "award") .Description("Gives someone a certain amount of flowers. **Bot Owner Only!**\n**Usage**: `$award 100 @person`") .AddCheck(SimpleCheckers.OwnerOnly()) .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); if (mentionedUser == null) { return; } await FlowersHandler.AddFlowersAsync(mentionedUser, $"Awarded by bot owner. ({e.User.Name}/{e.User.Id})", (int)amount).ConfigureAwait(false); await e.Channel.SendMessage($"{e.User.Mention} successfully awarded {amount} {NadekoBot.Config.CurrencyName}s to {mentionedUser.Mention}!").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "take") .Description("Takes a certain amount of flowers from someone. **Bot Owner Only!**") .AddCheck(SimpleCheckers.OwnerOnly()) .Parameter("amount", ParameterType.Required) .Parameter("rektperson", 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); if (mentionedUser == null) { return; } FlowersHandler.RemoveFlowers(mentionedUser, $"Taken by bot owner.({e.User.Name}/{e.User.Id})", (int)amount); await e.Channel.SendMessage($"{e.User.Mention} successfully took {amount} {NadekoBot.Config.CurrencyName}s from {mentionedUser.Mention}!").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "leaderboard") .Alias(Prefix + "lb") .Do(async e => { var richestTemp = DbHandler.Instance.GetTopRichest(); var richest = richestTemp as CurrencyState[] ?? richestTemp.ToArray(); if (richest.Length == 0) { return; } await e.Channel.SendMessage( richest.Aggregate(new StringBuilder( $@"```xl ┏━━━━━━━━━━━━━━━━━━━┳━━━━━━━┓ ┃ Id ┃ $$$ ┃ "), (cur, cs) => cur.AppendLine( $@"┣━━━━━━━━━━━━━━━━━━━╋━━━━━━━┫ ┃{cs.UserId,-18} ┃ {cs.Value,5} ┃") ).ToString() + "┗━━━━━━━━━━━━━━━━━━━┻━━━━━━━┛```"); }); }); }
internal override void Init(CommandGroupBuilder cgb) { cgb.CreateCommand(Module.Prefix + "pick") .Description($"Picks a flower planted in this channel. | `{Prefix}pick`") .Do(async e => { IEnumerable <Message> msgs; await e.Message.Delete().ConfigureAwait(false); if (!plantedFlowerChannels.TryRemove(e.Channel.Id, out msgs)) { return; } foreach (var msgToDelete in msgs) { await msgToDelete.Delete().ConfigureAwait(false); } await FlowersHandler.AddFlowersAsync(e.User, "Picked a flower.", 1, true).ConfigureAwait(false); var msg = await e.Channel.SendMessage($"**{e.User.Name}** picked a {NadekoBot.Config.CurrencyName}!").ConfigureAwait(false); ThreadPool.QueueUserWorkItem(async(state) => { try { await Task.Delay(10000).ConfigureAwait(false); await msg.Delete().ConfigureAwait(false); } catch { } }); }); cgb.CreateCommand(Module.Prefix + "plant") .Description($"Spend a flower to plant it in this channel. (If bot is restarted or crashes, flower will be lost) | `{Prefix}plant`") .Do(async e => { await locker.WaitAsync().ConfigureAwait(false); try { if (plantedFlowerChannels.ContainsKey(e.Channel.Id)) { await e.Channel.SendMessage($"There is already a {NadekoBot.Config.CurrencyName} in this channel.").ConfigureAwait(false); return; } var removed = await FlowersHandler.RemoveFlowers(e.User, "Planted a flower.", 1, true).ConfigureAwait(false); if (!removed) { await e.Channel.SendMessage($"You don't have any {NadekoBot.Config.CurrencyName}s.").ConfigureAwait(false); return; } var file = GetRandomCurrencyImagePath(); Message msg; if (file == null) { msg = await e.Channel.SendMessage(NadekoBot.Config.CurrencySign).ConfigureAwait(false); } else { msg = await e.Channel.SendFile(file).ConfigureAwait(false); } var vowelFirst = new[] { 'a', 'e', 'i', 'o', 'u' }.Contains(NadekoBot.Config.CurrencyName[0]); var msg2 = await e.Channel.SendMessage($"Oh how Nice! **{e.User.Name}** planted {(vowelFirst ? "an" : "a")} {NadekoBot.Config.CurrencyName}. Pick it using {Module.Prefix}pick").ConfigureAwait(false); plantedFlowerChannels.TryAdd(e.Channel.Id, new[] { msg, msg2 }); } finally { locker.Release(); } }); cgb.CreateCommand(Prefix + "gencurrency") .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`") .AddCheck(SimpleCheckers.ManageMessages()) .Parameter("cd", ParameterType.Unparsed) .Do(async e => { var cdStr = e.GetArg("cd"); int cd = 2; if (!int.TryParse(cdStr, out cd) || cd < 0) { cd = 2; } var config = SpecificConfigurations.Default.Of(e.Server.Id); int throwaway; if (config.GenerateCurrencyChannels.TryRemove(e.Channel.Id, out throwaway)) { await e.Channel.SendMessage("`Currency generation disabled on this channel.`").ConfigureAwait(false); } else { if (config.GenerateCurrencyChannels.TryAdd(e.Channel.Id, cd)) { await e.Channel.SendMessage($"`Currency generation enabled on this channel. Cooldown is {cd} minutes.`").ConfigureAwait(false); } } }); }
public override void Install(ModuleManager manager) { manager.CreateCommands("", cgb => { cgb.AddCheck(PermissionChecker.Instance); commands.ForEach(com => com.Init(cgb)); cgb.CreateCommand(Prefix + "raffle") .Description($"Prints a name and ID of a random user from the online list from the (optional) role. | `{Prefix}raffle` or `{Prefix}raffle RoleName`") .Parameter("role", ParameterType.Optional) .Do(async e => { var arg = string.IsNullOrWhiteSpace(e.GetArg("role")) ? "@everyone" : e.GetArg("role"); var role = e.Server.FindRoles(arg).FirstOrDefault(); if (role == null) { await e.Channel.SendMessage("💢 Role not found.").ConfigureAwait(false); return; } var members = role.Members.Where(u => u.Status == UserStatus.Online); // only online var membersArray = members as User[] ?? members.ToArray(); var usr = membersArray[new Random().Next(0, membersArray.Length)]; await e.Channel.SendMessage($"**Raffled user:** {usr.Name} (id: {usr.Id})").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "$$") .Description(string.Format("Check how much {0}s a person has. (Defaults to yourself) |`{1}$$` or `{1}$$ @Someone`", WizBot.Config.CurrencyName, Prefix)) .Parameter("all", ParameterType.Unparsed) .Do(async e => { var usr = e.Message.MentionedUsers.FirstOrDefault() ?? e.User; var pts = GetUserFlowers(usr.Id); var str = $"{usr.Name} has {pts} {WizBot.Config.CurrencySign}"; await e.Channel.SendMessage(str).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "give") .Description(string.Format("Give someone a certain amount of {0}s", WizBot.Config.CurrencyName) + $"|`{Prefix}give 1 \"@SomeGuy\"`") .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 != WizBot.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 {WizBot.Config.CurrencyName}s. You only have {userFlowers}{WizBot.Config.CurrencySign}.").ConfigureAwait(false); return; } await FlowersHandler.RemoveFlowers(e.User, "Gift", (int)amount, true).ConfigureAwait(false); await FlowersHandler.AddFlowersAsync(mentionedUser, "Gift", (int)amount).ConfigureAwait(false); await e.Channel.SendMessage($"{e.User.Mention} successfully sent {amount} {WizBot.Config.CurrencyName}s to {mentionedUser.Mention}!").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "award") .Description($"Gives someone a certain amount of flowers. **Bot Owner Only!** | `{Prefix}award 100 @person`") .AddCheck(SimpleCheckers.OwnerOnly()) .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 != WizBot.Client.CurrentUser.Id); if (mentionedUser == null) { return; } await FlowersHandler.AddFlowersAsync(mentionedUser, $"Awarded by bot owner. ({e.User.Name}/{e.User.Id})", (int)amount).ConfigureAwait(false); await e.Channel.SendMessage($"{e.User.Mention} successfully awarded {amount} {WizBot.Config.CurrencyName}s to {mentionedUser.Mention}!").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "take") .Description($"Takes a certain amount of flowers from someone. **Bot Owner Only!** | `{Prefix}take 1 \"@someguy\"`") .AddCheck(SimpleCheckers.OwnerOnly()) .Parameter("amount", ParameterType.Required) .Parameter("rektperson", 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 != WizBot.Client.CurrentUser.Id); if (mentionedUser == null) { return; } await FlowersHandler.RemoveFlowers(mentionedUser, $"Taken by bot owner.({e.User.Name}/{e.User.Id})", (int)amount).ConfigureAwait(false); await e.Channel.SendMessage($"{e.User.Mention} successfully took {amount} {WizBot.Config.CurrencyName}s from {mentionedUser.Mention}!").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "betroll") .Alias(Prefix + "br") .Description($"Bets a certain amount of {WizBot.Config.CurrencyName}s and rolls a dice. Rolling over 66 yields x2 flowers, over 90 - x3 and 100 x10. | `{Prefix}br 5`") .Parameter("amount", ParameterType.Required) .Do(async e => { var amountstr = e.GetArg("amount").Trim(); int amount; if (!int.TryParse(amountstr, out amount) || amount < 1) { return; } var userFlowers = GetUserFlowers(e.User.Id); if (userFlowers < amount) { await e.Channel.SendMessage($"{e.User.Mention} You don't have enough {WizBot.Config.CurrencyName}s. You only have {userFlowers}{WizBot.Config.CurrencySign}.").ConfigureAwait(false); return; } await FlowersHandler.RemoveFlowers(e.User, "Betroll Gamble", (int)amount, true).ConfigureAwait(false); var rng = new Random().Next(0, 101); var str = $"{e.User.Mention} `You rolled {rng}.` "; if (rng < 67) { str += "Better luck next time."; } else if (rng < 90) { str += $"Congratulations! You won {amount * 2}{WizBot.Config.CurrencySign} for rolling above 66"; await FlowersHandler.AddFlowersAsync(e.User, "Betroll Gamble", amount * 2, true).ConfigureAwait(false); } else if (rng < 100) { str += $"Congratulations! You won {amount * 3}{WizBot.Config.CurrencySign} for rolling above 90."; await FlowersHandler.AddFlowersAsync(e.User, "Betroll Gamble", amount * 3, true).ConfigureAwait(false); } else { str += $"👑 Congratulations! You won {amount * 10}{WizBot.Config.CurrencySign} for rolling **100**. 👑"; await FlowersHandler.AddFlowersAsync(e.User, "Betroll Gamble", amount * 10, true).ConfigureAwait(false); } await e.Channel.SendMessage(str).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "leaderboard") .Alias(Prefix + "lb") .Description($"Displays bot currency leaderboard | `{Prefix}lb`") .Do(async e => { var richestTemp = DbHandler.Instance.GetTopRichest(); var richest = richestTemp as CurrencyState[] ?? richestTemp.ToArray(); if (richest.Length == 0) { return; } await e.Channel.SendMessage( richest.Aggregate(new StringBuilder( $@"```xl ┏━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┓ ┃ Id ┃ $$$ ┃ "), (cur, cs) => cur.AppendLine( $@"┣━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━┫ ┃{(e.Server.Users.Where(u => u.Id == (ulong)cs.UserId).FirstOrDefault()?.Name.TrimTo(18, true) ?? cs.UserId.ToString()),-20} ┃ {cs.Value,5} ┃") ).ToString() + "┗━━━━━━━━━━━━━━━━━━━━━┻━━━━━━━┛```").ConfigureAwait(false); }); }); }
public override void Install(ModuleManager manager) { manager.CreateCommands("", cgb => { cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance); commands.ForEach(com => com.Init(cgb)); cgb.CreateCommand(Prefix + "raffle") .Description("Prints a name and ID of a random user from the online list from the (optional) role.") .Parameter("role", ParameterType.Optional) .Do(RaffleFunc()); cgb.CreateCommand(Prefix + "$$") .Description(string.Format("Check how much {0}s you have.", NadekoBot.Config.CurrencyName)) .Do(NadekoFlowerCheckFunc()); cgb.CreateCommand(Prefix + "give") .Description(string.Format("Give someone a certain amount of {0}s", NadekoBot.Config.CurrencyName)) .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 {NadekoBot.Config.CurrencyName}s. You have only {userFlowers}{NadekoBot.Config.CurrencySign}."); return; } FlowersHandler.RemoveFlowers(e.User, "Gift", (int)amount); await FlowersHandler.AddFlowersAsync(mentionedUser, "Gift", (int)amount); await e.Channel.SendMessage($"{e.User.Mention} successfully sent {amount} {NadekoBot.Config.CurrencyName}s to {mentionedUser.Mention}!"); }); cgb.CreateCommand(Prefix + "award") .Description("Gives someone a certain amount of flowers. **Owner only!**") .AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly()) .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); if (mentionedUser == null) { return; } await FlowersHandler.AddFlowersAsync(mentionedUser, $"Awarded by bot owner. ({e.User.Name}/{e.User.Id})", (int)amount); await e.Channel.SendMessage($"{e.User.Mention} successfully awarded {amount} {NadekoBot.Config.CurrencyName}s to {mentionedUser.Mention}!"); }); cgb.CreateCommand(Prefix + "take") .Description("Takes a certain amount of flowers from someone. **Owner only!**") .AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly()) .Parameter("amount", ParameterType.Required) .Parameter("rektperson", 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); if (mentionedUser == null) { return; } FlowersHandler.RemoveFlowers(mentionedUser, $"Taken by bot owner.({e.User.Name}/{e.User.Id})", (int)amount); await e.Channel.SendMessage($"{e.User.Mention} successfully took {amount} {NadekoBot.Config.CurrencyName}s from {mentionedUser.Mention}!"); }); }); }
/// <summary> /// This is what happens when NadekoBot receives messages /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public async void PotentialPlacement(object sender, MessageEventArgs e) { try { #region checks //Getting the messages we want if (e.Channel.IsPrivate) { return; //Because the default message would show up as well } if (e.Server != server) { return; } if (!Players.Keys.Contains(e.User)) { return; //Only track current players } if (e.User == currentCzar && !CzarDecision) { return; } if (CzarDecision && e.User != currentCzar) { return; } #endregion #region CzarDecision //if the Tzar is making the decision if (CzarDecision) { int choice; if (!int.TryParse(e.Message.Text, out choice)) { return; } choice--; //check whether it's out of range if (choice > WhiteCardsAssortment.Count - 1) { return; } var chosen = WhiteCardsAssortment[choice]; var winner = chosen.Key; var message = $"{winner.Name} has won this round with:\n"; var cards = WhiteCardsAssortment[choice].Value; if (currentBlackCard.CardContents.Contains("\\_\\_\\_")) { var str = currentBlackCard.ToString(); var cardsArray = cards.ToArray(); for (int i = 0; i < cards.Count(); i++) { var c = cardsArray[0]; str = str.Replace("\\_\\_\\_", c.CardContents); } message += str; } else { message += currentBlackCard.ToString(); cards.ToList().ForEach(x => message += x.CardContents + "\n"); } //cahCancelSource.Cancel(); CzarDecision = false; Players[winner].Points++; GameActive = false; await channel.SendMessage(message); //Remove chosen card of winner foreach (var card in cards) { Players[winner].Hand.Remove(card); } //Is it a final win? if (Players[winner].Points != WinRequirement) { return; } ShouldStopGame = true; await channel.Send($"We have a winner! Its {winner.Mention}\n{getLeaderboard()}"); //add leaderboard await FlowersHandler.AddFlowersAsync(winner, "Won CAH", 2); return; } #endregion #region regularPlayers var msg = e.Message.Text; var cardSet = new HashSet <CAHWhiteCard>(); CAHStats stat; if (!Players.TryGetValue(e.User, out stat)) { return; } if (currentBlackCard.WhiteCards == 1) { int index; if (!int.TryParse(msg.Trim(), out index)) { return; } index--; //!!! if (index > stat.Hand.Count() - 1) { return; } cardSet.Add(stat.Hand[index]); } else { if (!Regex.IsMatch(msg, @"\d")) { return; } var matches = Regex.Matches(msg, @"\d+"); if (matches.Count < currentBlackCard.WhiteCards) { await channel.SendMessage($"Black card need {currentBlackCard.WhiteCards} cards, seperated from each other."); return; } foreach (Match m in matches) { var s = m.Value; int index; if (!int.TryParse(s, out index)) { return; } index--; //!!! if (index < 0 || index > stat.Hand.Count() - 1) { cardSet.Add(stat.Hand[index]); } } } var newIndex = getRandomIndex(); var kvp = new KeyValuePair <User, HashSet <CAHWhiteCard> >(e.User, cardSet); var containing = false; WhiteCardsAssortment.Values.ForEach(x => { if (x.Key == e.User) { containing = true; var toUpdate = WhiteCardsAssortment.Where(y => y.Value.Equals(x)).First(); WhiteCardsAssortment.TryUpdate(toUpdate.Key, kvp, toUpdate.Value); } }); if (!containing) { WhiteCardsAssortment.TryAdd(newIndex, kvp); } //chosenWhiteCards.Add(e.User, stat.Hand[index]); //catch the outofRangeExceptions var unset = unSetPlayers(); await channel.SendMessage($"Registered chosen card(s) for {e.User.Mention}\n{unset}"); if (unset == String.Empty) //There are no players who haven't chosen yet { allChosen = true; } #endregion } catch (IndexOutOfRangeException) { //This shouldn't happen anymore await channel.SendMessage("Index given was out of range"); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
internal override void Init(CommandGroupBuilder cgb) { cgb.CreateCommand(Module.Prefix + "pick") .Description($"Nimmt einen in diesem Channel hinterlegten {MidnightBot.Config.CurrencyName}. | `{Prefix}pick`") .Do(async e => { IEnumerable <Message> msgs; await e.Message.Delete().ConfigureAwait(false); if (!plantedFlowerChannels.TryRemove(e.Channel.Id, out msgs)) { return; } foreach (var msgToDelete in msgs) { await msgToDelete.Delete().ConfigureAwait(false); } await FlowersHandler.AddFlowersAsync(e.User, "Took a dollar.", 1, true).ConfigureAwait(false); var msg = await e.Channel.SendMessage($"**{e.User.Name}** hat den {MidnightBot.Config.CurrencyName} aufgehoben!").ConfigureAwait(false); ThreadPool.QueueUserWorkItem(async(state) => { try { await Task.Delay(10000).ConfigureAwait(false); await msg.Delete().ConfigureAwait(false); } catch { } }); }); cgb.CreateCommand(Module.Prefix + "plant") .Description($"Gib einen {MidnightBot.Config.CurrencyName} aus, um in in diesen Channel zu legen. (Wenn der Bot neustartet, oder crashed, ist der {MidnightBot.Config.CurrencyName} verloren) | `{Prefix}plant`") .Do(async e => { await locker.WaitAsync().ConfigureAwait(false); try { if (plantedFlowerChannels.ContainsKey(e.Channel.Id)) { await e.Channel.SendMessage($"Hier liegt bereits ein {MidnightBot.Config.CurrencyName} in diesem Channel.").ConfigureAwait(false); return; } var removed = await FlowersHandler.RemoveFlowers(e.User, "Planted a flower.", 1, true).ConfigureAwait(false); if (!removed) { await e.Channel.SendMessage($"Du hast keinen {MidnightBot.Config.CurrencyName}s.").ConfigureAwait(false); return; } var file = GetRandomCurrencyImagePath(); Message msg; if (file == null) { msg = await e.Channel.SendMessage(MidnightBot.Config.CurrencySign).ConfigureAwait(false); } else { msg = await e.Channel.SendFile(file).ConfigureAwait(false); } var vowelFirst = new[] { 'a', 'e', 'i', 'o', 'u' }.Contains(MidnightBot.Config.CurrencyName[0]); var msg2 = await e.Channel.SendMessage($"Oh wie nett! **{e.User.Name}** hinterlies {(vowelFirst ? "einen" : "einen")} {MidnightBot.Config.CurrencyName}. Nimm ihn per {Module.Prefix}pick").ConfigureAwait(false); plantedFlowerChannels.TryAdd(e.Channel.Id, new[] { msg, msg2 }); } finally { locker.Release(); } }); cgb.CreateCommand(Prefix + "gencurrency") .Alias(Prefix + "gc") .Description($"Ändert Währungs Erstellung in diesem Channel. Jede geschriebene Nachricht hat eine Chance von 2%, einen {MidnightBot.Config.CurrencyName} zu spawnen. Optionaler Parameter ist die Cooldown Zeit in Minuten. 5 Minuten sind Standard. Benötigt Manage Messages Berechtigungen | `{Prefix}gc` oder `{Prefix}gc 60`") .AddCheck(SimpleCheckers.ManageMessages()) .Parameter("cd", ParameterType.Unparsed) .Do(async e => { var cdStr = e.GetArg("cd"); int cd = 2; if (!int.TryParse(cdStr, out cd) || cd < 0) { cd = 2; } var config = SpecificConfigurations.Default.Of(e.Server.Id); int throwaway; if (config.GenerateCurrencyChannels.TryRemove(e.Channel.Id, out throwaway)) { await e.Channel.SendMessage("`Währungs Erstellung deaktiviert in diesem Channel.`").ConfigureAwait(false); } else { if (config.GenerateCurrencyChannels.TryAdd(e.Channel.Id, cd)) { await e.Channel.SendMessage($"`Währungserstellung aktiviert in diesem Channel. Cooldown ist {cd} Minuten.`").ConfigureAwait(false); } } }); }
private async Task StartRace() { var rng = new Random(); Participant winner = null; Message msg = null; int place = 1; try { NadekoBot.Client.MessageReceived += Client_MessageReceived; while (!participants.All(p => p.Total >= 60)) { //update the state participants.ForEach(p => { p.Total += 1 + rng.Next(0, 10); if (p.Total > 60) { p.Total = 60; if (winner == null) { winner = p; } if (p.Place == 0) { p.Place = place++; } } }); //draw the state var text = $@"|🏁🏁🏁🏁🏁🏁🏁🏁🏁🏁🏁🏁🏁🏁🏁🔚| {String.Join("\n", participants.Select(p => $"{(int)(p.Total / 60f * 100),-2}%|{p.ToString()}"))} |🏁🏁🏁🏁🏁🏁🏁🏁🏁🏁🏁🏁🏁🏁🏁🔚|"; if (msg == null || messagesSinceGameStarted >= 10) // also resend the message if channel was spammed { if (msg != null) { try { await msg.Delete(); } catch { } } msg = await raceChannel.SendMessage(text); messagesSinceGameStarted = 0; } else { await msg.Edit(text); } await Task.Delay(2500); } } finally { NadekoBot.Client.MessageReceived -= Client_MessageReceived; } if (winner.AmountBet > 0) { var wonAmount = winner.AmountBet * (participants.Count - 1); await FlowersHandler.AddFlowersAsync(winner.User, "Won a Race", wonAmount).ConfigureAwait(false); await raceChannel.SendMessage($"🏁 {winner.User.Mention} as {winner.Animal} **Won the race and {wonAmount}{NadekoBot.Config.CurrencySign}!**"); } else { await raceChannel.SendMessage($"🏁 {winner.User.Mention} as {winner.Animal} **Won the race!**"); } }
public override void Install(ModuleManager manager) { manager.CreateCommands("", cgb => { cgb.AddCheck(PermissionChecker.Instance); commands.ForEach(com => com.Init(cgb)); cgb.CreateCommand(Prefix + "raffle") .Description($"Schreibt den Namen und die ID eines zufälligen Benutzers aus der Online Liste einer (optionalen) Rolle. | `{Prefix}raffle` oder `{Prefix}raffle RoleName`") .Parameter("role", ParameterType.Optional) .Do(async e => { var arg = string.IsNullOrWhiteSpace(e.GetArg("role")) ? "@everyone" : e.GetArg("role"); var role = e.Server.FindRoles(arg).FirstOrDefault(); if (role == null) { await e.Channel.SendMessage("💢 Rolle nicht gefunden.").ConfigureAwait(false); return; } var members = role.Members.Where(u => u.Status == UserStatus.Online); // only online var membersArray = members as User[] ?? members.ToArray(); var usr = membersArray[new Random().Next(0, membersArray.Length)]; await e.Channel.SendMessage($"**Gezogener Benutzer:** {usr.Name} (Id: {usr.Id})").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "$$") .Description(string.Format("Überprüft, wieviele {0} du hast.", MidnightBot.Config.CurrencyName)) .Parameter("all", ParameterType.Unparsed) .Do(async e => { var usr = e.Message.MentionedUsers.FirstOrDefault() ?? e.User; var pts = GetUserFlowers(usr.Id); var str = $"{usr.Name} hat {pts} {MidnightBot.Config.CurrencyName} {MidnightBot.Config.CurrencySign}"; await e.Channel.SendMessage(str).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "award") .Description(string.Format($"Gibt jemanden eine bestimmte Anzahl an {MidnightBot.Config.CurrencyName}. **Bot Owner Only!** | `{Prefix}award 5 @Benutzer`")) .AddCheck(SimpleCheckers.OwnerOnly()) .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 != MidnightBot.Client.CurrentUser.Id); if (mentionedUser == null) { return; } await FlowersHandler.AddFlowersAsync(mentionedUser, $"Awarded by bot owner. ({e.User.Name}/{e.User.Id})", (int)amount).ConfigureAwait(false); await e.Channel.SendMessage($"{e.User.Mention} erfolgreich {amount} {MidnightBot.Config.CurrencyName} zu {mentionedUser.Mention} hinzugefügt!").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "dailymoney") .Description($"Tägliches Geld (20 Euro, wird um 0 Uhr zurückgesetzt.) | `{Prefix}dailymoney`") .Do(async e => { DateTime today = DateTime.Today; var uid = (long)e.User.Id; var sid = (long)e.Server.Id; var user = DbHandler.Instance.FindOne <DailyMoney>(dm => dm.UserId == uid && dm.ServerId == sid); if (user == null) { var data = new DailyMoney { UserId = (long)e.User.Id, LastTimeGotten = today.AddDays(-1), ServerId = (long)e.Server.Id }; DbHandler.Instance.InsertData(data); user = DbHandler.Instance.FindOne <DailyMoney>(dm => dm.UserId == uid && dm.ServerId == sid); } if (user.LastTimeGotten.Date.DayOfYear < today.Date.DayOfYear) { var data = DbHandler.Instance.FindAll <DailyMoney>(d => d.ServerId == sid && d.UserId == uid); DbHandler.Instance.UpdateAll <DailyMoney>(data.Select(i => { i.LastTimeGotten = today; return(i); })); await FlowersHandler.AddFlowersAsync(e.User, $"Daily Reward. ({e.User.Name}/{e.User.Id})", 20).ConfigureAwait(false); await e.Channel.SendMessage($"{e.User.Mention} hat sich seinen täglichen Anteil von 20 {MidnightBot.Config.CurrencyName} abgeholt."); return; } else { await e.Channel.SendMessage("Du hast deinen täglichen Anteil heute bereits abgeholt."); } }); cgb.CreateCommand(Prefix + "take") .Description(string.Format($"Entfernt eine bestimmte Anzahl an {MidnightBot.Config.CurrencyName} von jemanden. **Bot Owner Only!** | `{Prefix}take 1 \"@someguy\"`")) .AddCheck(SimpleCheckers.OwnerOnly()) .Parameter("amount", ParameterType.Required) .Parameter("rektperson", 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 != MidnightBot.Client.CurrentUser.Id); if (mentionedUser == null) { return; } await FlowersHandler.RemoveFlowers(mentionedUser, $"Taken by bot owner.({e.User.Name}/{e.User.Id})", (int)amount).ConfigureAwait(false); await e.Channel.SendMessage($"{e.User.Mention} erfolgreich {amount} {MidnightBot.Config.CurrencyName} von {mentionedUser.Mention} entfernt!").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "give") .Description($"Gibt jemanden eine Anzahl {MidnightBot.Config.CurrencyName}. |`{Prefix}give 1 \"@SomeGuy\"`") .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 != MidnightBot.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} Du hast nicht genug {MidnightBot.Config.CurrencyName}. Du hast nur {userFlowers} {MidnightBot.Config.CurrencySign}.").ConfigureAwait(false); return; } await FlowersHandler.RemoveFlowers(e.User, "Gift", (int)amount, true).ConfigureAwait(false); await FlowersHandler.AddFlowersAsync(mentionedUser, "Gift", (int)amount).ConfigureAwait(false); await e.Channel.SendMessage($"{e.User.Mention} erfolgreich {amount}{MidnightBot.Config.CurrencyName} gesendet an {mentionedUser.Mention}!").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "betroll") .Alias(Prefix + "br") .Description($"Wettet einen bestimmten Betrag an {MidnightBot.Config.CurrencyName} und wirft einen Würfel. Bei über 66 Punkten: x2 {MidnightBot.Config.CurrencyName}, über 90 Punkte: x3 und 100 x10. | `{Prefix}br 5`") .Parameter("amount", ParameterType.Required) .Do(async e => { var amountstr = e.GetArg("amount").Trim(); int amount; if (!int.TryParse(amountstr, out amount) || amount < 1) { return; } var userFlowers = GetUserFlowers(e.User.Id); if (userFlowers < amount) { await e.Channel.SendMessage($"{e.User.Mention} Du hast nicht genug {MidnightBot.Config.CurrencyName}. Du hast nur {userFlowers}{MidnightBot.Config.CurrencySign}.").ConfigureAwait(false); return; } await FlowersHandler.RemoveFlowers(e.User, "Betroll Gamble", (int)amount, true).ConfigureAwait(false); var rng = new Random().Next(0, 101); var str = $"{e.User.Mention} `Du hast folgende Punktzahl geworfen: {rng}` "; if (rng < 67) { str += "Viel Glück beim nächsten Mal."; } else if (rng < 90) { str += $"Glückwunsch! Du hast {amount * 2}{MidnightBot.Config.CurrencySign} für das erzielen von mehr als 66 Punkten gewonnen."; await FlowersHandler.AddFlowersAsync(e.User, "Betroll Gamble", amount * 2, true).ConfigureAwait(false); } else if (rng < 100) { str += $"Glückwunsch! Du hast {amount * 3}{MidnightBot.Config.CurrencySign} für das erzielen von mehr als 90 Punkten gewonnen."; await FlowersHandler.AddFlowersAsync(e.User, "Betroll Gamble", amount * 3, true).ConfigureAwait(false); } else { str += $"👑 Glückwunsch! Du hast {amount * 10}{MidnightBot.Config.CurrencySign} für das erzielen von **100** Punkten gewonnen. 👑"; await FlowersHandler.AddFlowersAsync(e.User, "Betroll Gamble", amount * 10, true).ConfigureAwait(false); } await e.Channel.SendMessage(str).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "leaderboard") .Alias(Prefix + "lb") .Description($"Displays bot currency leaderboard | {Prefix}lb") .Do(async e => { var richestTemp = DbHandler.Instance.GetTopRichest(); var richest = richestTemp as CurrencyState[] ?? richestTemp.ToArray(); if (richest.Length == 0) { return; } await e.Channel.SendMessage ( richest.Aggregate(new StringBuilder( $@"```xl ┏━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┓ ┃ Id ┃ $$$ ┃ "), (cur, cs) => cur.AppendLine( $@"┣━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━┫ ┃{(e.Server.Users.Where(u => u.Id == (ulong)cs.UserId).FirstOrDefault()?.Name.TrimTo(18, true) ?? cs.UserId.ToString()),-20} ┃ {cs.Value,5} ┃") ).ToString() + "┗━━━━━━━━━━━━━━━━━━━━━┻━━━━━━━┛```").ConfigureAwait(false); }); }); }
private async System.Threading.Tasks.Task <string> Attack(User attacker, User target, string moveString) { PokemonSprite attackerPokemon = ActivePokemon(attacker); string returnstring = ""; var species = attackerPokemon.GetSpecies(); if (!species.moves.Keys.Contains(moveString)) { returnstring = $"Kann \"{moveString}\" nicht benutzen, benutze `{Prefix}ml` um eine Liste der Attacken zu sehen"; return(returnstring); } var attackerStats = UserStats.GetOrAdd(attacker.Id, new TrainerStats()); var defenderStats = UserStats.GetOrAdd(target.Id, new TrainerStats()); if (attackerStats.MovesMade > TrainerStats.MaxMoves || attackerStats.LastAttacked.Contains(target.Id)) { returnstring = $"{attacker.Mention} kann sich nicht bewegen!"; return(returnstring); } if (attackerPokemon.HP == 0) { returnstring = $"{attackerPokemon.NickName} wurde besiegt und kann nicht angreifen!"; return(returnstring); } var defenderPokemon = ActivePokemon(target); if (defenderPokemon.HP <= 0) { returnstring = $"{defenderPokemon.NickName} wurde bereits besiegt!"; return(returnstring); } double p = 0.90 * attackerPokemon.Speed / defenderPokemon.Speed; //await e.Channel.SendMessage($"p: {p.ToString()} 1-p: {(1- p).ToString()}"); if (rng.NextDouble() < (1 - p)) { if (target.Id == MidnightBot.Creds.BotId) { attackerStats.LastAttacked.Remove(target.Id); attackerStats.MovesMade = 0; UserStats.AddOrUpdate(attacker.Id, x => attackerStats, (s, t) => attackerStats); UserStats.AddOrUpdate(target.Id, x => defenderStats, (s, t) => defenderStats); DbHandler.Instance.Save(defenderPokemon); DbHandler.Instance.Save(attackerPokemon); } else { defenderStats.LastAttacked.Remove(target.Id); attackerStats.LastAttacked.Add(target.Id); attackerStats.MovesMade++; defenderStats.LastAttacked = new List <ulong>(); defenderStats.MovesMade = 0; UserStats.AddOrUpdate(attacker.Id, x => attackerStats, (s, t) => attackerStats); UserStats.AddOrUpdate(target.Id, x => defenderStats, (s, t) => defenderStats); DbHandler.Instance.Save(defenderPokemon); DbHandler.Instance.Save(attackerPokemon); } returnstring = $"{attackerPokemon.NickName}'s Attacke fehlgeschlagen!"; return(returnstring); } KeyValuePair <string, string> move = new KeyValuePair <string, string> (moveString, species.moves[moveString]); PokemonAttack attack = new PokemonAttack(attackerPokemon, defenderPokemon, move); returnstring += attack.AttackString(); defenderPokemon.HP -= attack.Damage; var HP = (defenderPokemon.HP < 0) ? 0 : defenderPokemon.HP; returnstring += $"{defenderPokemon.NickName} hat {HP} HP über!\n"; attackerStats.LastAttacked.Add(target.Id); attackerStats.MovesMade++; defenderStats.LastAttacked = new List <ulong>(); defenderStats.MovesMade = 0; UserStats.AddOrUpdate(attacker.Id, x => attackerStats, (s, t) => attackerStats); UserStats.AddOrUpdate(target.Id, x => defenderStats, (s, t) => defenderStats); DbHandler.Instance.Save(defenderPokemon); DbHandler.Instance.Save(attackerPokemon); if (defenderPokemon.HP <= 0) { defenderPokemon.HP = 0; if (target.Id != MidnightBot.Creds.BotId) { returnstring += $"{defenderPokemon.NickName} wurde besiegt!\n{attackerPokemon.NickName}'s Besitzer {attacker.Mention} erhält 1 {MidnightBot.Config.CurrencySign}\n"; } var lvl = attackerPokemon.Level; var extraXP = attackerPokemon.Reward(defenderPokemon); returnstring += $"{attackerPokemon.NickName} erhält {extraXP} von diesem Kampf\n"; if (attackerPokemon.Level > lvl) //levled up { returnstring += $"**{attackerPokemon.NickName}** ist aufgelevelt!\n**{attackerPokemon.NickName}** ist nun Level **{attackerPokemon.Level}**"; //Check evostatus } if (target.Id != MidnightBot.Creds.BotId) { var list = PokemonList(target).Where(s => (s.HP > 0 && s != defenderPokemon)); if (list.Any()) { var toSet = list.FirstOrDefault(); switch (SwitchPokemon(target, toSet)) { case 0: { returnstring += $"\n{target.Mention}'s aktives Pokemon auf **{toSet.NickName}** gesetzt"; defenderPokemon.IsActive = false; break; } case 1: case 2: { returnstring += $"\n **Error:** konnte Pokemon nicht austauschen"; break; } } } else { returnstring += $"\n{target.Mention} hat keine Pokemon über!"; returnstring += $"\n{attacker.Mention} erhält 3 {MidnightBot.Config.CurrencySign} für das Besiegen von {target.Mention}"; await FlowersHandler.AddFlowersAsync(attacker, $"Defeated {target.Mention} in pokemon!", 3); //do something? } } //await e.Channel.SendMessage(str); if (target.Id != MidnightBot.Creds.BotId) { await FlowersHandler.AddFlowersAsync(attacker, "Victorious in pokemon", 1, true); } } //Update stats, you shall defenderStats.LastAttacked.Remove(target.Id); attackerStats.LastAttacked.Add(target.Id); attackerStats.MovesMade++; defenderStats.LastAttacked = new List <ulong>(); defenderStats.MovesMade = 0; UserStats.AddOrUpdate(attacker.Id, x => attackerStats, (s, t) => attackerStats); UserStats.AddOrUpdate(target.Id, x => defenderStats, (s, t) => defenderStats); DbHandler.Instance.Save(defenderPokemon); DbHandler.Instance.Save(attackerPokemon); if (defenderPokemon.HP == 0 && target.Id == MidnightBot.Creds.BotId) { var db = DbHandler.Instance.GetAllRows <PokemonSprite> (); var row = db.Where(x => x.OwnerId == (long)MidnightBot.Creds.BotId); //var toDelete = DbHandler.Instance.FindAll<PokemonSprite>(s => s.OwnerId == (long)e.User.Id); foreach (var todel in row) { DbHandler.Instance.Delete <PokemonSprite>(todel.Id.Value); } PokemonList(target, attackerPokemon.Level); } return(returnstring); }