diff --git a/OshimaBot.Tests/GameplayCommandTests.cs b/OshimaBot.Tests/GameplayCommandTests.cs new file mode 100644 index 0000000..d45a621 --- /dev/null +++ b/OshimaBot.Tests/GameplayCommandTests.cs @@ -0,0 +1,197 @@ +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; + +/// P1 指令层:显式注册表 + CommandRouter + 真实玩法仓储的端到端验证。 +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(49, 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_LastPageContainsP1Group() + { + using GameplayCommandDatabase db = new(); + CommandRouter router = db.CreateRouter(); + + string content = await RouteAsync(router, "/帮助 p9"); + + Assert.Contains("9/9", content); + bool hasP1 = content.Contains("/状态", StringComparison.Ordinal) + || content.Contains("/抽卡", StringComparison.Ordinal) + || content.Contains("/每日任务", StringComparison.Ordinal) + || content.Contains("旅人存档", StringComparison.Ordinal); + Assert.True(hasP1, 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 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(options => options.UseSqlite(Connection)); + services.AddSingleton(Options.Create(new ServerOptions())); + services.AddSingleton(Options.Create(new DatabaseOptions { ApplyMigrationsOnStartup = false })); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + Provider = services.BuildServiceProvider(); + using IServiceScope scope = Provider.CreateScope(); + scope.ServiceProvider.GetRequiredService().Database.EnsureCreated(); + + Dependencies = new CommandDependencies( + null!, null!, null!, + Provider.GetRequiredService(), + Provider.GetRequiredService(), + NullLogger.Instance); + } + + public CommandRouter CreateRouter() => new( + CommandCatalog.Build(Dependencies), Dependencies, + Provider.GetRequiredService(), + Provider.GetRequiredService(), + NullLogger.Instance); + + public void Dispose() + { + Provider.Dispose(); + Connection.Dispose(); + } + } +} diff --git a/OshimaBot/Commands/CommandCatalog.cs b/OshimaBot/Commands/CommandCatalog.cs index 2ca6f89..6ea8285 100644 --- a/OshimaBot/Commands/CommandCatalog.cs +++ b/OshimaBot/Commands/CommandCatalog.cs @@ -1,5 +1,6 @@ using FunGame.Core.Library.Constant; using OshimaBot.Game.Services; +using OshimaBot.Gameplay; using OshimaBot.Messaging; using OshimaBot.Models; using OshimaBot.Services; @@ -19,7 +20,12 @@ public static class CommandCatalog "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" + "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" ]; public static CommandRegistry Build(CommandDependencies deps) @@ -93,8 +99,159 @@ public static class CommandCatalog key: "legacy-help", name: "玩法帮助", aliases: ["存档帮助", "社团帮助", "活动帮助", "商店帮助", "legacy"], usage: "/玩法帮助", description: "查看尚未迁移的模块", group: CommandGroups.Legacy, handler: _ => Task.FromResult(CommandReplies.Error( - "该模块尚未迁移到 OshimaBot", "存档、社团、活动和商店暂不可用", - "当前开放角色、物品、战斗查询与模拟指令", "/帮助"))), + "P2 模块尚未迁移", "商店、市场、交易、锻造、秘境与决斗暂不可用", + "P1 存档、角色、背包、签到、抽卡与练级已开放,输入 /状态 查看", "/状态"))), + + // ---- 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))), // ---- 查询 ---- "magic-card" => new DelegateCommand( @@ -234,6 +391,10 @@ public static class CommandCatalog 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}"); } @@ -279,4 +440,107 @@ public static class CommandCatalog ? CommandReplies.Paginated(title, result, context.Page, command) : CommandReplies.Detail(title, result, actions: actions.Length == 0 ? ["/帮助"] : actions); } + + // ---- P1 指令辅助 ---- + + /// @编号 / 纯数字都接受,统一转成 1-based 序号;无效返回 0 由仓储给出错误提示。 + 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; + } + + /// x2 / 2 都表示数量,缺省用 fallback。 + 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 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 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 整理背包(/背包)", + "", + "商店与交易摊位还蒙着布——那是下一批工匠的活。" + ], + ["/签到", "/每日任务", "/抽卡", "/练级 @1 1", "/背包"]); + } + + private static async Task QuestsAsync(CommandDependencies deps, CommandContext context) + { + IReadOnlyList quests = await deps.Players.GetQuestsAsync( + context.UserId, context.CancellationToken); + List 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 BagAsync(CommandDependencies deps, CommandContext context) + { + IReadOnlyList items = await deps.Players.GetBagAsync(context.UserId, context.CancellationToken); + List 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 CharactersAsync(CommandDependencies deps, CommandContext context) + { + IReadOnlyList characters = await deps.Players.GetCharactersAsync( + context.UserId, context.CancellationToken); + List 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, + "/我的角色", ["/状态", "/背包"]); + } } diff --git a/OshimaBot/Commands/CommandModels.cs b/OshimaBot/Commands/CommandModels.cs index d444ae2..108855f 100644 --- a/OshimaBot/Commands/CommandModels.cs +++ b/OshimaBot/Commands/CommandModels.cs @@ -13,6 +13,7 @@ public static class CommandGroups public const string Query = "查询"; public const string Stats = "统计"; public const string Simulation = "战斗模拟"; + public const string Player = "旅人存档"; public const string Legacy = "待迁移"; } diff --git a/OshimaBot/Commands/CommandReplies.cs b/OshimaBot/Commands/CommandReplies.cs index ae04588..ddc7dd9 100644 --- a/OshimaBot/Commands/CommandReplies.cs +++ b/OshimaBot/Commands/CommandReplies.cs @@ -1,4 +1,5 @@ using System.Text; +using OshimaBot.Gameplay; using OshimaBot.Messaging; using OshimaBot.Models; @@ -104,6 +105,48 @@ public static class CommandReplies return Compose(title, pageStatus, lines, actions, keyboard); } + /// 玩法仓储结果统一渲染:成功走 4 段式,失败走错误三段式。 + 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()); + + /// Markdown 列表分页(不包代码块,保留 - / @编号 的排版),附翻页指令与按钮。 + public static BotReply ListPage( + string title, string status, IReadOnlyList lines, int page, string command, + IEnumerable? extraActions = null) + { + List> chunks = []; + List 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 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); + } + /// 帮助完全由注册表生成,保证「文档与实现同源」。 public static BotReply Help(CommandRegistry registry, int page) {