Skip to content
This repository has been archived by the owner on Mar 4, 2024. It is now read-only.

Commit

Permalink
Merge aec0f06 into a084dde
Browse files Browse the repository at this point in the history
  • Loading branch information
bsdayo authored Nov 27, 2022
2 parents a084dde + aec0f06 commit 6ac147e
Show file tree
Hide file tree
Showing 19 changed files with 186 additions and 51 deletions.
6 changes: 0 additions & 6 deletions Flandre.sln
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Flandre.Core", "src\Flandre.Core\Flandre.Core.csproj", "{347EE5CE-CAB6-4FFA-AAF1-D7AA7BC6AFF7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Flandre.ExampleBot", "src\Flandre.ExampleBot\Flandre.ExampleBot.csproj", "{49D31127-B126-4734-B6E4-C1A6A6A41A5E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Flandre.Adapters.Konata", "src\Flandre.Adapters.Konata\Flandre.Adapters.Konata.csproj", "{723E8DD2-55F1-4095-93D7-E6AD600A63EE}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Flandre.Core.Tests", "tests\Flandre.Core.Tests\Flandre.Core.Tests.csproj", "{22726A9B-8E54-4513-AB04-61B4A34DDC2A}"
Expand All @@ -22,10 +20,6 @@ Global
{347EE5CE-CAB6-4FFA-AAF1-D7AA7BC6AFF7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{347EE5CE-CAB6-4FFA-AAF1-D7AA7BC6AFF7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{347EE5CE-CAB6-4FFA-AAF1-D7AA7BC6AFF7}.Release|Any CPU.Build.0 = Release|Any CPU
{49D31127-B126-4734-B6E4-C1A6A6A41A5E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{49D31127-B126-4734-B6E4-C1A6A6A41A5E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{49D31127-B126-4734-B6E4-C1A6A6A41A5E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{49D31127-B126-4734-B6E4-C1A6A6A41A5E}.Release|Any CPU.Build.0 = Release|Any CPU
{723E8DD2-55F1-4095-93D7-E6AD600A63EE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{723E8DD2-55F1-4095-93D7-E6AD600A63EE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{723E8DD2-55F1-4095-93D7-E6AD600A63EE}.Release|Any CPU.ActiveCfg = Release|Any CPU
Expand Down
7 changes: 7 additions & 0 deletions src/Flandre.Adapters.Konata/KonataBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ public sealed class KonataBot : FlandreBot
/// </summary>
public override string Platform => _config.PlatformOverride ?? "konata";

/// <inheritdoc />
public override string SelfId { get; }

/// <summary>
/// Konata 内部 bot
/// </summary>
Expand Down Expand Up @@ -52,6 +55,10 @@ internal KonataBot(KonataBotConfig config, Logger logger)
Internal = BotFather.Create(config.Konata, config.Device, config.KeyStore);
_config = config;

SelfId = string.IsNullOrWhiteSpace(_config.SelfId)
? Internal.Uin.ToString()
: _config.SelfId;

Internal.OnFriendMessage += InnerOnFriendMessage;
Internal.OnGroupMessage += InnerOnGroupMessage;
Internal.OnGroupInvite += InnerOnGroupInvite;
Expand Down
4 changes: 3 additions & 1 deletion src/Flandre.Adapters.Mock/MockBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ public class MockBot : Bot
/// </summary>
public override string Platform => "mock";

public override string SelfId => _selfId;

private readonly Logger _logger;

private readonly string _selfId = Guid.NewGuid().ToString();
Expand Down Expand Up @@ -83,4 +85,4 @@ internal void ReceiveMessage(Message message, TaskCompletionSource<MessageConten
public override event BotEventHandler<BotGuildInvitedEvent>? OnGuildInvited;
public override event BotEventHandler<BotGuildJoinRequestedEvent>? OnGuildJoinRequested;
public override event BotEventHandler<BotFriendRequestedEvent>? OnFriendRequested;
}
}
6 changes: 6 additions & 0 deletions src/Flandre.Adapters.OneBot/CqCodeParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public static MessageContent ParseCqMessage(string message)
"face" => ParseFace(sections[1..]),
"record" => ParseRecord(sections[1..]),
"image" => ParseImage(sections[1..]),
"at" => ParseAt(sections[1..]),
_ => new TextSegment(code)
});
}
Expand Down Expand Up @@ -145,4 +146,9 @@ private static OneBotImageSegment ParseImage(string[] data)

return segment;
}

private static AtSegment ParseAt(string[] data)
{
return new AtSegment(data[0][3..]); // qq=xxx
}
}
11 changes: 11 additions & 0 deletions src/Flandre.Adapters.OneBot/GuildBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ public class OneBotGuildBot : Bot
/// </summary>
public override string Platform => "qqguild";

public override string SelfId => _selfId;

private string _selfId = "";
private bool _isSelfIdSet;

public OneBotGuildInternalBot Internal { get; }

private readonly OneBotBot _mainBot;
Expand All @@ -35,6 +40,12 @@ internal OneBotGuildBot(OneBotBot mainBot)

internal void InvokeMessageEvent(OneBotApiGuildMessageEvent e)
{
if (!_isSelfIdSet)
{
_selfId = e.SelfId.ToString();
_isSelfIdSet = true;
}

OnMessageReceived?.Invoke(this, new BotMessageReceivedEvent(new Message
{
Time = DateTimeOffset.FromUnixTimeSeconds(e.Time).DateTime,
Expand Down
6 changes: 5 additions & 1 deletion src/Flandre.Adapters.OneBot/OneBotBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ public abstract class OneBotBot : Bot
/// </summary>
public override string Platform => "onebot";

/// <inheritdoc />
public override string SelfId { get; }

internal readonly OneBotGuildBot GuildBot;
internal readonly Logger Logger;

Expand All @@ -24,8 +27,9 @@ public abstract class OneBotBot : Bot

protected override Logger GetLogger() => Logger;

internal OneBotBot(Logger logger)
internal OneBotBot(string selfId, Logger logger)
{
SelfId = selfId;
Internal = new OneBotInternalBot(this);
GuildBot = new OneBotGuildBot(this);
Logger = logger;
Expand Down
2 changes: 1 addition & 1 deletion src/Flandre.Adapters.OneBot/WebSocketBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public class OneBotWebSocketBot : OneBotBot
public override event BotEventHandler<BotGuildJoinRequestedEvent>? OnGuildJoinRequested;
public override event BotEventHandler<BotFriendRequestedEvent>? OnFriendRequested;

internal OneBotWebSocketBot(OneBotBotConfig config, Logger logger) : base(logger)
internal OneBotWebSocketBot(OneBotBotConfig config, Logger logger) : base(config.SelfId, logger)
{
_config = config;

Expand Down
3 changes: 1 addition & 2 deletions src/Flandre.Core/Attributes/CommandAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,7 @@ public CommandAttribute(string pattern)
}

Parameters.Add(info);

FlandreApp.Logger.Debug(Parameters.Count.ToString());

parser.SkipSpaces();
}
}
Expand Down
5 changes: 5 additions & 0 deletions src/Flandre.Core/Common/Bot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ public abstract class Bot
/// </summary>
public abstract string Platform { get; }

/// <summary>
/// Bot 自身 ID
/// </summary>
public abstract string SelfId { get; }

/// <summary>
/// 获取 Logger
/// </summary>
Expand Down
36 changes: 20 additions & 16 deletions src/Flandre.Core/Common/Command.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,8 @@ internal Command(Plugin plugin, CommandAttribute info, MethodInfo innerMethod,
{
var peek = parser.SkipSpaces().Peek(' ');

if (peek.StartsWith("--"))
if (peek.StartsWith("--")) // option (full)
{
// option (full)
var optName = parser.Read(' ').TrimStart('-');
var optNo = false;

Expand Down Expand Up @@ -96,9 +95,8 @@ internal Command(Plugin plugin, CommandAttribute info, MethodInfo innerMethod,
break;
}
}
else if (peek.StartsWith('-'))
else if (peek.StartsWith('-')) // option (short)
{
// option (short)
var opts = parser.Read(' ').TrimStart('-');

parser.SkipSpaces();
Expand Down Expand Up @@ -128,25 +126,31 @@ internal Command(Plugin plugin, CommandAttribute info, MethodInfo innerMethod,
}
}
}
else
else // argument
{
// argument
if (argIndex >= CommandInfo.Parameters.Count)
return (args, "参数过多,请检查指令格式。");

var param = CommandInfo.Parameters[argIndex];

if (param.Type == "string")
switch (param.Type)
{
args.Arguments.ArgumentList.Add(
new KeyValuePair<string, object>(param.Name, parser.ReadQuoted()));
}
else
{
if (CommandUtils.TryParseType(parser.Read(' '),
param.Type, out var result, false))
args.Arguments.ArgumentList.Add(new KeyValuePair<string, object>(param.Name, result));
else return (args, $"参数 {param.Name} 类型错误,应为 {param.Type}。");
case "string":
args.Arguments.ArgumentList.Add(
new KeyValuePair<string, object>(param.Name, parser.ReadQuoted()));
break;

case "text":
args.Arguments.ArgumentList.Add(
new KeyValuePair<string, object>(param.Name, parser.ReadToEnd()));
break;

default:
if (CommandUtils.TryParseType(parser.Read(' '),
param.Type, out var result, false))
args.Arguments.ArgumentList.Add(new KeyValuePair<string, object>(param.Name, result));
else return (args, $"参数 {param.Name} 类型错误,应为 {param.Type}。");
break;
}

providedArgs.Add(param.Name);
Expand Down
5 changes: 5 additions & 0 deletions src/Flandre.Core/Common/Context.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,9 @@ public Context(FlandreApp app, Bot bot)
/// Bot 所在平台,等同于 Bot.Platform。
/// </summary>
public string Platform => Bot.Platform;

/// <summary>
/// Bot 自身 ID,等同于 Bot.SelfId。
/// </summary>
public string SelfId => Bot.SelfId;
}
30 changes: 30 additions & 0 deletions src/Flandre.Core/Extensions/AppExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
namespace Flandre.Core.Extensions;

/// <summary>
/// <see cref="FlandreApp" /> 的扩展方法
/// </summary>
public static class AppExtensions
{
/// <summary>
/// 设置群组代理 Bot(主 Bot)
/// </summary>
/// <param name="app">FlandreApp 实例</param>
/// <param name="platform">平台</param>
/// <param name="guildId">群组 ID</param>
/// <param name="botId">Bot.SelfId</param>
public static void SetGuildAssignee(this FlandreApp app, string platform, string guildId, string botId)
{
app.GuildAssignees.AddOrUpdate($"{platform}:{guildId}", botId, (_, _) => botId);
}

/// <summary>
/// 检查群组是否已被代理(已设置主 bot)
/// </summary>
/// <param name="app">FlandreApp 实例</param>
/// <param name="platform">平台</param>
/// <param name="botId">Bot.SelfId</param>
public static bool IsGuildAssigned(this FlandreApp app, string platform, string botId)
{
return app.GuildAssignees.ContainsKey($"{platform}:{botId}");
}
}
19 changes: 19 additions & 0 deletions src/Flandre.Core/Extensions/ContextExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using Flandre.Core.Messaging;

namespace Flandre.Core.Extensions;

/// <summary>
/// 上下文扩展方法
/// </summary>
public static class ContextExtensions
{
/// <summary>
/// 将 Bot 设置为群组主 Bot
/// </summary>
/// <param name="ctx">消息上下文</param>
public static void SetBotAsGuildAssignee(this MessageContext ctx)
{
if (ctx.GuildId is null) return;
ctx.App.SetGuildAssignee(ctx.Platform, ctx.GuildId, ctx.SelfId);
}
}
2 changes: 1 addition & 1 deletion src/Flandre.Core/Flandre.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<PropertyGroup>
<Title>Flandre.Core</Title>
<Product>$(Title)</Product>
<PackageVersion>0.5.0</PackageVersion>
<PackageVersion>0.6.0</PackageVersion>
<Version>$(PackageVersion)</Version>
<Authors>b1acksoil</Authors>
<Description>跨平台,低耦合的聊天机器人框架,一次编写,多处运行。</Description>
Expand Down
32 changes: 15 additions & 17 deletions src/Flandre.Core/FlandreApp.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Runtime.CompilerServices;
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using Flandre.Core.Common;
using Flandre.Core.Events.App;
using Flandre.Core.Events.Plugin;
Expand All @@ -17,7 +18,7 @@ namespace Flandre.Core;
/// <summary>
/// 应用基本框架
/// </summary>
public class FlandreApp
public partial class FlandreApp
{
internal readonly List<IAdapter> Adapters = new();
internal readonly List<Func<MessageContext, Action, Task>> Middlewares = new();
Expand All @@ -32,6 +33,8 @@ public class FlandreApp

internal Dictionary<string, Command> ShortcutMap { get; } = new();

internal ConcurrentDictionary<string, string> GuildAssignees { get; } = new();

/// <summary>
/// App 配置
/// </summary>
Expand Down Expand Up @@ -253,22 +256,14 @@ void CatchAndLog(Action action) => Task.Run(() =>
}
}

// 群组 assignee 检查
Use(CheckAssigneeMiddleware);

// 插件 OnMessageReceived
Use((ctx, next) =>
{
foreach (var plugin in Plugins)
plugin.OnMessageReceived(ctx);
next();
});
Use(PluginMessageReceivedMiddleware);

// 指令解析中间件
Use((ctx, next) =>
{
var content = ParseCommand(ctx);
if (content is not null)
ctx.Bot.SendMessage(ctx.Message, content);
next();
});
Use(ParseCommandMiddleware);
}

private void ExecuteMiddlewares(MessageContext ctx, int index)
Expand Down Expand Up @@ -305,7 +300,8 @@ private void ExecuteMiddlewares(MessageContext ctx, int index)
}

var commandStr = ctx.Message.GetText().Trim();
if (commandStr == Config.CommandPrefix) return null;
if (commandStr == Config.CommandPrefix)
return null;

var parser = new StringParser(commandStr);

Expand All @@ -314,7 +310,9 @@ private void ExecuteMiddlewares(MessageContext ctx, int index)
if (ShortcutMap.TryGetValue(root, out var command))
return ParseAndInvoke(command, parser);


if (!string.IsNullOrWhiteSpace(Config.CommandPrefix)
&& !root.StartsWith(Config.CommandPrefix))
return null;
root = root.TrimStart(Config.CommandPrefix);
parser.SkipSpaces();

Expand Down
Loading

0 comments on commit 6ac147e

Please sign in to comment.