nonebot-adapter-matrix 0.2.2__tar.gz → 0.3.0__tar.gz

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.
Files changed (28) hide show
  1. {nonebot_adapter_matrix-0.2.2 → nonebot_adapter_matrix-0.3.0}/PKG-INFO +41 -5
  2. {nonebot_adapter_matrix-0.2.2 → nonebot_adapter_matrix-0.3.0}/README.md +37 -4
  3. {nonebot_adapter_matrix-0.2.2 → nonebot_adapter_matrix-0.3.0}/nonebot/adapters/matrix/adapter.py +144 -33
  4. {nonebot_adapter_matrix-0.2.2 → nonebot_adapter_matrix-0.3.0}/nonebot/adapters/matrix/api/client.pyi +80 -2
  5. {nonebot_adapter_matrix-0.2.2 → nonebot_adapter_matrix-0.3.0}/nonebot/adapters/matrix/api/handle.py +194 -26
  6. {nonebot_adapter_matrix-0.2.2 → nonebot_adapter_matrix-0.3.0}/nonebot/adapters/matrix/api/model.py +45 -0
  7. {nonebot_adapter_matrix-0.2.2 → nonebot_adapter_matrix-0.3.0}/nonebot/adapters/matrix/bot.py +43 -8
  8. {nonebot_adapter_matrix-0.2.2 → nonebot_adapter_matrix-0.3.0}/nonebot/adapters/matrix/config.py +7 -0
  9. nonebot_adapter_matrix-0.3.0/nonebot/adapters/matrix/crypto/__init__.py +482 -0
  10. nonebot_adapter_matrix-0.3.0/nonebot/adapters/matrix/crypto/account.py +241 -0
  11. nonebot_adapter_matrix-0.3.0/nonebot/adapters/matrix/crypto/device_keys.py +138 -0
  12. nonebot_adapter_matrix-0.3.0/nonebot/adapters/matrix/crypto/megolm.py +346 -0
  13. nonebot_adapter_matrix-0.3.0/nonebot/adapters/matrix/crypto/recovery.py +309 -0
  14. nonebot_adapter_matrix-0.3.0/nonebot/adapters/matrix/crypto/sessions.py +149 -0
  15. nonebot_adapter_matrix-0.3.0/nonebot/adapters/matrix/crypto/store.py +168 -0
  16. {nonebot_adapter_matrix-0.2.2 → nonebot_adapter_matrix-0.3.0}/nonebot/adapters/matrix/event.py +12 -0
  17. {nonebot_adapter_matrix-0.2.2 → nonebot_adapter_matrix-0.3.0}/nonebot/adapters/matrix/serialization.py +26 -0
  18. {nonebot_adapter_matrix-0.2.2 → nonebot_adapter_matrix-0.3.0}/pyproject.toml +36 -1
  19. {nonebot_adapter_matrix-0.2.2 → nonebot_adapter_matrix-0.3.0}/nonebot/adapters/matrix/__init__.py +0 -0
  20. {nonebot_adapter_matrix-0.2.2 → nonebot_adapter_matrix-0.3.0}/nonebot/adapters/matrix/api/__init__.py +0 -0
  21. {nonebot_adapter_matrix-0.2.2 → nonebot_adapter_matrix-0.3.0}/nonebot/adapters/matrix/api/client.py +0 -0
  22. {nonebot_adapter_matrix-0.2.2 → nonebot_adapter_matrix-0.3.0}/nonebot/adapters/matrix/api/types.py +0 -0
  23. {nonebot_adapter_matrix-0.2.2 → nonebot_adapter_matrix-0.3.0}/nonebot/adapters/matrix/api/utils.py +0 -0
  24. {nonebot_adapter_matrix-0.2.2 → nonebot_adapter_matrix-0.3.0}/nonebot/adapters/matrix/api/validation.py +0 -0
  25. {nonebot_adapter_matrix-0.2.2 → nonebot_adapter_matrix-0.3.0}/nonebot/adapters/matrix/exception.py +0 -0
  26. {nonebot_adapter_matrix-0.2.2 → nonebot_adapter_matrix-0.3.0}/nonebot/adapters/matrix/message.py +0 -0
  27. {nonebot_adapter_matrix-0.2.2 → nonebot_adapter_matrix-0.3.0}/nonebot/adapters/matrix/oauth.py +0 -0
  28. {nonebot_adapter_matrix-0.2.2 → nonebot_adapter_matrix-0.3.0}/nonebot/adapters/matrix/utils.py +0 -0
@@ -1,12 +1,15 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: nonebot-adapter-matrix
3
- Version: 0.2.2
3
+ Version: 0.3.0
4
4
  Summary: Matrix adapter for nonebot2
5
5
  Keywords: nonebot,matrix,bot
6
6
  Author: elysia-best
7
7
  Author-email: elysia-best <a.elysia@proton.me>
8
8
  License-Expression: MIT
9
+ Requires-Dist: base58>=2.1.1
10
+ Requires-Dist: cryptography>=48.0.0
9
11
  Requires-Dist: nonebot2>=2.4.4
12
+ Requires-Dist: python3-olm>=3.2.19
10
13
  Requires-Dist: requests-oauth2client>=1.8.0
11
14
  Requires-Python: >=3.10, <4.0.0
12
15
  Project-URL: homepage, https://github.com/nonebot/adapter-matrix
@@ -204,8 +207,39 @@ MATRIX_TOKEN_STORE_PATH='.data/matrix-tokens.json'
204
207
  - 网络错误或 5xx:保留旧 refresh token,稍后重试。
205
208
  - 4xx 且带 `soft_logout: true`:若配置了 `login_password`,自动重新登录。
206
209
  - 4xx 无 `soft_logout`:视为会话失效,等待重试。
207
- - refresh 成功后更新内存中的 `access_token`、`refresh_token`、`access_token_expires_at_ms`,并写回状态文件。
208
- - adapter 不会回写 `.env` 或其他部署配置;`/sync` 的 `next_batch` 仍然不会持久化。
210
+ - refresh 成功后更新内存中的 `access_token`、`refresh_token`、`access_token_expires_at_ms`,并写回状态 json 文件。
211
+ - 注意,adapter 不会回写获取的 Token 到 `.env` 或其他 dotenv 文件;同样,`/sync` 的 `next_batch` 不会持久化。
212
+
213
+ ### 端到端加密 (E2EE)
214
+
215
+ 适配器支持 Matrix 端到端加密房间,使用 Olm/Megolm 协议进行消息加解密。E2EE 是 opt-in 的:只有配置了 `e2ee_store_path` 或 `MATRIX_TOKEN_STORE_PATH` 时才会启用。
216
+
217
+ ```dotenv
218
+ MATRIX_BOTS='[
219
+ {
220
+ "homeserver": "https://matrix.example.org",
221
+ "access_token": "YOUR_ACCESS_TOKEN",
222
+ "user_id": "@bot:example.org",
223
+ "device_id": "BOTDEVICE",
224
+ "recovery_code": "EsTb ...",
225
+ "e2ee_store_path": ".data/e2ee_store"
226
+ }
227
+ ]'
228
+ ```
229
+
230
+ - `recovery_code`:**MATRIX_RECOVERY_CODE**,用于从服务端密钥备份恢复 Megolm 会话密钥。格式为 base58 编码的 Curve25519 私钥,可以在 Element 等客户端的「安全与隐私」设置中找到。配置后,启动时自动从服务端备份恢复所有可解密的会话密钥,无需其他设备在线。
231
+ - `e2ee_store_path`:E2EE 加密状态的持久化目录路径。为 `None`(默认)时,会从 `MATRIX_TOKEN_STORE_PATH` 同目录下自动派生一个子目录(如 `e2ee_<hash>_<user>`)。如果两者均未设置,E2EE 完全禁用。
232
+
233
+ **E2EE 工作流程:**
234
+
235
+ 1. **启动时**:生成 Olm 设备密钥(Ed25519 + Curve25519),上传到 homeserver,确保一次性密钥 (OTK) 数量充足,上传 fallback 密钥作为备用。若配置了 `recovery_code`,从服务端密钥备份恢复 Megolm 会话。
236
+ 2. **进入加密房间**:当同步到 `m.room.encryption` 状态事件时,自动标记该房间为加密。首次向加密房间发送消息前,会通过 Olm to-device 消息向所有成员设备共享 Megolm 会话密钥。
237
+ 3. **收发加密消息**:发出的消息自动用 Megolm 加密后以 `m.room.encrypted` 事件发送;收到的加密消息自动解密为明文后再分派给插件处理。
238
+ 4. **设备列表跟踪**:自动处理 `/sync` 中的 `device_lists` 变更,查询新设备的密钥,保持设备密钥缓存更新。
239
+
240
+ **注意事项:**
241
+ - E2EE 依赖 `python-olm` 库(libolm 的 Python 绑定)。libolm 的 Olm session `from_pickle` 在某些平台/Python 版本上可能不可用,此时 Olm 会话不会跨重启持久化(不影响正常使用,仅影响重启后首次密钥共享的效率)。
242
+ - 机器人目前不处理密钥验证(SAS/emoji),其他用户的设备标记为「未验证」不影响正常收发消息。
209
243
 
210
244
  ## 插件示例
211
245
 
@@ -256,6 +290,8 @@ async def handle_img_send():
256
290
 
257
291
  ```
258
292
 
293
+ 需要注意,`content_type` 字段需要传入**正确的 MIME Type** 才能在客户端显示!
294
+
259
295
  ### 常用 Matrix 操作
260
296
 
261
297
  ```python
@@ -289,13 +325,13 @@ MATRIX_BOTS='[
289
325
  - 黑名单优先级高于白名单:即使用户在白名单中,若同时出现在黑名单中也不会自动接受邀请。
290
326
  - 自动加入失败时仅记录错误日志,不会中断同步循环。
291
327
 
292
- ## 当前范围
328
+ ## 当前实现范围
293
329
 
294
330
  当前实现面向 Matrix Client-Server bot 场景:
295
331
 
296
332
  - 通过 `/account/whoami` 校验身份。
297
333
  - 通过 `/sync` long-poll 接收 room timeline、state、typing、receipt 等事件。
298
334
  - 支持发送 `m.room.message`、上传媒体、reaction、redaction、typing、receipt 和 join room。
299
- - 不包含端到端加密房间支持。
335
+ - 支持端到端加密房间 (E2EE),可收发加密消息,支持通过 MATRIX_RECOVERY_CODE 从服务端密钥备份恢复会话。
300
336
  - 不包含 Matrix Application Service API。
301
337
  - 不持久化 `/sync` 的 `next_batch`;进程内重连会复用内存状态,跨进程重启默认丢弃早于本次启动时间的旧事件。
@@ -188,8 +188,39 @@ MATRIX_TOKEN_STORE_PATH='.data/matrix-tokens.json'
188
188
  - 网络错误或 5xx:保留旧 refresh token,稍后重试。
189
189
  - 4xx 且带 `soft_logout: true`:若配置了 `login_password`,自动重新登录。
190
190
  - 4xx 无 `soft_logout`:视为会话失效,等待重试。
191
- - refresh 成功后更新内存中的 `access_token`、`refresh_token`、`access_token_expires_at_ms`,并写回状态文件。
192
- - adapter 不会回写 `.env` 或其他部署配置;`/sync` 的 `next_batch` 仍然不会持久化。
191
+ - refresh 成功后更新内存中的 `access_token`、`refresh_token`、`access_token_expires_at_ms`,并写回状态 json 文件。
192
+ - 注意,adapter 不会回写获取的 Token 到 `.env` 或其他 dotenv 文件;同样,`/sync` 的 `next_batch` 不会持久化。
193
+
194
+ ### 端到端加密 (E2EE)
195
+
196
+ 适配器支持 Matrix 端到端加密房间,使用 Olm/Megolm 协议进行消息加解密。E2EE 是 opt-in 的:只有配置了 `e2ee_store_path` 或 `MATRIX_TOKEN_STORE_PATH` 时才会启用。
197
+
198
+ ```dotenv
199
+ MATRIX_BOTS='[
200
+ {
201
+ "homeserver": "https://matrix.example.org",
202
+ "access_token": "YOUR_ACCESS_TOKEN",
203
+ "user_id": "@bot:example.org",
204
+ "device_id": "BOTDEVICE",
205
+ "recovery_code": "EsTb ...",
206
+ "e2ee_store_path": ".data/e2ee_store"
207
+ }
208
+ ]'
209
+ ```
210
+
211
+ - `recovery_code`:**MATRIX_RECOVERY_CODE**,用于从服务端密钥备份恢复 Megolm 会话密钥。格式为 base58 编码的 Curve25519 私钥,可以在 Element 等客户端的「安全与隐私」设置中找到。配置后,启动时自动从服务端备份恢复所有可解密的会话密钥,无需其他设备在线。
212
+ - `e2ee_store_path`:E2EE 加密状态的持久化目录路径。为 `None`(默认)时,会从 `MATRIX_TOKEN_STORE_PATH` 同目录下自动派生一个子目录(如 `e2ee_<hash>_<user>`)。如果两者均未设置,E2EE 完全禁用。
213
+
214
+ **E2EE 工作流程:**
215
+
216
+ 1. **启动时**:生成 Olm 设备密钥(Ed25519 + Curve25519),上传到 homeserver,确保一次性密钥 (OTK) 数量充足,上传 fallback 密钥作为备用。若配置了 `recovery_code`,从服务端密钥备份恢复 Megolm 会话。
217
+ 2. **进入加密房间**:当同步到 `m.room.encryption` 状态事件时,自动标记该房间为加密。首次向加密房间发送消息前,会通过 Olm to-device 消息向所有成员设备共享 Megolm 会话密钥。
218
+ 3. **收发加密消息**:发出的消息自动用 Megolm 加密后以 `m.room.encrypted` 事件发送;收到的加密消息自动解密为明文后再分派给插件处理。
219
+ 4. **设备列表跟踪**:自动处理 `/sync` 中的 `device_lists` 变更,查询新设备的密钥,保持设备密钥缓存更新。
220
+
221
+ **注意事项:**
222
+ - E2EE 依赖 `python-olm` 库(libolm 的 Python 绑定)。libolm 的 Olm session `from_pickle` 在某些平台/Python 版本上可能不可用,此时 Olm 会话不会跨重启持久化(不影响正常使用,仅影响重启后首次密钥共享的效率)。
223
+ - 机器人目前不处理密钥验证(SAS/emoji),其他用户的设备标记为「未验证」不影响正常收发消息。
193
224
 
194
225
  ## 插件示例
195
226
 
@@ -240,6 +271,8 @@ async def handle_img_send():
240
271
 
241
272
  ```
242
273
 
274
+ 需要注意,`content_type` 字段需要传入**正确的 MIME Type** 才能在客户端显示!
275
+
243
276
  ### 常用 Matrix 操作
244
277
 
245
278
  ```python
@@ -273,13 +306,13 @@ MATRIX_BOTS='[
273
306
  - 黑名单优先级高于白名单:即使用户在白名单中,若同时出现在黑名单中也不会自动接受邀请。
274
307
  - 自动加入失败时仅记录错误日志,不会中断同步循环。
275
308
 
276
- ## 当前范围
309
+ ## 当前实现范围
277
310
 
278
311
  当前实现面向 Matrix Client-Server bot 场景:
279
312
 
280
313
  - 通过 `/account/whoami` 校验身份。
281
314
  - 通过 `/sync` long-poll 接收 room timeline、state、typing、receipt 等事件。
282
315
  - 支持发送 `m.room.message`、上传媒体、reaction、redaction、typing、receipt 和 join room。
283
- - 不包含端到端加密房间支持。
316
+ - 支持端到端加密房间 (E2EE),可收发加密消息,支持通过 MATRIX_RECOVERY_CODE 从服务端密钥备份恢复会话。
284
317
  - 不包含 Matrix Application Service API。
285
318
  - 不持久化 `/sync` 的 `next_batch`;进程内重连会复用内存状态,跨进程重启默认丢弃早于本次启动时间的旧事件。
@@ -24,14 +24,17 @@ from nonebot.utils import escape_tag
24
24
  from .api.handle import HandleMixin
25
25
  from .api.model import (
26
26
  InvitedRoomSync,
27
+ JoinedRoomSync,
28
+ LeftRoomSync,
27
29
  LoginResponse,
28
30
  RawMatrixEvent,
29
31
  SyncResponse,
30
32
  WhoamiResponse,
31
33
  )
32
- from .api.types import UserId
34
+ from .api.types import RoomId, UserId
33
35
  from .bot import Bot
34
36
  from .config import BotInfo, Config
37
+ from .crypto import CryptoEngine
35
38
  from .event import InviteEvent, LeaveEvent, event_from_raw
36
39
  from .exception import (
37
40
  ApiNotAvailable,
@@ -158,7 +161,10 @@ class Adapter(BaseAdapter, HandleMixin):
158
161
  try:
159
162
  raw = json.loads(path.read_text(encoding="utf-8"))
160
163
  except (OSError, json.JSONDecodeError) as e:
161
- log("ERROR", f"Failed to read Matrix token store {path}", e)
164
+ log(
165
+ "ERROR",
166
+ f"Failed to read Matrix token store {path}: {type(e).__name__}: {e}",
167
+ )
162
168
  return {}
163
169
  if isinstance(raw, dict):
164
170
  return raw
@@ -225,7 +231,10 @@ class Adapter(BaseAdapter, HandleMixin):
225
231
  temp_path.write_text(payload + "\n", encoding="utf-8")
226
232
  temp_path.replace(path)
227
233
  except OSError as e:
228
- log("ERROR", f"Failed to write Matrix token store {path}", e)
234
+ log(
235
+ "ERROR",
236
+ f"Failed to write Matrix token store {path}: {type(e).__name__}: {e}",
237
+ )
229
238
  with contextlib.suppress(OSError):
230
239
  temp_path.unlink(missing_ok=True)
231
240
 
@@ -580,8 +589,8 @@ class Adapter(BaseAdapter, HandleMixin):
580
589
  except UnauthorizedException as refresh_error:
581
590
  log(
582
591
  "ERROR",
583
- f"Token refresh rejected (4xx) for {bot.self_id}",
584
- refresh_error,
592
+ f"Token refresh rejected (4xx) for {bot.self_id}: "
593
+ f"{type(refresh_error).__name__}: {refresh_error}",
585
594
  )
586
595
  if refresh_error.soft_logout:
587
596
  self_info = await self._relogin_if_soft_logout(bot)
@@ -596,8 +605,8 @@ class Adapter(BaseAdapter, HandleMixin):
596
605
  except Exception as refresh_error:
597
606
  log(
598
607
  "ERROR",
599
- f"Failed to refresh Matrix access token for {bot.self_id}",
600
- refresh_error,
608
+ f"Failed to refresh Matrix access token for {bot.self_id}: "
609
+ f"{type(refresh_error).__name__}: {refresh_error}",
601
610
  )
602
611
  else:
603
612
  log(
@@ -688,7 +697,10 @@ class Adapter(BaseAdapter, HandleMixin):
688
697
  try:
689
698
  token_resp = await self._run_oauth2_login(bot_info)
690
699
  except OAuth2Error as oauth_err:
691
- log("ERROR", "OAuth2 login failed", oauth_err)
700
+ log(
701
+ "ERROR",
702
+ f"OAuth2 login failed: {type(oauth_err).__name__}: {oauth_err}",
703
+ )
692
704
  raise
693
705
  self._apply_token_update(
694
706
  bot_info,
@@ -728,17 +740,38 @@ class Adapter(BaseAdapter, HandleMixin):
728
740
  try:
729
741
  self_info = await self._bootstrap_bot(bot_info)
730
742
  bot = Bot(self, str(self_info.user_id), bot_info, self_info)
743
+
744
+ # 初始化 E2EE 加密引擎 (如果配置了存储路径)
745
+ if (
746
+ bot_info.e2ee_store_path
747
+ or self.matrix_config.matrix_token_store_path
748
+ ):
749
+ try:
750
+ bot.crypto = CryptoEngine(bot, self)
751
+ await bot.crypto.initialize()
752
+ except Exception as e:
753
+ log(
754
+ "WARNING",
755
+ f"E2EE 加密引擎初始化失败,将以明文模式运行: "
756
+ f"{type(e).__name__}: {e}",
757
+ )
758
+ bot.crypto = None
759
+
731
760
  self.bot_connect(bot)
732
761
  log("INFO", f"Matrix bot {escape_tag(bot.self_id)} connected")
733
762
  await self._sync_loop(bot)
734
763
  except asyncio.CancelledError:
735
764
  raise
736
765
  except Exception as e:
737
- log("ERROR", "Matrix bot loop failed; retrying...", e)
738
- await asyncio.sleep(self.matrix_config.matrix_retry_interval)
766
+ log(
767
+ "ERROR",
768
+ f"Matrix bot loop failed; retrying... {type(e).__name__}",
769
+ )
739
770
  finally:
740
771
  if bot and bot.self_id in self.bots:
741
772
  self.bot_disconnect(bot)
773
+ else:
774
+ await asyncio.sleep(self.matrix_config.matrix_retry_interval)
742
775
 
743
776
  async def _bootstrap_bot(self, bot_info: BotInfo) -> WhoamiResponse:
744
777
  # The adapter runs with configured tokens; whoami validates the token and
@@ -787,42 +820,103 @@ class Adapter(BaseAdapter, HandleMixin):
787
820
  except UnauthorizedException as e:
788
821
  if await self._handle_sync_unauthorized(bot, e):
789
822
  continue
790
- log("ERROR", f"Error while syncing Matrix bot {bot.self_id}", e)
823
+ log(
824
+ "ERROR",
825
+ f"Error while syncing Matrix bot {bot.self_id}: {type(e).__name__}: {e}",
826
+ )
791
827
  await asyncio.sleep(self.matrix_config.matrix_retry_interval)
792
828
  except asyncio.CancelledError:
793
829
  raise
794
830
  except Exception as e:
795
- log("ERROR", f"Error while syncing Matrix bot {bot.self_id}", e)
831
+ log(
832
+ "ERROR",
833
+ f"Error while syncing Matrix bot {bot.self_id}: {type(e).__name__}: {e}",
834
+ )
796
835
  await asyncio.sleep(self.matrix_config.matrix_retry_interval)
797
836
 
798
837
  async def _handle_sync(self, bot: Bot, sync: SyncResponse) -> None:
838
+ await self._handle_e2ee_sync_data(bot, sync)
799
839
  self._update_direct_rooms(bot, sync.account_data.events)
800
840
  for room_id, room in sync.rooms.join.items():
801
841
  self._update_direct_rooms(bot, room.account_data.events)
802
- for raw in [*room.state.events, *room.timeline.events]:
803
- await self._dispatch_room_event(bot, raw, room_id=str(room_id))
804
- for raw in room.ephemeral.events:
805
- await self._dispatch_room_event(bot, raw, room_id=str(room_id))
842
+ await self._handle_joined_room(bot, room_id, room)
806
843
  for room_id, room in sync.rooms.invite.items():
807
- event = InviteEvent(type="m.room.invite", room_id=room_id, content={})
808
- await bot.handle_event(event)
809
- for raw in room.invite_state.events:
810
- await self._dispatch_room_event(bot, raw, room_id=str(room_id))
811
- inviter = self._get_inviter(bot, room)
812
- if inviter is not None and self._should_accept_invite(bot, inviter):
844
+ await self._handle_invited_room(bot, room_id, room)
845
+ for room_id, room in sync.rooms.leave.items():
846
+ await self._handle_left_room(bot, room_id, room)
847
+
848
+ async def _handle_e2ee_sync_data(self, bot: Bot, sync: SyncResponse) -> None:
849
+ """Process device_lists and to_device events for E2EE."""
850
+ if sync.device_lists is not None and bot.crypto is not None:
851
+ await bot.crypto.handle_device_lists(
852
+ changed=[str(u) for u in sync.device_lists.changed],
853
+ left=[str(u) for u in sync.device_lists.left],
854
+ )
855
+
856
+ if sync.to_device is not None and bot.crypto is not None:
857
+ await self._handle_to_device_events(bot, sync.to_device.events)
858
+
859
+ async def _handle_to_device_events(
860
+ self, bot: Bot, events: list[RawMatrixEvent]
861
+ ) -> None:
862
+ """Process to-device messages for E2EE key exchange."""
863
+ for raw in events:
864
+ if bot.crypto is None:
865
+ break
866
+ await self._try_handle_to_device(bot, raw)
867
+
868
+ async def _try_handle_to_device(self, bot: Bot, raw: RawMatrixEvent) -> None:
869
+ if bot.crypto is None:
870
+ return
871
+ try:
872
+ await bot.crypto.handle_to_device_event(raw)
873
+ except Exception as e:
874
+ log(
875
+ "WARNING",
876
+ f"handle to-device event failed: {type(e).__name__}: {e}",
877
+ )
878
+
879
+ async def _handle_joined_room(
880
+ self, bot: Bot, room_id: RoomId, room: JoinedRoomSync
881
+ ) -> None:
882
+ """Process events for a joined room, including E2EE state detection."""
883
+ for raw in room.state.events:
884
+ if raw.type == "m.room.encryption" and bot.crypto is not None:
885
+ algorithm = raw.content.get("algorithm", "m.megolm.v1.aes-sha2")
886
+ bot.crypto.mark_room_as_encrypted(str(room_id), algorithm)
887
+ await self._dispatch_room_event(bot, raw, room_id=str(room_id))
888
+ for raw in room.timeline.events:
889
+ await self._dispatch_room_event(bot, raw, room_id=str(room_id))
890
+ for raw in room.ephemeral.events:
891
+ await self._dispatch_room_event(bot, raw, room_id=str(room_id))
892
+
893
+ async def _handle_invited_room(
894
+ self, bot: Bot, room_id: RoomId, room: InvitedRoomSync
895
+ ) -> None:
896
+ """Process events for an invited room and optionally auto-join."""
897
+ event = InviteEvent(type="m.room.invite", room_id=room_id, content={})
898
+ await bot.handle_event(event)
899
+ for raw in room.invite_state.events:
900
+ await self._dispatch_room_event(bot, raw, room_id=str(room_id))
901
+ inviter = self._get_inviter(bot, room)
902
+ if inviter is not None and self._should_accept_invite(bot, inviter):
903
+ log("INFO", f"Auto-accepting invite to room {room_id} from {inviter}")
904
+ try:
905
+ await self._api_join_room(bot, room_id=room_id)
906
+ except Exception as e:
813
907
  log(
814
- "INFO",
815
- f"Auto-accepting invite to room {room_id} from {inviter}",
908
+ "ERROR",
909
+ f"Failed to auto-join room {room_id}: {type(e).__name__}: {e}",
816
910
  )
817
- try:
818
- await self._api_join_room(bot, room_id=room_id)
819
- except Exception as e:
820
- log("ERROR", f"Failed to auto-join room {room_id}", e)
821
- for room_id, room in sync.rooms.leave.items():
822
- event = LeaveEvent(type="m.room.leave", room_id=room_id, content={})
823
- await bot.handle_event(event)
824
- for raw in [*room.state.events, *room.timeline.events]:
825
- await self._dispatch_room_event(bot, raw, room_id=str(room_id))
911
+
912
+ async def _handle_left_room(
913
+ self, bot: Bot, room_id: RoomId, room: LeftRoomSync
914
+ ) -> None:
915
+ """Process events for a left room."""
916
+ event = LeaveEvent(type="m.room.leave", room_id=room_id, content={})
917
+ await bot.handle_event(event)
918
+ for raw in [*room.state.events, *room.timeline.events]:
919
+ await self._dispatch_room_event(bot, raw, room_id=str(room_id))
826
920
 
827
921
  def _get_inviter(self, bot: Bot, room: InvitedRoomSync) -> str | None:
828
922
  """Extract the inviter's user ID from an invited room's state events."""
@@ -867,6 +961,23 @@ class Adapter(BaseAdapter, HandleMixin):
867
961
  ) -> None:
868
962
  if self._is_old_event(bot, raw):
869
963
  return
964
+
965
+ # 解密 m.room.encrypted 事件
966
+ if raw.type == "m.room.encrypted" and bot.crypto is not None:
967
+ try:
968
+ decrypted = await bot.crypto.decrypt_room_event(raw, room_id=room_id)
969
+ if decrypted is not None:
970
+ raw = decrypted
971
+ else:
972
+ # Unable to decrypt (missing session key), skip dispatch
973
+ return
974
+ except Exception as e:
975
+ log(
976
+ "WARNING",
977
+ f"解密房间事件失败 ({room_id}): {type(e).__name__}: {e}",
978
+ )
979
+ return
980
+
870
981
  if (
871
982
  raw.sender == bot.user_id
872
983
  and not self.matrix_config.matrix_handle_self_message
@@ -1,8 +1,8 @@
1
1
  # This file is auto-generated by scripts/generate_client_pyi.py.
2
2
  # Do not edit this file directly.
3
- # Generated at: 2026-06-03T01:26:54Z
3
+ # Generated at: 2026-06-04T08:54:55Z
4
4
  # Source file: nonebot/adapters/matrix/api/handle.py
5
- # Source SHA256: ff69364f5ac8613550202c7feadeb6e2016c0ce634cb47ab8294b976eeb4734a
5
+ # Source SHA256: 768d6ad82a1924dcefcd2557b8f813d8434c7bb40d5d0df858c86caf3496ce02
6
6
  # Script SHA256: 23fb4be2063fea658668d0f02a4efd3a61f3e7bbff87ede267ad72504e012201
7
7
 
8
8
  from typing import Any
@@ -219,3 +219,81 @@ class ApiClient:
219
219
  reason: str | None = None,
220
220
  ) -> JoinRoomResponse:
221
221
  """Join a Matrix room by ID."""
222
+
223
+ async def keys_upload(
224
+ self,
225
+ *,
226
+ device_keys: dict[str, Any] | None = None,
227
+ one_time_keys: dict[str, str] | None = None,
228
+ fallback_keys: dict[str, str] | None = None,
229
+ ) -> dict[str, Any]:
230
+ """上传设备身份密钥和/或一次性密钥。
231
+
232
+ POST /keys/upload
233
+
234
+ device_keys: 设备的 Ed25519/Curve25519 身份密钥 (带自签名)
235
+ one_time_keys: 用于 Olm 会话建立的 signed_curve25519 密钥
236
+ fallback_keys: 当 OTK 耗尽时使用的备用密钥
237
+ """
238
+
239
+ async def keys_query(
240
+ self,
241
+ *,
242
+ device_keys: dict[str, list[str]],
243
+ timeout: int | None = None,
244
+ ) -> dict[str, Any]:
245
+ """查询指定用户的设备密钥。
246
+
247
+ POST /keys/query
248
+
249
+ device_keys: {user_id: [device_id, ...]} 空列表表示查询所有设备
250
+ """
251
+
252
+ async def keys_claim(
253
+ self,
254
+ *,
255
+ one_time_keys: dict[str, dict[str, str]],
256
+ timeout: int | None = None,
257
+ ) -> dict[str, Any]:
258
+ """为指定设备索取一次性密钥用于 Olm 会话建立。
259
+
260
+ POST /keys/claim
261
+
262
+ one_time_keys: {user_id: {device_id: "signed_curve25519"}}
263
+ """
264
+
265
+ async def send_to_device(
266
+ self,
267
+ *,
268
+ event_type: str,
269
+ txn_id: str,
270
+ messages: dict[str, dict[str, Any]],
271
+ ) -> None:
272
+ """发送 to-device 消息给指定设备。
273
+
274
+ PUT /sendToDevice/{event_type}/{txn_id}
275
+
276
+ messages: {user_id: {device_id: content}}
277
+ """
278
+
279
+ async def room_keys_version(
280
+ self,
281
+ *,
282
+ version: str | None = None,
283
+ ) -> dict[str, Any]:
284
+ """获取密钥备份的版本信息。
285
+
286
+ GET /room_keys/version[/{version}]
287
+ """
288
+
289
+ async def room_keys_keys(
290
+ self,
291
+ *,
292
+ room_id: str | None = None,
293
+ session_id: str | None = None,
294
+ version: str,
295
+ ) -> dict[str, Any]:
296
+ """从密钥备份中获取加密会话密钥。
297
+
298
+ GET /room_keys/keys[/{room_id}[/{session_id}]]?version={version}
299
+ """