Added many more braces for multiline if's, Improved .crypto command quite a bit and applied locale-specific format

This commit is contained in:
Kwoth
2022-02-04 06:00:17 +01:00
parent f77f2f433f
commit eda38e64d1
129 changed files with 635 additions and 233 deletions

View File

@@ -131,9 +131,11 @@ public sealed class AnimalRace : IDisposable
}
if (FinishedUsers[0].Bet > 0)
{
await _currency.AddAsync(FinishedUsers[0].UserId,
FinishedUsers[0].Bet * (_users.Count - 1),
new("animalrace", "win"));
}
_ = OnEnded?.Invoke(this);
});

View File

@@ -53,8 +53,10 @@ public partial class Gambling
try
{
if (arg.Channel.Id == ctx.Channel.Id)
{
if (ar.CurrentPhase == AnimalRace.Phase.Running && ++count % 9 == 0)
raceMessage = null;
}
}
catch { }
});
@@ -67,10 +69,13 @@ public partial class Gambling
_service.AnimalRaces.TryRemove(ctx.Guild.Id, out _);
var winner = race.FinishedUsers[0];
if (race.FinishedUsers[0].Bet > 0)
{
return SendConfirmAsync(GetText(strs.animal_race),
GetText(strs.animal_race_won_money(Format.Bold(winner.Username),
winner.Animal.Icon,
(race.FinishedUsers[0].Bet * (race.Users.Count - 1)) + CurrencySign)));
}
return SendConfirmAsync(GetText(strs.animal_race),
GetText(strs.animal_race_won(Format.Bold(winner.Username), winner.Animal.Icon)));
}
@@ -110,11 +115,13 @@ public partial class Gambling
if (msg is null)
raceMessage = await SendConfirmAsync(text);
else
{
await msg.ModifyAsync(x => x.Embed = _eb.Create()
.WithTitle(GetText(strs.animal_race))
.WithDescription(text)
.WithOkColor()
.Build());
}
}
private Task Ar_OnStartingFailed(AnimalRace race)
@@ -140,9 +147,11 @@ public partial class Gambling
{
var user = await ar.JoinRace(ctx.User.Id, ctx.User.ToString(), amount);
if (amount > 0)
{
await SendConfirmAsync(GetText(strs.animal_race_join_bet(ctx.User.Mention,
user.Animal.Icon,
amount + CurrencySign)));
}
else
await SendConfirmAsync(GetText(strs.animal_race_join(ctx.User.Mention, user.Animal.Icon)));
}

View File

@@ -56,9 +56,11 @@ public partial class Gambling
if (await bj.Join(ctx.User, amount))
await ReplyConfirmLocalizedAsync(strs.bj_joined);
else
{
Log.Information("{User} can't join a blackjack game as it's in {BlackjackState} state already",
ctx.User,
bj.State);
}
}
await ctx.Message.DeleteAsync();
@@ -114,21 +116,13 @@ public partial class Gambling
full = "✅ " + full;
}
else if (p == bj.CurrentUser)
{
full = "▶ " + full;
}
else if (p.State == User.UserState.Stand)
{
full = "⏹ " + full;
}
else if (p.State == User.UserState.Bust)
{
full = "💥 " + full;
}
else if (p.State == User.UserState.Blackjack)
{
full = "💰 " + full;
}
embed.AddField(full, cStr);
}
@@ -177,8 +171,10 @@ public partial class Gambling
else if (a == BjAction.Stand)
await bj.Stand(ctx.User);
else if (a == BjAction.Double)
{
if (!await bj.Double(ctx.User))
await ReplyErrorLocalizedAsync(strs.not_enough(CurrencySign));
}
await ctx.Message.DeleteAsync();
}

View File

@@ -202,6 +202,7 @@ public class Blackjack
}
if (hw > 21)
{
foreach (var usr in Players)
{
if (usr.State is User.UserState.Stand or User.UserState.Blackjack)
@@ -209,7 +210,9 @@ public class Blackjack
else
usr.State = User.UserState.Lost;
}
}
else
{
foreach (var usr in Players)
{
if (usr.State == User.UserState.Blackjack)
@@ -219,6 +222,7 @@ public class Blackjack
else
usr.State = User.UserState.Lost;
}
}
foreach (var usr in Players)
{

View File

@@ -129,9 +129,7 @@ public sealed class Connect4Game : IDisposable
_players[0] = (userId, userName);
}
else //else join as a second player
{
_players[1] = (userId, userName);
}
CurrentPhase = Phase.P1Move; //start the game
playerTimeoutTimer = new(async _ =>
@@ -197,6 +195,7 @@ public sealed class Connect4Game : IDisposable
var first = _gameState[i + (j * NUMBER_OF_ROWS)];
if (first != Field.Empty)
{
for (var k = 1; k < 4; k++)
{
var next = _gameState[i + k + (j * NUMBER_OF_ROWS)];
@@ -208,10 +207,9 @@ public sealed class Connect4Game : IDisposable
continue;
}
else
{
break;
}
}
}
}
}
@@ -228,17 +226,21 @@ public sealed class Connect4Game : IDisposable
var first = _gameState[j + (i * NUMBER_OF_ROWS)];
if (first != Field.Empty)
{
for (var k = 1; k < 4; k++)
{
var next = _gameState[j + ((i + k) * NUMBER_OF_ROWS)];
if (next == first)
{
if (k == 3)
EndGame(Result.CurrentPlayerWon, CurrentPlayer.UserId);
else
continue;
}
else
break;
}
}
}
}

View File

@@ -65,6 +65,7 @@ public partial class Gambling
}
if (options.Bet > 0)
{
if (!await _cs.RemoveAsync(ctx.User.Id, options.Bet, new("connect4", "bet")))
{
await ReplyErrorLocalizedAsync(strs.not_enough(CurrencySign));
@@ -72,6 +73,7 @@ public partial class Gambling
game.Dispose();
return;
}
}
game.OnGameStateUpdated += Game_OnGameStateUpdated;
game.OnGameFailedToStart += GameOnGameFailedToStart;
@@ -106,8 +108,10 @@ public partial class Gambling
return;
RepostCounter++;
if (RepostCounter == 0)
{
try { msg = await ctx.Channel.SendMessageAsync("", embed: (Embed)msg.Embeds.First()); }
catch { }
}
}
});
return Task.CompletedTask;
@@ -134,11 +138,15 @@ public partial class Gambling
string title;
if (result == Connect4Game.Result.CurrentPlayerWon)
{
title = GetText(strs.connect4_won(Format.Bold(arg.CurrentPlayer.Username),
Format.Bold(arg.OtherPlayer.Username)));
}
else if (result == Connect4Game.Result.OtherPlayerWon)
{
title = GetText(strs.connect4_won(Format.Bold(arg.OtherPlayer.Username),
Format.Bold(arg.CurrentPlayer.Username)));
}
else
title = GetText(strs.connect4_draw);

View File

@@ -82,6 +82,7 @@ public partial class Gambling
if (randomNumber == 6 || dice.Count == 0)
toInsert = 0;
else if (randomNumber != 1)
{
for (var j = 0; j < dice.Count; j++)
{
if (values[j] < randomNumber)
@@ -90,11 +91,10 @@ public partial class Gambling
break;
}
}
}
}
else
{
toInsert = dice.Count;
}
dice.Insert(toInsert, GetDice(randomNumber));
values.Insert(toInsert, randomNumber);
@@ -190,9 +190,7 @@ public partial class Gambling
rolled = new NadekoRandom().Next(arr[0], arr[1] + 1);
}
else
{
rolled = new NadekoRandom().Next(0, int.Parse(range) + 1);
}
await ReplyConfirmLocalizedAsync(strs.dice_rolled(Format.Bold(rolled.ToString())));
}

View File

@@ -43,6 +43,7 @@ public class CurrencyEventsService : INService
var added = _events.TryAdd(guildId, ce);
if (added)
{
try
{
ce.OnEnded += OnEventEnded;
@@ -54,6 +55,7 @@ public class CurrencyEventsService : INService
_events.TryRemove(guildId, out ce);
return false;
}
}
return added;
}

View File

@@ -82,6 +82,7 @@ public class GameStatusEvent : ICurrencyEvent
);
if (_isPotLimited)
{
await msg.ModifyAsync(m =>
{
m.Embed = GetEmbed(PotSize).Build();
@@ -90,6 +91,7 @@ public class GameStatusEvent : ICurrencyEvent
{
RetryMode = RetryMode.AlwaysRetry
});
}
Log.Information("Awarded {Count} users {Amount} currency.{Remaining}",
toAward.Count,
@@ -179,6 +181,7 @@ public class GameStatusEvent : ICurrencyEvent
private bool TryTakeFromPot()
{
if (_isPotLimited)
{
lock (_potLock)
{
if (PotSize < _amount)
@@ -187,6 +190,7 @@ public class GameStatusEvent : ICurrencyEvent
PotSize -= _amount;
return true;
}
}
return true;
}

View File

@@ -75,6 +75,7 @@ public class ReactionEvent : ICurrencyEvent
await _cs.AddBulkAsync(toAward, _amount, new("event", "reaction"));
if (_isPotLimited)
{
await msg.ModifyAsync(m =>
{
m.Embed = GetEmbed(PotSize).Build();
@@ -83,6 +84,7 @@ public class ReactionEvent : ICurrencyEvent
{
RetryMode = RetryMode.AlwaysRetry
});
}
Log.Information("Awarded {Count} users {Amount} currency.{Remaining}",
toAward.Count,
@@ -178,6 +180,7 @@ public class ReactionEvent : ICurrencyEvent
private bool TryTakeFromPot()
{
if (_isPotLimited)
{
lock (_potLock)
{
if (PotSize < _amount)
@@ -186,6 +189,7 @@ public class ReactionEvent : ICurrencyEvent
PotSize -= _amount;
return true;
}
}
return true;
}

View File

@@ -75,7 +75,7 @@ public partial class Gambling
+ GetText(strs.flipped(headCount > 0
? Format.Bold(GetText(strs.heads))
: Format.Bold(GetText(strs.tails))));
await ctx.Channel.SendFileAsync(stream, $"{count} coins.{format.FileExtensions.First()}", msg);
}
@@ -114,9 +114,7 @@ public partial class Gambling
await _cs.AddAsync(ctx.User, toWin, new("betflip", "win"));
}
else
{
str = Format.Bold(ctx.User.ToString()) + " " + GetText(strs.better_luck);
}
await ctx.Channel.EmbedAsync(_eb.Create()
.WithDescription(str)

View File

@@ -8,7 +8,6 @@ using NadekoBot.Modules.Gambling.Services;
using NadekoBot.Services.Currency;
using NadekoBot.Services.Database.Models;
using System.Globalization;
using System.Numerics;
using System.Text;
namespace NadekoBot.Modules.Gambling;
@@ -79,13 +78,15 @@ public partial class Gambling : GamblingModule<GamblingService>
// This stops the top 1% from owning more than 100% of the money
if (ec.Cash > 0)
{
onePercent = ec.OnePercent / (ec.Cash - ec.Bot);
}
// [21:03] Bob Page: Kinda remids me of US economy
var embed = _eb.Create()
.WithTitle(GetText(strs.economy_state))
.AddField(GetText(strs.currency_owned),
N((ec.Cash - ec.Bot)))
N(ec.Cash - ec.Bot))
.AddField(GetText(strs.currency_one_percent), (onePercent * 100).ToString("F2") + "%")
.AddField(GetText(strs.currency_planted), N(ec.Planted))
.AddField(GetText(strs.owned_waifus_total), N(ec.Waifus))
@@ -132,7 +133,9 @@ public partial class Gambling : GamblingModule<GamblingService>
public async partial Task TimelySet(int amount, int period = 24)
{
if (amount < 0 || period < 0)
{
return;
}
_configService.ModifyConfig(gs =>
{
@@ -141,9 +144,13 @@ public partial class Gambling : GamblingModule<GamblingService>
});
if (amount == 0)
{
await ReplyConfirmLocalizedAsync(strs.timely_set_none);
}
else
{
await ReplyConfirmLocalizedAsync(strs.timely_set(Format.Bold(N(amount)), Format.Bold(period.ToString())));
}
}
[Cmd]
@@ -155,7 +162,10 @@ public partial class Gambling : GamblingModule<GamblingService>
var members = (await role.GetMembersAsync()).Where(u => u.Status != UserStatus.Offline);
var membersArray = members as IUser[] ?? members.ToArray();
if (membersArray.Length == 0)
{
return;
}
var usr = membersArray[new NadekoRandom().Next(0, membersArray.Length)];
await SendConfirmAsync("🎟 " + GetText(strs.raffled_user),
$"**{usr.Username}#{usr.Discriminator}**",
@@ -171,7 +181,10 @@ public partial class Gambling : GamblingModule<GamblingService>
var members = await role.GetMembersAsync();
var membersArray = members as IUser[] ?? members.ToArray();
if (membersArray.Length == 0)
{
return;
}
var usr = membersArray[new NadekoRandom().Next(0, membersArray.Length)];
await SendConfirmAsync("🎟 " + GetText(strs.raffled_user),
$"**{usr.Username}#{usr.Discriminator}**",
@@ -198,7 +211,9 @@ public partial class Gambling : GamblingModule<GamblingService>
private async Task InternalCurrencyTransactions(ulong userId, int page)
{
if (--page < 0)
{
return;
}
List<CurrencyTransaction> trs;
await using (var uow = _db.GetDbContext())
@@ -222,10 +237,14 @@ public partial class Gambling : GamblingModule<GamblingService>
sb.AppendLine($"\\{change} {date} {Format.Bold(N(tr.Amount))}");
var transactionString = GetHumanReadableTransaction(tr.Type, tr.Extra, tr.OtherId);
if (transactionString is not null)
{
sb.AppendLine(transactionString);
}
if (!string.IsNullOrWhiteSpace(tr.Note))
{
sb.AppendLine($"\t`Note:` {tr.Note.TrimTo(50)}");
}
}
embed.WithDescription(sb.ToString());
@@ -264,10 +283,14 @@ public partial class Gambling : GamblingModule<GamblingService>
eb.AddField("Extra", tr.Extra, true);
if (tr.OtherId is ulong other)
{
eb.AddField("From Id", other);
}
if (!string.IsNullOrWhiteSpace(tr.Note))
{
eb.AddField("Note", tr.Note);
}
eb.WithFooter(GetFormattedCurtrDate(tr));
@@ -313,7 +336,9 @@ public partial class Gambling : GamblingModule<GamblingService>
public async partial Task Give(ShmartNumber amount, IGuildUser receiver, [Leftover] string msg)
{
if (amount <= 0 || ctx.User.Id == receiver.Id || receiver.IsBot)
{
return;
}
if (!await _cs.TransferAsync(ctx.User.Id, receiver.Id, amount, ctx.User.ToString(), msg))
{
@@ -350,7 +375,9 @@ public partial class Gambling : GamblingModule<GamblingService>
public async partial Task Award(long amount, ulong usrId, [Leftover] string msg = null)
{
if (amount <= 0)
{
return;
}
var usr = await ((DiscordSocketClient)Context.Client).Rest.GetUserAsync(usrId);
@@ -414,7 +441,9 @@ public partial class Gambling : GamblingModule<GamblingService>
public async partial Task Take(long amount, [Leftover] IGuildUser user)
{
if (amount <= 0)
{
return;
}
var extra = new TxData("take",
ctx.User.ToString()!,
@@ -422,9 +451,13 @@ public partial class Gambling : GamblingModule<GamblingService>
ctx.User.Id);
if (await _cs.RemoveAsync(user.Id, amount, extra))
{
await ReplyConfirmLocalizedAsync(strs.take(N(amount), Format.Bold(user.ToString())));
}
else
{
await ReplyErrorLocalizedAsync(strs.take_fail(N(amount), Format.Bold(user.ToString()), CurrencySign));
}
}
@@ -433,7 +466,9 @@ public partial class Gambling : GamblingModule<GamblingService>
public async partial Task Take(long amount, [Leftover] ulong usrId)
{
if (amount <= 0)
{
return;
}
var extra = new TxData("take",
ctx.User.ToString()!,
@@ -441,9 +476,13 @@ public partial class Gambling : GamblingModule<GamblingService>
ctx.User.Id);
if (await _cs.RemoveAsync(usrId, amount, extra))
{
await ReplyConfirmLocalizedAsync(strs.take(N(amount), $"<@{usrId}>"));
}
else
{
await ReplyErrorLocalizedAsync(strs.take_fail(N(amount), Format.Code(usrId.ToString()), CurrencySign));
}
}
[Cmd]
@@ -451,12 +490,16 @@ public partial class Gambling : GamblingModule<GamblingService>
public async partial Task RollDuel(IUser u)
{
if (ctx.User.Id == u.Id)
{
return;
}
//since the challenge is created by another user, we need to reverse the ids
//if it gets removed, means challenge is accepted
if (_service.Duels.TryRemove((ctx.User.Id, u.Id), out var game))
{
await game.StartGame();
}
}
[Cmd]
@@ -464,10 +507,14 @@ public partial class Gambling : GamblingModule<GamblingService>
public async partial Task RollDuel(ShmartNumber amount, IUser u)
{
if (ctx.User.Id == u.Id)
{
return;
}
if (amount <= 0)
{
return;
}
var embed = _eb.Create().WithOkColor().WithTitle(GetText(strs.roll_duel));
@@ -478,9 +525,14 @@ public partial class Gambling : GamblingModule<GamblingService>
if (_service.Duels.TryGetValue((ctx.User.Id, u.Id), out var other))
{
if (other.Amount != amount)
{
await ReplyErrorLocalizedAsync(strs.roll_duel_already_challenged);
}
else
{
await RollDuel(u);
}
return;
}
@@ -504,12 +556,16 @@ public partial class Gambling : GamblingModule<GamblingService>
embed = embed.WithDescription(description);
if (rdMsg is null)
{
rdMsg = await ctx.Channel.EmbedAsync(embed);
}
else
{
await rdMsg.ModifyAsync(x =>
{
x.Embed = embed.Build();
});
}
}
async Task GameOnEnded(RollDuelGame rdGame, RollDuelGame.Reason reason)
@@ -544,7 +600,9 @@ public partial class Gambling : GamblingModule<GamblingService>
private async Task InternallBetroll(long amount)
{
if (!await CheckBetMandatory(amount))
{
return;
}
if (!await _cs.RemoveAsync(ctx.User, amount, new("betroll", "bet")))
{
@@ -588,14 +646,18 @@ public partial class Gambling : GamblingModule<GamblingService>
public async partial Task Leaderboard(int page = 1, params string[] args)
{
if (--page < 0)
{
return;
}
var (opts, _) = OptionsParser.ParseFrom(new LbOpts(), args);
List<DiscordUser> cleanRichest;
// it's pointless to have clean on dm context
if (ctx.Guild is null)
{
opts.Clean = false;
}
if (opts.Clean)
{
@@ -658,7 +720,9 @@ public partial class Gambling : GamblingModule<GamblingService>
public async partial Task Rps(RpsPick pick, ShmartNumber amount = default)
{
if (!await CheckBetOptional(amount) || amount == 1)
{
return;
}
string GetRpsPick(RpsPick p)
{
@@ -678,6 +742,7 @@ public partial class Gambling : GamblingModule<GamblingService>
var nadekoPick = (RpsPick)new NadekoRandom().Next(0, 3);
if (amount > 0)
{
if (!await _cs.RemoveAsync(ctx.User.Id,
amount,
new("rps", "bet", "")))
@@ -685,6 +750,7 @@ public partial class Gambling : GamblingModule<GamblingService>
await ReplyErrorLocalizedAsync(strs.not_enough(CurrencySign));
return;
}
}
string msg;
if (pick == nadekoPick)

View File

@@ -14,11 +14,10 @@ public sealed class GamblingConfigService : ConfigServiceBase<GamblingConfig>
private readonly IEnumerable<WaifuItemModel> _antiGiftSeed = new[]
{
new WaifuItemModel("🥀", 100, "WiltedRose", true),
new WaifuItemModel("✂️", 1000, "Haircut", true),
new WaifuItemModel("🥀", 100, "WiltedRose", true), new WaifuItemModel("✂️", 1000, "Haircut", true),
new WaifuItemModel("🧻", 10000, "ToiletPaper", true)
};
public GamblingConfigService(IConfigSeria serializer, IPubSub pubSub)
: base(FILE_PATH, serializer, pubSub, _changeKey)
{
@@ -26,7 +25,7 @@ public sealed class GamblingConfigService : ConfigServiceBase<GamblingConfig>
gs => gs.Currency.Name,
ConfigParsers.String,
ConfigPrinters.ToString);
AddParsedProp("currency.sign",
gs => gs.Currency.Sign,
ConfigParsers.String,
@@ -37,7 +36,7 @@ public sealed class GamblingConfigService : ConfigServiceBase<GamblingConfig>
int.TryParse,
ConfigPrinters.ToString,
val => val >= 0);
AddParsedProp("maxbet",
gs => gs.MaxBet,
int.TryParse,
@@ -49,19 +48,19 @@ public sealed class GamblingConfigService : ConfigServiceBase<GamblingConfig>
int.TryParse,
ConfigPrinters.ToString,
val => val >= 1);
AddParsedProp("gen.max",
gs => gs.Generation.MaxAmount,
int.TryParse,
ConfigPrinters.ToString,
val => val >= 1);
AddParsedProp("gen.cd",
gs => gs.Generation.GenCooldown,
int.TryParse,
ConfigPrinters.ToString,
val => val > 0);
AddParsedProp("gen.chance",
gs => gs.Generation.Chance,
decimal.TryParse,
@@ -72,73 +71,73 @@ public sealed class GamblingConfigService : ConfigServiceBase<GamblingConfig>
gs => gs.Generation.HasPassword,
bool.TryParse,
ConfigPrinters.ToString);
AddParsedProp("bf.multi",
gs => gs.BetFlip.Multiplier,
decimal.TryParse,
ConfigPrinters.ToString,
val => val >= 1);
AddParsedProp("waifu.min_price",
gs => gs.Waifu.MinPrice,
long.TryParse,
ConfigPrinters.ToString,
val => val >= 0);
AddParsedProp("waifu.multi.reset",
gs => gs.Waifu.Multipliers.WaifuReset,
int.TryParse,
ConfigPrinters.ToString,
val => val >= 0);
AddParsedProp("waifu.multi.crush_claim",
gs => gs.Waifu.Multipliers.CrushClaim,
decimal.TryParse,
ConfigPrinters.ToString,
val => val >= 0);
AddParsedProp("waifu.multi.normal_claim",
gs => gs.Waifu.Multipliers.NormalClaim,
decimal.TryParse,
ConfigPrinters.ToString,
val => val > 0);
AddParsedProp("waifu.multi.divorce_value",
gs => gs.Waifu.Multipliers.DivorceNewValue,
decimal.TryParse,
ConfigPrinters.ToString,
val => val > 0);
AddParsedProp("waifu.multi.all_gifts",
gs => gs.Waifu.Multipliers.AllGiftPrices,
decimal.TryParse,
ConfigPrinters.ToString,
val => val > 0);
AddParsedProp("waifu.multi.gift_effect",
gs => gs.Waifu.Multipliers.GiftEffect,
decimal.TryParse,
ConfigPrinters.ToString,
val => val >= 0);
AddParsedProp("waifu.multi.negative_gift_effect",
gs => gs.Waifu.Multipliers.NegativeGiftEffect,
decimal.TryParse,
ConfigPrinters.ToString,
val => val >= 0);
AddParsedProp("decay.percent",
gs => gs.Decay.Percent,
decimal.TryParse,
ConfigPrinters.ToString,
val => val is >= 0 and <= 1);
AddParsedProp("decay.maxdecay",
gs => gs.Decay.MaxDecay,
int.TryParse,
ConfigPrinters.ToString,
val => val >= 0);
AddParsedProp("decay.threshold",
gs => gs.Decay.MinThreshold,
int.TryParse,
@@ -151,23 +150,29 @@ public sealed class GamblingConfigService : ConfigServiceBase<GamblingConfig>
public void Migrate()
{
if (data.Version < 2)
{
ModifyConfig(c =>
{
c.Waifu.Items = c.Waifu.Items.Concat(_antiGiftSeed).ToList();
c.Version = 2;
});
}
if (data.Version < 3)
{
ModifyConfig(c =>
{
c.Version = 3;
c.VoteReward = 100;
});
if(data.Version < 5)
}
if (data.Version < 5)
{
ModifyConfig(c =>
{
c.Version = 5;
});
}
}
}

View File

@@ -70,12 +70,12 @@ public class GamblingService : INService, IReadyExecutor
}
}
}
private async Task CurrencyDecayLoopAsync()
{
if (_bot.Client.ShardId != 0)
return;
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(5));
while (await timer.WaitForNextTickAsync())
{
@@ -125,16 +125,18 @@ WHERE CurrencyAmount > {config.Decay.MinThreshold} AND UserId!={_client.CurrentU
}
}
}
public async Task<SlotResponse> SlotAsync(ulong userId, long amount)
{
var takeRes = await _cs.RemoveAsync(userId, amount, new("slot", "bet"));
if (!takeRes)
{
return new()
{
Error = GamblingError.NotEnough
};
}
var game = new SlotGame();
var result = game.Spin();
@@ -161,11 +163,13 @@ WHERE CurrencyAmount > {config.Decay.MinThreshold} AND UserId!={_client.CurrentU
public EconomyResult GetEconomy()
{
if (_cache.TryGetEconomy(out var data))
{
try
{
return JsonConvert.DeserializeObject<EconomyResult>(data);
}
catch { }
}
decimal cash;
decimal onePercent;

View File

@@ -1,7 +1,6 @@
#nullable disable
using NadekoBot.Modules.Gambling.Services;
using System.Globalization;
using System.Runtime;
namespace NadekoBot.Modules.Gambling.Common;
@@ -39,8 +38,9 @@ public abstract class GamblingModule<TService> : NadekoModule<TService>
return true;
}
protected string N<T>(T cur) where T : INumber<T>
protected string N<T>(T cur)
where T : INumber<T>
{
var flowersCi = (CultureInfo)Culture.Clone();
flowersCi.NumberFormat.CurrencySymbol = CurrencySign;

View File

@@ -31,12 +31,14 @@ public partial class Gambling
}
if (((SocketGuild)ctx.Guild).CurrentUser.GuildPermissions.ManageMessages)
{
try
{
_logService.AddDeleteIgnore(ctx.Message.Id);
await ctx.Message.DeleteAsync();
}
catch { }
}
}
[Cmd]
@@ -61,7 +63,7 @@ public partial class Gambling
ctx.User.ToString(),
amount,
pass);
if (!success)
await ReplyErrorLocalizedAsync(strs.not_enough(CurrencySign));
}

View File

@@ -52,6 +52,7 @@ public class CurrencyRaffleService : INService
}
if (newGame)
{
_ = Task.Run(async () =>
{
await Task.Delay(60000);
@@ -68,6 +69,7 @@ public class CurrencyRaffleService : INService
catch { }
finally { _locker.Release(); }
});
}
return (crg, null);
}

View File

@@ -182,8 +182,10 @@ public partial class Gambling
.ShopEntries);
entry = entries.ElementAtOrDefault(index);
if (entry is not null)
{
if (entry.Items.Add(item))
uow.SaveChanges();
}
}
await ReplyErrorLocalizedAsync(strs.shop_buy_error);
@@ -193,9 +195,7 @@ public partial class Gambling
await ReplyConfirmLocalizedAsync(strs.shop_item_purchase);
}
else
{
await ReplyErrorLocalizedAsync(strs.not_enough(CurrencySign));
}
}
}
@@ -291,11 +291,13 @@ public partial class Gambling
.ShopEntries);
entry = entries.ElementAtOrDefault(index);
if (entry is not null && (rightType = entry.Type == ShopEntryType.List))
{
if (entry.Items.Add(item))
{
added = true;
uow.SaveChanges();
}
}
}
if (entry is null)
@@ -353,9 +355,7 @@ public partial class Gambling
await ctx.OkAsync();
}
else
{
await ctx.ErrorAsync();
}
}
[Cmd]
@@ -373,9 +373,7 @@ public partial class Gambling
await ctx.OkAsync();
}
else
{
await ctx.ErrorAsync();
}
}
[Cmd]
@@ -393,9 +391,7 @@ public partial class Gambling
await ctx.OkAsync();
}
else
{
await ctx.ErrorAsync();
}
}
[Cmd]
@@ -413,9 +409,7 @@ public partial class Gambling
await ctx.OkAsync();
}
else
{
await ctx.ErrorAsync();
}
}
public IEmbedBuilder EntryToEmbed(ShopEntry entry)
@@ -423,6 +417,7 @@ public partial class Gambling
var embed = _eb.Create().WithOkColor();
if (entry.Type == ShopEntryType.Role)
{
return embed
.AddField(GetText(strs.name),
GetText(strs.shop_role(Format.Bold(ctx.Guild.GetRole(entry.RoleId)?.Name
@@ -430,11 +425,14 @@ public partial class Gambling
true)
.AddField(GetText(strs.price), N(entry.Price), true)
.AddField(GetText(strs.type), entry.Type.ToString(), true);
}
if (entry.Type == ShopEntryType.List)
{
return embed.AddField(GetText(strs.name), entry.Name, true)
.AddField(GetText(strs.price), N(entry.Price), true)
.AddField(GetText(strs.type), GetText(strs.random_unique_item), true);
}
//else if (entry.Type == ShopEntryType.Infinite_List)
// return embed.AddField(GetText(strs.name), GetText(strs.shop_role(Format.Bold(entry.RoleName)), true))

View File

@@ -135,16 +135,20 @@ public partial class Gambling
var (w, result, amount, remaining) = await _service.DivorceWaifuAsync(ctx.User, targetId);
if (result == DivorceResult.SucessWithPenalty)
{
await ReplyConfirmLocalizedAsync(strs.waifu_divorced_like(Format.Bold(w.Waifu.ToString()),
N(amount)));
}
else if (result == DivorceResult.Success)
await ReplyConfirmLocalizedAsync(strs.waifu_divorced_notlike(N(amount)));
else if (result == DivorceResult.NotYourWife)
await ReplyErrorLocalizedAsync(strs.waifu_not_yours);
else
{
await ReplyErrorLocalizedAsync(strs.waifu_recent_divorce(
Format.Bold(((int)remaining?.TotalHours).ToString()),
Format.Bold(remaining?.Minutes.ToString())));
}
}
[Cmd]
@@ -161,11 +165,14 @@ public partial class Gambling
if (!sucess)
{
if (remaining is not null)
{
await ReplyErrorLocalizedAsync(strs.waifu_affinity_cooldown(
Format.Bold(((int)remaining?.TotalHours).ToString()),
Format.Bold(remaining?.Minutes.ToString())));
}
else
await ReplyErrorLocalizedAsync(strs.waifu_affinity_already);
return;
}
@@ -174,8 +181,10 @@ public partial class Gambling
else if (oldAff is null)
await ReplyConfirmLocalizedAsync(strs.waifu_affinity_set(Format.Bold(user.ToString())));
else
{
await ReplyConfirmLocalizedAsync(strs.waifu_affinity_changed(Format.Bold(oldAff.ToString()),
Format.Bold(user.ToString())));
}
}
[Cmd]
@@ -323,8 +332,10 @@ public partial class Gambling
var sucess = await _service.GiftWaifuAsync(ctx.User, waifu, item);
if (sucess)
{
await ReplyConfirmLocalizedAsync(strs.waifu_gift(Format.Bold(item + " " + item.ItemEmoji),
Format.Bold(waifu.ToString())));
}
else
await ReplyErrorLocalizedAsync(strs.not_enough(CurrencySign));
}

View File

@@ -99,7 +99,8 @@ public class WaifuService : INService, IReadyExecutor
.GroupBy(x => x.New)
.Count();
return (long)Math.Ceiling(waifu.Price * 1.25f) + ((divorces + affs + 2) * settings.Waifu.Multipliers.WaifuReset);
return (long)Math.Ceiling(waifu.Price * 1.25f)
+ ((divorces + affs + 2) * settings.Waifu.Multipliers.WaifuReset);
}
public async Task<bool> TryReset(IUser user)
@@ -154,9 +155,7 @@ public class WaifuService : INService, IReadyExecutor
var claimer = uow.GetOrCreateUser(user);
var waifu = uow.GetOrCreateUser(target);
if (!await _cs.RemoveAsync(user.Id, amount, new("waifu", "claim")))
{
result = WaifuClaimResult.NotEnoughFunds;
}
else
{
uow.WaifuInfo.Add(w = new()
@@ -179,9 +178,7 @@ public class WaifuService : INService, IReadyExecutor
else if (isAffinity && amount > w.Price * settings.Waifu.Multipliers.CrushClaim)
{
if (!await _cs.RemoveAsync(user.Id, amount, new("waifu", "claim")))
{
result = WaifuClaimResult.NotEnoughFunds;
}
else
{
var oldClaimer = w.Claimer;
@@ -201,9 +198,7 @@ public class WaifuService : INService, IReadyExecutor
else if (amount >= w.Price * settings.Waifu.Multipliers.NormalClaim) // if no affinity
{
if (!await _cs.RemoveAsync(user.Id, amount, new("waifu", "claim")))
{
result = WaifuClaimResult.NotEnoughFunds;
}
else
{
var oldClaimer = w.Claimer;
@@ -221,9 +216,7 @@ public class WaifuService : INService, IReadyExecutor
}
}
else
{
result = WaifuClaimResult.InsufficientAmount;
}
await uow.SaveChangesAsync();
@@ -311,13 +304,9 @@ public class WaifuService : INService, IReadyExecutor
{
w = uow.WaifuInfo.ByWaifuUserId(targetId);
if (w?.Claimer is null || w.Claimer.UserId != user.Id)
{
result = DivorceResult.NotYourWife;
}
else if (!_cache.TryAddDivorceCooldown(user.Id, out remaining))
{
result = DivorceResult.Cooldown;
}
else
{
amount = w.Price / 2;
@@ -361,6 +350,7 @@ public class WaifuService : INService, IReadyExecutor
await using var uow = _db.GetDbContext();
var w = uow.WaifuInfo.ByWaifuUserId(giftedWaifu.Id, set => set.Include(x => x.Items).Include(x => x.Claimer));
if (w is null)
{
uow.WaifuInfo.Add(w = new()
{
Affinity = null,
@@ -368,6 +358,7 @@ public class WaifuService : INService, IReadyExecutor
Price = 1,
Waifu = uow.GetOrCreateUser(giftedWaifu)
});
}
if (!itemObj.Negative)
{
@@ -399,6 +390,7 @@ public class WaifuService : INService, IReadyExecutor
using var uow = _db.GetDbContext();
var wi = uow.GetWaifuInfo(targetId);
if (wi is null)
{
wi = new()
{
AffinityCount = 0,
@@ -412,6 +404,7 @@ public class WaifuService : INService, IReadyExecutor
Items = new(),
Price = 1
};
}
return wi;
}
@@ -498,7 +491,7 @@ public class WaifuService : INService, IReadyExecutor
// only decay waifu values from shard 0
if (_client.ShardId != 0)
return;
var redisKey = $"{_creds.RedisKey()}_last_waifu_decay";
while (true)
{
@@ -509,9 +502,7 @@ public class WaifuService : INService, IReadyExecutor
var decayInterval = _gss.Data.Waifu.Decay.HourInterval;
if (multi is < 0f or > 1f || decayInterval < 0)
{
continue;
}
var val = await _cache.Redis.GetDatabase().StringGetAsync(redisKey);
if (val != default)
@@ -520,9 +511,7 @@ public class WaifuService : INService, IReadyExecutor
var toWait = decayInterval.Hours() - (DateTime.UtcNow - lastDecay);
if (toWait > 0.Hours())
{
continue;
}
}
await _cache.Redis.GetDatabase().StringSetAsync(redisKey, DateTime.UtcNow.ToBinary());

View File

@@ -18,11 +18,13 @@ public class Betroll
var pair = _thresholdPairs.FirstOrDefault(x => x.WhenAbove < roll);
if (pair is null)
{
return new()
{
Multiplier = 0,
Roll = roll
};
}
return new()
{