OneBot.Net.Sdk 1.0.0

dotnet add package OneBot.Net.Sdk --version 1.0.0
                    
NuGet\Install-Package OneBot.Net.Sdk -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="OneBot.Net.Sdk" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="OneBot.Net.Sdk" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="OneBot.Net.Sdk" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add OneBot.Net.Sdk --version 1.0.0
                    
#r "nuget: OneBot.Net.Sdk, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package OneBot.Net.Sdk@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=OneBot.Net.Sdk&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=OneBot.Net.Sdk&version=1.0.0
                    
Install as a Cake Tool

<div align="center">

🤖 OneBot.Net.Sdk

基于 .NET 8 的 OneBot 11 协议 SDK —— 快速开发你的 QQ 机器人

.NET OneBot 11 NapCat License

</div>


🌟 项目简介

OneBot.Net.Sdk 是一个轻量、优雅、可扩展的 .NET SDK,用于对接遵循 OneBot 11 协议的 QQ 机器人实现(如 NapCatQQ、go-cqhttp 等)。

只需几行代码,即可完成 连接 → 接收事件 → 调用接口 的完整链路,让你专注于业务逻辑,而无需关心 WebSocket 的收发、重连、请求关联等底层细节。

// 收到私聊消息,直接复读回去 —— 就这么简单
public async Task HandleAsync(PrivateMessageEvent e, EventContext ctx, CancellationToken ct)
    => await ctx.Api.SendPrivateMsgAsync(e.UserId, e.Message, ct);

✨ 核心特性

特性 说明
🔌 稳定的 WebSocket 连接 正向连接 NapCat,内置心跳、消息分片重组、指数退避自动重连
📡 完整的事件体系 元事件 / 消息事件 / 通知事件 / 请求事件全量建模,两级 sub_type 精确解析
🎯 灵活的事件分发 支持 DI 的 IEventHandler<T> 与委托 Subscribe<T>(),可按基类捕获一类事件
🛠️ 丰富的 API 封装 发消息、撤回、群管理、好友操作、点赞、戳一戳…… 强类型返回
💬 优雅的消息构造 MessageSegment 工厂 + MessageBuilder 链式构建,兼容字符串 / 消息段数组
🔗 可靠的请求响应 基于 echo 关联响应,支持超时;断线时未完成请求立即失败
⚙️ 标准 .NET 生态 基于 Microsoft.Extensions 的配置、日志与依赖注入,与 Generic Host 无缝集成
🧩 协议无关 仅依赖 OneBot 11 协议,适用于任意兼容实现

📦 环境要求

  • ✅ .NET SDK 8.0 或更高版本
  • ✅ 一个已运行并开启 正向 WebSocket 的 OneBot 11 实现(推荐 NapCatQQ)

🚀 安装

方式一:项目引用(当前)

<ItemGroup>
  <ProjectReference Include="..\OneBot.Net.Sdk\OneBot.Net.Sdk.csproj" />
</ItemGroup>

方式二:NuGet(发布后)

dotnet add package OneBot.Net.Sdk

⚡ 快速开始

1️⃣ 配置连接

在 appsettings.json 中填写 NapCat 的正向 WebSocket 地址与令牌:

{
  "OneBot": {
    "WebSocketUrl": "ws://127.0.0.1:3001",  // NapCat 正向 WS 地址
    "AccessToken": "你的 access_token",      // 留空表示不鉴权
    "ApiTimeoutMs": 10000,                    // API 调用超时(毫秒)
    "Reconnect": {
      "Enabled": true,                        // 断线自动重连
      "InitialDelayMs": 1000,                 // 首次重连延迟
      "MaxDelayMs": 30000                     // 重连延迟上限(指数退避)
    }
  }
}

2️⃣ 注册服务与启动

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using OneBot.Net.Sdk;
using OneBot.Net.Sdk.Dispatching;
using OneBot.Net.Sdk.Events;

var builder = Host.CreateApplicationBuilder(args);

// 注册 OneBot SDK(连接、API、事件分发、后台驱动)
builder.Services.AddOneBot(builder.Configuration);

// 注册你的业务处理器
builder.Services.AddSingleton<IEventHandler<PrivateMessageEvent>, MyHandler>();

await builder.Build().RunAsync();

3️⃣ 编写业务处理器

using OneBot.Net.Sdk.Api;
using OneBot.Net.Sdk.Dispatching;
using OneBot.Net.Sdk.Events;

public sealed class MyHandler : IEventHandler<PrivateMessageEvent>
{
    public async Task HandleAsync(PrivateMessageEvent e, EventContext ctx, CancellationToken ct)
    {
        Console.WriteLine($"[私聊] {e.UserId}: {e.RawMessage}");
        await ctx.Api.SendPrivateMsgAsync(e.UserId, e.Message, ct); // 复读
    }
}

💡 TEvent 可以是具体事件类型,也可以是基类(如 MessageEvent、GroupNoticeEvent、OneBotEvent)以捕获整类事件。


📖 使用说明

🎧 接收事件

实现 IEventHandler<TEvent> 并注册到 DI:

builder.Services.AddSingleton<IEventHandler<GroupMessageEvent>, GroupMessageHandler>();

或使用委托订阅(适合轻量场景):

// 订阅某一类事件
dispatcher.Subscribe<GroupRecallEvent>(async (e, ctx, ct) =>
{
    Console.WriteLine($"群 {e.GroupId} 撤回了消息 {e.MessageId}");
});

// 订阅所有事件(日志、埋点等)
dispatcher.Subscribe<OneBotEvent>((e, ctx, ct) =>
{
    Console.WriteLine($"[事件] {e.PostType}");
    return Task.CompletedTask;
});

📤 调用 API

所有接口通过 EventContext.Api(或从 DI 注入 IOneBotApi)调用:

// —— 消息 ——
long id = await api.SendPrivateMsgAsync(userId, "你好", ct);
long id2 = await api.SendGroupMsgAsync(groupId, "大家好", ct);
await api.DeleteMsgAsync(messageId, ct);

// —— 好友 ——
var login    = await api.GetLoginInfoAsync(ct);
var friends  = await api.GetFriendListAsync(ct);
await api.FriendPokeAsync(userId, ct);
await api.SendLikeAsync(userId, times: 1, ct);

// —— 群管理 ——
var groups  = await api.GetGroupListAsync(ct);
var members = await api.GetGroupMemberListAsync(groupId, ct);
await api.SetGroupBanAsync(groupId, userId, 600, ct);   // 禁言 600 秒
await api.SetGroupKickAsync(groupId, userId, ct);       // 踢出
await api.SetGroupAdminAsync(groupId, userId, true, ct); // 设置管理员

// —— 请求处理 ——
await api.SetFriendAddRequestAsync(flag, approve: true, remark: "欢迎", ct);

🔧 未封装的接口可直接调用底层方法:

var response = await api.CallAsync("some_action", new { foo = "bar" }, ct);
var data = await api.CallAsync<MyData>("some_action", new { foo = "bar" }, ct); // 失败抛 OneBotApiException

💬 构造消息

using OneBot.Net.Sdk.Messages;

// 纯文本
await api.SendGroupMsgAsync(groupId, "你好", ct);

// 链式构建
var message = new MessageBuilder()
    .Reply(messageId)
    .At(userId)
    .Text(" 欢迎!")
    .Image("https://example.com/a.png")
    .Build();
await api.SendGroupMsgAsync(groupId, message, ct);

// 或使用消息段工厂
var message2 = new Message(new[]
{
    MessageSegment.At(userId),
    MessageSegment.Text(" 早上好"),
});

可用消息段:Text · At · AtAll · Image · Face · Reply · Record,或 MessageSegment.Create(type, data) 自定义。

⚙️ 配置项

字段 类型 默认值 说明
WebSocketUrl string ws://127.0.0.1:3001 正向 WebSocket 地址
AccessToken string? - 作为 access_token 查询参数附加
ApiTimeoutMs int 10000 API 调用超时
Reconnect.Enabled bool true 是否自动重连
Reconnect.InitialDelayMs int 1000 首次重连延迟
Reconnect.MaxDelayMs int 30000 重连延迟上限

📋 已建模事件

分类 事件类型
🧩 元事件 HeartbeatEvent、LifecycleEvent
💬 消息 PrivateMessageEvent、GroupMessageEvent、MessageSentEvent
📨 请求 FriendRequestEvent、GroupRequestEvent
🔔 通知 FriendAddEvent、FriendRecallEvent、GroupRecallEvent、GroupIncreaseEvent、GroupDecreaseEvent、GroupAdminEvent、GroupBanEvent、GroupUploadEvent、GroupCardEvent、GroupMsgEmojiLikeEvent、GroupEssenceEvent、BotOfflineEvent
👆 notify FriendPokeEvent、GroupPokeEvent、ProfileLikeEvent、InputStatusEvent、GroupNameEvent、GroupTitleEvent、GroupGrayTipEvent

所有事件均继承自 OneBotEvent(含 Time、SelfId、PostType);无法识别的事件以 UnknownEvent 分发,原始 JSON 保存在 Raw。


🗂️ 项目结构

OneBot.Net.Sdk/
├─ Configuration/   # OneBotOptions 配置
├─ Connection/      # WebSocket 连接、重连、心跳
├─ Events/          # 事件模型 + EventParser
├─ Messages/        # Message / MessageSegment / MessageBuilder
├─ Dispatching/     # 事件分发与 IEventHandler
├─ Api/             # IOneBotApi、扩展方法、响应模型
└─ OneBotServiceCollectionExtensions.cs

🙏 鸣谢

本项目的诞生离不开以下优秀开源项目与社区,特此致谢:

项目 说明 链接
🐱 NapCatQQ 基于 NTQQ 的 OneBot 11 实现,本 SDK 的主要对接目标 https://github.com/NapNeko/NapCatQQ
📜 OneBot 11 OneBot 11 协议规范,本 SDK 的理论依据 https://github.com/botuniverse/onebot-11
🔗 OneBot 统一的聊天机器人应用接口标准 https://github.com/botuniverse/onebot
🚀 go-cqhttp 经典的 OneBot 实现(协议行为参考) https://github.com/Mrs4s/go-cqhttp
🧩 .NET / Microsoft.Extensions 运行时,以及配置、日志、依赖注入基础设施 https://github.com/dotnet/runtime

感谢以上项目及其贡献者的无私奉献 ❤️


📄 许可证

本项目基于 MIT License 开源。

Copyright © 2026 WorldmeQC

详见 LICENSE。


<div align="center">

⭐ 如果这个项目对你有帮助,欢迎点个 Star!

Made with ❤️ by WorldmeQC

</div>

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0 94 9/24/2026