Compare commits

...
10 Commits
43 changed files with 6176 additions and 359 deletions
+6
View File
@@ -16,6 +16,9 @@ obj/
appsettings.*.local.json
*.pfx
# 模拟器运行期产物(S9 用 simulation_runs 表替代)
rounds_archive.zip
# WorkBuddy 会话数据
.workbuddy/
@@ -25,3 +28,6 @@ appsettings.*.local.json
*.db-wal
*.db-shm
TestResults/
# Ubuntu 部署包产物(publish-linux.bat 生成)
/publish/
+82 -59
View File
@@ -17,57 +17,79 @@ namespace OshimaBot.Game.Services
{
public class FunGameSimulation
{
public static Dictionary<Character, CharacterStatistics> CharacterStatistics { get; } = [];
public static Dictionary<Character, CharacterStatistics> TeamCharacterStatistics { get; } = [];
public static IReadOnlyList<string> LastRecord { get; private set; } = [];
public static IReadOnlyList<string> LastFullRecord { get; private set; } = [];
public static GameMap Map { get; } = new FastAutoMap();
// ---- S8 前置:运行态按实例隔离,统计/日志收敛到仓储 ----
private static readonly AsyncLocal<SimulationRunContext?> Ambient = new();
private static readonly SimulationRunContext DefaultContext = new();
private static ISimulationStatisticsStore _statisticsStore = new InMemorySimulationStatisticsStore();
public static void InitializeStatistics()
/// <summary>当前执行流绑定的运行上下文;未在 BeginRun 作用域内时退回默认上下文。</summary>
public static SimulationRunContext Current => Ambient.Value ?? DefaultContext;
public static ISimulationStatisticsStore StatisticsStore => _statisticsStore;
/// <summary>注入自定义统计仓储(S9 可换数据库实现),须在首次模拟/统计读写前调用。</summary>
public static void UseStatisticsStore(ISimulationStatisticsStore store)
=> _statisticsStore = store ?? throw new ArgumentNullException(nameof(store));
/// <summary>把后续静态状态读写绑定到指定运行上下文;AsyncLocal 随 async 流与 Task.Run 传递。</summary>
public static IDisposable BeginRun(SimulationRunContext context)
{
CharacterStatistics.Clear();
TeamCharacterStatistics.Clear();
LastRecord = [];
LastFullRecord = [];
foreach (Character character in FunGameService.Characters)
{
CharacterStatistics.Add(character, new());
TeamCharacterStatistics.Add(character, new());
}
ArgumentNullException.ThrowIfNull(context);
SimulationRunContext? previous = Ambient.Value;
Ambient.Value = context;
return new RunScope(previous);
}
public static bool IsRuning { get; set; } = false;
public static bool IsWeb { get; set; } = false;
public static bool IsDebug { get; set; } = false;
public static bool PrintOut { get; set; } = false;
public static bool DeathMatchRoundDetail { get; set; } = false;
public static string Msg { get; set; } = "";
private sealed class RunScope(SimulationRunContext? previous) : IDisposable
{
public void Dispose() => Ambient.Value = previous;
}
// 跨运行共享:统计与最近日志由仓储持有,查询服务只读这里。
public static Dictionary<Character, CharacterStatistics> CharacterStatistics => _statisticsStore.CharacterStatistics;
public static Dictionary<Character, CharacterStatistics> TeamCharacterStatistics => _statisticsStore.TeamCharacterStatistics;
public static IReadOnlyList<string> LastRecord { get => _statisticsStore.LastRecord; private set => _statisticsStore.LastRecord = value; }
public static IReadOnlyList<string> LastFullRecord { get => _statisticsStore.LastFullRecord; private set => _statisticsStore.LastFullRecord = value; }
public static GameMap Map { get => Current.Map; set => Current.Map = value; }
public static void InitializeStatistics() => _statisticsStore.Reset(FunGameService.Characters);
// 单次运行态:全部委托到 SimulationRunContext,进程内不再有共享可变字段。
public static bool IsRuning { get => Current.IsRunning; set => Current.IsRunning = value; }
public static bool IsWeb { get => Current.IsWeb; set => Current.IsWeb = value; }
public static bool IsDebug { get => Current.IsDebug; set => Current.IsDebug = value; }
public static bool PrintOut { get => Current.PrintOut; set => Current.PrintOut = value; }
public static bool DeathMatchRoundDetail { get => Current.DeathMatchRoundDetail; set => Current.DeathMatchRoundDetail = value; }
public static string Msg { get => Current.Msg; set => Current.Msg = value; }
/// <summary>
/// 指定本局使用的随机种子;为 null 时每局自动随机<br/>
/// 设值后(或读取 <see cref="Seed"/> 得到的上一局实际值)同一份输入数据下整局模拟可复现
/// 指定本局种子;为 null 时每局自动随机。现在字段属于运行上下文,设置后不会泄漏到下一局。
/// </summary>
public static int? SeedOverride { get; set; } = null;
public static int? SeedOverride { get => Current.SeedOverride; set => Current.SeedOverride = value; }
/// <summary>
/// 固定武器 Id(0 = 不固定,按品质随机)。由 <see cref="SimulationOptions.FixedWeaponId"/> 传入。
/// <para/>用于平衡测试时消除「武器攻击力 20–170(8.5×)+ 副属性各异 + 武器类型倍率 1.41×」这组混淆变量。
/// </summary>
public static long FixedWeaponId { get; set; } = 0;
/// <summary>固定武器 Id(0 = 不固定)。同种子复现用,属于本局运行态。</summary>
public static long FixedWeaponId { get => Current.FixedWeaponId; set => Current.FixedWeaponId = value; }
/// <summary>
/// 本局实际使用的随机种子(开局确定并保留,便于复现)
/// </summary>
public static int Seed { get; private set; } = 0;
/// <summary>本局实际使用的随机种子(开局确定并保留,便于复现)。</summary>
public static int Seed { get => Current.Seed; private set => Current.Seed = value; }
/// <summary>
/// 模拟器自己的随机数生成器(由 <see cref="Seed"/> 决定)
/// <para>队列创建之前的角色抽选、技能分配、分队等走它;队列创建之后一律走 <see cref="GamingQueue.Random"/>。</para>
/// <para>两者同源,因此本文件内<b>禁止使用进程级的 <c>Random.Shared</c></b>,否则整局不可复现</para>
/// </summary>
public static Random Random { get; private set; } = new();
/// <summary>本局随机数生成器(由 Seed 决定);禁止改回进程级 Random.Shared。</summary>
public static Random Random { get => Current.Random; private set => Current.Random = value; }
public static async Task<List<string>> StartSimulationGame(SimulationOptions options)
/// <summary>兼容旧调用:使用一次性默认上下文。</summary>
public static Task<List<string>> StartSimulationGame(SimulationOptions options)
=> StartSimulationGame(options, new SimulationRunContext());
/// <summary>S8 起推荐入口:显式绑定本次运行上下文,静态运行态不再跨局共享。</summary>
public static async Task<List<string>> StartSimulationGame(SimulationOptions options, SimulationRunContext context)
{
ArgumentNullException.ThrowIfNull(context);
context.ArchiveRounds = options.ArchiveRounds;
using IDisposable scope = BeginRun(context);
return await StartSimulationGameCore(options).ConfigureAwait(false);
}
private static async Task<List<string>> StartSimulationGameCore(SimulationOptions options)
{
PrintOut = options.PrintOut;
IsWeb = options.IsWeb;
@@ -165,7 +187,7 @@ namespace OshimaBot.Game.Services
TeamGamingQueue? tgq = null;
if (isTeam)
{
tgq = new TeamGamingQueue(characters, WriteLine, seed: Seed)
tgq = new TeamGamingQueue(characters, Current.WriteLine, seed: Seed)
{
MaxRespawnTimes = -1,
MaxScoreToWin = 30
@@ -174,7 +196,7 @@ namespace OshimaBot.Game.Services
}
else
{
mgq = new MixGamingQueue(characters, WriteLine, seed: Seed)
mgq = new MixGamingQueue(characters, Current.WriteLine, seed: Seed)
{
MaxRespawnTimes = maxRespawnTimesMix
};
@@ -680,18 +702,23 @@ namespace OshimaBot.Game.Services
}
}
string zipFileName = "rounds_archive.zip";
try
// S9:默认不再无条件落盘 zip;结果由 simulation_runs 表承载,
// 只有显式开启 ArchiveRounds(复盘 / 平衡测试)才生成 rounds_archive.zip。
if (Current.ArchiveRounds)
{
WriteRoundsToZip(actionQueue.Rounds.ToDictionary(kv => kv.Round, kv => kv), zipFileName);
}
catch (Exception ex)
{
// 档案落盘失败(IO/权限/磁盘满等)不应连带丢弃整局模拟结果
string msg = $"回合记录写入失败({zipFileName}):{ex.Message}";
Console.WriteLine(ex);
result.Add(msg);
lastRecord.Add(msg);
string zipFileName = "rounds_archive.zip";
try
{
WriteRoundsToZip(actionQueue.Rounds.ToDictionary(kv => kv.Round, kv => kv), zipFileName);
}
catch (Exception ex)
{
// 档案落盘失败(IO/权限/磁盘满等)不应连带丢弃整局模拟结果
string msg = $"回合记录写入失败({zipFileName}):{ex.Message}";
Console.WriteLine(ex);
result.Add(msg);
lastRecord.Add(msg);
}
}
LastRecord = result;
@@ -842,11 +869,7 @@ namespace OshimaBot.Game.Services
return roundsData;
}
public static void WriteLine(string str)
{
Msg += str + "\r\n";
if (PrintOut) Console.WriteLine(str);
}
public static void WriteLine(string str) => Current.WriteLine(str);
public static void AddStoreItems(GamingQueue queue, List<Item> store)
{
@@ -32,6 +32,12 @@ namespace OshimaBot.Game.Services
/// <summary>调试模式(输出更多运行细节)</summary>
public bool IsDebug { get; set; }
/// <summary>
/// S9:是否把回合记录写入 rounds_archive.zip。默认 false —— 归档改由
/// simulation_runs 表承担,只有显式开启(复盘/平衡测试)才落盘。
/// </summary>
public bool ArchiveRounds { get; set; }
/// <summary>
/// 是否启用「角色绑定的回合奖励」(对应 <c>InitRoundRewards</c> 的 bindToCharacter)。<para/>
/// <b>默认 true</b>:不启用时【命运XX】系技能(抢夺 / 剥夺 / 馈赠)与【强运】会全部静默失效。
@@ -0,0 +1,34 @@
using FunGame.Core.Model.Framework;
using Milimoe.FunGameTesting.Others;
namespace OshimaBot.Game.Services;
/// <summary>
/// 单次模拟的运行态。S8 前置改造:原先挂在 FunGameSimulation 上的进程级 static 可变字段
/// 全部搬到这里,每次运行一个实例,避免多用户并发/串局时互相污染。
/// 内容目录(FunGameService.Characters/Skills/Items)是只读模板,仍保持进程级共享。
/// </summary>
public sealed class SimulationRunContext
{
public bool IsRunning { get; set; }
public bool IsWeb { get; set; }
public bool IsDebug { get; set; }
public bool PrintOut { get; set; }
public bool DeathMatchRoundDetail { get; set; }
public string Msg { get; set; } = "";
public int? SeedOverride { get; set; }
public long FixedWeaponId { get; set; }
public int Seed { get; set; }
public Random Random { get; set; } = new();
public GameMap Map { get; set; } = new FastAutoMap();
/// <summary>S9:本局是否额外写 rounds_archive.zip(默认关闭,结果统一入库)。</summary>
public bool ArchiveRounds { get; set; }
/// <summary>绑定到本实例的日志回调:不依赖 AsyncLocal,跨线程回调也不会串局。</summary>
public void WriteLine(string text)
{
Msg += text + "\r\n";
if (PrintOut) Console.WriteLine(text);
}
}
@@ -0,0 +1,60 @@
using FunGame.Core.Entity;
namespace OshimaBot.Game.Services;
/// <summary>
/// 跨运行共享的统计与最近日志。S8 前置把读写从 FunGameSimulation 的静态字典收敛到仓储接口;
/// S9 可替换为 EF Core(simulation_statistics / simulation_runs)实现而无需改动模拟器。
/// </summary>
public interface ISimulationStatisticsStore
{
Dictionary<Character, CharacterStatistics> CharacterStatistics { get; }
Dictionary<Character, CharacterStatistics> TeamCharacterStatistics { get; }
IReadOnlyList<string> LastRecord { get; set; }
IReadOnlyList<string> LastFullRecord { get; set; }
/// <summary>按当前内容目录重建统计行(进程启动或目录热重载时调用)。</summary>
void Reset(IEnumerable<Character> characters);
/// <summary>在读锁内执行读取,避免与正在写入的模拟互相干扰。</summary>
T Read<T>(Func<ISimulationStatisticsStore, T> reader);
/// <summary>
/// 一局模拟结束后把统计与最近日志持久化。内存实现为空操作;
/// S9 的 EF Core 实现写 simulation_statistics,重启后可恢复。
/// </summary>
Task PersistAsync(CancellationToken cancellationToken = default);
}
public sealed class InMemorySimulationStatisticsStore : ISimulationStatisticsStore
{
private readonly Lock _sync = new();
public Dictionary<Character, CharacterStatistics> CharacterStatistics { get; } = [];
public Dictionary<Character, CharacterStatistics> TeamCharacterStatistics { get; } = [];
public IReadOnlyList<string> LastRecord { get; set; } = [];
public IReadOnlyList<string> LastFullRecord { get; set; } = [];
public void Reset(IEnumerable<Character> characters)
{
lock (_sync)
{
CharacterStatistics.Clear();
TeamCharacterStatistics.Clear();
LastRecord = [];
LastFullRecord = [];
foreach (Character character in characters)
{
CharacterStatistics.Add(character, new());
TeamCharacterStatistics.Add(character, new());
}
}
}
public T Read<T>(Func<ISimulationStatisticsStore, T> reader)
{
lock (_sync) return reader(this);
}
public Task PersistAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
}
+290
View File
@@ -0,0 +1,290 @@
using System.Security.Claims;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using OshimaBot.Commands;
using OshimaBot.Messaging;
using OshimaBot.Models;
using OshimaBot.Security;
using Xunit;
namespace OshimaBot.Tests;
public sealed class CommandFrameworkTests
{
[Fact]
public void Registry_ResolvesExactAliasesAndLegacyPrefixes()
{
CommandRegistry registry = CreateRegistry(out _);
Assert.Equal("help", registry.Resolve("/帮助")!.Command.Key);
Assert.Equal("help", registry.Resolve("help")!.Command.Key);
Assert.Equal("char", registry.Resolve("查角色 1")!.Command.Key);
Assert.Equal("1", Assert.Single(registry.Resolve("查角色 1")!.Args));
Assert.Equal("1", Assert.Single(registry.Resolve("查角色1")!.Args)); // 旧版无空格前缀写法
Assert.Equal("team-stats", registry.Resolve("查团队数据 3")!.Command.Key); // 最长前缀优先
Assert.Equal("stats", registry.Resolve("查数据 3")!.Command.Key);
Assert.Equal("log", registry.Resolve("上次的日志")!.Command.Key);
Assert.Equal("log-full", registry.Resolve("/上次的完整日志")!.Command.Key);
Assert.Null(registry.Resolve("不存在的指令"));
Assert.Null(registry.Resolve(" "));
}
[Fact]
public void Registry_StripsPageTokensWithoutTouchingNumericArguments()
{
CommandRegistry registry = CreateRegistry(out _);
CommandMatch log = registry.Resolve("/上次的日志 p3")!;
Assert.Equal(3, log.Page);
Assert.Empty(log.Args);
Assert.Equal(2, registry.Resolve("/帮助 p2")!.Page);
CommandMatch stats = registry.Resolve("查数据 12")!;
Assert.Equal(1, stats.Page);
Assert.Equal("12", Assert.Single(stats.Args));
}
[Fact]
public void Catalog_AllCommandsHaveCompleteMetadata()
{
CommandRegistry registry = CreateRegistry(out _);
Assert.Equal(CommandCatalog.Keys.Count, registry.All.Count);
Assert.Equal(CommandCatalog.Keys.Count, CommandCatalog.Keys.Distinct().Count());
foreach (ICommand command in registry.All)
{
Assert.False(string.IsNullOrWhiteSpace(command.Name), command.Key);
Assert.False(string.IsNullOrWhiteSpace(command.Usage), command.Key);
Assert.False(string.IsNullOrWhiteSpace(command.Description), command.Key);
Assert.False(string.IsNullOrWhiteSpace(command.Group), command.Key);
}
Assert.Throws<ArgumentOutOfRangeException>(() => CommandCatalog.Create("unknown", CreateDeps(out _, out _)));
}
[Fact]
public async Task Help_IsGeneratedFromRegistryAndUsesFourSections()
{
(CommandRouter router, CommandRegistry registry, _, _) = CreateRouter();
BotReply? reply = await router.RouteAsync(Message("/帮助"), new OtherData());
Assert.NotNull(reply);
string content = reply!.Markdown!.Content!;
Assert.StartsWith("## ", content);
Assert.Contains("第 1/", content);
Assert.Contains("qqbot-cmd-input", content);
Assert.NotNull(reply.Keyboard);
Assert.Equal(5, reply.Keyboard!.Content!.Rows[0].Buttons.Count);
Assert.Equal(2, reply.Keyboard.Content.Rows.Count); // 常用指令行 + 分页行
// 帮助与注册表同源:翻完所有页应覆盖每一条 Usage。
int pages = (registry.All.Count + CommandReplies.HelpPageSize - 1) / CommandReplies.HelpPageSize;
string allHelp = string.Concat(Enumerable.Range(1, pages)
.Select(page => CommandReplies.Help(registry, page).Markdown!.Content));
foreach (ICommand command in registry.All)
{
// Usage 经 Markdown 转义(< > 等),名称本身是安全锚点。
Assert.Contains(command.Name, allHelp, StringComparison.Ordinal);
}
}
[Fact]
public async Task Router_UnknownCommandReturnsNull()
{
(CommandRouter router, _, _, _) = CreateRouter();
Assert.Null(await router.RouteAsync(Message("随便说点什么"), new OtherData()));
}
[Fact]
public async Task Router_ErrorRepliesHaveThreeSegments()
{
(CommandRouter router, _, _, _) = CreateRouter();
BotReply? reply = await router.RouteAsync(Message("/绑定", isGroup: true), new OtherData());
Assert.NotNull(reply);
string content = reply!.Markdown!.Content!;
Assert.Contains("没有发生", content);
Assert.Contains("下一步", content);
Assert.Contains("qqbot-cmd-input", content);
}
[Fact]
public async Task Router_UptimeUsesFourSegmentMarkdown()
{
(CommandRouter router, _, _, _) = CreateRouter();
BotReply? reply = await router.RouteAsync(Message("/查询服务器启动时间"), new OtherData());
Assert.Contains("服务器状态", reply!.Markdown!.Content!);
Assert.Contains("UTC", reply.Markdown!.Content!);
Assert.Contains("qqbot-cmd-input", reply.Markdown!.Content!);
}
[Fact]
public async Task Router_BindGuardsGroupChatAndAnonymousUsers()
{
(CommandRouter router, _, _, FakeBindCodes codes) = CreateRouter();
BotReply? group = await router.RouteAsync(Message("/绑定", isGroup: true), new OtherData());
Assert.Contains("群聊不能签发绑定码", group!.Markdown!.Content!);
Assert.Equal(0, codes.Calls);
BotReply? anonymous = await router.RouteAsync(Message("/获取接入码", userId: 0), new OtherData());
Assert.Contains("身份尚未就绪", anonymous!.Markdown!.Content!);
Assert.Equal(0, codes.Calls);
BotReply? ok = await router.RouteAsync(Message("/绑定"), new OtherData());
Assert.Contains("一次性绑定码", ok!.Markdown!.Content!);
Assert.Matches(@"\d{6}", ok.Markdown!.Content!);
Assert.Equal(1, codes.Calls);
}
[Fact]
public async Task Router_CancelClearsPendingSession()
{
(CommandRouter router, _, FakeSessions sessions, _) = CreateRouter();
BotReply? reply = await router.RouteAsync(Message("/重置状态"), new OtherData());
Assert.Contains("状态已重置", reply!.Markdown!.Content!);
Assert.Equal(1, sessions.ClearCalls);
}
[Fact]
public async Task Router_EnforcesRequiredRole()
{
DelegateCommand adminCommand = new("admin", "管理员指令", [], "/管理员指令", "测试",
CommandGroups.System, _ => Task.FromResult(BotReply.FromText("ok")), requiredRole: BotRole.Admin);
(CommandRouter router, _, _, _) = CreateRouter(new CommandRegistry([adminCommand]));
BotReply? denied = await router.RouteAsync(Message("/管理员指令"), new OtherData());
Assert.Contains("权限不足", denied!.Markdown!.Content!);
ThirdPartyMessage message = Message("/管理员指令");
message.Principal = new ClaimsPrincipal(new ClaimsIdentity(
[new Claim(ClaimTypes.Role, BotRole.Admin.ToString())], "test"));
BotReply? allowed = await router.RouteAsync(message, new OtherData());
Assert.Equal("ok", allowed!.Text);
}
[Fact]
public async Task Router_EnforcesCooldown()
{
DelegateCommand slowCommand = new("slow", "慢指令", [], "/慢指令", "测试",
CommandGroups.System, _ => Task.FromResult(BotReply.FromText("ok")), cooldownMilliseconds: 60_000);
(CommandRouter router, _, _, _) = CreateRouter(new CommandRegistry([slowCommand]));
Assert.Equal("ok", (await router.RouteAsync(Message("/慢指令"), new OtherData()))!.Text);
Assert.Contains("操作太快", (await router.RouteAsync(Message("/慢指令"), new OtherData()))!.Markdown!.Content!);
}
[Fact]
public void CommandReplies_PaginatesLongContent()
{
string body = new('x', 7000);
Assert.Equal(3, QQMarkdown.Split(body, QQMarkdown.DefaultMaxLength).Count);
BotReply first = CommandReplies.Paginated("📜 长日志", body, 1, "/上次的日志");
Assert.Contains("第 1/3 页", first.Markdown!.Content!);
Assert.Contains("p2", first.Markdown!.Content!); // CmdInput 会 urlencode,页码仍可见
Assert.NotNull(first.Keyboard);
BotReply last = CommandReplies.Paginated("📜 长日志", body, 99, "/上次的日志");
Assert.Contains("第 3/3 页", last.Markdown!.Content!);
}
[Fact]
public void CommandContext_ParsesOptionsReferencesAndFlags()
{
CommandRegistry registry = CreateRegistry(out CommandDependencies deps);
CommandContext context = new()
{
Message = Message("/测试 @3 x2 --seed=42 --yes"),
Raw = "/测试 @3 x2 --seed=42 --yes",
Verb = "测试",
Args = ["@3", "x2", "--seed=42", "--yes"],
Page = 1,
Registry = registry,
Dependencies = deps,
Data = new OtherData(),
CancellationToken = CancellationToken.None
};
Assert.Equal("3", context.Reference());
Assert.Equal("42", context.Option("seed"));
Assert.True(context.HasFlag("--yes"));
Assert.False(context.HasFlag("--no"));
Assert.Equal("@3 x2 --seed=42 --yes", context.ArgumentText);
}
private static CommandRegistry CreateRegistry(out CommandDependencies deps)
{
deps = CreateDeps(out _, out _);
return CommandCatalog.Build(deps);
}
private static CommandDependencies CreateDeps(out FakeSessions sessions, out FakeBindCodes codes)
{
sessions = new FakeSessions();
codes = new FakeBindCodes();
return new CommandDependencies(null!, null!, codes, sessions, null!, null!, NullLogger.Instance);
}
private static (CommandRouter Router, CommandRegistry Registry, FakeSessions Sessions, FakeBindCodes Codes)
CreateRouter(CommandRegistry? customRegistry = null)
{
CommandDependencies deps = CreateDeps(out FakeSessions sessions, out FakeBindCodes codes);
CommandRegistry registry = customRegistry ?? CommandCatalog.Build(deps);
CommandRouter router = new(registry, deps, new EmptyScopeFactory(),
new MemoryCache(new MemoryCacheOptions()), NullLogger<CommandRouter>.Instance);
return (router, registry, sessions, codes);
}
private static ThirdPartyMessage Message(string detail, bool isGroup = false, long userId = 42)
=> new()
{
Id = "MSG-TEST", Detail = detail, IsGroup = isGroup, OpenId = isGroup ? "GROUP" : "USER",
AuthorOpenId = "USER", FunGameUID = userId, Timestamp = "2026-11-09 23:00:00"
};
private sealed class FakeBindCodes : IBindCodeService
{
public int Calls { get; private set; }
public int TtlSeconds => 300;
public Task<string> IssueAsync(long userId, string purpose = "qq_bind", CancellationToken cancellationToken = default)
{
Calls++;
return Task.FromResult("123456");
}
public Task<BindRedeemResult> RedeemAsync(string code, ExternalIdentity identity, CancellationToken cancellationToken = default)
=> Task.FromResult(BindRedeemResult.Ok(42));
}
private sealed class FakeSessions : IUserSessionService
{
public int ClearCalls { get; private set; }
public Task<UserSessionState?> GetAsync(long userId, CancellationToken cancellationToken = default) => Task.FromResult<UserSessionState?>(null);
public Task SetPendingAsync(long userId, string action, string payloadJson, TimeSpan ttl, CancellationToken cancellationToken = default) => Task.CompletedTask;
public Task ClearPendingAsync(long userId, CancellationToken cancellationToken = default)
{
ClearCalls++;
return Task.CompletedTask;
}
public Task SetPageCursorAsync(long userId, string cursor, CancellationToken cancellationToken = default) => Task.CompletedTask;
}
private sealed class EmptyScopeFactory : IServiceScopeFactory
{
public IServiceScope CreateScope() => new EmptyScope();
}
private sealed class EmptyScope : IServiceScope
{
public IServiceProvider ServiceProvider { get; } = new ServiceCollection().BuildServiceProvider();
public void Dispose() { }
}
}
+160
View File
@@ -0,0 +1,160 @@
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using OshimaBot.Commands;
using OshimaBot.Data;
using OshimaBot.Game.Services;
using OshimaBot.Gameplay;
using OshimaBot.Models;
using OshimaBot.Security;
using Xunit;
namespace OshimaBot.Tests;
/// <summary>P2 指令层:真实 SQLite + CommandRouter 的端到端验证。</summary>
public sealed class EconomyCommandTests
{
private const long UserId = 42;
[Fact]
public void Registry_ResolvesP2VerbsAndKeepsPurchaseDistinct()
{
using EconomyCommandDatabase db = new();
CommandRegistry registry = CommandCatalog.Build(db.Dependencies);
Assert.Equal(66, registry.All.Count);
Assert.Equal("shop", registry.Resolve("/商店")!.Command.Key);
Assert.Equal("buy", registry.Resolve("/购买 @1 x2")!.Command.Key);
Assert.Equal(new[] { "@1", "x2" }, registry.Resolve("/购买 @1 x2")!.Args);
Assert.Equal("market-buy", registry.Resolve("/购买市场 @1")!.Command.Key);
Assert.Equal("boss", registry.Resolve("/Boss")!.Command.Key);
Assert.Equal("rank", registry.Resolve("/排行榜 战绩")!.Command.Key);
Assert.Equal("list-item", registry.Resolve("/上架 @1 200")!.Command.Key);
}
[Fact]
public async Task Router_StoreBuyAndMarketLifecycle()
{
using EconomyCommandDatabase db = new();
CommandRouter router = db.CreateRouter();
string shop = await RouteAsync(router, "/商店");
Assert.Contains("补给包", shop);
Assert.Contains("@1", shop);
Assert.Contains("购买成功", await RouteAsync(router, "/购买 @1"));
Assert.Contains("上架成功", await RouteAsync(router, "/上架 @1 200"));
Assert.Contains("200 金币", await RouteAsync(router, "/市场"));
Assert.Contains("不能购买自己的挂单", await RouteAsync(router, "/购买市场 @1"));
Assert.Contains("已下架", await RouteAsync(router, "/下架 @1"));
Assert.Contains("市场暂时空着", await RouteAsync(router, "/市场"));
}
[Fact]
public async Task Router_OffersInstanceBossDuelAndRanking()
{
using EconomyCommandDatabase db = new();
CommandRouter router = db.CreateRouter();
Assert.Contains("报价单已发布", await RouteAsync(router, "/报价 @1 300"));
Assert.Contains("300 金币", await RouteAsync(router, "/报价列表"));
Assert.Contains("不能接受自己的报价单", await RouteAsync(router, "/接受报价 @1"));
Assert.Contains("报价已撤回", await RouteAsync(router, "/撤回报价 @1"));
Assert.Contains("材料数量不足", await RouteAsync(router, "/锻造 @1 1"));
Assert.Contains("进入秘境", await RouteAsync(router, "/秘境 精英"));
Assert.Contains("尚未结束", await RouteAsync(router, "/收取秘境"));
Assert.Contains("Boss 讨伐成功", await RouteAsync(router, "/Boss"));
Assert.Contains("今天已经挑战过", await RouteAsync(router, "/Boss"));
Assert.Contains("决斗", await RouteAsync(router, "/决斗"));
string rank = await RouteAsync(router, "/排行榜 战绩");
Assert.Contains("战绩榜", rank);
Assert.Contains("@1", rank);
}
[Fact]
public async Task Router_LookAndHelpReflectP2()
{
using EconomyCommandDatabase db = new();
CommandRouter router = db.CreateRouter();
string look = await RouteAsync(router, "/观察");
Assert.Contains("补给站", look);
Assert.Contains("交易摊", look);
string help = await RouteAsync(router, "/帮助 p11");
Assert.Contains("11/11", help);
Assert.Contains("经济战斗", help);
string legacy = await RouteAsync(router, "/玩法帮助");
Assert.Contains("P0", legacy);
Assert.Contains("P1", legacy);
Assert.Contains("P2", legacy);
}
private static async Task<string> RouteAsync(CommandRouter router, string command)
{
BotReply? reply = await router.RouteAsync(Message(command), new OtherData());
Assert.NotNull(reply);
return reply!.Markdown?.Content ?? reply.Text ?? "";
}
private static ThirdPartyMessage Message(string detail)
=> new()
{
Id = "MSG-P2", Detail = detail, IsGroup = false, OpenId = "USER",
AuthorOpenId = "USER", FunGameUID = UserId, Timestamp = "2026-11-10 00:40:00"
};
private sealed class EconomyCommandDatabase : IDisposable
{
public SqliteConnection Connection { get; }
public ServiceProvider Provider { get; }
public CommandDependencies Dependencies { get; }
public EconomyCommandDatabase()
{
FunGameRuntime.EnsureInitialized();
Connection = new SqliteConnection("Data Source=:memory:");
Connection.Open();
ServiceCollection services = new();
services.AddLogging();
services.AddMemoryCache();
services.AddDbContext<BotDbContext>(options => options.UseSqlite(Connection));
services.AddSingleton(Options.Create(new ServerOptions()));
services.AddSingleton(Options.Create(new DatabaseOptions { ApplyMigrationsOnStartup = false }));
services.AddSingleton<IUserDirectory, UserDirectory>();
services.AddSingleton<IUserSessionService, UserSessionService>();
services.AddSingleton<IPlayerService, PlayerService>();
services.AddSingleton<IEconomyService, EconomyService>();
Provider = services.BuildServiceProvider();
using IServiceScope scope = Provider.CreateScope();
scope.ServiceProvider.GetRequiredService<BotDbContext>().Database.EnsureCreated();
Dependencies = new CommandDependencies(
null!, null!, null!,
Provider.GetRequiredService<IUserSessionService>(),
Provider.GetRequiredService<IPlayerService>(),
Provider.GetRequiredService<IEconomyService>(),
NullLogger.Instance);
}
public CommandRouter CreateRouter() => new(
CommandCatalog.Build(Dependencies), Dependencies,
Provider.GetRequiredService<IServiceScopeFactory>(),
Provider.GetRequiredService<IMemoryCache>(),
NullLogger<CommandRouter>.Instance);
public void Dispose()
{
Provider.Dispose();
Connection.Dispose();
}
}
}
+282
View File
@@ -0,0 +1,282 @@
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using OshimaBot.Data;
using OshimaBot.Data.Entities;
using OshimaBot.Game.Services;
using OshimaBot.Gameplay;
using OshimaBot.Models;
using OshimaBot.Security;
using Xunit;
namespace OshimaBot.Tests;
/// <summary>P2 经济仓储:跨用户交易、托管、双边账本、定时结算与排行榜。</summary>
public sealed class EconomyTests
{
private const long Seller = 42;
private const long Buyer = 43;
[Fact]
public async Task Store_LazySeedsAndBuyWritesBalancedLedger()
{
using EconomyDatabase db = new();
IEconomyService economy = db.Get<IEconomyService>();
IReadOnlyList<StoreEntry> goods = await economy.GetStoreAsync(Seller);
Assert.Equal(GameplayRules.SeedStoreGoods.Count, goods.Count);
Assert.Equal(1, goods[0].Index);
ActionResult buy = await economy.BuyAsync(Seller, 1, 2);
Assert.True(buy.Ok, buy.Title);
using IServiceScope scope = db.Provider.CreateScope();
BotDbContext dbContext = scope.ServiceProvider.GetRequiredService<BotDbContext>();
PlayerState state = await dbContext.PlayerStates.FirstAsync(x => x.UserId == Seller);
LedgerEntry entry = await dbContext.LedgerEntries.FirstAsync(x => x.Reason == "store_buy");
Assert.Equal(-goods[0].Price * 2, entry.Delta);
Assert.Equal(state.Credits, entry.BalanceAfter);
// 同名同品质物品会堆叠成一行,数量累加。
Assert.Equal(2, (await dbContext.ItemInstances.SingleAsync(
x => x.UserId == Seller && x.CatalogId == "store")).Quantity);
}
[Fact]
public async Task Store_InsufficientCreditsRollsBackEverything()
{
using EconomyDatabase db = new();
IEconomyService economy = db.Get<IEconomyService>();
await economy.GetStoreAsync(Seller);
await db.Get<IPlayerService>().GetSnapshotAsync(Seller); // 懒建 player_state,便于设置余额
await SetCreditsAsync(db, Seller, 0);
ActionResult result = await economy.BuyAsync(Seller, 1, 1);
Assert.False(result.Ok);
using IServiceScope scope = db.Provider.CreateScope();
BotDbContext dbContext = scope.ServiceProvider.GetRequiredService<BotDbContext>();
Assert.Empty(await dbContext.LedgerEntries.Where(x => x.Reason == "store_buy").ToListAsync());
Assert.Equal(0, await dbContext.ItemInstances.CountAsync(x => x.UserId == Seller && x.CatalogId == "store"));
Assert.Equal(GameplayRules.SeedStoreGoods[0].Stock,
(await dbContext.StoreGoods.OrderBy(x => x.Id).FirstAsync()).Stock);
}
[Fact]
public async Task Market_CrossUserTradeHasTwoBalancedLedgerEntries()
{
using EconomyDatabase db = new();
IEconomyService economy = db.Get<IEconomyService>();
IPlayerService players = db.Get<IPlayerService>();
await players.GetSnapshotAsync(Seller); // 建档 + 初始 3 件物品
ActionResult listed = await economy.ListOnMarketAsync(Seller, 1, 200);
Assert.True(listed.Ok, listed.Title);
Assert.Equal(GameplayRules.StartingItems - 1, (await players.GetBagAsync(Seller)).Count); // 已托管
IReadOnlyList<MarketEntry> market = await economy.GetMarketAsync(Buyer);
Assert.Single(market);
Assert.False(market[0].IsMine);
Assert.Equal(GameplayRules.MarketFee(200), market[0].Fee);
ActionResult bought = await economy.BuyMarketAsync(Buyer, 1);
Assert.True(bought.Ok, bought.Title);
using IServiceScope scope = db.Provider.CreateScope();
BotDbContext dbContext = scope.ServiceProvider.GetRequiredService<BotDbContext>();
PlayerState sellerState = await dbContext.PlayerStates.FirstAsync(x => x.UserId == Seller);
PlayerState buyerState = await dbContext.PlayerStates.FirstAsync(x => x.UserId == Buyer);
Assert.Equal(sellerState.Credits,
(await dbContext.LedgerEntries.FirstAsync(x => x.Reason == "market_sale")).BalanceAfter);
Assert.Equal(buyerState.Credits,
(await dbContext.LedgerEntries.FirstAsync(x => x.Reason == "market_buy")).BalanceAfter);
Assert.Equal(200, (await dbContext.LedgerEntries.FirstAsync(x => x.Reason == "market_sale")).Delta);
Assert.Equal(-200, (await dbContext.LedgerEntries.FirstAsync(x => x.Reason == "market_buy")).Delta);
Assert.Equal(1, (await dbContext.MarketListings.FirstAsync()).Status);
long tradedItemId = (await dbContext.MarketListings.FirstAsync()).ItemInstanceId;
Assert.Equal(Buyer, (await dbContext.ItemInstances.FirstAsync(x => x.Id == tradedItemId)).UserId);
Assert.Empty(await economy.GetMarketAsync(Buyer));
}
[Fact]
public async Task Market_CannotBuyOwnListingAndDelistReturnsItem()
{
using EconomyDatabase db = new();
IEconomyService economy = db.Get<IEconomyService>();
IPlayerService players = db.Get<IPlayerService>();
await players.GetSnapshotAsync(Seller);
Assert.True((await economy.ListOnMarketAsync(Seller, 1, 150)).Ok);
Assert.False((await economy.BuyMarketAsync(Seller, 1)).Ok);
Assert.True((await economy.DelistAsync(Seller, 1)).Ok);
Assert.Equal(GameplayRules.StartingItems, (await players.GetBagAsync(Seller)).Count);
Assert.Empty(await economy.GetMarketAsync(Seller));
using IServiceScope scope = db.Provider.CreateScope();
BotDbContext dbContext = scope.ServiceProvider.GetRequiredService<BotDbContext>();
Assert.Equal(2, (await dbContext.MarketListings.FirstAsync()).Status);
}
[Fact]
public async Task Offer_AcceptAndCancelLifecycle()
{
using EconomyDatabase db = new();
IEconomyService economy = db.Get<IEconomyService>();
IPlayerService players = db.Get<IPlayerService>();
await players.GetSnapshotAsync(Seller);
Assert.True((await economy.CreateOfferAsync(Seller, 1, 300)).Ok);
Assert.Single(await economy.GetOffersAsync(Buyer));
Assert.False((await economy.AcceptOfferAsync(Seller, 1)).Ok); // 不能接受自己的报价
ActionResult accepted = await economy.AcceptOfferAsync(Buyer, 1);
Assert.True(accepted.Ok, accepted.Title);
using IServiceScope scope = db.Provider.CreateScope();
BotDbContext dbContext = scope.ServiceProvider.GetRequiredService<BotDbContext>();
Assert.Equal(-300, (await dbContext.LedgerEntries.FirstAsync(x => x.Reason == "offer_buy")).Delta);
Assert.Equal(300, (await dbContext.LedgerEntries.FirstAsync(x => x.Reason == "offer_sale")).Delta);
Assert.Equal(1, (await dbContext.Trades.FirstAsync()).Status);
Assert.Equal(Buyer, (await dbContext.Trades.FirstAsync()).BuyerUserId);
Assert.True((await economy.CreateOfferAsync(Seller, 1, 100)).Ok);
Assert.True((await economy.CancelOfferAsync(Seller, 1)).Ok);
Assert.Equal(2, (await dbContext.Trades.OrderBy(x => x.Id).LastAsync()).Status);
}
[Fact]
public async Task ForgeAndInstance_RequireExpiryThenDeliverRewards()
{
using EconomyDatabase db = new();
IEconomyService economy = db.Get<IEconomyService>();
IPlayerService players = db.Get<IPlayerService>();
await players.GetSnapshotAsync(Seller);
await AddMaterialAsync(db, Seller, 3); // @4(初始 3 件之后)
Assert.True((await economy.ForgeAsync(Seller, 4, 1)).Ok);
Assert.False((await economy.ClaimForgeAsync(Seller)).Ok);
await ExpireAsync(db, "forge");
Assert.True((await economy.ClaimForgeAsync(Seller)).Ok);
Assert.Contains(await players.GetBagAsync(Seller), item => item.Name.Contains("锻造"));
Assert.True((await economy.InstanceAsync(Seller, "精英")).Ok);
Assert.False((await economy.ClaimInstanceAsync(Seller)).Ok);
await ExpireAsync(db, "instance");
Assert.True((await economy.ClaimInstanceAsync(Seller)).Ok);
Assert.Contains(await players.GetBagAsync(Seller), item => item.Name.Contains("秘境掉落"));
using IServiceScope scope = db.Provider.CreateScope();
BotDbContext dbContext = scope.ServiceProvider.GetRequiredService<BotDbContext>();
Assert.True((await dbContext.PlayerStates.FirstAsync(x => x.UserId == Seller)).Exp
>= GameplayRules.InstanceRewardExp);
Assert.Single(await dbContext.LedgerEntries.Where(x => x.Reason == "instance_reward").ToListAsync());
}
[Fact]
public async Task Boss_OncePerGameDayAndRankingReflectsPoints()
{
using EconomyDatabase db = new();
IEconomyService economy = db.Get<IEconomyService>();
Assert.True((await economy.BossAsync(Seller)).Ok);
Assert.False((await economy.BossAsync(Seller)).Ok);
Assert.True((await economy.DuelAsync(Seller)).Ok);
IReadOnlyList<RankEntry> points = await economy.GetRankingAsync("战绩");
IReadOnlyList<RankEntry> credits = await economy.GetRankingAsync("credits");
Assert.Single(points);
Assert.True(points[0].Value >= GameplayRules.BossWinPoints);
Assert.NotEmpty(credits);
using IServiceScope scope = db.Provider.CreateScope();
BotDbContext dbContext = scope.ServiceProvider.GetRequiredService<BotDbContext>();
Assert.Single(await dbContext.AppConfigs.Where(x => x.Key.StartsWith("boss:")).ToListAsync());
Assert.Equal(2, await dbContext.LedgerEntries.CountAsync(x => x.Reason == "boss_reward"));
}
[Fact]
public async Task NoIdentity_NeverWritesEconomyData()
{
using EconomyDatabase db = new();
IEconomyService economy = db.Get<IEconomyService>();
Assert.False((await economy.BuyAsync(0, 1, 1)).Ok);
Assert.False((await economy.ListOnMarketAsync(0, 1, 100)).Ok);
Assert.False((await economy.BossAsync(0)).Ok);
using IServiceScope scope = db.Provider.CreateScope();
BotDbContext dbContext = scope.ServiceProvider.GetRequiredService<BotDbContext>();
Assert.Equal(0, await dbContext.MarketListings.CountAsync());
Assert.Equal(0, await dbContext.Trades.CountAsync());
}
private static async Task SetCreditsAsync(EconomyDatabase db, long userId, long credits)
{
using IServiceScope scope = db.Provider.CreateScope();
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
PlayerState state = await context.PlayerStates.FirstAsync(x => x.UserId == userId);
state.Credits = credits;
await context.SaveChangesAsync();
}
private static async Task AddMaterialAsync(EconomyDatabase db, long userId, int quantity)
{
using IServiceScope scope = db.Provider.CreateScope();
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
context.ItemInstances.Add(new ItemInstance
{
UserId = userId, CatalogId = "test", Quality = 1, Quantity = quantity,
PayloadJson = "{\"name\":\"测试材料\"}"
});
await context.SaveChangesAsync();
}
private static async Task ExpireAsync(EconomyDatabase db, string kind)
{
using IServiceScope scope = db.Provider.CreateScope();
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
if (kind == "forge")
{
ForgingJob job = await context.ForgingJobs.FirstAsync();
job.EndsAtUtc = DateTime.UtcNow.AddMinutes(-1);
}
else
{
ExplorationRun run = await context.ExplorationRuns.FirstAsync();
run.EndsAtUtc = DateTime.UtcNow.AddMinutes(-1);
}
await context.SaveChangesAsync();
}
private sealed class EconomyDatabase : IDisposable
{
public SqliteConnection Connection { get; }
public ServiceProvider Provider { get; }
public EconomyDatabase()
{
FunGameRuntime.EnsureInitialized();
Connection = new SqliteConnection("Data Source=:memory:");
Connection.Open();
ServiceCollection services = new();
services.AddLogging();
services.AddDbContext<BotDbContext>(options => options.UseSqlite(Connection));
services.AddSingleton(Options.Create(new ServerOptions()));
services.AddSingleton(Options.Create(new DatabaseOptions { ApplyMigrationsOnStartup = false }));
services.AddSingleton<IUserDirectory, UserDirectory>();
services.AddSingleton<IPlayerService, PlayerService>();
services.AddSingleton<IEconomyService, EconomyService>();
Provider = services.BuildServiceProvider();
using IServiceScope scope = Provider.CreateScope();
scope.ServiceProvider.GetRequiredService<BotDbContext>().Database.EnsureCreated();
}
public T Get<T>() where T : notnull => Provider.GetRequiredService<T>();
public void Dispose()
{
Provider.Dispose();
Connection.Dispose();
}
}
}
+35 -1
View File
@@ -1,3 +1,4 @@
using System.Security.Claims;
using System.Text.Json;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
@@ -7,6 +8,7 @@ using Microsoft.Extensions.Logging.Abstractions;
using OshimaBot.Data;
using OshimaBot.Messaging;
using OshimaBot.Models;
using OshimaBot.Security;
using OshimaBot.Services;
using Xunit;
@@ -30,7 +32,7 @@ public sealed class EventPipelineTests
private static QQEventDispatcher CreateDispatcher(
FakeDedup dedup, FakeAck ack, FakeSink sink) => new(
dedup, ack, sink, NullLogger<QQEventDispatcher>.Instance);
dedup, ack, sink, new FakeUserDirectory(), NullLogger<QQEventDispatcher>.Instance);
[Fact]
public async Task DedupStore_SecondMarkIsRejected()
@@ -77,6 +79,24 @@ public sealed class EventPipelineTests
Assert.Equal(1, dedup.MarkedCount);
}
[Fact]
public async Task Dispatcher_AttachesResolvedIdentityBeforeQueue()
{
FakeDedup dedup = new();
FakeSink sink = new();
FakeUserDirectory users = new();
QQEventDispatcher dispatcher = new(dedup, new FakeAck(), sink, users, NullLogger<QQEventDispatcher>.Instance);
EventDispatchResult result = await dispatcher.DispatchAsync(Parse(C2CJson), QQEventSource.WebSocket);
Assert.Equal(EventDispatchStatus.Accepted, result.Status);
IBotMessage message = Assert.Single(sink.Messages);
Assert.Equal(42, message.FunGameUID);
Assert.NotNull(message.Principal);
Assert.Equal("42", message.Principal!.FindFirst(ClaimTypes.NameIdentifier)!.Value);
Assert.Equal(1, users.Calls);
}
[Fact]
public async Task Dispatcher_RejectsDuplicateAcrossBothSources()
{
@@ -264,6 +284,20 @@ public sealed class EventPipelineTests
}
}
private sealed class FakeUserDirectory : IUserDirectory
{
public int Calls { get; private set; }
public Task<BotUserPrincipal> ResolveAsync(ExternalIdentity identity, CancellationToken cancellationToken = default)
{
Calls++;
return Task.FromResult(new BotUserPrincipal(42, "U000042", "", [BotRole.Player], false));
}
public Task<IdentityLinkStatus> LinkAsync(long userId, ExternalIdentity identity, CancellationToken cancellationToken = default)
=> Task.FromResult(IdentityLinkStatus.Linked);
}
private sealed class FakeSink : IBotMessageSink
{
public List<IBotMessage> Messages { get; } = [];
+196
View File
@@ -0,0 +1,196 @@
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using OshimaBot.Commands;
using OshimaBot.Data;
using OshimaBot.Game.Services;
using OshimaBot.Gameplay;
using OshimaBot.Models;
using OshimaBot.Security;
using Xunit;
namespace OshimaBot.Tests;
/// <summary>P1 指令层:显式注册表 + CommandRouter + 真实玩法仓储的端到端验证。</summary>
public sealed class GameplayCommandTests
{
private const long UserId = 42;
[Fact]
public void Registry_RegistersP1VerbsWithoutBreakingP0Aliases()
{
using GameplayCommandDatabase db = new();
CommandRegistry registry = CommandCatalog.Build(db.Dependencies);
Assert.Equal(66, registry.All.Count);
Assert.Equal("status", registry.Resolve("/状态")!.Command.Key);
Assert.Equal("status", registry.Resolve("存档")!.Command.Key);
Assert.Equal("gacha-ten", registry.Resolve("/十连抽卡")!.Command.Key);
Assert.Equal("char", registry.Resolve("查角色 1")!.Command.Key); // 旧别名未被「我的角色」抢走
Assert.Equal("characters", registry.Resolve("/我的角色")!.Command.Key);
CommandMatch party = registry.Resolve("/小队 加入 @2")!;
Assert.Equal("party", party.Command.Key);
Assert.Equal(new[] { "加入", "@2" }, party.Args);
Assert.Equal("x10", Assert.Single(registry.Resolve("/抽卡 x10")!.Args));
Assert.Equal("@3", Assert.Single(registry.Resolve("/领奖 @3")!.Args));
Assert.Equal(2, registry.Resolve("/背包 p2")!.Page);
}
[Fact]
public async Task Router_SignInQuestsAndClaimChainWorks()
{
using GameplayCommandDatabase db = new();
CommandRouter router = db.CreateRouter();
string signin = await RouteAsync(router, "/签到");
string quests = await RouteAsync(router, "/每日任务");
string claim = await RouteAsync(router, "/领奖 @1");
string repeat = await RouteAsync(router, "/领奖 @1");
string status = await RouteAsync(router, "/状态");
Assert.Contains("签到成功", signin);
Assert.Contains("可领取", quests);
Assert.Contains("任务奖励已领取", claim);
Assert.Contains("已领取", repeat);
Assert.Contains("指令未能完成", repeat);
Assert.Contains("旅人档案", status);
Assert.Contains("金币", status);
}
[Fact]
public async Task Router_BagReferencesLockAndSalvageWork()
{
using GameplayCommandDatabase db = new();
CommandRouter router = db.CreateRouter();
Assert.Contains("抽卡", await RouteAsync(router, "/抽卡 3"));
string bag = await RouteAsync(router, "/背包");
Assert.Contains("@1", bag);
Assert.Contains("物品已锁定", await RouteAsync(router, "/锁定 @1"));
Assert.Contains("锁定或绑定", await RouteAsync(router, "/分解 @1"));
Assert.Contains("物品已解锁", await RouteAsync(router, "/解锁 @1"));
Assert.Contains("分解完成", await RouteAsync(router, "/分解 @1"));
}
[Fact]
public async Task Router_NoIdentityReturnsStructuredError()
{
using GameplayCommandDatabase db = new();
CommandRouter router = db.CreateRouter();
BotReply? reply = await router.RouteAsync(Message("/签到", userId: 0), new OtherData());
Assert.NotNull(reply);
string content = reply!.Markdown!.Content!;
Assert.Contains("身份尚未就绪", content);
Assert.Contains("没有发生", content);
Assert.Contains("下一步", content);
}
[Fact]
public async Task Help_LastPageContainsP2Group()
{
using GameplayCommandDatabase db = new();
CommandRouter router = db.CreateRouter();
string content = await RouteAsync(router, "/帮助 p11");
Assert.Contains("11/11", content);
bool hasP2 = content.Contains("/排行榜", StringComparison.Ordinal)
|| content.Contains("经济战斗", StringComparison.Ordinal);
Assert.True(hasP2, content);
}
[Fact]
public void FromResult_RendersSuccessAndFailureDifferently()
{
string ok = CommandReplies.FromResult(ActionResult.Success("标题", "状态", ["- 行"], ["/帮助"]))
.Markdown!.Content!;
string fail = CommandReplies.FromResult(ActionResult.Fail("发生了什么", "没有发生什么", "下一步", "/帮助"))
.Markdown!.Content!;
Assert.Contains("## 标题", ok);
Assert.Contains("状态", ok);
Assert.Contains("指令未能完成", fail);
Assert.Contains("没有发生", fail);
Assert.Contains("下一步", fail);
}
[Fact]
public async Task Router_LookAndLegacyHelpReflectMigratedP1()
{
using GameplayCommandDatabase db = new();
CommandRouter router = db.CreateRouter();
string look = await RouteAsync(router, "/观察");
string legacy = await RouteAsync(router, "/玩法帮助");
Assert.Contains("中央广场", look);
Assert.Contains("P1", legacy);
Assert.Contains("商店", legacy);
}
private static async Task<string> RouteAsync(CommandRouter router, string command)
{
BotReply? reply = await router.RouteAsync(Message(command), new OtherData());
Assert.NotNull(reply);
return reply!.Markdown?.Content ?? reply.Text ?? "";
}
private static ThirdPartyMessage Message(string detail, long userId = UserId)
=> new()
{
Id = "MSG-P1", Detail = detail, IsGroup = false, OpenId = "USER",
AuthorOpenId = "USER", FunGameUID = userId, Timestamp = "2026-11-10 00:00:00"
};
private sealed class GameplayCommandDatabase : IDisposable
{
public SqliteConnection Connection { get; }
public ServiceProvider Provider { get; }
public CommandDependencies Dependencies { get; }
public GameplayCommandDatabase()
{
FunGameRuntime.EnsureInitialized();
Connection = new SqliteConnection("Data Source=:memory:");
Connection.Open();
ServiceCollection services = new();
services.AddLogging();
services.AddMemoryCache();
services.AddDbContext<BotDbContext>(options => options.UseSqlite(Connection));
services.AddSingleton(Options.Create(new ServerOptions()));
services.AddSingleton(Options.Create(new DatabaseOptions { ApplyMigrationsOnStartup = false }));
services.AddSingleton<IUserDirectory, UserDirectory>();
services.AddSingleton<IUserSessionService, UserSessionService>();
services.AddSingleton<IPlayerService, PlayerService>();
Provider = services.BuildServiceProvider();
using IServiceScope scope = Provider.CreateScope();
scope.ServiceProvider.GetRequiredService<BotDbContext>().Database.EnsureCreated();
Dependencies = new CommandDependencies(
null!, null!, null!,
Provider.GetRequiredService<IUserSessionService>(),
Provider.GetRequiredService<IPlayerService>(),
null!,
NullLogger.Instance);
}
public CommandRouter CreateRouter() => new(
CommandCatalog.Build(Dependencies), Dependencies,
Provider.GetRequiredService<IServiceScopeFactory>(),
Provider.GetRequiredService<IMemoryCache>(),
NullLogger<CommandRouter>.Instance);
public void Dispose()
{
Provider.Dispose();
Connection.Dispose();
}
}
}
+308
View File
@@ -0,0 +1,308 @@
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using OshimaBot.Data;
using OshimaBot.Data.Entities;
using OshimaBot.Game.Services;
using OshimaBot.Gameplay;
using OshimaBot.Models;
using OshimaBot.Security;
using Xunit;
namespace OshimaBot.Tests;
/// <summary>P1 玩法仓储:真实 SQLite 内存库,验证事务、ledger 对账与 @编号 生命周期。</summary>
public sealed class GameplayTests
{
private const long UserId = 42;
[Fact]
public async Task Ensure_CreatesInitialStateOnlyOnce()
{
using GameplayDatabase db = new();
IPlayerService players = db.Get<IPlayerService>();
PlayerSnapshot? first = await players.GetSnapshotAsync(UserId);
PlayerSnapshot? second = await players.GetSnapshotAsync(UserId);
Assert.NotNull(first);
Assert.Equal(GameplayRules.StartingCredits, first.Credits);
Assert.Equal(GameplayRules.StartingDiamonds, first.Diamonds);
Assert.Equal(1, first.CharacterCount);
Assert.Equal(GameplayRules.StartingItems, first.ItemCount);
Assert.Equal(second!.Credits, first.Credits);
using IServiceScope scope = db.Provider.CreateScope();
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
Assert.Equal(1, await context.PlayerStates.CountAsync());
Assert.Equal(1, await context.LedgerEntries.CountAsync(x => x.Reason == "register"));
}
[Fact]
public async Task SignIn_IsIdempotentAndWritesLedger()
{
using GameplayDatabase db = new();
IPlayerService players = db.Get<IPlayerService>();
ActionResult first = await players.SignInAsync(UserId);
ActionResult second = await players.SignInAsync(UserId);
Assert.True(first.Ok);
Assert.False(second.Ok);
Assert.Contains("已经签到", second.Title);
using IServiceScope scope = db.Provider.CreateScope();
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
PlayerState state = await context.PlayerStates.FirstAsync(x => x.UserId == UserId);
LedgerEntry entry = await context.LedgerEntries.FirstAsync(x => x.Reason == "signin");
Assert.Equal(state.Credits, entry.BalanceAfter);
Assert.Equal(GameplayRules.SignInCredits(0), entry.Delta);
Assert.Equal(1, await context.SignInRecords.CountAsync());
Assert.Equal(1, await context.LedgerEntries.CountAsync(x => x.Reason == "signin"));
}
[Fact]
public async Task Gacha_WithInsufficientDiamondsRollsBackEverything()
{
using GameplayDatabase db = new();
IPlayerService players = db.Get<IPlayerService>();
await players.GetSnapshotAsync(UserId);
await SetDiamondsAsync(db, 0);
ActionResult result = await players.GachaAsync(UserId, 10);
Assert.False(result.Ok);
using IServiceScope scope = db.Provider.CreateScope();
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
Assert.Equal(0, (await context.PlayerStates.FirstAsync(x => x.UserId == UserId)).Diamonds);
Assert.Empty(await context.LedgerEntries.Where(x => x.Reason == "gacha").ToListAsync());
Assert.Equal(GameplayRules.StartingItems, await context.ItemInstances.CountAsync(x => x.UserId == UserId));
}
[Fact]
public async Task Gacha_TenPullDebitsDiscountAndKeepsLedgerBalanced()
{
using GameplayDatabase db = new();
IPlayerService players = db.Get<IPlayerService>();
await players.GetSnapshotAsync(UserId);
await SetDiamondsAsync(db, 100);
ActionResult result = await players.GachaAsync(UserId, 10);
Assert.True(result.Ok, result.Title);
using IServiceScope scope = db.Provider.CreateScope();
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
PlayerState state = await context.PlayerStates.FirstAsync(x => x.UserId == UserId);
Assert.Equal(100 - GameplayRules.GachaTenCost, state.Diamonds);
LedgerEntry entry = await context.LedgerEntries.FirstAsync(x => x.Reason == "gacha");
Assert.Equal(-GameplayRules.GachaTenCost, entry.Delta);
Assert.Equal(state.Diamonds, entry.BalanceAfter);
Assert.True(await context.ItemInstances.CountAsync(x => x.UserId == UserId) > GameplayRules.StartingItems);
Assert.Contains(await context.ItemInstances.Where(x => x.CatalogId == "gacha").ToListAsync(),
item => item.Quality >= 4); // 十连保底
}
[Fact]
public async Task Bag_LockSalvageAndEquipLifecycle()
{
using GameplayDatabase db = new();
IPlayerService players = db.Get<IPlayerService>();
IReadOnlyList<BagEntry> bag = await players.GetBagAsync(UserId);
Assert.Equal(GameplayRules.StartingItems, bag.Count);
Assert.Equal(1, bag[0].Index);
Assert.True((await players.SetLockAsync(UserId, 1, true)).Ok);
Assert.False((await players.SalvageAsync(UserId, 1, 1)).Ok);
Assert.True((await players.SetLockAsync(UserId, 1, false)).Ok);
PlayerSnapshot before = (await players.GetSnapshotAsync(UserId))!;
ActionResult salvage = await players.SalvageAsync(UserId, 1, 1);
Assert.True(salvage.Ok, salvage.Title);
PlayerSnapshot after = (await players.GetSnapshotAsync(UserId))!;
Assert.Equal(before.Credits + GameplayRules.SalvageValue(1, 1), after.Credits);
using IServiceScope scope = db.Provider.CreateScope();
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
LedgerEntry entry = await context.LedgerEntries.FirstAsync(x => x.Reason == "salvage");
Assert.Equal(after.Credits, entry.BalanceAfter);
Assert.True((await players.EquipAsync(UserId, 2)).Ok);
Assert.True((await players.GetBagAsync(UserId))[1].Equipped);
Assert.False((await players.EquipAsync(UserId, 2)).Ok); // 已绑定,不能重复装备
Assert.False((await players.SalvageAsync(UserId, 2, 1)).Ok); // 绑定物品不可分解
Assert.True((await players.UnequipAsync(UserId, "weapon")).Ok);
Assert.False((await players.GetBagAsync(UserId))[1].Equipped);
Assert.True((await players.SalvageAsync(UserId, 2, 1)).Ok);
}
[Fact]
public async Task Train_RequiresExpiryThenGrantsExpForLevelUp()
{
using GameplayDatabase db = new();
IPlayerService players = db.Get<IPlayerService>();
Assert.True((await players.TrainStartAsync(UserId, 1, 1)).Ok);
Assert.False((await players.TrainClaimAsync(UserId)).Ok); // 尚未结束
Assert.False((await players.TrainStartAsync(UserId, 1, 1)).Ok); // 不能重复开练
using (IServiceScope scope = db.Provider.CreateScope())
{
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
TrainingSession session = await context.TrainingSessions.FirstAsync(x => x.UserId == UserId);
session.EndsAtUtc = DateTime.UtcNow.AddMinutes(-1);
await context.SaveChangesAsync();
}
Assert.True((await players.TrainClaimAsync(UserId)).Ok);
PlayerSnapshot snapshot = (await players.GetSnapshotAsync(UserId))!;
Assert.Equal(GameplayRules.TrainExpBase + GameplayRules.TrainExpPerLevel, snapshot.Exp);
Assert.True((await players.LevelUpAsync(UserId, 1)).Ok);
IReadOnlyList<CharacterEntry> characters = await players.GetCharactersAsync(UserId);
Assert.Equal(2, Assert.Single(characters).Level);
}
[Fact]
public async Task Squad_MainAndQuestRewardsArePersistent()
{
using GameplayDatabase db = new();
IPlayerService players = db.Get<IPlayerService>();
Assert.True((await players.SquadAsync(UserId, "", 0)).Ok);
Assert.True((await players.SquadAsync(UserId, "add", 1)).Ok);
Assert.False((await players.SquadAsync(UserId, "add", 1)).Ok);
Assert.True((await players.SquadAsync(UserId, "remove", 1)).Ok);
Assert.Equal(0, (await players.GetSnapshotAsync(UserId))!.SquadCount);
Assert.True((await players.SignInAsync(UserId)).Ok);
IReadOnlyList<QuestEntry> quests = await players.GetQuestsAsync(UserId);
Assert.Equal(1, quests[0].Status);
Assert.Equal(0, quests[1].Status);
PlayerSnapshot before = (await players.GetSnapshotAsync(UserId))!;
Assert.True((await players.ClaimQuestAsync(UserId, 1)).Ok);
Assert.False((await players.ClaimQuestAsync(UserId, 1)).Ok); // 不能重复领
Assert.False((await players.ClaimQuestAsync(UserId, 2)).Ok); // 未完成
PlayerSnapshot after = (await players.GetSnapshotAsync(UserId))!;
Assert.Equal(before.Credits + GameplayRules.QuestRewardCredits, after.Credits);
Assert.Equal(before.Diamonds + GameplayRules.QuestRewardDiamonds, after.Diamonds);
Assert.Equal(2, (await players.GetQuestsAsync(UserId))[0].Status);
}
[Fact]
public async Task SimulationProgress_AdvancesQuest()
{
using GameplayDatabase db = new();
IPlayerService players = db.Get<IPlayerService>();
Assert.True((await players.RecordSimulationAsync(UserId)).Ok);
Assert.Equal(1, (await players.GetQuestsAsync(UserId))[1].Status);
Assert.True((await players.ClaimQuestAsync(UserId, 2)).Ok);
}
[Fact]
public async Task NoIdentity_NeverWritesPlayerState()
{
using GameplayDatabase db = new();
IPlayerService players = db.Get<IPlayerService>();
Assert.False((await players.SignInAsync(0)).Ok);
Assert.False((await players.GachaAsync(0, 1)).Ok);
Assert.Null(await players.GetSnapshotAsync(0));
Assert.Empty(await players.GetBagAsync(0));
using IServiceScope scope = db.Provider.CreateScope();
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
Assert.Equal(0, await context.PlayerStates.CountAsync());
Assert.Equal(0, await context.LedgerEntries.CountAsync());
}
[Fact]
public async Task ApiKey_LazilyBindsIndependentInternalUsers()
{
using GameplayDatabase db = new();
using (IServiceScope scope = db.Provider.CreateScope())
{
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
context.ApiKeys.AddRange(
new ApiKey { Name = "a", KeyHash = ApiKeyDefaults.Hash("key-a"), ScopesJson = "[]" },
new ApiKey { Name = "b", KeyHash = ApiKeyDefaults.Hash("key-b"), ScopesJson = "[]" });
await context.SaveChangesAsync();
}
ApiKeyAuthenticator authenticator = db.Get<ApiKeyAuthenticator>();
ApiKeyIdentity? a1 = await authenticator.AuthenticateAsync("key-a");
ApiKeyIdentity? b1 = await authenticator.AuthenticateAsync("key-b");
ApiKeyIdentity? a2 = await authenticator.AuthenticateAsync("key-a");
Assert.NotNull(a1);
Assert.NotNull(b1);
Assert.NotNull(a2);
Assert.True(a1.UserId > 0);
Assert.True(b1.UserId > 0);
Assert.NotEqual(a1.UserId, b1.UserId);
Assert.Equal(a1.UserId, a2.UserId);
Assert.Equal(BotRole.Player, Assert.Single(a1.Roles));
using IServiceScope verifyScope = db.Provider.CreateScope();
BotDbContext verifyContext = verifyScope.ServiceProvider.GetRequiredService<BotDbContext>();
Assert.Equal(2, await verifyContext.Users.CountAsync());
Assert.Equal(2, await verifyContext.UserIdentities.CountAsync(x => x.Provider == "apikey"));
Assert.Equal(0, await verifyContext.ApiKeys.CountAsync(x => x.UserId == null));
}
[Fact]
public void Rules_AreDeterministicAndBounded()
{
Assert.Equal(GameplayRules.Fortune(7, "2026-11-10"), GameplayRules.Fortune(7, "2026-11-10"));
Assert.Contains(GameplayRules.Fortune(8, "2026-11-10"), GameplayRules.FortuneTexts);
Assert.Equal(10, GameplayRules.LevelCap(0));
Assert.Equal(20, GameplayRules.LevelCap(1));
Assert.True(GameplayRules.ExpForLevel(10) > GameplayRules.ExpForLevel(1));
Assert.InRange(GameplayRules.RollQuality(new Random(1)), 1, 5);
}
private static async Task SetDiamondsAsync(GameplayDatabase db, int diamonds)
{
using IServiceScope scope = db.Provider.CreateScope();
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
PlayerState state = await context.PlayerStates.FirstAsync(x => x.UserId == UserId);
state.Diamonds = diamonds;
await context.SaveChangesAsync();
}
private sealed class GameplayDatabase : IDisposable
{
public SqliteConnection Connection { get; }
public ServiceProvider Provider { get; }
public GameplayDatabase()
{
FunGameRuntime.EnsureInitialized();
Connection = new SqliteConnection("Data Source=:memory:");
Connection.Open();
ServiceCollection services = new();
services.AddLogging();
services.AddDbContext<BotDbContext>(options => options.UseSqlite(Connection));
services.AddSingleton(Options.Create(new ServerOptions()));
services.AddSingleton(Options.Create(new DatabaseOptions { ApplyMigrationsOnStartup = false }));
services.AddSingleton<IUserDirectory, UserDirectory>();
services.AddSingleton<ApiKeyAuthenticator>();
services.AddSingleton<IPlayerService, PlayerService>();
Provider = services.BuildServiceProvider();
using IServiceScope scope = Provider.CreateScope();
scope.ServiceProvider.GetRequiredService<BotDbContext>().Database.EnsureCreated();
}
public T Get<T>() where T : notnull => Provider.GetRequiredService<T>();
public void Dispose()
{
Provider.Dispose();
Connection.Dispose();
}
}
}
+229
View File
@@ -0,0 +1,229 @@
using System.Security.Claims;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using OshimaBot.Data;
using OshimaBot.Data.Entities;
using OshimaBot.Models;
using OshimaBot.Security;
using Xunit;
namespace OshimaBot.Tests;
public sealed class IdentityTests
{
[Fact]
public async Task UserDirectory_RegistersLazilyOnlyOnce()
{
using TestDatabase db = new();
IUserDirectory directory = db.Get<IUserDirectory>();
BotUserPrincipal first = await directory.ResolveAsync(ExternalIdentity.Qq("OPENID1"));
BotUserPrincipal second = await directory.ResolveAsync(ExternalIdentity.Qq("OPENID1"));
Assert.True(first.IsNew);
Assert.False(second.IsNew);
Assert.Equal(first.UserId, second.UserId);
Assert.Equal(BotRole.Player, Assert.Single(first.Roles));
Assert.StartsWith("U", first.Handle);
using IServiceScope scope = db.Provider.CreateScope();
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
Assert.Equal(1, await context.Users.CountAsync());
Assert.Equal(1, await context.UserIdentities.CountAsync());
Assert.Equal(1, await context.AuditLogs.CountAsync());
Assert.Equal("user.register", (await context.AuditLogs.FirstAsync()).Action);
}
[Fact]
public async Task UserDirectory_UnionSubjectReusesExistingAccount()
{
using TestDatabase db = new();
IUserDirectory directory = db.Get<IUserDirectory>();
BotUserPrincipal c2c = await directory.ResolveAsync(ExternalIdentity.Qq("C2C-1", "c2c", "UNION-1"));
BotUserPrincipal group = await directory.ResolveAsync(ExternalIdentity.Qq("GROUP-1", "group", "UNION-1"));
Assert.Equal(c2c.UserId, group.UserId);
Assert.False(group.IsNew);
using IServiceScope scope = db.Provider.CreateScope();
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
Assert.Equal(1, await context.Users.CountAsync());
Assert.Equal(2, await context.UserIdentities.CountAsync());
Assert.Equal(2, await context.AuditLogs.CountAsync()); // register + union_link
}
[Fact]
public async Task UserDirectory_SuperAdminWhitelistGrantsOwner()
{
using TestDatabase db = new(new ServerOptions { SuperAdminOpenIds = ["BOSS-OPENID"] });
BotUserPrincipal principal = await db.Get<IUserDirectory>().ResolveAsync(ExternalIdentity.Qq("BOSS-OPENID"));
Assert.Contains(BotRole.Owner, principal.Roles);
Assert.True(principal.HasRole(BotRole.Admin));
Assert.True(principal.ToClaimsPrincipal().IsInRole("Owner"));
}
[Fact]
public async Task BindCodeService_IsSixDigitsOneTimeAndLinksIdentity()
{
using TestDatabase db = new();
BotUserPrincipal host = await db.Get<IUserDirectory>().ResolveAsync(ExternalIdentity.Qq("HOST"));
IBindCodeService codes = db.Get<IBindCodeService>();
string code = await codes.IssueAsync(host.UserId);
Assert.Matches(@"^\d{6}$", code);
Assert.Equal(300, codes.TtlSeconds);
BindRedeemResult redeemed = await codes.RedeemAsync(code, ExternalIdentity.Qq("NEW-OPENID"));
Assert.Equal(BindRedeemStatus.Success, redeemed.Status);
Assert.Equal(host.UserId, redeemed.UserId);
Assert.Equal(BindRedeemStatus.Used, (await codes.RedeemAsync(code, ExternalIdentity.Qq("ANOTHER"))).Status);
using IServiceScope scope = db.Provider.CreateScope();
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
Assert.NotNull(await context.UserIdentities.FirstOrDefaultAsync(x => x.Subject == "NEW-OPENID"));
Assert.Null(await context.UserIdentities.FirstOrDefaultAsync(x => x.Subject == "ANOTHER"));
Assert.NotNull((await context.BindCodes.FirstAsync()).UsedAtUtc);
}
[Fact]
public async Task BindCodeService_RejectsExpiredConflictAndMissingUser()
{
using TestDatabase db = new();
IUserDirectory directory = db.Get<IUserDirectory>();
BotUserPrincipal host = await directory.ResolveAsync(ExternalIdentity.Qq("HOST"));
BotUserPrincipal other = await directory.ResolveAsync(ExternalIdentity.Qq("TAKEN"));
IBindCodeService codes = db.Get<IBindCodeService>();
Assert.Equal(BindRedeemStatus.NotFound, (await codes.RedeemAsync("000000", ExternalIdentity.Qq("X"))).Status);
Assert.Equal(BindRedeemStatus.Conflict,
(await codes.RedeemAsync(await codes.IssueAsync(host.UserId), ExternalIdentity.Qq("TAKEN"))).Status);
Assert.Equal(BindRedeemStatus.InvalidUser,
(await codes.RedeemAsync(await codes.IssueAsync(9999), ExternalIdentity.Qq("X"))).Status);
Assert.NotEqual(host.UserId, other.UserId);
using IServiceScope scope = db.Provider.CreateScope();
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
context.BindCodes.Add(new BindCode
{
Code = "123456", UserId = host.UserId, Purpose = "test",
ExpiresAtUtc = DateTime.UtcNow.AddMinutes(-1), CreatedAtUtc = DateTime.UtcNow.AddMinutes(-2)
});
await context.SaveChangesAsync();
Assert.Equal(BindRedeemStatus.Expired, (await codes.RedeemAsync("123456", ExternalIdentity.Qq("X"))).Status);
}
[Fact]
public async Task ApiKeyAuthenticator_ValidatesHashRevocationAndExpiry()
{
using TestDatabase db = new();
const string secret = "a-high-entropy-random-key-0123456789";
ApiKeyAuthenticator authenticator = db.Get<ApiKeyAuthenticator>();
using (IServiceScope scope = db.Provider.CreateScope())
{
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
context.ApiKeys.Add(new ApiKey
{
Name = "test", KeyHash = ApiKeyDefaults.Hash(secret), ScopesJson = "[\"thirdparty\",\"bind\"]",
CreatedAtUtc = DateTime.UtcNow
});
await context.SaveChangesAsync();
}
ApiKeyIdentity? valid = await authenticator.AuthenticateAsync(secret);
Assert.NotNull(valid);
Assert.Contains("thirdparty", valid!.Scopes);
Assert.Null(await authenticator.AuthenticateAsync("wrong-key"));
using (IServiceScope scope = db.Provider.CreateScope())
{
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
ApiKey row = await context.ApiKeys.FirstAsync();
row.RevokedAtUtc = DateTime.UtcNow;
await context.SaveChangesAsync();
}
Assert.Null(await authenticator.AuthenticateAsync(secret));
using (IServiceScope scope = db.Provider.CreateScope())
{
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
ApiKey row = await context.ApiKeys.FirstAsync();
row.RevokedAtUtc = null;
row.ExpiresAtUtc = DateTime.UtcNow.AddMinutes(-1);
await context.SaveChangesAsync();
}
Assert.Null(await authenticator.AuthenticateAsync(secret));
}
[Fact]
public async Task DatabaseInitializer_BootstrapsApiKeyHashOnly()
{
using TestDatabase db = new();
DatabaseInitializer initializer = new(
db.Provider.GetRequiredService<IServiceScopeFactory>(),
Options.Create(new DatabaseOptions { ApplyMigrationsOnStartup = false }),
Options.Create(new ServerOptions { ApiKey = "bootstrap-secret" }),
NullLogger<DatabaseInitializer>.Instance);
await initializer.InitializeAsync(CancellationToken.None);
ApiKeyAuthenticator authenticator = db.Get<ApiKeyAuthenticator>();
Assert.NotNull(await authenticator.AuthenticateAsync("bootstrap-secret"));
using IServiceScope scope = db.Provider.CreateScope();
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
ApiKey row = await context.ApiKeys.FirstAsync();
Assert.NotEqual("bootstrap-secret", row.KeyHash);
Assert.Equal(64, row.KeyHash.Length);
}
[Fact]
public void Principals_CarryRolesAndScopes()
{
ApiKeyIdentity key = new(7, 42, "svc", ["thirdparty", "bind"], [BotRole.Admin]);
ClaimsPrincipal principal = key.ToClaimsPrincipal(ApiKeyDefaults.Scheme);
Assert.Equal("42", principal.FindFirst(ClaimTypes.NameIdentifier)!.Value);
Assert.True(principal.IsInRole("Admin"));
Assert.Contains(principal.FindAll("scope"), claim => claim.Value == "bind");
BotUserPrincipal user = new(1, "U000001", "", [BotRole.Owner], false);
Assert.True(user.HasRole(BotRole.Admin));
Assert.False(new BotUserPrincipal(2, "U2", "", [BotRole.Player], false).HasRole(BotRole.Admin));
Assert.Equal(ApiKeyDefaults.Hash("abc"), ApiKeyDefaults.Hash("abc"));
Assert.Equal(new[] { BotRole.Player }, ApiKeyDefaults.ParseRoles([0, 99, 0]));
}
/// <summary>共享的 SQLite 内存库 + 真实 DI 容器,保证测的是真实 EF Core 行为。</summary>
private sealed class TestDatabase : IDisposable
{
public SqliteConnection Connection { get; }
public ServiceProvider Provider { get; }
public TestDatabase(ServerOptions? serverOptions = null)
{
Connection = new SqliteConnection("Data Source=:memory:");
Connection.Open();
ServiceCollection services = new();
services.AddLogging();
services.AddDbContext<BotDbContext>(options => options.UseSqlite(Connection));
services.AddSingleton(Options.Create(serverOptions ?? new ServerOptions()));
services.AddSingleton(Options.Create(new DatabaseOptions { ApplyMigrationsOnStartup = false }));
services.AddSingleton<IUserDirectory, UserDirectory>();
services.AddSingleton<IBindCodeService, BindCodeService>();
services.AddSingleton<ApiKeyAuthenticator>();
Provider = services.BuildServiceProvider();
using IServiceScope scope = Provider.CreateScope();
scope.ServiceProvider.GetRequiredService<BotDbContext>().Database.EnsureCreated();
}
public T Get<T>() where T : notnull => Provider.GetRequiredService<T>();
public void Dispose()
{
Provider.Dispose();
Connection.Dispose();
}
}
}
+139
View File
@@ -0,0 +1,139 @@
using FunGame.Core.Entity;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using OshimaBot.Game.Services;
using OshimaBot.Models;
using OshimaBot.Services;
using Xunit;
namespace OshimaBot.Tests;
public sealed class SimulationIsolationTests
{
[Fact]
public void RunContext_MapAndRandomArePerInstance()
{
SimulationRunContext first = new();
SimulationRunContext second = new();
Assert.NotSame(first.Map, second.Map);
Assert.NotSame(first.Random, second.Random);
Assert.Equal("", first.Msg);
Assert.Null(first.SeedOverride);
}
[Fact]
public void BeginRun_IsolatesMutableStateBetweenRuns()
{
SimulationRunContext first = new() { Msg = "A", SeedOverride = 11 };
SimulationRunContext second = new() { Msg = "B", SeedOverride = 22 };
using (FunGameSimulation.BeginRun(first))
{
FunGameSimulation.Msg += "1";
FunGameSimulation.WriteLine("2");
FunGameSimulation.IsRuning = true;
Assert.Equal("A12\r\n", first.Msg);
Assert.Equal(11, FunGameSimulation.SeedOverride);
Assert.True(FunGameSimulation.IsRuning);
}
Assert.NotSame(first, FunGameSimulation.Current);
using (FunGameSimulation.BeginRun(second))
{
Assert.Equal("B", FunGameSimulation.Msg);
Assert.Equal(22, FunGameSimulation.SeedOverride);
Assert.False(FunGameSimulation.IsRuning); // 不串上一局的运行中标记
}
Assert.Equal("A12\r\n", first.Msg);
Assert.Equal("B", second.Msg);
}
[Fact]
public void BeginRun_NestedScopeRestoresPreviousContext()
{
SimulationRunContext outer = new() { Msg = "OUT" };
using (FunGameSimulation.BeginRun(outer))
{
using (FunGameSimulation.BeginRun(new SimulationRunContext { Msg = "IN" }))
{
Assert.Equal("IN", FunGameSimulation.Msg);
}
Assert.Equal("OUT", FunGameSimulation.Msg);
}
}
[Fact]
public async Task BeginRun_FlowsIntoTaskRun()
{
SimulationRunContext context = new() { Msg = "X" };
using (FunGameSimulation.BeginRun(context))
{
await Task.Run(() => FunGameSimulation.WriteLine("Y"));
}
Assert.Equal("XY\r\n", context.Msg);
}
[Fact]
public void StaticStatistics_AreBackedByStore()
{
Assert.Same(FunGameSimulation.StatisticsStore.CharacterStatistics,
FunGameSimulation.CharacterStatistics);
Assert.Same(FunGameSimulation.StatisticsStore.TeamCharacterStatistics,
FunGameSimulation.TeamCharacterStatistics);
Assert.NotNull(FunGameSimulation.StatisticsStore.Read(store => store.LastRecord));
}
[Fact]
public void StatisticsStore_ResetRebuildsRowsForCurrentCatalog()
{
FunGameRuntime.EnsureInitialized();
InMemorySimulationStatisticsStore store = new();
store.LastRecord = ["stale"];
store.Reset(FunGameService.Characters);
Assert.Equal(FunGameService.Characters.Count, store.CharacterStatistics.Count);
Assert.Equal(FunGameService.Characters.Count, store.TeamCharacterStatistics.Count);
Assert.Empty(store.LastRecord);
Assert.Empty(store.LastFullRecord);
Assert.All(store.CharacterStatistics.Values, stats => Assert.NotNull(stats));
}
[Fact]
public async Task SimulationService_ReadsLastRecordFromStoreNotStatics()
{
InMemorySimulationStatisticsStore store = new();
store.LastRecord = ["A"];
store.LastFullRecord = ["A", "B"];
FunGameSimulationService service = new(store, new NoopRunRecorder(),
Options.Create(new ServerOptions()), NullLogger<FunGameSimulationService>.Instance);
Assert.Equal(new[] { "A" }, await service.GetLastAsync(false));
Assert.Equal(2, (await service.GetLastAsync(true)).Count);
Assert.False(service.IsRunning);
}
[Fact]
public async Task QueryService_ReadsStatisticsFromInjectedStore()
{
FunGameRuntime.EnsureInitialized();
InMemorySimulationStatisticsStore store = new();
Character character = FunGameService.Characters[0];
store.CharacterStatistics[character] = new CharacterStatistics();
FunGameQueryService queries = new(store);
string stats = await queries.GetStatsAsync(1, false);
Assert.Contains("参赛", stats);
List<string> ranking = await queries.GetRankingAsync(false, true);
Assert.Single(ranking);
Assert.Contains("技术得分", ranking[0]);
}
private sealed class NoopRunRecorder : ISimulationRunRecorder
{
public Task<long> RecordAsync(SimulationRunRecord record, CancellationToken cancellationToken = default)
=> Task.FromResult(0L);
}
}
@@ -0,0 +1,199 @@
using FunGame.Core.Entity;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using OshimaBot.Data;
using OshimaBot.Game.Services;
using OshimaBot.Models;
using OshimaBot.Services;
using Xunit;
namespace OshimaBot.Tests;
/// <summary>S9:模拟统计 / 日志数据库化,验证重启恢复与默认值。</summary>
public sealed class SimulationPersistenceTests
{
[Fact]
public async Task Restart_RestoresStatisticsAndLastLogs()
{
using PersistenceDatabase db = new();
EfSimulationStatisticsStore first = db.CreateStore();
await first.LoadAsync(); // 空库
first.Reset(FunGameService.Characters);
Character character = FunGameService.Characters[0];
first.CharacterStatistics[character].Plays = 7;
first.TeamCharacterStatistics[character].Wins = 3;
DateTimeOffset now = DateTimeOffset.UtcNow;
await first.RecordAsync(new SimulationRunRecord(
42, 12345, "{\"IsTeam\":false}", ["精简A", "精简B"],
["完整A", "完整B", "完整C"], now, now.AddSeconds(2)));
await first.PersistAsync();
// 全新 store 实例 + 同一数据库 = 进程重启
EfSimulationStatisticsStore second = db.CreateStore();
await second.LoadAsync();
Assert.Equal(FunGameService.Characters.Count, second.CharacterStatistics.Count);
Assert.Equal(7, second.CharacterStatistics[character].Plays);
Assert.Equal(3, second.TeamCharacterStatistics[character].Wins);
Assert.Equal(new[] { "精简A", "精简B" }, second.LastRecord);
Assert.Equal(3, second.LastFullRecord.Count);
Assert.Equal("完整C", second.LastFullRecord[2]);
}
[Fact]
public async Task Persist_IsUpsertAndNotDuplicate()
{
using PersistenceDatabase db = new();
EfSimulationStatisticsStore store = db.CreateStore();
await store.LoadAsync();
store.Reset(FunGameService.Characters);
await store.PersistAsync();
int firstCount = await db.CountStatisticsAsync();
await store.PersistAsync();
int secondCount = await db.CountStatisticsAsync();
Assert.Equal(FunGameService.Characters.Count * 2, firstCount); // character + team
Assert.Equal(firstCount, secondCount);
}
[Fact]
public async Task RecordAsync_WritesSimulationRunRow()
{
using PersistenceDatabase db = new();
EfSimulationStatisticsStore store = db.CreateStore();
DateTimeOffset now = DateTimeOffset.UtcNow;
long id = await store.RecordAsync(new SimulationRunRecord(
99, 777, "{}", ["结果"], ["完整"], now, now.AddSeconds(1)));
Assert.True(id > 0);
using IServiceScope scope = db.Provider.CreateScope();
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
var run = await context.SimulationRuns.SingleAsync();
Assert.Equal("777", run.Seed);
Assert.Equal(99, run.UserId);
Assert.Equal("[\"结果\"]", run.ResultJson);
Assert.Equal("[\"完整\"]", run.RoundsJson);
Assert.NotNull(run.FinishedAtUtc);
}
[Fact]
public async Task LoadAsync_ToleratesCorruptStatsJson()
{
using PersistenceDatabase db = new();
using (IServiceScope scope = db.Provider.CreateScope())
{
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
context.SimulationStatistics.Add(new OshimaBot.Data.Entities.SimulationStatistic
{
Scope = "character",
CatalogId = FunGameService.Characters[0].Id.ToString(),
StatsJson = "{ 不是合法 JSON",
UpdatedAtUtc = DateTime.UtcNow
});
await context.SaveChangesAsync();
}
EfSimulationStatisticsStore store = db.CreateStore();
await store.LoadAsync();
Assert.Equal(0, store.CharacterStatistics[FunGameService.Characters[0]].Plays);
}
[Fact]
public async Task RealSimulation_IsRecordedAndPersisted()
{
using PersistenceDatabase db = new();
EfSimulationStatisticsStore store = db.CreateStore();
await store.LoadAsync();
store.Reset(FunGameService.Characters);
// 与生产一致:模拟器静态委托也指向同一个 EF 仓储,结束后恢复全局实例避免污染其它测试。
ISimulationStatisticsStore previous = FunGameSimulation.StatisticsStore;
FunGameSimulation.UseStatisticsStore(store);
try
{
FunGameSimulationService service = new(store, store,
Options.Create(new ServerOptions()), NullLogger<FunGameSimulationService>.Instance);
SimulationResult? result = await service.RunAsync(new SimulationRequest
{
UserId = 42, Seed = 20261110, MaxRespawnTimesMix = 0
});
Assert.NotNull(result);
Assert.Equal(20261110, result.Seed);
Assert.NotEmpty(await service.GetLastAsync(false));
Assert.NotNull(await service.GetLastAsync(true));
using IServiceScope scope = db.Provider.CreateScope();
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
Assert.Equal(1, await context.SimulationRuns.CountAsync());
Assert.Equal(42, (await context.SimulationRuns.SingleAsync()).UserId);
Assert.True(await context.SimulationStatistics.CountAsync() > 0);
}
finally
{
FunGameSimulation.UseStatisticsStore(previous);
}
}
[Fact]
public void Archiving_IsOffByDefault()
{
Assert.False(new SimulationOptions().ArchiveRounds);
Assert.False(new SimulationRunContext().ArchiveRounds);
Assert.False(new ServerOptions().ArchiveSimulationRounds);
Assert.True(new ServerOptions().StoreFullSimulationLog);
}
[Fact]
public async Task InMemoryStore_PersistIsNoOp()
{
InMemorySimulationStatisticsStore store = new();
await store.PersistAsync();
await store.PersistAsync();
Assert.Empty(store.CharacterStatistics);
}
private sealed class PersistenceDatabase : IDisposable
{
public SqliteConnection Connection { get; }
public ServiceProvider Provider { get; }
public PersistenceDatabase()
{
FunGameRuntime.EnsureInitialized();
Connection = new SqliteConnection("Data Source=:memory:");
Connection.Open();
ServiceCollection services = new();
services.AddLogging();
services.AddDbContext<BotDbContext>(options => options.UseSqlite(Connection));
Provider = services.BuildServiceProvider();
using IServiceScope scope = Provider.CreateScope();
scope.ServiceProvider.GetRequiredService<BotDbContext>().Database.EnsureCreated();
}
public EfSimulationStatisticsStore CreateStore() => new(
Provider.GetRequiredService<IServiceScopeFactory>(),
NullLogger<EfSimulationStatisticsStore>.Instance);
public async Task<int> CountStatisticsAsync()
{
using IServiceScope scope = Provider.CreateScope();
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
return await context.SimulationStatistics.CountAsync();
}
public void Dispose()
{
Provider.Dispose();
Connection.Dispose();
}
}
}
+719
View File
@@ -0,0 +1,719 @@
using System.Globalization;
using FunGame.Core.Library.Constant;
using OshimaBot.Game.Services;
using OshimaBot.Gameplay;
using OshimaBot.Messaging;
using OshimaBot.Models;
using OshimaBot.Services;
namespace OshimaBot.Commands;
/// <summary>
/// 显式命令工厂(用户要求:switch-case 清单式注册,禁止反射扫描程序集)。
/// 新增指令必须同时改 Keys 与 Create 的 switch;帮助、别名表、权限矩阵都由这一份数据生成。
/// </summary>
public static class CommandCatalog
{
public static readonly IReadOnlyList<string> Keys =
[
"help", "battle-help", "cancel", "bind", "uptime", "legacy-help",
"magic-card", "magic-card-pack",
"char", "skill", "item", "stats", "team-stats",
"rank-win", "rank-team-win", "rank-rating", "rank-team-rating",
"log", "log-full",
"sim-debug", "sim-team-map", "sim-team", "sim-map", "sim-mix", "sim",
// ---- P1:旅人存档 ----
"register", "status", "look", "notice", "fortune", "signin",
"quests", "quest-claim", "gacha", "gacha-ten", "bag",
"use", "salvage", "lock", "unlock", "equip", "unequip",
"characters", "set-main", "levelup", "break", "train", "train-claim", "party",
// ---- P2:经济与战斗 ----
"shop", "buy", "market", "list-item", "delist", "market-buy",
"offers", "offer", "offer-accept", "offer-cancel",
"forge", "forge-claim", "instance", "instance-claim",
"duel", "boss", "rank"
];
public static CommandRegistry Build(CommandDependencies deps)
=> new(Keys.Select(key => Create(key, deps)));
public static ICommand Create(string key, CommandDependencies deps) => key switch
{
// ---- 系统 ----
"help" => new DelegateCommand(
key: "help", name: "帮助", aliases: ["help", "?"], usage: "/帮助 [p2]",
description: "列出全部指令(分页)", group: CommandGroups.System,
handler: context => Task.FromResult(CommandReplies.Help(context.Registry, context.Page))),
"battle-help" => new DelegateCommand(
key: "battle-help", name: "战斗帮助", aliases: ["角色帮助", "物品帮助", "battlehelp"],
usage: "/战斗帮助", description: "战斗与资料查询说明", group: CommandGroups.System,
handler: _ => Task.FromResult(CommandReplies.Compose("⚔️ 战斗与资料指令", "旧版指令仍可直接使用",
[
"- /查角色 <编号或名称> 满级角色资料",
"- /查技能 <编号或名称> 1/2 级与满级技能",
"- /查物品 <编号或名称> 物品属性",
"- /混战模拟 [复活次数] 个人混战",
"- /FunGame模拟 无复活混战",
"- /FunGame团队模拟 团队模拟",
"- /个人地图模拟 · /团队地图模拟 · /团队调试模拟",
"- /查数据 · /查团队数据 累计统计",
"- /查个人胜率 · /查团队胜率 · /查个人评分 · /查团队评分",
"- /上次的日志 · /上次的完整日志"
], ["/帮助", "/查角色 1", "/FunGame模拟"]))),
"cancel" => new DelegateCommand(
key: "cancel", name: "取消", aliases: ["重置状态", "cancel", "reset"], usage: "/取消",
description: "清空待确认操作与会话状态", group: CommandGroups.System,
handler: async context =>
{
await deps.Sessions.ClearPendingAsync(context.UserId, context.CancellationToken);
return CommandReplies.Compose("🧹 状态已重置", "待确认操作与会话游标已清空",
["- 上一条待确认操作已作废", "- 存档与背包数据不受影响"], ["/帮助"]);
}),
"bind" => new DelegateCommand(
key: "bind", name: "绑定", aliases: ["获取接入码", "bind"], usage: "/绑定",
description: "签发 6 位一次性绑定码(仅单聊)", group: CommandGroups.System, audit: true,
handler: async context =>
{
if (context.IsGroup)
{
return CommandReplies.Error("群聊不能签发绑定码", "没有生成任何码",
"请在与机器人的单聊里发送 /绑定", "/帮助");
}
if (context.UserId <= 0)
{
return CommandReplies.Error("身份尚未就绪", "没有生成任何码", "请稍后重发一条消息触发注册");
}
string code = await deps.BindCodes.IssueAsync(context.UserId, "qq_bind", context.CancellationToken);
return CommandReplies.Compose("🔑 一次性绑定码", $"{code} · {deps.BindCodes.TtlSeconds / 60} 分钟内有效",
[
$"- 绑定码:{code}",
"- 只能使用一次,用后即失效",
"- 旧版直接回显 OpenID 的「接入码」已停用"
], ["/帮助"]);
}),
"uptime" => new DelegateCommand(
key: "uptime", name: "查询服务器启动时间", aliases: ["启动时间", "uptime", "status"],
usage: "/查询服务器启动时间", description: "查看服务启动时间(UTC)", group: CommandGroups.System,
handler: _ => Task.FromResult(CommandReplies.Compose("🖥️ 服务器状态",
$"启动于 {FunGameRuntime.StartedAt:yyyy-MM-dd HH:mm:ss} UTC",
[$"- 核心:{FunGameInfo.FunGame_Version}", "- 接入:WebSocket 单模式"], ["/帮助"]))),
"legacy-help" => new DelegateCommand(
key: "legacy-help", name: "玩法帮助", aliases: ["存档帮助", "社团帮助", "活动帮助", "商店帮助", "legacy"],
usage: "/玩法帮助", description: "查看当前开放的玩法范围", group: CommandGroups.Legacy,
handler: _ => Task.FromResult(CommandReplies.Compose("🧭 OshimaBot 版本状态",
"P0 至 P2 玩法已全部开放",
[
"- P0 角色/技能/物品查询、战斗模拟与统计排行",
"- P1 存档、背包、签到、抽卡、练级、每日任务",
"- P2 商店、市场、报价交易、锻造、秘境、决斗、Boss、排行榜",
"- P3(社团/赛马/赛事预测)按计划不在本轮范围"
], ["/帮助", "/状态", "/商店"]))),
// ---- P1:旅人存档(全部由显式 switch 注册)----
"register" => new DelegateCommand(
key: "register", name: "注册", aliases: ["register", "建档"], usage: "/注册",
description: "建立旅人存档并领取初始资源", group: CommandGroups.Player,
handler: async context => CommandReplies.FromResult(
await deps.Players.RegisterAsync(context.UserId, context.CancellationToken))),
"status" => new DelegateCommand(
key: "status", name: "状态", aliases: ["存档", "me"], usage: "/状态",
description: "旅人档案:等级、货币、角色与背包概览", group: CommandGroups.Player,
handler: context => StatusAsync(deps, context)),
"look" => new DelegateCommand(
key: "look", name: "观察", aliases: ["场景", "look"], usage: "/观察",
description: "MUD 场景:当前所在与可交互地点", group: CommandGroups.Player,
handler: context => LookAsync(deps, context)),
"notice" => new DelegateCommand(
key: "notice", name: "公告", aliases: ["notice"], usage: "/公告",
description: "查看运营公告", group: CommandGroups.Player,
handler: async context => CommandReplies.Compose("📜 铎京公告", null,
[QQMarkdown.Escape(await deps.Players.GetNoticeAsync(context.CancellationToken))],
["/状态", "/帮助"])),
"fortune" => new DelegateCommand(
key: "fortune", name: "运势", aliases: ["今日运势", "fortune"], usage: "/运势",
description: "今日占卜(同一天结果固定)", group: CommandGroups.Player,
handler: async context => CommandReplies.Compose("🔮 今日运势",
GameplayRules.Today(),
[QQMarkdown.Escape(await deps.Players.GetFortuneAsync(context.UserId, context.CancellationToken))],
["/签到", "/每日任务"])),
"signin" => new DelegateCommand(
key: "signin", name: "签到", aliases: ["signin", "daily"], usage: "/签到",
description: "每日签到,连续签到有额外钻石", group: CommandGroups.Player,
handler: async context => CommandReplies.FromResult(
await deps.Players.SignInAsync(context.UserId, context.CancellationToken))),
"quests" => new DelegateCommand(
key: "quests", name: "每日任务", aliases: ["任务", "quests"], usage: "/每日任务 [p2]",
description: "今日任务进度与领奖编号", group: CommandGroups.Player,
handler: context => QuestsAsync(deps, context)),
"quest-claim" => new DelegateCommand(
key: "quest-claim", name: "领奖", aliases: ["领取任务", "questclaim"], usage: "/领奖 @1",
description: "领取指定任务的每日奖励", group: CommandGroups.Player, audit: true,
handler: async context => CommandReplies.FromResult(
await deps.Players.ClaimQuestAsync(context.UserId, RefIndex(context), context.CancellationToken))),
"gacha" => new DelegateCommand(
key: "gacha", name: "抽卡", aliases: ["gacha"], usage: "/抽卡 [数量]",
description: "消耗钻石抽取物品(最多 10 连)", group: CommandGroups.Player, audit: true,
handler: async context => CommandReplies.FromResult(
await deps.Players.GachaAsync(context.UserId, Quantity(context, 0, 1), context.CancellationToken))),
"gacha-ten" => new DelegateCommand(
key: "gacha-ten", name: "十连抽卡", aliases: ["十连", "gacha10"], usage: "/十连抽卡",
description: "十连抽卡(折扣价 + 史诗保底)", group: CommandGroups.Player, audit: true,
handler: async context => CommandReplies.FromResult(
await deps.Players.GachaAsync(context.UserId, 10, context.CancellationToken))),
"bag" => new DelegateCommand(
key: "bag", name: "背包", aliases: ["查看库存", "bag", "inventory"], usage: "/背包 [p2]",
description: "查看背包,@编号 用于其它指令", group: CommandGroups.Player,
handler: context => BagAsync(deps, context)),
"use" => new DelegateCommand(
key: "use", name: "使用", aliases: ["use"], usage: "/使用 @1 [x2]",
description: "使用物品换取旅人经验", group: CommandGroups.Player,
handler: async context => CommandReplies.FromResult(await deps.Players.UseAsync(
context.UserId, RefIndex(context), Quantity(context, 1, 1), context.CancellationToken))),
"salvage" => new DelegateCommand(
key: "salvage", name: "分解", aliases: ["salvage"], usage: "/分解 @1 [x2]",
description: "分解未锁定物品换取金币", group: CommandGroups.Player,
handler: async context => CommandReplies.FromResult(await deps.Players.SalvageAsync(
context.UserId, RefIndex(context), Quantity(context, 1, 1), context.CancellationToken))),
"lock" => new DelegateCommand(
key: "lock", name: "锁定", aliases: ["lock"], usage: "/锁定 @1",
description: "锁定物品,防止误分解", group: CommandGroups.Player,
handler: async context => CommandReplies.FromResult(await deps.Players.SetLockAsync(
context.UserId, RefIndex(context), true, context.CancellationToken))),
"unlock" => new DelegateCommand(
key: "unlock", name: "解锁", aliases: ["unlock"], usage: "/解锁 @1",
description: "解除物品锁定", group: CommandGroups.Player,
handler: async context => CommandReplies.FromResult(await deps.Players.SetLockAsync(
context.UserId, RefIndex(context), false, context.CancellationToken))),
"equip" => new DelegateCommand(
key: "equip", name: "装备", aliases: ["equip"], usage: "/装备 @1",
description: "把物品装到主战角色的空槽", group: CommandGroups.Player,
handler: async context => CommandReplies.FromResult(
await deps.Players.EquipAsync(context.UserId, RefIndex(context), context.CancellationToken))),
"unequip" => new DelegateCommand(
key: "unequip", name: "卸下", aliases: ["unequip"], usage: "/卸下 weapon|armor|trinket",
description: "卸下主战角色指定槽位的装备", group: CommandGroups.Player,
handler: async context =>
{
string slot = context.FirstArgument ?? "";
return string.IsNullOrWhiteSpace(slot)
? CommandReplies.Error("缺少槽位", "没有卸下任何装备",
"用法:/卸下 weapon · /卸下 armor · /卸下 trinket", "/角色")
: CommandReplies.FromResult(await deps.Players.UnequipAsync(
context.UserId, slot.Trim().ToLowerInvariant(), context.CancellationToken));
}),
"characters" => new DelegateCommand(
key: "characters", name: "我的角色", aliases: ["角色列表", "chars"], usage: "/我的角色 [p2]",
description: "角色列表与主战标记", group: CommandGroups.Player,
handler: context => CharactersAsync(deps, context)),
"set-main" => new DelegateCommand(
key: "set-main", name: "设主战", aliases: ["主战", "setmain"], usage: "/设主战 @1",
description: "指定主战角色", group: CommandGroups.Player,
handler: async context => CommandReplies.FromResult(await deps.Players.SetMainAsync(
context.UserId, RefIndex(context), context.CancellationToken))),
"levelup" => new DelegateCommand(
key: "levelup", name: "升级", aliases: ["levelup"], usage: "/升级 @1",
description: "消耗旅人经验提升角色等级", group: CommandGroups.Player,
handler: async context => CommandReplies.FromResult(await deps.Players.LevelUpAsync(
context.UserId, RefIndex(context), context.CancellationToken))),
"break" => new DelegateCommand(
key: "break", name: "突破", aliases: ["break", "突破上限"], usage: "/突破 @1",
description: "满级后消耗金币提升等级上限", group: CommandGroups.Player, audit: true,
handler: async context => CommandReplies.FromResult(await deps.Players.BreakAsync(
context.UserId, RefIndex(context), context.CancellationToken))),
"train" => new DelegateCommand(
key: "train", name: "练级", aliases: ["训练", "train"], usage: "/练级 @1 [分钟]",
description: "花费金币开始离线练级", group: CommandGroups.Player,
handler: async context => CommandReplies.FromResult(await deps.Players.TrainStartAsync(
context.UserId, RefIndex(context),
Quantity(context, 1, GameplayRules.TrainDefaultMinutes), context.CancellationToken))),
"train-claim" => new DelegateCommand(
key: "train-claim", name: "收取练级", aliases: ["收训练", "trainclaim"], usage: "/收取练级",
description: "结算已完成的练级经验", group: CommandGroups.Player,
handler: async context => CommandReplies.FromResult(
await deps.Players.TrainClaimAsync(context.UserId, context.CancellationToken))),
"party" => new DelegateCommand(
key: "party", name: "小队", aliases: ["编队", "party"], usage: "/小队 [加入|移除 @编号]",
description: "查看或调整 3 人主力小队", group: CommandGroups.Player,
handler: async context => CommandReplies.FromResult(await deps.Players.SquadAsync(
context.UserId, context.FirstArgument ?? "", RefIndex(context, 1), context.CancellationToken))),
// ---- P2:经济与战斗(全部由显式 switch 注册)----
"shop" => new DelegateCommand(
key: "shop", name: "商店", aliases: ["shop"], usage: "/商店 [p2]",
description: "铎京补给站货架", group: CommandGroups.Economy,
handler: context => ShopAsync(deps, context)),
"buy" => new DelegateCommand(
key: "buy", name: "购买", aliases: ["buy"], usage: "/购买 @1 [x2]",
description: "购买商店商品(最多 10 件)", group: CommandGroups.Economy, audit: true,
handler: async context => CommandReplies.FromResult(await deps.Economy.BuyAsync(
context.UserId, RefIndex(context), Quantity(context, 1, 1), context.CancellationToken))),
"market" => new DelegateCommand(
key: "market", name: "市场", aliases: ["market"], usage: "/市场 [p2]",
description: "旅人挂单列表", group: CommandGroups.Economy,
handler: context => MarketAsync(deps, context)),
"list-item" => new DelegateCommand(
key: "list-item", name: "上架", aliases: ["list"], usage: "/上架 @1 <价格>",
description: "把背包物品挂到市场(收上架费)", group: CommandGroups.Economy, audit: true,
handler: async context => CommandReplies.FromResult(await deps.Economy.ListOnMarketAsync(
context.UserId, RefIndex(context), Price(context), context.CancellationToken))),
"delist" => new DelegateCommand(
key: "delist", name: "下架", aliases: ["delist"], usage: "/下架 @1",
description: "撤回自己的挂单", group: CommandGroups.Economy,
handler: async context => CommandReplies.FromResult(await deps.Economy.DelistAsync(
context.UserId, RefIndex(context), context.CancellationToken))),
"market-buy" => new DelegateCommand(
key: "market-buy", name: "购买市场", aliases: ["marketbuy"], usage: "/购买市场 @1",
description: "购买市场挂单(买卖双方各记一笔账)", group: CommandGroups.Economy, audit: true,
handler: async context => CommandReplies.FromResult(await deps.Economy.BuyMarketAsync(
context.UserId, RefIndex(context), context.CancellationToken))),
"offers" => new DelegateCommand(
key: "offers", name: "报价列表", aliases: ["offers"], usage: "/报价列表 [p2]",
description: "查看公开报价单", group: CommandGroups.Economy,
handler: context => OffersAsync(deps, context)),
"offer" => new DelegateCommand(
key: "offer", name: "报价", aliases: ["offer"], usage: "/报价 @1 <价格>",
description: "发布物品报价单(不收上架费)", group: CommandGroups.Economy, audit: true,
handler: async context => CommandReplies.FromResult(await deps.Economy.CreateOfferAsync(
context.UserId, RefIndex(context), Price(context), context.CancellationToken))),
"offer-accept" => new DelegateCommand(
key: "offer-accept", name: "接受报价", aliases: ["offeraccept"], usage: "/接受报价 @1",
description: "按报价买下物品", group: CommandGroups.Economy, audit: true,
handler: async context => CommandReplies.FromResult(await deps.Economy.AcceptOfferAsync(
context.UserId, RefIndex(context), context.CancellationToken))),
"offer-cancel" => new DelegateCommand(
key: "offer-cancel", name: "撤回报价", aliases: ["offercancel"], usage: "/撤回报价 @1",
description: "撤回自己发布的报价单", group: CommandGroups.Economy,
handler: async context => CommandReplies.FromResult(await deps.Economy.CancelOfferAsync(
context.UserId, RefIndex(context), context.CancellationToken))),
"forge" => new DelegateCommand(
key: "forge", name: "锻造", aliases: ["forge"], usage: "/锻造 @1 [分钟]",
description: "消耗 2 个同类材料 + 金币开始锻造", group: CommandGroups.Economy, audit: true,
handler: async context => CommandReplies.FromResult(await deps.Economy.ForgeAsync(
context.UserId, RefIndex(context),
Quantity(context, 1, GameplayRules.ForgeDefaultMinutes), context.CancellationToken))),
"forge-claim" => new DelegateCommand(
key: "forge-claim", name: "收取锻造", aliases: ["forgeclaim"], usage: "/收取锻造",
description: "结算已完成的锻造", group: CommandGroups.Economy,
handler: async context => CommandReplies.FromResult(
await deps.Economy.ClaimForgeAsync(context.UserId, context.CancellationToken))),
"instance" => new DelegateCommand(
key: "instance", name: "秘境", aliases: ["instance"], usage: "/秘境 [难度]",
description: "进入秘境探索(定时结算)", group: CommandGroups.Economy, audit: true,
handler: async context => CommandReplies.FromResult(await deps.Economy.InstanceAsync(
context.UserId, context.FirstArgument ?? "", context.CancellationToken))),
"instance-claim" => new DelegateCommand(
key: "instance-claim", name: "收取秘境", aliases: ["instanceclaim"], usage: "/收取秘境",
description: "结算秘境经验、金币与掉落", group: CommandGroups.Economy,
handler: async context => CommandReplies.FromResult(
await deps.Economy.ClaimInstanceAsync(context.UserId, context.CancellationToken))),
"duel" => new DelegateCommand(
key: "duel", name: "决斗", aliases: ["duel"], usage: "/决斗",
description: "即时决斗,胜负都累计战绩", group: CommandGroups.Economy, audit: true,
handler: async context => CommandReplies.FromResult(
await deps.Economy.DuelAsync(context.UserId, context.CancellationToken))),
"boss" => new DelegateCommand(
key: "boss", name: "Boss", aliases: ["挑战Boss"], usage: "/Boss",
description: "每日一次 Boss 讨伐", group: CommandGroups.Economy, audit: true,
handler: async context => CommandReplies.FromResult(
await deps.Economy.BossAsync(context.UserId, context.CancellationToken))),
"rank" => new DelegateCommand(
key: "rank", name: "排行榜", aliases: ["rank", "ranklist"], usage: "/排行榜 [金币|等级|战绩]",
description: "查看服务器排行榜", group: CommandGroups.Economy,
handler: context => RankAsync(deps, context)),
// ---- 查询 ----
"magic-card" => new DelegateCommand(
key: "magic-card", name: "预览魔法卡", aliases: ["魔法卡", "card"], usage: "/预览魔法卡",
description: "随机生成一张魔法卡", group: CommandGroups.Query,
handler: _ => Task.FromResult(CommandReplies.Detail("🃏 魔法卡", deps.Queries.GenerateMagicCard(),
actions: ["/预览魔法卡", "/预览魔法卡包"]))),
"magic-card-pack" => new DelegateCommand(
key: "magic-card-pack", name: "预览魔法卡包", aliases: ["魔法卡包", "pack"], usage: "/预览魔法卡包",
description: "随机生成一包魔法卡", group: CommandGroups.Query,
handler: _ => Task.FromResult(CommandReplies.Detail("🎴 魔法卡包", deps.Queries.GenerateMagicCardPack(),
actions: ["/预览魔法卡", "/预览魔法卡包"]))),
"char" => new DelegateCommand(
key: "char", name: "查角色", aliases: ["角色", "char", "character"], usage: "/查角色 <编号或名称>",
description: "查看满级角色资料", group: CommandGroups.Query, prefixMatch: true,
handler: context => Task.FromResult(Found("📖 角色资料",
deps.Queries.GetCharacterInfo(context.ArgumentText), "未找到角色", context, "/查角色 1"))),
"skill" => new DelegateCommand(
key: "skill", name: "查技能", aliases: ["技能", "skill"], usage: "/查技能 <编号或名称>",
description: "查看 1/2 级与满级技能", group: CommandGroups.Query, prefixMatch: true,
handler: context =>
{
string argument = context.ArgumentText;
string result = long.TryParse(argument, out long id)
? deps.Queries.GetSkillInfo(id, null)
: deps.Queries.GetSkillInfo(null, argument);
return Task.FromResult(Found("📖 技能资料", result, "未找到技能", context, "/查技能 1"));
}),
"item" => new DelegateCommand(
key: "item", name: "查物品", aliases: ["物品", "item"], usage: "/查物品 <编号或名称>",
description: "查看物品资料", group: CommandGroups.Query, prefixMatch: true,
handler: context =>
{
string argument = context.ArgumentText;
string result = long.TryParse(argument, out long id)
? deps.Queries.GetItemInfo(id, null)
: deps.Queries.GetItemInfo(null, argument);
return Task.FromResult(Found("📖 物品资料", result, "未找到物品", context, "/查物品 1"));
}),
"stats" => new DelegateCommand(
key: "stats", name: "查数据", aliases: ["数据", "stats"], usage: "/查数据 <编号>",
description: "角色累计统计", group: CommandGroups.Stats, prefixMatch: true,
handler: context => StatsAsync(deps, false, "📊 角色统计", context)),
"team-stats" => new DelegateCommand(
key: "team-stats", name: "查团队数据", aliases: ["团队数据", "teamstats"], usage: "/查团队数据 <编号>",
description: "角色团队累计统计", group: CommandGroups.Stats, prefixMatch: true,
handler: context => StatsAsync(deps, true, "📊 角色团队统计", context)),
"rank-win" => new DelegateCommand(
key: "rank-win", name: "查个人胜率", aliases: ["个人胜率", "rankwin"], usage: "/查个人胜率",
description: "个人胜率排行", group: CommandGroups.Stats, prefixMatch: true,
handler: context => RankingAsync(deps, false, false, "🏆 个人胜率排行", context)),
"rank-team-win" => new DelegateCommand(
key: "rank-team-win", name: "查团队胜率", aliases: ["团队胜率", "rankteamwin"], usage: "/查团队胜率",
description: "团队胜率排行", group: CommandGroups.Stats, prefixMatch: true,
handler: context => RankingAsync(deps, true, false, "🏆 团队胜率排行", context)),
"rank-rating" => new DelegateCommand(
key: "rank-rating", name: "查个人评分", aliases: ["个人评分", "rankrating"], usage: "/查个人评分",
description: "个人评分排行", group: CommandGroups.Stats, prefixMatch: true,
handler: context => RankingAsync(deps, false, true, "🏆 个人评分排行", context)),
"rank-team-rating" => new DelegateCommand(
key: "rank-team-rating", name: "查团队评分", aliases: ["团队评分", "rankteamrating"], usage: "/查团队评分",
description: "团队评分排行", group: CommandGroups.Stats, prefixMatch: true,
handler: context => RankingAsync(deps, true, true, "🏆 团队评分排行", context)),
// ---- 日志与模拟 ----
"log" => new DelegateCommand(
key: "log", name: "上次的日志", aliases: ["日志", "log"], usage: "/上次的日志 [p2]",
description: "最近一次模拟日志", group: CommandGroups.Simulation,
handler: async context => CommandReplies.CodePage("📜 上次的模拟日志",
await deps.Simulations.GetLastAsync(false, context.CancellationToken), context.Page, "/上次的日志")),
"log-full" => new DelegateCommand(
key: "log-full", name: "上次的完整日志", aliases: ["完整日志", "logfull"], usage: "/上次的完整日志 [p2]",
description: "最近一次完整模拟日志", group: CommandGroups.Simulation,
handler: async context => CommandReplies.CodePage("📜 上次的完整日志",
await deps.Simulations.GetLastAsync(true, context.CancellationToken), context.Page, "/上次的完整日志")),
"sim-debug" => new DelegateCommand(
key: "sim-debug", name: "团队调试模拟", aliases: ["团队调试", "simdebug"], usage: "/团队调试模拟 [p2]",
description: "团队地图调试模拟", group: CommandGroups.Simulation, prefixMatch: true, audit: true,
handler: context => RunSimulationAsync(deps, new SimulationRequest
{
IsTeam = true, HasMap = true, IsDebug = true, ShowAll = true, MaxRespawnTimesMix = 0
}, context)),
"sim-team-map" => new DelegateCommand(
key: "sim-team-map", name: "团队地图模拟", aliases: ["团队地图", "simteammap"], usage: "/团队地图模拟 [p2]",
description: "带地图的团队模拟", group: CommandGroups.Simulation, prefixMatch: true, audit: true,
handler: context => RunSimulationAsync(deps, new SimulationRequest { IsTeam = true, HasMap = true }, context)),
"sim-team" => new DelegateCommand(
key: "sim-team", name: "FunGame团队模拟", aliases: ["团队模拟", "simteam"], usage: "/FunGame团队模拟 [p2]",
description: "团队模拟", group: CommandGroups.Simulation, prefixMatch: true, audit: true,
handler: context => RunSimulationAsync(deps, new SimulationRequest { IsTeam = true }, context)),
"sim-map" => new DelegateCommand(
key: "sim-map", name: "个人地图模拟", aliases: ["个人地图", "simmap"], usage: "/个人地图模拟 [p2]",
description: "带地图的个人模拟", group: CommandGroups.Simulation, prefixMatch: true, audit: true,
handler: context => RunSimulationAsync(deps, new SimulationRequest { HasMap = true, MaxRespawnTimesMix = 0 }, context)),
"sim-mix" => new DelegateCommand(
key: "sim-mix", name: "混战模拟", aliases: ["混战", "simmix"], usage: "/混战模拟 [复活次数] [p2]",
description: "个人混战模拟", group: CommandGroups.Simulation, prefixMatch: true, audit: true,
handler: context =>
{
SimulationRequest request = new()
{
MaxRespawnTimesMix = context.TryInt(0, out int times) ? times : 1
};
return RunSimulationAsync(deps, request, context);
}),
"sim" => new DelegateCommand(
key: "sim", name: "FunGame模拟", aliases: ["模拟", "sim"], usage: "/FunGame模拟 [p2]",
description: "无复活混战模拟", group: CommandGroups.Simulation, prefixMatch: true, audit: true,
handler: context => RunSimulationAsync(deps, new SimulationRequest { MaxRespawnTimesMix = 0 }, context)),
_ => throw new ArgumentOutOfRangeException(nameof(key), key, "未注册的指令键。")
};
private static async Task<BotReply> RunSimulationAsync(
CommandDependencies deps, SimulationRequest request, CommandContext context)
{
// S9:把触发者写入 simulation_runs.user_id,便于按用户复盘;
// userId=0 的匿名 / 第三方请求留空。
request.UserId = context.UserId > 0 ? context.UserId : null;
SimulationResult? result = await deps.Simulations.RunAsync(request, context.CancellationToken);
if (result is null)
{
return CommandReplies.Error("已有模拟正在运行", "没有启动新的模拟", "请等待上一次模拟结束后重试", "/上次的日志");
}
deps.Logger.LogInformation("模拟完成:Seed={Seed}, Duration={Duration}", result.Seed, result.Duration);
if (context.UserId > 0 && deps.Players is not null)
{
await deps.Players.RecordSimulationAsync(context.UserId, context.CancellationToken);
}
return CommandReplies.CodePage($"🎲 模拟结果 · 种子 {result.Seed}", result.Messages,
context.Page, $"/{context.Verb}");
}
private static async Task<BotReply> StatsAsync(
CommandDependencies deps, bool team, string title, CommandContext context)
{
if (!context.TryInt(0, out int id))
{
return CommandReplies.Error("缺少或无效的角色编号", "没有执行统计查询",
"用法:/查数据 <编号> 或 /查团队数据 <编号>", team ? "/查团队数据 1" : "/查数据 1");
}
string result = await deps.Queries.GetStatsAsync(id, team, context.CancellationToken);
return Found(title, result, team ? "未找到角色团队统计" : "未找到角色统计", context,
team ? "/查团队数据 1" : "/查数据 1");
}
private static async Task<BotReply> RankingAsync(
CommandDependencies deps, bool team, bool byRating, string title, CommandContext context)
{
List<string> ranking = await deps.Queries.GetRankingAsync(team, byRating, context.CancellationToken);
if (ranking.Count == 0)
{
return CommandReplies.Error("暂无统计数据", "没有生成排行", "先运行一次模拟再查询", "/FunGame模拟");
}
string text = string.Join("\r\n\r\n", ranking);
return text.Length > QQMarkdown.DefaultMaxLength - 300
? CommandReplies.Paginated(title, text, context.Page, $"/{context.Verb}")
: CommandReplies.Detail(title, text, actions: ["/帮助"]);
}
private static BotReply Found(
string title, string? result, string fallback, CommandContext context, params string[] actions)
{
if (string.IsNullOrWhiteSpace(result))
{
return CommandReplies.Error(fallback, "查询没有返回内容",
"检查参数后重试,或输入 /帮助 查看用法", actions.FirstOrDefault() ?? "/帮助");
}
// 翻页命令保留原参数,例如 /查技能 123 p2,否则第二页会丢查询目标。
string command = $"/{context.Verb} {context.ArgumentText}".TrimEnd();
return result.Length > QQMarkdown.DefaultMaxLength - 300
? CommandReplies.Paginated(title, result, context.Page, command)
: CommandReplies.Detail(title, result, actions: actions.Length == 0 ? ["/帮助"] : actions);
}
// ---- P1 指令辅助 ----
/// <summary>@编号 / 纯数字都接受,统一转成 1-based 序号;无效返回 0 由仓储给出错误提示。</summary>
private static int RefIndex(CommandContext context, int position = 0)
{
if (position >= context.Args.Count) return 0;
string token = context.Args[position];
if (token.StartsWith('@')) token = token[1..];
return int.TryParse(token, out int value) && value > 0 ? value : 0;
}
/// <summary>x2 / 2 都表示数量,缺省用 fallback。</summary>
private static int Quantity(CommandContext context, int position, int fallback)
{
if (position >= context.Args.Count) return fallback;
string token = context.Args[position];
if (token.Length > 1 && (token[0] == 'x' || token[0] == 'X')) token = token[1..];
return int.TryParse(token, out int value) && value > 0 ? value : fallback;
}
private static BotReply NoIdentity()
=> CommandReplies.Error("身份尚未就绪", "没有读写任何存档",
"请通过 QQ 消息触发注册,或稍后重试", "/帮助");
private static async Task<BotReply> StatusAsync(CommandDependencies deps, CommandContext context)
{
PlayerSnapshot? snapshot = await deps.Players.GetSnapshotAsync(context.UserId, context.CancellationToken);
if (snapshot is null) return NoIdentity();
return CommandReplies.Compose("📍 铎京 · 旅人档案",
$"Lv.{snapshot.Level} 金币 {snapshot.Credits} 钻石 {snapshot.Diamonds} 经验 {snapshot.Exp}",
[
"潮湿的石板路延伸到雾里,铁匠铺的锤声隔着两条街传来。",
"",
$"- 主战角色:{snapshot.MainCharacter ?? "(无)"} 角色 {snapshot.CharacterCount} 名",
$"- 背包 {snapshot.ItemCount} 格 小队 {snapshot.SquadCount}/3 人 练级中 {snapshot.PendingTrainings} 场",
$"- 连续签到 {snapshot.SignInStreak} 天 最近签到:{(string.IsNullOrEmpty(snapshot.SignedOn) ? "尚未" : snapshot.SignedOn)}"
],
["/签到", "/每日任务", "/背包", "/我的角色", "/抽卡"]);
}
private static async Task<BotReply> LookAsync(CommandDependencies deps, CommandContext context)
{
PlayerSnapshot? snapshot = await deps.Players.GetSnapshotAsync(context.UserId, context.CancellationToken);
if (snapshot is null) return NoIdentity();
return CommandReplies.Compose("📍 铎京 · 中央广场",
$"Lv.{snapshot.Level} · 金币 {snapshot.Credits} · 钻石 {snapshot.Diamonds}",
[
"雾气贴着石板路,北面的铁匠铺还亮着炉火。",
"",
"- 后勤部 @1 领取补给(/签到 · /每日任务)",
"- 抽卡屋 @2 碰碰手气(/抽卡 · /十连抽卡)",
"- 训练场 @3 锻炼角色(/练级 @1 · /收取练级)",
"- 仓库  @4 整理背包(/背包)",
"- 补给站 @5 /商店 · /购买 @1",
"- 交易摊 @6 /市场 · /上架 @1 200",
"- 锻造炉 @7 /锻造 @1 · /收取锻造",
"",
"补给站和交易摊已经开张,铁匠的炉火也重新烧起来了。"
],
["/签到", "/每日任务", "/商店", "/市场", "/背包"]);
}
private static async Task<BotReply> QuestsAsync(CommandDependencies deps, CommandContext context)
{
IReadOnlyList<QuestEntry> quests = await deps.Players.GetQuestsAsync(
context.UserId, context.CancellationToken);
List<string> lines = quests.Select(quest =>
$"- @{quest.Index} {quest.Name} {quest.Progress}/{quest.Target} {QuestStatus(quest.Status)}").ToList();
lines.Add($"- 完成后 /领奖 @编号(金币 +{GameplayRules.QuestRewardCredits} / 钻石 +{GameplayRules.QuestRewardDiamonds})");
return CommandReplies.ListPage("📋 每日任务", GameplayRules.Today(), lines, context.Page,
"/每日任务", ["/签到", "/抽卡", "/FunGame模拟", "/状态"]);
}
private static string QuestStatus(int status) => status switch
{
1 => "✅ 可领取",
2 => "已领取",
_ => "进行中"
};
private static async Task<BotReply> BagAsync(CommandDependencies deps, CommandContext context)
{
IReadOnlyList<BagEntry> items = await deps.Players.GetBagAsync(context.UserId, context.CancellationToken);
List<string> lines = items.Select(item =>
$"- @{item.Index} {GameplayRules.QualityName(item.Quality)} · {item.Name} ×{item.Quantity}"
+ (item.Locked ? " 🔒" : "") + (item.Equipped ? " ⚔️" : "") + (item.Bound ? " 绑定" : "")).ToList();
if (lines.Count == 0) lines.Add("- 背包空空如也,先 /抽卡 或 /签到");
lines.Add("- /使用 @编号 [x数量] · /分解 @编号 · /锁定 @编号 · /装备 @编号");
return CommandReplies.ListPage("🎒 背包", $"{items.Count} 格", lines, context.Page,
"/背包", ["/抽卡", "/状态"]);
}
private static async Task<BotReply> CharactersAsync(CommandDependencies deps, CommandContext context)
{
IReadOnlyList<CharacterEntry> characters = await deps.Players.GetCharactersAsync(
context.UserId, context.CancellationToken);
List<string> lines = characters.Select(character =>
$"- @{character.Index} {character.Name} Lv.{character.Level} / 上限 {GameplayRules.LevelCap(character.BreakLevel)}"
+ $" 突破 {character.BreakLevel} 阶 装备 {character.EquipmentCount} 件"
+ (character.IsMain ? " ⭐主战" : "")).ToList();
if (lines.Count == 0) lines.Add("- 还没有角色,输入 /注册 领取初始角色");
lines.Add("- /设主战 @编号 · /升级 @编号 · /突破 @编号 · /练级 @编号 [分钟]");
return CommandReplies.ListPage("👤 我的角色", $"{characters.Count} 名", lines, context.Page,
"/我的角色", ["/状态", "/背包"]);
}
// ---- P2 指令辅助 ----
private static long Price(CommandContext context, int position = 1)
=> position < context.Args.Count && long.TryParse(context.Args[position], out long value)
? value : 0; // 0 会被仓储的价格范围校验拦下并给出三段式提示
private static async Task<BotReply> ShopAsync(CommandDependencies deps, CommandContext context)
{
IReadOnlyList<StoreEntry> goods = await deps.Economy.GetStoreAsync(
context.UserId, context.CancellationToken);
List<string> lines = goods.Select(good =>
$"- @{good.Index} {good.Name} {good.Price} 金币 库存 {(good.Stock < 0 ? "无限" : good.Stock.ToString(CultureInfo.InvariantCulture))}").ToList();
lines.Add("- /购买 @编号 [x数量] · 同名物品会自动堆叠");
return CommandReplies.ListPage("🏪 铎京补给站", $"{goods.Count} 种商品", lines,
context.Page, "/商店", ["/背包", "/状态"]);
}
private static async Task<BotReply> MarketAsync(CommandDependencies deps, CommandContext context)
{
IReadOnlyList<MarketEntry> listings = await deps.Economy.GetMarketAsync(
context.UserId, context.CancellationToken);
List<string> lines = listings.Select(listing =>
$"- @{listing.Index} {GameplayRules.QualityName(listing.Quality)} · {listing.ItemName}"
+ $" {listing.Price} 金币 卖家 {listing.SellerHandle}{(listing.IsMine ? "(我的)" : "")}").ToList();
if (lines.Count == 0) lines.Add("- 市场暂时空着,用 /上架 @编号 <价格> 挂出第一件物品");
lines.Add("- /上架 @编号 <价格> · /购买市场 @编号 · /下架 @编号");
return CommandReplies.ListPage("🏷️ 旅人市场", $"{listings.Count} 件在售", lines,
context.Page, "/市场", ["/背包", "/状态"]);
}
private static async Task<BotReply> OffersAsync(CommandDependencies deps, CommandContext context)
{
IReadOnlyList<OfferEntry> offers = await deps.Economy.GetOffersAsync(
context.UserId, context.CancellationToken);
List<string> lines = offers.Select(offer =>
$"- @{offer.Index} {offer.ItemName} {offer.Price} 金币"
+ $" 发起 {offer.SellerHandle}{(offer.IsMine ? "(我的)" : "")}").ToList();
if (lines.Count == 0) lines.Add("- 暂无报价单,用 /报价 @编号 <价格> 发布");
lines.Add("- /报价 @编号 <价格> · /接受报价 @编号 · /撤回报价 @编号");
return CommandReplies.ListPage("📝 公开报价", $"{offers.Count} 份报价", lines,
context.Page, "/报价列表", ["/市场", "/背包"]);
}
private static async Task<BotReply> RankAsync(CommandDependencies deps, CommandContext context)
{
string board = context.FirstArgument ?? "credits";
IReadOnlyList<RankEntry> ranks = await deps.Economy.GetRankingAsync(
board, context.CancellationToken);
List<string> lines = ranks.Select(rank =>
$"- @{rank.Index} {rank.Handle} {rank.Value}").ToList();
if (lines.Count == 0) lines.Add("- 榜单还没有数据,先去 /决斗 或 /Boss 攒点战绩");
return CommandReplies.ListPage("🏆 排行榜", GameplayRules.RankingBoardName(board), lines,
context.Page, $"/排行榜 {board}", ["/决斗", "/Boss", "/状态"]);
}
}
+123
View File
@@ -0,0 +1,123 @@
using System.Security.Claims;
using OshimaBot.Gameplay;
using OshimaBot.Messaging;
using OshimaBot.Models;
using OshimaBot.Security;
using OshimaBot.Services;
namespace OshimaBot.Commands;
public static class CommandGroups
{
public const string System = "系统";
public const string Query = "查询";
public const string Stats = "统计";
public const string Simulation = "战斗模拟";
public const string Player = "旅人存档";
public const string Economy = "经济战斗";
public const string Legacy = "版本状态";
}
/// <summary>命令工厂所需的全部依赖,全部由 DI 显式传入,不做反射扫描。</summary>
public sealed record CommandDependencies(
FunGameQueryService Queries,
FunGameSimulationService Simulations,
IBindCodeService BindCodes,
IUserSessionService Sessions,
IPlayerService Players,
IEconomyService Economy,
ILogger Logger);
public interface ICommand
{
string Key { get; }
string Name { get; }
IReadOnlyList<string> Aliases { get; }
string Usage { get; }
string Description { get; }
string Group { get; }
BotRole RequiredRole { get; }
/// <summary>兼容旧版「前缀 + 参数」写法(如「查角色1」「团队调试模拟」)。</summary>
bool PrefixMatch { get; }
/// <summary>0 表示不启用冷却。</summary>
int CooldownMilliseconds { get; }
/// <summary>是否写入 audit_logs(写操作/重操作才开)。</summary>
bool Audit { get; }
Task<BotReply> ExecuteAsync(CommandContext context);
}
/// <summary>显式注册的委托命令:每个命令的元数据与执行逻辑都在 CommandCatalog 的 switch 里可见。</summary>
public sealed class DelegateCommand(
string key,
string name,
string[] aliases,
string usage,
string description,
string group,
Func<CommandContext, Task<BotReply>> handler,
bool prefixMatch = false,
BotRole requiredRole = BotRole.Player,
int cooldownMilliseconds = 0,
bool audit = false) : ICommand
{
public string Key { get; } = key;
public string Name { get; } = name;
public IReadOnlyList<string> Aliases { get; } = aliases;
public string Usage { get; } = usage;
public string Description { get; } = description;
public string Group { get; } = group;
public bool PrefixMatch { get; } = prefixMatch;
public BotRole RequiredRole { get; } = requiredRole;
public int CooldownMilliseconds { get; } = cooldownMilliseconds;
public bool Audit { get; } = audit;
public Task<BotReply> ExecuteAsync(CommandContext context) => handler(context);
}
public sealed record CommandMatch(ICommand Command, IReadOnlyList<string> Args, int Page);
public sealed class CommandContext
{
public required IBotMessage Message { get; init; }
public required string Raw { get; init; }
public required string Verb { get; init; }
public required IReadOnlyList<string> Args { get; init; }
public required int Page { get; init; }
public required CommandRegistry Registry { get; init; }
public required CommandDependencies Dependencies { get; init; }
public required OtherData Data { get; init; }
public required CancellationToken CancellationToken { get; init; }
public long UserId => Message.FunGameUID;
public ClaimsPrincipal? Principal => Message.Principal;
public bool IsGroup => Message.IsGroup;
public string ArgumentText => string.Join(' ', Args);
public string? FirstArgument => Args.Count > 0 ? Args[0] : null;
public bool HasFlag(string flag) => Args.Contains(flag, StringComparer.OrdinalIgnoreCase);
public bool TryInt(int index, out int value)
{
value = 0;
return index < Args.Count && int.TryParse(Args[index], out value);
}
/// <summary>@编号:把列表序号解析成用户不必记忆的内部 ID。</summary>
public string? Reference(int index = 0)
=> index < Args.Count && Args[index].StartsWith('@') ? Args[index][1..] : null;
/// <summary>--seed=123 / --yes 这类选项。</summary>
public string? Option(string name)
{
string prefix = $"--{name}=";
string? raw = Args.FirstOrDefault(arg => arg.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));
return raw is null ? null : raw[prefix.Length..];
}
public bool HasRole(BotRole required)
=> Principal?.FindAll(ClaimTypes.Role)
.Any(claim => Enum.TryParse(claim.Value, out BotRole role) && role >= required) ?? false;
}
+97
View File
@@ -0,0 +1,97 @@
using System.Globalization;
namespace OshimaBot.Commands;
/// <summary>
/// 命令索引:精确动词 + 旧版前缀双轨匹配。别名按长度降序,保证「查团队数据」优先于「查数据」。
/// 所有命令都来自 CommandCatalog 的显式 switch 工厂,不做程序集反射扫描。
/// </summary>
public sealed class CommandRegistry
{
private readonly Dictionary<string, ICommand> _exact = new(StringComparer.OrdinalIgnoreCase);
private readonly List<(string Alias, ICommand Command)> _prefixes = [];
public IReadOnlyList<ICommand> All { get; }
public CommandRegistry(IEnumerable<ICommand> commands)
{
All = [.. commands];
foreach (ICommand command in All)
{
foreach (string alias in new[] { command.Name }.Concat(command.Aliases))
{
if (!_exact.TryAdd(alias, command))
{
throw new InvalidOperationException($"指令别名重复注册:{alias}({command.Key})");
}
if (command.PrefixMatch) _prefixes.Add((alias, command));
}
}
_prefixes.Sort((left, right) => right.Alias.Length.CompareTo(left.Alias.Length));
}
public ICommand? FindByKey(string key)
=> All.FirstOrDefault(command => string.Equals(command.Key, key, StringComparison.OrdinalIgnoreCase));
public CommandMatch? Resolve(string? raw)
{
string text = Normalize(raw);
if (text.Length == 0) return null;
string[] tokens = text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
ICommand? command = null;
string[] arguments = [];
if (_exact.TryGetValue(tokens[0], out ICommand? exact))
{
command = exact;
arguments = tokens[1..];
}
else
{
foreach ((string alias, ICommand candidate) in _prefixes)
{
if (!text.StartsWith(alias, StringComparison.OrdinalIgnoreCase)) continue;
command = candidate;
string remainder = text[alias.Length..].Trim();
arguments = remainder.Length == 0
? []
: remainder.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
break;
}
}
if (command is null) return null;
return new CommandMatch(command, StripPageTokens(arguments), ExtractPage(arguments));
}
private static string Normalize(string? raw)
{
if (string.IsNullOrWhiteSpace(raw)) return "";
string text = raw.Trim();
while (text.StartsWith('/')) text = text[1..].TrimStart();
return text.Trim();
}
private static IReadOnlyList<string> StripPageTokens(string[] arguments)
=> arguments.Where(argument => !IsPageToken(argument)).ToArray();
private static int ExtractPage(IEnumerable<string> arguments)
{
foreach (string argument in arguments)
{
if (IsPageToken(argument)
&& int.TryParse(argument.AsSpan(1), NumberStyles.None, CultureInfo.InvariantCulture, out int page)
&& page > 0)
{
return page;
}
}
return 1;
}
private static bool IsPageToken(string value)
=> value.Length > 1
&& (value[0] == 'p' || value[0] == 'P')
&& value.Skip(1).All(char.IsAsciiDigit);
}
+186
View File
@@ -0,0 +1,186 @@
using System.Text;
using OshimaBot.Gameplay;
using OshimaBot.Messaging;
using OshimaBot.Models;
namespace OshimaBot.Commands;
/// <summary>
/// MUD 回复构造:4 段式(场景 → 状态 → 列表 → 可点击行动)、错误三段式、长文本分页。
/// 官方不支持表格,因此列表 + @编号 + CmdInput / 按钮是排版与交互主力。
/// </summary>
public static class CommandReplies
{
public const int HelpPageSize = 6;
public static BotReply Compose(
string title,
string? status = null,
IEnumerable<string>? lines = null,
IEnumerable<string>? actions = null,
KeyboardMessage? keyboard = null)
{
StringBuilder builder = new();
builder.AppendLine(QQMarkdown.Heading(title, 2));
if (!string.IsNullOrWhiteSpace(status))
{
builder.AppendLine(QQMarkdown.Bold(status)).AppendLine();
}
if (lines is not null)
{
foreach (string line in lines) builder.AppendLine(line);
}
if (actions is not null)
{
builder.AppendLine();
foreach (string action in actions) builder.AppendLine(QQCmdTag.CmdInput(action));
}
return BotReply.FromMarkdown(builder.ToString().TrimEnd(), keyboard);
}
/// <summary>错误回复固定三段:发生了什么 / 没有发生什么 / 下一步怎么做。</summary>
public static BotReply Error(string what, string notHappened, string next, string? action = null)
=> Compose("⚠️ 指令未能完成", null,
[
QQMarkdown.Escape(what),
"",
$"**没有发生**:{QQMarkdown.Escape(notHappened)}",
$"**下一步**:{QQMarkdown.Escape(next)}"
],
action is null ? null : [action]);
/// <summary>查询类结果:标题 + 状态 + 代码块正文 + 行动指令。</summary>
public static BotReply Detail(string title, string body, string? status = null, IEnumerable<string>? actions = null)
=> Compose(title, status, ["```", body.Replace("```", "``", StringComparison.Ordinal), "```"], actions);
public static string Empty(string fallback) => fallback;
/// <summary>纯文本或结果为空时的兜底(保持旧版返回语义)。</summary>
public static BotReply TextOr(string result, string fallback)
=> string.IsNullOrWhiteSpace(result) ? BotReply.FromText(fallback) : BotReply.FromText(result);
/// <summary>把模拟日志按旧规则裁剪后分页,页数与翻页按钮同时给出。</summary>
public static BotReply CodePage(string title, IReadOnlyCollection<string> messages, int page, string command)
{
if (messages.Count == 0) return BotReply.FromText("暂无记录,请先运行一次模拟。");
List<string> selected = [.. messages];
if (selected.Count > 30)
{
selected = [.. selected[..15], $"……已省略 {messages.Count - 30} 段日志……", .. selected[^15..]];
}
StringBuilder body = new();
foreach (string message in selected)
{
if (body.Length > 48_000)
{
body.AppendLine("……日志过长,后续内容已省略……");
break;
}
body.AppendLine(message);
}
return Paginated(title, body.ToString(), page, command);
}
/// <summary>按 3000 字符切分,附 pN/M 与翻页指令/按钮。</summary>
public static BotReply Paginated(string title, string body, int page, string command, string? status = null)
{
// 预留标题/状态/行动指令的字符,避免整条 content 超出保守上限。
IReadOnlyList<string> parts = QQMarkdown.Split(body, QQMarkdown.DefaultMaxLength - 300);
int total = Math.Max(1, parts.Count);
int current = Math.Clamp(page, 1, total);
string pageStatus = $"第 {current}/{total} 页{(string.IsNullOrWhiteSpace(status) ? "" : " · " + status)}";
List<string> lines = ["```", parts[current - 1].Replace("```", "``", StringComparison.Ordinal), "```"];
List<string> actions = [];
if (current > 1) actions.Add($"{command} p{current - 1}");
if (current < total) actions.Add($"{command} p{current + 1}");
KeyboardMessage? keyboard = null;
if (total > 1)
{
keyboard = new KeyboardBuilder().AddPagination(command, current, total).Build();
}
return Compose(title, pageStatus, lines, actions, keyboard);
}
/// <summary>玩法仓储结果统一渲染:成功走 4 段式,失败走错误三段式。</summary>
public static BotReply FromResult(ActionResult result)
=> result.Ok
? Compose(result.Title, result.Status, result.Lines, result.Actions)
: Error(result.Title, result.Status,
result.Lines.FirstOrDefault() ?? "稍后重试,或输入 /帮助 查看用法",
result.Actions.FirstOrDefault());
/// <summary>Markdown 列表分页(不包代码块,保留 - / @编号 的排版),附翻页指令与按钮。</summary>
public static BotReply ListPage(
string title, string status, IReadOnlyList<string> lines, int page, string command,
IEnumerable<string>? extraActions = null)
{
List<List<string>> chunks = [];
List<string> current = [];
int length = 0;
foreach (string line in lines)
{
if (current.Count > 0 && length + line.Length + 1 > QQMarkdown.DefaultMaxLength - 400)
{
chunks.Add(current);
current = [];
length = 0;
}
current.Add(line);
length += line.Length + 1;
}
if (current.Count > 0) chunks.Add(current);
int total = Math.Max(1, chunks.Count);
int currentPage = Math.Clamp(page, 1, total);
List<string> actions = [];
if (currentPage > 1) actions.Add($"{command} p{currentPage - 1}");
if (currentPage < total) actions.Add($"{command} p{currentPage + 1}");
if (extraActions is not null) actions.AddRange(extraActions);
KeyboardMessage? keyboard = total > 1
? new KeyboardBuilder().AddPagination(command, currentPage, total).Build()
: null;
return Compose(title, $"{status} · 第 {currentPage}/{total} 页",
chunks.Count == 0 ? ["- (空)"] : chunks[currentPage - 1], actions, keyboard);
}
/// <summary>帮助完全由注册表生成,保证「文档与实现同源」。</summary>
public static BotReply Help(CommandRegistry registry, int page)
{
IReadOnlyList<ICommand> commands = registry.All;
int total = Math.Max(1, (commands.Count + HelpPageSize - 1) / HelpPageSize);
int current = Math.Clamp(page, 1, total);
List<string> lines = [];
string? lastGroup = null;
foreach (ICommand command in commands.Skip((current - 1) * HelpPageSize).Take(HelpPageSize))
{
if (lastGroup != command.Group)
{
lines.Add(QQMarkdown.Bold($"【{command.Group}】"));
lastGroup = command.Group;
}
lines.Add($"- {QQMarkdown.Bold(command.Usage)} {command.Description}");
}
List<string> actions = ["/战斗帮助", "/取消"];
if (total > 1) actions.Insert(0, $"/帮助 p{(current < total ? current + 1 : 1)}");
KeyboardBuilder keyboardBuilder = new KeyboardBuilder()
.AddButtons(5,
KeyboardBuilder.CmdButton("帮助", "/帮助"),
KeyboardBuilder.CmdButton("战斗帮助", "/战斗帮助"),
KeyboardBuilder.CmdButton("开始时间", "/查询服务器启动时间"),
KeyboardBuilder.CmdButton("查角色", "/查角色 1"),
KeyboardBuilder.CmdButton("模拟", "/FunGame模拟"));
if (total > 1) keyboardBuilder.AddPagination("/帮助", current, total);
return Compose("📖 OshimaBot 指令", $"第 {current}/{total} 页 · 共 {commands.Count} 条指令 · / 可省略",
lines,
actions,
keyboardBuilder.Build());
}
}
+107
View File
@@ -0,0 +1,107 @@
using Microsoft.Extensions.Caching.Memory;
using OshimaBot.Data;
using OshimaBot.Data.Entities;
using OshimaBot.Models;
using OshimaBot.Security;
namespace OshimaBot.Commands;
/// <summary>
/// 全局指令中间件:解析 → 权限 → 冷却 → 会话游标 → 执行 → 审计 → 异常兜底。
/// 只负责产出 BotReply,发送仍由 scoped 的 MessageSender 完成。
/// </summary>
public sealed class CommandRouter(
CommandRegistry registry,
CommandDependencies dependencies,
IServiceScopeFactory scopeFactory,
IMemoryCache cooldown,
ILogger<CommandRouter> logger)
{
public async Task<BotReply?> RouteAsync(IBotMessage message, OtherData data, CancellationToken cancellationToken = default)
{
string raw = message.Detail?.Trim() ?? "";
if (raw.Length == 0) return null;
CommandMatch? match = registry.Resolve(raw);
if (match is null)
{
logger.LogDebug("未识别的指令:{Command}", raw);
return null;
}
CommandContext context = new()
{
Message = message,
Raw = raw,
Verb = match.Command.Name,
Args = match.Args,
Page = match.Page,
Registry = registry,
Dependencies = dependencies,
Data = data,
CancellationToken = cancellationToken
};
// Player 是默认最低角色:Principal 为空(第三方/用户库暂不可用)时仍允许 P0 查询。
if (match.Command.RequiredRole > BotRole.Player && !context.HasRole(match.Command.RequiredRole))
{
return CommandReplies.Error("权限不足", "指令没有执行", $"需要 {match.Command.RequiredRole} 及以上角色", "/帮助");
}
if (match.Command.CooldownMilliseconds > 0 && !TryEnterCooldown(context, match.Command))
{
return CommandReplies.Error("操作太快", "指令没有执行", "稍等片刻再试", "/帮助");
}
try
{
BotReply reply = await match.Command.ExecuteAsync(context);
if (match.Page > 1 && context.UserId > 0)
{
await dependencies.Sessions.SetPageCursorAsync(
context.UserId, $"{match.Command.Key}:p{match.Page}", cancellationToken);
}
if (match.Command.Audit) await WriteAuditAsync(context, match.Command, cancellationToken);
return reply;
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (Exception exception)
{
logger.LogError(exception, "指令执行失败:Key={Key}, Raw={Raw}", match.Command.Key, raw);
return CommandReplies.Error("指令执行时出现异常", "没有产生结果", "稍后重试,或输入 /帮助 查看用法", "/帮助");
}
}
private bool TryEnterCooldown(CommandContext context, ICommand command)
{
string key = $"OshimaBot:Cooldown:{context.UserId}:{command.Key}";
if (cooldown.TryGetValue(key, out _)) return false;
cooldown.Set(key, true, TimeSpan.FromMilliseconds(command.CooldownMilliseconds));
return true;
}
private async Task WriteAuditAsync(CommandContext context, ICommand command, CancellationToken cancellationToken)
{
try
{
using IServiceScope scope = scopeFactory.CreateScope();
BotDbContext db = scope.ServiceProvider.GetRequiredService<BotDbContext>();
db.AuditLogs.Add(new AuditLog
{
ActorUserId = context.UserId > 0 ? context.UserId : null,
Action = $"command.{command.Key}",
Target = context.Raw.Length > 200 ? context.Raw[..200] : context.Raw,
PayloadJson = "{}",
CreatedAtUtc = DateTime.UtcNow
});
await db.SaveChangesAsync(cancellationToken);
}
catch (Exception exception)
{
logger.LogWarning(exception, "指令审计写入失败:Key={Key}", command.Key);
}
}
}
+84
View File
@@ -0,0 +1,84 @@
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using OshimaBot.Data;
using OshimaBot.Data.Entities;
namespace OshimaBot.Commands;
public interface IUserSessionService
{
Task<UserSessionState?> GetAsync(long userId, CancellationToken cancellationToken = default);
Task SetPendingAsync(long userId, string action, string payloadJson, TimeSpan ttl, CancellationToken cancellationToken = default);
Task ClearPendingAsync(long userId, CancellationToken cancellationToken = default);
Task SetPageCursorAsync(long userId, string cursor, CancellationToken cancellationToken = default);
}
public sealed record UserSessionState(
string CurrentRegion, string? PendingAction, string PageCursor, DateTime? PendingExpiresAtUtc);
/// <summary>会话状态入库,替代旧版内存字典 + SemaphoreSlim;userId=0 的匿名请求直接跳过。</summary>
public sealed class UserSessionService(IServiceScopeFactory scopeFactory) : IUserSessionService
{
public async Task<UserSessionState?> GetAsync(long userId, CancellationToken cancellationToken = default)
{
if (userId <= 0) return null;
using IServiceScope scope = scopeFactory.CreateScope();
BotDbContext db = scope.ServiceProvider.GetRequiredService<BotDbContext>();
UserSession? row = await db.UserSessions.AsNoTracking()
.FirstOrDefaultAsync(x => x.UserId == userId, cancellationToken);
if (row is null) return null;
bool pendingValid = row.PendingExpiresAtUtc is null || row.PendingExpiresAtUtc > DateTime.UtcNow;
return new UserSessionState(row.CurrentRegion,
pendingValid ? row.PendingActionJson : null, row.PageCursor, row.PendingExpiresAtUtc);
}
public async Task SetPendingAsync(long userId, string action, string payloadJson, TimeSpan ttl, CancellationToken cancellationToken = default)
{
if (userId <= 0) return;
using IServiceScope scope = scopeFactory.CreateScope();
BotDbContext db = scope.ServiceProvider.GetRequiredService<BotDbContext>();
UserSession? row = await db.UserSessions.FirstOrDefaultAsync(x => x.UserId == userId, cancellationToken);
if (row is null)
{
row = new UserSession { UserId = userId };
db.UserSessions.Add(row);
}
row.PendingActionJson = JsonSerializer.Serialize(new { action, payload = payloadJson });
row.PendingExpiresAtUtc = DateTime.UtcNow + ttl;
row.UpdatedAtUtc = DateTime.UtcNow;
await db.SaveChangesAsync(cancellationToken);
}
public async Task ClearPendingAsync(long userId, CancellationToken cancellationToken = default)
{
if (userId <= 0) return;
using IServiceScope scope = scopeFactory.CreateScope();
BotDbContext db = scope.ServiceProvider.GetRequiredService<BotDbContext>();
await db.UserSessions.Where(x => x.UserId == userId)
.ExecuteUpdateAsync(setters => setters
.SetProperty(x => x.PendingActionJson, "")
.SetProperty(x => x.PendingExpiresAtUtc, (DateTime?)null)
.SetProperty(x => x.UpdatedAtUtc, DateTime.UtcNow), cancellationToken);
}
public async Task SetPageCursorAsync(long userId, string cursor, CancellationToken cancellationToken = default)
{
if (userId <= 0) return;
using IServiceScope scope = scopeFactory.CreateScope();
BotDbContext db = scope.ServiceProvider.GetRequiredService<BotDbContext>();
UserSession? row = await db.UserSessions.FirstOrDefaultAsync(x => x.UserId == userId, cancellationToken);
if (row is null)
{
db.UserSessions.Add(new UserSession
{
UserId = userId, PageCursor = cursor, UpdatedAtUtc = DateTime.UtcNow
});
}
else
{
row.PageCursor = cursor;
row.UpdatedAtUtc = DateTime.UtcNow;
}
await db.SaveChangesAsync(cancellationToken);
}
}
+38 -2
View File
@@ -1,3 +1,4 @@
using System.Security.Claims;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
@@ -12,7 +13,8 @@ namespace OshimaBot.Controllers
public sealed class QQBotController(
IOptions<QQBotOptions> options,
ILogger<QQBotController> logger,
IQQEventDispatcher dispatcher) : ControllerBase
IQQEventDispatcher dispatcher,
IBindCodeService bindCodes) : ControllerBase
{
private readonly QQBotOptions _options = options.Value;
@@ -85,11 +87,43 @@ namespace OshimaBot.Controllers
{
if (message is null) return Ok("");
// 第三方消息自报的 openid 只用于回显,身份一律以 ApiKey 关联的 ClaimsPrincipal 为准。
message.FunGameUID = CurrentUserId();
message.Principal = HttpContext.User;
OtherData data = new() { RequestUrl = $"{Request.Scheme}://{Request.Host}{Request.PathBase}" };
bool handled = await rainBot.Handler(message, data, cancellationToken);
return Ok(!handled || message.IsCompleted ? message.Result : "");
}
private long CurrentUserId()
=> long.TryParse(HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier), out long userId) ? userId : 0;
[RequireApiKey]
[HttpPost("bind")]
public async Task<IActionResult> Bind([FromBody] BindRequest? request, CancellationToken cancellationToken)
{
if (request is null || string.IsNullOrWhiteSpace(request.Code) || string.IsNullOrWhiteSpace(request.OpenId))
{
return BadRequest(new { error = "需要 code 与 openId。" });
}
ExternalIdentity identity = new(
string.IsNullOrWhiteSpace(request.Provider) ? "qq" : request.Provider.Trim(),
request.OpenId.Trim(),
string.IsNullOrWhiteSpace(request.Scene) ? "c2c" : request.Scene.Trim());
BindRedeemResult result = await bindCodes.RedeemAsync(request.Code.Trim(), identity, cancellationToken);
logger.LogInformation("绑定码兑换:Status={Status}, UserId={UserId}, Provider={Provider}",
result.Status, result.UserId, identity.Provider);
return result.Status switch
{
BindRedeemStatus.Success => Ok(new { bound = true, userId = result.UserId }),
BindRedeemStatus.Conflict => Conflict(new { error = result.Reason }),
BindRedeemStatus.InvalidUser => StatusCode(StatusCodes.Status503ServiceUnavailable, new { error = result.Reason }),
_ => BadRequest(new { error = result.Reason })
};
}
[RequireApiKey]
[HttpPost("thirdpartytest")]
public async Task<IActionResult> ThirdPartyTest(
@@ -107,7 +141,9 @@ namespace OshimaBot.Controllers
OpenId = openID,
Detail = msg,
Id = openID,
Timestamp = DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss")
Timestamp = DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss"),
FunGameUID = CurrentUserId(),
Principal = HttpContext.User
};
OtherData data = new() { RequestUrl = $"{Request.Scheme}://{Request.Host}{Request.PathBase}" };
bool handled = await rainBot.Handler(message, data, cancellationToken);
+49 -11
View File
@@ -1,6 +1,9 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using OshimaBot.Data.Entities;
using OshimaBot.Models;
using OshimaBot.Security;
using OshimaBot.Services;
namespace OshimaBot.Data;
@@ -11,21 +14,56 @@ namespace OshimaBot.Data;
public sealed class DatabaseInitializer(
IServiceScopeFactory scopeFactory,
IOptions<DatabaseOptions> options,
IOptions<ServerOptions> serverOptions,
ILogger<DatabaseInitializer> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (!options.Value.ApplyMigrationsOnStartup)
{
logger.LogInformation("已跳过数据库自动迁移(Database:ApplyMigrationsOnStartup=false)。");
return;
}
protected override Task ExecuteAsync(CancellationToken stoppingToken) => InitializeAsync(stoppingToken);
/// <summary>公开以便集成测试直接等待完成(BackgroundService.StartAsync 不会等待 ExecuteAsync)。</summary>
public async Task InitializeAsync(CancellationToken cancellationToken)
{
using IServiceScope scope = scopeFactory.CreateScope();
BotDbContext db = scope.ServiceProvider.GetRequiredService<BotDbContext>();
await db.Database.MigrateAsync(stoppingToken);
await db.Database.ExecuteSqlRawAsync("PRAGMA journal_mode=WAL;", stoppingToken);
await db.Database.ExecuteSqlRawAsync("PRAGMA foreign_keys=ON;", stoppingToken);
logger.LogInformation("数据库迁移完成,已启用 WAL 与外键约束。");
if (options.Value.ApplyMigrationsOnStartup)
{
await db.Database.MigrateAsync(cancellationToken);
await db.Database.ExecuteSqlRawAsync("PRAGMA journal_mode=WAL;", cancellationToken);
await db.Database.ExecuteSqlRawAsync("PRAGMA foreign_keys=ON;", cancellationToken);
logger.LogInformation("数据库迁移完成,已启用 WAL 与外键约束。");
}
else
{
logger.LogInformation("已跳过数据库自动迁移(Database:ApplyMigrationsOnStartup=false)。");
}
// S9:迁移完成后把模拟统计与最近一次日志从数据库恢复到内存工作副本。
// 用 GetService 而非构造函数注入,保证只构建 DbContext 的集成测试也能复用本类。
EfSimulationStatisticsStore? statistics = scope.ServiceProvider.GetService<EfSimulationStatisticsStore>();
if (statistics is not null) await statistics.LoadAsync(cancellationToken);
await SeedBootstrapApiKeyAsync(db, cancellationToken);
}
/// <summary>
/// 兼容旧配置的过渡:若 Server:ApiKey 非空,首次启动时把 SHA-256 摘要写入 api_keys。
/// 认证只查库;写入后应从配置移除明文,后续密钥直接由数据库管理(可吊销/过期/分权)。
/// </summary>
private async Task SeedBootstrapApiKeyAsync(BotDbContext db, CancellationToken cancellationToken)
{
string plain = serverOptions.Value.ApiKey;
if (string.IsNullOrWhiteSpace(plain)) return;
string hash = ApiKeyDefaults.Hash(plain);
if (await db.ApiKeys.AnyAsync(x => x.KeyHash == hash, cancellationToken)) return;
db.ApiKeys.Add(new ApiKey
{
Name = "bootstrap",
KeyHash = hash,
ScopesJson = "[\"thirdparty\",\"bind\"]",
CreatedAtUtc = DateTime.UtcNow
});
await db.SaveChangesAsync(cancellationToken);
logger.LogWarning("已从 Server:ApiKey 引导写入 API Key 摘要;请从配置中移除明文,改用 api_keys 表管理密钥。");
}
}
+624
View File
@@ -0,0 +1,624 @@
using System.Globalization;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using OshimaBot.Data;
using OshimaBot.Data.Entities;
namespace OshimaBot.Gameplay;
public interface IEconomyService
{
Task<IReadOnlyList<StoreEntry>> GetStoreAsync(long userId, CancellationToken cancellationToken = default);
Task<ActionResult> BuyAsync(long userId, int index, int quantity, CancellationToken cancellationToken = default);
Task<IReadOnlyList<MarketEntry>> GetMarketAsync(long userId, CancellationToken cancellationToken = default);
Task<ActionResult> ListOnMarketAsync(long userId, int itemIndex, long price, CancellationToken cancellationToken = default);
Task<ActionResult> DelistAsync(long userId, int index, CancellationToken cancellationToken = default);
Task<ActionResult> BuyMarketAsync(long userId, int index, CancellationToken cancellationToken = default);
Task<IReadOnlyList<OfferEntry>> GetOffersAsync(long userId, CancellationToken cancellationToken = default);
Task<ActionResult> CreateOfferAsync(long userId, int itemIndex, long price, CancellationToken cancellationToken = default);
Task<ActionResult> AcceptOfferAsync(long userId, int index, CancellationToken cancellationToken = default);
Task<ActionResult> CancelOfferAsync(long userId, int index, CancellationToken cancellationToken = default);
Task<ActionResult> ForgeAsync(long userId, int materialIndex, int minutes, CancellationToken cancellationToken = default);
Task<ActionResult> ClaimForgeAsync(long userId, CancellationToken cancellationToken = default);
Task<ActionResult> InstanceAsync(long userId, string difficulty, CancellationToken cancellationToken = default);
Task<ActionResult> ClaimInstanceAsync(long userId, CancellationToken cancellationToken = default);
Task<ActionResult> DuelAsync(long userId, CancellationToken cancellationToken = default);
Task<ActionResult> BossAsync(long userId, CancellationToken cancellationToken = default);
Task<IReadOnlyList<RankEntry>> GetRankingAsync(string board, CancellationToken cancellationToken = default);
}
/// <summary>
/// P2 经济与战斗仓储。所有货币变动(含跨用户买卖)都在同一个 SQLite 事务内完成,
/// 买卖双方各自写一条 ledger;市场上架/报价的物品托管到 EscrowUserId,不出现在任何玩家背包。
/// </summary>
public sealed class EconomyService(IServiceScopeFactory scopeFactory, ILogger<EconomyService> logger) : IEconomyService
{
private const string StoreKey = "system";
private const string PointsKey = "p2_points";
private async Task<T> ReadAsync<T>(
Func<BotDbContext, CancellationToken, Task<T>> body, CancellationToken cancellationToken)
{
using IServiceScope scope = scopeFactory.CreateScope();
BotDbContext db = scope.ServiceProvider.GetRequiredService<BotDbContext>();
return await body(db, cancellationToken);
}
private async Task<ActionResult> MutateAsync(
long userId,
Func<BotDbContext, PlayerState, CancellationToken, Task<ActionResult>> body,
CancellationToken cancellationToken)
{
if (userId <= 0) return PlayerService.NoIdentity;
try
{
using IServiceScope scope = scopeFactory.CreateScope();
BotDbContext db = scope.ServiceProvider.GetRequiredService<BotDbContext>();
await using Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction transaction =
await db.Database.BeginTransactionAsync(cancellationToken);
PlayerState state = await PlayerService.EnsureAsync(db, userId, cancellationToken);
ActionResult result = await body(db, state, cancellationToken);
if (!result.Ok)
{
await transaction.RollbackAsync(cancellationToken);
return result;
}
state.UpdatedAtUtc = DateTime.UtcNow;
await db.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);
return result;
}
catch (DbUpdateConcurrencyException)
{
return ActionResult.Fail("存档正被另一条消息修改", "本次操作已回滚", "稍等一秒后重试", "/状态");
}
catch (Exception exception)
{
logger.LogError(exception, "P2 经济操作失败:UserId={UserId}", userId);
return ActionResult.Fail("操作出现异常", "本次操作已回滚", "稍后重试", "/状态");
}
}
// ---------------- 商店 ----------------
private static async Task<List<StoreGood>> EnsureStoreAsync(BotDbContext db, CancellationToken ct)
{
if (!await db.Stores.AnyAsync(x => x.Key == StoreKey, ct))
{
db.Stores.Add(new Store { Key = StoreKey, Name = "铎京补给站", Kind = "system", ConfigJson = "{}" });
await db.SaveChangesAsync(ct);
}
List<StoreGood> goods = await db.StoreGoods
.Where(x => x.StoreKey == StoreKey).OrderBy(x => x.Id).ToListAsync(ct);
if (goods.Count == 0)
{
foreach ((string name, long price, int stock) in GameplayRules.SeedStoreGoods)
{
db.StoreGoods.Add(new StoreGood
{
StoreKey = StoreKey, ItemCatalogId = name,
PriceCurrency = "credits", Price = price, Stock = stock, Quota = -1
});
}
await db.SaveChangesAsync(ct);
goods = await db.StoreGoods.Where(x => x.StoreKey == StoreKey).OrderBy(x => x.Id).ToListAsync(ct);
}
return goods;
}
public Task<IReadOnlyList<StoreEntry>> GetStoreAsync(long userId, CancellationToken cancellationToken = default)
=> ReadAsync<IReadOnlyList<StoreEntry>>(async (db, ct) =>
{
List<StoreGood> goods = await EnsureStoreAsync(db, ct);
return goods.Select((good, i) => new StoreEntry(
i + 1, good.Id, good.ItemCatalogId, good.Price, good.Stock)).ToArray();
}, cancellationToken);
public Task<ActionResult> BuyAsync(long userId, int index, int quantity, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, state, ct) =>
{
List<StoreGood> goods = await EnsureStoreAsync(db, ct);
if (index <= 0 || index > goods.Count) return NoListing("商品");
StoreGood good = goods[index - 1];
int amount = Math.Clamp(quantity, 1, 10);
if (good.Stock >= 0 && good.Stock < amount)
{
return ActionResult.Fail("库存不足", "没有扣除金币,也没有发放物品",
"减少购买数量或改买其它商品", "/商店");
}
long cost = good.Price * amount;
if (state.Credits < cost)
{
return ActionResult.Fail("金币不足", "没有扣除金币,也没有发放物品",
$"需要 {cost} 金币,当前 {state.Credits}", "/签到");
}
PlayerService.ApplyCurrency(db, state, -cost, "credits", "store_buy", "store_good", good.Id.ToString(CultureInfo.InvariantCulture));
if (good.Stock >= 0) good.Stock -= amount;
int quality = good.Price >= 500 ? 4 : good.Price >= 260 ? 2 : 1;
await PlayerService.AddItemAsync(db, userId, good.ItemCatalogId, quality, amount, ct, "store");
return ActionResult.Success("🛒 购买成功",
$"{good.ItemCatalogId} ×{amount} · 花费 {cost} 金币",
[$"- 当前金币:{state.Credits} 库存:{(good.Stock < 0 ? "无限" : good.Stock.ToString(CultureInfo.InvariantCulture))}",
"- 已写入账本 ledger"], ["/商店", "/背包", "/状态"]);
}, cancellationToken);
// ---------------- 市场 ----------------
private static async Task<List<MarketListing>> ActiveListingsAsync(BotDbContext db, CancellationToken ct)
=> await db.MarketListings.Where(x => x.Status == 0).OrderBy(x => x.Id).ToListAsync(ct);
private static async Task<IReadOnlyList<MarketEntry>> MarketViewAsync(
BotDbContext db, long userId, CancellationToken ct)
{
List<MarketListing> listings = await ActiveListingsAsync(db, ct);
if (listings.Count == 0) return [];
List<long> ids = listings.Select(x => x.ItemInstanceId).ToList();
Dictionary<long, ItemInstance> items = await db.ItemInstances.AsNoTracking()
.Where(x => ids.Contains(x.Id)).ToDictionaryAsync(x => x.Id, ct);
List<long> sellers = listings.Select(x => x.SellerUserId).Distinct().ToList();
Dictionary<long, string> handles = await db.Users.AsNoTracking()
.Where(x => sellers.Contains(x.Id)).ToDictionaryAsync(x => x.Id, x => x.Handle, ct);
return listings.Select((listing, i) =>
{
items.TryGetValue(listing.ItemInstanceId, out ItemInstance? item);
return new MarketEntry(i + 1, listing.Id,
item is null ? "未知物品" : PlayerService.ReadName(item), item?.Quality ?? 1,
listing.Price, listing.Fee,
handles.GetValueOrDefault(listing.SellerUserId, $"旅人{listing.SellerUserId}"),
listing.SellerUserId == userId);
}).ToArray();
}
public Task<IReadOnlyList<MarketEntry>> GetMarketAsync(long userId, CancellationToken cancellationToken = default)
=> ReadAsync<IReadOnlyList<MarketEntry>>((db, ct) => MarketViewAsync(db, userId, ct), cancellationToken);
public Task<ActionResult> ListOnMarketAsync(long userId, int itemIndex, long price, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, state, ct) =>
{
if (price is < GameplayRules.MarketMinPrice or > GameplayRules.MarketMaxPrice)
{
return ActionResult.Fail("价格超出允许范围", "没有上架任何物品",
$"价格需在 {GameplayRules.MarketMinPrice} ~ {GameplayRules.MarketMaxPrice} 之间", "/市场");
}
int active = await db.MarketListings.CountAsync(
x => x.SellerUserId == userId && x.Status == 0, ct);
if (active >= GameplayRules.MarketMaxListingsPerUser)
{
return ActionResult.Fail("在售挂单已满", "没有上架任何物品",
$"最多同时挂 {GameplayRules.MarketMaxListingsPerUser} 件,先 /下架 @编号", "/市场");
}
ItemInstance? item = await PlayerService.ItemByIndexAsync(db, userId, itemIndex, ct);
if (item is null) return NoListing("背包物品");
if (item.Locked || item.Bound)
{
return ActionResult.Fail("该物品已锁定或绑定", "没有上架任何物品",
"先 /解锁 @编号,已装备物品需先 /卸下", "/背包");
}
long fee = GameplayRules.MarketFee(price);
if (state.Credits < fee)
{
return ActionResult.Fail("金币不足以支付上架费", "没有上架任何物品",
$"需要 {fee} 金币,当前 {state.Credits}", "/状态");
}
PlayerService.ApplyCurrency(db, state, -fee, "credits", "market_fee", "listing", price.ToString(CultureInfo.InvariantCulture));
item.UserId = GameplayRules.EscrowUserId;
db.MarketListings.Add(new MarketListing
{
SellerUserId = userId, ItemInstanceId = item.Id,
Price = price, Fee = fee, Status = 0, CreatedAtUtc = DateTime.UtcNow
});
return ActionResult.Success("🏷️ 上架成功",
$"{PlayerService.ReadName(item)} · 标价 {price} 金币",
[$"- 上架费 {fee} 金币({GameplayRules.MarketFeeRatePercent}%)已记入账本",
"- 物品已移入托管,成交前不会出现在背包",
"- 用 /市场 查看编号,/下架 @编号 可撤回"], ["/市场", "/背包", "/状态"]);
}, cancellationToken);
public Task<ActionResult> DelistAsync(long userId, int index, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, _, ct) =>
{
List<MarketListing> listings = await ActiveListingsAsync(db, ct);
if (index <= 0 || index > listings.Count) return NoListing("挂单");
MarketListing listing = listings[index - 1];
if (listing.SellerUserId != userId)
{
return ActionResult.Fail("这不是你的挂单", "没有下架任何物品", "只能下架自己上架的商品", "/市场");
}
ItemInstance? item = await db.ItemInstances.FirstOrDefaultAsync(x => x.Id == listing.ItemInstanceId, ct);
listing.Status = 2;
listing.ClosedAtUtc = DateTime.UtcNow;
if (item is not null) item.UserId = userId;
return ActionResult.Success("📦 已下架",
$"{(item is null ? "未知物品" : PlayerService.ReadName(item))} 已退回背包",
["- 上架费不予退还"], ["/市场", "/背包"]);
}, cancellationToken);
public Task<ActionResult> BuyMarketAsync(long userId, int index, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, state, ct) =>
{
List<MarketListing> listings = await ActiveListingsAsync(db, ct);
if (index <= 0 || index > listings.Count) return NoListing("挂单");
MarketListing listing = listings[index - 1];
if (listing.SellerUserId == userId)
{
return ActionResult.Fail("不能购买自己的挂单", "没有发生任何交易", "用 /下架 @编号 撤回", "/市场");
}
if (state.Credits < listing.Price)
{
return ActionResult.Fail("金币不足", "没有发生任何交易",
$"需要 {listing.Price} 金币,当前 {state.Credits}", "/状态");
}
ItemInstance? item = await db.ItemInstances.FirstOrDefaultAsync(x => x.Id == listing.ItemInstanceId, ct);
if (item is null) return ActionResult.Fail("挂单物品已丢失", "没有发生任何交易", "联系管理员核查", "/市场");
PlayerState seller = await PlayerService.EnsureAsync(db, listing.SellerUserId, ct);
string reference = listing.Id.ToString(CultureInfo.InvariantCulture);
PlayerService.ApplyCurrency(db, state, -listing.Price, "credits", "market_buy", "listing", reference);
PlayerService.ApplyCurrency(db, seller, listing.Price, "credits", "market_sale", "listing", reference);
item.UserId = userId;
listing.Status = 1;
listing.ClosedAtUtc = DateTime.UtcNow;
return ActionResult.Success("🤝 交易达成",
$"{PlayerService.ReadName(item)} · {listing.Price} 金币",
[$"- 买家支出 {listing.Price},卖家收入 {listing.Price}",
"- 双方各写一条 ledger,金额可对账",
"- 物品已放入买家背包"], ["/市场", "/背包", "/状态"]);
}, cancellationToken);
// ---------------- 报价交易 ----------------
private static async Task<List<Trade>> ActiveOffersAsync(BotDbContext db, CancellationToken ct)
=> await db.Trades.Where(x => x.Status == 0).OrderBy(x => x.Id).ToListAsync(ct);
public Task<IReadOnlyList<OfferEntry>> GetOffersAsync(long userId, CancellationToken cancellationToken = default)
=> ReadAsync<IReadOnlyList<OfferEntry>>(async (db, ct) =>
{
List<Trade> trades = await ActiveOffersAsync(db, ct);
if (trades.Count == 0) return [];
List<long> tradeIds = trades.Select(x => x.Id).ToList();
List<TradeItem> tradeItems = await db.TradeItems.AsNoTracking()
.Where(x => tradeIds.Contains(x.TradeId)).ToListAsync(ct);
List<long> itemIds = tradeItems.Select(x => x.ItemInstanceId).ToList();
Dictionary<long, ItemInstance> items = await db.ItemInstances.AsNoTracking()
.Where(x => itemIds.Contains(x.Id)).ToDictionaryAsync(x => x.Id, ct);
List<long> sellers = trades.Select(x => x.SellerUserId).Distinct().ToList();
Dictionary<long, string> handles = await db.Users.AsNoTracking()
.Where(x => sellers.Contains(x.Id)).ToDictionaryAsync(x => x.Id, x => x.Handle, ct);
return trades.Select((trade, i) =>
{
TradeItem? line = tradeItems.FirstOrDefault(x => x.TradeId == trade.Id);
items.TryGetValue(line?.ItemInstanceId ?? 0, out ItemInstance? item);
return new OfferEntry(i + 1, trade.Id,
item is null ? "未知物品" : PlayerService.ReadName(item), line?.Price ?? 0,
handles.GetValueOrDefault(trade.SellerUserId, $"旅人{trade.SellerUserId}"),
trade.SellerUserId == userId);
}).ToArray();
}, cancellationToken);
public Task<ActionResult> CreateOfferAsync(long userId, int itemIndex, long price, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, _, ct) =>
{
if (price is < GameplayRules.MarketMinPrice or > GameplayRules.MarketMaxPrice)
{
return ActionResult.Fail("报价超出允许范围", "没有创建报价单",
$"价格需在 {GameplayRules.MarketMinPrice} ~ {GameplayRules.MarketMaxPrice} 之间", "/报价列表");
}
ItemInstance? item = await PlayerService.ItemByIndexAsync(db, userId, itemIndex, ct);
if (item is null) return NoListing("背包物品");
if (item.Locked || item.Bound)
{
return ActionResult.Fail("该物品已锁定或绑定", "没有创建报价单",
"先 /解锁 @编号,已装备物品需先 /卸下", "/背包");
}
item.UserId = GameplayRules.EscrowUserId;
Trade trade = new() { SellerUserId = userId, Status = 0, CreatedAtUtc = DateTime.UtcNow };
db.Trades.Add(trade);
await db.SaveChangesAsync(ct); // 先落库取得 Trade.Id
db.TradeItems.Add(new TradeItem
{
TradeId = trade.Id, FromUserId = userId, ItemInstanceId = item.Id,
Quantity = 1, Price = price
});
return ActionResult.Success("📝 报价单已发布",
$"{PlayerService.ReadName(item)} · 要价 {price} 金币",
["- 物品已移入托管,等待其它旅人 /接受报价 @编号",
"- 报价交易不收上架费,撤回用 /撤回报价 @编号"], ["/报价列表", "/背包"]);
}, cancellationToken);
public Task<ActionResult> AcceptOfferAsync(long userId, int index, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, state, ct) =>
{
List<Trade> trades = await ActiveOffersAsync(db, ct);
if (index <= 0 || index > trades.Count) return NoListing("报价单");
Trade trade = trades[index - 1];
if (trade.SellerUserId == userId)
{
return ActionResult.Fail("不能接受自己的报价单", "没有发生任何交易", "用 /撤回报价 @编号 取消", "/报价列表");
}
TradeItem? line = await db.TradeItems.FirstOrDefaultAsync(x => x.TradeId == trade.Id, ct);
if (line is null) return ActionResult.Fail("报价单缺少物品", "没有发生任何交易", "联系管理员核查", "/报价列表");
if (state.Credits < line.Price)
{
return ActionResult.Fail("金币不足", "没有发生任何交易",
$"需要 {line.Price} 金币,当前 {state.Credits}", "/状态");
}
ItemInstance? item = await db.ItemInstances.FirstOrDefaultAsync(x => x.Id == line.ItemInstanceId, ct);
if (item is null) return ActionResult.Fail("报价物品已丢失", "没有发生任何交易", "联系管理员核查", "/报价列表");
PlayerState seller = await PlayerService.EnsureAsync(db, trade.SellerUserId, ct);
string reference = trade.Id.ToString(CultureInfo.InvariantCulture);
PlayerService.ApplyCurrency(db, state, -line.Price, "credits", "offer_buy", "trade", reference);
PlayerService.ApplyCurrency(db, seller, line.Price, "credits", "offer_sale", "trade", reference);
item.UserId = userId;
trade.Status = 1;
trade.BuyerUserId = userId;
trade.ClosedAtUtc = DateTime.UtcNow;
return ActionResult.Success("🤝 报价成交",
$"{PlayerService.ReadName(item)} · {line.Price} 金币",
["- 双方各写一条 ledger", "- 物品已放入买家背包"], ["/报价列表", "/背包", "/状态"]);
}, cancellationToken);
public Task<ActionResult> CancelOfferAsync(long userId, int index, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, _, ct) =>
{
List<Trade> trades = await ActiveOffersAsync(db, ct);
if (index <= 0 || index > trades.Count) return NoListing("报价单");
Trade trade = trades[index - 1];
if (trade.SellerUserId != userId)
{
return ActionResult.Fail("这不是你的报价单", "没有撤回任何交易", "只能撤回自己发布的报价", "/报价列表");
}
TradeItem? line = await db.TradeItems.FirstOrDefaultAsync(x => x.TradeId == trade.Id, ct);
ItemInstance? item = line is null ? null :
await db.ItemInstances.FirstOrDefaultAsync(x => x.Id == line.ItemInstanceId, ct);
trade.Status = 2;
trade.ClosedAtUtc = DateTime.UtcNow;
if (item is not null) item.UserId = userId;
return ActionResult.Success("↩️ 报价已撤回",
$"{(item is null ? "未知物品" : PlayerService.ReadName(item))} 已退回背包",
[], ["/报价列表", "/背包"]);
}, cancellationToken);
// ---------------- 锻造 / 秘境 ----------------
public Task<ActionResult> ForgeAsync(long userId, int materialIndex, int minutes, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, state, ct) =>
{
if (await db.ForgingJobs.AnyAsync(x => x.UserId == userId && x.SettledAtUtc == null, ct))
{
return ActionResult.Fail("已有锻造进行中", "没有开始新的锻造",
"等待结束后用 /收取锻造 结算", "/收取锻造");
}
ItemInstance? material = await PlayerService.ItemByIndexAsync(db, userId, materialIndex, ct);
if (material is null) return NoListing("材料");
if (material.Locked || material.Bound)
{
return ActionResult.Fail("材料已锁定或绑定", "没有消耗材料", "先 /解锁 @编号", "/背包");
}
if (material.Quantity < GameplayRules.ForgeMaterialQuantity)
{
return ActionResult.Fail("材料数量不足", "没有消耗材料",
$"需要 {GameplayRules.ForgeMaterialQuantity} 个同类材料", "/背包");
}
if (state.Credits < GameplayRules.ForgeCostCredits)
{
return ActionResult.Fail("金币不足", "没有消耗材料或金币",
$"需要 {GameplayRules.ForgeCostCredits} 金币,当前 {state.Credits}", "/状态");
}
string name = PlayerService.ReadName(material);
int duration = Math.Clamp(minutes, 1, GameplayRules.ForgeMaxMinutes);
PlayerService.ApplyCurrency(db, state, -GameplayRules.ForgeCostCredits, "credits", "forge_start", "forge", userId.ToString(CultureInfo.InvariantCulture));
PlayerService.Consume(db, material, GameplayRules.ForgeMaterialQuantity);
DateTime now = DateTime.UtcNow;
db.ForgingJobs.Add(new ForgingJob
{
UserId = userId, RecipeKey = "standard",
StateJson = JsonSerializer.Serialize(new { material = name }),
StartedAtUtc = now, EndsAtUtc = now.AddMinutes(duration)
});
return ActionResult.Success("🔨 开始锻造",
$"{name} ×{GameplayRules.ForgeMaterialQuantity} · {duration} 分钟后结算",
[$"- 消耗金币 {GameplayRules.ForgeCostCredits},剩余 {state.Credits}",
$"- 成品品质:{GameplayRules.QualityName(GameplayRules.ForgeOutputQuality)}"],
["/收取锻造", "/背包"]);
}, cancellationToken);
public Task<ActionResult> ClaimForgeAsync(long userId, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, _, ct) =>
{
ForgingJob? job = await db.ForgingJobs
.Where(x => x.UserId == userId && x.SettledAtUtc == null)
.OrderBy(x => x.EndsAtUtc).FirstOrDefaultAsync(ct);
if (job is null) return ActionResult.Fail("没有进行中的锻造", "没有产出任何物品", "先用 /锻造 @编号 [分钟] 开始", "/锻造 @1 1");
if (job.EndsAtUtc > DateTime.UtcNow) return NotReady("锻造", job.EndsAtUtc);
await PlayerService.AddItemAsync(db, userId, "锻造·精制装备",
GameplayRules.ForgeOutputQuality, 1, ct, "forge");
job.SettledAtUtc = DateTime.UtcNow;
return ActionResult.Success("⚒️ 锻造完成", "精制装备已放入背包",
[$"- 品质:{GameplayRules.QualityName(GameplayRules.ForgeOutputQuality)}"],
["/背包", "/状态"]);
}, cancellationToken);
public Task<ActionResult> InstanceAsync(long userId, string difficulty, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, state, ct) =>
{
if (await db.ExplorationRuns.AnyAsync(x => x.UserId == userId && x.SettledAtUtc == null, ct))
{
return ActionResult.Fail("已有秘境探索进行中", "没有开始新的探索",
"等待结束后用 /收取秘境 结算", "/收取秘境");
}
if (state.Credits < GameplayRules.InstanceCostCredits)
{
return ActionResult.Fail("金币不足", "没有开始探索",
$"需要 {GameplayRules.InstanceCostCredits} 金币,当前 {state.Credits}", "/状态");
}
string region = string.IsNullOrWhiteSpace(difficulty) ? "普通" : difficulty.Trim();
DateTime now = DateTime.UtcNow;
PlayerService.ApplyCurrency(db, state, -GameplayRules.InstanceCostCredits, "credits", "instance_start", "instance", region);
db.ExplorationRuns.Add(new ExplorationRun
{
UserId = userId, RegionKey = region,
StateJson = JsonSerializer.Serialize(new { difficulty = region }),
StartedAtUtc = now, EndsAtUtc = now.AddMinutes(GameplayRules.InstanceDefaultMinutes)
});
return ActionResult.Success("🗺️ 进入秘境",
$"{region} 难度 · {GameplayRules.InstanceDefaultMinutes} 分钟后结算",
[$"- 消耗金币 {GameplayRules.InstanceCostCredits}",
$"- 预计收获:经验 +{GameplayRules.InstanceRewardExp} / 金币 +{GameplayRules.InstanceRewardCredits} / 随机掉落"],
["/收取秘境", "/状态"]);
}, cancellationToken);
public Task<ActionResult> ClaimInstanceAsync(long userId, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, state, ct) =>
{
ExplorationRun? run = await db.ExplorationRuns
.Where(x => x.UserId == userId && x.SettledAtUtc == null)
.OrderBy(x => x.EndsAtUtc).FirstOrDefaultAsync(ct);
if (run is null) return ActionResult.Fail("没有进行中的探索", "没有结算任何奖励", "先用 /秘境 开始", "/秘境");
if (run.EndsAtUtc > DateTime.UtcNow) return NotReady("探索", run.EndsAtUtc);
state.Exp += GameplayRules.InstanceRewardExp;
PlayerService.ApplyCurrency(db, state, GameplayRules.InstanceRewardCredits, "credits", "instance_reward", "instance", run.RegionKey);
int quality = GameplayRules.RollQuality(Random.Shared);
await PlayerService.AddItemAsync(db, userId, $"{run.RegionKey}秘境掉落", quality, 1, ct, "instance");
run.SettledAtUtc = DateTime.UtcNow;
return ActionResult.Success("🏆 秘境结算",
$"经验 +{GameplayRules.InstanceRewardExp} · 金币 +{GameplayRules.InstanceRewardCredits}",
[$"- 掉落:{GameplayRules.QualityName(quality)} · {run.RegionKey}秘境掉落",
$"- 当前经验:{state.Exp} 金币:{state.Credits}"],
["/背包", "/状态"]);
}, cancellationToken);
// ---------------- 决斗 / Boss / 排行 ----------------
public Task<ActionResult> DuelAsync(long userId, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, state, ct) =>
{
if (state.Credits < GameplayRules.DuelCostCredits)
{
return ActionResult.Fail("金币不足", "没有开始决斗",
$"需要 {GameplayRules.DuelCostCredits} 金币,当前 {state.Credits}", "/状态");
}
PlayerService.ApplyCurrency(db, state, -GameplayRules.DuelCostCredits, "credits", "duel_entry", "duel", userId.ToString(CultureInfo.InvariantCulture));
bool win = Random.Shared.Next(100) < 55;
if (win)
{
PlayerService.ApplyCurrency(db, state, GameplayRules.DuelRewardCredits, "credits", "duel_reward", "duel", userId.ToString(CultureInfo.InvariantCulture));
}
int gain = win ? GameplayRules.DuelWinPoints : GameplayRules.DuelLosePoints;
long points = await AddPointsAsync(db, userId, gain, ct);
return ActionResult.Success(win ? "⚔️ 决斗胜利" : "🛡️ 决斗失利",
win ? $"金币 +{GameplayRules.DuelRewardCredits - GameplayRules.DuelCostCredits}(净) · 战绩 +{gain}"
: $"损失报名费 {GameplayRules.DuelCostCredits} · 战绩 +{gain}",
[$"- 当前战绩积分:{points} 金币:{state.Credits}", "- 战绩可在 /排行榜 战绩 查看"],
["/决斗", "/排行榜 战绩", "/状态"]);
}, cancellationToken);
public Task<ActionResult> BossAsync(long userId, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, state, ct) =>
{
string key = $"boss:{userId}:{GameplayRules.Today()}";
if (await db.AppConfigs.AsNoTracking().AnyAsync(x => x.Key == key, ct))
{
return ActionResult.Fail("今天已经挑战过 Boss", "没有扣除金币,也没有发放奖励",
"明天再来,或先去 /决斗 练手", "/决斗");
}
if (state.Credits < GameplayRules.BossCostCredits)
{
return ActionResult.Fail("金币不足", "没有开始挑战",
$"需要 {GameplayRules.BossCostCredits} 金币,当前 {state.Credits}", "/状态");
}
PlayerService.ApplyCurrency(db, state, -GameplayRules.BossCostCredits, "credits", "boss_entry", "boss", key);
PlayerService.ApplyCurrency(db, state, GameplayRules.BossRewardCredits, "credits", "boss_reward", "boss", key);
PlayerService.ApplyCurrency(db, state, GameplayRules.BossRewardDiamonds, "diamonds", "boss_reward", "boss", key);
long points = await AddPointsAsync(db, userId, GameplayRules.BossWinPoints, ct);
db.AppConfigs.Add(new AppConfig
{
Key = key, ValueJson = "{\"count\":1}", UpdatedAtUtc = DateTime.UtcNow
});
return ActionResult.Success("🐉 Boss 讨伐成功",
$"金币 +{GameplayRules.BossRewardCredits - GameplayRules.BossCostCredits}(净) · 钻石 +{GameplayRules.BossRewardDiamonds} · 战绩 +{GameplayRules.BossWinPoints}",
[$"- 当前战绩积分:{points} 金币:{state.Credits} 钻石:{state.Diamonds}",
"- 每日仅可讨伐一次(按游戏日重置)"],
["/排行榜 战绩", "/状态"]);
}, cancellationToken);
public Task<IReadOnlyList<RankEntry>> GetRankingAsync(string board, CancellationToken cancellationToken = default)
=> ReadAsync<IReadOnlyList<RankEntry>>(async (db, ct) =>
{
string normalized = board.ToLowerInvariant() switch
{
"level" or "等级" => "level",
"points" or "战绩" => "points",
_ => "credits"
};
if (normalized == "points")
{
List<ActivityProgress> rows = await db.ActivityProgress.AsNoTracking()
.Where(x => x.ActivityKey == PointsKey).ToListAsync(ct);
List<long> ids = rows.Select(x => x.UserId).ToList();
Dictionary<long, string> handles = await db.Users.AsNoTracking()
.Where(x => ids.Contains(x.Id)).ToDictionaryAsync(x => x.Id, x => x.Handle, ct);
return rows.Select(x => new { x.UserId, Value = ReadPoints(x.ProgressJson) })
.Where(x => x.Value > 0)
.OrderByDescending(x => x.Value).Take(GameplayRules.RankingTop)
.Select((x, i) => new RankEntry(i + 1,
handles.GetValueOrDefault(x.UserId, $"旅人{x.UserId}"), x.Value)).ToArray();
}
IQueryable<PlayerState> query = db.PlayerStates.AsNoTracking();
List<PlayerState> states = normalized == "level"
? await query.OrderByDescending(x => x.Level).ThenByDescending(x => x.Exp)
.Take(GameplayRules.RankingTop).ToListAsync(ct)
: await query.OrderByDescending(x => x.Credits).Take(GameplayRules.RankingTop).ToListAsync(ct);
List<long> userIds = states.Select(x => x.UserId).ToList();
Dictionary<long, string> stateHandles = await db.Users.AsNoTracking()
.Where(x => userIds.Contains(x.Id)).ToDictionaryAsync(x => x.Id, x => x.Handle, ct);
return states.Select((state, i) => new RankEntry(i + 1,
stateHandles.GetValueOrDefault(state.UserId, $"旅人{state.UserId}"),
normalized == "level" ? state.Level : state.Credits)).ToArray();
}, cancellationToken);
// ---------------- 内部工具 ----------------
private static async Task<long> AddPointsAsync(BotDbContext db, long userId, int delta, CancellationToken ct)
{
ActivityProgress? row = await db.ActivityProgress.FirstOrDefaultAsync(
x => x.UserId == userId && x.ActivityKey == PointsKey, ct);
long points = (row is null ? 0 : ReadPoints(row.ProgressJson)) + delta;
string json = JsonSerializer.Serialize(new { points });
if (row is null)
{
db.ActivityProgress.Add(new ActivityProgress
{
UserId = userId, ActivityKey = PointsKey,
ProgressJson = json, ClaimedJson = "[]", UpdatedAtUtc = DateTime.UtcNow
});
}
else
{
row.ProgressJson = json;
row.UpdatedAtUtc = DateTime.UtcNow;
}
return points;
}
private static long ReadPoints(string json)
{
try
{
using JsonDocument document = JsonDocument.Parse(json);
return document.RootElement.TryGetProperty("points", out JsonElement points)
? points.GetInt64() : 0;
}
catch (JsonException) { return 0; }
}
private static ActionResult NoListing(string what)
=> ActionResult.Fail($"{what} @编号 不存在", "没有改动任何数据",
"先查看列表确认编号(编号按列表顺序稳定排列)", "/状态");
private static ActionResult NotReady(string what, DateTime endsAtUtc)
=> ActionResult.Fail($"{what}尚未结束", "没有结算任何奖励",
$"还需约 {(int)Math.Ceiling((endsAtUtc - DateTime.UtcNow).TotalSeconds)} 秒,稍后再收取", "/状态");
}
+45
View File
@@ -0,0 +1,45 @@
namespace OshimaBot.Gameplay;
/// <summary>玩法层与指令层之间的纯数据契约,玩法层不依赖 Messaging/Models。</summary>
public sealed record PlayerSnapshot(
long UserId, int Level, long Exp, long Credits, long Diamonds,
int SignInStreak, string SignedOn, string? MainCharacter,
int CharacterCount, int ItemCount, int SquadCount, int PendingTrainings);
public sealed record BagEntry(
int Index, long Id, string Name, string CatalogId, int Quantity,
int Quality, bool Locked, bool Bound, bool Equipped);
public sealed record CharacterEntry(
int Index, long Id, string Name, int Level, long Exp,
int BreakLevel, bool IsMain, int EquipmentCount);
public sealed record QuestEntry(int Index, string Key, string Name, int Status, int Progress, int Target);
/// <summary>
/// 统一的玩法结果。Ok=true 时按 4 段式渲染(Title / Status / Lines / Actions);
/// Ok=false 时按错误三段式渲染(发生了什么 / 没有发生什么 / 下一步)。
/// </summary>
public sealed record ActionResult(
bool Ok, string Title, string Status, IReadOnlyList<string> Lines, IReadOnlyList<string> Actions)
{
public static ActionResult Success(
string title, string status,
IEnumerable<string>? lines = null, IEnumerable<string>? actions = null)
=> new(true, title, status,
lines?.ToArray() ?? [], actions?.ToArray() ?? ["/状态"]);
public static ActionResult Fail(string what, string notHappened, string next, string? action = null)
=> new(false, what, notHappened, [next], action is null ? ["/帮助"] : [action]);
}
/// <summary>P2 经济与排行视图。</summary>
public sealed record StoreEntry(int Index, long Id, string Name, long Price, int Stock);
public sealed record MarketEntry(
int Index, long Id, string ItemName, int Quality, long Price, long Fee, string SellerHandle, bool IsMine);
public sealed record OfferEntry(
int Index, long Id, string ItemName, long Price, string SellerHandle, bool IsMine);
public sealed record RankEntry(int Index, string Handle, long Value);
+175
View File
@@ -0,0 +1,175 @@
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
namespace OshimaBot.Gameplay;
/// <summary>
/// P1 玩法数值与文案的默认规则。集中在一处便于调参,业务层不硬编码数字。
/// 用户未指定数值时按本文件默认值实现(计划 §5.4)。
/// </summary>
public static class GameplayRules
{
public const long StartingCredits = 1200;
public const int StartingDiamonds = 30;
public const int StartingItems = 3;
public const int GachaCost = 5;
public const int GachaTenCost = 45;
public const int MaxGachaPerCall = 10;
public const int SignInBaseCredits = 100;
public const int SignInStreakBonus = 20;
public const int SignInStreakCapDays = 7;
public const int SignInDiamondEveryDays = 7;
public const int SignInDiamondAmount = 5;
public const int LevelsPerBreak = 10;
public const int BreakCreditsBase = 500;
public const int SalvageValueBase = 20;
public const int UseExpBase = 30;
public const int TrainCostCredits = 50;
public const int TrainDefaultMinutes = 10;
public const int TrainMaxMinutes = 120;
public const int TrainExpBase = 120;
public const int TrainExpPerLevel = 20;
public const int QuestRewardCredits = 80;
public const int QuestRewardDiamonds = 2;
/// <summary>装备槽位,装备时按序占用第一个空槽。</summary>
public static readonly IReadOnlyList<string> EquipmentSlots = ["weapon", "armor", "trinket"];
public static readonly IReadOnlyList<string> FortuneTexts =
[
"大吉 · 今天适合孤身深入,意料之外的收获正在等你。",
"中吉 · 稳扎稳打,旧线索会连成一条路。",
"小吉 · 有人愿意搭把手,别拒绝。",
"平 · 雾很厚,但路还在脚下。",
"小凶 · 别急着做决定,先看看背包。",
"中凶 · 今天不宜逞强,休整也是一种前进。",
"大凶 · 收好贵重物品,等雾散了再出门。"
];
public const string DefaultNotice =
"欢迎来到铎京。旧存档未迁移(MySQL 数据已丢失),所有旅人从今天重新开始;" +
"每日签到、抽卡、练级与背包已开放,商店与交易将在后续开放。";
/// <summary>每日任务定义:key → 名称 / 目标次数。进度写在 daily_quests.progress_json。</summary>
public static readonly IReadOnlyList<(string Key, string Name, int Target)> DailyQuests =
[
("signin", "今日签到", 1),
("simulate", "完成一次战斗模拟", 1),
("gacha", "进行一次抽卡", 1)
];
private static TimeZoneInfo GameTimeZone
=> TimeZoneInfo.TryFindSystemTimeZoneById("Asia/Shanghai", out TimeZoneInfo? iana)
? iana
: TimeZoneInfo.FindSystemTimeZoneById("China Standard Time");
/// <summary>游戏日(Asia/Shanghai),签到/任务/运势全部以它为准,避免 UTC 跨日。</summary>
public static string Today()
=> DateOnly.FromDateTime(TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, GameTimeZone))
.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
public static long ExpForLevel(int level)
=> (long)Math.Ceiling(100 * Math.Pow(Math.Max(1, level), 1.5));
public static int LevelCap(int breakLevel) => LevelsPerBreak * (breakLevel + 1);
public static long SalvageValue(int quality, int quantity)
=> SalvageValueBase * (long)Math.Max(1, quality) * Math.Max(1, quality) * Math.Max(1, quantity);
public static int UseExp(int quality, int quantity)
=> UseExpBase * Math.Max(1, quality) * Math.Max(1, quantity);
public static long BreakCost(int breakLevel) => BreakCreditsBase * (breakLevel + 1L);
public static long SignInCredits(int streak)
=> SignInBaseCredits + SignInStreakBonus * Math.Min(Math.Max(0, streak), SignInStreakCapDays);
/// <summary>品质权重:普通 60 / 精良 25 / 稀有 10 / 史诗 4 / 传说 1。</summary>
public static int RollQuality(Random random)
{
int roll = random.Next(100);
return roll switch
{
< 60 => 1,
< 85 => 2,
< 95 => 3,
< 99 => 4,
_ => 5
};
}
public static string QualityName(int quality) => quality switch
{
1 => "普通",
2 => "精良",
3 => "稀有",
4 => "史诗",
_ => "传说"
};
/// <summary>同一用户同一天的运势稳定不变(服务端确定性哈希,不用 Random.Shared)。</summary>
public static string Fortune(long userId, string date)
{
byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes($"{userId}:{date}"));
return FortuneTexts[hash[0] % FortuneTexts.Count];
}
// ---- P2:经济与战斗 ----
public const long MarketFeeRatePercent = 5;
public const long MarketMinPrice = 1;
public const long MarketMaxPrice = 1_000_000;
public const int MarketMaxListingsPerUser = 5;
public const int ForgeCostCredits = 200;
public const int ForgeMaterialQuantity = 2;
public const int ForgeDefaultMinutes = 5;
public const int ForgeOutputQuality = 3;
public const int ForgeMaxMinutes = 120;
public const int InstanceCostCredits = 80;
public const int InstanceDefaultMinutes = 3;
public const int InstanceRewardExp = 200;
public const int InstanceRewardCredits = 60;
public const int InstanceMaxMinutes = 120;
public const int DuelCostCredits = 30;
public const int DuelRewardCredits = 80;
public const int DuelWinPoints = 10;
public const int DuelLosePoints = 2;
public const int BossCostCredits = 100;
public const int BossRewardCredits = 300;
public const int BossRewardDiamonds = 3;
public const int BossWinPoints = 25;
public const int RankingTop = 10;
/// <summary>托管用户 id:市场上架 / 报价单在成交前的物品归属,不会出现在任何玩家背包。</summary>
public const long EscrowUserId = -1;
public static long MarketFee(long price)
=> Math.Max(1, price * MarketFeeRatePercent / 100);
/// <summary>系统商店的默认货架(懒建,不进 Migration)。</summary>
public static readonly IReadOnlyList<(string Name, long Price, int Stock)> SeedStoreGoods =
[
("补给包", 120, -1),
("精良装备箱", 260, -1),
("史诗遗物匣", 500, 20)
];
public static string RankingBoardName(string board) => board.ToLowerInvariant() switch
{
"level" or "等级" => "等级榜",
"points" or "战绩" => "战绩榜",
_ => "金币榜"
};
public static string CatalogVersion => "core-v3";
}
+775
View File
@@ -0,0 +1,775 @@
using System.Globalization;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using OshimaBot.Data;
using OshimaBot.Data.Entities;
using OshimaBot.Game.Services;
using DataCharacter = OshimaBot.Data.Entities.Character;
namespace OshimaBot.Gameplay;
public interface IPlayerService
{
Task<PlayerSnapshot?> GetSnapshotAsync(long userId, CancellationToken cancellationToken = default);
Task<ActionResult> RegisterAsync(long userId, CancellationToken cancellationToken = default);
Task<ActionResult> SignInAsync(long userId, CancellationToken cancellationToken = default);
Task<ActionResult> GachaAsync(long userId, int count, CancellationToken cancellationToken = default);
Task<IReadOnlyList<BagEntry>> GetBagAsync(long userId, CancellationToken cancellationToken = default);
Task<ActionResult> UseAsync(long userId, int index, int quantity, CancellationToken cancellationToken = default);
Task<ActionResult> SalvageAsync(long userId, int index, int quantity, CancellationToken cancellationToken = default);
Task<ActionResult> SetLockAsync(long userId, int index, bool locked, CancellationToken cancellationToken = default);
Task<ActionResult> EquipAsync(long userId, int index, CancellationToken cancellationToken = default);
Task<ActionResult> UnequipAsync(long userId, string slot, CancellationToken cancellationToken = default);
Task<IReadOnlyList<CharacterEntry>> GetCharactersAsync(long userId, CancellationToken cancellationToken = default);
Task<ActionResult> SetMainAsync(long userId, int index, CancellationToken cancellationToken = default);
Task<ActionResult> LevelUpAsync(long userId, int index, CancellationToken cancellationToken = default);
Task<ActionResult> BreakAsync(long userId, int index, CancellationToken cancellationToken = default);
Task<ActionResult> TrainStartAsync(long userId, int index, int minutes, CancellationToken cancellationToken = default);
Task<ActionResult> TrainClaimAsync(long userId, CancellationToken cancellationToken = default);
Task<ActionResult> SquadAsync(long userId, string operation, int index, CancellationToken cancellationToken = default);
Task<IReadOnlyList<QuestEntry>> GetQuestsAsync(long userId, CancellationToken cancellationToken = default);
Task<ActionResult> ClaimQuestAsync(long userId, int index, CancellationToken cancellationToken = default);
Task<ActionResult> RecordSimulationAsync(long userId, CancellationToken cancellationToken = default);
Task<string> GetNoticeAsync(CancellationToken cancellationToken = default);
Task<string> GetFortuneAsync(long userId, CancellationToken cancellationToken = default);
}
/// <summary>
/// P1 玩法仓储:所有「改货币 + 改物品 + 写 ledger」在一个 SQLite 事务内完成。
/// singleton(与 CommandCatalog 生命周期一致),每次操作自己开 scope;userId&lt;=0 一律拒绝。
/// </summary>
public sealed class PlayerService(IServiceScopeFactory scopeFactory, ILogger<PlayerService> logger) : IPlayerService
{
internal static ActionResult NoIdentity => ActionResult.Fail(
"身份尚未就绪", "没有读写任何存档", "请通过 QQ 消息触发注册,或稍后重试", "/状态");
// ---------------- 读 ----------------
private async Task<T> ReadAsync<T>(
Func<BotDbContext, CancellationToken, Task<T>> body, CancellationToken cancellationToken)
{
using IServiceScope scope = scopeFactory.CreateScope();
BotDbContext db = scope.ServiceProvider.GetRequiredService<BotDbContext>();
return await body(db, cancellationToken);
}
public Task<PlayerSnapshot?> GetSnapshotAsync(long userId, CancellationToken cancellationToken = default)
=> userId <= 0 ? Task.FromResult<PlayerSnapshot?>(null) : ReadAsync<PlayerSnapshot?>(async (db, ct) =>
{
PlayerState state = await EnsureAsync(db, userId, ct);
List<DataCharacter> characters = await db.Characters.AsNoTracking()
.Where(x => x.UserId == userId).OrderBy(x => x.Id).ToListAsync(ct);
int itemCount = await db.ItemInstances.AsNoTracking().CountAsync(x => x.UserId == userId, ct);
List<long> squadIds = await db.Squads.AsNoTracking()
.Where(x => x.UserId == userId).Select(x => x.Id).ToListAsync(ct);
int squadCount = squadIds.Count == 0 ? 0 : await db.SquadMembers.AsNoTracking()
.CountAsync(x => squadIds.Contains(x.SquadId), ct);
int pendingTrainings = await db.TrainingSessions.AsNoTracking()
.CountAsync(x => x.UserId == userId && x.SettledAtUtc == null, ct);
return new PlayerSnapshot(userId, state.Level, state.Exp, state.Credits, state.Diamonds,
state.SignInStreak, state.SignedOn, characters.FirstOrDefault(x => x.IsMain)?.Name,
characters.Count, itemCount, squadCount, pendingTrainings);
}, cancellationToken);
public Task<IReadOnlyList<BagEntry>> GetBagAsync(long userId, CancellationToken cancellationToken = default)
=> userId <= 0 ? Task.FromResult<IReadOnlyList<BagEntry>>([]) : ReadAsync(async (db, ct) =>
{
await EnsureAsync(db, userId, ct);
List<ItemInstance> items = await db.ItemInstances.AsNoTracking()
.Where(x => x.UserId == userId).OrderBy(x => x.Id).ToListAsync(ct);
List<long> ids = items.Select(x => x.Id).ToList();
HashSet<long> equipped = (await db.CharacterEquipment.AsNoTracking()
.Where(x => ids.Contains(x.ItemInstanceId))
.Select(x => x.ItemInstanceId).ToListAsync(ct)).ToHashSet();
return (IReadOnlyList<BagEntry>)items.Select((item, i) => new BagEntry(
i + 1, item.Id, ReadName(item), item.CatalogId, item.Quantity,
item.Quality, item.Locked, item.Bound, equipped.Contains(item.Id))).ToArray();
}, cancellationToken);
public Task<IReadOnlyList<CharacterEntry>> GetCharactersAsync(long userId, CancellationToken cancellationToken = default)
=> userId <= 0 ? Task.FromResult<IReadOnlyList<CharacterEntry>>([]) : ReadAsync(async (db, ct) =>
{
await EnsureAsync(db, userId, ct);
List<DataCharacter> characters = await db.Characters.AsNoTracking()
.Where(x => x.UserId == userId).OrderBy(x => x.Id).ToListAsync(ct);
Dictionary<long, int> equipment = await db.CharacterEquipment.AsNoTracking()
.GroupBy(x => x.CharacterId).Select(g => new { g.Key, Count = g.Count() })
.ToDictionaryAsync(x => x.Key, x => x.Count, ct);
return (IReadOnlyList<CharacterEntry>)characters.Select((c, i) => new CharacterEntry(
i + 1, c.Id, c.Name, c.Level, c.Exp, c.BreakLevel, c.IsMain,
equipment.GetValueOrDefault(c.Id))).ToArray();
}, cancellationToken);
public async Task<IReadOnlyList<QuestEntry>> GetQuestsAsync(long userId, CancellationToken cancellationToken = default)
{
if (userId <= 0) return [];
string date = GameplayRules.Today();
return await ReadAsync(async (db, ct) =>
{
Dictionary<string, DailyQuest> rows = await db.DailyQuests.AsNoTracking()
.Where(x => x.UserId == userId && x.QuestDate == date)
.ToDictionaryAsync(x => x.QuestKey, ct);
List<QuestEntry> result = [];
for (int i = 0; i < GameplayRules.DailyQuests.Count; i++)
{
(string key, string name, int target) = GameplayRules.DailyQuests[i];
rows.TryGetValue(key, out DailyQuest? row);
result.Add(new QuestEntry(i + 1, key, name, row?.Status ?? 0,
row is null ? 0 : ReadProgress(row), target));
}
return (IReadOnlyList<QuestEntry>)result;
}, cancellationToken);
}
public Task<string> GetNoticeAsync(CancellationToken cancellationToken = default)
=> ReadAsync(async (db, ct) =>
{
AppConfig? config = await db.AppConfigs.AsNoTracking()
.FirstOrDefaultAsync(x => x.Key == "notice", ct);
if (config is null) return GameplayRules.DefaultNotice;
try
{
using JsonDocument document = JsonDocument.Parse(config.ValueJson);
return document.RootElement.TryGetProperty("text", out JsonElement text)
? text.GetString() ?? GameplayRules.DefaultNotice
: GameplayRules.DefaultNotice;
}
catch (JsonException) { return GameplayRules.DefaultNotice; }
}, cancellationToken);
public Task<string> GetFortuneAsync(long userId, CancellationToken cancellationToken = default)
=> Task.FromResult(userId <= 0
? "身份尚未就绪,无法占卜。"
: GameplayRules.Fortune(userId, GameplayRules.Today()));
// ---------------- 写(事务) ----------------
private async Task<ActionResult> MutateAsync(
long userId,
Func<BotDbContext, PlayerState, CancellationToken, Task<ActionResult>> body,
CancellationToken cancellationToken)
{
if (userId <= 0) return NoIdentity;
try
{
using IServiceScope scope = scopeFactory.CreateScope();
BotDbContext db = scope.ServiceProvider.GetRequiredService<BotDbContext>();
await using Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction transaction =
await db.Database.BeginTransactionAsync(cancellationToken);
PlayerState state = await EnsureAsync(db, userId, cancellationToken);
ActionResult result = await body(db, state, cancellationToken);
if (!result.Ok)
{
await transaction.RollbackAsync(cancellationToken);
return result;
}
state.UpdatedAtUtc = DateTime.UtcNow;
await db.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);
return result;
}
catch (DbUpdateConcurrencyException)
{
return ActionResult.Fail("存档正被另一条消息修改", "本次操作已回滚", "稍等一秒后重试", "/状态");
}
catch (DbUpdateException exception)
{
logger.LogWarning(exception, "玩法写入冲突:UserId={UserId}", userId);
return ActionResult.Fail("存档写入冲突", "本次操作已回滚", "稍后重试", "/状态");
}
catch (Exception exception)
{
logger.LogError(exception, "玩法操作失败:UserId={UserId}", userId);
return ActionResult.Fail("玩法操作出现异常", "本次操作已回滚", "稍后重试,或输入 /帮助", "/帮助");
}
}
public Task<ActionResult> RegisterAsync(long userId, CancellationToken cancellationToken = default)
=> userId <= 0 ? Task.FromResult(NoIdentity) : ReadAsync<ActionResult>(async (db, ct) =>
{
// 读路径自己判断是否为首次建档,避免 EnsureAsync 已建档后误报「存档已存在」。
bool existed = await db.PlayerStates.AsNoTracking().AnyAsync(x => x.UserId == userId, ct);
PlayerState state = await EnsureAsync(db, userId, ct);
return ActionResult.Success("🎒 旅人登记",
existed ? "存档已存在,未重复发放初始资源" : "初始资源已发放",
[
$"- 旅人等级:Lv.{state.Level} 经验:{state.Exp}",
$"- 金币:{state.Credits} 钻石:{state.Diamonds}",
$"- 角色:{await db.Characters.CountAsync(x => x.UserId == userId, ct)} 名",
$"- 物品:{await db.ItemInstances.CountAsync(x => x.UserId == userId, ct)} 格",
"- 旧版 JSON 存档未迁移,所有旅人从今天重新开始"
], ["/状态", "/签到", "/抽卡", "/背包"]);
}, cancellationToken);
public Task<ActionResult> SignInAsync(long userId, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, state, ct) =>
{
string today = GameplayRules.Today();
if (string.Equals(state.SignedOn, today, StringComparison.Ordinal))
{
return ActionResult.Fail("今天已经签到过了", "没有重复发放奖励",
"明天再来,或先完成每日任务", "/每日任务");
}
bool continuous = string.Equals(state.SignedOn,
DateOnly.ParseExact(today, "yyyy-MM-dd", CultureInfo.InvariantCulture)
.AddDays(-1).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), StringComparison.Ordinal);
state.SignInStreak = continuous ? state.SignInStreak + 1 : 1;
state.SignedOn = today;
long credits = GameplayRules.SignInCredits(state.SignInStreak - 1);
ApplyCurrency(db, state, credits, "credits", "signin", "signin", today);
int diamonds = state.SignInStreak % GameplayRules.SignInDiamondEveryDays == 0
? GameplayRules.SignInDiamondAmount : 0;
if (diamonds > 0)
{
ApplyCurrency(db, state, diamonds, "diamonds", "signin_streak", "signin", today);
}
db.SignInRecords.Add(new SignInRecord
{
UserId = userId, SignInDate = today,
RewardJson = JsonSerializer.Serialize(new { credits, diamonds }),
CreatedAtUtc = DateTime.UtcNow
});
await AdvanceQuestAsync(db, userId, "signin", ct);
return ActionResult.Success("📅 签到成功",
$"连续 {state.SignInStreak} 天 · 金币 +{credits}{(diamonds > 0 ? $" · 钻石 +{diamonds}" : "")}",
[
$"- 当前金币:{state.Credits} 钻石:{state.Diamonds}",
$"- 连续签到每满 {GameplayRules.SignInDiamondEveryDays} 天额外送 {GameplayRules.SignInDiamondAmount} 钻石",
"- 今日任务「今日签到」进度已更新"
], ["/每日任务", "/状态", "/抽卡"]);
}, cancellationToken);
public Task<ActionResult> GachaAsync(long userId, int count, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, state, ct) =>
{
int pulls = Math.Clamp(count, 1, GameplayRules.MaxGachaPerCall);
int cost = pulls == 10 ? GameplayRules.GachaTenCost : GameplayRules.GachaCost * pulls;
if (state.Diamonds < cost)
{
return ActionResult.Fail("钻石不足", "没有扣除钻石,也没有生成物品",
$"需要 {cost} 钻石,当前 {state.Diamonds};可先签到或领取每日任务", "/签到");
}
ApplyCurrency(db, state, -cost, "diamonds", "gacha", "gacha", GameplayRules.Today());
var catalog = FunGameService.AllItems;
List<(string Name, int Quality)> drawn = [];
for (int i = 0; i < pulls; i++)
{
int quality = GameplayRules.RollQuality(Random.Shared);
// 十连保底至少一件史诗及以上。
if (pulls == 10 && i == pulls - 1 && drawn.All(x => x.Quality < 4)) quality = 4;
string name = catalog.Count == 0
? "无名的遗物"
: catalog[Random.Shared.Next(catalog.Count)].Name;
drawn.Add((name, quality));
}
foreach ((string name, int quality) in drawn)
{
await AddItemAsync(db, userId, name, quality, 1, ct);
}
await AdvanceQuestAsync(db, userId, "gacha", ct);
List<string> lines = drawn.Select((item, i) =>
$"- {i + 1}. {GameplayRules.QualityName(item.Quality)} · {item.Name}").ToList();
lines.Add($"- 消耗钻石 {cost},剩余 {state.Diamonds}");
lines.Add("- 用 /背包 查看物品编号后再 @编号 使用或分解");
return ActionResult.Success(pulls == 10 ? "🎰 十连抽卡" : "🎲 抽卡",
$"{pulls} 次抽取 · 已全部放入背包",
lines, ["/背包", "/状态", "/抽卡"]);
}, cancellationToken);
public Task<ActionResult> UseAsync(long userId, int index, int quantity, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, state, ct) =>
{
ItemInstance? item = await ItemByIndexAsync(db, userId, index, ct);
if (item is null) return NoSuchItem(index);
if (await db.CharacterEquipment.AsNoTracking()
.AnyAsync(x => x.ItemInstanceId == item.Id, ct))
{
return ActionResult.Fail("该物品已装备", "没有消耗物品",
"先 /卸下 <槽位> 再使用", "/背包");
}
int amount = Math.Clamp(quantity, 1, item.Quantity);
int exp = GameplayRules.UseExp(item.Quality, amount);
state.Exp += exp;
Consume(db, item, amount);
return ActionResult.Success("🧪 使用物品",
$"{ReadName(item)} ×{amount} · 旅人经验 +{exp}",
[$"- 当前经验:{state.Exp} 等级:Lv.{state.Level}", "- 物品已扣除,未产生货币变动"],
["/背包", "/状态"]);
}, cancellationToken);
public Task<ActionResult> SalvageAsync(long userId, int index, int quantity, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, state, ct) =>
{
ItemInstance? item = await ItemByIndexAsync(db, userId, index, ct);
if (item is null) return NoSuchItem(index);
if (item.Locked || item.Bound)
{
return ActionResult.Fail("该物品已锁定或绑定", "没有分解任何物品",
"先用 /解锁 @编号,绑定装备需先 /卸下", "/背包");
}
int amount = Math.Clamp(quantity, 1, item.Quantity);
string name = ReadName(item);
long credits = GameplayRules.SalvageValue(item.Quality, amount);
ApplyCurrency(db, state, credits, "credits", "salvage", "item", item.Id.ToString(CultureInfo.InvariantCulture));
Consume(db, item, amount);
return ActionResult.Success("♻️ 分解完成",
$"{name} ×{amount} · 金币 +{credits}",
[$"- 品质:{GameplayRules.QualityName(item.Quality)} 当前金币:{state.Credits}", "- 已写入账本 ledger,可对账"],
["/背包", "/状态"]);
}, cancellationToken);
public Task<ActionResult> SetLockAsync(long userId, int index, bool locked, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, _, ct) =>
{
ItemInstance? item = await ItemByIndexAsync(db, userId, index, ct);
if (item is null) return NoSuchItem(index);
item.Locked = locked;
return ActionResult.Success(locked ? "🔒 物品已锁定" : "🔓 物品已解锁",
$"{ReadName(item)} 现在{(locked ? "不可分解/丢弃" : "可分解")}",
["- 锁定状态已写入存档"], ["/背包"]);
}, cancellationToken);
public Task<ActionResult> EquipAsync(long userId, int index, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, _, ct) =>
{
ItemInstance? item = await ItemByIndexAsync(db, userId, index, ct);
if (item is null) return NoSuchItem(index);
if (item.Bound) return ActionResult.Fail("该物品已装备", "没有重复装备", "先 /卸下 <槽位>", "/背包");
DataCharacter? main = await MainCharacterAsync(db, userId, ct);
if (main is null) return NoMainCharacter();
List<string> used = await db.CharacterEquipment.AsNoTracking()
.Where(x => x.CharacterId == main.Id).Select(x => x.Slot).ToListAsync(ct);
string? slot = GameplayRules.EquipmentSlots.FirstOrDefault(s => !used.Contains(s));
if (slot is null)
{
return ActionResult.Fail("装备槽已满", "没有装备该物品",
"先 /卸下 weapon / armor / trinket 之一", "/角色");
}
item.Bound = true;
db.CharacterEquipment.Add(new CharacterEquipment
{
CharacterId = main.Id, Slot = slot, ItemInstanceId = item.Id
});
return ActionResult.Success("🛡️ 装备成功",
$"{ReadName(item)} → {main.Name} 的 {slot} 槽",
["- 装备后自动绑定,需先卸下才能分解", "- 槽位:weapon / armor / trinket"],
["/角色", "/背包", "/状态"]);
}, cancellationToken);
public Task<ActionResult> UnequipAsync(long userId, string slot, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, _, ct) =>
{
DataCharacter? main = await MainCharacterAsync(db, userId, ct);
if (main is null) return NoMainCharacter();
CharacterEquipment? equipment = await db.CharacterEquipment
.FirstOrDefaultAsync(x => x.CharacterId == main.Id && x.Slot == slot, ct);
if (equipment is null)
{
return ActionResult.Fail("该槽位没有装备", "没有卸下任何物品",
"用 /角色 查看当前装备,槽位为 weapon / armor / trinket", "/角色");
}
ItemInstance? item = await db.ItemInstances
.FirstOrDefaultAsync(x => x.Id == equipment.ItemInstanceId && x.UserId == userId, ct);
db.CharacterEquipment.Remove(equipment);
if (item is not null) item.Bound = false;
return ActionResult.Success("📦 已卸下",
$"{slot} 槽 · {(item is null ? "未知物品" : ReadName(item))}",
["- 物品已回到背包并解除绑定"], ["/背包", "/角色"]);
}, cancellationToken);
public Task<ActionResult> SetMainAsync(long userId, int index, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, _, ct) =>
{
List<DataCharacter> characters = await db.Characters
.Where(x => x.UserId == userId).OrderBy(x => x.Id).ToListAsync(ct);
if (index <= 0 || index > characters.Count) return NoSuchCharacter(index);
foreach (DataCharacter character in characters) character.IsMain = false;
DataCharacter selected = characters[index - 1];
selected.IsMain = true;
return ActionResult.Success("⭐ 主战角色已更新", selected.Name,
["- 装备、练级、突破都作用于当前主战角色"], ["/角色", "/状态"]);
}, cancellationToken);
public Task<ActionResult> LevelUpAsync(long userId, int index, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, state, ct) =>
{
DataCharacter? character = await CharacterByIndexAsync(db, userId, index, ct);
if (character is null) return NoSuchCharacter(index);
int cap = GameplayRules.LevelCap(character.BreakLevel);
if (character.Level >= cap)
{
return ActionResult.Fail("已达当前等级上限", "没有消耗经验",
$"上限 Lv.{cap},先用 /突破 @编号 提升", "/角色");
}
long cost = GameplayRules.ExpForLevel(character.Level);
if (state.Exp < cost)
{
return ActionResult.Fail("旅人经验不足", "没有消耗经验,等级未变",
$"升级需要 {cost} 经验,当前 {state.Exp};练级或使用物品可获得经验", "/练级 @1");
}
state.Exp -= cost;
character.Level += 1;
character.Exp += cost;
return ActionResult.Success("⬆️ 角色升级", $"{character.Name} → Lv.{character.Level}",
[$"- 消耗旅人经验 {cost},剩余 {state.Exp}", $"- 当前上限 Lv.{cap}"],
["/角色", "/状态"]);
}, cancellationToken);
public Task<ActionResult> BreakAsync(long userId, int index, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, state, ct) =>
{
DataCharacter? character = await CharacterByIndexAsync(db, userId, index, ct);
if (character is null) return NoSuchCharacter(index);
int cap = GameplayRules.LevelCap(character.BreakLevel);
if (character.Level < cap)
{
return ActionResult.Fail("尚未达到当前等级上限", "没有消耗金币",
$"需要 Lv.{cap},当前 Lv.{character.Level}", "/角色");
}
long cost = GameplayRules.BreakCost(character.BreakLevel);
if (state.Credits < cost)
{
return ActionResult.Fail("金币不足", "没有消耗金币,突破等级未变",
$"需要 {cost} 金币,当前 {state.Credits}", "/签到");
}
ApplyCurrency(db, state, -cost, "credits", "break", "character", character.Id.ToString(CultureInfo.InvariantCulture));
character.BreakLevel += 1;
return ActionResult.Success("💥 突破成功",
$"{character.Name} · 突破 {character.BreakLevel} 阶 · 上限提升至 Lv.{GameplayRules.LevelCap(character.BreakLevel)}",
[$"- 消耗金币 {cost},剩余 {state.Credits}", "- 已写入账本 ledger"],
["/角色", "/状态"]);
}, cancellationToken);
public Task<ActionResult> TrainStartAsync(long userId, int index, int minutes, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, state, ct) =>
{
DataCharacter? character = await CharacterByIndexAsync(db, userId, index, ct);
if (character is null) return NoSuchCharacter(index);
if (await db.TrainingSessions.AnyAsync(x => x.UserId == userId && x.SettledAtUtc == null, ct))
{
return ActionResult.Fail("已有角色在练级", "没有重复扣除金币",
"等待结束后用 /收取练级 结算", "/收取练级");
}
if (state.Credits < GameplayRules.TrainCostCredits)
{
return ActionResult.Fail("金币不足", "没有开始练级",
$"需要 {GameplayRules.TrainCostCredits} 金币,当前 {state.Credits}", "/签到");
}
int duration = Math.Clamp(minutes, 1, GameplayRules.TrainMaxMinutes);
DateTime now = DateTime.UtcNow;
ApplyCurrency(db, state, -GameplayRules.TrainCostCredits, "credits", "train_start", "character", character.Id.ToString(CultureInfo.InvariantCulture));
db.TrainingSessions.Add(new TrainingSession
{
UserId = userId, CharacterId = character.Id,
StartedAtUtc = now, EndsAtUtc = now.AddMinutes(duration)
});
return ActionResult.Success("🏋️ 开始练级",
$"{character.Name} · {duration} 分钟后可用 /收取练级 结算",
[$"- 消耗金币 {GameplayRules.TrainCostCredits},剩余 {state.Credits}",
$"- 结算经验:{GameplayRules.TrainExpBase + GameplayRules.TrainExpPerLevel * character.Level}"],
["/收取练级", "/状态"]);
}, cancellationToken);
public Task<ActionResult> TrainClaimAsync(long userId, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, state, ct) =>
{
TrainingSession? session = await db.TrainingSessions
.Where(x => x.UserId == userId && x.SettledAtUtc == null)
.OrderBy(x => x.EndsAtUtc).FirstOrDefaultAsync(ct);
if (session is null)
{
return ActionResult.Fail("当前没有练级中的角色", "没有结算任何经验",
"先用 /练级 @编号 [分钟] 开始", "/练级 @1 1");
}
if (session.EndsAtUtc > DateTime.UtcNow)
{
int seconds = (int)Math.Ceiling((session.EndsAtUtc - DateTime.UtcNow).TotalSeconds);
return ActionResult.Fail("练级尚未结束", "没有结算任何经验",
$"还需约 {seconds} 秒,稍后再用 /收取练级", "/收取练级");
}
DataCharacter? character = await db.Characters
.FirstOrDefaultAsync(x => x.Id == session.CharacterId && x.UserId == userId, ct);
long exp = GameplayRules.TrainExpBase + GameplayRules.TrainExpPerLevel * (character?.Level ?? 1);
state.Exp += exp;
if (character is not null) character.Exp += exp;
session.SettledAtUtc = DateTime.UtcNow;
return ActionResult.Success("🎓 练级结算",
$"{(character is null ? "角色" : character.Name)} · 旅人经验 +{exp}",
[$"- 当前经验:{state.Exp} 等级:Lv.{state.Level}", "- 经验可用于 /升级 @编号"],
["/角色", "/升级 @1", "/状态"]);
}, cancellationToken);
public Task<ActionResult> SquadAsync(long userId, string operation, int index, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, _, ct) =>
{
Squad? squad = await db.Squads.FirstOrDefaultAsync(x => x.UserId == userId && x.IsActive, ct);
if (squad is null)
{
squad = new Squad { UserId = userId, Name = "主力小队", IsActive = true };
db.Squads.Add(squad);
await db.SaveChangesAsync(ct);
}
List<SquadMember> members = await db.SquadMembers
.Where(x => x.SquadId == squad.Id).OrderBy(x => x.Slot).ToListAsync(ct);
List<DataCharacter> characters = await db.Characters.AsNoTracking()
.Where(x => x.UserId == userId).OrderBy(x => x.Id).ToListAsync(ct);
string op = operation.ToLowerInvariant();
if (op is "add" or "加入")
{
if (index <= 0 || index > characters.Count) return NoSuchCharacter(index);
if (members.Any(x => x.CharacterId == characters[index - 1].Id))
{
return ActionResult.Fail("该角色已在小队中", "没有重复加入", "用 /小队 查看编成", "/小队");
}
if (members.Count >= 3)
{
return ActionResult.Fail("小队已满(3 人)", "没有加入新成员",
"先用 /小队 移除 @编号 腾出位置", "/小队");
}
int slot = Enumerable.Range(1, 3).First(s => members.All(x => x.Slot != s));
db.SquadMembers.Add(new SquadMember { SquadId = squad.Id, CharacterId = characters[index - 1].Id, Slot = slot });
return ActionResult.Success("👥 小队编成", $"{characters[index - 1].Name} 加入 {slot} 号位",
["- 小队上限 3 人"], ["/小队", "/角色"]);
}
if (op is "remove" or "移除" or "rm")
{
SquadMember? target = members.FirstOrDefault(x => x.Slot == index);
if (target is null)
{
return ActionResult.Fail("该位置没有成员", "没有移除任何角色",
"用 /小队 查看位置编号", "/小队");
}
db.SquadMembers.Remove(target);
return ActionResult.Success("👥 小队编成", $"{index} 号位已移除",
["- 其余成员位置保持不变"], ["/小队"]);
}
List<string> lines = [];
foreach (int slot in Enumerable.Range(1, 3))
{
SquadMember? member = members.FirstOrDefault(x => x.Slot == slot);
DataCharacter? character = member is null ? null : characters.FirstOrDefault(x => x.Id == member.CharacterId);
lines.Add($"- @{slot} {(character is null ? "(空)" : character.Name)}");
}
lines.Add("- /小队 加入 @编号 · /小队 移除 @位置");
return ActionResult.Success("👥 主力小队", $"{members.Count}/3 人",
lines, ["/角色", "/状态"]);
}, cancellationToken);
public Task<ActionResult> ClaimQuestAsync(long userId, int index, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, state, ct) =>
{
if (index <= 0 || index > GameplayRules.DailyQuests.Count)
{
return ActionResult.Fail("任务编号无效", "没有领取任何奖励",
"用 /每日任务 查看编号", "/每日任务");
}
(string key, string name, int target) = GameplayRules.DailyQuests[index - 1];
string date = GameplayRules.Today();
DailyQuest? quest = await db.DailyQuests
.FirstOrDefaultAsync(x => x.UserId == userId && x.QuestKey == key && x.QuestDate == date, ct);
if (quest is null || ReadProgress(quest) < target || quest.Status == 0)
{
return ActionResult.Fail($"「{name}」尚未完成", "没有发放奖励",
"完成对应行为后再领取", "/每日任务");
}
if (quest.Status == 2)
{
return ActionResult.Fail("该任务奖励已领取", "没有重复发放",
"明天再来", "/每日任务");
}
ApplyCurrency(db, state, GameplayRules.QuestRewardCredits, "credits", "quest", "quest", key);
ApplyCurrency(db, state, GameplayRules.QuestRewardDiamonds, "diamonds", "quest", "quest", key);
quest.Status = 2;
quest.ClaimedAtUtc = DateTime.UtcNow;
return ActionResult.Success("✅ 任务奖励已领取", name,
[
$"- 金币 +{GameplayRules.QuestRewardCredits} 钻石 +{GameplayRules.QuestRewardDiamonds}",
$"- 当前金币:{state.Credits} 钻石:{state.Diamonds}",
"- 已写入账本 ledger"
], ["/每日任务", "/状态"]);
}, cancellationToken);
public Task<ActionResult> RecordSimulationAsync(long userId, CancellationToken cancellationToken = default)
=> MutateAsync(userId, async (db, _, ct) =>
{
await AdvanceQuestAsync(db, userId, "simulate", ct);
return ActionResult.Success("模拟已计入每日任务", "「完成一次战斗模拟」进度 +1",
[], ["/每日任务"]);
}, cancellationToken);
// ---------------- 内部工具 ----------------
/// <summary>首次访问懒建档:player_state + 初始角色 + 初始物品 + 初始资金流水,全部一次保存。</summary>
internal static async Task<PlayerState> EnsureAsync(BotDbContext db, long userId, CancellationToken ct)
{
PlayerState? state = await db.PlayerStates.FirstOrDefaultAsync(x => x.UserId == userId, ct);
if (state is not null) return state;
state = new PlayerState
{
UserId = userId, Credits = GameplayRules.StartingCredits,
Diamonds = GameplayRules.StartingDiamonds, Level = 1,
LogonOn = GameplayRules.Today(), UpdatedAtUtc = DateTime.UtcNow
};
db.PlayerStates.Add(state);
var characterTemplates = FunGameService.Characters;
if (characterTemplates.Count > 0)
{
var template = characterTemplates[0];
db.Characters.Add(new DataCharacter
{
UserId = userId,
CatalogId = template.Id.ToString(CultureInfo.InvariantCulture),
CatalogVersion = GameplayRules.CatalogVersion,
Name = template.GetName(), Level = 1, IsMain = true,
AttrsJson = "{}", CreatedAtUtc = DateTime.UtcNow
});
}
var itemTemplates = FunGameService.AllItems;
for (int i = 0; i < Math.Min(GameplayRules.StartingItems, itemTemplates.Count); i++)
{
var template = itemTemplates[i];
db.ItemInstances.Add(new ItemInstance
{
UserId = userId, CatalogId = template.Id.ToString(CultureInfo.InvariantCulture),
Quantity = 1, Quality = 1, PayloadJson = JsonSerializer.Serialize(new { name = template.Name }),
AcquiredAtUtc = DateTime.UtcNow
});
}
db.LedgerEntries.Add(new LedgerEntry
{
UserId = userId, Currency = "credits", Delta = GameplayRules.StartingCredits,
BalanceAfter = GameplayRules.StartingCredits, Reason = "register",
RefType = "player", RefId = userId.ToString(CultureInfo.InvariantCulture),
CreatedAtUtc = DateTime.UtcNow
});
await db.SaveChangesAsync(ct);
return state;
}
/// <summary>货币变动与 ledger 必须成对出现;Add 后由调用方的 SaveChanges 一次提交。</summary>
internal static void ApplyCurrency(
BotDbContext db, PlayerState state, long delta, string currency,
string reason, string refType, string refId)
{
if (delta == 0) return;
if (currency == "diamonds") state.Diamonds += delta;
else state.Credits += delta;
long balance = currency == "diamonds" ? state.Diamonds : state.Credits;
db.LedgerEntries.Add(new LedgerEntry
{
UserId = state.UserId, Currency = currency, Delta = delta, BalanceAfter = balance,
Reason = reason, RefType = refType, RefId = refId, CreatedAtUtc = DateTime.UtcNow
});
}
internal static async Task AddItemAsync(
BotDbContext db, long userId, string name, int quality, int quantity,
CancellationToken ct, string catalogId = "gacha")
{
string payload = JsonSerializer.Serialize(new { name });
ItemInstance? stack = await db.ItemInstances.FirstOrDefaultAsync(
x => x.UserId == userId && x.CatalogId == catalogId && x.Quality == quality
&& x.PayloadJson == payload && !x.Bound && !x.Locked, ct);
if (stack is null)
{
db.ItemInstances.Add(new ItemInstance
{
UserId = userId, CatalogId = catalogId, Quantity = quantity, Quality = quality,
PayloadJson = payload, AcquiredAtUtc = DateTime.UtcNow
});
}
else
{
stack.Quantity += quantity;
}
}
internal static async Task<ItemInstance?> ItemByIndexAsync(
BotDbContext db, long userId, int index, CancellationToken ct)
=> index <= 0 ? null : await db.ItemInstances
.Where(x => x.UserId == userId).OrderBy(x => x.Id)
.Skip(index - 1).FirstOrDefaultAsync(ct);
internal static async Task<DataCharacter?> CharacterByIndexAsync(
BotDbContext db, long userId, int index, CancellationToken ct)
=> index <= 0 ? null : await db.Characters
.Where(x => x.UserId == userId).OrderBy(x => x.Id)
.Skip(index - 1).FirstOrDefaultAsync(ct);
internal static async Task<DataCharacter?> MainCharacterAsync(BotDbContext db, long userId, CancellationToken ct)
=> await db.Characters.Where(x => x.UserId == userId && x.IsMain)
.OrderBy(x => x.Id).FirstOrDefaultAsync(ct);
internal static void Consume(BotDbContext db, ItemInstance item, int amount)
{
if (item.Quantity <= amount) db.ItemInstances.Remove(item);
else item.Quantity -= amount;
}
internal static async Task AdvanceQuestAsync(BotDbContext db, long userId, string key, CancellationToken ct)
{
(string _, string _, int target) = GameplayRules.DailyQuests.First(x => x.Key == key);
string date = GameplayRules.Today();
DailyQuest? quest = await db.DailyQuests.FirstOrDefaultAsync(
x => x.UserId == userId && x.QuestKey == key && x.QuestDate == date, ct);
if (quest is null)
{
quest = new DailyQuest
{
UserId = userId, QuestKey = key, QuestDate = date,
Status = target <= 1 ? 1 : 0,
ProgressJson = JsonSerializer.Serialize(new { count = 1 })
};
db.DailyQuests.Add(quest);
return;
}
if (quest.Status == 2) return;
int count = ReadProgress(quest) + 1;
quest.ProgressJson = JsonSerializer.Serialize(new { count });
if (count >= target) quest.Status = 1;
}
internal static int ReadProgress(DailyQuest quest)
{
try
{
using JsonDocument document = JsonDocument.Parse(quest.ProgressJson);
return document.RootElement.TryGetProperty("count", out JsonElement count)
? count.GetInt32() : 0;
}
catch (JsonException) { return 0; }
}
internal static string ReadName(ItemInstance item)
{
if (string.IsNullOrWhiteSpace(item.PayloadJson)) return $"物品 {item.CatalogId}";
try
{
using JsonDocument document = JsonDocument.Parse(item.PayloadJson);
return document.RootElement.TryGetProperty("name", out JsonElement name)
? name.GetString() ?? $"物品 {item.CatalogId}"
: $"物品 {item.CatalogId}";
}
catch (JsonException) { return $"物品 {item.CatalogId}"; }
}
internal static ActionResult NoSuchItem(int index)
=> ActionResult.Fail($"背包 @ {index} 不存在", "没有改动任何物品",
"用 /背包 查看当前编号,编号按背包顺序稳定排列", "/背包");
internal static ActionResult NoSuchCharacter(int index)
=> ActionResult.Fail($"角色 @ {index} 不存在", "没有改动任何角色",
"用 /角色 查看当前编号", "/角色");
internal static ActionResult NoMainCharacter()
=> ActionResult.Fail("没有主战角色", "没有改动任何装备",
"用 /角色 查看角色,再用 /设主战 @编号 指定", "/角色");
}
+12
View File
@@ -0,0 +1,12 @@
using System.Text.Json.Serialization;
namespace OshimaBot.Models;
/// <summary>第三方/管理端凭一次性绑定码把 QQ OpenID 绑到内部用户。</summary>
public sealed class BindRequest
{
[JsonPropertyName("code")] public string Code { get; set; } = "";
[JsonPropertyName("openId")] public string OpenId { get; set; } = "";
[JsonPropertyName("provider")] public string Provider { get; set; } = "qq";
[JsonPropertyName("scene")] public string Scene { get; set; } = "c2c";
}
+8
View File
@@ -1,3 +1,4 @@
using System.Security.Claims;
using System.Text.Json;
using System.Text.Json.Serialization;
using OshimaBot.Messaging;
@@ -44,6 +45,9 @@ namespace OshimaBot.Models
/// <summary>互动事件的被动回复使用 event_id(与 msg_id 互斥);消息事件为 null。</summary>
string? EventId { get; set; }
/// <summary>S6 起由事件管线注入;第三方接口则由 ApiKey ClaimsPrincipal 注入。</summary>
ClaimsPrincipal? Principal { get; set; }
}
public sealed class ThirdPartyMessage : IBotMessage
@@ -58,6 +62,7 @@ namespace OshimaBot.Models
[JsonIgnore] public long FunGameUID { get; set; }
[JsonIgnore] public bool SendProactive { get; set; }
[JsonIgnore] public string? EventId { get; set; }
[JsonIgnore] public ClaimsPrincipal? Principal { get; set; }
[JsonIgnore] public bool IsCompleted { get; set; }
[JsonIgnore] public string Result { get; set; } = "";
}
@@ -71,6 +76,7 @@ namespace OshimaBot.Models
[JsonIgnore] public long FunGameUID { get; set; }
[JsonIgnore] public bool SendProactive { get; set; }
[JsonIgnore] public string? EventId { get; set; }
[JsonIgnore] public ClaimsPrincipal? Principal { get; set; }
public string Detail { get => Content; set => Content = value; }
public string OpenId => Author.UserOpenId;
public string AuthorOpenId => Author.UserOpenId;
@@ -87,6 +93,7 @@ namespace OshimaBot.Models
[JsonIgnore] public long FunGameUID { get; set; }
[JsonIgnore] public bool SendProactive { get; set; }
[JsonIgnore] public string? EventId { get; set; }
[JsonIgnore] public ClaimsPrincipal? Principal { get; set; }
public string Detail { get => Content; set => Content = value; }
public string OpenId => GroupOpenId;
public string AuthorOpenId => Author.MemberOpenId;
@@ -104,6 +111,7 @@ namespace OshimaBot.Models
[JsonIgnore] public long FunGameUID { get; set; }
[JsonIgnore] public bool SendProactive { get; set; }
[JsonIgnore] public string? EventId { get; set; }
[JsonIgnore] public ClaimsPrincipal? Principal { get; set; }
public string Detail { get => Data.Resolved?.ButtonData ?? ""; set { } }
public string OpenId => IsGroup ? GroupOpenId : UserOpenId;
public string AuthorOpenId => UserOpenId;
+13
View File
@@ -85,7 +85,20 @@ namespace OshimaBot.Models
{
public const string SectionName = "Server";
/// <summary>仅作首次启动引导密钥:启动时把其 SHA-256 写入 api_keys,认证阶段不再读取明文。</summary>
public string ApiKey { get; set; } = "";
public int MaximumRespawnTimes { get; set; } = 10;
/// <summary>超管白名单 QQ OpenID,与 user_roles 双轨;数据库清空后仍可恢复管理权限。</summary>
public List<string> SuperAdminOpenIds { get; set; } = [];
/// <summary>一次性绑定码有效期(秒)。</summary>
public int BindCodeTtlSeconds { get; set; } = 300;
/// <summary>S9:是否额外把回合记录写入 rounds_archive.zip。默认关闭,结果统一入 simulation_runs 表。</summary>
public bool ArchiveSimulationRounds { get; set; }
/// <summary>S9:是否把完整模拟日志写入 simulation_runs.rounds_json(供 /上次的完整日志 重启后恢复)。</summary>
public bool StoreFullSimulationLog { get; set; } = true;
}
}
+38
View File
@@ -1,8 +1,11 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using OshimaBot.Commands;
using OshimaBot.Data;
using OshimaBot.Game.Services;
using OshimaBot.Gameplay;
using OshimaBot.Messaging;
using OshimaBot.Models;
using OshimaBot.Security;
@@ -31,6 +34,7 @@ builder.Services.AddOptions<QQBotOptions>()
builder.Services.AddOptions<ServerOptions>()
.Bind(builder.Configuration.GetSection(ServerOptions.SectionName))
.Validate(options => options.MaximumRespawnTimes is >= 0 and <= 100, "最大复活次数必须在 0 到 100 之间。")
.Validate(options => options.BindCodeTtlSeconds is >= 30 and <= 3600, "绑定码有效期必须在 30 到 3600 秒之间。")
.ValidateOnStart();
builder.Services.AddOptions<DatabaseOptions>()
.Bind(builder.Configuration.GetSection(DatabaseOptions.SectionName))
@@ -38,6 +42,11 @@ builder.Services.AddOptions<DatabaseOptions>()
.ValidateOnStart();
builder.Services.AddSingleton<WebhookSignatureVerifier>();
builder.Services.AddAuthentication(ApiKeyDefaults.Scheme)
.AddScheme<AuthenticationSchemeOptions, ApiKeyAuthenticationHandler>(ApiKeyDefaults.Scheme, null);
builder.Services.AddAuthorization(options => options.AddPolicy(ApiKeyDefaults.Policy, policy => policy
.AddAuthenticationSchemes(ApiKeyDefaults.Scheme)
.RequireAuthenticatedUser()));
builder.Services.AddDbContext<BotDbContext>(options =>
{
@@ -58,15 +67,35 @@ builder.Services.AddHttpClient(QQBotService.HttpClientName, client =>
client.Timeout = TimeSpan.FromSeconds(builder.Configuration.GetValue("QQBot:RequestTimeoutSeconds", 30));
});
builder.Services.AddSingleton<IQQBotService, QQBotService>();
// S9:统计与模拟运行记录统一由 EF Core 实现;模拟器、查询服务与后台任务共享同一实例。
builder.Services.AddSingleton<EfSimulationStatisticsStore>();
builder.Services.AddSingleton<ISimulationStatisticsStore>(sp => sp.GetRequiredService<EfSimulationStatisticsStore>());
builder.Services.AddSingleton<ISimulationRunRecorder>(sp => sp.GetRequiredService<EfSimulationStatisticsStore>());
builder.Services.AddSingleton<FunGameSimulationService>();
builder.Services.AddSingleton<FunGameQueryService>();
builder.Services.AddScoped<MessageSender>();
builder.Services.AddSingleton<IUserSessionService, UserSessionService>();
builder.Services.AddSingleton<IPlayerService, PlayerService>();
builder.Services.AddSingleton<IEconomyService, EconomyService>();
builder.Services.AddSingleton(sp => new CommandDependencies(
sp.GetRequiredService<FunGameQueryService>(),
sp.GetRequiredService<FunGameSimulationService>(),
sp.GetRequiredService<IBindCodeService>(),
sp.GetRequiredService<IUserSessionService>(),
sp.GetRequiredService<IPlayerService>(),
sp.GetRequiredService<IEconomyService>(),
sp.GetRequiredService<ILoggerFactory>().CreateLogger("OshimaBot.Commands")));
builder.Services.AddSingleton(sp => CommandCatalog.Build(sp.GetRequiredService<CommandDependencies>()));
builder.Services.AddSingleton<CommandRouter>();
builder.Services.AddScoped<RainBotService>();
builder.Services.AddSingleton<BotMessageQueue>();
builder.Services.AddSingleton<IBotMessageSink>(sp => sp.GetRequiredService<BotMessageQueue>());
builder.Services.AddSingleton<IEventDeduplicationStore, EventDeduplicationStore>();
builder.Services.AddSingleton<IInteractionAckService, InteractionAckService>();
builder.Services.AddSingleton<IQQEventDispatcher, QQEventDispatcher>();
builder.Services.AddSingleton<ApiKeyAuthenticator>();
builder.Services.AddSingleton<IUserDirectory, UserDirectory>();
builder.Services.AddSingleton<IBindCodeService, BindCodeService>();
builder.Services.AddSingleton<IGatewayApiClient, GatewayApiClient>();
builder.Services.AddSingleton<IGatewaySessionStore, GatewaySessionStore>();
builder.Services.AddSingleton<IGatewayStatus, GatewayStatus>();
@@ -76,11 +105,20 @@ builder.Services.AddHostedService<QQBotGatewayClient>();
WebApplication app = builder.Build();
// S9:在首次模拟 / 统计读写前把 EF Core 仓储注入模拟器。
// InitializeStatistics 只为新仓储补齐字典;真正的数据库恢复由 DatabaseInitializer.LoadAsync 在迁移后完成。
EfSimulationStatisticsStore statisticsStore = app.Services.GetRequiredService<EfSimulationStatisticsStore>();
FunGameSimulation.UseStatisticsStore(statisticsStore);
FunGameSimulation.InitializeStatistics();
app.UseExceptionHandler();
// 仅当 QQBot:EnableWebhook=true 时对 POST /QQBot 校验 Ed25519 签名。
app.UseMiddleware<WebhookSignatureMiddleware>();
app.UseAuthentication();
app.UseAuthorization();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
+93 -22
View File
@@ -1,51 +1,122 @@
# OshimaBot WebAPI
# OshimaBot
基于 FunGame.Core v3 与 OshimaBot.Content 的独立 ASP.NET Core 游戏服务器,不依赖 FunGameServer、OshimaServers 或旧 WebAPI 插件。
基于 **FunGame.Core v3** 的 QQ 机器人 MUD 服务端。由旧版 `OshimaGameModule`(Core v2 / FunGameServer v2)迁移而来,**不再依赖 FunGameServer、MySQL 或旧插件体系**,独立部署。
- 接入:**WebSocket 单模式**(开发与部署一致);Webhook 按官方规范补齐验签 / ACK,但默认关闭。
- 存储:**SQLite + EF Core 10**,33 张业务表;用户存档、背包、经济流水、模拟统计全部入库,不再有 `saved/*.json`。
- 指令:**66 条**显式注册(零反射扫描),中文动词为主、旧版别名兼容,Markdown 4 段式回复 + 可点击指令 / 自定义按钮。
## 项目结构
- `OshimaBot`:WebAPI、RainBot、QQ Bot 与后台消息队列。
- `OshimaBot.Game`:共享的 `FunGameService`、模拟器和初始化逻辑。
- `OshimaBot.Content`:角色、技能、物品内容包。
| 项目 | 职责 |
|---|---|
| `OshimaBot` | ASP.NET Core WebAPI、QQ 事件管线、消息层、指令框架、玩法仓储、数据层 |
| `OshimaBot.Game` | `FunGameService` 内容目录、模拟器、运行态上下文、统计仓储接口 |
| `OshimaBot.Content` | 18 角色 / 118 技能 / 198 物品的内容定义 |
| `OshimaBot.Tests` | xunit 单测(128 条,含真实 SQLite 端到端) |
## 启动
目录要点:`Commands/`(显式 `CommandCatalog` + Router)、`Messaging/`(QQ Markdown / 按钮 / 发送)、`Gameplay/`(规则、玩家存档、经济)、`Data/`(DbContext / Migration)、`Security/`(验签、身份、ApiKey)、`Services/Gateway/`(WebSocket 网关)。
> `OshimaBot.slnx` 以相对路径引用仓库外的 `../../FunGame/FunGame.Core/src/FunGame.Core.csproj`;换机器或公开仓库前需改为子模块 / 包引用。
## 快速开始
在解决方案根目录执行:
```powershell
dotnet run --project OshimaBot/OshimaBot.csproj
dotnet build OshimaBot.slnx
dotnet test OshimaBot.Tests/OshimaBot.Tests.csproj
dotnet run --project OshimaBot/OshimaBot.csproj --urls http://127.0.0.1:5090
```
默认地址为 `http://localhost:5090`,开发环境 OpenAPI 文档位于 `/openapi/v1.json`。也可在解决方案目录构建全部项目:
开发环境的 OpenAPI 文档位于 `/openapi/v1.json`;`GET /health` 返回模式、网关连接状态与最近错误。端口可用 `--urls` 或环境变量覆盖。
数据库默认 `Data Source=oshimobot.db`(相对 `OshimaBot/` 内容根),启动时自动应用 Migration 并开启 WAL / 外键。需要手动管理迁移时:
```powershell
dotnet build OshimaBot.slnx
dotnet tool install dotnet-ef --version 10.0.11 --tool-path .tools
./.tools/dotnet-ef.exe migrations add <Name> --project OshimaBot/OshimaBot.csproj
./.tools/dotnet-ef.exe database update --project OshimaBot/OshimaBot.csproj
```
## 首轮接口
## Linux 部署包(Ubuntu x64)
保留旧版核心路由:
在**仓库根目录**运行 `publish-linux.bat`,一键生成框架依赖版(`--self-contained false`,**不含 .NET runtime**):
- `GET /FunGame/test`、`/FunGame/testdebug`:混战或团队模拟,支持种子、地图、初始等级等参数。
- `GET /FunGame/last?full=false`:最近模拟日志。
- `GET /FunGame/characterinfo`、`skillinfo`、`skillinfoname`、`iteminfo`、`iteminfoname`。
- `GET /FunGame/stats`、`teamstats`、`winraterank`、`ratingrank`。
- `GET /FunGame/newmagiccard`、`newmagiccardpack`。
- `POST /QQBot`:QQ Webhook;`POST /QQBot/thirdparty`:第三方机器人消息。
| 产物 | 说明 |
|---|---|
| `publish\linux-x64-fd\` | 可直接上传的部署目录,含 `OshimaBot.dll`、依赖库、`appsettings*.json` 与英文 `DEPLOY.txt` |
| `publish\OshimaBot-linux-x64-fd.zip` | 同内容压缩包,解压即用 |
新增 `GET /FunGame/status`、`characters`、`skills`、`items` 用于服务状态和目录查询。
脚本会先清理旧产物、校验仓库外的 `FunGame.Core` 引用,先尝试 `--no-restore` 发布、失败再回退到带还原的发布;完成后**剔除本机 `*.db*` / `*.pfx` / `appsettings.*.local.json` / `rounds_archive.zip`**,绝不把本地存档或凭据带进部署包。`publish/` 已被 gitignore。
目标机(Ubuntu 22.04 / 24.04 x64)需预装 **.NET 10 ASP.NET Core Runtime**,然后:
```bash
sudo unzip -o OshimaBot-linux-x64-fd.zip -d /opt/oshimobot
cd /opt/oshimobot
dotnet OshimaBot.dll --urls http://127.0.0.1:5090
curl http://127.0.0.1:5090/health
```
凭据用环境变量(`QQBot__Enabled` / `QQBot__AppId` / `QQBot__Secret` / `Server__ApiKey`)注入,不要写进 `appsettings.json`;SQLite 数据库首次启动自动创建并迁移。systemd unit 模板、备份与反向代理说明见包内 `DEPLOY.txt`。
## 配置
QQ 外部发送默认关闭。通过用户机密、环境变量或部署配置设置,不要提交真实凭据:
**不要把真实凭据提交进仓库**,用 `dotnet user-secrets` 或环境变量:
```powershell
dotnet user-secrets set "QQBot:Enabled" "true" --project OshimaBot/OshimaBot.csproj
dotnet user-secrets set "QQBot:AppId" "<app-id>" --project OshimaBot/OshimaBot.csproj
dotnet user-secrets set "QQBot:Secret" "<secret>" --project OshimaBot/OshimaBot.csproj
dotnet user-secrets set "QQBot:Secret" "<bot-secret>" --project OshimaBot/OshimaBot.csproj
dotnet user-secrets set "Server:ApiKey" "<third-party-api-key>" --project OshimaBot/OshimaBot.csproj
```
第三方接口使用 `X-API-Key: <key>` 或 `Authorization: Bearer <key>`。未配置 `Server:ApiKey` 时,第三方接口返回 503。
| 配置节 | 关键项 | 说明 |
|---|---|---|
| `QQBot` | `Enabled` / `Mode=WebSocket` / `Environment` | WS 仅在 `Enabled=true && Mode=WebSocket` 时启动;`Intents=100663296` = `GROUP_AND_C2C_EVENT \| INTERACTION` |
| | `EnableWebhook=false` | 打开后 `POST /QQBot` 才接受回调,并执行 Ed25519 入站验签 + 时间戳防重放 |
| | `GatewayUrl` / `ShardId` / `GatewayMaxReconnectDelaySeconds` | 留空 `GatewayUrl` 时走 `GET /gateway/bot` 自动发现;支持 Resume 与会话持久化 |
| `Database` | `ConnectionString` / `ApplyMigrationsOnStartup` / `ProcessedEventRetentionHours` | SQLite 单实例;事件幂等记录保留 24 小时 |
| `Server` | `ApiKey` | **仅首次启动引导**:把 SHA-256 写入 `api_keys` 后应从配置移除明文;认证只查库,密钥支持吊销 / 过期 / 分权 |
| | `BindCodeTtlSeconds` / `SuperAdminOpenIds` | 一次性绑定码 300 秒;超管白名单与 `user_roles` 双轨 |
| | `ArchiveSimulationRounds=false` | 默认不生成 `rounds_archive.zip`,复盘时再打开 |
| | `StoreFullSimulationLog=true` | 完整模拟日志写入 `simulation_runs.rounds_json`,重启后可恢复 `/上次的完整日志` |
RainBot 首轮支持帮助、角色/技能/物品查询、魔法卡预览、模拟战、统计和排行。存档、库存、交易、社团、活动等依赖旧数据库与 FunGameServer 的模块不在本轮范围内。
`Server:ApiKey` 首次启动会为第三方通道懒建一个独立内部用户;每个 ApiKey 一个账号,需要多人共用时显式指定 `api_keys.user_id`。
## HTTP 接口
| 路由 | 说明 |
|---|---|
| `GET /`、`GET /health` | 服务信息与健康检查 |
| `POST /QQBot` | Webhook 回调(默认 404;开启后验签 + op13 验证 + op12 ACK + 事件分发) |
| `POST /QQBot/thirdparty` | 第三方消息(JSON body),需 `X-API-Key` 或 `Authorization: Bearer` |
| `POST /QQBot/thirdpartytest?msg=...&openID=...` | 联调用的简化入口,同样需 ApiKey |
| `POST /QQBot/bind` | 用 6 位一次性绑定码兑换外部身份,需 ApiKey |
第三方消息自报的 `openid` 只用于回显,身份一律以 ApiKey 的 `ClaimsPrincipal` 为准。
## 指令概览
语法 `/动词 [目标] [参数]`,`/` 可省略;`@编号` 按列表顺序稳定映射,`x2` 表示数量,`p2` 翻页。`/帮助` 由注册表自动生成(11 页)。
| 批次 | 代表指令 |
|---|---|
| 系统 / 查询 | `/帮助`、`/战斗帮助`、`/取消`、`/绑定`、`/查角色`、`/查技能`、`/查物品`、`/上次的日志` |
| 战斗模拟 | `/FunGame模拟`、`/混战模拟`、`/FunGame团队模拟`、`/查个人评分`、`/查团队胜率` |
| P1 存档 | `/状态`、`/观察`、`/签到`、`/每日任务`、`/领奖 @1`、`/抽卡`、`/十连抽卡`、`/背包`、`/使用 @1`、`/分解 @1`、`/装备 @1`、`/我的角色`、`/设主战 @1`、`/升级 @1`、`/突破 @1`、`/练级 @1`、`/小队` |
| P2 经济 | `/商店`、`/购买 @1`、`/市场`、`/上架 @1 200`、`/购买市场 @1`、`/报价列表`、`/报价 @1 300`、`/锻造 @1`、`/秘境 精英`、`/决斗`、`/Boss`、`/排行榜 战绩` |
所有货币变动与物品变动在**同一事务**完成并写 `ledger_entries`;市场 / 报价成交时买卖双方各记一笔,可对账。市场上架物品会进入托管状态,成交前不出现在任何玩家背包。
## 数据与持久化
- 首访懒建档:`users` / `user_identities` / `user_roles` + `player_states`;外部 OpenID 与内部 `users.id` 解耦,支持换绑。
- **旧版 MySQL 存档不导入**(数据已丢失、OpenID→uid 不可重建);所有旅人从今天重新开始。
- 模拟统计与日志存 `simulation_statistics` / `simulation_runs`,启动时 `LoadAsync` 恢复,重启后 `/上次的日志` 与评分排行仍在;`rounds_archive.zip` 默认不再生成。
- 备份:停服后直接复制 `oshimobot.db`(含 WAL 时一并复制 `-wal` / `-shm`),或用 `VACUUM INTO` 生成一致性快照。
## 范围
玩法交付 **P0(查询 / 模拟)→ P1(存档 / 养成)→ P2(经济 / 战斗)**。P3(社团、赛马、赛事预测、探索地图、私信)按计划不在本轮范围,相关表未建。完整迁移计划与运维说明见 `docs/`(本地资料,不纳入版本控制)。
+91
View File
@@ -0,0 +1,91 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using OshimaBot.Data;
using OshimaBot.Data.Entities;
using System.Text.Encodings.Web;
namespace OshimaBot.Security;
/// <summary>数据库侧 API Key 校验:只认 api_keys 表中的 SHA-256 摘要,支持吊销/过期/按 key 分权。</summary>
public sealed class ApiKeyAuthenticator(
IServiceScopeFactory scopeFactory,
IUserDirectory directory,
ILogger<ApiKeyAuthenticator> logger)
{
public async Task<ApiKeyIdentity?> AuthenticateAsync(string key, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(key)) return null;
string hash = ApiKeyDefaults.Hash(key);
using IServiceScope scope = scopeFactory.CreateScope();
BotDbContext db = scope.ServiceProvider.GetRequiredService<BotDbContext>();
ApiKey? row = await db.ApiKeys.AsNoTracking()
.FirstOrDefaultAsync(x => x.KeyHash == hash, cancellationToken);
if (row is null || row.RevokedAtUtc is not null) return null;
if (row.ExpiresAtUtc is not null && row.ExpiresAtUtc <= DateTime.UtcNow) return null;
// S6 遗留边界:引导密钥的 user_id 为 NULL,第三方通道因此拿不到存档身份。
// 每个 ApiKey 首次认证时懒建一个独立内部用户(provider=apikey),之后走纯读路径。
long? userId = row.UserId;
if (userId is null)
{
try
{
ExternalIdentity identity = new("apikey", $"key-{row.Id}", "thirdparty");
BotUserPrincipal principal = await directory.ResolveAsync(identity, cancellationToken);
await db.ApiKeys.Where(x => x.Id == row.Id && x.UserId == null)
.ExecuteUpdateAsync(setters => setters
.SetProperty(x => x.UserId, (long?)principal.UserId), cancellationToken);
userId = principal.UserId;
logger.LogInformation("API Key 已绑定内部用户:KeyId={KeyId}, UserId={UserId}", row.Id, userId);
}
catch (Exception exception)
{
// 身份写入失败不阻断只读查询;需身份的 P1 指令会提示「身份尚未就绪」。
logger.LogWarning(exception, "API Key 身份懒注册失败:KeyId={KeyId}", row.Id);
}
}
List<int> roleValues = userId is null
? []
: await db.UserRoles.AsNoTracking()
.Where(x => x.UserId == userId.Value).Select(x => x.Role).ToListAsync(cancellationToken);
return new ApiKeyIdentity(row.Id, userId, row.Name,
ApiKeyDefaults.ParseScopes(row.ScopesJson), ApiKeyDefaults.ParseRoles(roleValues));
}
}
/// <summary>把 X-API-Key / Bearer 换成标准 ClaimsPrincipal,供 Policy 与 S7 指令权限使用。</summary>
public sealed class ApiKeyAuthenticationHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
string key = Request.Headers[ApiKeyDefaults.HeaderName].ToString();
if (string.IsNullOrWhiteSpace(key))
{
string authorization = Request.Headers.Authorization.ToString();
if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
{
key = authorization[7..].Trim();
}
}
if (string.IsNullOrWhiteSpace(key)) return AuthenticateResult.NoResult();
ApiKeyAuthenticator authenticator = Context.RequestServices.GetRequiredService<ApiKeyAuthenticator>();
ApiKeyIdentity? identity = await authenticator.AuthenticateAsync(key, Context.RequestAborted);
if (identity is null) return AuthenticateResult.Fail("API Key 无效、已吊销或已过期。");
AuthenticationTicket ticket = new(identity.ToClaimsPrincipal(ApiKeyDefaults.Scheme), Scheme.Name);
return AuthenticateResult.Success(ticket);
}
protected override Task HandleChallengeAsync(AuthenticationProperties properties)
{
Response.Headers.WWWAuthenticate = "Bearer";
return base.HandleChallengeAsync(properties);
}
}
+103
View File
@@ -0,0 +1,103 @@
using System.Security.Cryptography;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using OshimaBot.Data;
using OshimaBot.Data.Entities;
using OshimaBot.Models;
namespace OshimaBot.Security;
public enum BindRedeemStatus
{
Success,
NotFound,
Expired,
Used,
Conflict,
InvalidUser
}
public readonly record struct BindRedeemResult(BindRedeemStatus Status, long UserId = 0, string Reason = "")
{
public static BindRedeemResult Ok(long userId) => new(BindRedeemStatus.Success, userId);
public static BindRedeemResult Fail(BindRedeemStatus status, string reason) => new(status, 0, reason);
}
public interface IBindCodeService
{
int TtlSeconds { get; }
Task<string> IssueAsync(long userId, string purpose = "qq_bind", CancellationToken cancellationToken = default);
Task<BindRedeemResult> RedeemAsync(string code, ExternalIdentity identity, CancellationToken cancellationToken = default);
}
/// <summary>6 位一次性绑定码,替代旧版「获取接入码」直接回显 OpenID。</summary>
public sealed class BindCodeService(
IServiceScopeFactory scopeFactory,
IUserDirectory userDirectory,
IOptions<ServerOptions> options,
ILogger<BindCodeService> logger) : IBindCodeService
{
private readonly int _ttlSeconds = Math.Max(30, options.Value.BindCodeTtlSeconds);
public int TtlSeconds => _ttlSeconds;
public async Task<string> IssueAsync(long userId, string purpose = "qq_bind", CancellationToken cancellationToken = default)
{
using IServiceScope scope = scopeFactory.CreateScope();
BotDbContext db = scope.ServiceProvider.GetRequiredService<BotDbContext>();
for (int attempt = 0; attempt < 12; attempt++)
{
string code = RandomNumberGenerator.GetInt32(100_000, 1_000_000).ToString(System.Globalization.CultureInfo.InvariantCulture);
if (await db.BindCodes.AnyAsync(x => x.Code == code, cancellationToken)) continue;
BindCode entity = new()
{
Code = code,
UserId = userId,
Purpose = purpose,
ExpiresAtUtc = DateTime.UtcNow.AddSeconds(_ttlSeconds),
CreatedAtUtc = DateTime.UtcNow
};
db.BindCodes.Add(entity);
try
{
await db.SaveChangesAsync(cancellationToken);
logger.LogInformation("已签发绑定码:UserId={UserId}, Purpose={Purpose}, TTL={Ttl}s", userId, purpose, _ttlSeconds);
return code;
}
catch (DbUpdateException)
{
// 6 位码碰撞:把失败的实体从跟踪器里摘掉,再换一个重试。
db.Entry(entity).State = EntityState.Detached;
}
}
throw new InvalidOperationException("绑定码生成失败:连续碰撞,请稍后重试。");
}
public async Task<BindRedeemResult> RedeemAsync(string code, ExternalIdentity identity, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(code)) return BindRedeemResult.Fail(BindRedeemStatus.NotFound, "绑定码不能为空。");
using IServiceScope scope = scopeFactory.CreateScope();
BotDbContext db = scope.ServiceProvider.GetRequiredService<BotDbContext>();
BindCode? bind = await db.BindCodes.FirstOrDefaultAsync(x => x.Code == code, cancellationToken);
if (bind is null) return BindRedeemResult.Fail(BindRedeemStatus.NotFound, "绑定码不存在。");
if (bind.UsedAtUtc is not null) return BindRedeemResult.Fail(BindRedeemStatus.Used, "绑定码已被使用。");
if (bind.ExpiresAtUtc <= DateTime.UtcNow) return BindRedeemResult.Fail(BindRedeemStatus.Expired, "绑定码已过期。");
IdentityLinkStatus link = await userDirectory.LinkAsync(bind.UserId, identity, cancellationToken);
switch (link)
{
case IdentityLinkStatus.UserNotFound:
return BindRedeemResult.Fail(BindRedeemStatus.InvalidUser, "绑定码关联的用户不存在。");
case IdentityLinkStatus.Conflict:
return BindRedeemResult.Fail(BindRedeemStatus.Conflict, "该 QQ 身份已绑定其它账号。");
}
bind.UsedAtUtc = DateTime.UtcNow;
await db.SaveChangesAsync(cancellationToken);
logger.LogInformation("绑定码已兑换:UserId={UserId}, Provider={Provider}, Subject={Subject}",
bind.UserId, identity.Provider, identity.Subject);
return BindRedeemResult.Ok(bind.UserId);
}
}
+85
View File
@@ -0,0 +1,85 @@
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
namespace OshimaBot.Security;
/// <summary>角色层级:数值越大权限越高,HasRole 按层级比较。</summary>
public enum BotRole
{
Player = 0,
Operator = 1,
Admin = 2,
Owner = 3
}
/// <summary>外部身份坐标:业务代码永远不直接拿 OpenID 当用户主键。</summary>
public sealed record ExternalIdentity(string Provider, string Subject, string Scene, string? UnionSubject = null)
{
public static ExternalIdentity Qq(string openId, string scene = "c2c", string? unionOpenId = null)
=> new("qq", openId, scene, unionOpenId);
}
public sealed record BotUserPrincipal(
long UserId, string Handle, string Nickname, IReadOnlyList<BotRole> Roles, bool IsNew)
{
public const string Scheme = "QQBotEvent";
public bool HasRole(BotRole required) => Roles.Any(role => role >= required);
public ClaimsPrincipal ToClaimsPrincipal()
{
List<Claim> claims =
[
new(ClaimTypes.NameIdentifier, UserId.ToString(System.Globalization.CultureInfo.InvariantCulture)),
new(ClaimTypes.Name, string.IsNullOrWhiteSpace(Nickname) ? Handle : Nickname),
new("handle", Handle)
];
claims.AddRange(Roles.Select(role => new Claim(ClaimTypes.Role, role.ToString())));
return new ClaimsPrincipal(new ClaimsIdentity(claims, Scheme));
}
}
public sealed record ApiKeyIdentity(
long KeyId, long? UserId, string Name, IReadOnlyList<string> Scopes, IReadOnlyList<BotRole> Roles)
{
public ClaimsPrincipal ToClaimsPrincipal(string scheme)
{
List<Claim> claims =
[
new("api_key_id", KeyId.ToString(System.Globalization.CultureInfo.InvariantCulture)),
new(ClaimTypes.Name, Name)
];
if (UserId is not null)
{
claims.Add(new Claim(ClaimTypes.NameIdentifier, UserId.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)));
}
claims.AddRange(Scopes.Select(scope => new Claim("scope", scope)));
claims.AddRange(Roles.Select(role => new Claim(ClaimTypes.Role, role.ToString())));
return new ClaimsPrincipal(new ClaimsIdentity(claims, scheme));
}
}
public static class ApiKeyDefaults
{
public const string Scheme = "ApiKey";
public const string Policy = "ApiKey";
public const string HeaderName = "X-API-Key";
/// <summary>API Key 为高熵随机串,数据库只存 SHA-256 十六进制摘要,不存明文。</summary>
public static string Hash(string key)
=> Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(key))).ToLowerInvariant();
public static IReadOnlyList<string> ParseScopes(string json)
{
try { return JsonSerializer.Deserialize<List<string>>(json) ?? []; }
catch (JsonException) { return []; }
}
public static IReadOnlyList<BotRole> ParseRoles(IEnumerable<int> values)
=> values.Select(value => (BotRole)value)
.Where(Enum.IsDefined)
.Distinct()
.ToArray();
}
+9 -42
View File
@@ -1,51 +1,18 @@
using System.Security.Cryptography;
using System.Text;
using OshimaBot.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authorization;
namespace OshimaBot.Security
{
/// <summary>
/// 旧版直接比对全局明文 Server:ApiKey;S6 起改为标准 AuthenticationScheme + Policy,
/// 由 ApiKeyAuthenticationHandler 查库校验哈希,支持吊销、过期与分权。
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class RequireApiKeyAttribute : Attribute, IAuthorizationFilter
public sealed class RequireApiKeyAttribute : AuthorizeAttribute
{
public void OnAuthorization(AuthorizationFilterContext context)
public RequireApiKeyAttribute()
{
ServerOptions options = context.HttpContext.RequestServices
.GetRequiredService<IOptions<ServerOptions>>().Value;
if (string.IsNullOrWhiteSpace(options.ApiKey))
{
context.Result = new ObjectResult(new ProblemDetails
{
Title = "第三方接口尚未配置 API Key。",
Status = StatusCodes.Status503ServiceUnavailable
})
{
StatusCode = StatusCodes.Status503ServiceUnavailable
};
return;
}
string provided = context.HttpContext.Request.Headers["X-API-Key"].ToString();
if (string.IsNullOrWhiteSpace(provided))
{
string authorization = context.HttpContext.Request.Headers.Authorization.ToString();
if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
{
provided = authorization[7..].Trim();
}
}
byte[] expectedBytes = Encoding.UTF8.GetBytes(options.ApiKey);
byte[] providedBytes = Encoding.UTF8.GetBytes(provided);
if (providedBytes.Length == 0
|| providedBytes.Length != expectedBytes.Length
|| !CryptographicOperations.FixedTimeEquals(providedBytes, expectedBytes))
{
context.HttpContext.Response.Headers.WWWAuthenticate = "Bearer";
context.Result = new UnauthorizedResult();
}
AuthenticationSchemes = ApiKeyDefaults.Scheme;
Policy = ApiKeyDefaults.Policy;
}
}
}
+190
View File
@@ -0,0 +1,190 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using OshimaBot.Data;
using OshimaBot.Data.Entities;
using OshimaBot.Models;
namespace OshimaBot.Security;
public enum IdentityLinkStatus
{
Linked,
AlreadyLinked,
Conflict,
UserNotFound
}
public interface IUserDirectory
{
/// <summary>按 (provider, subject) 解析内部 users.id;首次出现懒注册建档。</summary>
Task<BotUserPrincipal> ResolveAsync(ExternalIdentity identity, CancellationToken cancellationToken = default);
/// <summary>把外部身份绑定到指定内部用户(绑定码兑换时调用)。</summary>
Task<IdentityLinkStatus> LinkAsync(long userId, ExternalIdentity identity, CancellationToken cancellationToken = default);
}
public sealed class UserDirectory(
IServiceScopeFactory scopeFactory,
IOptions<ServerOptions> options,
ILogger<UserDirectory> logger) : IUserDirectory
{
private readonly ServerOptions _options = options.Value;
public async Task<BotUserPrincipal> ResolveAsync(ExternalIdentity identity, CancellationToken cancellationToken = default)
{
try
{
return await ResolveCoreAsync(identity, cancellationToken);
}
catch (DbUpdateException)
{
// 并发懒注册撞上 UNIQUE(provider, subject):回滚后按已有身份重查。
using IServiceScope scope = scopeFactory.CreateScope();
BotDbContext db = scope.ServiceProvider.GetRequiredService<BotDbContext>();
UserIdentity? existing = await db.UserIdentities.AsNoTracking()
.FirstOrDefaultAsync(x => x.Provider == identity.Provider && x.Subject == identity.Subject, cancellationToken);
if (existing is null) throw;
return await BuildPrincipalAsync(db, existing.UserId, false, cancellationToken);
}
}
private async Task<BotUserPrincipal> ResolveCoreAsync(ExternalIdentity identity, CancellationToken cancellationToken)
{
using IServiceScope scope = scopeFactory.CreateScope();
BotDbContext db = scope.ServiceProvider.GetRequiredService<BotDbContext>();
UserIdentity? existing = await db.UserIdentities.AsNoTracking()
.FirstOrDefaultAsync(x => x.Provider == identity.Provider && x.Subject == identity.Subject, cancellationToken);
if (existing is not null)
{
DateTime now = DateTime.UtcNow;
await db.Users.Where(x => x.Id == existing.UserId)
.ExecuteUpdateAsync(setters => setters.SetProperty(x => x.LastSeenAtUtc, now), cancellationToken);
return await BuildPrincipalAsync(db, existing.UserId, false, cancellationToken);
}
await using Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction transaction =
await db.Database.BeginTransactionAsync(cancellationToken);
long userId = 0;
bool created = false;
if (!string.IsNullOrWhiteSpace(identity.UnionSubject))
{
UserIdentity? union = await db.UserIdentities.AsNoTracking()
.FirstOrDefaultAsync(x => x.UnionSubject == identity.UnionSubject, cancellationToken);
if (union is not null) userId = union.UserId;
}
if (userId == 0)
{
User user = new()
{
Handle = "U" + Guid.NewGuid().ToString("N")[..8].ToUpperInvariant(),
Nickname = "",
Status = 0,
CreatedAtUtc = DateTime.UtcNow,
LastSeenAtUtc = DateTime.UtcNow
};
db.Users.Add(user);
await db.SaveChangesAsync(cancellationToken);
userId = user.Id;
created = true;
}
db.UserIdentities.Add(new UserIdentity
{
UserId = userId,
Provider = identity.Provider,
Subject = identity.Subject,
UnionSubject = identity.UnionSubject,
Scene = identity.Scene,
CreatedAtUtc = DateTime.UtcNow
});
await EnsureRolesAsync(db, userId, identity, cancellationToken);
db.AuditLogs.Add(new AuditLog
{
ActorUserId = userId,
Action = created ? "user.register" : "identity.union_link",
Target = $"{identity.Provider}:{identity.Subject}",
PayloadJson = $"{{\"scene\":\"{identity.Scene}\"}}",
CreatedAtUtc = DateTime.UtcNow
});
await db.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);
BotUserPrincipal principal = await BuildPrincipalAsync(db, userId, created, cancellationToken);
logger.LogInformation("QQ 用户懒注册:UserId={UserId}, Handle={Handle}, Created={Created}",
userId, principal.Handle, created);
return principal;
}
public async Task<IdentityLinkStatus> LinkAsync(long userId, ExternalIdentity identity, CancellationToken cancellationToken = default)
{
using IServiceScope scope = scopeFactory.CreateScope();
BotDbContext db = scope.ServiceProvider.GetRequiredService<BotDbContext>();
if (!await db.Users.AnyAsync(x => x.Id == userId, cancellationToken)) return IdentityLinkStatus.UserNotFound;
UserIdentity? existing = await db.UserIdentities.AsNoTracking()
.FirstOrDefaultAsync(x => x.Provider == identity.Provider && x.Subject == identity.Subject, cancellationToken);
if (existing is not null)
{
return existing.UserId == userId ? IdentityLinkStatus.AlreadyLinked : IdentityLinkStatus.Conflict;
}
db.UserIdentities.Add(new UserIdentity
{
UserId = userId,
Provider = identity.Provider,
Subject = identity.Subject,
UnionSubject = identity.UnionSubject,
Scene = identity.Scene,
CreatedAtUtc = DateTime.UtcNow
});
db.AuditLogs.Add(new AuditLog
{
ActorUserId = userId,
Action = "identity.bind_code_redeem",
Target = $"{identity.Provider}:{identity.Subject}",
PayloadJson = "{}",
CreatedAtUtc = DateTime.UtcNow
});
try
{
await db.SaveChangesAsync(cancellationToken);
return IdentityLinkStatus.Linked;
}
catch (DbUpdateException)
{
return IdentityLinkStatus.Conflict;
}
}
private async Task EnsureRolesAsync(BotDbContext db, long userId, ExternalIdentity identity, CancellationToken cancellationToken)
{
HashSet<int> current = (await db.UserRoles.AsNoTracking()
.Where(x => x.UserId == userId).Select(x => x.Role).ToListAsync(cancellationToken)).ToHashSet();
if (current.Add((int)BotRole.Player))
{
db.UserRoles.Add(new UserRole { UserId = userId, Role = (int)BotRole.Player });
}
// 超管双轨:配置白名单 OpenID + user_roles,避免数据库被清空后彻底失去管理能力。
if (string.Equals(identity.Provider, "qq", StringComparison.Ordinal)
&& _options.SuperAdminOpenIds.Contains(identity.Subject, StringComparer.Ordinal)
&& current.Add((int)BotRole.Owner))
{
db.UserRoles.Add(new UserRole { UserId = userId, Role = (int)BotRole.Owner });
logger.LogInformation("按白名单授予 Owner:UserId={UserId}", userId);
}
await db.SaveChangesAsync(cancellationToken);
}
private static async Task<BotUserPrincipal> BuildPrincipalAsync(
BotDbContext db, long userId, bool isNew, CancellationToken cancellationToken)
{
User user = await db.Users.AsNoTracking().FirstAsync(x => x.Id == userId, cancellationToken);
List<int> roles = await db.UserRoles.AsNoTracking()
.Where(x => x.UserId == userId).Select(x => x.Role).ToListAsync(cancellationToken);
return new BotUserPrincipal(user.Id, user.Handle, user.Nickname, ApiKeyDefaults.ParseRoles(roles), isNew);
}
}
+9 -9
View File
@@ -7,7 +7,7 @@ namespace OshimaBot.Services
{
public sealed record CatalogEntry(long Id, string Name, string Category);
public sealed class FunGameQueryService(FunGameSimulationService simulations)
public sealed class FunGameQueryService(ISimulationStatisticsStore statistics)
{
public IReadOnlyList<CatalogEntry> GetCharacters()
=> [.. FunGameService.Characters.Select(character => new CatalogEntry(character.Id, character.GetName(), "角色"))];
@@ -84,14 +84,14 @@ namespace OshimaBot.Services
=> FunGameService.GenerateMagicCardPack(Random.Shared, 3)?.ToString(false, true) ?? "";
public Task<string> GetStatsAsync(int id, bool team, CancellationToken cancellationToken = default)
=> simulations.ReadAsync(() =>
=> Task.FromResult(statistics.Read(store =>
{
Character? character = FunGameService.Characters.ElementAtOrDefault(id - 1);
if (id <= 0 || character is null) return "";
Dictionary<Character, CharacterStatistics> source = team
? FunGameSimulation.TeamCharacterStatistics
: FunGameSimulation.CharacterStatistics;
? store.TeamCharacterStatistics
: store.CharacterStatistics;
if (!source.TryGetValue(character, out CharacterStatistics? stats)) return "";
StringBuilder builder = new();
@@ -107,14 +107,14 @@ namespace OshimaBot.Services
builder.AppendLine($"存活回合:{stats.LiveRound} / 行动回合:{stats.ActionTurn} / 存活时长:{stats.LiveTime:0.##}");
builder.Append($"决策数:{stats.TurnDecisions} / 决策点:{stats.UseDecisionPoints}");
return builder.ToString();
}, cancellationToken);
}));
public Task<List<string>> GetRankingAsync(bool team, bool byRating, CancellationToken cancellationToken = default)
=> simulations.ReadAsync(() =>
=> Task.FromResult(statistics.Read(store =>
{
Dictionary<Character, CharacterStatistics> source = team
? FunGameSimulation.TeamCharacterStatistics
: FunGameSimulation.CharacterStatistics;
? store.TeamCharacterStatistics
: store.CharacterStatistics;
IEnumerable<KeyValuePair<Character, CharacterStatistics>> ordered = byRating
? source.OrderByDescending(entry => entry.Value.Rating)
: source.OrderByDescending(entry => entry.Value.Winrate);
@@ -131,7 +131,7 @@ namespace OshimaBot.Services
result.Add(builder.ToString());
}
return result;
}, cancellationToken);
}));
private static Character CreateDemoCharacter()
{
+51 -21
View File
@@ -1,6 +1,7 @@
using System.Text.Json;
using Microsoft.Extensions.Options;
using OshimaBot.Game.Services;
using OshimaBot.Models;
using Microsoft.Extensions.Options;
namespace OshimaBot.Services
{
@@ -20,6 +21,9 @@ namespace OshimaBot.Services
public int NormalAttackLevel { get; set; } = 2;
public long FixedWeaponId { get; set; }
public int? Seed { get; set; }
/// <summary>S9:触发模拟的内部用户,写入 simulation_runs.user_id;第三方/匿名请求为 null。</summary>
public long? UserId { get; set; }
}
public sealed record SimulationResult(
@@ -28,12 +32,24 @@ namespace OshimaBot.Services
DateTimeOffset CompletedAt,
TimeSpan Duration);
public sealed class FunGameSimulationService(IOptions<ServerOptions> options)
/// <summary>
/// S8 前置:每次运行创建独立的 SimulationRunContext,静态运行态不再进程级共享。
/// S9:一局结束后把结果与统计写入 SQLite(simulation_runs / simulation_statistics),
/// 内存仓储只作为模拟器运行期的工作副本,重启后由 LoadAsync 恢复。
/// 引擎仍串行执行(FunGame.Core 目录为只读共享)。
/// </summary>
public sealed class FunGameSimulationService(
ISimulationStatisticsStore statistics,
ISimulationRunRecorder recorder,
IOptions<ServerOptions> options,
ILogger<FunGameSimulationService> logger)
{
private readonly SemaphoreSlim _gate = new(1, 1);
private readonly int _maximumRespawnTimes = options.Value.MaximumRespawnTimes;
private readonly bool _archiveRounds = options.Value.ArchiveSimulationRounds;
private readonly bool _storeFullLog = options.Value.StoreFullSimulationLog;
public bool IsRunning => FunGameSimulation.IsRuning;
public bool IsRunning => _gate.CurrentCount == 0;
public async Task<SimulationResult?> RunAsync(SimulationRequest request, CancellationToken cancellationToken = default)
{
@@ -42,7 +58,10 @@ namespace OshimaBot.Services
DateTimeOffset startedAt = DateTimeOffset.UtcNow;
try
{
FunGameSimulation.SeedOverride = request.Seed is > 0 ? request.Seed : null;
SimulationRunContext context = new()
{
SeedOverride = request.Seed is > 0 ? request.Seed : null
};
SimulationOptions simulationOptions = new()
{
PrintOut = false,
@@ -58,44 +77,55 @@ namespace OshimaBot.Services
SkillLevel = Math.Clamp(request.SkillLevel, 1, 8),
NormalAttackLevel = Math.Clamp(request.NormalAttackLevel, 1, 8),
EnablePeriodicDrop = request.EnablePeriodicDrop,
FixedWeaponId = request.FixedWeaponId
FixedWeaponId = request.FixedWeaponId,
ArchiveRounds = _archiveRounds
};
List<string> messages = await Task.Run(
() => FunGameSimulation.StartSimulationGame(simulationOptions),
CancellationToken.None);
() => FunGameSimulation.StartSimulationGame(simulationOptions, context),
cancellationToken);
return new SimulationResult(
messages,
FunGameSimulation.Seed,
DateTimeOffset.UtcNow,
DateTimeOffset.UtcNow - startedAt);
DateTimeOffset finishedAt = DateTimeOffset.UtcNow;
SimulationResult result = new(messages, context.Seed, finishedAt, finishedAt - startedAt);
await PersistRunAsync(request, context.Seed, messages, startedAt, finishedAt, cancellationToken);
return result;
}
finally
{
FunGameSimulation.SeedOverride = null;
_gate.Release();
}
}
public async Task<T> ReadAsync<T>(Func<T> reader, CancellationToken cancellationToken = default)
/// <summary>持久化失败只记日志,不丢弃已经算完的模拟结果。</summary>
private async Task PersistRunAsync(
SimulationRequest request, int seed, IReadOnlyList<string> messages,
DateTimeOffset startedAt, DateTimeOffset finishedAt, CancellationToken cancellationToken)
{
await _gate.WaitAsync(cancellationToken);
try
{
return reader();
IReadOnlyList<string> full = _storeFullLog
? statistics.Read(store => (IReadOnlyList<string>)[.. store.LastFullRecord])
: [];
await recorder.RecordAsync(new SimulationRunRecord(
request.UserId, seed, JsonSerializer.Serialize(request), messages, full,
startedAt, finishedAt), cancellationToken);
await statistics.PersistAsync(cancellationToken);
}
finally
catch (Exception exception)
{
_gate.Release();
logger.LogWarning(exception, "模拟结果入库失败:Seed={Seed}", seed);
}
}
/// <summary>读锁内读取仓储;保留给外部只读调用。</summary>
public Task<T> ReadAsync<T>(Func<T> reader, CancellationToken cancellationToken = default)
=> Task.FromResult(statistics.Read(_ => reader()));
public Task<IReadOnlyList<string>> GetLastAsync(bool full, CancellationToken cancellationToken = default)
=> ReadAsync(() =>
=> Task.FromResult(statistics.Read(store =>
{
IReadOnlyList<string> source = full ? FunGameSimulation.LastFullRecord : FunGameSimulation.LastRecord;
IReadOnlyList<string> source = full ? store.LastFullRecord : store.LastRecord;
return (IReadOnlyList<string>)[.. source];
}, cancellationToken);
}));
}
}
+22
View File
@@ -1,6 +1,7 @@
using System.Text.Json;
using OshimaBot.Messaging;
using OshimaBot.Models;
using OshimaBot.Security;
namespace OshimaBot.Services;
@@ -47,6 +48,7 @@ public sealed class QQEventDispatcher(
IEventDeduplicationStore deduplication,
IInteractionAckService interactionAck,
IBotMessageSink sink,
IUserDirectory userDirectory,
ILogger<QQEventDispatcher> logger) : IQQEventDispatcher
{
private const string InteractionPrefix = "INTERACTION_CREATE:";
@@ -98,6 +100,7 @@ public sealed class QQEventDispatcher(
? payload.Id
: null;
await AttachIdentityAsync(message, eventKey, cancellationToken);
await sink.QueueAsync(message, cancellationToken);
await deduplication.MarkProcessedAsync(eventKey, 0, cancellationToken);
logger.LogInformation("已接收 QQ {EventType} 事件:Source={Source}, EventId={EventId}, MessageId={MessageId}",
@@ -117,6 +120,25 @@ public sealed class QQEventDispatcher(
}
}
private async Task AttachIdentityAsync(IBotMessage message, string eventKey, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(message.AuthorOpenId)) return;
ExternalIdentity identity = ExternalIdentity.Qq(message.AuthorOpenId, message.IsGroup ? "group" : "c2c");
try
{
BotUserPrincipal principal = await userDirectory.ResolveAsync(identity, cancellationToken);
message.FunGameUID = principal.UserId;
message.Principal = principal.ToClaimsPrincipal();
logger.LogDebug("QQ 身份解析完成:EventId={EventId}, UserId={UserId}, IsNew={IsNew}",
eventKey, principal.UserId, principal.IsNew);
}
catch (Exception exception)
{
// 用户库暂不可用时仍允许查询类指令工作;S7 起需要身份的指令再单独拦截。
logger.LogWarning(exception, "QQ 用户身份解析失败:EventId={EventId},按未认证消息继续投递。", eventKey);
}
}
private static string ResolveEventKey(Payload payload, QQEventSource source)
{
if (!string.IsNullOrWhiteSpace(payload.Id)) return payload.Id;
+19 -191
View File
@@ -1,200 +1,28 @@
using System.Text;
using OshimaBot.Game.Services;
using OshimaBot.Commands;
using OshimaBot.Messaging;
using OshimaBot.Models;
using FunGame.Core.Library.Constant;
namespace OshimaBot.Services
namespace OshimaBot.Services;
/// <summary>
/// S7 起指令层只负责「路由结果 → 发送」:指令注册、解析、权限、审计都在 Commands/ 下。
/// 保留 Handler / HandlerByConsole 两个入口,Webhook、WS、第三方 HTTP 无需改动。
/// </summary>
public sealed class RainBotService(CommandRouter router, MessageSender messageSender)
{
public sealed class RainBotService(
FunGameQueryService queries,
FunGameSimulationService simulations,
MessageSender messageSender,
ILogger<RainBotService> logger)
public async Task<bool> Handler(IBotMessage message, OtherData data, CancellationToken cancellationToken = default)
{
public async Task<bool> Handler(IBotMessage message, OtherData data, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(message);
string command = message.Detail.Trim();
if (command.StartsWith('/')) command = command[1..].Trim();
message.Detail = command;
if (command.Length == 0) return false;
ArgumentNullException.ThrowIfNull(message);
message.Detail = message.Detail?.Trim() ?? "";
if (message.Detail.Length == 0) return false;
BotReply? reply = await RouteCommandAsync(message, command, cancellationToken);
if (reply is null) return false;
BotReply? reply = await router.RouteAsync(message, data, cancellationToken);
if (reply is null) return false;
await SendAsync(message, reply, cancellationToken);
return true;
}
public Task<bool> HandlerByConsole(IBotMessage message, OtherData data, CancellationToken cancellationToken = default)
=> Handler(message, data, cancellationToken);
private async Task<BotReply?> RouteCommandAsync(IBotMessage message, string command, CancellationToken cancellationToken)
{
if (command == "帮助") return BotReply.FromMarkdown(CreateHelp());
if (command is "战斗帮助" or "角色帮助" or "物品帮助") return BotReply.FromMarkdown(CreateBattleHelp());
if (command == "重置状态") return "当前版本采用无状态指令路由,无需重置指令状态。";
if (command == "获取接入码" && !message.IsGroup) return $"你的接入码为 {message.AuthorOpenId},请妥善保存!";
if (command == "查询服务器启动时间") return $"OshimaBot 启动时间(UTC):{FunGameRuntime.StartedAt:yyyy-MM-dd HH:mm:ss}";
if (command == "预览魔法卡") return queries.GenerateMagicCard();
if (command == "预览魔法卡包") return queries.GenerateMagicCardPack();
if (TryArgument(command, "查角色", out string character))
return RequireResult(queries.GetCharacterInfo(character), "未找到角色。用法:查角色 <编号或名称>");
if (TryArgument(command, "查技能", out string skill))
{
string result = long.TryParse(skill, out long id)
? queries.GetSkillInfo(id, null)
: queries.GetSkillInfo(null, skill);
return RequireResult(result, "未找到技能。用法:查技能 <编号或名称>");
}
if (TryArgument(command, "查物品", out string item))
{
string result = long.TryParse(item, out long id)
? queries.GetItemInfo(id, null)
: queries.GetItemInfo(null, item);
return RequireResult(result, "未找到物品。用法:查物品 <编号或名称>");
}
if (TryArgument(command, "查团队数据", out string teamStats) && int.TryParse(teamStats, out int teamStatsId))
return RequireResult(await queries.GetStatsAsync(teamStatsId, true, cancellationToken), "未找到角色团队统计。");
if (TryArgument(command, "查数据", out string stats) && int.TryParse(stats, out int statsId))
return RequireResult(await queries.GetStatsAsync(statsId, false, cancellationToken), "未找到角色统计。");
if (command.StartsWith("查团队胜率", StringComparison.OrdinalIgnoreCase))
return MergeRanking(await queries.GetRankingAsync(true, false, cancellationToken));
if (command.StartsWith("查个人胜率", StringComparison.OrdinalIgnoreCase))
return MergeRanking(await queries.GetRankingAsync(false, false, cancellationToken));
if (command.StartsWith("查团队评分", StringComparison.OrdinalIgnoreCase))
return MergeRanking(await queries.GetRankingAsync(true, true, cancellationToken));
if (command.StartsWith("查个人评分", StringComparison.OrdinalIgnoreCase))
return MergeRanking(await queries.GetRankingAsync(false, true, cancellationToken));
if (command == "上次的完整日志")
return MergeToMarkdown("上次的完整日志:", await simulations.GetLastAsync(true, cancellationToken));
if (command == "上次的日志")
return MergeToMarkdown("上次的模拟日志:", await simulations.GetLastAsync(false, cancellationToken));
if (command.StartsWith("团队调试模拟", StringComparison.OrdinalIgnoreCase))
return await RunSimulationAsync(new SimulationRequest { IsTeam = true, HasMap = true, IsDebug = true, ShowAll = true, MaxRespawnTimesMix = 0 }, cancellationToken);
if (command.StartsWith("团队地图模拟", StringComparison.OrdinalIgnoreCase))
return await RunSimulationAsync(new SimulationRequest { IsTeam = true, HasMap = true }, cancellationToken);
if (command.StartsWith("FunGame团队模拟", StringComparison.OrdinalIgnoreCase))
return await RunSimulationAsync(new SimulationRequest { IsTeam = true }, cancellationToken);
if (command.StartsWith("个人地图模拟", StringComparison.OrdinalIgnoreCase))
return await RunSimulationAsync(new SimulationRequest { HasMap = true, MaxRespawnTimesMix = 0 }, cancellationToken);
if (TryArgument(command, "混战模拟", out string respawn))
return await RunSimulationAsync(new SimulationRequest
{
MaxRespawnTimesMix = int.TryParse(respawn, out int times) ? times : 1
}, cancellationToken);
if (command.StartsWith("FunGame模拟", StringComparison.OrdinalIgnoreCase))
return await RunSimulationAsync(new SimulationRequest { MaxRespawnTimesMix = 0 }, cancellationToken);
if (command is "存档帮助" or "玩法帮助" or "社团帮助" or "活动帮助" or "商店帮助")
return "该模块尚未迁移到 OshimaBot。首轮已开放角色、物品、战斗查询与模拟指令。";
return null;
}
private async Task<BotReply> RunSimulationAsync(SimulationRequest request, CancellationToken cancellationToken)
{
SimulationResult? result = await simulations.RunAsync(request, cancellationToken);
if (result is null) return "游戏正在模拟中,请勿重复请求!";
logger.LogInformation("RainBot 模拟完成:Seed={Seed},Duration={Duration}", result.Seed, result.Duration);
return MergeToMarkdown($"模拟结果如下(种子:{result.Seed}):", result.Messages);
}
private Task SendAsync(IBotMessage message, BotReply reply, CancellationToken cancellationToken)
=> messageSender.SendAsync(message, reply, cancellationToken);
public BotReply MergeToMarkdown(string subtitle, IReadOnlyCollection<string> messages)
{
if (messages.Count == 0) return "暂无记录,请先运行一次模拟。";
List<string> selected = [.. messages];
if (selected.Count > 30)
{
selected = [.. selected[..15], $"\r\n……已省略 {messages.Count - 30} 段日志……\r\n", .. selected[^15..]];
}
StringBuilder content = new();
content.AppendLine(subtitle).AppendLine("```");
foreach (string message in selected)
{
if (content.Length > 48_000)
{
content.AppendLine("……日志过长,后续内容已省略……");
break;
}
content.AppendLine(message);
}
content.AppendLine("```");
return BotReply.FromMarkdown(content.ToString());
}
public List<string> MergeMessages(IReadOnlyCollection<string> messages)
{
const int groupSize = 5;
List<string> merged = [];
List<string> source = [.. messages];
if (source.Count > 20) source = [source[0], .. source[^20..]];
for (int index = 0; index < source.Count; index += groupSize)
{
merged.Add(string.Join("\r\n", source.Skip(index).Take(groupSize)));
}
return merged.Count >= 3 ? [merged[0], .. merged[^2..]] : merged;
}
public BotReply CreateMarkdownFromText(string text) => BotReply.FromMarkdown(text);
private static BotReply MergeRanking(IReadOnlyCollection<string> ranking)
=> ranking.Count == 0 ? "暂无统计数据。" : string.Join("\r\n\r\n", ranking);
private static BotReply RequireResult(string result, string fallback)
=> string.IsNullOrWhiteSpace(result) ? fallback : result;
private static bool TryArgument(string command, string prefix, out string argument)
{
argument = "";
if (!command.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) return false;
argument = command[prefix.Length..].Trim();
return true;
}
private static string CreateHelp() => $"""
欢迎使用《筽祀牻》OshimaBot 服务器!
核心库版本:{FunGameInfo.FunGame_Version}
首轮指令:
1. 查角色 <编号或名称>
2. 查技能 <编号或名称>
3. 查物品 <编号或名称>
4. 预览魔法卡 / 预览魔法卡包
5. 查数据 <编号> / 查团队数据 <编号>
6. 查个人胜率 / 查团队胜率 / 查个人评分 / 查团队评分
7. 混战模拟 [复活次数] / FunGame模拟 / FunGame团队模拟
8. 个人地图模拟 / 团队地图模拟 / 团队调试模拟
9. 上次的日志 / 上次的完整日志
10. 查询服务器启动时间
存档、社团、活动和商店等旧模块将在后续迁移。
""";
private static string CreateBattleHelp() => """
《筽祀牻》战斗指令
1. 查角色 <编号或名称>:查看满级角色资料。
2. 查技能 <编号或名称>:查看 1、2 级与满级技能资料。
3. 查物品 <编号或名称>:查看物品资料。
4. 混战模拟 [复活次数]:开始个人混战模拟。
5. FunGame模拟:开始无复活混战模拟。
6. FunGame团队模拟:开始团队模拟。
7. 个人地图模拟 / 团队地图模拟:开始带地图的模拟。
8. 团队调试模拟:输出团队地图调试模拟。
9. 查数据 / 查团队数据:查看角色累计统计。
10. 查个人胜率 / 查团队胜率 / 查个人评分 / 查团队评分:查看排行。
11. 上次的日志 / 上次的完整日志:查看最近模拟记录。
""";
await messageSender.SendAsync(message, reply, cancellationToken);
return true;
}
public Task<bool> HandlerByConsole(IBotMessage message, OtherData data, CancellationToken cancellationToken = default)
=> Handler(message, data, cancellationToken);
}
+189
View File
@@ -0,0 +1,189 @@
using System.Globalization;
using System.Text.Encodings.Web;
using System.Text.Json;
using FunGame.Core.Entity;
using CoreCharacter = FunGame.Core.Entity.Character;
using Microsoft.EntityFrameworkCore;
using OshimaBot.Data;
using OshimaBot.Data.Entities;
using OshimaBot.Game.Services;
namespace OshimaBot.Services;
/// <summary>一局模拟的入库快照。</summary>
public sealed record SimulationRunRecord(
long? UserId,
int Seed,
string OptionsJson,
IReadOnlyList<string> Messages,
IReadOnlyList<string> FullMessages,
DateTimeOffset StartedAt,
DateTimeOffset FinishedAt);
public interface ISimulationRunRecorder
{
Task<long> RecordAsync(SimulationRunRecord record, CancellationToken cancellationToken = default);
}
/// <summary>
/// S9:用 SQLite 持久化模拟统计与最近日志,替代进程内字典 + rounds_archive.zip。
/// 模拟器仍直接读写内存字典(FunGame.Core 的统计对象是纯 POCO,可无损 JSON 往返),
/// 在每次运行结束时 PersistAsync 落库;应用启动时 LoadAsync 恢复,重启后状态不丢。
/// 同时实现 ISimulationRunRecorder,把每局结果写入 simulation_runs。
/// </summary>
public sealed class EfSimulationStatisticsStore(
IServiceScopeFactory scopeFactory,
ILogger<EfSimulationStatisticsStore> logger) : ISimulationStatisticsStore, ISimulationRunRecorder
{
// 数据库里保留可读中文,便于直接查表复盘。
private static readonly JsonSerializerOptions JsonOptions = new()
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
private readonly Lock _sync = new();
public Dictionary<CoreCharacter, CharacterStatistics> CharacterStatistics { get; } = [];
public Dictionary<CoreCharacter, CharacterStatistics> TeamCharacterStatistics { get; } = [];
public IReadOnlyList<string> LastRecord { get; set; } = [];
public IReadOnlyList<string> LastFullRecord { get; set; } = [];
/// <summary>
/// 由 FunGameRuntime 初始化时调用:只补齐缺失角色,不清空已加载的数据。
/// 真正的覆盖式恢复在应用启动迁移完成后由 LoadAsync 执行。
/// </summary>
public void Reset(IEnumerable<CoreCharacter> characters)
{
lock (_sync)
{
foreach (CoreCharacter character in characters)
{
CharacterStatistics.TryAdd(character, new CharacterStatistics());
TeamCharacterStatistics.TryAdd(character, new CharacterStatistics());
}
}
}
public T Read<T>(Func<ISimulationStatisticsStore, T> reader)
{
lock (_sync) return reader(this);
}
/// <summary>启动迁移完成后调用:从数据库恢复统计字典与最近一次模拟日志。</summary>
public async Task LoadAsync(CancellationToken cancellationToken = default)
{
using IServiceScope scope = scopeFactory.CreateScope();
BotDbContext db = scope.ServiceProvider.GetRequiredService<BotDbContext>();
List<SimulationStatistic> rows = await db.SimulationStatistics.AsNoTracking()
.ToListAsync(cancellationToken);
Dictionary<(string Scope, string CatalogId), CharacterStatistics> loaded = [];
foreach (SimulationStatistic row in rows)
{
CharacterStatistics? stats = DeserializeStats(row.StatsJson);
if (stats is not null) loaded[(row.Scope, row.CatalogId)] = stats;
}
SimulationRun? last = await db.SimulationRuns.AsNoTracking()
.OrderByDescending(x => x.Id).FirstOrDefaultAsync(cancellationToken);
lock (_sync)
{
CharacterStatistics.Clear();
TeamCharacterStatistics.Clear();
foreach (CoreCharacter character in FunGameService.Characters)
{
string id = character.Id.ToString(CultureInfo.InvariantCulture);
CharacterStatistics[character] = loaded.GetValueOrDefault(("character", id))
?? new CharacterStatistics();
TeamCharacterStatistics[character] = loaded.GetValueOrDefault(("team", id))
?? new CharacterStatistics();
}
if (last is not null)
{
LastRecord = DeserializeMessages(last.ResultJson);
LastFullRecord = DeserializeMessages(last.RoundsJson);
}
}
logger.LogInformation("模拟统计已从数据库恢复:{Rows} 条统计行,最近日志 {Lines} 行",
rows.Count, LastRecord.Count);
}
/// <summary>一局结束后把两个统计字典 upsert 到 simulation_statistics。</summary>
public async Task PersistAsync(CancellationToken cancellationToken = default)
{
List<(string Scope, string CatalogId, string Json)> snapshot = [];
lock (_sync)
{
snapshot.AddRange(CharacterStatistics.Select(pair => (
"character", pair.Key.Id.ToString(CultureInfo.InvariantCulture),
JsonSerializer.Serialize(pair.Value, JsonOptions))));
snapshot.AddRange(TeamCharacterStatistics.Select(pair => (
"team", pair.Key.Id.ToString(CultureInfo.InvariantCulture),
JsonSerializer.Serialize(pair.Value, JsonOptions))));
}
if (snapshot.Count == 0) return;
using IServiceScope scope = scopeFactory.CreateScope();
BotDbContext db = scope.ServiceProvider.GetRequiredService<BotDbContext>();
foreach ((string scopeKey, string catalogId, string json) in snapshot)
{
SimulationStatistic? row = await db.SimulationStatistics.FirstOrDefaultAsync(
x => x.Scope == scopeKey && x.CatalogId == catalogId, cancellationToken);
if (row is null)
{
db.SimulationStatistics.Add(new SimulationStatistic
{
Scope = scopeKey, CatalogId = catalogId, StatsJson = json,
UpdatedAtUtc = DateTime.UtcNow
});
}
else
{
row.StatsJson = json;
row.UpdatedAtUtc = DateTime.UtcNow;
}
}
await db.SaveChangesAsync(cancellationToken);
}
/// <summary>把一局结果写入 simulation_runs,并同步内存中的「上次的日志」。</summary>
public async Task<long> RecordAsync(SimulationRunRecord record, CancellationToken cancellationToken = default)
{
using IServiceScope scope = scopeFactory.CreateScope();
BotDbContext db = scope.ServiceProvider.GetRequiredService<BotDbContext>();
SimulationRun run = new()
{
UserId = record.UserId,
Seed = record.Seed.ToString(CultureInfo.InvariantCulture),
OptionsJson = record.OptionsJson,
ResultJson = JsonSerializer.Serialize(record.Messages, JsonOptions),
RoundsJson = JsonSerializer.Serialize(record.FullMessages, JsonOptions),
StartedAtUtc = record.StartedAt.UtcDateTime,
FinishedAtUtc = record.FinishedAt.UtcDateTime
};
db.SimulationRuns.Add(run);
await db.SaveChangesAsync(cancellationToken);
lock (_sync)
{
LastRecord = [.. record.Messages];
LastFullRecord = [.. record.FullMessages];
}
return run.Id;
}
private static CharacterStatistics? DeserializeStats(string json)
{
if (string.IsNullOrWhiteSpace(json)) return null;
try { return JsonSerializer.Deserialize<CharacterStatistics>(json); }
catch (JsonException) { return null; }
}
private static IReadOnlyList<string> DeserializeMessages(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return [];
try { return JsonSerializer.Deserialize<List<string>>(json) ?? []; }
catch (JsonException) { return []; }
}
}
+5 -1
View File
@@ -30,6 +30,10 @@
},
"Server": {
"ApiKey": "",
"MaximumRespawnTimes": 10
"MaximumRespawnTimes": 10,
"SuperAdminOpenIds": [],
"BindCodeTtlSeconds": 300,
"ArchiveSimulationRounds": false,
"StoreFullSimulationLog": true
}
}
+191
View File
@@ -0,0 +1,191 @@
@echo off
:: ============================================================
:: 生成 OshimaBot 的 Ubuntu linux-x64 框架依赖部署包 (fd)
::
:: 用法:在仓库根目录执行 publish-linux.bat(双击亦可)
::
:: 产物结构:
:: publish\linux-x64-fd\ 可直接上传的部署目录
:: OshimaBot.dll + 全部依赖 dll + appsettings*.json
:: DEPLOY.txt 英文部署说明:环境变量 / systemd / 备份
:: publish\OshimaBot-linux-x64-fd.zip 同内容压缩包
::
:: 目标机(Ubuntu 22.04 / 24.04 x64)需自行安装 .NET 10 ASP.NET Core Runtime,
:: 本包不含 .NET runtime,也不含本机 SQLite 数据库与任何凭据:
:: dotnet OshimaBot.dll --urls http://127.0.0.1:5090
::
:: 注意:本脚本用 goto 标签做错误处理(cmd 解析带转义括号的多行
:: if/else 分支块会失效,两分支都执行),不要改成多行 if/else。
:: ============================================================
setlocal
chcp 936 >nul 2>nul
cd /d "%~dp0"
set "OUT=publish\linux-x64-fd"
set "ZIP=publish\OshimaBot-linux-x64-fd.zip"
set "DEPLOY=%OUT%\DEPLOY.txt"
echo ==^> 1/6 检查构建环境
where dotnet >nul 2>nul
if errorlevel 1 goto err_no_dotnet
if not exist "OshimaBot\OshimaBot.csproj" goto err_no_project
if not exist "..\..\FunGame\FunGame.Core\src\FunGame.Core.csproj" goto err_no_core
dotnet --version
echo ==^> 2/6 清理旧发布产物
if exist "%OUT%" rmdir /s /q "%OUT%"
if exist "%ZIP%" del /f /q "%ZIP%"
if not exist publish mkdir publish
echo ==^> 3/6 发布 linux-x64 框架依赖版 --self-contained false
dotnet publish OshimaBot\OshimaBot.csproj -c Release -r linux-x64 --self-contained false -o "%OUT%" --no-restore
if not errorlevel 1 goto step4
echo --no-restore 失败,清理半成品后回退到带还原的发布
if exist "%OUT%" rmdir /s /q "%OUT%"
dotnet publish OshimaBot\OshimaBot.csproj -c Release -r linux-x64 --self-contained false -o "%OUT%"
if errorlevel 1 goto err_publish
:step4
echo ==^> 4/6 校验产物、剔除本机数据并写入部署说明
if not exist "%OUT%\OshimaBot.dll" goto err_missing
if not exist "%OUT%\appsettings.json" goto err_missing
:: 本机数据库含账号、ApiKey 哈希与玩法数据,绝不随包发布;目标机首次启动自动建库
del /f /q "%OUT%\*.db*" >nul 2>nul
del /f /q "%OUT%\appsettings.*.local.json" >nul 2>nul
del /f /q "%OUT%\*.pfx" >nul 2>nul
del /f /q "%OUT%\rounds_archive.zip" >nul 2>nul
>"%DEPLOY%" echo OshimaBot - Ubuntu linux-x64 deployment package
>>"%DEPLOY%" echo ============================================================
>>"%DEPLOY%" echo Framework-dependent build. The .NET runtime is NOT included.
>>"%DEPLOY%" echo This package contains no local database and no credentials.
>>"%DEPLOY%" echo.
>>"%DEPLOY%" echo Prerequisites on the target host
>>"%DEPLOY%" echo Ubuntu 22.04 or 24.04, x64
>>"%DEPLOY%" echo .NET 10 ASP.NET Core Runtime already installed
>>"%DEPLOY%" echo A writable directory for the SQLite database
>>"%DEPLOY%" echo.
>>"%DEPLOY%" echo 1. Extract
>>"%DEPLOY%" echo sudo mkdir -p /opt/oshimobot
>>"%DEPLOY%" echo sudo unzip -o OshimaBot-linux-x64-fd.zip -d /opt/oshimobot
>>"%DEPLOY%" echo cd /opt/oshimobot
>>"%DEPLOY%" echo.
>>"%DEPLOY%" echo 2. Configure secrets with environment variables or an
>>"%DEPLOY%" echo appsettings.Production.json override file.
>>"%DEPLOY%" echo Never put real credentials into appsettings.json.
>>"%DEPLOY%" echo ASPNETCORE_ENVIRONMENT=Production
>>"%DEPLOY%" echo QQBot__Enabled=true
>>"%DEPLOY%" echo QQBot__Mode=WebSocket
>>"%DEPLOY%" echo QQBot__Environment=Production
>>"%DEPLOY%" echo QQBot__AppId=YOUR_APP_ID
>>"%DEPLOY%" echo QQBot__Secret=YOUR_BOT_SECRET
>>"%DEPLOY%" echo Server__ApiKey=YOUR_THIRD_PARTY_KEY
>>"%DEPLOY%" echo Database__ConnectionString=Data Source=oshimobot.db
>>"%DEPLOY%" echo.
>>"%DEPLOY%" echo Notes
>>"%DEPLOY%" echo - QQBot__Environment selects the official or sandbox API domain.
>>"%DEPLOY%" echo - GatewayUrl left blank uses GET /gateway/bot auto discovery.
>>"%DEPLOY%" echo - Server__ApiKey is a one-time bootstrap key. After the first
>>"%DEPLOY%" echo start remove the plain value; auth then reads api_keys only.
>>"%DEPLOY%" echo - Webhook is disabled by default. POST /QQBot returns 404.
>>"%DEPLOY%" echo.
>>"%DEPLOY%" echo 3. Start manually
>>"%DEPLOY%" echo dotnet OshimaBot.dll --urls http://127.0.0.1:5090
>>"%DEPLOY%" echo curl http://127.0.0.1:5090/health
>>"%DEPLOY%" echo.
>>"%DEPLOY%" echo 4. systemd unit at /etc/systemd/system/oshimobot.service
>>"%DEPLOY%" echo [Unit]
>>"%DEPLOY%" echo Description=OshimaBot QQ MUD
>>"%DEPLOY%" echo After=network.target
>>"%DEPLOY%" echo [Service]
>>"%DEPLOY%" echo Type=simple
>>"%DEPLOY%" echo WorkingDirectory=/opt/oshimobot
>>"%DEPLOY%" echo ExecStart=/usr/bin/dotnet /opt/oshimobot/OshimaBot.dll --urls http://127.0.0.1:5090
>>"%DEPLOY%" echo Environment=ASPNETCORE_ENVIRONMENT=Production
>>"%DEPLOY%" echo Environment=QQBot__Enabled=true
>>"%DEPLOY%" echo Environment=QQBot__AppId=YOUR_APP_ID
>>"%DEPLOY%" echo Environment=QQBot__Secret=YOUR_BOT_SECRET
>>"%DEPLOY%" echo Restart=always
>>"%DEPLOY%" echo RestartSec=5
>>"%DEPLOY%" echo [Install]
>>"%DEPLOY%" echo WantedBy=multi-user.target
>>"%DEPLOY%" echo.
>>"%DEPLOY%" echo sudo systemctl daemon-reload
>>"%DEPLOY%" echo sudo systemctl enable --now oshimobot
>>"%DEPLOY%" echo sudo journalctl -u oshimobot -f
>>"%DEPLOY%" echo.
>>"%DEPLOY%" echo 5. Data
>>"%DEPLOY%" echo The database is created and migrated on first start. Relative
>>"%DEPLOY%" echo paths in Database__ConnectionString resolve against
>>"%DEPLOY%" echo WorkingDirectory. Stop the service before backup, then copy
>>"%DEPLOY%" echo oshimobot.db, oshimobot.db-wal and oshimobot.db-shm together,
>>"%DEPLOY%" echo or use VACUUM INTO for a consistent snapshot.
>>"%DEPLOY%" echo Simulation statistics and logs live in simulation_statistics
>>"%DEPLOY%" echo and simulation_runs. No JSON save files are needed.
>>"%DEPLOY%" echo.
>>"%DEPLOY%" echo 6. Optional reverse proxy
>>"%DEPLOY%" echo nginx proxy_pass to http://127.0.0.1:5090
>>"%DEPLOY%" echo GET /health is the readiness endpoint.
if not exist "%DEPLOY%" goto err_copy
echo ==^> 5/6 打包 zip
if not exist "%SystemRoot%\System32\tar.exe" goto no_tar
pushd "%OUT%"
"%SystemRoot%\System32\tar.exe" -a -cf "..\OshimaBot-linux-x64-fd.zip" *
if errorlevel 1 goto err_zip_in
popd
goto step6
:err_zip_in
popd
goto err_zip
:no_tar
echo 未找到系统 tar.exe,跳过压缩包,仅保留目录产物
:step6
echo ==^> 6/6 完成
echo.
echo 部署目录 : %CD%\%OUT%
if exist "%ZIP%" echo 压缩包 : %CD%\%ZIP%
echo.
echo 目标机需预装 .NET 10 ASP.NET Core Runtime,上传解压后执行:
echo dotnet OshimaBot.dll --urls http://127.0.0.1:5090
echo curl http://127.0.0.1:5090/health
echo.
echo 凭据用环境变量注入(QQBot__AppId / QQBot__Secret / Server__ApiKey 等),
echo 不要写进 appsettings.json;数据库首次启动自动创建。详见包内 DEPLOY.txt。
echo.
goto :eof
:err_no_dotnet
echo [错误] 未找到 dotnet,请先安装 .NET 10 SDK
exit /b 1
:err_no_project
echo [错误] 请在仓库根目录运行本脚本(找不到 OshimaBot\OshimaBot.csproj)
exit /b 1
:err_no_core
echo [错误] 找不到仓库外的 FunGame.Core.csproj
echo OshimaBot.slnx 相对引用 ..\..\FunGame\FunGame.Core\src\FunGame.Core.csproj
echo 换机器编译时需先把 FunGame.Core 放到对应位置,或改成子模块 / 包引用
exit /b 1
:err_publish
echo [错误] dotnet publish 失败
exit /b 1
:err_missing
echo [错误] 发布产物缺少 OshimaBot.dll 或 appsettings.json
exit /b 1
:err_copy
echo [错误] 写入 DEPLOY.txt 失败
exit /b 1
:err_zip
echo [错误] 打包 zip 失败,publish\linux-x64-fd 目录产物仍可使用
exit /b 1
endlocal