feat(S2): port BotReplyExtension with QQ markdown, keyboard and msg_seq fixes
This commit is contained in:
@@ -0,0 +1,132 @@
|
|||||||
|
using OshimaBot.Messaging;
|
||||||
|
using OshimaBot.Models;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace OshimaBot.Tests;
|
||||||
|
|
||||||
|
public sealed class MessagingTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void CmdInput_UrlEncodesTextAndShow()
|
||||||
|
{
|
||||||
|
string tag = QQCmdTag.CmdInput("/背包 查看", "点这里");
|
||||||
|
Assert.StartsWith("<qqbot-cmd-input text=\"", tag);
|
||||||
|
Assert.DoesNotContain("背包", tag);
|
||||||
|
Assert.DoesNotContain("点这里", tag);
|
||||||
|
Assert.Contains("%", tag);
|
||||||
|
Assert.Contains("reference=\"false\"", tag);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void CmdInput_TruncatesTo100Characters()
|
||||||
|
{
|
||||||
|
string encoded = QQCmdTag.Encode(new string('a', 150));
|
||||||
|
Assert.Equal(100, encoded.Length);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void CmdEnter_UsesEnterTag()
|
||||||
|
{
|
||||||
|
string tag = QQCmdTag.CmdEnter("/签到");
|
||||||
|
Assert.StartsWith("<qqbot-cmd-enter text=\"", tag);
|
||||||
|
Assert.DoesNotContain("qqbot-cmd-input", tag);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void AtUser_DoesNotInjectTags()
|
||||||
|
=> Assert.Equal("<qqbot-at-user id=\"abc"123\" />", QQCmdTag.AtUser("abc\"123"));
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Escape_NeutralizesCmdTagInjection()
|
||||||
|
{
|
||||||
|
string escaped = QQMarkdown.Escape("<qqbot-cmd-input text=\"x\"/>");
|
||||||
|
Assert.DoesNotContain("<qqbot", escaped);
|
||||||
|
Assert.Contains("<", escaped);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Split_RespectsMaxLength()
|
||||||
|
{
|
||||||
|
IReadOnlyList<string> parts = QQMarkdown.Split(new string('a', 7000), 3000);
|
||||||
|
Assert.Equal(3, parts.Count);
|
||||||
|
Assert.All(parts, part => Assert.True(part.Length <= 3000));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void CmdButton_FillsRequiredUnsupportedTips()
|
||||||
|
{
|
||||||
|
KeyboardButton button = KeyboardBuilder.CmdButton("签到", "/签到");
|
||||||
|
Assert.Equal(2, button.Action.Type);
|
||||||
|
Assert.False(string.IsNullOrWhiteSpace(button.Action.UnsupportTips));
|
||||||
|
Assert.Equal(2, button.Action.Permission.Type);
|
||||||
|
Assert.Equal("签到", button.RenderData.Label);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void InteractionButton_UsesCallbackType()
|
||||||
|
{
|
||||||
|
KeyboardButton button = KeyboardBuilder.InteractionButton("确认", "confirm:1");
|
||||||
|
Assert.Equal(1, button.Action.Type);
|
||||||
|
Assert.Null(button.Action.Enter);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void KeyboardBuilder_EnforcesFiveRowLimit()
|
||||||
|
{
|
||||||
|
KeyboardBuilder builder = new();
|
||||||
|
for (int row = 0; row < 5; row++)
|
||||||
|
{
|
||||||
|
builder.AddNewRow(1, KeyboardBuilder.CmdButton($"B{row}", $"/b{row}"));
|
||||||
|
}
|
||||||
|
Assert.Throws<InvalidOperationException>(() => builder.AddNewRow(1, KeyboardBuilder.CmdButton("X", "/x")));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void AppendButtons_WrapsAutomatically()
|
||||||
|
{
|
||||||
|
KeyboardMessage keyboard = new();
|
||||||
|
KeyboardButton[] buttons = Enumerable.Range(0, 7)
|
||||||
|
.Select(index => KeyboardBuilder.CmdButton($"B{index}", $"/b{index}"))
|
||||||
|
.ToArray();
|
||||||
|
keyboard.AppendButtons(3, buttons);
|
||||||
|
Assert.Equal(3, keyboard.Content!.Rows.Count);
|
||||||
|
Assert.Equal(3, keyboard.Content.Rows[0].Buttons.Count);
|
||||||
|
Assert.Equal(1, keyboard.Content.Rows[2].Buttons.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void AddPaginationRow_UsesMudPageSyntax()
|
||||||
|
{
|
||||||
|
KeyboardMessage keyboard = new();
|
||||||
|
keyboard.AddPaginationRow("/bag", 1, 3);
|
||||||
|
KeyboardRow row = keyboard.Content!.Rows[0];
|
||||||
|
Assert.Equal(3, row.Buttons.Count);
|
||||||
|
Assert.Equal("/bag p2", row.Buttons[1].Action.Data);
|
||||||
|
Assert.Equal("/bag p3", row.Buttons[2].Action.Data);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void CreateCmdInput_Extension_RespectsThisIsText()
|
||||||
|
{
|
||||||
|
string normal = "显示".CreateCmdInput("/go 城门");
|
||||||
|
Assert.Contains("text=\"%2Fgo", normal);
|
||||||
|
Assert.Contains("show=\"%E6%98%BE", normal);
|
||||||
|
|
||||||
|
string swapped = "显示".CreateCmdInput("/go 城门", thisIsText: true);
|
||||||
|
Assert.Contains("text=\"%E6%98%BE", swapped);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ReplyComposer_ProducesFourPartMarkdown()
|
||||||
|
{
|
||||||
|
BotReply reply = ReplyComposer.Compose(
|
||||||
|
"铎京 · 中央广场",
|
||||||
|
"HP 100/100 · 金币 1,250",
|
||||||
|
["铁匠铺 @1 可锻造", "城门 @3 可前往"],
|
||||||
|
["/go @3"]);
|
||||||
|
Assert.NotNull(reply.Markdown);
|
||||||
|
Assert.StartsWith("## ", reply.Markdown!.Content);
|
||||||
|
Assert.Contains("**HP", reply.Markdown.Content);
|
||||||
|
Assert.Contains("qqbot-cmd-input", reply.Markdown.Content);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
using OshimaBot.Models;
|
||||||
|
|
||||||
|
namespace OshimaBot.Messaging;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 自定义 keyboard 构造(用户已确认可用)。强制官方上限:5 行 × 每行 5 按钮、label ≤10 字符。
|
||||||
|
/// 照搬 v2 的 Button.CreateCmdButton / CreateInteractionButton 工厂语义。
|
||||||
|
/// </summary>
|
||||||
|
public sealed class KeyboardBuilder
|
||||||
|
{
|
||||||
|
public const int MaxRows = 5;
|
||||||
|
public const int MaxButtonsPerRow = 5;
|
||||||
|
public const int MaxLabelLength = 10;
|
||||||
|
|
||||||
|
private readonly KeyboardMessage _keyboard = new() { Content = new KeyboardContent() };
|
||||||
|
|
||||||
|
/// <summary>action.type=2 指令按钮:点击填充输入框或直接发送 data。</summary>
|
||||||
|
public static KeyboardButton CmdButton(
|
||||||
|
string label,
|
||||||
|
string data,
|
||||||
|
bool enter = true,
|
||||||
|
bool reply = false,
|
||||||
|
string? visitedLabel = null,
|
||||||
|
int style = 1,
|
||||||
|
int permissionType = 2,
|
||||||
|
params string[] specifyUserIds)
|
||||||
|
{
|
||||||
|
string display = Truncate(label);
|
||||||
|
return new KeyboardButton
|
||||||
|
{
|
||||||
|
Id = Guid.NewGuid().ToString(),
|
||||||
|
RenderData = new KeyboardRenderData
|
||||||
|
{
|
||||||
|
Label = display,
|
||||||
|
VisitedLabel = Truncate(visitedLabel ?? label),
|
||||||
|
Style = style
|
||||||
|
},
|
||||||
|
Action = new KeyboardAction
|
||||||
|
{
|
||||||
|
Type = 2,
|
||||||
|
Data = data,
|
||||||
|
Enter = enter,
|
||||||
|
Reply = reply,
|
||||||
|
Permission = new KeyboardPermission
|
||||||
|
{
|
||||||
|
Type = permissionType,
|
||||||
|
SpecifyUserIds = [.. specifyUserIds]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>action.type=1 回调按钮:会触发 INTERACTION_CREATE,必须调用 PUT /interactions/{id} 回执。</summary>
|
||||||
|
public static KeyboardButton InteractionButton(
|
||||||
|
string label,
|
||||||
|
string data,
|
||||||
|
string? visitedLabel = null,
|
||||||
|
int style = 1,
|
||||||
|
int permissionType = 2,
|
||||||
|
params string[] specifyUserIds)
|
||||||
|
{
|
||||||
|
string display = Truncate(label);
|
||||||
|
return new KeyboardButton
|
||||||
|
{
|
||||||
|
Id = Guid.NewGuid().ToString(),
|
||||||
|
RenderData = new KeyboardRenderData
|
||||||
|
{
|
||||||
|
Label = display,
|
||||||
|
VisitedLabel = Truncate(visitedLabel ?? label),
|
||||||
|
Style = style
|
||||||
|
},
|
||||||
|
Action = new KeyboardAction
|
||||||
|
{
|
||||||
|
Type = 1,
|
||||||
|
Data = data,
|
||||||
|
Enter = null,
|
||||||
|
Permission = new KeyboardPermission
|
||||||
|
{
|
||||||
|
Type = permissionType,
|
||||||
|
SpecifyUserIds = [.. specifyUserIds]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public KeyboardBuilder AddButtons(int perRow, params KeyboardButton[] buttons)
|
||||||
|
{
|
||||||
|
_keyboard.AppendButtons(perRow, buttons);
|
||||||
|
Validate();
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public KeyboardBuilder AddNewRow(int perRow, params KeyboardButton[] buttons)
|
||||||
|
{
|
||||||
|
_keyboard.AppendButtonsWithNewRow(perRow, buttons);
|
||||||
|
Validate();
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public KeyboardBuilder AddPagination(string command, int currentPage, int totalPages)
|
||||||
|
{
|
||||||
|
_keyboard.AddPaginationRow(command, currentPage, totalPages);
|
||||||
|
Validate();
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public KeyboardMessage Build()
|
||||||
|
{
|
||||||
|
Validate();
|
||||||
|
return _keyboard;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Validate()
|
||||||
|
{
|
||||||
|
KeyboardContent content = _keyboard.Content!;
|
||||||
|
if (content.Rows.Count > MaxRows)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException($"keyboard 最多 {MaxRows} 行,当前 {content.Rows.Count} 行。");
|
||||||
|
}
|
||||||
|
foreach (KeyboardRow row in content.Rows)
|
||||||
|
{
|
||||||
|
if (row.Buttons.Count > MaxButtonsPerRow)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException($"keyboard 每行最多 {MaxButtonsPerRow} 个按钮,当前 {row.Buttons.Count} 个。");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Truncate(string value)
|
||||||
|
=> value.Length <= MaxLabelLength ? value : value[..MaxLabelLength];
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
using Microsoft.Extensions.Caching.Memory;
|
||||||
|
using OshimaBot.Models;
|
||||||
|
using OshimaBot.Services;
|
||||||
|
|
||||||
|
namespace OshimaBot.Messaging;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 出站消息统一入口:修正旧版 msgSeq 恒为 1 的缺陷(同一 msg_id 第二次回复会触发 40054005),
|
||||||
|
/// 按 msg_id 在被动窗口内递增序号;第三方消息则直接写回结果对象。
|
||||||
|
/// </summary>
|
||||||
|
public sealed class MessageSender(IQQBotService qqBot, IMemoryCache cache, ILogger<MessageSender> logger)
|
||||||
|
{
|
||||||
|
private static readonly TimeSpan PassiveWindow = TimeSpan.FromMinutes(5);
|
||||||
|
private readonly object _seqLock = new();
|
||||||
|
|
||||||
|
public async Task SendAsync(IBotMessage message, BotReply reply, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
if (message is ThirdPartyMessage thirdParty)
|
||||||
|
{
|
||||||
|
thirdParty.Result = reply.Markdown?.Content ?? reply.Text;
|
||||||
|
thirdParty.IsCompleted = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
string? msgId = message.SendProactive ? null : message.Id;
|
||||||
|
int? msgSeq = string.IsNullOrWhiteSpace(msgId) ? null : NextSeq(msgId);
|
||||||
|
|
||||||
|
if (reply.Markdown is not null && !string.IsNullOrWhiteSpace(reply.Markdown.Content))
|
||||||
|
{
|
||||||
|
if (message.IsGroup)
|
||||||
|
{
|
||||||
|
await qqBot.SendGroupMarkdownAsync(message.OpenId, reply.Markdown, reply.Keyboard, msgId, msgSeq, cancellationToken);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await qqBot.SendC2CMarkdownAsync(message.OpenId, reply.Markdown, reply.Keyboard, msgId, msgSeq, cancellationToken);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(reply.Text)) return;
|
||||||
|
|
||||||
|
string content = message.IsGroup ? "\r\n" + reply.Text.Trim() : reply.Text.Trim();
|
||||||
|
if (message.IsGroup)
|
||||||
|
{
|
||||||
|
await qqBot.SendGroupMessageAsync(message.OpenId, content, msgId: msgId, msgSeq: msgSeq, cancellationToken: cancellationToken);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await qqBot.SendC2CMessageAsync(message.OpenId, content, msgId: msgId, msgSeq: msgSeq, cancellationToken: cancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>同一 msg_id 的回复序号 1,2,3…;5 分钟后随被动窗口一起失效。</summary>
|
||||||
|
private int NextSeq(string msgId)
|
||||||
|
{
|
||||||
|
lock (_seqLock)
|
||||||
|
{
|
||||||
|
string key = $"OshimaBot:MsgSeq:{msgId}";
|
||||||
|
int next = cache.TryGetValue(key, out int current) ? current + 1 : 1;
|
||||||
|
cache.Set(key, next, PassiveWindow);
|
||||||
|
logger.LogDebug("被动回复序号:MsgId={MsgId}, MsgSeq={MsgSeq}", msgId, next);
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
namespace OshimaBot.Messaging;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// QQ 官方文本交互标签构造(文档更新 2026/10/26):
|
||||||
|
/// https://bot.qq.com/wiki/develop/api-v2/server-inter/message/trans/text-chain.html
|
||||||
|
/// text / show 各 ≤100 字符且必须 urlencode —— 旧版 CreateCmdInput 只做了引号转义,这里统一补齐。
|
||||||
|
/// </summary>
|
||||||
|
public static class QQCmdTag
|
||||||
|
{
|
||||||
|
public const int MaxTextLength = 100;
|
||||||
|
public const string DefaultUnsupportedTips = "当前客户端不支持该操作,请手动输入指令。";
|
||||||
|
|
||||||
|
/// <summary>截断到 100 字符后 urlencode,并转义属性值中的引号。</summary>
|
||||||
|
public static string Encode(string? value)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(value)) return "";
|
||||||
|
string truncated = value.Length > MaxTextLength ? value[..MaxTextLength] : value;
|
||||||
|
return Uri.EscapeDataString(truncated).Replace("\"", """, StringComparison.Ordinal);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>点击后把 text 插入输入框,用户自行编辑发送。</summary>
|
||||||
|
public static string CmdInput(string text, string? show = null, bool reference = false)
|
||||||
|
=> $"<qqbot-cmd-input text=\"{Encode(text)}\" show=\"{Encode(show ?? text)}\" reference=\"{(reference ? "true" : "false")}\"/>";
|
||||||
|
|
||||||
|
/// <summary>点击后直接发送 text(仅单聊场景支持)。</summary>
|
||||||
|
public static string CmdEnter(string text)
|
||||||
|
=> $"<qqbot-cmd-enter text=\"{Encode(text)}\"/>";
|
||||||
|
|
||||||
|
public static string AtUser(string openId)
|
||||||
|
=> $"<qqbot-at-user id=\"{EscapeAttribute(openId)}\" />";
|
||||||
|
|
||||||
|
public static string AtEveryone() => "<qqbot-at-everyone />";
|
||||||
|
|
||||||
|
public static string AtChannel(string channelId)
|
||||||
|
=> $"<#{EscapeAttribute(channelId)}>";
|
||||||
|
|
||||||
|
private static string EscapeAttribute(string value)
|
||||||
|
=> value.Replace("&", "&", StringComparison.Ordinal)
|
||||||
|
.Replace("\"", """, StringComparison.Ordinal)
|
||||||
|
.Replace("<", "<", StringComparison.Ordinal)
|
||||||
|
.Replace(">", ">", StringComparison.Ordinal);
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace OshimaBot.Messaging;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// QQ 自定义 Markdown 构造助手。官方 2026/04/23 已对单聊/群聊全量开放自定义 Markdown。
|
||||||
|
/// 支持:标题、粗/斜体/删除线、链接、图片、有序/无序列表、块引用、水平分割线、多行。
|
||||||
|
/// **不支持表格**(官方格式清单中没有),因此本类刻意不提供 Table 方法。
|
||||||
|
/// https://bot.q.qq.com/wiki/develop/api-v2/server-inter/message/type/markdown.html
|
||||||
|
/// </summary>
|
||||||
|
public static class QQMarkdown
|
||||||
|
{
|
||||||
|
/// <summary>官方未明示 content 上限,按 3000 字符保守分段(错误码 40054007 消息长度超限)。</summary>
|
||||||
|
public const int DefaultMaxLength = 3000;
|
||||||
|
|
||||||
|
/// <summary>转义用户可控文本,避免破坏排版或注入 <qqbot-*> 标签。</summary>
|
||||||
|
public static string Escape(string? text)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(text)) return "";
|
||||||
|
|
||||||
|
StringBuilder builder = new(text.Length + 8);
|
||||||
|
foreach (char c in text)
|
||||||
|
{
|
||||||
|
switch (c)
|
||||||
|
{
|
||||||
|
case '\\': builder.Append("\\\\"); break;
|
||||||
|
case '`': builder.Append("\\`"); break;
|
||||||
|
case '*': builder.Append("\\*"); break;
|
||||||
|
case '_': builder.Append("\\_"); break;
|
||||||
|
case '~': builder.Append("\\~"); break;
|
||||||
|
case '>': builder.Append("\\>"); break;
|
||||||
|
case '#': builder.Append("\\#"); break;
|
||||||
|
case '[': builder.Append("\\["); break;
|
||||||
|
case ']': builder.Append("\\]"); break;
|
||||||
|
case '(': builder.Append("\\("); break;
|
||||||
|
case ')': builder.Append("\\)"); break;
|
||||||
|
case '!': builder.Append("\\!"); break;
|
||||||
|
case '<': builder.Append("<"); break;
|
||||||
|
default: builder.Append(c); break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string Heading(string text, int level = 2)
|
||||||
|
=> $"{new string('#', Math.Clamp(level, 1, 6))} {Escape(text)}";
|
||||||
|
|
||||||
|
public static string Bold(string text) => $"**{Escape(text)}**";
|
||||||
|
public static string Italic(string text) => $"*{Escape(text)}*";
|
||||||
|
public static string Strike(string text) => $"~~{Escape(text)}~~";
|
||||||
|
public static string Quote(string text) => $"> {Escape(text)}";
|
||||||
|
public static string Divider() => "***";
|
||||||
|
public static string Link(string label, string url) => $"[{Escape(label)}]({url})";
|
||||||
|
public static string Image(string url, string? alt = null, string? size = null)
|
||||||
|
=> $"";
|
||||||
|
|
||||||
|
public static string OrderedList(IEnumerable<string> items)
|
||||||
|
=> string.Join(Environment.NewLine, items.Select((item, index) => $"{index + 1}. {Escape(item)}"));
|
||||||
|
|
||||||
|
public static string UnorderedList(IEnumerable<string> items)
|
||||||
|
=> string.Join(Environment.NewLine, items.Select(item => $"- {Escape(item)}"));
|
||||||
|
|
||||||
|
/// <summary>按字符上限切分长回复,优先在换行处断开。</summary>
|
||||||
|
public static IReadOnlyList<string> Split(string content, int maxLength = DefaultMaxLength)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(content) || content.Length <= maxLength) return [content];
|
||||||
|
|
||||||
|
List<string> parts = [];
|
||||||
|
int start = 0;
|
||||||
|
while (start < content.Length)
|
||||||
|
{
|
||||||
|
int length = Math.Min(maxLength, content.Length - start);
|
||||||
|
int breakAt = content.LastIndexOf('\n', start + length - 1, length);
|
||||||
|
if (breakAt > start) length = breakAt - start + 1;
|
||||||
|
parts.Add(content.Substring(start, length));
|
||||||
|
start += length;
|
||||||
|
}
|
||||||
|
return parts;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
using System.Text;
|
||||||
|
using OshimaBot.Models;
|
||||||
|
|
||||||
|
namespace OshimaBot.Messaging;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// MUD 4 段式回复:场景/标题 → 状态条 → 列表 → 可点击行动。
|
||||||
|
/// 按钮客户端与不支持按钮的客户端各有一条通路(keyboard 由调用方另挂)。
|
||||||
|
/// </summary>
|
||||||
|
public static class ReplyComposer
|
||||||
|
{
|
||||||
|
public static BotReply Compose(
|
||||||
|
string title,
|
||||||
|
string? status = null,
|
||||||
|
IEnumerable<string>? lines = null,
|
||||||
|
IEnumerable<string>? actions = null)
|
||||||
|
{
|
||||||
|
StringBuilder builder = new();
|
||||||
|
builder.AppendLine(QQMarkdown.Heading(title, 2));
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(status))
|
||||||
|
{
|
||||||
|
builder.AppendLine(QQMarkdown.Bold(status));
|
||||||
|
builder.AppendLine();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (lines is not null)
|
||||||
|
{
|
||||||
|
foreach (string line in lines)
|
||||||
|
{
|
||||||
|
builder.AppendLine(QQMarkdown.Escape(line));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (actions is not null)
|
||||||
|
{
|
||||||
|
builder.AppendLine();
|
||||||
|
builder.AppendLine(QQMarkdown.Strike("可执行"));
|
||||||
|
foreach (string action in actions)
|
||||||
|
{
|
||||||
|
builder.AppendLine(QQCmdTag.CmdInput(action));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return BotReply.FromMarkdown(builder.ToString().TrimEnd());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
|
using OshimaBot.Messaging;
|
||||||
|
|
||||||
namespace OshimaBot.Models
|
namespace OshimaBot.Models
|
||||||
{
|
{
|
||||||
@@ -181,8 +182,13 @@ namespace OshimaBot.Models
|
|||||||
[JsonPropertyName("id")] public string Id { get; set; } = Guid.NewGuid().ToString();
|
[JsonPropertyName("id")] public string Id { get; set; } = Guid.NewGuid().ToString();
|
||||||
[JsonPropertyName("render_data")] public KeyboardRenderData RenderData { get; set; } = new();
|
[JsonPropertyName("render_data")] public KeyboardRenderData RenderData { get; set; } = new();
|
||||||
[JsonPropertyName("action")] public KeyboardAction Action { get; set; } = new();
|
[JsonPropertyName("action")] public KeyboardAction Action { get; set; } = new();
|
||||||
|
|
||||||
|
[JsonPropertyName("group_id")]
|
||||||
|
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||||
|
public string? GroupId { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>style:0 灰色线框 / 1 蓝色线框 / 3 白底红字 / 4 蓝底白字;label 最多 10 字符。</summary>
|
||||||
public sealed class KeyboardRenderData
|
public sealed class KeyboardRenderData
|
||||||
{
|
{
|
||||||
[JsonPropertyName("label")] public string Label { get; set; } = "";
|
[JsonPropertyName("label")] public string Label { get; set; } = "";
|
||||||
@@ -192,15 +198,42 @@ namespace OshimaBot.Models
|
|||||||
|
|
||||||
public sealed class KeyboardAction
|
public sealed class KeyboardAction
|
||||||
{
|
{
|
||||||
|
/// <summary>0 跳转 / 1 回调(触发 INTERACTION_CREATE,必须回执) / 2 指令。</summary>
|
||||||
[JsonPropertyName("type")] public int Type { get; set; } = 2;
|
[JsonPropertyName("type")] public int Type { get; set; } = 2;
|
||||||
[JsonPropertyName("permission")] public KeyboardPermission Permission { get; set; } = new();
|
[JsonPropertyName("permission")] public KeyboardPermission Permission { get; set; } = new();
|
||||||
[JsonPropertyName("data")] public string Data { get; set; } = "";
|
[JsonPropertyName("data")] public string Data { get; set; } = "";
|
||||||
[JsonPropertyName("enter")] public bool? Enter { get; set; } = true;
|
|
||||||
[JsonPropertyName("reply")] public bool? Reply { get; set; }
|
[JsonPropertyName("enter")]
|
||||||
|
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||||
|
public bool? Enter { get; set; } = true;
|
||||||
|
|
||||||
|
[JsonPropertyName("reply")]
|
||||||
|
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||||
|
public bool? Reply { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("anchor")]
|
||||||
|
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||||
|
public int? Anchor { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("modal")]
|
||||||
|
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||||
|
public KeyboardModal? Modal { get; set; }
|
||||||
|
|
||||||
|
/// <summary>官方 msg-btn 页列为必填:客户端不支持该 action 时的 toast 文案。</summary>
|
||||||
|
[JsonPropertyName("unsupport_tips")]
|
||||||
|
public string UnsupportTips { get; set; } = QQCmdTag.DefaultUnsupportedTips;
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class KeyboardModal
|
||||||
|
{
|
||||||
|
[JsonPropertyName("content")] public string Content { get; set; } = "";
|
||||||
|
[JsonPropertyName("confirm_text")] public string ConfirmText { get; set; } = "确认";
|
||||||
|
[JsonPropertyName("cancel_text")] public string CancelText { get; set; } = "取消";
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class KeyboardPermission
|
public sealed class KeyboardPermission
|
||||||
{
|
{
|
||||||
|
/// <summary>0 指定用户 / 1 仅管理者 / 2 所有人 / 3 指定身份组(仅频道)。</summary>
|
||||||
[JsonPropertyName("type")] public int Type { get; set; } = 2;
|
[JsonPropertyName("type")] public int Type { get; set; } = 2;
|
||||||
[JsonPropertyName("specify_user_ids")] public List<string> SpecifyUserIds { get; set; } = [];
|
[JsonPropertyName("specify_user_ids")] public List<string> SpecifyUserIds { get; set; } = [];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
using OshimaBot.Messaging;
|
||||||
|
|
||||||
|
namespace OshimaBot.Models;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 照搬 v2 `OshimaServers/Model/QQBot.cs:106-232` 的 BotReplyExtension 全部扩展,
|
||||||
|
/// 并按 2026/10/26 官方规范做合规修正:CreateCmdInput 走 QQCmdTag(urlencode + 100 字符截断),
|
||||||
|
/// 分页/new-row 逻辑保持原样。v2 的 params IEnumerable<Button>[] 收敛为 params KeyboardButton[]。
|
||||||
|
/// </summary>
|
||||||
|
public static class BotReplyExtension
|
||||||
|
{
|
||||||
|
/// <summary>按每行上限自动换行追加按钮。</summary>
|
||||||
|
public static KeyboardMessage AppendButtons(this KeyboardMessage kb, int btnCountPerRow, params KeyboardButton[] buttons)
|
||||||
|
{
|
||||||
|
KeyboardContent content = kb.Content ??= new KeyboardContent();
|
||||||
|
btnCountPerRow = Math.Clamp(btnCountPerRow, 1, KeyboardBuilder.MaxButtonsPerRow);
|
||||||
|
|
||||||
|
List<KeyboardRow> rows = content.Rows;
|
||||||
|
KeyboardRow? currentRow = rows.Count > 0 ? rows[^1] : null;
|
||||||
|
foreach (KeyboardButton button in buttons)
|
||||||
|
{
|
||||||
|
if (currentRow is null || currentRow.Buttons.Count >= btnCountPerRow)
|
||||||
|
{
|
||||||
|
currentRow = new KeyboardRow();
|
||||||
|
rows.Add(currentRow);
|
||||||
|
}
|
||||||
|
currentRow.Buttons.Add(button);
|
||||||
|
}
|
||||||
|
return kb;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>强制另起一行后追加按钮。</summary>
|
||||||
|
public static KeyboardMessage AppendButtonsWithNewRow(this KeyboardMessage kb, int btnCountPerRow, params KeyboardButton[] buttons)
|
||||||
|
{
|
||||||
|
KeyboardContent content = kb.Content ??= new KeyboardContent();
|
||||||
|
btnCountPerRow = Math.Clamp(btnCountPerRow, 1, KeyboardBuilder.MaxButtonsPerRow);
|
||||||
|
|
||||||
|
List<KeyboardRow> rows = content.Rows;
|
||||||
|
KeyboardRow? currentRow = null;
|
||||||
|
foreach (KeyboardButton button in buttons)
|
||||||
|
{
|
||||||
|
if (currentRow is null || currentRow.Buttons.Count >= btnCountPerRow)
|
||||||
|
{
|
||||||
|
currentRow = new KeyboardRow();
|
||||||
|
rows.Add(currentRow);
|
||||||
|
}
|
||||||
|
currentRow.Buttons.Add(button);
|
||||||
|
}
|
||||||
|
return kb;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 通用分页行。页码命令按新版 MUD 语法生成 "{command} p{n}"(v2 直接拼 "{command}{n}")。
|
||||||
|
/// </summary>
|
||||||
|
public static KeyboardMessage AddPaginationRow(this KeyboardMessage kb, string command, int currentPage, int totalPages)
|
||||||
|
{
|
||||||
|
string prefix = command.TrimEnd();
|
||||||
|
List<KeyboardButton> buttons = [];
|
||||||
|
|
||||||
|
if (currentPage > 1)
|
||||||
|
{
|
||||||
|
buttons.Add(KeyboardBuilder.CmdButton("<<", $"{prefix} p1"));
|
||||||
|
buttons.Add(KeyboardBuilder.CmdButton("<", $"{prefix} p{currentPage - 1}"));
|
||||||
|
}
|
||||||
|
|
||||||
|
buttons.Add(KeyboardBuilder.CmdButton($"{currentPage} / {totalPages}", $"{prefix} ", enter: false));
|
||||||
|
|
||||||
|
if (currentPage < totalPages)
|
||||||
|
{
|
||||||
|
buttons.Add(KeyboardBuilder.CmdButton(">", $"{prefix} p{currentPage + 1}"));
|
||||||
|
buttons.Add(KeyboardBuilder.CmdButton(">>", $"{prefix} p{totalPages}"));
|
||||||
|
}
|
||||||
|
|
||||||
|
return kb.AppendButtonsWithNewRow(KeyboardBuilder.MaxButtonsPerRow, [.. buttons]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>创建 qqbot-cmd-input 标签;thisIsText=true 时交换 this 与 text 的角色(与 v2 一致)。</summary>
|
||||||
|
public static string CreateCmdInput(this string show, string text, bool thisIsText = false)
|
||||||
|
{
|
||||||
|
string inputText = thisIsText ? show : text;
|
||||||
|
string inputShow = thisIsText ? text : show;
|
||||||
|
return QQCmdTag.CmdInput(inputText, inputShow);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>展示文本与填充内容相同的 cmd-input 标签。</summary>
|
||||||
|
public static string CreateCmdInput(this string text) => QQCmdTag.CmdInput(text);
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ using Microsoft.EntityFrameworkCore;
|
|||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using OshimaBot.Data;
|
using OshimaBot.Data;
|
||||||
using OshimaBot.Game.Services;
|
using OshimaBot.Game.Services;
|
||||||
|
using OshimaBot.Messaging;
|
||||||
using OshimaBot.Models;
|
using OshimaBot.Models;
|
||||||
using OshimaBot.Security;
|
using OshimaBot.Security;
|
||||||
using OshimaBot.Services;
|
using OshimaBot.Services;
|
||||||
@@ -56,6 +57,7 @@ builder.Services.AddHttpClient(QQBotService.HttpClientName, client =>
|
|||||||
builder.Services.AddSingleton<IQQBotService, QQBotService>();
|
builder.Services.AddSingleton<IQQBotService, QQBotService>();
|
||||||
builder.Services.AddSingleton<FunGameSimulationService>();
|
builder.Services.AddSingleton<FunGameSimulationService>();
|
||||||
builder.Services.AddSingleton<FunGameQueryService>();
|
builder.Services.AddSingleton<FunGameQueryService>();
|
||||||
|
builder.Services.AddScoped<MessageSender>();
|
||||||
builder.Services.AddScoped<RainBotService>();
|
builder.Services.AddScoped<RainBotService>();
|
||||||
builder.Services.AddSingleton<BotMessageQueue>();
|
builder.Services.AddSingleton<BotMessageQueue>();
|
||||||
builder.Services.AddHostedService<BotMessageBackgroundService>();
|
builder.Services.AddHostedService<BotMessageBackgroundService>();
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
using OshimaBot.Game.Services;
|
using OshimaBot.Game.Services;
|
||||||
|
using OshimaBot.Messaging;
|
||||||
using OshimaBot.Models;
|
using OshimaBot.Models;
|
||||||
using FunGame.Core.Library.Constant;
|
using FunGame.Core.Library.Constant;
|
||||||
|
|
||||||
@@ -8,7 +9,7 @@ namespace OshimaBot.Services
|
|||||||
public sealed class RainBotService(
|
public sealed class RainBotService(
|
||||||
FunGameQueryService queries,
|
FunGameQueryService queries,
|
||||||
FunGameSimulationService simulations,
|
FunGameSimulationService simulations,
|
||||||
IQQBotService qqBot,
|
MessageSender messageSender,
|
||||||
ILogger<RainBotService> logger)
|
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)
|
||||||
@@ -105,32 +106,8 @@ namespace OshimaBot.Services
|
|||||||
return MergeToMarkdown($"模拟结果如下(种子:{result.Seed}):", result.Messages);
|
return MergeToMarkdown($"模拟结果如下(种子:{result.Seed}):", result.Messages);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task SendAsync(IBotMessage message, BotReply reply, CancellationToken cancellationToken)
|
private Task SendAsync(IBotMessage message, BotReply reply, CancellationToken cancellationToken)
|
||||||
{
|
=> messageSender.SendAsync(message, reply, cancellationToken);
|
||||||
if (message is ThirdPartyMessage thirdParty)
|
|
||||||
{
|
|
||||||
thirdParty.Result = reply.Markdown?.Content ?? reply.Text;
|
|
||||||
thirdParty.IsCompleted = true;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
string? msgId = message.SendProactive ? null : message.Id;
|
|
||||||
if (reply.Markdown is not null && !string.IsNullOrWhiteSpace(reply.Markdown.Content))
|
|
||||||
{
|
|
||||||
if (message.IsGroup)
|
|
||||||
await qqBot.SendGroupMarkdownAsync(message.OpenId, reply.Markdown, reply.Keyboard, msgId, 1, cancellationToken);
|
|
||||||
else
|
|
||||||
await qqBot.SendC2CMarkdownAsync(message.OpenId, reply.Markdown, reply.Keyboard, msgId, 1, cancellationToken);
|
|
||||||
}
|
|
||||||
else if (!string.IsNullOrWhiteSpace(reply.Text))
|
|
||||||
{
|
|
||||||
string content = message.IsGroup ? "\r\n" + reply.Text.Trim() : reply.Text.Trim();
|
|
||||||
if (message.IsGroup)
|
|
||||||
await qqBot.SendGroupMessageAsync(message.OpenId, content, msgId: msgId, msgSeq: 1, cancellationToken: cancellationToken);
|
|
||||||
else
|
|
||||||
await qqBot.SendC2CMessageAsync(message.OpenId, content, msgId: msgId, msgSeq: 1, cancellationToken: cancellationToken);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public BotReply MergeToMarkdown(string subtitle, IReadOnlyCollection<string> messages)
|
public BotReply MergeToMarkdown(string subtitle, IReadOnlyCollection<string> messages)
|
||||||
{
|
{
|
||||||
|
|||||||
Reference in New Issue
Block a user