Skip to content

♻️ 重构 Discord 出站序列化#87

Merged
shoucandanghehe merged 7 commits into
masterfrom
refactor/discord-outbound-serialization
Mar 17, 2026
Merged

♻️ 重构 Discord 出站序列化#87
shoucandanghehe merged 7 commits into
masterfrom
refactor/discord-outbound-serialization

Conversation

@shoucandanghehe
Copy link
Copy Markdown
Member

No description provided.

@shoucandanghehe shoucandanghehe requested a review from Copilot March 16, 2026 08:58
@codecov
Copy link
Copy Markdown

codecov Bot commented Mar 16, 2026

Codecov Report

❌ Patch coverage is 78.31325% with 72 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.76%. Comparing base (7877e50) to head (7238777).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
nonebot/adapters/discord/api/handle.py 18.00% 41 Missing ⚠️
nonebot/adapters/discord/serialization.py 82.71% 7 Missing and 7 partials ⚠️
tests/test_outbound_transport_serialization.py 90.69% 12 Missing ⚠️
nonebot/adapters/discord/utils.py 55.55% 2 Missing and 2 partials ⚠️
nonebot/adapters/discord/api/utils.py 96.29% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master      #87      +/-   ##
==========================================
+ Coverage   74.89%   75.76%   +0.86%     
==========================================
  Files          38       40       +2     
  Lines        7090     7286     +196     
  Branches      375      380       +5     
==========================================
+ Hits         5310     5520     +210     
+ Misses       1714     1684      -30     
- Partials       66       82      +16     
Flag Coverage Δ
unittests 75.76% <78.31%> (+0.86%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

此 PR 旨在将 Discord 适配器的出站(HTTP / multipart / gateway)序列化逻辑集中到统一的传输编码路径中,避免各处自行 model_dump/json.dumps 导致的行为漂移。

Changes:

  • 新增 nonebot.adapters.discord.serialization,提供统一的 JSON 文本/数据编码与 multipart payload_json 构造(PreparedRequest / encode_*)。
  • api/utils.pyparse_data / parse_forum_thread_message / parse_interaction_response 改为返回 PreparedRequest,并在 api/handle.py 中统一通过 encode_prepared_request 生成请求参数。
  • 补充/调整测试,覆盖 multipart payload_json、嵌套 message/data 结构,以及 gateway heartbeat 的传输 JSON 文本。

Reviewed changes

Copilot reviewed 9 out of 10 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
uv.lock 更新 adapter 版本并补充 dev 依赖锁定条目
tests/test_removed_guild_endpoints_warning.py 调整 monkeypatch 目标以匹配新的序列化入口
tests/test_outbound_transport_serialization.py 新增端到端测试:捕获 Request 并断言传输层 JSON 与 multipart payload_json
tests/test_api_nullability.py 测试改为覆盖 encode_prepared_request 后的传输结果(nullability + datetime + multipart)
nonebot/adapters/discord/utils.py 调整 model_dump:不再做 transport 编码,transport 编码移至新模块
nonebot/adapters/discord/serialization.py 新增:统一 JSON text/data 编码、multipart payload_json 与附件 id 映射
nonebot/adapters/discord/api/utils.py parse_* 系列改为构造 PreparedRequest,抽离附件提取逻辑
nonebot/adapters/discord/api/handle.py 大量端点改用 encode_model_json_data / encode_prepared_request / encode_json_text
nonebot/adapters/discord/api/client.pyi 重新生成的 stub 元信息更新
nonebot/adapters/discord/adapter.py gateway heartbeat/鉴权帧改用统一的 encode_model_json_text

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

You can also share your feedback on Copilot code review. Take the survey.

return data


# TODO)): Switch back to nonebot.compat.model_dump. Wait for the next release.
def encode_json_text(value: object) -> str:
if PYDANTIC_V2:
return _JSON_ADAPTER.dump_json(value).decode()
return json.dumps(value, default=pydantic_encoder)
Comment on lines +158 to +179
def encode_prepared_request(
prepared: PreparedRequest,
) -> dict[Literal["files", "json"], Any]:
payload = encode_model_json_data(
prepared.body,
include=prepared.include,
exclude=prepared.exclude,
by_alias=prepared.by_alias,
exclude_unset=prepared.exclude_unset,
exclude_defaults=prepared.exclude_defaults,
exclude_none=prepared.exclude_none,
omit_unset_values=prepared.omit_unset_values,
)
if prepared.files:
return {
"files": _build_multipart_payload(
payload,
prepared.files,
attachment_owner_path=prepared.attachment_owner_path,
)
}
return {"json": payload}
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR refactors Discord outbound payload serialization by introducing a centralized transport-encoding layer, aiming to keep HTTP JSON bodies, multipart payload_json, and gateway frames consistent across the adapter.

Changes:

  • Added nonebot.adapters.discord.serialization (PreparedRequest + encoding helpers) and migrated API utilities to return PreparedRequest.
  • Updated API request building in api/handle.py and gateway send paths in adapter.py to use the new encoding helpers.
  • Added/updated tests to validate datetime and multipart serialization behavior under the new transport encoding.

Reviewed changes

Copilot reviewed 9 out of 10 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
uv.lock Bumps adapter version and updates dev dependency lock entries.
tests/test_removed_guild_endpoints_warning.py Adjusts monkeypatching to new encoding function used by handle layer.
tests/test_outbound_transport_serialization.py New tests capturing outbound Request objects to assert transport JSON/multipart/gateway encoding.
tests/test_api_nullability.py Updates assertions to operate on PreparedRequest + encode_prepared_request output.
nonebot/adapters/discord/utils.py Refactors model_dump to return Python data only and adds IncEx typing for include/exclude.
nonebot/adapters/discord/serialization.py New centralized outbound transport serialization and multipart assembly implementation.
nonebot/adapters/discord/api/utils.py Migrates parse_data/parse_forum_thread_message/parse_interaction_response to return PreparedRequest.
nonebot/adapters/discord/api/handle.py Replaces scattered model_dump/json.dumps usage with centralized encoding helpers.
nonebot/adapters/discord/api/client.pyi Regenerated stub to match updated handle API implementation.
nonebot/adapters/discord/adapter.py Uses centralized JSON-text encoding for gateway heartbeat/auth payloads.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

You can also share your feedback on Copilot code review. Take the survey.

return data


# TODO)): Switch back to nonebot.compat.model_dump. Wait for the next release.
omit_unset_values: bool = False,
) -> dict[str, Any]:
# Keep JSON-data and JSON-text transport encoding on one path so HTTP bodies,
# multipart payload_json, and gateway frames cannot drift apart.
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

该 PR 将 Discord 适配器的出站请求(HTTP + Gateway)序列化逻辑集中重构到新的 serialization 模块中,以统一 JSON/Multipart 编码行为,并减少在各处散落的 model_dump/json.dumps 组合。

Changes:

  • 新增 nonebot.adapters.discord.serialization:引入 PreparedRequest/prepare_requestencode_* 编码函数,统一传输层 JSON/Multipart 序列化。
  • API 层(api/utils.pyapi/handle.pyadapter.py)改为使用新的序列化入口(encode_model_json_data/textencode_prepared_request)。
  • 补充与调整测试覆盖(multipart payload_json、嵌套 message/data、datetime 序列化、gateway heartbeat 文本发送)。

Reviewed changes

Copilot reviewed 9 out of 10 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
uv.lock 更新包版本与开发依赖项以匹配本次重构/测试需求。
tests/test_removed_guild_endpoints_warning.py 适配新的序列化函数名,确保 deprecation warning 测试仍可通过 monkeypatch 运行时依赖。
tests/test_outbound_transport_serialization.py 新增覆盖:捕获 Request,断言 multipart payload_json、嵌套结构与 datetime 在传输层的编码结果。
tests/test_api_nullability.py 由“直接断言 parse_* 返回 dict”改为断言 PreparedRequestencode_prepared_request 编码后的 payload。
nonebot/adapters/discord/utils.py 调整 model_dump:不再负责 datetime 等传输序列化(转移到 serialization)。
nonebot/adapters/discord/serialization.py 新增核心序列化模块:统一 JSON 文本/数据与 multipart 构建、附件 id 映射等。
nonebot/adapters/discord/api/utils.py parse_data/parse_forum_thread_message/parse_interaction_response 改为返回 PreparedRequest 并集中提取 files。
nonebot/adapters/discord/api/handle.py 大量 endpoint 改用 encode_model_json_dataencode_prepared_request,避免直接使用旧 model_dump 走传输。
nonebot/adapters/discord/api/client.pyi 随 handle.py 变更重新生成的类型存根元信息更新。
nonebot/adapters/discord/adapter.py Gateway 发送 payload 改用 encode_model_json_text,统一 websocket 文本序列化。

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

You can also share your feedback on Copilot code review. Take the survey.

return data


# TODO)): Switch back to nonebot.compat.model_dump. Wait for the next release.
@shoucandanghehe shoucandanghehe merged commit 199712e into master Mar 17, 2026
23 checks passed
@shoucandanghehe shoucandanghehe deleted the refactor/discord-outbound-serialization branch March 17, 2026 05:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants