feat(S7): add explicit command catalog, MUD replies and P0 command rewrite

This commit is contained in:
2026-11-09 23:31:42 +08:00
parent 052fe47db7
commit e89b5867cd
9 changed files with 1150 additions and 202 deletions
+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("/玩法帮助"), 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, 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() { }
}
}
+282
View File
@@ -0,0 +1,282 @@
using FunGame.Core.Library.Constant;
using OshimaBot.Game.Services;
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"
];
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.Error(
"该模块尚未迁移到 OshimaBot", "存档、社团、活动和商店暂不可用",
"当前开放角色、物品、战斗查询与模拟指令", "/帮助"))),
// ---- 查询 ----
"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)
{
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);
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);
}
}
+118
View File
@@ -0,0 +1,118 @@
using System.Security.Claims;
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 Legacy = "待迁移";
}
/// <summary>命令工厂所需的全部依赖,全部由 DI 显式传入,不做反射扫描。</summary>
public sealed record CommandDependencies(
FunGameQueryService Queries,
FunGameSimulationService Simulations,
IBindCodeService BindCodes,
IUserSessionService Sessions,
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);
}
+143
View File
@@ -0,0 +1,143 @@
using System.Text;
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>帮助完全由注册表生成,保证「文档与实现同源」。</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);
}
}
+10
View File
@@ -2,6 +2,7 @@ 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.Messaging;
@@ -68,6 +69,15 @@ builder.Services.AddSingleton<IQQBotService, QQBotService>();
builder.Services.AddSingleton<FunGameSimulationService>();
builder.Services.AddSingleton<FunGameQueryService>();
builder.Services.AddScoped<MessageSender>();
builder.Services.AddSingleton<IUserSessionService, UserSessionService>();
builder.Services.AddSingleton(sp => new CommandDependencies(
sp.GetRequiredService<FunGameQueryService>(),
sp.GetRequiredService<FunGameSimulationService>(),
sp.GetRequiredService<IBindCodeService>(),
sp.GetRequiredService<IUserSessionService>(),
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>());
+12 -195
View File
@@ -1,211 +1,28 @@
using System.Text;
using OshimaBot.Game.Services;
using OshimaBot.Commands;
using OshimaBot.Messaging;
using OshimaBot.Models;
using OshimaBot.Security;
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,
IBindCodeService bindCodes,
ILogger<RainBotService> logger)
{
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;
message.Detail = message.Detail?.Trim() ?? "";
if (message.Detail.Length == 0) return false;
BotReply? reply = await RouteCommandAsync(message, command, cancellationToken);
BotReply? reply = await router.RouteAsync(message, data, cancellationToken);
if (reply is null) return false;
await SendAsync(message, reply, cancellationToken);
await messageSender.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 "当前版本采用无状态指令路由,无需重置指令状态。";
// 旧版直接回显 OpenID 作为「接入码」已停用:改为 6 位一次性绑定码。
if ((command is "获取接入码" or "绑定" or "/绑定") && !message.IsGroup)
{
if (message.FunGameUID <= 0)
{
return "身份尚未就绪,请稍后重试或换一条消息触发注册。";
}
string code = await bindCodes.IssueAsync(message.FunGameUID, "qq_bind", cancellationToken);
return $"你的绑定码为 {code},{bindCodes.TtlSeconds / 60} 分钟内有效且只能使用一次。请在第三方端凭码绑定,切勿公开;旧版直接回显 OpenID 的方式已停用。";
}
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. 上次的日志 / 上次的完整日志:查看最近模拟记录。
""";
}
}