dsh-shlr-bilitoolkit 0.1.19 → 0.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -6,5 +6,4 @@
6
6
  禁止只给链接、用 ASCII、让用户自己跑命令。用户确认后调 bili_login_status 完成登录。
7
7
 
8
8
  ## 其它
9
- - 非常驻的 B 站能力懒加载:`bili_open()` 看分组,`bili_open({ group })` 打开(下一轮生效)。
10
- - 写操作会真实修改账号状态,执行前先与用户确认。
9
+ 写操作(点赞 / 收藏 / 投币 / 关注 / 评论 / 私信 / 三连 / 发动态 / 改资料)会真实修改账号状态,执行前先与用户确认。
package/README.md CHANGED
@@ -1,98 +1,129 @@
1
1
  # dsh-shlr-bilitoolkit
2
2
 
3
- B 站(哔哩哔哩)接口封装的 **TypeScript** 移植版,作为 [dsh](https://dshmp.com)(DeepSeek Harness)插件提供「视频 / 搜索 / 空间 / 专栏 / 动态 / 评论 / 关注 / 消息中心」等读取能力,以及点赞、收藏、投币、关注、评论、私信、三连、发动态等写操作。
3
+ 0.1.15-0.1.19为工具懒加载版,
4
4
 
5
- > 本项目从原 Python 工具箱(`bili/`)完整移植而来,并作为 dsh(cordis 体系)插件提供上述能力。
5
+ B 站(哔哩哔哩)接口封装的 **TypeScript** 移植版,作为 [dsh](https://dshmp.com)(DeepSeek Harness)插件提供「视频 / 搜索 / 空间」等读取能力。
6
6
 
7
- ## 安装
7
+ > 本项目从原 Python 工具箱(`bili/`)完整移植而来,覆盖视频、搜索、空间、评论、私信、互动(点赞/收藏/投币/关注/三连)、动态、专栏、关注关系、消息中心、个人资料与扫码登录,并作为 [dsh](https://dshmp.com)(DeepSeek Harness)插件提供上述能力。
8
8
 
9
- ```bash
10
- # 已发布到 npm
11
- dsh plugin --profile <name> add dsh-shlr-bilitoolkit@latest
9
+ ## 目录结构
12
10
 
13
- # 本地开发 / 试运行
14
- npm install
15
- npm run build
11
+ ```
12
+ dsh-shlr-bilitoolkit/
13
+ ├── src/
14
+ │ ├── client.ts # BiliClient:Session / Cookie / 请求 / 节流 / 重试 / 风控 / 表单编码
15
+ │ ├── wbi.ts # WbiSigner:w_rid / wts 签名(含官方 mixin_key 算法)
16
+ │ ├── errors.ts # BiliApiError / CaptchaRequired / CookieError
17
+ │ ├── models.ts # Video / Article / Comment / PrivateMessage / RelationUser /
18
+ │ │ # Dynamic / Notice / User / Page / PlayInfo / Subtitle / Collection
19
+ │ ├── formatting.ts # 播放量、时长、HTML 清理等展示格式化
20
+ │ ├── pagination.ts # iterPages:统一翻页异步生成器
21
+ │ ├── endpoints.ts # 所有接口 URL 常量
22
+ │ ├── apis/
23
+ │ │ ├── video.ts # 推荐流 / 详情 / 分P / 播放地址 / 字幕
24
+ │ │ ├── search.ts # 搜索视频 / 用户
25
+ │ │ ├── space.ts # 空间信息 / 投稿 / 合集
26
+ │ │ ├── comment.ts # 评论:视频/动态/专栏 的读取与发表/回复/删除
27
+ │ │ ├── message.ts # 私信:发送 / 撤回 / 记录 / 未读
28
+ │ │ ├── interact.ts # 点赞 / 收藏 / 投币 / 关注 / 三连
29
+ │ │ ├── dynamic.ts # 动态:关注流 / 空间 / 发布 / 转发 / 点赞 / 删除
30
+ │ │ ├── article.ts # 专栏:详情 / UP 主列表
31
+ │ │ ├── relation.ts # 关注 / 粉丝 / 统计
32
+ │ │ ├── notify.ts # 消息中心:未读 / 回复我的 / @我的 / 收到的赞
33
+ │ │ ├── profile.ts # 个人资料:读取 / 改签名 / 改昵称性别生日
34
+ │ │ ├── auth.ts # 扫码登录(generate / poll / wait / login)
35
+ │ │ └── download.ts # 下载与 ffmpeg 合并工具
36
+ │ ├── dsh.ts # dsh 插件入口:apply(ctx) + 工具列表
37
+ │ └── index.ts # 对外导出
38
+ ├── tests/ # 离线单测(wbi 签名、格式化、模型)
39
+ ├── cordis.patch.yml # dsh bundle 的配置补丁
40
+ ├── dsh-manifest.json # 市场目录收录清单(schema v1)
41
+ ├── package.json # 含 dsh.bundle.patch 声明
42
+ └── tsconfig.json
16
43
  ```
17
44
 
18
- 本地登录(独立获取 Cookie,终端打印 ASCII 二维码):
45
+ ## 构建与测试
19
46
 
20
47
  ```bash
21
- npm install && npm run login
22
- # 或指定 Cookie 文件
23
- BILI_COOKIE_FILE=./my_cookies.json npm run login
48
+ npm install
49
+ npm run typecheck # tsc --noEmit
50
+ npm test # 离线单测(node --test + tsx)
51
+ npm run build # 产出 dist/
24
52
  ```
25
53
 
26
- ## 插件入口
27
-
28
- 对齐官方 cordis 规范:`src/dsh.ts` 导出 `name` / `inject = ["tools"]` / `apply(ctx)`,在 `apply` 内用官方 `ctx.tools.register(defineTool({ name, description, parameters, output, execute }))` 注册每个工具。`defineTool` 来自 `@deepseek-ai/dsh-tools`,由宿主提供、插件不打包(保证单实例),已在 `peerDependencies` 声明。`cordis.patch.yml` 为组合包配置层(`- insert: - id: bili name: dsh-shlr-bilitoolkit`,按包名解析到 `main`)。较旧、没有 `ctx.tools` 的 dsh 仍保留 `ctx.registerTool` / `ctx.services.tools.register` 回退。
54
+ > 说明:`tsconfig` 使用 `moduleResolution: Bundler`,相对导入不带扩展名,适合被 dsh 运行时(基于打包器的 cordis 应用)消费。若要在原生 Node ESM 下直接 `node dist/index.js`,需改用 `NodeNext` 并补 `.js` 扩展名。
29
55
 
30
- ## 工具清单
56
+ ## 当作库用
31
57
 
32
- 同类能力已用参数合并(`type` / `target` / `action` / `list`),**功能未减少**。
58
+ ```ts
59
+ import { BiliClient } from "dsh-shlr-bilitoolkit";
33
60
 
34
- - **读取**:
35
- `bili_recommend` · `bili_video_detail` · `bili_video_subtitle` · `bili_search` · `bili_space_info` · `bili_space_videos` · `bili_article_view` · `bili_article_list` · `bili_dynamic_feed` · `bili_dynamic_space` · `bili_comment_list` · `bili_relation_list` · `bili_notify_unread` · `bili_notify_list` · `bili_fav_folders` · `bili_video_pagelist` · `bili_video_playurl` · `bili_video_status` · `bili_space_collections` · `bili_space_collection` · `bili_fav_folder_videos` · `bili_dynamic_detail` · `bili_message_unread` · `bili_message_history` · `bili_relation_stat` · `bili_user_following` · `bili_profile_info` · `bili_comment_replies`
36
- - **写操作**(均会真实修改账号状态,需登录):
37
- `bili_like` · `bili_follow` · `bili_favorite` · `bili_send_message` · `bili_triple` · `bili_dynamic_publish` · `bili_dynamic_repost` · `bili_coin` · `bili_fav_folder_create` · `bili_fav_folder_delete` · `bili_dynamic_like` · `bili_dynamic_delete` · `bili_comment_send` · `bili_comment_reply` · `bili_comment_delete` · `bili_comment_like` · `bili_message_recall` · `bili_profile_update`
38
- - **辅助**:`bili_login_status`(查登录态)· `bili_gen_qr`(生成登录二维码)· `bili_cache_clear`(清空本地缓存)
61
+ const client = new BiliClient({ cookieFile: "bili_cookies.json" });
62
+ await client.loadCookies();
39
63
 
40
- 合并工具的公共参数约定:
41
-
42
- | 工具 | 参数 |
43
- | --- | --- |
44
- | `bili_search` | `type=video\|user`,`order`(仅视频) |
45
- | `bili_relation_list` | `type=followings\|followers` |
46
- | `bili_notify_list` | `type=replies\|ats\|likes` |
47
- | `bili_favorite` | `action=add\|remove` |
48
- | `bili_video_subtitle` | `list=true` 时列字幕轨,否则取正文 |
49
- | `bili_comment_*` | `target=video\|dynamic\|article`,`id`(bvid / 动态 id / 专栏 cv 号) |
50
- | `bili_profile_update` | `uname` / `sex` / `birthday` / `sign`(至少一项) |
64
+ const videos = await client.video.recommend(2, 10);
65
+ const detail = await client.video.detail("BV1xx411c7mD");
66
+ const text = await client.video.subtitleText("BV1xx411c7mD"); // 字幕纯文本
67
+ const [videos2, total] = await client.search.videos("孤独摇滚");
68
+ const info = await client.space.info(574115689);
69
+ const [ups, _] = await client.space.videos(574115689, 1, 10);
70
+ ```
51
71
 
52
- ## 数据目录
72
+ ## 作为 dsh 插件
53
73
 
54
- Cookie / 缓存 / 二维码 / 设备号统一放在一个目录,默认 `bili_data/`(相对 dsh 工作目录),避免散落污染工作目录:
74
+ - 包名 `dsh-shlr-bilitoolkit`(符合 `dsh-` 前缀约定),`package.json` 里声明了 `dsh.bundle.patch: ./cordis.patch.yml`,因此会被 dsh 识别为插件而非普通库。
75
+ - 入口 `src/dsh.ts` 导出 `apply(ctx)`,注册一组工具(读取为主,写操作明确标注「需登录 / 谨慎」):
76
+ - 读取:`bili_recommend` / `bili_video_detail` / `bili_video_subtitle` / `bili_search_video` / `bili_search_user` / `bili_space_info` / `bili_space_videos` / `bili_article_view` / `bili_article_list` / `bili_dynamic_feed` / `bili_dynamic_space` / `bili_comment_list` / `bili_relation_followings` / `bili_relation_followers` / `bili_notify_unread` / `bili_notify_replies` / `bili_fav_folders` / `bili_video_pagelist` / `bili_video_subtitles` / `bili_video_playurl` / `bili_video_status` / `bili_space_collections` / `bili_space_collection` / `bili_fav_folder_videos` / `bili_dynamic_detail` / `bili_notify_ats` / `bili_notify_likes` / `bili_message_unread` / `bili_message_history` / `bili_relation_stat` / `bili_user_following` / `bili_profile_info` / `bili_comment_replies`
77
+ - 写操作:`bili_like` / `bili_follow` / `bili_favorite` / `bili_send_comment` / `bili_send_message` / `bili_triple` / `bili_dynamic_publish` / `bili_dynamic_repost` / `bili_coin` / `bili_unfavorite` / `bili_fav_folder_create` / `bili_fav_folder_delete` / `bili_dynamic_like` / `bili_dynamic_delete` / `bili_comment_send` / `bili_comment_reply` / `bili_comment_delete` / `bili_comment_like` / `bili_message_recall` / `bili_profile_update_sign` / `bili_profile_update`(均会真实修改账号状态,需登录)
78
+ - 辅助:`bili_login_status`(查登录态)/ `bili_gen_qr`(生成扫码登录二维码)/ `bili_cache_clear`(清空本地缓存)
79
+ - 工具读取 `BILI_COOKIE_FILE`(默认 `bili_data/bili_cookies.json`)作为登录态。
80
+ - **数据目录**:Cookie / 缓存 / 二维码 / 设备号统一放在一个目录里,默认 `bili_data/`(相对 dsh 工作目录),避免散落污染工作目录。可用 `BILI_DATA_DIR` 改目录;`BILI_COOKIE_FILE` / `BILI_CACHE_FILE` / `BILI_QR_FILE` / `BILI_DEVICE_FILE` 可精确指定单个文件。设备号(私信 `dev_id`)会落盘到 `bili_data/bili_device.json`,跨重启保持稳定,避免被 B 站当成新设备触发风控。兼容旧版:若新目录还没有 Cookie、而旧位置(`./bili_cookies.json`)有,会继续沿用旧的。
81
+ - **扫码登录(独立获取 Cookie)**:运行 `npm run login`,终端会打印 ASCII 二维码,用「哔哩哔哩」App 扫码并确认后,Cookie 自动写入 `bili_data/bili_cookies.json`。也可在对话里先调 `bili_login_status` 查登录态、调 `bili_gen_qr` 拿二维码链接与可直接展示的 `ascii` 二维码。写操作(点赞 / 收藏 / 投币 / 关注 / 评论 / 私信 / 三连)都依赖该 Cookie 中的 `SESSDATA` / `bili_jct`。
82
+ - **缓存持久化**:除 Cookie 外,客户端还会把 WBI 签名密钥(`B 站每天轮换`)、`bvid→aid` 映射这类稳定 / 带 TTL 的数据写入本地 JSON 缓存(`BILI_CACHE_FILE`,默认 `bili_data/bili_cache.json`),用临时文件 + 原子替换落盘、文件损坏会自动自愈。冷启动或跨进程时直接复用,避免每次都请求 `nav` 接口;密钥过期或失效时 `refresh()` 会重新拉取并覆盖缓存。若签名反复报 `-403/-352`,可调用 `bili_cache_clear` 强制清空缓存后重试(不影响 Cookie / 登录态)。
83
+ - **计费 / 缓存与懒加载**:默认**稳定注册全部工具**,让 prompt 前缀保持不变、最大化 DeepSeek 前缀缓存命中(未命中价 ≈ 命中价 50 倍,中途改工具列表反而更贵)。列表类工具默认**精简返回**(`full=true` 取全量)。如确认提供商不做前缀缓存、想极致压缩每轮 schema,设 `BILI_LAZY=1` 开启懒加载(常驻核心 + `bili_open` 按需开组,下一轮生效)。
55
84
 
56
- | 文件 | 用途 |
57
- | --- | --- |
58
- | `bili_cookies.json` | 登录 Cookie(`SESSDATA` / `bili_jct`) |
59
- | `bili_cache.json` | WBI 签名密钥 + `bvid→aid` 缓存(原子写、损坏自愈) |
60
- | `bili_qrcode.png` | 最近一次生成的登录二维码 |
61
- | `bili_device.json` | 私信设备号 `dev_id`(跨重启稳定,降低风控) |
85
+ > **给 Agent 的约定**:仓库根目录的 [`AGENTS.md`](./AGENTS.md) 写明了登录流程——需要登录时必须调用 `bili_gen_qr` 并把二维码**图片**展示给用户,而不是只给链接或 ASCII。把这份 `AGENTS.md` 放到 dsh 的工作目录(或确保你的 dsh 会读取它),agent 就会按约定输出登录二维码。
62
86
 
63
- 可用环境变量:`BILI_DATA_DIR`(改目录)、`BILI_COOKIE_FILE` / `BILI_CACHE_FILE` / `BILI_QR_FILE` / `BILI_DEVICE_FILE`(精确指定单个文件)。兼容旧版:若新目录还没有 Cookie、而旧位置 `./bili_cookies.json` 有,会继续沿用。
87
+ 安装到 dsh(任选其一,取决于你的发行方式):
64
88
 
65
- ## 给 Agent 的约定
89
+ ```bash
90
+ dsh plugin --profile <name> add dsh-shlr-bilitoolkit # 已发布到 npm
91
+ dsh plugin --profile <name> add github:your-name/dsh-shlr-bilitoolkit#<ref>
92
+ ```
66
93
 
67
- 仓库根目录的 [`AGENTS.md`](./AGENTS.md) 约定:需要登录时必须调用 `bili_gen_qr` 并把二维码**图片**展示给用户(而非只给链接或 ASCII)。把该 `AGENTS.md` 放到 dsh 工作目录,agent 即会遵守。
94
+ > 插件入口已对齐 **官方 DeepSeek Harness(cordis 体系)** 的约定:模块导出 `name` / `inject = ["tools"]` / `apply(ctx)`,并在 `apply` 内用官方 `ctx.tools.register(defineTool({ name, description, parameters, output, execute }))` 注册每个工具(`defineTool` 来自 `@deepseek-ai/dsh-tools`,由宿主提供、插件不打包,保证单实例)。`parameters` 用官方简化 schema(`{ 参数名: { type, required, description, enum? } }`),工具返回规范 JSON 值,由 `output.render` 转成面向模型的文本。`cordis.patch.yml` 是官方组合包配置层(`- insert: - id: bili name: dsh-shlr-bilitoolkit`,按包名解析到 `main` 入口)。若你的 dsh 版本较旧、没有 `ctx.tools`,`apply` 仍保留了 `ctx.registerTool` / `ctx.services.tools.register` 的回退路径。
68
95
 
69
- ## 目录结构
96
+ ## 与原 Python 版的对应关系
70
97
 
71
- ```
72
- src/
73
- client.ts BiliClient:Session / Cookie / 请求 / 节流 / 重试 / 风控 / 表单编码
74
- wbi.ts WbiSigner:w_rid / wts 签名(官方 mixin_key 算法,密钥落盘缓存 6h)
75
- cache.ts JsonCache:本地 JSON 缓存(TTL / 原子写 / 损坏自愈)
76
- errors.ts BiliApiError / CaptchaRequired / CookieError
77
- models.ts 纯数据模型 + toDict()
78
- formatting.ts 播放量 / 时长 / HTML 清理等展示格式化
79
- pagination.ts iterPages:统一分页异步生成器
80
- endpoints.ts 所有接口 URL 常量
81
- apis/ video / search / space / comment / message / interact / dynamic /
82
- article / relation / notify / profile / auth / download
83
- dsh.ts dsh 插件入口:apply(ctx) + 工具清单
84
- index.ts 对外导出
85
- tests/ 离线单测(wbi 签名、格式化、缓存、lossless JSON 等)
86
- cordis.patch.yml dsh 组合包配置层
87
- scripts/login.ts npm run login 扫码登录脚本
88
- ```
98
+ | Python | TS |
99
+ | --- | --- |
100
+ | `bili/client.py` | `src/client.ts` |
101
+ | `bili/wbi.py` | `src/wbi.ts` |
102
+ | `bili/video.py` | `src/apis/video.ts` |
103
+ | `bili/search.py` | `src/apis/search.ts` |
104
+ | `bili/space.py` | `src/apis/space.ts` |
105
+ | `bili/comment.py` | `src/apis/comment.ts` |
106
+ | `bili/message.py` | `src/apis/message.ts` |
107
+ | `bili/interact.py` | `src/apis/interact.ts` |
108
+ | `bili/dynamic.py` | `src/apis/dynamic.ts` |
109
+ | `bili/article.py` | `src/apis/article.ts` |
110
+ | `bili/relation.py` | `src/apis/relation.ts` |
111
+ | `bili/notify.py` | `src/apis/notify.ts` |
112
+ | `bili/profile.py` | `src/apis/profile.ts` |
113
+ | `bili/auth.py` | `src/apis/auth.ts` |
114
+ | `bili/download.py` | `src/apis/download.ts` |
115
+ | `bili/models.py` | `src/models.ts` |
116
+ | `bili/formatting.py` | `src/formatting.ts` |
117
+ | `bili/pagination.py` | `src/pagination.ts` |
118
+
119
+ 约定保持一致:`client.xxx.yyy()` 调用风格、`iter_*` 异步生成器、`toDict()` 导出、WBI 签名算法与密钥 6 小时缓存(已落地到 `bili_cache.json`,跨进程复用)。
89
120
 
90
121
  ## 与原 Python 版的差异 / 已知限制
91
122
 
92
- - **写接口为表单编码**:`client.post` 默认把对象编码为 `application/x-www-form-urlencoded`,仅动态点赞等少数接口显式走 JSON(`jsonBody=true`)。
93
- - **动态仅支持纯文字**:带图 / 投票 / 预约的富动态需额外图片上传流程,暂未实现。
94
- - **下载 / ffmpeg**:`src/apis/download.ts` 为纯工具函数,未接入 dsh 工具。
123
+ - **写接口为表单编码**:原 Python 用 `requests` 的 `data=` 默认表单;本包的 `client.post` 默认把对象编码为 `application/x-www-form-urlencoded`,仅动态点赞等少数接口显式走 JSON(`jsonBody=true`)。
124
+ - **图文动态**:`bili_dynamic_publish` 支持「文字 + 本地图片」(先上传 B 站动态图床拿到 url/尺寸,再带 `pictures` 以 type=2 创建)。上传 / pictures 组装按社区通用接口实现,**未在真实账号验证**;若失败请把报错码反馈回来校准。
125
+ - **下载 / ffmpeg**:`src/apis/download.ts` 提供 `downloadUrl` / `mergeWithFfmpeg`,为纯工具函数,未接入 dsh 工具(下载行为在 dsh 里通常不合适)。
95
126
 
96
127
  ## 风控说明
97
128
 
98
- 内置与原 Python 版一致的基础降风控策略:请求节流(默认 0.6s + 0~0.4s 抖动)、GET 退避重试、写操作不重试、HTTP 412 / `-412` 立即停手、WBI 签名。但单账号操作量上限、避免短时间切 IP/UA 等仍需使用习惯配合。设备号 `dev_id` 已落盘保持稳定。
129
+ 本包内置与原 Python 版一致的基础降风控策略:请求节流(默认 0.6s + 0~0.4s 抖动)、GET 退避重试、写操作不重试、HTTP 412 / `-412` 立即停手、WBI 签名。但单账号操作量上限、避免短时间切 IP/UA 等仍需使用习惯配合。
@@ -15,6 +15,13 @@ export declare class DynamicAPI {
15
15
  iterFeed(maxPages?: number, type?: string): AsyncGenerator<Dynamic>;
16
16
  iterSpace(uid: number, maxPages?: number): AsyncGenerator<Dynamic>;
17
17
  publish(text: string, atUids?: number[], ctrl?: any[], closeComment?: boolean): Promise<string>;
18
+ /** 上传单张图片到 B 站动态图床,返回 pictures 需要的一段信息。 */
19
+ private uploadImage;
20
+ /** 发布图文动态(文字 + 最多若干张图片)。图片可以是本地路径或 Buffer。 */
21
+ publishWithImages(text: string, images: Array<string | Buffer>, opts?: {
22
+ atUids?: number[];
23
+ closeComment?: boolean;
24
+ }): Promise<string>;
18
25
  repost(dynamicId: string | number, text?: string): Promise<string>;
19
26
  thumb(dynamicId: string | number, liked?: boolean): Promise<void>;
20
27
  delete(dynamicId: string | number): Promise<void>;
@@ -3,9 +3,13 @@
3
3
  读取走网页版 polymer 接口,需要登录态。写操作(publish / repost / thumb /
4
4
  delete)都是公开行为,受风控和人机验证限制,使用前请自行确认。
5
5
  */
6
+ import { readFile } from "node:fs/promises";
7
+ import { basename } from "node:path";
8
+ import FormData from "form-data";
6
9
  import * as endpoints from "../endpoints.js";
7
10
  import { BiliApiError } from "../errors.js";
8
11
  import { Dynamic } from "../models.js";
12
+ import { guessImageType } from "../util.js";
9
13
  const FEATURES = "itemOpusStyle";
10
14
  const REFERER = "https://t.bilibili.com/";
11
15
  export class DynamicAPI {
@@ -106,6 +110,70 @@ export class DynamicAPI {
106
110
  const payload = await this.client.post(endpoints.DYNAMIC_CREATE, form, { Referer: REFERER });
107
111
  return DynamicAPI.dynamicId(payload);
108
112
  }
113
+ /** 上传单张图片到 B 站动态图床,返回 pictures 需要的一段信息。 */
114
+ async uploadImage(img) {
115
+ let bytes;
116
+ let name = "image.png";
117
+ if (Buffer.isBuffer(img)) {
118
+ bytes = img;
119
+ }
120
+ else {
121
+ bytes = await readFile(String(img));
122
+ name = basename(String(img));
123
+ }
124
+ // 动态图床上传是 multipart,用 form-data 包(Node 下 axios 靠它正确序列化二进制)
125
+ const form = new FormData();
126
+ form.append("biz", "draw");
127
+ form.append("csrf", this.client.csrf);
128
+ form.append("file_up", bytes, { filename: name, contentType: guessImageType(name) });
129
+ const resp = await this.client.http.post(endpoints.DYNAMIC_IMAGE_UPLOAD, form, {
130
+ headers: { ...form.getHeaders(), Referer: REFERER },
131
+ maxContentLength: Infinity,
132
+ maxBodyLength: Infinity,
133
+ });
134
+ const data = resp?.data ?? {};
135
+ const raw = data.data;
136
+ const url = typeof raw === "string" ? raw : raw?.url;
137
+ if (data.code !== 0 || !url) {
138
+ throw new BiliApiError(`图片上传失败: ${data.message ?? "接口未返回 url"}`, data.code, raw);
139
+ }
140
+ const meta = raw && typeof raw === "object" ? raw : {};
141
+ return {
142
+ img_src: String(url),
143
+ img_width: Number(meta.image_width ?? meta.width ?? 0),
144
+ img_height: Number(meta.image_height ?? meta.height ?? 0),
145
+ // 接口有时不返回体积,用字节数兜底(KB)
146
+ img_size: Number(meta.img_size ?? Math.round(bytes.length / 1024)),
147
+ };
148
+ }
149
+ /** 发布图文动态(文字 + 最多若干张图片)。图片可以是本地路径或 Buffer。 */
150
+ async publishWithImages(text, images, opts = {}) {
151
+ text = (text || "").trim();
152
+ const pics = [];
153
+ for (const img of images ?? []) {
154
+ pics.push(await this.uploadImage(img));
155
+ }
156
+ if (!text && !pics.length)
157
+ throw new Error("动态内容不能为空");
158
+ const extension = { emoji_type: 1, from: { emoji_type: 1 }, flag_cfg: {} };
159
+ const form = {
160
+ dynamic_id: 0,
161
+ type: pics.length ? 2 : 4, // 2 = 图文,4 = 纯文字
162
+ rid: 0,
163
+ content: text,
164
+ up_choose_comment: 0,
165
+ up_close_comment: opts.closeComment ? 1 : 0,
166
+ extension: JSON.stringify(extension),
167
+ at_uids: (opts.atUids ?? []).map(String).join(","),
168
+ ctrl: JSON.stringify([]),
169
+ csrf: this.client.csrf,
170
+ csrf_token: this.client.csrf,
171
+ };
172
+ if (pics.length)
173
+ form["pictures"] = JSON.stringify(pics);
174
+ const payload = await this.client.post(endpoints.DYNAMIC_CREATE, form, { Referer: REFERER });
175
+ return DynamicAPI.dynamicId(payload);
176
+ }
109
177
  async repost(dynamicId, text = "") {
110
178
  const form = {
111
179
  dynamic_id: String(Math.floor(Number(dynamicId))),
@@ -12,4 +12,8 @@ export declare class ProfileAPI {
12
12
  avatarUrl(): Promise<string>;
13
13
  updateSign(sign: string): Promise<void>;
14
14
  updateProfile(uname?: string, sex?: string, birthday?: string): Promise<void>;
15
+ /** 上传头像图片到 B 站图床,返回可用的图片 URL。 */
16
+ private uploadFaceUrl;
17
+ /** 更换头像:先上传图片拿 URL,再调 face/update。img 为本地路径或 Buffer。 */
18
+ changeAvatar(img: string | Buffer): Promise<void>;
15
19
  }
@@ -4,7 +4,12 @@
4
4
  - updateSign 用的是 x/member/web/sign/update,改完进入审核队列。
5
5
  - updateProfile 用的是 x/member/web/update,只支持昵称、性别、生日。
6
6
  */
7
+ import { readFile } from "node:fs/promises";
8
+ import { basename } from "node:path";
9
+ import FormData from "form-data";
7
10
  import * as endpoints from "../endpoints.js";
11
+ import { BiliApiError } from "../errors.js";
12
+ import { guessImageType } from "../util.js";
8
13
  const SEX_VALUES = ["男", "女", "保密"];
9
14
  const MAX_SIGN_LENGTH = 70;
10
15
  export class ProfileAPI {
@@ -56,4 +61,41 @@ export class ProfileAPI {
56
61
  }
57
62
  await this.client.post(endpoints.MEMBER_PROFILE_UPDATE, form);
58
63
  }
64
+ /** 上传头像图片到 B 站图床,返回可用的图片 URL。 */
65
+ async uploadFaceUrl(img) {
66
+ let bytes;
67
+ let name = "avatar.png";
68
+ if (Buffer.isBuffer(img)) {
69
+ bytes = img;
70
+ }
71
+ else {
72
+ bytes = await readFile(String(img));
73
+ name = basename(String(img));
74
+ }
75
+ const form = new FormData();
76
+ form.append("biz", "draw");
77
+ form.append("csrf", this.client.csrf);
78
+ form.append("file_up", bytes, { filename: name, contentType: guessImageType(name) });
79
+ const resp = await this.client.http.post(endpoints.DYNAMIC_IMAGE_UPLOAD, form, {
80
+ headers: { ...form.getHeaders(), Referer: "https://space.bilibili.com/" },
81
+ maxContentLength: Infinity,
82
+ maxBodyLength: Infinity,
83
+ });
84
+ const data = resp?.data ?? {};
85
+ const raw = data.data;
86
+ const url = typeof raw === "string" ? raw : raw?.url;
87
+ if (data.code !== 0 || !url) {
88
+ throw new BiliApiError(`头像图片上传失败: ${data.message ?? "接口未返回 url"}`, data.code, raw);
89
+ }
90
+ return String(url);
91
+ }
92
+ /** 更换头像:先上传图片拿 URL,再调 face/update。img 为本地路径或 Buffer。 */
93
+ async changeAvatar(img) {
94
+ const face = await this.uploadFaceUrl(img);
95
+ await this.client.post(endpoints.MEMBER_FACE_UPDATE, {
96
+ face,
97
+ csrf: this.client.csrf,
98
+ csrf_token: this.client.csrf,
99
+ });
100
+ }
59
101
  }
package/dist/dsh.js CHANGED
@@ -474,11 +474,15 @@ export const TOOLS = [
474
474
  // ---- 动态(写操作,需登录,会公开展示在主页) ----
475
475
  {
476
476
  id: "bili_dynamic_publish",
477
- description: "发布一条文字动态(写操作,需登录,会公开展示在你的主页)。返回动态 id 与链接。",
477
+ description: "发布动态:纯文字,或文字+图片(写操作,需登录,会公开展示在你的主页)。图片传本地文件路径(多个用逗号 / 换行分隔)。返回动态 id 与链接。",
478
478
  parameters: {
479
479
  type: "object",
480
480
  properties: {
481
- content: { type: "string", description: "动态正文文字内容" },
481
+ content: { type: "string", description: "动态正文(可与图片同时,也可仅发图片)" },
482
+ images: {
483
+ type: "string",
484
+ description: "本地图片路径,多个用逗号 / 换行分隔(可选,带图即发图文动态)",
485
+ },
482
486
  atUids: {
483
487
  type: "string",
484
488
  description: "要 @ 的用户 uid,多个用逗号分隔(可选)",
@@ -489,7 +493,6 @@ export const TOOLS = [
489
493
  description: "是否关闭评论",
490
494
  },
491
495
  },
492
- required: ["content"],
493
496
  },
494
497
  handler: async (a) => {
495
498
  const c = await getClient();
@@ -497,7 +500,20 @@ export const TOOLS = [
497
500
  .split(/[,,\s]+/)
498
501
  .map((s) => Number(s.trim()))
499
502
  .filter((n) => Number.isFinite(n) && n > 0);
500
- const id = await c.dynamic.publish(String(a.content ?? ""), atUids, undefined, Boolean(a.closeComment ?? false));
503
+ const images = String(a.images ?? "")
504
+ .split(/[,,\n]+/)
505
+ .map((s) => s.trim())
506
+ .filter(Boolean);
507
+ const content = String(a.content ?? "");
508
+ if (!content.trim() && !images.length) {
509
+ throw new Error("动态内容不能为空:至少提供正文或图片");
510
+ }
511
+ const id = images.length
512
+ ? await c.dynamic.publishWithImages(content, images, {
513
+ atUids,
514
+ closeComment: Boolean(a.closeComment ?? false),
515
+ })
516
+ : await c.dynamic.publish(content, atUids, undefined, Boolean(a.closeComment ?? false));
501
517
  return { ok: true, dynamicId: id, url: `https://t.bilibili.com/${id}` };
502
518
  },
503
519
  },
@@ -955,7 +971,7 @@ export const TOOLS = [
955
971
  },
956
972
  {
957
973
  id: "bili_profile_update",
958
- description: "修改我的昵称 / 性别 / 生日 / 签名(写操作,需登录,至少改一项)。",
974
+ description: "修改我的昵称 / 性别 / 生日 / 签名 / 头像(写操作,需登录,至少改一项)。头像传本地图片路径。",
959
975
  parameters: {
960
976
  type: "object",
961
977
  properties: {
@@ -963,19 +979,24 @@ export const TOOLS = [
963
979
  sex: { type: "string", enum: ["男", "女", "保密"] },
964
980
  birthday: { type: "string", description: "YYYY-MM-DD" },
965
981
  sign: { type: "string", description: "个性签名(≤70 字)" },
982
+ avatar: { type: "string", description: "新头像的本地图片路径" },
966
983
  },
967
984
  },
968
985
  handler: async (a) => {
969
986
  const c = await getClient();
970
987
  const hasProfile = a.uname != null || a.sex != null || a.birthday != null;
971
- if (a.sign == null && !hasProfile) {
972
- throw new Error("至少修改一项:uname / sex / birthday / sign");
988
+ const hasSign = a.sign != null;
989
+ const hasAvatar = a.avatar != null && String(a.avatar).trim() !== "";
990
+ if (!hasSign && !hasProfile && !hasAvatar) {
991
+ throw new Error("至少修改一项:uname / sex / birthday / sign / avatar");
973
992
  }
974
- if (a.sign != null)
993
+ if (hasSign)
975
994
  await c.profile.updateSign(String(a.sign));
976
995
  if (hasProfile) {
977
996
  await c.profile.updateProfile(a.uname != null ? String(a.uname) : undefined, a.sex != null ? String(a.sex) : undefined, a.birthday != null ? String(a.birthday) : undefined);
978
997
  }
998
+ if (hasAvatar)
999
+ await c.profile.changeAvatar(String(a.avatar));
979
1000
  return { ok: true };
980
1001
  },
981
1002
  },
@@ -1276,21 +1297,23 @@ function registerOne(ctx, tool) {
1276
1297
  }
1277
1298
  }
1278
1299
  export function apply(ctx) {
1279
- // 捕获工具注册表,供 bili_open 动态注册 / bili_close 卸载
1300
+ // 捕获工具注册表,供懒加载模式下的 bili_open 动态注册
1280
1301
  toolsRegistry =
1281
1302
  ctx?.tools && typeof ctx.tools.register === "function" ? ctx.tools : null;
1282
- // 懒加载机制工具始终注册
1283
- for (const t of lazyTools)
1284
- registerOne(ctx, t);
1285
- // BILI_LAZY=0 可强制关闭懒加载(全部注册),用于兜底
1286
- const lazyDisabled = process.env.BILI_LAZY === "0" || process.env.BILI_LAZY === "false";
1287
- if (!toolsRegistry || lazyDisabled) {
1288
- // 运行时不支持动态注册 / 手动关闭:退化为全部注册(功能完整,但不省 token)
1303
+ // 默认:稳定注册全部工具——让 prompt 前缀保持不变、最大化 DeepSeek 前缀缓存命中。
1304
+ // (缓存未命中价 ≈ 命中价 50 倍;工具 schema 在前缀里是命中价、成本可忽略,
1305
+ // 中途改工具列表反而造成未命中、更贵。)只有确认提供商不做前缀缓存、
1306
+ // 想极致压缩每轮 schema 时,才用 BILI_LAZY=1 开启懒加载。
1307
+ const lazyEnabled = !!toolsRegistry &&
1308
+ (process.env.BILI_LAZY === "1" || process.env.BILI_LAZY === "true");
1309
+ if (!lazyEnabled) {
1289
1310
  for (const t of TOOLS)
1290
1311
  registerOne(ctx, t);
1291
1312
  return;
1292
1313
  }
1293
- // 仅注册常驻核心,其余按需通过 bili_open 打开
1314
+ // 懒加载模式:注册机制工具 + 常驻核心,其余按需 bili_open 打开
1315
+ for (const t of lazyTools)
1316
+ registerOne(ctx, t);
1294
1317
  for (const id of CORE_IDS) {
1295
1318
  const t = TOOL_BY_ID.get(id);
1296
1319
  if (t)
@@ -39,6 +39,7 @@ export declare const MEMBER_ACCOUNT = "https://api.bilibili.com/x/member/web/acc
39
39
  export declare const MEMBER_MYINFO = "https://api.bilibili.com/x/space/myinfo";
40
40
  export declare const MEMBER_SIGN_UPDATE = "https://api.bilibili.com/x/member/web/sign/update";
41
41
  export declare const MEMBER_PROFILE_UPDATE = "https://api.bilibili.com/x/member/web/update";
42
+ export declare const MEMBER_FACE_UPDATE = "https://api.bilibili.com/x/member/web/face/update";
42
43
  export declare const DYNAMIC_FEED_ALL = "https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/all";
43
44
  export declare const DYNAMIC_FEED_SPACE = "https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/space";
44
45
  export declare const DYNAMIC_DETAIL = "https://api.bilibili.com/x/polymer/web-dynamic/v1/detail";
@@ -46,6 +47,7 @@ export declare const DYNAMIC_CREATE = "https://api.vc.bilibili.com/dynamic_svr/v
46
47
  export declare const DYNAMIC_REPUBLISH = "https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/republish";
47
48
  export declare const DYNAMIC_DELETE = "https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/rm_dynamic";
48
49
  export declare const DYNAMIC_THUMB = "https://api.bilibili.com/x/dynamic/feed/dyn/thumb";
50
+ export declare const DYNAMIC_IMAGE_UPLOAD = "https://api.bilibili.com/x/dynamic/feed/draw/upload_bfs";
49
51
  export declare const REPLY_LIST = "https://api.bilibili.com/x/v2/reply";
50
52
  export declare const REPLY_ADD = "https://api.bilibili.com/x/v2/reply/add";
51
53
  export declare const REPLY_DEL = "https://api.bilibili.com/x/v2/reply/del";
package/dist/endpoints.js CHANGED
@@ -50,6 +50,7 @@ export const MEMBER_ACCOUNT = `${API_BASE}/x/member/web/account`;
50
50
  export const MEMBER_MYINFO = `${API_BASE}/x/space/myinfo`;
51
51
  export const MEMBER_SIGN_UPDATE = `${API_BASE}/x/member/web/sign/update`;
52
52
  export const MEMBER_PROFILE_UPDATE = `${API_BASE}/x/member/web/update`;
53
+ export const MEMBER_FACE_UPDATE = `${API_BASE}/x/member/web/face/update`;
53
54
  // ---- 动态 ----
54
55
  export const DYNAMIC_FEED_ALL = `${API_BASE}/x/polymer/web-dynamic/v1/feed/all`;
55
56
  export const DYNAMIC_FEED_SPACE = `${API_BASE}/x/polymer/web-dynamic/v1/feed/space`;
@@ -58,6 +59,7 @@ export const DYNAMIC_CREATE = `${VC_BASE}/dynamic_svr/v1/dynamic_svr/create`;
58
59
  export const DYNAMIC_REPUBLISH = `${VC_BASE}/dynamic_svr/v1/dynamic_svr/republish`;
59
60
  export const DYNAMIC_DELETE = `${VC_BASE}/dynamic_svr/v1/dynamic_svr/rm_dynamic`;
60
61
  export const DYNAMIC_THUMB = `${API_BASE}/x/dynamic/feed/dyn/thumb`;
62
+ export const DYNAMIC_IMAGE_UPLOAD = `${API_BASE}/x/dynamic/feed/draw/upload_bfs`;
61
63
  // ---- 评论 ----
62
64
  export const REPLY_LIST = `${API_BASE}/x/v2/reply`;
63
65
  export const REPLY_ADD = `${API_BASE}/x/v2/reply/add`;
package/dist/util.d.ts CHANGED
@@ -1,2 +1,4 @@
1
1
  /** 小工具函数。 */
2
2
  export declare function sleep(ms: number): Promise<void>;
3
+ /** 根据文件名猜图片 MIME,用于 multipart 上传(缺省按 jpeg)。 */
4
+ export declare function guessImageType(name: string): string;
package/dist/util.js CHANGED
@@ -2,3 +2,16 @@
2
2
  export function sleep(ms) {
3
3
  return new Promise((resolve) => setTimeout(resolve, ms));
4
4
  }
5
+ const IMAGE_TYPES = {
6
+ png: "image/png",
7
+ jpg: "image/jpeg",
8
+ jpeg: "image/jpeg",
9
+ gif: "image/gif",
10
+ webp: "image/webp",
11
+ bmp: "image/bmp",
12
+ };
13
+ /** 根据文件名猜图片 MIME,用于 multipart 上传(缺省按 jpeg)。 */
14
+ export function guessImageType(name) {
15
+ const ext = (name.toLowerCase().split(".").pop() ?? "").trim();
16
+ return IMAGE_TYPES[ext] ?? "image/jpeg";
17
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-shlr-bilitoolkit",
3
- "version": "0.1.19",
3
+ "version": "0.1.21",
4
4
  "description": "深海猎人专用B站接口工具箱 dsh 插件。",
5
5
  "type": "module",
6
6
  "main": "dist/dsh.js",
@@ -23,10 +23,11 @@
23
23
  },
24
24
  "dependencies": {
25
25
  "axios": "^1.7.0",
26
+ "form-data": "^4.0.6",
26
27
  "qrcode": "^1.5.4"
27
28
  },
28
29
  "devDependencies": {
29
- "@deepseek-ai/cordis": "0.0.1-rc.1",
30
+ "@deepseek-ai/cordis": "^4.0.5",
30
31
  "@deepseek-ai/dsh-tools": "0.0.1-rc.1",
31
32
  "@types/node": "^22.0.0",
32
33
  "@types/qrcode": "^1.5.5",