Compare commits

..

37 Commits
4.3.0 ... 4.3.4

Author SHA1 Message Date
Kwoth
7d5c4666b8 Fixed VoiceXP bug, closes #374. Upped version to 4.3.4, Updated changelog 2022-08-07 13:07:51 +02:00
Kwoth
8d3f2f186a Merge branch 'v4' of https://gitlab.com/kwoth/nadekobot into v4 2022-08-06 17:57:32 +02:00
Kwoth
9572b9dc43 Updated changelog.md 2022-08-06 17:56:53 +02:00
Kwoth
ca32086089 Updated changelog.md 2022-08-06 17:56:14 +02:00
Kwoth
57f839dbcd Added client id as a potential fix for VoiceXp 'bug'. The solution may be to use different redis instances for each bot, or to switch from botCache: from 'redis' to 'memory' in creds.yml 2022-08-06 17:47:24 +02:00
Kwoth
71d6eeb9dd Possibly fixed #375 trivia bug 2022-08-06 17:28:31 +02:00
Kwoth
8c51cf8537 Added .xpshopbuy and .xpshopuse convenience commands 2022-08-06 13:26:41 +02:00
Kwoth
b683026cf3 Owner should also be able to buy items from the xp shop 2022-08-01 21:14:28 +02:00
Kwoth
bca2bc5af1 Fixed awarded amount position on the xp card 2022-08-01 20:59:35 +02:00
Kwoth
b385a83bdd Updated position of the username and club in the .xp image 2022-08-01 17:46:41 +02:00
Kwoth
3bf0286c81 Feature limit should have IsPatronLimit enabled 2022-08-01 16:08:23 +02:00
Kwoth
98272f66e7 Made improvements to the XP card text visibility with other backgrounds 2022-08-01 12:01:01 +02:00
Kwoth
cf3788c6ea Added an optional preview url to the xp shop items 2022-08-01 10:53:59 +02:00
Kwoth
4b3fc53cb6 Updated changelog 2022-07-31 21:31:29 +02:00
Kwoth
4e17dca856 Merge branch 'v4' of https://gitlab.com/kwoth/nadekobot into v4 2022-07-31 21:26:46 +02:00
Kwoth
82d89148f3 Added betroll bettest, fixed a bug which caused betroll to have very low payout 2022-07-31 21:26:34 +02:00
Kwoth
cc4c09b4d7 Merge branch 'hokutochen-v4-patch-85503' into 'v4'
updated redis requirement for release

See merge request Kwoth/nadekobot!262
2022-07-30 10:37:29 +00:00
Kwoth
616f01f8b2 Make sure broken youtube-dl didn't cache invalid data, closes #373 2022-07-30 10:29:33 +02:00
Hokuto Chen
56f89a02bc updated redis requirement for release 2022-07-30 07:32:30 +00:00
Kwoth
48ce988d20 Fixed a mistake in CHANGELOG.md 2022-07-29 19:53:45 +02:00
Kwoth
119b1cdec2 Changelog fixed 2022-07-29 18:38:54 +02:00
Kwoth
43fa5a22f5 Updated changelog.md, Upped version to 4.3.2 2022-07-28 14:33:32 +02:00
Kwoth
3c715a29ca .bank withdraw <expression> will now correctly use bank amount for calculations. Fixed .br giving double win amounts 2022-07-28 12:41:38 +02:00
Kwoth
31e1cbb19f Fixed an unreported bug with postgresql reminder loop, ref #370 2022-07-28 09:21:19 +02:00
Kwoth
8e464e9f09 Fixed mysql and postgresql reactionrole migration, closes #370 2022-07-28 09:10:21 +02:00
Kwoth
a190a3d933 Fixed Reaction Roles not working properly with animated emojis, closes #369 2022-07-28 08:30:28 +02:00
Kwoth
bedba98130 Fixed medusa Reply*LocalizedAsync not working with placeholders 2022-07-28 07:39:46 +02:00
Kwoth
d69f8435f6 Fixed .slot alignment, closes #372 2022-07-28 05:47:40 +02:00
Kwoth
8440b34338 Forgot to update the version to 4.3.1 2022-07-27 11:21:08 +02:00
Kwoth
a2715740c1 Merge branch 'v4' of https://gitlab.com/kwoth/nadekobot into v4 2022-07-27 11:20:06 +02:00
Kwoth
36b7fd2352 Possible fix for .reroa working even for non-patrons 2022-07-27 11:18:35 +02:00
Kwoth
6563cb507a Merge branch 'feature/v4-creds.yml-location' into 'v4'
NEW: add NadekoBot__creds env to specify alternative creds.yml

See merge request Kwoth/nadekobot!257
2022-07-27 05:00:28 +00:00
Veovis
cc6128997e NEW: add NadekoBot__creds env to specify alternative creds.yml 2022-07-27 05:00:27 +00:00
Kwoth
e942da4470 Merge branch 'hokutochen-v4-patch-80656' into 'v4'
updated notepad ++ descrption

See merge request Kwoth/nadekobot!261
2022-07-27 04:59:33 +00:00
Hokuto Chen
ab2bcdf00d updated notepad ++ descrption 2022-07-27 04:59:33 +00:00
Kwoth
d7c1dad4f0 Check for updates should run once per hour, not every 15 seconds 2022-07-27 06:53:16 +02:00
Kwoth
8bd6b887b8 Fixed docker build 2022-07-27 06:37:04 +02:00
44 changed files with 678 additions and 327 deletions

View File

@@ -1,6 +1,11 @@
# Ignore all files
*
# Don't ignore nugetconfig
!./NuGet.Config
# Don't ignore src projects
!src/Nadeko.Econ/**
!src/Nadeko.Common/**
# Use Nadeko.Medusa project
!src/Nadeko.Medusa/**
# Use NadekoBot project

View File

@@ -2,6 +2,47 @@
Experimental changelog. Mostly based on [keepachangelog](https://keepachangelog.com/en/1.0.0/) except date format. a-c-f-r-o
## Unreleased
## [4.3.3] - 06.08.2022
### Added
- Added `betroll` option to `.bettest` command
- Added `.xpshopbuy` and `.xpshopuse` convenience commands
- Added an optional preview url to teh xp shop item config model which will be shown instead of the real Url
### Changed
- Updated position of Username and Club name on the .xp card
- Improved text visibility on the .xp card
### Fixed
- Possibly fixed .trivia not stopping bug
- Fixed very low payout rate on `.betroll`
- Fixed an issue with youtube song resolver which caused invalid data to be cached
- Added client id to the cache key as a potential fix for VoiceXp 'bug'. The solution may be to use different redis instances for each bot, or to switch from botCache: from 'redis' to 'memory' in creds.yml
- Bot owner should now be able to buy items from the xpshop when patron requirement is set
- Fixed youtube-dl caching invalid data. Please use yt-dlp instead
## [4.3.2] - 28.07.2022
### Fixed
- Fixed Reaction Roles not working properly with animated emojis
- Fixed `.slot` alignment
- Fixed `mysql` and `postgresql` reactionrole migration
- Fixed repeat loop with `postgresql` db provider
- Fixed `.bank withdraw <expression>` will now correctly use bank amount for calculation
- [dev] Fixed medusa Reply*LocalizedAsync not working with placeholders
## [4.3.1] - 27.07.2022
### Changed
- Check for updates will run once per hour as it was supposed to
## [4.3.0] - 27.07.2022
### Added
@@ -15,9 +56,10 @@ Experimental changelog. Mostly based on [keepachangelog](https://keepachangelog.
- They payouts are very good, but seven always loses
- Added `.lula` command. Plays the same as `.wof` but looks much nicer, and is easily customizable from gambling.yml without any changes to the sourcecode needed.
- Added `.repeatskip` command which makes the next repeat trigger not post anything
- Added `.imageonly` which will make the bot only allow link posts in the channel. Exclusive with `.imageonly`
- Added `.linkonly` which will make the bot only allow link posts in the channel. Exclusive with `.imageonly`
- Added release notifications. Bot owners will now receive new release notifications in dms if they have `checkForUpdates` set to `true` in data/bot.yml
- You can also configure it via `.conf bot checkforupdates <true/false>`
- You can also configure it via `.conf bot checkfor
- updates <true/false>`
- Added `.xpshop` which lets bot owners add xp backgrounds and xp frames for sale by configuring `data/xp.yml`
- You can also toggle xpshop feature via `.conf xp shop.is_enabled`

View File

@@ -2,10 +2,13 @@ FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /source
COPY src/Nadeko.Medusa/*.csproj src/Nadeko.Medusa/
COPY src/Nadeko.Econ/*.csproj src/Nadeko.Econ/
COPY src/Nadeko.Common/*.csproj src/Nadeko.Common/
COPY src/NadekoBot/*.csproj src/NadekoBot/
COPY src/NadekoBot.Coordinator/*.csproj src/NadekoBot.Coordinator/
COPY src/NadekoBot.Generators/*.csproj src/NadekoBot.Generators/
COPY src/ayu/Ayu.Discord.Voice/*.csproj src/ayu/Ayu.Discord.Voice/
COPY NuGet.Config ./
RUN dotnet restore src/NadekoBot/
COPY . .
@@ -39,6 +42,7 @@ COPY docker-entrypoint.sh /usr/local/sbin
ENV shard_id=0
ENV total_shards=1
ENV NadekoBot__creds=/app/data/creds.yml
VOLUME [ "/app/data" ]
ENTRYPOINT [ "/usr/local/sbin/docker-entrypoint.sh" ]

View File

@@ -13,7 +13,15 @@ do
fi
done
# fix folder permissions
# creds.yml migration
if [ -f /app/creds.yml ]; then
echo "Default location for creds.yml is now /app/data/creds.yml."
echo "Please move your creds.yml and update your docker-compose.yml accordingly."
export Nadeko_creds=/app/creds.yml
fi
# ensure nadeko can write on /app/data
chown -R nadeko:nadeko "$data"
# drop to regular user and launch command

View File

@@ -69,7 +69,7 @@ Open Terminal (if you're on an installation with a window manager) and navigate
###### Prerequisites
1. Nadeko requires redis to function
1. (Optional) Installing Redis
- ubuntu installation command: `sudo apt-get install redis-server`
2. Playing music requires `ffmpeg`, `libopus`, `libsodium` and `youtube-dl` (which in turn requires python3)
- ubuntu installation command: `sudo apt-get install ffmpeg libopus0 opus-tools libopus-dev libsodium-dev -y`

View File

@@ -19,7 +19,7 @@
**Optional**
- [Notepad++] (makes it easier to edit your credentials)
- [Visual Studio Code](https://code.visualstudio.com/Download) (Highly suggested if you plan on editing files)
- [Visual C++ 2010 (x86)] and [Visual C++ 2017 (x64)] (both are required if you want Nadeko to play music - restart Windows after installation)
#### Setup

View File

@@ -26,20 +26,6 @@ public class NadekoRandom : Random
return Math.Abs(BitConverter.ToInt32(bytes, 0)) % maxValue;
}
public byte Next(byte minValue, byte maxValue)
{
if (minValue > maxValue)
throw new ArgumentOutOfRangeException(nameof(maxValue));
if (minValue == maxValue)
return minValue;
var bytes = new byte[1];
_rng.GetBytes(bytes);
return (byte)((bytes[0] % (maxValue - minValue)) + minValue);
}
public override int Next(int minValue, int maxValue)
{
if (minValue > maxValue)

View File

@@ -0,0 +1,19 @@
namespace Nadeko.Common;
public readonly struct ShmartBankAmount
{
public long Amount { get; }
public ShmartBankAmount(long amount)
{
Amount = amount;
}
public static implicit operator ShmartBankAmount(long num)
=> new(num);
public static implicit operator long(ShmartBankAmount num)
=> num.Amount;
public static implicit operator ShmartBankAmount(int num)
=> new(num);
}

View File

@@ -3,12 +3,10 @@
public readonly struct ShmartNumber : IEquatable<ShmartNumber>
{
public long Value { get; }
public string? Input { get; }
public ShmartNumber(long val, string? input = null)
public ShmartNumber(long val)
{
Value = val;
Input = input;
}
public static implicit operator ShmartNumber(long num)

View File

@@ -12,7 +12,7 @@ public sealed class BetflipGame
public BetflipResult Flip(byte guess, decimal amount)
{
var side = _rng.Next(0, 2);
var side = (byte)_rng.Next(0, 2);
if (side == guess)
{
return new BetflipResult()

View File

@@ -13,7 +13,7 @@ public sealed class BetrollGame
public BetrollResult Roll(decimal amount = 0)
{
var roll = _rng.Next(0, 101);
var roll = _rng.Next(1, 101);
for (var i = 0; i < _thresholdPairs.Length; i++)
{

View File

@@ -8,9 +8,9 @@ public class SlotGame
{
var rolls = new[]
{
_rng.Next(0, 6),
_rng.Next(0, 6),
_rng.Next(0, 6)
(byte)_rng.Next(0, 6),
(byte)_rng.Next(0, 6),
(byte)_rng.Next(0, 6)
};
ref var a = ref rolls[0];

View File

@@ -47,7 +47,7 @@ public static class MedusaExtensions
=> ctx.Message.AddReactionAsync(new Emoji("🤔"));
public static Task<IUserMessage> ErrorLocalizedAsync(this AnyContext ctx, string key, params object[]? args)
=> ctx.SendErrorAsync(ctx.GetText(key));
=> ctx.SendErrorAsync(ctx.GetText(key, args));
public static Task<IUserMessage> PendingLocalizedAsync(this AnyContext ctx, string key, params object[]? args)
=> ctx.SendPendingAsync(ctx.GetText(key, args));
@@ -56,11 +56,11 @@ public static class MedusaExtensions
=> ctx.SendConfirmAsync(ctx.GetText(key, args));
public static Task<IUserMessage> ReplyErrorLocalizedAsync(this AnyContext ctx, string key, params object[]? args)
=> ctx.SendErrorAsync($"{Format.Bold(ctx.User.ToString())} {ctx.GetText(key)}");
=> ctx.SendErrorAsync($"{Format.Bold(ctx.User.ToString())} {ctx.GetText(key, args)}");
public static Task<IUserMessage> ReplyPendingLocalizedAsync(this AnyContext ctx, string key, params object[]? args)
=> ctx.SendPendingAsync($"{Format.Bold(ctx.User.ToString())} {ctx.GetText(key)}");
=> ctx.SendPendingAsync($"{Format.Bold(ctx.User.ToString())} {ctx.GetText(key, args)}");
public static Task<IUserMessage> ReplyConfirmLocalizedAsync(this AnyContext ctx, string key, params object[]? args)
=> ctx.SendConfirmAsync($"{Format.Bold(ctx.User.ToString())} {ctx.GetText(key)}");
=> ctx.SendConfirmAsync($"{Format.Bold(ctx.User.ToString())} {ctx.GetText(key, args)}");
}

View File

@@ -35,13 +35,13 @@ public sealed class Bot
private readonly IBotCredsProvider _credsProvider;
// private readonly InteractionService _interactionService;
public Bot(int shardId, int? totalShards)
public Bot(int shardId, int? totalShards, string credPath = null)
{
if (shardId < 0)
throw new ArgumentOutOfRangeException(nameof(shardId));
ShardId = shardId;
_credsProvider = new BotCredsProvider(totalShards);
_credsProvider = new BotCredsProvider(totalShards, credPath);
_creds = _credsProvider.GetCreds();
_db = new(_credsProvider);

View File

@@ -0,0 +1,94 @@
using System.Text.RegularExpressions;
using NadekoBot.Db;
using NadekoBot.Modules.Gambling.Services;
using NCalc;
using OneOf;
namespace NadekoBot.Common.TypeReaders;
public class BaseShmartInputAmountReader
{
private static readonly Regex _percentRegex = new(@"^((?<num>100|\d{1,2})%)$", RegexOptions.Compiled);
protected readonly DbService _db;
protected readonly GamblingConfigService _gambling;
public BaseShmartInputAmountReader(DbService db, GamblingConfigService gambling)
{
_db = db;
_gambling = gambling;
}
public async ValueTask<OneOf<long, OneOf.Types.Error<string>>> ReadAsync(ICommandContext context, string input)
{
var i = input.Trim().ToUpperInvariant();
i = i.Replace("K", "000");
//can't add m because it will conflict with max atm
if (await TryHandlePercentage(context, i) is long num)
{
return num;
}
try
{
var expr = new Expression(i, EvaluateOptions.IgnoreCase);
expr.EvaluateParameter += (str, ev) => EvaluateParam(str, ev, context).GetAwaiter().GetResult();
return (long)decimal.Parse(expr.Evaluate().ToString()!);
}
catch (Exception)
{
return new OneOf.Types.Error<string>($"Invalid input: {input}");
}
}
private async Task EvaluateParam(string name, ParameterArgs args, ICommandContext ctx)
{
switch (name.ToUpperInvariant())
{
case "PI":
args.Result = Math.PI;
break;
case "E":
args.Result = Math.E;
break;
case "ALL":
case "ALLIN":
args.Result = await Cur(ctx);
break;
case "HALF":
args.Result = await Cur(ctx) / 2;
break;
case "MAX":
args.Result = await Max(ctx);
break;
}
}
protected virtual async Task<long> Cur(ICommandContext ctx)
{
await using var uow = _db.GetDbContext();
return await uow.DiscordUser.GetUserCurrencyAsync(ctx.User.Id);
}
protected virtual async Task<long> Max(ICommandContext ctx)
{
var settings = _gambling.Data;
var max = settings.MaxBet;
return max == 0 ? await Cur(ctx) : max;
}
private async Task<long?> TryHandlePercentage(ICommandContext ctx, string input)
{
var m = _percentRegex.Match(input);
if (m.Captures.Count == 0)
return null;
if (!long.TryParse(m.Groups["num"].ToString(), out var percent))
return null;
return (long)(await Cur(ctx) * (percent / 100.0f));
}
}

View File

@@ -0,0 +1,32 @@
#nullable disable
using NadekoBot.Modules.Gambling.Bank;
using NadekoBot.Modules.Gambling.Services;
namespace NadekoBot.Common.TypeReaders;
public sealed class ShmartBankAmountTypeReader : NadekoTypeReader<ShmartBankAmount>
{
private readonly IBankService _bank;
private readonly ShmartBankInputAmountReader _tr;
public ShmartBankAmountTypeReader(IBankService bank, DbService db, GamblingConfigService gambling)
{
_bank = bank;
_tr = new ShmartBankInputAmountReader(bank, db, gambling);
}
public override async ValueTask<TypeReaderResult<ShmartBankAmount>> ReadAsync(ICommandContext ctx, string input)
{
if (string.IsNullOrWhiteSpace(input))
return TypeReaderResult.FromError<ShmartBankAmount>(CommandError.ParseFailed, "Input is empty.");
var result = await _tr.ReadAsync(ctx, input);
if (result.TryPickT0(out var val, out var err))
{
return TypeReaderResult.FromSuccess<ShmartBankAmount>(new(val));
}
return TypeReaderResult.FromError<ShmartBankAmount>(CommandError.Unsuccessful, err.Value);
}
}

View File

@@ -0,0 +1,21 @@
using NadekoBot.Modules.Gambling.Bank;
using NadekoBot.Modules.Gambling.Services;
namespace NadekoBot.Common.TypeReaders;
public sealed class ShmartBankInputAmountReader : BaseShmartInputAmountReader
{
private readonly IBankService _bank;
public ShmartBankInputAmountReader(IBankService bank, DbService db, GamblingConfigService gambling)
: base(db, gambling)
{
_bank = bank;
}
protected override Task<long> Cur(ICommandContext ctx)
=> _bank.GetBalanceAsync(ctx.User.Id);
protected override Task<long> Max(ICommandContext ctx)
=> Cur(ctx);
}

View File

@@ -0,0 +1,29 @@
#nullable disable
using NadekoBot.Modules.Gambling.Services;
namespace NadekoBot.Common.TypeReaders;
public sealed class ShmartNumberTypeReader : NadekoTypeReader<ShmartNumber>
{
private readonly BaseShmartInputAmountReader _tr;
public ShmartNumberTypeReader(DbService db, GamblingConfigService gambling)
{
_tr = new BaseShmartInputAmountReader(db, gambling);
}
public override async ValueTask<TypeReaderResult<ShmartNumber>> ReadAsync(ICommandContext ctx, string input)
{
if (string.IsNullOrWhiteSpace(input))
return TypeReaderResult.FromError<ShmartNumber>(CommandError.ParseFailed, "Input is empty.");
var result = await _tr.ReadAsync(ctx, input);
if (result.TryPickT0(out var val, out var err))
{
return TypeReaderResult.FromSuccess<ShmartNumber>(new(val));
}
return TypeReaderResult.FromError<ShmartNumber>(CommandError.Unsuccessful, err.Value);
}
}

View File

@@ -1,100 +0,0 @@
#nullable disable
using NadekoBot.Db;
using NadekoBot.Modules.Gambling.Services;
using NCalc;
using System.Text.RegularExpressions;
using Nadeko.Common;
namespace NadekoBot.Common.TypeReaders;
public sealed class ShmartNumberTypeReader : NadekoTypeReader<ShmartNumber>
{
private static readonly Regex _percentRegex = new(@"^((?<num>100|\d{1,2})%)$", RegexOptions.Compiled);
private readonly DbService _db;
private readonly GamblingConfigService _gambling;
public ShmartNumberTypeReader(DbService db, GamblingConfigService gambling)
{
_db = db;
_gambling = gambling;
}
public override ValueTask<TypeReaderResult<ShmartNumber>> ReadAsync(ICommandContext context, string input)
{
if (string.IsNullOrWhiteSpace(input))
return new(TypeReaderResult.FromError<ShmartNumber>(CommandError.ParseFailed, "Input is empty."));
var i = input.Trim().ToUpperInvariant();
i = i.Replace("K", "000");
//can't add m because it will conflict with max atm
if (TryHandlePercentage(context, i, out var num))
return new(TypeReaderResult.FromSuccess(new ShmartNumber(num, i)));
try
{
var expr = new Expression(i, EvaluateOptions.IgnoreCase);
expr.EvaluateParameter += (str, ev) => EvaluateParam(str, ev, context);
var lon = (long)decimal.Parse(expr.Evaluate().ToString());
return new(TypeReaderResult.FromSuccess(new ShmartNumber(lon, input)));
}
catch (Exception)
{
return ValueTask.FromResult(
TypeReaderResult.FromError<ShmartNumber>(CommandError.ParseFailed, $"Invalid input: {input}"));
}
}
private void EvaluateParam(string name, ParameterArgs args, ICommandContext ctx)
{
switch (name.ToUpperInvariant())
{
case "PI":
args.Result = Math.PI;
break;
case "E":
args.Result = Math.E;
break;
case "ALL":
case "ALLIN":
args.Result = Cur(ctx);
break;
case "HALF":
args.Result = Cur(ctx) / 2;
break;
case "MAX":
args.Result = Max(ctx);
break;
}
}
private long Cur(ICommandContext ctx)
{
using var uow = _db.GetDbContext();
return uow.DiscordUser.GetUserCurrency(ctx.User.Id);
}
private long Max(ICommandContext ctx)
{
var settings = _gambling.Data;
var max = settings.MaxBet;
return max == 0 ? Cur(ctx) : max;
}
private bool TryHandlePercentage(ICommandContext ctx, string input, out long num)
{
num = 0;
var m = _percentRegex.Match(input);
if (m.Captures.Count != 0)
{
if (!long.TryParse(m.Groups["num"].ToString(), out var percent))
return false;
num = (long)(Cur(ctx) * (percent / 100.0f));
return true;
}
return false;
}
}

View File

@@ -108,8 +108,8 @@ public static class DiscordUserExtensions
.Take(count)
.ToList();
public static long GetUserCurrency(this DbSet<DiscordUser> users, ulong userId)
=> users.AsNoTracking().FirstOrDefault(x => x.UserId == userId)?.CurrencyAmount ?? 0;
public static async Task<long> GetUserCurrencyAsync(this DbSet<DiscordUser> users, ulong userId)
=> (await users.FirstOrDefaultAsyncLinqToDB(x => x.UserId == userId))?.CurrencyAmount ?? 0;
public static void RemoveFromMany(this DbSet<DiscordUser> users, IEnumerable<ulong> ids)
{

View File

@@ -20,6 +20,8 @@ public sealed class PostgreSqlContext : NadekoContext
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
base.OnConfiguring(optionsBuilder);
optionsBuilder
.UseLowerCaseNamingConvention()

View File

@@ -1,10 +1,22 @@
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Migrations;
namespace NadekoBot.Migrations;
public static class MigrationQueries
{
public static void MigrateRero(MigrationBuilder migrationBuilder)
{
if (migrationBuilder.IsMySql())
{
migrationBuilder.Sql(
@"INSERT IGNORE into reactionroles(guildid, channelid, messageid, emote, roleid, `group`, levelreq, dateadded)
select guildid, channelid, messageid, emotename, roleid, exclusive, 0, reactionrolemessage.dateadded
from reactionrole
left join reactionrolemessage on reactionrolemessage.id = reactionrole.reactionrolemessageid
left join guildconfigs on reactionrolemessage.guildconfigid = guildconfigs.id;");
}
else if (migrationBuilder.IsSqlite())
{
migrationBuilder.Sql(
@"insert or ignore into reactionroles(guildid, channelid, messageid, emote, roleid, 'group', levelreq, dateadded)
@@ -13,4 +25,18 @@ from reactionrole
left join reactionrolemessage on reactionrolemessage.id = reactionrole.reactionrolemessageid
left join guildconfigs on reactionrolemessage.guildconfigid = guildconfigs.id;");
}
else if (migrationBuilder.IsNpgsql())
{
migrationBuilder.Sql(@"insert into reactionroles(guildid, channelid, messageid, emote, roleid, ""group"", levelreq, dateadded)
select guildid, channelid, messageid, emotename, roleid, exclusive::int, 0, reactionrolemessage.dateadded
from reactionrole
left join reactionrolemessage on reactionrolemessage.id = reactionrole.reactionrolemessageid
left join guildconfigs on reactionrolemessage.guildconfigid = guildconfigs.id
ON CONFLICT DO NOTHING;");
}
else
{
throw new NotSupportedException("This database provider doesn't have an implementation for MigrateRero");
}
}
}

View File

@@ -58,7 +58,7 @@ public sealed class ReactionRolesService : IReadyExecutor, INService, IReactionR
}
private async Task<(IGuildUser, IRole)> GetUserAndRoleAsync(
SocketReaction r,
ulong userId,
ReactionRoleV2 rero)
{
var guild = _client.GetGuild(rero.GuildId);
@@ -67,8 +67,8 @@ public sealed class ReactionRolesService : IReadyExecutor, INService, IReactionR
if (role is null)
return default;
var user = guild.GetUser(r.UserId) as IGuildUser
?? await _client.Rest.GetGuildUserAsync(guild.Id, r.UserId);
var user = guild.GetUser(userId) as IGuildUser
?? await _client.Rest.GetGuildUserAsync(guild.Id, userId);
if (user is null)
return default;
@@ -77,20 +77,23 @@ public sealed class ReactionRolesService : IReadyExecutor, INService, IReactionR
}
private Task ClientOnReactionRemoved(
Cacheable<IUserMessage, ulong> msg,
Cacheable<IUserMessage, ulong> cmsg,
Cacheable<IMessageChannel, ulong> ch,
SocketReaction r)
{
if (!_cache.TryGetValue(msg.Id, out var reros))
if (!_cache.TryGetValue(cmsg.Id, out var reros))
return Task.CompletedTask;
_ = Task.Run(async () =>
{
var rero = reros.FirstOrDefault(x => x.Emote == r.Emote.Name || x.Emote == r.Emote.ToString());
var emote = await GetFixedEmoteAsync(cmsg, r.Emote);
var rero = reros.FirstOrDefault(x => x.Emote == emote.Name
|| x.Emote == emote.ToString());
if (rero is null)
return;
var (user, role) = await GetUserAndRoleAsync(r, rero);
var (user, role) = await GetUserAndRoleAsync(r.UserId, rero);
if (user.IsBot)
return;
@@ -112,6 +115,24 @@ public sealed class ReactionRolesService : IReadyExecutor, INService, IReactionR
return Task.CompletedTask;
}
// had to add this because for some reason, reactionremoved event's reaction doesn't have IsAnimated set,
// causing the .ToString() to be wrong on animated custom emotes
private async Task<IEmote> GetFixedEmoteAsync(
Cacheable<IUserMessage, ulong> cmsg,
IEmote inputEmote)
{
// this should only run for emote
if (inputEmote is not Emote e)
return inputEmote;
// try to get the message and pull
var msg = await cmsg.GetOrDownloadAsync();
var emote = msg.Reactions.Keys.FirstOrDefault(x => e.Equals(x));
return emote ?? inputEmote;
}
private Task ClientOnReactionAdded(
Cacheable<IUserMessage, ulong> msg,
Cacheable<IMessageChannel, ulong> ch,
@@ -126,7 +147,7 @@ public sealed class ReactionRolesService : IReadyExecutor, INService, IReactionR
if (rero is null)
return;
var (user, role) = await GetUserAndRoleAsync(r, rero);
var (user, role) = await GetUserAndRoleAsync(r.UserId, rero);
if (user.IsBot)
return;

View File

@@ -27,7 +27,7 @@ public sealed class CheckForUpdatesService : INService, IReadyExecutor
if (_client.ShardId != 0)
return;
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(15));
using var timer = new PeriodicTimer(TimeSpan.FromHours(1));
while (await timer.WaitForNextTickAsync())
{
var conf = _bcs.Data;

View File

@@ -1,5 +1,4 @@
using Nadeko.Common;
using NadekoBot.Modules.Gambling.Bank;
using NadekoBot.Modules.Gambling.Bank;
using NadekoBot.Modules.Gambling.Common;
using NadekoBot.Modules.Gambling.Services;
@@ -35,7 +34,7 @@ public partial class Gambling
}
[Cmd]
public async Task BankWithdraw(ShmartNumber amount)
public async Task BankWithdraw(ShmartBankAmount amount)
{
if (amount <= 0)
return;

View File

@@ -663,7 +663,6 @@ public partial class Gambling : GamblingModule<GamblingService>
if (win > 0)
{
str = GetText(strs.br_win(N(win), result.Threshold + (result.Roll == 100 ? " 👑" : "")));
await _cs.AddAsync(ctx.User, win, new("betroll", "win"));
}
else
{
@@ -876,11 +875,12 @@ public partial class Gambling : GamblingModule<GamblingService>
public enum GambleTestTarget
{
Slot,
Betroll,
Betflip,
BetflipT,
BetDraw,
BetDrawHL,
BetDrawRB,
Betflip,
BetflipT,
Lula,
Rps,
}
@@ -921,6 +921,7 @@ public partial class Gambling : GamblingModule<GamblingService>
GambleTestTarget.BetflipT => (await _gs.BetFlipAsync(ctx.User.Id, 0, 1)).AsT0.Multiplier,
GambleTestTarget.Lula => (await _gs.LulaAsync(ctx.User.Id, 0)).AsT0.Multiplier,
GambleTestTarget.Rps => (await _gs.RpsAsync(ctx.User.Id, 0, (byte)(i % 3))).AsT0.Multiplier,
GambleTestTarget.Betroll => (await _gs.BetRollAsync(ctx.User.Id, 0)).AsT0.Multiplier,
_ => throw new ArgumentOutOfRangeException(nameof(target))
};

View File

@@ -142,7 +142,7 @@ public class GamblingService : INService, IReadyExecutor
var onePercent = uow.DiscordUser.GetTopOnePercentCurrency(_client.CurrentUser.Id);
decimal planted = uow.PlantedCurrency.AsQueryable().Sum(x => x.Amount);
var waifus = uow.WaifuInfo.GetTotalValue();
var bot = uow.DiscordUser.GetUserCurrency(_client.CurrentUser.Id);
var bot = await uow.DiscordUser.GetUserCurrencyAsync(_client.CurrentUser.Id);
decimal bank = await uow.GetTable<BankUser>()
.SumAsyncLinqToDB(x => x.Balance);

View File

@@ -235,7 +235,7 @@ public partial class Gambling
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
WrappingLength = 140,
Origin = new(227, 92)
Origin = new(298, 100)
},
((long)result.Won).ToString(),
fontColor));
@@ -247,7 +247,7 @@ public partial class Gambling
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
WrappingLength = 135,
Origin = new(129, 472)
Origin = new(196, 480)
},
amount.ToString(),
fontColor));
@@ -256,8 +256,7 @@ public partial class Gambling
{
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
WrappingLength = 135,
Origin = new(325, 472)
Origin = new(393, 480)
},
ownedAmount.ToString(),
fontColor));

View File

@@ -57,11 +57,14 @@ public sealed class TriviaGame
// loop until game is stopped
// each iteration is one round
var firstRun = true;
try
{
while (!_isStopped)
{
if (errorCount >= 5)
{
Log.Warning("Trivia errored 5 times and will quit");
await OnEnded(this);
break;
}
@@ -77,7 +80,7 @@ public sealed class TriviaGame
var maybeQuestion = await _questionPool.GetQuestionAsync();
if(!(maybeQuestion is TriviaQuestion question))
if (!(maybeQuestion is TriviaQuestion question))
{
// if question is null (ran out of question, or other bugg ) - stop
break;
@@ -87,7 +90,8 @@ public sealed class TriviaGame
try
{
// clear out all of the past guesses
while (_inputs.Reader.TryRead(out _)) ;
while (_inputs.Reader.TryRead(out _))
;
await OnQuestion(this, question);
}
@@ -169,11 +173,17 @@ public sealed class TriviaGame
}
}
}
}
catch
{
}
finally
{
// make sure game is set as ended
_isStopped = true;
await OnEnded(this);
_ = OnEnded(this);
}
}
public IReadOnlyList<(ulong User, int points)> GetLeaderboard()

View File

@@ -274,7 +274,7 @@ public sealed class YtdlYoutubeResolver : IYoutubeResolver
Log.Information("Resolving youtube song by search term: {YoutubeQuery}", query);
var cachedData = await _trackCacher.GetCachedDataByQueryAsync(query, MusicPlatform.Youtube);
if (cachedData is null)
if (cachedData is null || string.IsNullOrWhiteSpace(cachedData.Title))
{
var stringData = await _ytdlSearchOperation.GetDataAsync(query);
var trackData = ResolveYtdlData(stringData);

View File

@@ -715,8 +715,8 @@ public sealed class PatronageService
return new()
{
Name = key.PrettyName,
Quota = defaultValue,
IsPatronLimit = false,
Quota = 0,
IsPatronLimit = true,
};
return new()

View File

@@ -334,14 +334,15 @@ public partial class Xp : NadekoModule<XpService>
public enum XpShopInputType
{
F = 0,
Frs = 0,
Fs = 0,
Frames = 0,
Backgrounds = 1,
B = 1,
Bg = 1,
Bgs = 1,
Backgrounds = 1
Frames = 0,
F = 0,
Fr = 0,
Frs = 0,
Fs = 0,
}
[Cmd]
@@ -353,8 +354,11 @@ public partial class Xp : NadekoModule<XpService>
return;
}
await SendConfirmAsync(GetText(strs.available_commands), $@"`{prefix}xpshop bgs`
`{prefix}xpshop frames`");
await SendConfirmAsync(GetText(strs.available_commands),
$@"`{prefix}xpshop bgs`
`{prefix}xpshop frames`
*{GetText(strs.xpshop_website)}*");
}
[Cmd]
@@ -394,13 +398,18 @@ public partial class Xp : NadekoModule<XpService>
.WithOkColor()
.WithTitle(item.Name)
.AddField(GetText(strs.price), Gambling.Gambling.N(item.Price, culture), true)
// .AddField(GetText(strs.buy), $"{prefix}xpbuy {key}", true)
.WithImageUrl(item.Url.ToString());
.WithImageUrl(string.IsNullOrWhiteSpace(item.Preview)
? item.Url
: item.Preview);
if (!string.IsNullOrWhiteSpace(item.Desc))
eb.WithDescription(item.Desc);
eb.AddField(GetText(strs.desc), item.Desc);
var tier = _service.GetXpShopTierRequirement();
if (key == "default")
eb.WithDescription(GetText(strs.xpshop_website));
var tier = _service.GetXpShopTierRequirement(type);
if (tier != PatronTier.None)
{
eb.WithFooter(GetText(strs.xp_shop_buy_required_tier(tier.ToString())));
@@ -455,6 +464,42 @@ public partial class Xp : NadekoModule<XpService>
addPaginatedFooter: false);
}
[Cmd]
public async Task XpShopBuy(XpShopInputType type, string key)
{
var result = await _service.BuyShopItemAsync(ctx.User.Id, (XpShopItemType)type, key);
if (result != BuyResult.Success)
{
var _ = result switch
{
BuyResult.InsufficientFunds => await ReplyErrorLocalizedAsync(strs.not_enough(_gss.Data.Currency.Sign)),
BuyResult.AlreadyOwned => await ReplyErrorLocalizedAsync(strs.xpshop_already_owned),
BuyResult.UnknownItem => await ReplyErrorLocalizedAsync(strs.xpshop_item_not_found),
BuyResult.InsufficientPatronTier => await ReplyErrorLocalizedAsync(strs.patron_insuff_tier),
_ => throw new ArgumentOutOfRangeException()
};
return;
}
await ReplyConfirmLocalizedAsync(strs.xpshop_buy_success(type.ToString().ToLowerInvariant(),
key.ToLowerInvariant()));
}
[Cmd]
public async Task XpShopUse(XpShopInputType type, string key)
{
var result = await _service.UseShopItemAsync(ctx.User.Id, (XpShopItemType)type, key);
if (!result)
{
await ReplyConfirmLocalizedAsync(strs.xp_shop_item_cant_use);
return;
}
await ctx.OkAsync();
}
private async Task OnShopUse(SocketMessageComponent smc, (string? key, XpShopItemType type)? maybeState)
{
if (maybeState is not { } state)

View File

@@ -10,7 +10,7 @@ namespace NadekoBot.Modules.Xp;
public sealed partial class XpConfig : ICloneable<XpConfig>
{
[Comment(@"DO NOT CHANGE")]
public int Version { get; set; } = 3;
public int Version { get; set; } = 5;
[Comment(@"How much XP will the users receive per message")]
public int XpPerMessage { get; set; } = 3;
@@ -37,9 +37,13 @@ True -> Users can access the xp shop using .xpshop command
False -> Users can't access the xp shop")]
public bool IsEnabled { get; set; } = false;
[Comment(@"Which patron tier do users need in order to use the .xpshop command
[Comment(@"Which patron tier do users need in order to use the .xpshop bgs command
Leave at 'None' if patron system is disabled or you don't want any restrictions")]
public PatronTier TierRequirement { get; set; } = PatronTier.None;
public PatronTier BgsTierRequirement { get; set; } = PatronTier.None;
[Comment(@"Which patron tier do users need in order to use the .xpshop frames command
Leave at 'None' if patron system is disabled or you don't want any restrictions")]
public PatronTier FramesTierRequirement { get; set; } = PatronTier.None;
[Comment(@"Frames available for sale. Keys are unique IDs.
Do not change keys as they are not publicly visible. Only change properties (name, price, id)
@@ -71,6 +75,9 @@ To remove an item from the shop, but keep previous purchases, set the price to -
[Comment(@"Direct url to the .png image which will be applied to the user's XP card")]
public string Url { get; set; }
[Comment(@"Optional preview url which will show instead of the real URL in the shop ")]
public string Preview { get; set; }
[Comment(@"Optional description of the item")]
public string Desc { get; set; }
}

View File

@@ -52,11 +52,11 @@ public sealed class XpConfigService : ConfigServiceBase<XpConfig>
});
}
if (data.Version < 3)
if (data.Version < 5)
{
ModifyConfig(c =>
{
c.Version = 3;
c.Version = 5;
});
}
}

View File

@@ -593,12 +593,12 @@ public class XpService : INService, IReadyExecutor, IExecNoCommand
{
if (ShouldTrackVoiceChannel(channel))
{
foreach (var user in channel.Users)
foreach (var user in channel.ConnectedUsers)
await ScanUserForVoiceXp(user, channel);
}
else
{
foreach (var user in channel.Users)
foreach (var user in channel.ConnectedUsers)
await UserLeftVoiceChannel(user, channel);
}
}
@@ -617,13 +617,13 @@ public class XpService : INService, IReadyExecutor, IExecNoCommand
}
private bool ShouldTrackVoiceChannel(SocketVoiceChannel channel)
=> channel.Users.Where(UserParticipatingInVoiceChannel).Take(2).Count() >= 2;
=> channel.ConnectedUsers.Where(UserParticipatingInVoiceChannel).Take(2).Count() >= 2;
private bool UserParticipatingInVoiceChannel(SocketGuildUser user)
=> !user.IsDeafened && !user.IsMuted && !user.IsSelfDeafened && !user.IsSelfMuted;
private TypedKey<long> GetVoiceXpKey(ulong userId)
=> new($"xp:vc_join:{userId}");
=> new($"xp:{_client.CurrentUser.Id}:vc_join:{userId}");
private async Task UserJoinedVoiceChannel(SocketGuildUser user)
{
@@ -635,6 +635,18 @@ public class XpService : INService, IReadyExecutor, IExecNoCommand
overwrite: false);
}
// private void UserJoinedVoiceChannel(SocketGuildUser user)
// {
// var key = $"{_creds.RedisKey()}_user_xp_vc_join_{user.Id}";
// var value = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
//
// _cache.Redis.GetDatabase()
// .StringSet(key,
// value,
// TimeSpan.FromMinutes(_xpConfig.Data.VoiceMaxMinutes),
// when: When.NotExists);
// }
private async Task UserLeftVoiceChannel(SocketGuildUser user, SocketVoiceChannel channel)
{
var key = GetVoiceXpKey(user.Id);
@@ -654,6 +666,7 @@ public class XpService : INService, IReadyExecutor, IExecNoCommand
if (actualXp > 0)
{
Log.Information("Adding {Amount} voice xp to {User}", actualXp, user.ToString());
await _xpGainQueue.Writer.WriteAsync(new()
{
Guild = channel.Guild,
@@ -664,6 +677,38 @@ public class XpService : INService, IReadyExecutor, IExecNoCommand
}
}
/*
* private void UserLeftVoiceChannel(SocketGuildUser user, SocketVoiceChannel channel)
{
var key = $"{_creds.RedisKey()}_user_xp_vc_join_{user.Id}";
var value = _cache.Redis.GetDatabase().StringGet(key);
_cache.Redis.GetDatabase().KeyDelete(key);
// Allow for if this function gets called multiple times when a user leaves a channel.
if (value.IsNull)
return;
if (!value.TryParse(out long startUnixTime))
return;
var dateStart = DateTimeOffset.FromUnixTimeSeconds(startUnixTime);
var dateEnd = DateTimeOffset.UtcNow;
var minutes = (dateEnd - dateStart).TotalMinutes;
var xp = _xpConfig.Data.VoiceXpPerMinute * minutes;
var actualXp = (int)Math.Floor(xp);
if (actualXp > 0)
{
_addMessageXp.Enqueue(new()
{
Guild = channel.Guild,
User = user,
XpAmount = actualXp
});
}
}
*/
private bool ShouldTrackXp(SocketGuildUser user, ulong channelId)
{
if (_excludedChannels.TryGetValue(user.Guild.Id, out var chans) && chans.Contains(channelId))
@@ -767,8 +812,8 @@ public class XpService : INService, IReadyExecutor, IExecNoCommand
return Enumerable.Empty<ulong>();
}
private static TypedKey<bool> GetUserRewKey(ulong userId)
=> new($"xp:user_gain:{userId}");
private TypedKey<bool> GetUserRewKey(ulong userId)
=> new($"xp:{_client.CurrentUser.Id}:user_gain:{userId}");
private async Task<bool> SetUserRewardedAsync(ulong userId)
=> await _c.AddAsync(GetUserRewKey(userId),
@@ -887,6 +932,8 @@ public class XpService : INService, IReadyExecutor, IExecNoCommand
throw new ArgumentNullException(nameof(bgBytes));
}
var outlinePen = new Pen(Color.Black, 1f);
using var img = Image.Load<Rgba32>(bgBytes, out var imageFormat);
if (template.User.Name.Show)
{
@@ -909,7 +956,8 @@ public class XpService : INService, IReadyExecutor, IExecNoCommand
Origin = new(template.User.Name.Pos.X, template.User.Name.Pos.Y + 8)
},
"@" + username,
template.User.Name.Color);
Brushes.Solid(template.User.Name.Color),
outlinePen);
});
}
@@ -929,7 +977,8 @@ public class XpService : INService, IReadyExecutor, IExecNoCommand
Origin = new(template.Club.Name.Pos.X + 50, template.Club.Name.Pos.Y - 8)
},
clubName,
template.Club.Name.Color));
Brushes.Solid(template.Club.Name.Color),
outlinePen));
}
Font GetTruncatedFont(
@@ -987,7 +1036,6 @@ public class XpService : INService, IReadyExecutor, IExecNoCommand
});
}
var pen = new Pen(Color.Black, 1.25f);
var global = stats.Global;
var guild = stats.Guild;
@@ -1012,7 +1060,7 @@ public class XpService : INService, IReadyExecutor, IExecNoCommand
},
$"{global.LevelXp}/{global.RequiredXp}",
Brushes.Solid(template.User.Xp.Global.Color),
pen));
outlinePen));
}
if (template.User.Xp.Guild.Show)
@@ -1026,7 +1074,7 @@ public class XpService : INService, IReadyExecutor, IExecNoCommand
},
$"{guild.LevelXp}/{guild.RequiredXp}",
Brushes.Solid(template.User.Xp.Guild.Color),
pen));
outlinePen));
}
if (stats.FullGuildStats.AwardedXp != 0 && template.User.Xp.Awarded.Show)
@@ -1038,10 +1086,11 @@ public class XpService : INService, IReadyExecutor, IExecNoCommand
img.Mutate(x => x.DrawText($"({sign}{stats.FullGuildStats.AwardedXp})",
_fonts.NotoSans.CreateFont(template.User.Xp.Awarded.FontSize, FontStyle.Bold),
Brushes.Solid(template.User.Xp.Awarded.Color),
pen,
outlinePen,
new(awX, awY)));
}
var rankPen = new Pen(Color.White, 1);
//ranking
if (template.User.GlobalRank.Show)
{
@@ -1054,10 +1103,15 @@ public class XpService : INService, IReadyExecutor, IExecNoCommand
globalRankStr,
68);
img.Mutate(x => x.DrawText(globalRankStr,
globalRankFont,
template.User.GlobalRank.Color,
new(template.User.GlobalRank.Pos.X, template.User.GlobalRank.Pos.Y)));
img.Mutate(x => x.DrawText(
new TextOptions(globalRankFont)
{
Origin = new(template.User.GlobalRank.Pos.X, template.User.GlobalRank.Pos.Y)
},
globalRankStr,
Brushes.Solid(template.User.GlobalRank.Color),
rankPen
));
}
if (template.User.GuildRank.Show)
@@ -1071,10 +1125,15 @@ public class XpService : INService, IReadyExecutor, IExecNoCommand
guildRankStr,
43);
img.Mutate(x => x.DrawText(guildRankStr,
guildRankFont,
template.User.GuildRank.Color,
new(template.User.GuildRank.Pos.X, template.User.GuildRank.Pos.Y)));
img.Mutate(x => x.DrawText(
new TextOptions(guildRankFont)
{
Origin = new(template.User.GuildRank.Pos.X, template.User.GuildRank.Pos.Y)
},
guildRankStr,
Brushes.Solid(template.User.GuildRank.Color),
rankPen
));
}
//avatar
@@ -1337,11 +1396,15 @@ public class XpService : INService, IReadyExecutor, IExecNoCommand
if (!conf.Shop.IsEnabled)
return BuyResult.UnknownItem;
if (conf.Shop.TierRequirement != PatronTier.None)
var req = type == XpShopItemType.Background
? conf.Shop.BgsTierRequirement
: conf.Shop.FramesTierRequirement;
if (req != PatronTier.None && !_creds.IsOwner(userId))
{
var patron = await _ps.GetPatronAsync(userId);
if ((int)patron.Tier < (int)conf.Shop.TierRequirement)
if ((int)patron.Tier < (int)req)
return BuyResult.InsufficientPatronTier;
}
@@ -1468,8 +1531,12 @@ public class XpService : INService, IReadyExecutor, IExecNoCommand
return false;
}
public PatronTier GetXpShopTierRequirement()
=> _xpConfig.Data.Shop.TierRequirement;
public PatronTier GetXpShopTierRequirement(Xp.XpShopInputType type)
=> type switch
{
Xp.XpShopInputType.F => _xpConfig.Data.Shop.FramesTierRequirement,
_ => _xpConfig.Data.Shop.BgsTierRequirement,
};
public bool IsShopEnabled()
=> _xpConfig.Data.Shop.IsEnabled;

View File

@@ -27,4 +27,4 @@ if (args.Length > 0 && args[0] != "run")
LogSetup.SetupLogger(shardId);
Log.Information("Pid: {ProcessId}", pid);
await new Bot(shardId, totalShards).RunAndBlockAsync();
await new Bot(shardId, totalShards, Environment.GetEnvironmentVariable("NadekoBot__creds")).RunAndBlockAsync();

View File

@@ -18,11 +18,9 @@ public sealed class BotCredsProvider : IBotCredsProvider
private const string CREDS_FILE_NAME = "creds.yml";
private const string CREDS_EXAMPLE_FILE_NAME = "creds_example.yml";
private string CredsPath
=> Path.Combine(Directory.GetCurrentDirectory(), CREDS_FILE_NAME);
private string CredsPath { get; }
private string CredsExamplePath
=> Path.Combine(Directory.GetCurrentDirectory(), CREDS_EXAMPLE_FILE_NAME);
private string CredsExamplePath { get; }
private readonly int? _totalShards;
@@ -34,9 +32,21 @@ public sealed class BotCredsProvider : IBotCredsProvider
private readonly object _reloadLock = new();
private readonly IDisposable _changeToken;
public BotCredsProvider(int? totalShards = null)
public BotCredsProvider(int? totalShards = null, string credPath = null)
{
_totalShards = totalShards;
if (!string.IsNullOrWhiteSpace(credPath))
{
CredsPath = credPath;
CredsExamplePath = Path.Combine(Path.GetDirectoryName(credPath), CREDS_EXAMPLE_FILE_NAME);
}
else
{
CredsPath = Path.Combine(Directory.GetCurrentDirectory(), CREDS_FILE_NAME);
CredsExamplePath = Path.Combine(Directory.GetCurrentDirectory(), CREDS_EXAMPLE_FILE_NAME);
}
try
{
if (!File.Exists(CredsExamplePath))

View File

@@ -7,7 +7,7 @@ namespace NadekoBot.Services;
public sealed class StatsService : IStatsService, IReadyExecutor, INService
{
public const string BOT_VERSION = "4.3.0";
public const string BOT_VERSION = "4.3.4";
public string Author
=> "Kwoth#2452";

View File

@@ -1064,6 +1064,10 @@ xpadd:
- xpadd
xpshop:
- xpshop
xpshopbuy:
- xpshopbuy
xpshopuse:
- xpshopuse
clubcreate:
- clubcreate
clubtransfer:

Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

After

Width:  |  Height:  |  Size: 13 KiB

View File

@@ -2128,6 +2128,16 @@ xpshop:
- "bgs"
- "frames"
- "bgs 3"
xpshopbuy:
desc: "Buy an item from the xp shop by specifying the type and the key of the item."
args:
- "bg open_sea"
- "fr gold"
xpshopuse:
desc: "Use a previously purchased item from the xp shop by specifying the type and the key of the item."
args:
- "bg synth"
- "fr default"
bible:
desc: "Shows bible verse. You need to supply book name and chapter:verse"
args:

View File

@@ -1003,7 +1003,7 @@
"feature_limit_reached_you": "You've reached the limit of {0} for the {1} feature. You may be able to increase this limit by upgrading your patron tier.",
"feature_limit_reached_owner": "Server owner has reached the limit of {0} for the {1} feature. Server owner may be able to upgrade this limit by upgrading patron tier.",
"feature_limit_reached_either": "The limit of {0} for the {1} feature has been reached. Either you or the server owner may able to upgrade this limit by upgrading the patron tier.",
"xp_shop_buy_required_tier": "Buying items from the shop requires Patron Tier {0} or higher.",
"xp_shop_buy_required_tier": "Buying items from this shop requires Patron Tier {0} or higher.",
"available_commands": "Available Commands",
"tier": "Tier",
"pledge": "Pledge",
@@ -1017,5 +1017,10 @@
"patron_not_enabled": "Patron system is disabled.",
"results_in": "{0} results in {1}s",
"patron_msg_sent": "Done sending messages to patrons at and above tier {1}. {1} successfully sent and {2} failed.",
"xpadd_users": "Added {0} server XP to {1} users."
"xpadd_users": "Added {0} server XP to {1} users.",
"xpshop_buy_success": "Successfully purchased `{0}/{1}`",
"patron_insuff_tier": "Your Patron Tier insufficient to perform this action.",
"xpshop_already_owned": "You already own this item.",
"xpshop_item_not_found": "An item with that key doesn't exist.",
"xpshop_website": "You can see the list of all Xp Shop items here: <https://xpshop.nadeko.bot>"
}

View File

@@ -1,5 +1,5 @@
# DO NOT CHANGE
version: 3
version: 5
# How much XP will the users receive per message
xpPerMessage: 3
# How often can the users receive XP in minutes
@@ -16,9 +16,12 @@ shop:
# True -> Users can access the xp shop using .xpshop command
# False -> Users can't access the xp shop
isEnabled: false
# Which patron tier do users need in order to use the .xpshop command
# Which patron tier do users need in order to use the .xpshop bgs command
# Leave at 'None' if patron system is disabled or you don't want any restrictions
tierRequirement: None
bgsTierRequirement: None
# Which patron tier do users need in order to use the .xpshop frames command
# Leave at 'None' if patron system is disabled or you don't want any restrictions
framesTierRequirement: None
# Frames available for sale. Keys are unique IDs.
# Do not change keys as they are not publicly visible. Only change properties (name, price, id)
# Removing a key which previously existed means that all previous purchases will also be unusable.
@@ -31,6 +34,8 @@ shop:
price: 0
# Direct url to the .png image which will be applied to the user's XP card
url: ''
# Optional preview url which will show instead of the real URL in the shop
preview:
# Optional description of the item
desc:
# Backgrounds available for sale. Keys are unique IDs.
@@ -45,5 +50,7 @@ shop:
price: 0
# Direct url to the .png image which will be applied to the user's XP card
url: ''
# Optional preview url which will show instead of the real URL in the shop
preview:
# Optional description of the item
desc:

View File

@@ -10,8 +10,8 @@
"Show": true,
"FontSize": 50,
"Pos": {
"X": 130,
"Y": 17
"X": 105,
"Y": 25
}
},
"Icon": {
@@ -65,7 +65,7 @@
"Bar": {
"Show": true,
"Global": {
"Color": "00000066",
"Color": "00000095",
"PointA": {
"X": 321,
"Y": 104
@@ -78,7 +78,7 @@
"Direction": 3
},
"Guild": {
"Color": "00000066",
"Color": "00000095",
"PointA": {
"X": 282,
"Y": 248
@@ -114,7 +114,7 @@
"Show": true,
"FontSize": 25,
"Pos": {
"X": 490,
"X": 450,
"Y": 345
}
}
@@ -138,7 +138,7 @@
"FontSize": 35,
"Pos": {
"X": 650,
"Y": 49
"Y": 55
}
}
}