@hfyjq/crannia 1.0.0 → 1.1.0

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 (221) hide show
  1. package/LICENSE +201 -201
  2. package/NOTICE +45 -45
  3. package/THIRD-PARTY-FRONTEND.md +5266 -5266
  4. package/THIRD-PARTY-PYTHON.md +162 -153
  5. package/THIRD-PARTY.md +316 -316
  6. package/apps/desktop/quotes.txt +56 -56
  7. package/bus/core.py +671 -671
  8. package/bus/loaders/channel_loader.py +64 -64
  9. package/bus/loaders/skill_md.py +676 -676
  10. package/bus/skill_state.py +124 -124
  11. package/channels/cli_channel/manifest.yaml +5 -5
  12. package/channels/dingtalk_channel/manifest.yaml +12 -12
  13. package/channels/feishu_channel/manifest.yaml +12 -12
  14. package/channels/qq_bot_channel/__init__.py +1 -1
  15. package/channels/qq_bot_channel/handler.py +881 -881
  16. package/channels/qq_bot_channel/manifest.yaml +4 -4
  17. package/channels/telegram_channel/__init__.py +1 -1
  18. package/channels/telegram_channel/handler.py +813 -813
  19. package/channels/telegram_channel/manifest.yaml +4 -4
  20. package/channels/telegram_channel/media.py +231 -231
  21. package/channels/textfmt.py +58 -58
  22. package/channels/wechat_channel/__init__.py +1 -1
  23. package/channels/wechat_channel/auth.py +23 -5
  24. package/channels/wechat_channel/manifest.yaml +5 -5
  25. package/channels/wechat_channel/media.py +178 -178
  26. package/config.yaml +2 -2
  27. package/core/activity.py +3 -0
  28. package/core/agent_loop.py +390 -55
  29. package/core/approval.py +17 -6
  30. package/core/artifacts.py +7 -0
  31. package/core/auto_review.py +23 -5
  32. package/core/channel_configs.py +34 -2
  33. package/core/channel_turns.py +759 -759
  34. package/core/child_approval.py +150 -0
  35. package/core/config_requirements.py +205 -0
  36. package/core/cron/runner.py +118 -6
  37. package/core/cron/store.py +14 -5
  38. package/core/cron/tools.py +17 -5
  39. package/core/endpoint.py +141 -0
  40. package/core/events.py +23 -0
  41. package/core/i18n.py +329 -329
  42. package/core/ice/store.py +191 -191
  43. package/core/inbound.py +193 -193
  44. package/core/jobs.py +19 -3
  45. package/core/last_good.py +150 -150
  46. package/core/llm_errors.py +227 -227
  47. package/core/llm_retry.py +230 -230
  48. package/core/memory/compressor.py +1214 -1214
  49. package/core/memory/manager.py +14 -0
  50. package/core/model_configs.py +80 -0
  51. package/core/pipeline/scheduler.py +2 -2
  52. package/core/pipeline/stages/agent_loop.py +24 -4
  53. package/core/pipeline/stages/pre_process.py +58 -7
  54. package/core/prompt_assembler.py +680 -680
  55. package/core/rg.py +255 -255
  56. package/core/security.py +1544 -1544
  57. package/core/settings_baseline.py +70 -1
  58. package/core/shell.py +5 -17
  59. package/core/skill_settings.py +7 -2
  60. package/core/state_registry.py +19 -0
  61. package/core/subagent.py +64 -3
  62. package/core/task_tool.py +1 -1
  63. package/core/tasks_notify.py +69 -4
  64. package/core/tiers.py +9 -3
  65. package/core/tool_outcome.py +108 -0
  66. package/core/update_tui.py +158 -0
  67. package/core/version.py +2 -2
  68. package/core/web_cache.py +152 -0
  69. package/crannia_tray.py +278 -278
  70. package/creators/models.json +4 -4
  71. package/data/settings.example.json +67 -0
  72. package/licenses/GPL-3.0.txt +619 -619
  73. package/licenses/LGPL-2.1.txt +502 -502
  74. package/licenses/LGPL-3.0.txt +165 -165
  75. package/licenses/MIT-chat-on-wechat.txt +18 -18
  76. package/licenses/MIT-deepseek-harness.txt +21 -21
  77. package/licenses/Molio-LICENSE.txt +44 -44
  78. package/locales/en.json +9 -4
  79. package/main.py +154 -154
  80. package/mcpx/manager.py +522 -522
  81. package/mcpx/servers/__init__.py +22 -22
  82. package/mcpx/servers/web_search.py +321 -33
  83. package/package.json +14 -9
  84. package/providers/anthropic/client.py +772 -772
  85. package/providers/cost_table.json +3779 -3779
  86. package/providers/deepseek/client.py +20 -20
  87. package/providers/deepseek/manifest.yaml +2 -2
  88. package/providers/factory.py +136 -136
  89. package/providers/lmstudio/client.py +2 -2
  90. package/providers/metadata.py +80 -80
  91. package/providers/model_capabilities.json +6665 -6665
  92. package/providers/moonshot/client.py +12 -12
  93. package/providers/ollama/client.py +2 -2
  94. package/providers/openai/client.py +13 -13
  95. package/providers/openrouter/client.py +2 -2
  96. package/providers/qwen/__init__.py +1 -1
  97. package/providers/qwen/client.py +2 -2
  98. package/providers/qwen/manifest.yaml +16 -16
  99. package/providers/rate_limiter.py +144 -144
  100. package/providers/siliconflow/client.py +2 -2
  101. package/providers/validation.py +171 -171
  102. package/providers/window_table.json +8909 -8909
  103. package/sbom.json +4413 -4296
  104. package/skills/entertainment/SKILL.md +35 -35
  105. package/skills/entertainment/__init__.py +1 -1
  106. package/skills/entertainment/handler.py +91 -91
  107. package/skills/entertainment/manifest.yaml +26 -26
  108. package/skills/file_parser/GUIDANCE.md +10 -10
  109. package/skills/file_parser/handler.py +177 -4
  110. package/skills/file_parser/manifest.yaml +22 -1
  111. package/skills/github/SKILL.md +32 -32
  112. package/skills/github/__init__.py +1 -1
  113. package/skills/github/manifest.yaml +5 -0
  114. package/skills/mail_parser/SKILL.md +68 -68
  115. package/skills/mail_parser/__init__.py +1 -1
  116. package/skills/mail_parser/handler.py +806 -806
  117. package/skills/mail_parser/manifest.yaml +5 -0
  118. package/skills/media_gen/GUIDANCE.md +19 -19
  119. package/skills/media_gen/SKILL.md +43 -43
  120. package/skills/media_gen/__init__.py +1 -1
  121. package/skills/media_gen/handler.py +430 -430
  122. package/skills/media_gen/manifest.yaml +93 -88
  123. package/skills/office_parser/cell_validation.py +127 -127
  124. package/skills/office_parser/excel_transform.py +936 -936
  125. package/skills/office_parser/layout_spec.py +243 -243
  126. package/skills/office_parser/pptx_export/console_encoding.py +27 -27
  127. package/skills/office_parser/pptx_export/resource_paths.py +88 -88
  128. package/skills/office_parser/pptx_export/svg_finalize/__init__.py +12 -12
  129. package/skills/office_parser/pptx_export/svg_finalize/align_embed_images.py +575 -575
  130. package/skills/office_parser/pptx_export/svg_finalize/crop_images.py +366 -366
  131. package/skills/office_parser/pptx_export/svg_finalize/embed_icons.py +498 -498
  132. package/skills/office_parser/pptx_export/svg_finalize/embed_images.py +288 -288
  133. package/skills/office_parser/pptx_export/svg_finalize/fix_image_aspect.py +388 -388
  134. package/skills/office_parser/pptx_export/svg_finalize/flatten_tspan.py +818 -818
  135. package/skills/office_parser/pptx_export/svg_finalize/svg_rect_to_path.py +345 -345
  136. package/skills/office_parser/pptx_export/svg_to_pptx/__init__.py +14 -14
  137. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/__init__.py +1 -1
  138. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/context.py +186 -186
  139. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/converter.py +781 -781
  140. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/elements.py +2490 -2490
  141. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/paths.py +429 -429
  142. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/styles.py +656 -656
  143. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/__init__.py +1 -1
  144. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/builder.py +1267 -1267
  145. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/dimensions.py +155 -155
  146. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/discovery.py +101 -101
  147. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/media.py +141 -141
  148. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/narration.py +236 -236
  149. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/notes.py +257 -257
  150. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/slide_xml.py +136 -136
  151. package/skills/office_parser/pptx_export/svg_to_pptx/tspan_flattener.py +44 -44
  152. package/skills/office_parser/pptx_export/svg_to_pptx/use_expander.py +129 -129
  153. package/skills/office_parser/references/LICENSE-Office-Word-MCP-Server.txt +20 -20
  154. package/skills/office_parser/references/LICENSE-excel-mcp-server.txt +21 -21
  155. package/skills/office_parser/references/layout_library.md +816 -816
  156. package/skills/office_parser/references/ppt-master/LICENSE +21 -21
  157. package/skills/office_parser/references/ppt-master/references/executor-base.md +474 -474
  158. package/skills/office_parser/references/ppt-master/references/shared-standards.md +1002 -1002
  159. package/skills/office_parser/references/ppt-master/references/strategist.md +880 -880
  160. package/skills/office_parser/references/ppt-master/references/template-designer.md +402 -402
  161. package/skills/office_parser/references/ppt-master/references/visual-review.md +240 -240
  162. package/skills/office_parser/references/ppt-master/references/visual-styles/_index.md +106 -106
  163. package/skills/office_parser/references/ppt-master/references/visual-styles/blueprint.md +37 -37
  164. package/skills/office_parser/references/ppt-master/references/visual-styles/brutalist.md +38 -38
  165. package/skills/office_parser/references/ppt-master/references/visual-styles/chalkboard.md +36 -36
  166. package/skills/office_parser/references/ppt-master/references/visual-styles/dark-tech.md +37 -37
  167. package/skills/office_parser/references/ppt-master/references/visual-styles/data-journalism.md +36 -36
  168. package/skills/office_parser/references/ppt-master/references/visual-styles/editorial.md +38 -38
  169. package/skills/office_parser/references/ppt-master/references/visual-styles/glassmorphism.md +36 -36
  170. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-notes.md +37 -37
  171. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-wash.md +36 -36
  172. package/skills/office_parser/references/ppt-master/references/visual-styles/memphis.md +37 -37
  173. package/skills/office_parser/references/ppt-master/references/visual-styles/paper-cut.md +36 -36
  174. package/skills/office_parser/references/ppt-master/references/visual-styles/photo-editorial.md +38 -38
  175. package/skills/office_parser/references/ppt-master/references/visual-styles/pixel-art.md +36 -36
  176. package/skills/office_parser/references/ppt-master/references/visual-styles/sketch-notes.md +36 -36
  177. package/skills/office_parser/references/ppt-master/references/visual-styles/soft-rounded.md +37 -37
  178. package/skills/office_parser/references/ppt-master/references/visual-styles/swiss-minimal.md +38 -38
  179. package/skills/office_parser/references/ppt-master/references/visual-styles/vintage-poster.md +36 -36
  180. package/skills/office_parser/references/ppt-master/references/visual-styles/zine.md +37 -37
  181. package/skills/office_parser/references/spec_lock.md +235 -235
  182. package/skills/office_parser/soffice.py +68 -68
  183. package/skills/office_parser/word_tools.py +2909 -2909
  184. package/tui/crannia.cmd +134 -0
  185. package/tui/crannia_tui/__init__.py +1 -0
  186. package/tui/crannia_tui/__main__.py +223 -0
  187. package/tui/crannia_tui/app.py +1318 -0
  188. package/tui/crannia_tui/app.tcss +153 -0
  189. package/tui/crannia_tui/approval.py +85 -0
  190. package/tui/crannia_tui/backend.py +279 -0
  191. package/tui/crannia_tui/channel.py +472 -0
  192. package/tui/crannia_tui/client.py +125 -0
  193. package/tui/crannia_tui/clipboard.py +62 -0
  194. package/tui/crannia_tui/commands.py +65 -0
  195. package/tui/crannia_tui/doctor.py +304 -0
  196. package/tui/crannia_tui/events.py +84 -0
  197. package/tui/crannia_tui/headless.py +152 -0
  198. package/tui/crannia_tui/i18n.py +164 -0
  199. package/tui/crannia_tui/locales/en.json +263 -0
  200. package/tui/crannia_tui/outcome.py +62 -0
  201. package/tui/crannia_tui/paths.py +181 -0
  202. package/tui/crannia_tui/probe.py +53 -0
  203. package/tui/crannia_tui/profile.py +169 -0
  204. package/tui/crannia_tui/render.py +209 -0
  205. package/tui/crannia_tui/settings.py +134 -0
  206. package/tui/crannia_tui/setup.py +380 -0
  207. package/tui/crannia_tui/term.py +116 -0
  208. package/tui/crannia_tui/ui.py +1236 -0
  209. package/tui/crannia_tui/update.py +389 -0
  210. package/vendor/ripgrep/COPYING.txt +3 -3
  211. package/vendor/ripgrep/LICENSE-MIT.txt +21 -21
  212. package/vendor/ripgrep/NOTICE-vscode-ripgrep.txt +13 -13
  213. package/vendor/ripgrep/README.md +51 -51
  214. package/vendor/ripgrep/UNLICENSE.txt +24 -24
  215. package/vendor/ripgrep/package-source.json +19 -19
  216. package/web/__main__.py +15 -0
  217. package/web/server.py +168 -19
  218. package/web/static/img/channel-telegram.svg +1 -1
  219. package/web/static/img/channel-wechat.svg +1 -1
  220. package/web/templates/logs.html +49 -49
  221. package/web/templates/models.html +46 -46
@@ -1,813 +1,813 @@
1
- """
2
- Telegram Channel — multi-user messaging via Telegram Bot API.
3
-
4
- Uses a manual `getUpdates` polling loop instead of PTB's
5
- `Updater` / `run_polling()`. This avoids all the threading and
6
- event-loop conflicts that prevent message dispatch when running
7
- inside an existing asyncio context.
8
-
9
- Architecture::
10
-
11
- while running:
12
- updates = await bot.get_updates(offset=offset, timeout=0)
13
- for update in updates:
14
- await app.process_update(update) # dispatches to handlers
15
- offset = update.update_id + 1
16
-
17
- 所有 `/` 命令都进管线(`filters.COMMAND`)——
18
- 以前只注册了 `/start` `/clear` `/compact` 三条,其余命令
19
- 发过去什么都不发生(`filters.TEXT & ~filters.COMMAND` 把它们挡在门外),
20
- 而管线的 `/effort` `/skill` `/btw` 那一族一条都没被叫到过。
21
- 入站媒体每种都有去处(照片 / 语音 / 音频 / 视频 / 视频留言 / GIF /
22
- 贴纸 / 文档)—— 分派在 `media.items_of`,下载一个异常都不许漏出去。
23
- 出站媒体(`send_media_file`)—— `deliver_file` 因此在 Telegram 会话里
24
- 也走直发,不再落到邮件兜底;取件排在回复之后(`core/delivery_outbox`)。
25
- """
26
-
27
- from __future__ import annotations
28
-
29
- import asyncio
30
- import json
31
- import os
32
- from pathlib import Path
33
- from typing import Any
34
-
35
- from channels.base import (
36
- Channel,
37
- ChannelMetadata,
38
- Message,
39
- MessageSession,
40
- MessageType,
41
- )
42
- from channels.converter import MessageConverter
43
- from channels.message import MessageChain, Plain
44
- from channels.telegram_channel import media as tg_media
45
- from core import channel_turns
46
-
47
- # ------------------------------------------------------------------
48
- # Constants
49
- # ------------------------------------------------------------------
50
-
51
- TELEGRAM_MAX_MESSAGE_LENGTH = 4096
52
- _TEMP_DIR = Path("data/workdata/telegram_files")
53
-
54
- #: 分片前缀 `(i/N)` 的预算(最长 `(9999/9999)\n` = 12 字符)。
55
- #: 不扣这 12 个字符的后果:第一片正好 4096 时 `前缀 + 正文` 超限,
56
- #: Telegram 直接拒收 —— 整条回复发不出去,而日志里只有一行 400。
57
- _CHUNK_PREFIX_BUDGET = 12
58
-
59
- #: 轮询游标(`update_id + 1`)的落点 —— 运行时数据,进 `data/runtime/`。
60
- _OFFSET_PATH = Path("data/runtime/telegram_offset.json")
61
-
62
-
63
- # ------------------------------------------------------------------
64
- # TelegramMessageConverter
65
- # ------------------------------------------------------------------
66
-
67
- class TelegramMessageConverter(MessageConverter):
68
- """Translate between Telegram `Update` and `MessageChain`.
69
-
70
- `to_internal` extracts text, caption, photo, and document from
71
- a `telegram.Update` (the raw message from PTB).
72
-
73
- `to_platform` converts a `MessageChain` back to a dict
74
- representation that the channel's send methods understand.
75
- """
76
-
77
- # -- platform → internal -----------------------------------------
78
-
79
- def to_internal(
80
- self,
81
- platform_message: Any,
82
- media: list[tuple[dict, str]] | None = None,
83
- ) -> MessageChain:
84
- """Convert a `telegram.Update` into a MessageChain.
85
-
86
- *media* 是已经下好的 `[(item, local_path)]`(`media.items_of` 的
87
- 形状,路径由通道的 `_download_media` 填)—— 这里只负责排进链子。
88
-
89
- 本方法不 import `telegram`:鸭子类型就够(字段用 `getattr` 取),
90
- 所以没装 SDK 的测试也能跑;而"没装 SDK 就整条丢空"是旧写法的副作用。
91
- """
92
- tg_msg = getattr(platform_message, "message", None)
93
- if tg_msg is None:
94
- return MessageChain()
95
-
96
- components: list = []
97
- #: 文字 / 图注(媒体消息也常带 caption)—— 排在媒体之前,
98
- #: 与钉钉 / 飞书那两条通道同一个顺序。
99
- text = getattr(tg_msg, "text", None) or getattr(tg_msg, "caption", None) or ""
100
- if text:
101
- components.append(Plain(str(text)))
102
- for item, local_path in (media or []):
103
- comp = tg_media.component_of(item, local_path)
104
- if comp is not None:
105
- components.append(comp)
106
- return MessageChain(components) if components else MessageChain()
107
-
108
- # -- internal → platform -----------------------------------------
109
-
110
- def to_platform(self, message_chain: MessageChain, **kwargs: Any) -> dict[str, Any]:
111
- """Convert a MessageChain to a dict for Telegram send methods.
112
-
113
- Returns a dict with keys like `text`, `photo_path`,
114
- `doc_path`, `doc_name`.
115
-
116
- 今天只有 `to_internal` 那条路在用(入站);出站走的是
117
- `send_media_file`(本地文件直接交给 Bot API),不再经过这个 dict。
118
- 留着它是 `MessageConverter` 的契约,别在别处按它写第二套。
119
- """
120
- result: dict[str, Any] = {"text": message_chain.content}
121
-
122
- for img in message_chain.images:
123
- result["photo_path"] = img.local_path
124
- if img.mime_type:
125
- result["photo_mime"] = img.mime_type
126
- break # Only one photo per message (Telegram limitation)
127
-
128
- for f in message_chain.files:
129
- result["doc_path"] = f.local_path
130
- result["doc_name"] = f.name
131
- if f.mime_type:
132
- result["doc_mime"] = f.mime_type
133
- break # Only one doc per message
134
-
135
- return result
136
-
137
-
138
- # ------------------------------------------------------------------
139
- # TelegramChannel
140
- # ------------------------------------------------------------------
141
-
142
- class TelegramChannel(Channel):
143
- """Telegram Bot adapter — manual getUpdates loop, no PTB Updater."""
144
-
145
- def __init__(
146
- self,
147
- config: dict | None = None,
148
- scheduler=None,
149
- session_pool=None,
150
- ) -> None:
151
- super().__init__(config)
152
- self._converter = TelegramMessageConverter()
153
- self._scheduler = scheduler
154
- self._pool = session_pool
155
- self._running = False
156
- self._app = None
157
- self._bot = None
158
-
159
- tg_cfg = (config or {}).get("channel", {}).get("telegram", {})
160
- # 配置条目账本是唯一写入方;读不到才回退到 config.yaml / 环境变量。
161
- from core import channel_configs as _cc
162
- self._bot_token = (_cc.credentials_for("telegram").get("bot_token")
163
- or tg_cfg.get("bot_token")
164
- or os.environ.get("TELEGRAM_BOT_TOKEN", ""))
165
- #: 代理从一处口径取(`core/net_proxy` 的三档),而不是"读环境变量"。
166
- #: 真取值发生在 `run()` 里(`_resolve_proxy()`)—— 这里只放一个初值,
167
- #: 好让"构造完就能看到它是什么"这件事成立(自检 / 日志用)。
168
- self._proxy_url = self._resolve_proxy()
169
- self._polling_timeout = tg_cfg.get("polling_timeout", 30)
170
-
171
- #: 机器人自己的身份(`run()` 拿到 `get_me` 之后填)—— 群聊唤醒门要用。
172
- self._bot_username = ""
173
- self._bot_id = None
174
- #: 群聊里什么时候才回:`mention`(默认,@ / 回复机器人)· `any`(每条都回)。
175
- #: 默认与 Telegram 自己的隐私模式一致;`any` 是给"把机器人当群助手"的人留的。
176
- #: 读不到/写错,回默认(不是拒启:这是一个口味轴,不是能力轴)。
177
- _gt = str(tg_cfg.get("group_trigger", "mention") or "mention").strip().lower()
178
- self._group_trigger = _gt if _gt in ("mention", "any") else "mention"
179
-
180
- _TEMP_DIR.mkdir(parents=True, exist_ok=True)
181
-
182
- # ---- Channel ABC ----
183
-
184
- def meta(self) -> ChannelMetadata:
185
- return ChannelMetadata(
186
- name="telegram_channel",
187
- description="Telegram Bot adapter — multi-user messaging",
188
- platform_type="telegram",
189
- support_multimodal=True,
190
- )
191
-
192
- def _resolve_proxy(self) -> str:
193
- """每次 `run()` 现取代理 —— 与微信一致(它在 `run()` 里建 client)。
194
-
195
- 为什么不能只在 `__init__` 里取:
196
- 通道实例是进程内长活的(`bus.registry` 里那一份),
197
- `__init__` 只在应用启动时跑一次。若在那里定死,
198
- 「先启动通道 → 之后才开代理」时,连"停止通道再启动"都换不过来
199
- (拿到的还是同一个实例),只能重启整个应用 —— 而症状是
200
- 界面绿框"运行中"、IM 里发消息没有任何回应(最贵的那种形状)。
201
- 优先级:通道自己的 `proxy` 配置 > 全局三档;`direct` 档下**连通道级
202
- 配置也让开**(那正是自救路)。
203
- """
204
- tg_cfg = (self.config or {}).get("channel", {}).get("telegram", {})
205
- from core import net_proxy as _np
206
- mode, url = _np.state()
207
- if mode == "direct":
208
- base = ""
209
- elif mode == "manual":
210
- base = url
211
- else:
212
- base = os.environ.get("HTTPS_PROXY", "")
213
- return tg_cfg.get("proxy", "") or base
214
-
215
- async def run(self) -> None:
216
- self._proxy_url = self._resolve_proxy()
217
- """Manual getUpdates loop — all inside our event loop."""
218
- if not self._bot_token:
219
- print("[telegram] ERROR: No bot token configured.")
220
- return
221
-
222
- # Proxy
223
- #: 不再往 `os.environ` 里塞(那会污染同进程里所有其他出网方,
224
- #: 包括模型 provider —— 一处配错全线遭殃)。改成只作用于这个 bot。
225
- from telegram.ext import ApplicationBuilder
226
- builder = ApplicationBuilder().token(self._bot_token)
227
- if self._proxy_url:
228
- from core.net_proxy import redact as _redact
229
- print(f"[telegram] Using proxy: {_redact(self._proxy_url)}")
230
- builder = builder.proxy(self._proxy_url).get_updates_proxy(self._proxy_url)
231
- app = builder.build()
232
-
233
- try:
234
- await app.initialize()
235
- await app.start()
236
- except Exception as e:
237
- _ename = type(e).__name__
238
- print(f"[telegram] ERROR: Cannot start — {_ename}: {e}")
239
- # 网络类失败要说改哪里,不是让用户去猜 token / 代理 / 网络三者中的哪一个。
240
- # 真机上遇到过:系统代理开着、设置里是「直连」,于是直连超时;
241
- # 而原来那句话只有 "Check your token, proxy, and network",用户得反过来
242
- # 查注册表才知道是代理档位的问题。
243
- if _ename in ("TimedOut", "NetworkError") or "timed out" in str(e).lower():
244
- try:
245
- from core import net_proxy as _np
246
- _mode = _np.state()[0]
247
- except Exception: # noqa: BLE001
248
- _mode = "?"
249
- _err = ("连接异常,请检查代理设置 —— 设置 → 安全 → 代理设置"
250
- f"(当前档位:{_mode})")
251
- _tpl = ("连接异常,请检查代理设置 —— 设置 → 安全 → 代理设置"
252
- "(当前档位:{mode})")
253
- _vars = {"mode": _mode}
254
- else:
255
- _err = f"{_ename}: {e}"
256
- _tpl, _vars = "", {}
257
- print("[telegram] Check your token, proxy, and network.")
258
- print("[telegram] " + _err)
259
- #: 让界面也看得见。原来只有终端那一行,而桌面壳里没有终端,
260
- #: 通道卡只会回到「未运行」。走事故账本:它的明细行已经支持
261
- #: 「模板 + 变量」,英文界面也翻得动。
262
- try:
263
- from core import incidents as _inc
264
- _inc.note("telegram_channel", "channel", _err,
265
- error_tpl=_tpl, error_vars=_vars,
266
- detail=f"{_ename}: {e}")
267
- except Exception: # noqa: BLE001
268
- pass
269
- return
270
-
271
- self._app = app
272
- self._bot = app.bot
273
-
274
- # Verify connection
275
- try:
276
- me = await app.bot.get_me()
277
- #: 机器人自己的身份 —— 群聊唤醒门要用(`media.addressed_to_bot`)。
278
- self._bot_username = str(getattr(me, "username", "") or "")
279
- self._bot_id = getattr(me, "id", None)
280
- print(f"[telegram] Connected as @{me.username} (id={me.id})")
281
- #: 成对的另一半:这次真的连上了,就撤掉上次那条事故。没有它,
282
- #: 用户改好代理、通道起来了,横幅还挂着,那就是一条没人能撤的旧账。
283
- try:
284
- from core import incidents as _inc
285
- _inc.resolve("telegram_channel", "channel")
286
- except Exception: # noqa: BLE001
287
- pass
288
- except Exception as e:
289
- print(f"[telegram] WARNING: get_me failed — {type(e).__name__}: {e}")
290
-
291
- # ---- Register handlers on the application ----
292
- from telegram.ext import MessageHandler, filters
293
-
294
- channel = self # closure capture
295
-
296
- #: 回调只做转发 —— 真逻辑在 `self._handle_update` / `self._reply_update`
297
- #: (类方法才测得了:闭包只能在 `run()` 里活一次)。
298
- #: 回答不在这里发了 —— `_handle_update` 只入队就返回,
299
- #: 回答由 worker 线程回头调 `_reply_update`(本条的 `on_reply`)。
300
- #: 旧写法是 `_reply_update(update, await _handle_update(update))`,
301
- #: 而 `_handle_update` 里 `await execute` 整轮不回头,轮询循环
302
- #: 连下一条 `get_updates` 都发不出去("IM 打不断"的真形状)。
303
- async def _handler(update: Any, context: Any) -> None:
304
- """文本 / 所有 `/` 命令 —— 都走同一条处理链。"""
305
- await channel._handle_update(update)
306
-
307
- async def _media_handler(update: Any, context: Any) -> None:
308
- """照片 / 语音 / 音频 / 视频 / 视频留言 / GIF / 贴纸 / 文档。"""
309
- if not update.message:
310
- return
311
- media = await channel._download_media(update.message)
312
- await channel._handle_update(update, media=media)
313
-
314
- # 一条命令都不许漏:`filters.COMMAND` 兜住所有 `/xxx`。
315
- # 旧写法只注册了 `/start` `/clear` `/compact` 三条 ——
316
- # `/effort` `/skill` `/btw` `/recap` `/language` 那一族发过去
317
- # 什么都不发生(而它们全都在管线的 pre_process 里实现好了)。
318
- app.add_handler(MessageHandler(
319
- filters.TEXT & ~filters.COMMAND, _handler,
320
- ))
321
- app.add_handler(MessageHandler(filters.COMMAND, _handler))
322
- app.add_handler(MessageHandler(
323
- filters.PHOTO | filters.VOICE | filters.AUDIO | filters.VIDEO
324
- | filters.VIDEO_NOTE | filters.ANIMATION | filters.Sticker.ALL
325
- | filters.Document.ALL,
326
- _media_handler,
327
- ))
328
-
329
- # ---- Main polling loop ----
330
- print("[telegram] Bot is running (manual getUpdates loop).")
331
- self._running = True
332
- #: 游标从盘上接回来 —— 否则重启会把最近未确认的那批 update
333
- #: 再处理一遍(去重缓存重启后是空的,拦不住)。
334
- offset = _load_offset()
335
- if offset:
336
- print("[telegram] 从上次的游标接着收(update_id >= %d)" % offset)
337
-
338
- while self._running:
339
- retries = 0
340
- try:
341
- updates = await app.bot.get_updates(
342
- offset=offset,
343
- timeout=0,
344
- allowed_updates=["message"],
345
- )
346
- retries = 0 # reset on success
347
- await asyncio.sleep(0.8) # rate-limit
348
- except Exception as e:
349
- err_name = type(e).__name__
350
- if "TimedOut" in err_name or "Timeout" in str(e):
351
- await asyncio.sleep(1)
352
- continue
353
- retries += 1
354
- wait = min(2 ** retries, 30)
355
- print(f"[telegram] {err_name}, retry in {wait}s (attempt {retries})")
356
- await asyncio.sleep(wait)
357
- continue
358
-
359
- moved = False
360
- for update in updates:
361
- offset = update.update_id + 1
362
- moved = True
363
- try:
364
- await app.process_update(update)
365
- except Exception as e:
366
- print(f"[telegram] process_update error: "
367
- f"{type(e).__name__}: {e}")
368
- # 游标照推(这条算丢),但必须说出来
369
- # (「丢,提醒用户『消息遗失,未接受』」)。
370
- # 不推游标,一条坏消息会被无限重投,整条通道卡死;
371
- # 推了却不说,用户看见的是"我发了,它没理我"。
372
- await self._notify_lost(update)
373
- #: 一批处理完才落盘(每条都写会把盘写穿);写失败它自己会出声。
374
- if moved:
375
- _save_offset(offset)
376
-
377
- async def _notify_lost(self, update: Any) -> None:
378
- """一条 update 没能处理成,在那个会话里明说「消息遗失,未接受」。
379
-
380
- 不抛:这条路本来就是失败路径,再抛一次会连累同一批后面的
381
- update(`process_update` 那层会继续下一轮)。
382
- """
383
- chat_id = None
384
- try:
385
- chat_id = getattr(getattr(update, "effective_chat", None), "id", None)
386
- except Exception: # noqa: BLE001
387
- chat_id = None
388
- if chat_id is None or self._bot is None:
389
- print("[telegram] 这条消息没处理成,且没有可用的会话回话 —— 只能记日志")
390
- return
391
- try:
392
- await self._bot.send_message(
393
- chat_id=chat_id,
394
- text="⚠️ 消息遗失,未接收,需要时请重新发送。")
395
- except Exception as e: # noqa: BLE001
396
- print(f"[telegram] 「消息遗失」提醒没发出去:"
397
- f"{type(e).__name__}: {e}")
398
-
399
- async def terminate(self) -> None:
400
- self._running = False
401
- if self._app:
402
- try:
403
- await self._app.stop()
404
- await self._app.shutdown()
405
- except Exception:
406
- pass
407
- print("[telegram] Bot stopped.")
408
-
409
- # ------------------------------------------------------------------
410
- # 入站:一条 update → 管线 → 回答
411
- # ------------------------------------------------------------------
412
-
413
- async def _handle_update(self, update: Any,
414
- media: list[tuple[dict, str]] | None = None
415
- ) -> str | None:
416
- """Core processing: convert update → pipeline → response.
417
-
418
- *media* 是已经下好的 `[(item, path)]`(媒体那条路先下载再进来)。
419
- Returns the response text (or None on empty / error).
420
- """
421
- if not getattr(update, "message", None) or not getattr(update, "effective_user", None):
422
- return None
423
-
424
- user = update.effective_user
425
-
426
- chain = self._converter.to_internal(update, media=media)
427
-
428
- # Skip completely empty chains (silent messages)
429
- if chain.is_empty:
430
- return None
431
-
432
- session = self._make_session(update)
433
-
434
- # 群聊唤醒门:群里默认只回「@ 我」与「回复我」。
435
- # 判据见 `media.addressed_to_bot`(实体 / 回复 / 文本兜底三种信号)。
436
- # 机器人身份一个都拿不到时(`get_me` 失败)放行 ——
437
- # 判不出来就别拦:漏回一条比误吞一条更糟。
438
- if (session.message_type is MessageType.GROUP
439
- and self._group_trigger != "any"
440
- and (self._bot_username or self._bot_id is not None)
441
- and not tg_media.addressed_to_bot(
442
- getattr(update, "message", None),
443
- self._bot_username, self._bot_id)):
444
- print("[telegram] 群里这条不是在跟我说话,跳过(chat=%s)"
445
- % session.session_id)
446
- return None
447
-
448
- log_text = chain.content[:80] if chain.content else "[media]"
449
- print(f"[telegram] msg from {user.full_name or user.username}: {log_text}")
450
-
451
- message = Message(
452
- sender_id=str(user.id),
453
- sender_name=user.full_name or user.username or "",
454
- message_chain=chain,
455
- message_type=session.message_type,
456
- session=session,
457
- #: 平台消息号 —— 管线用它做去重(`pre_process` 那道闸读的
458
- #: 就是 `ctx.metadata["message_id"]`)。不传 = 那道闸恒不触发。
459
- message_id=str(getattr(update.message, "message_id", "") or ""),
460
- )
461
- event = self.commit_event(message)
462
-
463
- # Typing indicator
464
- try:
465
- await update.message.chat.send_action("typing")
466
- except Exception: # noqa: BLE001
467
- pass
468
-
469
- if not self._scheduler:
470
- return None
471
-
472
- #: 只入队,立刻返回。回答由 worker 线程投回**本通道的
473
- #: loop** 上发(`on_reply`)—— 客户端绑在这个 loop 上,别新造循环。
474
- #: 异常那句人话也由 `core/channel_turns` 统一发(同一个 worker 线程)。
475
- async def _on_reply(text: str) -> None:
476
- await self._reply_update(update, text)
477
-
478
- await channel_turns.intake(self, event, on_reply=_on_reply)
479
- return None
480
-
481
- async def _reply_update(self, update: Any, response: str | None) -> None:
482
- """发回答,然后把本轮登记的文件发出去。
483
-
484
- 顺序是判据(`core/delivery_outbox`):用户先看到那句话,再收到附件;
485
- 取件只取自己这一轮的(三格全对)。
486
- """
487
- # 取件放在 `finally` 里:发送这一段抛了(429 / 网络 / 实体错),
488
- # 文件也照样要发 —— 否则"模型说要交付"与"用户收到"是两件事。
489
- try:
490
- if response and getattr(update, "message", None):
491
- await self._send_long(update.message, response)
492
- finally:
493
- try:
494
- await self._drain_delivered(self._make_session(update))
495
- except Exception as e: # noqa: BLE001
496
- print(f"[telegram] 发待交付文件时出错({type(e).__name__}: {e})")
497
-
498
- async def send(self, session: MessageSession, content: str | MessageChain) -> bool:
499
- """没有 Bot 就是没送达 —— 以前这一支什么都不做、也不出声。
500
-
501
- 异常照旧往上抛(`Runner` 那条 `except` 会把它记成失败);
502
- 这里只把"静默什么都不做"那一支改成一个明确的 `False`。
503
-
504
- 发完之后顺手把本轮登记的文件取走发掉 —— 定时任务 / 后台回报
505
- 这条路上,那是文件唯一的出口(同微信 / 飞书 / 钉钉)。
506
- """
507
- if not self._bot:
508
- print(f"[telegram] 没有 Bot 实例,这条没有送达:{session.session_id}")
509
- return False
510
- chat_id = _chat_id_of(session)
511
- if chat_id is None:
512
- print(f"[telegram] 会话 id 不是数字,发不出去:{session.session_id!r}")
513
- return False
514
- text = content if isinstance(content, str) else content.content
515
- delivered = False
516
- if str(text or "").strip():
517
- await self._send_long_via_bot(chat_id, str(text))
518
- delivered = True
519
- files = await self._drain_delivered(session)
520
- return delivered or files > 0
521
-
522
- async def send_note(self, session: MessageSession, text: str,
523
- event=None) -> bool:
524
- """一行旁白("已收到" / "已中断")—— 不捎带本轮待发文件。
525
-
526
- 为什么不直接用 `send()`:它会取走 `core/delivery_outbox` 里
527
- 本轮待交付的文件,一轮还在跑的时候附件就被提前发出去了
528
- (用户先看到文件、再看到回答)。判据见 `channels/base.py::send_note`。
529
- """
530
- if not self._bot:
531
- print(f"[telegram] 没有 Bot 实例,这句旁白没送达:{session.session_id}")
532
- return False
533
- chat_id = _chat_id_of(session)
534
- if chat_id is None or not str(text or "").strip():
535
- return False
536
- await self._send_long_via_bot(chat_id, str(text))
537
- return True
538
-
539
- async def test_connection(self) -> dict:
540
- """连通性自检(通道页 / 引导页用)。
541
-
542
- 判据:配置在 + SDK 在就算"可接入";
543
- 真连一次网络是 `run()` 的事(这里不替用户打请求)。
544
- """
545
- if not self._bot_token:
546
- return {"ok": False, "message": "Telegram bot_token 没配置"}
547
- try:
548
- import telegram # noqa: F401
549
- except ImportError:
550
- return {"ok": False, "message": "python-telegram-bot 没装"}
551
- if self._bot is not None:
552
- try:
553
- me = await self._bot.get_me()
554
- return {"ok": True, "message": "Connected as @%s" % me.username}
555
- except Exception as exc: # noqa: BLE001
556
- return {"ok": False, "message": "%s: %s"
557
- % (type(exc).__name__, exc)}
558
- return {"ok": True, "message": "Telegram SDK available"}
559
-
560
- # ------------------------------------------------------------------
561
- # 出站媒体(`MediaSendCapable`)
562
- # ------------------------------------------------------------------
563
-
564
- async def send_media_file(self, session: MessageSession, file_path: str,
565
- filename: str = "",
566
- context_token: str = "") -> bool:
567
- """发一个本地图片/文件。真交出去才回 `True`(的回执契约)。
568
-
569
- *context_token* 是微信那条协议的概念,Telegram 不用它 —— 保留形参
570
- 是为了与能力协议(`channels/capabilities.py::MediaSendCapable`)同一个
571
- 签名,`deliver_file` 那侧按属性存在认通道。
572
- """
573
- if not self._bot:
574
- print("[telegram] 没有 Bot 实例,附件发不出去")
575
- return False
576
- p = Path(str(file_path or ""))
577
- if not p.is_file():
578
- print("[telegram] 要发的文件不存在:%s" % (file_path or "(空)"))
579
- return False
580
- chat_id = _chat_id_of(session)
581
- if chat_id is None:
582
- print(f"[telegram] 会话 id 不是数字,附件发不出去:{session.session_id!r}")
583
- return False
584
- name = filename or p.name
585
- kind = tg_media.outbound_kind(name)
586
- try:
587
- from telegram import InputFile
588
- with open(p, "rb") as fh:
589
- upload = InputFile(fh, filename=name)
590
- if kind == "photo":
591
- await self._call_with_retry(
592
- self._bot.send_photo, chat_id=chat_id, photo=upload)
593
- else:
594
- await self._call_with_retry(
595
- self._bot.send_document, chat_id=chat_id,
596
- document=upload)
597
- except Exception as exc: # noqa: BLE001
598
- print(f"[telegram] 附件发送失败({type(exc).__name__}: {exc})")
599
- return False
600
- print("[telegram] 附件已发送:%s(%s)" % (name, kind))
601
- return True
602
-
603
- async def _drain_delivered(self, session: MessageSession) -> int:
604
- """把本轮 `deliver_file` 登记的文件发出去,返回真发出去的条数。
605
-
606
- 判据见 `core/delivery_outbox`:工具是同步的、不能 await 这个循环,
607
- 所以它只登记;通道在发完回复之后取走发掉,失败时回一句话给用户。
608
- 三格都要对上:`session_key + channel + user_id`。
609
- """
610
- from core import delivery_outbox as _outbox
611
- from core.session_key import session_key_for
612
-
613
- try:
614
- recs = _outbox.take_for(
615
- session_key=session_key_for(session),
616
- channel="telegram_channel",
617
- user_id=str(getattr(session, "session_id", "") or ""))
618
- except Exception as exc: # noqa: BLE001
619
- print(f"[telegram] 取待发文件失败({type(exc).__name__}: {exc})")
620
- return 0
621
- sent = 0
622
- for rec in recs:
623
- if await self.send_media_file(session, rec.get("path", ""),
624
- rec.get("name", "")):
625
- sent += 1
626
- continue
627
- chat_id = _chat_id_of(session)
628
- if chat_id is None:
629
- continue
630
- try:
631
- await self._bot.send_message(
632
- chat_id=chat_id,
633
- text="文件 %s 没能发出去(原因在框架日志里)。"
634
- % (rec.get("name") or "?"))
635
- except Exception: # noqa: BLE001
636
- pass
637
- return sent
638
-
639
- # ------------------------------------------------------------------
640
- # 入站媒体
641
- # ------------------------------------------------------------------
642
-
643
- async def _download_media(self, tg_msg: Any) -> list[tuple[dict, str]]:
644
- """把这条消息的媒体下到本地,返回 `[(item, 本地路径)]`。
645
-
646
- 一个异常都不许漏出去:漏出去整条消息连管线都进不去,
647
- 用户看到的是"这条消息不存在"(飞书那次的真现场)。取不到就
648
- 跳过这一件,其余照常 —— 并且说出来。
649
- 20 MB 是 Bot API `getFile` 的硬上限,超了连下载地址都拿不到
650
- 提前判,别把它报成"下载失败"。
651
- """
652
- out: list[tuple[dict, str]] = []
653
- for item in tg_media.items_of(tg_msg):
654
- file_id = str(item.get("file_id") or "")
655
- if not file_id:
656
- print("[telegram] 媒体没有 file_id,跳过(kind=%s)" % item.get("kind"))
657
- continue
658
- size = int(item.get("size") or 0)
659
- if size > tg_media.MAX_DOWNLOAD_BYTES:
660
- print("[telegram] 附件太大(%d 字节 > %d),没有下载:%s"
661
- % (size, tg_media.MAX_DOWNLOAD_BYTES, item.get("name")))
662
- continue
663
- try:
664
- tg_file = await self._bot.get_file(file_id)
665
- path = _TEMP_DIR / ("%s_%s%s" % (
666
- item.get("kind") or "file", file_id[-12:],
667
- tg_media.ext_of(item)))
668
- await tg_file.download_to_drive(path)
669
- out.append((item, str(path)))
670
- print("[telegram] 附件已落盘:%s(%s,%d 字节)"
671
- % (path.name, item.get("kind"), size))
672
- except Exception as exc: # noqa: BLE001
673
- print(f"[telegram] 取附件失败({type(exc).__name__}: {exc})")
674
- return out
675
-
676
- # ------------------------------------------------------------------
677
- # Internal
678
- # ------------------------------------------------------------------
679
-
680
- def _make_session(self, update: Any) -> MessageSession:
681
- from telegram.constants import ChatType
682
- chat = update.effective_chat
683
- if chat.type == ChatType.PRIVATE:
684
- return MessageSession("telegram", MessageType.PRIVATE, str(chat.id))
685
- return MessageSession("telegram", MessageType.GROUP, str(chat.id))
686
-
687
- async def _call_with_retry(self, fn, *args, **kwargs):
688
- """调一次 Bot API;撞上 429 就等它说的秒数,重试一次。
689
-
690
- `RetryAfter` 必须处理:Telegram 的 per-chat 限速是真实存在的 ——
691
- 一段长回复切成十几片时就会撞上。不处理的话症状是"最后几片没了",
692
- 而日志里只有一行 429。
693
- """
694
- try:
695
- return await fn(*args, **kwargs)
696
- except Exception as exc: # noqa: BLE001
697
- wait = _retry_after_of(exc)
698
- if wait is None:
699
- raise
700
- print("[telegram] 被限流,%.0f 秒后重试一次" % wait)
701
- await asyncio.sleep(wait)
702
- return await fn(*args, **kwargs)
703
-
704
- async def _send_long(self, message: Any, content: str) -> None:
705
- """Send, splitting long messages(前缀也算进 4096 的预算)。"""
706
- for prefix, chunk in _split_for_telegram(content):
707
- await self._call_with_retry(message.reply_text, prefix + chunk)
708
-
709
- async def _send_long_via_bot(self, chat_id: int, content: str) -> None:
710
- """Send via bot (for proactive messages)."""
711
- for prefix, chunk in _split_for_telegram(content):
712
- await self._call_with_retry(
713
- self._bot.send_message, chat_id=chat_id, text=prefix + chunk)
714
-
715
-
716
- # ------------------------------------------------------------------
717
- # Helpers
718
- # ------------------------------------------------------------------
719
-
720
- def _load_offset(path: Path | None = None) -> int:
721
- """读回上次的 `update_id + 1`。读不到 / 坏文件,`0`(出声,不静默)。
722
-
723
- 为什么它非有不可:`getUpdates` 的 offset 只活在进程里。重启后从 0 开始,
724
- Telegram 会把最近未确认的那批 update 再发一遍(最多 24 小时),
725
- 而去重缓存(5 分钟 TTL)重启后是空的,用户会收到重复的回复。
726
- """
727
- p = Path(path) if path is not None else _OFFSET_PATH
728
- try:
729
- data = json.loads(p.read_text(encoding="utf-8"))
730
- except FileNotFoundError:
731
- return 0
732
- except Exception as exc: # noqa: BLE001
733
- print("[telegram] 游标读不出来,从 0 开始(可能重放积压):%s: %s"
734
- % (type(exc).__name__, exc))
735
- return 0
736
- try:
737
- return max(0, int((data or {}).get("offset") or 0))
738
- except (TypeError, ValueError, AttributeError):
739
- return 0
740
-
741
-
742
- def _save_offset(value: int, path: Path | None = None) -> None:
743
- """把游标写回(先写临时文件再 `replace`,半个文件不会留在那儿)。"""
744
- p = Path(path) if path is not None else _OFFSET_PATH
745
- try:
746
- p.parent.mkdir(parents=True, exist_ok=True)
747
- tmp = p.with_suffix(p.suffix + ".tmp")
748
- tmp.write_text(json.dumps({"offset": int(value)}), encoding="utf-8")
749
- tmp.replace(p)
750
- except Exception as exc: # noqa: BLE001
751
- # 写不进去也要出声:否则下次重启静默重放
752
- print("[telegram] 游标写不进去(重启会重放积压):%s: %s"
753
- % (type(exc).__name__, exc))
754
-
755
-
756
- def _retry_after_of(exc: BaseException) -> float | None:
757
- """异常里的 `retry_after` 秒数;不是限流就 `None`。
758
-
759
- 按属性认,不 import `telegram.error` —— 没装 SDK 也能测。
760
- PTB 各版本给的是 `int` 或 `timedelta`,两种都认。
761
- """
762
- value = getattr(exc, "retry_after", None)
763
- if value is None:
764
- return None
765
- try:
766
- secs = value.total_seconds() if hasattr(value, "total_seconds") else value
767
- return max(0.0, float(secs))
768
- except (TypeError, ValueError):
769
- return None
770
-
771
-
772
- def _split_for_telegram(text: str) -> list[tuple[str, str]]:
773
- """切成 `(前缀, 正文)`,两段加起来 ≤ 4096。
774
-
775
- 旧写法先按 4096 切、再加 `(i/N)` 前缀,第一片正好 4096 时超限,
776
- Telegram 拒收,整条回复发不出去(日志只有一行 400)。
777
- """
778
- s = str(text or "")
779
- if len(s) <= TELEGRAM_MAX_MESSAGE_LENGTH:
780
- return [("", s)]
781
- chunks = _split_text(s, TELEGRAM_MAX_MESSAGE_LENGTH - _CHUNK_PREFIX_BUDGET)
782
- n = len(chunks)
783
- if n <= 1:
784
- return [("", chunks[0] if chunks else s)]
785
- return [("(%d/%d)\n" % (i + 1, n), c) for i, c in enumerate(chunks)]
786
-
787
-
788
- def _chat_id_of(session: MessageSession) -> int | None:
789
- """会话 id → Telegram 的 chat id。不猜:不是整数就回 `None`。
790
-
791
- 回 `None` 而不是抛:调用方(`send` / `send_media_file`)要把它变成
792
- 一个明确的 `False`(没送达要说得出来),而不是炸到调度器里。
793
- """
794
- try:
795
- return int(str(getattr(session, "session_id", "")))
796
- except (TypeError, ValueError):
797
- return None
798
-
799
-
800
- def _split_text(text: str, max_len: int) -> list[str]:
801
- if len(text) <= max_len:
802
- return [text]
803
- chunks: list[str] = []
804
- remaining = text
805
- while len(remaining) > max_len:
806
- split_at = remaining.rfind("\n", 0, max_len)
807
- if split_at == -1 or split_at < max_len // 2:
808
- split_at = max_len
809
- chunks.append(remaining[:split_at])
810
- remaining = remaining[split_at:].lstrip("\n")
811
- if remaining:
812
- chunks.append(remaining)
813
- return chunks
1
+ """
2
+ Telegram Channel — multi-user messaging via Telegram Bot API.
3
+
4
+ Uses a manual `getUpdates` polling loop instead of PTB's
5
+ `Updater` / `run_polling()`. This avoids all the threading and
6
+ event-loop conflicts that prevent message dispatch when running
7
+ inside an existing asyncio context.
8
+
9
+ Architecture::
10
+
11
+ while running:
12
+ updates = await bot.get_updates(offset=offset, timeout=0)
13
+ for update in updates:
14
+ await app.process_update(update) # dispatches to handlers
15
+ offset = update.update_id + 1
16
+
17
+ 所有 `/` 命令都进管线(`filters.COMMAND`)——
18
+ 以前只注册了 `/start` `/clear` `/compact` 三条,其余命令
19
+ 发过去什么都不发生(`filters.TEXT & ~filters.COMMAND` 把它们挡在门外),
20
+ 而管线的 `/effort` `/skill` `/btw` 那一族一条都没被叫到过。
21
+ 入站媒体每种都有去处(照片 / 语音 / 音频 / 视频 / 视频留言 / GIF /
22
+ 贴纸 / 文档)—— 分派在 `media.items_of`,下载一个异常都不许漏出去。
23
+ 出站媒体(`send_media_file`)—— `deliver_file` 因此在 Telegram 会话里
24
+ 也走直发,不再落到邮件兜底;取件排在回复之后(`core/delivery_outbox`)。
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import asyncio
30
+ import json
31
+ import os
32
+ from pathlib import Path
33
+ from typing import Any
34
+
35
+ from channels.base import (
36
+ Channel,
37
+ ChannelMetadata,
38
+ Message,
39
+ MessageSession,
40
+ MessageType,
41
+ )
42
+ from channels.converter import MessageConverter
43
+ from channels.message import MessageChain, Plain
44
+ from channels.telegram_channel import media as tg_media
45
+ from core import channel_turns
46
+
47
+ # ------------------------------------------------------------------
48
+ # Constants
49
+ # ------------------------------------------------------------------
50
+
51
+ TELEGRAM_MAX_MESSAGE_LENGTH = 4096
52
+ _TEMP_DIR = Path("data/workdata/telegram_files")
53
+
54
+ #: 分片前缀 `(i/N)` 的预算(最长 `(9999/9999)\n` = 12 字符)。
55
+ #: 不扣这 12 个字符的后果:第一片正好 4096 时 `前缀 + 正文` 超限,
56
+ #: Telegram 直接拒收 —— 整条回复发不出去,而日志里只有一行 400。
57
+ _CHUNK_PREFIX_BUDGET = 12
58
+
59
+ #: 轮询游标(`update_id + 1`)的落点 —— 运行时数据,进 `data/runtime/`。
60
+ _OFFSET_PATH = Path("data/runtime/telegram_offset.json")
61
+
62
+
63
+ # ------------------------------------------------------------------
64
+ # TelegramMessageConverter
65
+ # ------------------------------------------------------------------
66
+
67
+ class TelegramMessageConverter(MessageConverter):
68
+ """Translate between Telegram `Update` and `MessageChain`.
69
+
70
+ `to_internal` extracts text, caption, photo, and document from
71
+ a `telegram.Update` (the raw message from PTB).
72
+
73
+ `to_platform` converts a `MessageChain` back to a dict
74
+ representation that the channel's send methods understand.
75
+ """
76
+
77
+ # -- platform → internal -----------------------------------------
78
+
79
+ def to_internal(
80
+ self,
81
+ platform_message: Any,
82
+ media: list[tuple[dict, str]] | None = None,
83
+ ) -> MessageChain:
84
+ """Convert a `telegram.Update` into a MessageChain.
85
+
86
+ *media* 是已经下好的 `[(item, local_path)]`(`media.items_of` 的
87
+ 形状,路径由通道的 `_download_media` 填)—— 这里只负责排进链子。
88
+
89
+ 本方法不 import `telegram`:鸭子类型就够(字段用 `getattr` 取),
90
+ 所以没装 SDK 的测试也能跑;而"没装 SDK 就整条丢空"是旧写法的副作用。
91
+ """
92
+ tg_msg = getattr(platform_message, "message", None)
93
+ if tg_msg is None:
94
+ return MessageChain()
95
+
96
+ components: list = []
97
+ #: 文字 / 图注(媒体消息也常带 caption)—— 排在媒体之前,
98
+ #: 与钉钉 / 飞书那两条通道同一个顺序。
99
+ text = getattr(tg_msg, "text", None) or getattr(tg_msg, "caption", None) or ""
100
+ if text:
101
+ components.append(Plain(str(text)))
102
+ for item, local_path in (media or []):
103
+ comp = tg_media.component_of(item, local_path)
104
+ if comp is not None:
105
+ components.append(comp)
106
+ return MessageChain(components) if components else MessageChain()
107
+
108
+ # -- internal → platform -----------------------------------------
109
+
110
+ def to_platform(self, message_chain: MessageChain, **kwargs: Any) -> dict[str, Any]:
111
+ """Convert a MessageChain to a dict for Telegram send methods.
112
+
113
+ Returns a dict with keys like `text`, `photo_path`,
114
+ `doc_path`, `doc_name`.
115
+
116
+ 今天只有 `to_internal` 那条路在用(入站);出站走的是
117
+ `send_media_file`(本地文件直接交给 Bot API),不再经过这个 dict。
118
+ 留着它是 `MessageConverter` 的契约,别在别处按它写第二套。
119
+ """
120
+ result: dict[str, Any] = {"text": message_chain.content}
121
+
122
+ for img in message_chain.images:
123
+ result["photo_path"] = img.local_path
124
+ if img.mime_type:
125
+ result["photo_mime"] = img.mime_type
126
+ break # Only one photo per message (Telegram limitation)
127
+
128
+ for f in message_chain.files:
129
+ result["doc_path"] = f.local_path
130
+ result["doc_name"] = f.name
131
+ if f.mime_type:
132
+ result["doc_mime"] = f.mime_type
133
+ break # Only one doc per message
134
+
135
+ return result
136
+
137
+
138
+ # ------------------------------------------------------------------
139
+ # TelegramChannel
140
+ # ------------------------------------------------------------------
141
+
142
+ class TelegramChannel(Channel):
143
+ """Telegram Bot adapter — manual getUpdates loop, no PTB Updater."""
144
+
145
+ def __init__(
146
+ self,
147
+ config: dict | None = None,
148
+ scheduler=None,
149
+ session_pool=None,
150
+ ) -> None:
151
+ super().__init__(config)
152
+ self._converter = TelegramMessageConverter()
153
+ self._scheduler = scheduler
154
+ self._pool = session_pool
155
+ self._running = False
156
+ self._app = None
157
+ self._bot = None
158
+
159
+ tg_cfg = (config or {}).get("channel", {}).get("telegram", {})
160
+ # 配置条目账本是唯一写入方;读不到才回退到 config.yaml / 环境变量。
161
+ from core import channel_configs as _cc
162
+ self._bot_token = (_cc.credentials_for("telegram").get("bot_token")
163
+ or tg_cfg.get("bot_token")
164
+ or os.environ.get("TELEGRAM_BOT_TOKEN", ""))
165
+ #: 代理从一处口径取(`core/net_proxy` 的三档),而不是"读环境变量"。
166
+ #: 真取值发生在 `run()` 里(`_resolve_proxy()`)—— 这里只放一个初值,
167
+ #: 好让"构造完就能看到它是什么"这件事成立(自检 / 日志用)。
168
+ self._proxy_url = self._resolve_proxy()
169
+ self._polling_timeout = tg_cfg.get("polling_timeout", 30)
170
+
171
+ #: 机器人自己的身份(`run()` 拿到 `get_me` 之后填)—— 群聊唤醒门要用。
172
+ self._bot_username = ""
173
+ self._bot_id = None
174
+ #: 群聊里什么时候才回:`mention`(默认,@ / 回复机器人)· `any`(每条都回)。
175
+ #: 默认与 Telegram 自己的隐私模式一致;`any` 是给"把机器人当群助手"的人留的。
176
+ #: 读不到/写错,回默认(不是拒启:这是一个口味轴,不是能力轴)。
177
+ _gt = str(tg_cfg.get("group_trigger", "mention") or "mention").strip().lower()
178
+ self._group_trigger = _gt if _gt in ("mention", "any") else "mention"
179
+
180
+ _TEMP_DIR.mkdir(parents=True, exist_ok=True)
181
+
182
+ # ---- Channel ABC ----
183
+
184
+ def meta(self) -> ChannelMetadata:
185
+ return ChannelMetadata(
186
+ name="telegram_channel",
187
+ description="Telegram Bot adapter — multi-user messaging",
188
+ platform_type="telegram",
189
+ support_multimodal=True,
190
+ )
191
+
192
+ def _resolve_proxy(self) -> str:
193
+ """每次 `run()` 现取代理 —— 与微信一致(它在 `run()` 里建 client)。
194
+
195
+ 为什么不能只在 `__init__` 里取:
196
+ 通道实例是进程内长活的(`bus.registry` 里那一份),
197
+ `__init__` 只在应用启动时跑一次。若在那里定死,
198
+ 「先启动通道 → 之后才开代理」时,连"停止通道再启动"都换不过来
199
+ (拿到的还是同一个实例),只能重启整个应用 —— 而症状是
200
+ 界面绿框"运行中"、IM 里发消息没有任何回应(最贵的那种形状)。
201
+ 优先级:通道自己的 `proxy` 配置 > 全局三档;`direct` 档下**连通道级
202
+ 配置也让开**(那正是自救路)。
203
+ """
204
+ tg_cfg = (self.config or {}).get("channel", {}).get("telegram", {})
205
+ from core import net_proxy as _np
206
+ mode, url = _np.state()
207
+ if mode == "direct":
208
+ base = ""
209
+ elif mode == "manual":
210
+ base = url
211
+ else:
212
+ base = os.environ.get("HTTPS_PROXY", "")
213
+ return tg_cfg.get("proxy", "") or base
214
+
215
+ async def run(self) -> None:
216
+ self._proxy_url = self._resolve_proxy()
217
+ """Manual getUpdates loop — all inside our event loop."""
218
+ if not self._bot_token:
219
+ print("[telegram] ERROR: No bot token configured.")
220
+ return
221
+
222
+ # Proxy
223
+ #: 不再往 `os.environ` 里塞(那会污染同进程里所有其他出网方,
224
+ #: 包括模型 provider —— 一处配错全线遭殃)。改成只作用于这个 bot。
225
+ from telegram.ext import ApplicationBuilder
226
+ builder = ApplicationBuilder().token(self._bot_token)
227
+ if self._proxy_url:
228
+ from core.net_proxy import redact as _redact
229
+ print(f"[telegram] Using proxy: {_redact(self._proxy_url)}")
230
+ builder = builder.proxy(self._proxy_url).get_updates_proxy(self._proxy_url)
231
+ app = builder.build()
232
+
233
+ try:
234
+ await app.initialize()
235
+ await app.start()
236
+ except Exception as e:
237
+ _ename = type(e).__name__
238
+ print(f"[telegram] ERROR: Cannot start — {_ename}: {e}")
239
+ # 网络类失败要说改哪里,不是让用户去猜 token / 代理 / 网络三者中的哪一个。
240
+ # 真机上遇到过:系统代理开着、设置里是「直连」,于是直连超时;
241
+ # 而原来那句话只有 "Check your token, proxy, and network",用户得反过来
242
+ # 查注册表才知道是代理档位的问题。
243
+ if _ename in ("TimedOut", "NetworkError") or "timed out" in str(e).lower():
244
+ try:
245
+ from core import net_proxy as _np
246
+ _mode = _np.state()[0]
247
+ except Exception: # noqa: BLE001
248
+ _mode = "?"
249
+ _err = ("连接异常,请检查代理设置 —— 设置 → 安全 → 代理设置"
250
+ f"(当前档位:{_mode})")
251
+ _tpl = ("连接异常,请检查代理设置 —— 设置 → 安全 → 代理设置"
252
+ "(当前档位:{mode})")
253
+ _vars = {"mode": _mode}
254
+ else:
255
+ _err = f"{_ename}: {e}"
256
+ _tpl, _vars = "", {}
257
+ print("[telegram] Check your token, proxy, and network.")
258
+ print("[telegram] " + _err)
259
+ #: 让界面也看得见。原来只有终端那一行,而桌面壳里没有终端,
260
+ #: 通道卡只会回到「未运行」。走事故账本:它的明细行已经支持
261
+ #: 「模板 + 变量」,英文界面也翻得动。
262
+ try:
263
+ from core import incidents as _inc
264
+ _inc.note("telegram_channel", "channel", _err,
265
+ error_tpl=_tpl, error_vars=_vars,
266
+ detail=f"{_ename}: {e}")
267
+ except Exception: # noqa: BLE001
268
+ pass
269
+ return
270
+
271
+ self._app = app
272
+ self._bot = app.bot
273
+
274
+ # Verify connection
275
+ try:
276
+ me = await app.bot.get_me()
277
+ #: 机器人自己的身份 —— 群聊唤醒门要用(`media.addressed_to_bot`)。
278
+ self._bot_username = str(getattr(me, "username", "") or "")
279
+ self._bot_id = getattr(me, "id", None)
280
+ print(f"[telegram] Connected as @{me.username} (id={me.id})")
281
+ #: 成对的另一半:这次真的连上了,就撤掉上次那条事故。没有它,
282
+ #: 用户改好代理、通道起来了,横幅还挂着,那就是一条没人能撤的旧账。
283
+ try:
284
+ from core import incidents as _inc
285
+ _inc.resolve("telegram_channel", "channel")
286
+ except Exception: # noqa: BLE001
287
+ pass
288
+ except Exception as e:
289
+ print(f"[telegram] WARNING: get_me failed — {type(e).__name__}: {e}")
290
+
291
+ # ---- Register handlers on the application ----
292
+ from telegram.ext import MessageHandler, filters
293
+
294
+ channel = self # closure capture
295
+
296
+ #: 回调只做转发 —— 真逻辑在 `self._handle_update` / `self._reply_update`
297
+ #: (类方法才测得了:闭包只能在 `run()` 里活一次)。
298
+ #: 回答不在这里发了 —— `_handle_update` 只入队就返回,
299
+ #: 回答由 worker 线程回头调 `_reply_update`(本条的 `on_reply`)。
300
+ #: 旧写法是 `_reply_update(update, await _handle_update(update))`,
301
+ #: 而 `_handle_update` 里 `await execute` 整轮不回头,轮询循环
302
+ #: 连下一条 `get_updates` 都发不出去("IM 打不断"的真形状)。
303
+ async def _handler(update: Any, context: Any) -> None:
304
+ """文本 / 所有 `/` 命令 —— 都走同一条处理链。"""
305
+ await channel._handle_update(update)
306
+
307
+ async def _media_handler(update: Any, context: Any) -> None:
308
+ """照片 / 语音 / 音频 / 视频 / 视频留言 / GIF / 贴纸 / 文档。"""
309
+ if not update.message:
310
+ return
311
+ media = await channel._download_media(update.message)
312
+ await channel._handle_update(update, media=media)
313
+
314
+ # 一条命令都不许漏:`filters.COMMAND` 兜住所有 `/xxx`。
315
+ # 旧写法只注册了 `/start` `/clear` `/compact` 三条 ——
316
+ # `/effort` `/skill` `/btw` `/recap` `/language` 那一族发过去
317
+ # 什么都不发生(而它们全都在管线的 pre_process 里实现好了)。
318
+ app.add_handler(MessageHandler(
319
+ filters.TEXT & ~filters.COMMAND, _handler,
320
+ ))
321
+ app.add_handler(MessageHandler(filters.COMMAND, _handler))
322
+ app.add_handler(MessageHandler(
323
+ filters.PHOTO | filters.VOICE | filters.AUDIO | filters.VIDEO
324
+ | filters.VIDEO_NOTE | filters.ANIMATION | filters.Sticker.ALL
325
+ | filters.Document.ALL,
326
+ _media_handler,
327
+ ))
328
+
329
+ # ---- Main polling loop ----
330
+ print("[telegram] Bot is running (manual getUpdates loop).")
331
+ self._running = True
332
+ #: 游标从盘上接回来 —— 否则重启会把最近未确认的那批 update
333
+ #: 再处理一遍(去重缓存重启后是空的,拦不住)。
334
+ offset = _load_offset()
335
+ if offset:
336
+ print("[telegram] 从上次的游标接着收(update_id >= %d)" % offset)
337
+
338
+ while self._running:
339
+ retries = 0
340
+ try:
341
+ updates = await app.bot.get_updates(
342
+ offset=offset,
343
+ timeout=0,
344
+ allowed_updates=["message"],
345
+ )
346
+ retries = 0 # reset on success
347
+ await asyncio.sleep(0.8) # rate-limit
348
+ except Exception as e:
349
+ err_name = type(e).__name__
350
+ if "TimedOut" in err_name or "Timeout" in str(e):
351
+ await asyncio.sleep(1)
352
+ continue
353
+ retries += 1
354
+ wait = min(2 ** retries, 30)
355
+ print(f"[telegram] {err_name}, retry in {wait}s (attempt {retries})")
356
+ await asyncio.sleep(wait)
357
+ continue
358
+
359
+ moved = False
360
+ for update in updates:
361
+ offset = update.update_id + 1
362
+ moved = True
363
+ try:
364
+ await app.process_update(update)
365
+ except Exception as e:
366
+ print(f"[telegram] process_update error: "
367
+ f"{type(e).__name__}: {e}")
368
+ # 游标照推(这条算丢),但必须说出来
369
+ # (「丢,提醒用户『消息遗失,未接受』」)。
370
+ # 不推游标,一条坏消息会被无限重投,整条通道卡死;
371
+ # 推了却不说,用户看见的是"我发了,它没理我"。
372
+ await self._notify_lost(update)
373
+ #: 一批处理完才落盘(每条都写会把盘写穿);写失败它自己会出声。
374
+ if moved:
375
+ _save_offset(offset)
376
+
377
+ async def _notify_lost(self, update: Any) -> None:
378
+ """一条 update 没能处理成,在那个会话里明说「消息遗失,未接受」。
379
+
380
+ 不抛:这条路本来就是失败路径,再抛一次会连累同一批后面的
381
+ update(`process_update` 那层会继续下一轮)。
382
+ """
383
+ chat_id = None
384
+ try:
385
+ chat_id = getattr(getattr(update, "effective_chat", None), "id", None)
386
+ except Exception: # noqa: BLE001
387
+ chat_id = None
388
+ if chat_id is None or self._bot is None:
389
+ print("[telegram] 这条消息没处理成,且没有可用的会话回话 —— 只能记日志")
390
+ return
391
+ try:
392
+ await self._bot.send_message(
393
+ chat_id=chat_id,
394
+ text="⚠️ 消息遗失,未接收,需要时请重新发送。")
395
+ except Exception as e: # noqa: BLE001
396
+ print(f"[telegram] 「消息遗失」提醒没发出去:"
397
+ f"{type(e).__name__}: {e}")
398
+
399
+ async def terminate(self) -> None:
400
+ self._running = False
401
+ if self._app:
402
+ try:
403
+ await self._app.stop()
404
+ await self._app.shutdown()
405
+ except Exception:
406
+ pass
407
+ print("[telegram] Bot stopped.")
408
+
409
+ # ------------------------------------------------------------------
410
+ # 入站:一条 update → 管线 → 回答
411
+ # ------------------------------------------------------------------
412
+
413
+ async def _handle_update(self, update: Any,
414
+ media: list[tuple[dict, str]] | None = None
415
+ ) -> str | None:
416
+ """Core processing: convert update → pipeline → response.
417
+
418
+ *media* 是已经下好的 `[(item, path)]`(媒体那条路先下载再进来)。
419
+ Returns the response text (or None on empty / error).
420
+ """
421
+ if not getattr(update, "message", None) or not getattr(update, "effective_user", None):
422
+ return None
423
+
424
+ user = update.effective_user
425
+
426
+ chain = self._converter.to_internal(update, media=media)
427
+
428
+ # Skip completely empty chains (silent messages)
429
+ if chain.is_empty:
430
+ return None
431
+
432
+ session = self._make_session(update)
433
+
434
+ # 群聊唤醒门:群里默认只回「@ 我」与「回复我」。
435
+ # 判据见 `media.addressed_to_bot`(实体 / 回复 / 文本兜底三种信号)。
436
+ # 机器人身份一个都拿不到时(`get_me` 失败)放行 ——
437
+ # 判不出来就别拦:漏回一条比误吞一条更糟。
438
+ if (session.message_type is MessageType.GROUP
439
+ and self._group_trigger != "any"
440
+ and (self._bot_username or self._bot_id is not None)
441
+ and not tg_media.addressed_to_bot(
442
+ getattr(update, "message", None),
443
+ self._bot_username, self._bot_id)):
444
+ print("[telegram] 群里这条不是在跟我说话,跳过(chat=%s)"
445
+ % session.session_id)
446
+ return None
447
+
448
+ log_text = chain.content[:80] if chain.content else "[media]"
449
+ print(f"[telegram] msg from {user.full_name or user.username}: {log_text}")
450
+
451
+ message = Message(
452
+ sender_id=str(user.id),
453
+ sender_name=user.full_name or user.username or "",
454
+ message_chain=chain,
455
+ message_type=session.message_type,
456
+ session=session,
457
+ #: 平台消息号 —— 管线用它做去重(`pre_process` 那道闸读的
458
+ #: 就是 `ctx.metadata["message_id"]`)。不传 = 那道闸恒不触发。
459
+ message_id=str(getattr(update.message, "message_id", "") or ""),
460
+ )
461
+ event = self.commit_event(message)
462
+
463
+ # Typing indicator
464
+ try:
465
+ await update.message.chat.send_action("typing")
466
+ except Exception: # noqa: BLE001
467
+ pass
468
+
469
+ if not self._scheduler:
470
+ return None
471
+
472
+ #: 只入队,立刻返回。回答由 worker 线程投回**本通道的
473
+ #: loop** 上发(`on_reply`)—— 客户端绑在这个 loop 上,别新造循环。
474
+ #: 异常那句人话也由 `core/channel_turns` 统一发(同一个 worker 线程)。
475
+ async def _on_reply(text: str) -> None:
476
+ await self._reply_update(update, text)
477
+
478
+ await channel_turns.intake(self, event, on_reply=_on_reply)
479
+ return None
480
+
481
+ async def _reply_update(self, update: Any, response: str | None) -> None:
482
+ """发回答,然后把本轮登记的文件发出去。
483
+
484
+ 顺序是判据(`core/delivery_outbox`):用户先看到那句话,再收到附件;
485
+ 取件只取自己这一轮的(三格全对)。
486
+ """
487
+ # 取件放在 `finally` 里:发送这一段抛了(429 / 网络 / 实体错),
488
+ # 文件也照样要发 —— 否则"模型说要交付"与"用户收到"是两件事。
489
+ try:
490
+ if response and getattr(update, "message", None):
491
+ await self._send_long(update.message, response)
492
+ finally:
493
+ try:
494
+ await self._drain_delivered(self._make_session(update))
495
+ except Exception as e: # noqa: BLE001
496
+ print(f"[telegram] 发待交付文件时出错({type(e).__name__}: {e})")
497
+
498
+ async def send(self, session: MessageSession, content: str | MessageChain) -> bool:
499
+ """没有 Bot 就是没送达 —— 以前这一支什么都不做、也不出声。
500
+
501
+ 异常照旧往上抛(`Runner` 那条 `except` 会把它记成失败);
502
+ 这里只把"静默什么都不做"那一支改成一个明确的 `False`。
503
+
504
+ 发完之后顺手把本轮登记的文件取走发掉 —— 定时任务 / 后台回报
505
+ 这条路上,那是文件唯一的出口(同微信 / 飞书 / 钉钉)。
506
+ """
507
+ if not self._bot:
508
+ print(f"[telegram] 没有 Bot 实例,这条没有送达:{session.session_id}")
509
+ return False
510
+ chat_id = _chat_id_of(session)
511
+ if chat_id is None:
512
+ print(f"[telegram] 会话 id 不是数字,发不出去:{session.session_id!r}")
513
+ return False
514
+ text = content if isinstance(content, str) else content.content
515
+ delivered = False
516
+ if str(text or "").strip():
517
+ await self._send_long_via_bot(chat_id, str(text))
518
+ delivered = True
519
+ files = await self._drain_delivered(session)
520
+ return delivered or files > 0
521
+
522
+ async def send_note(self, session: MessageSession, text: str,
523
+ event=None) -> bool:
524
+ """一行旁白("已收到" / "已中断")—— 不捎带本轮待发文件。
525
+
526
+ 为什么不直接用 `send()`:它会取走 `core/delivery_outbox` 里
527
+ 本轮待交付的文件,一轮还在跑的时候附件就被提前发出去了
528
+ (用户先看到文件、再看到回答)。判据见 `channels/base.py::send_note`。
529
+ """
530
+ if not self._bot:
531
+ print(f"[telegram] 没有 Bot 实例,这句旁白没送达:{session.session_id}")
532
+ return False
533
+ chat_id = _chat_id_of(session)
534
+ if chat_id is None or not str(text or "").strip():
535
+ return False
536
+ await self._send_long_via_bot(chat_id, str(text))
537
+ return True
538
+
539
+ async def test_connection(self) -> dict:
540
+ """连通性自检(通道页 / 引导页用)。
541
+
542
+ 判据:配置在 + SDK 在就算"可接入";
543
+ 真连一次网络是 `run()` 的事(这里不替用户打请求)。
544
+ """
545
+ if not self._bot_token:
546
+ return {"ok": False, "message": "Telegram bot_token 没配置"}
547
+ try:
548
+ import telegram # noqa: F401
549
+ except ImportError:
550
+ return {"ok": False, "message": "python-telegram-bot 没装"}
551
+ if self._bot is not None:
552
+ try:
553
+ me = await self._bot.get_me()
554
+ return {"ok": True, "message": "Connected as @%s" % me.username}
555
+ except Exception as exc: # noqa: BLE001
556
+ return {"ok": False, "message": "%s: %s"
557
+ % (type(exc).__name__, exc)}
558
+ return {"ok": True, "message": "Telegram SDK available"}
559
+
560
+ # ------------------------------------------------------------------
561
+ # 出站媒体(`MediaSendCapable`)
562
+ # ------------------------------------------------------------------
563
+
564
+ async def send_media_file(self, session: MessageSession, file_path: str,
565
+ filename: str = "",
566
+ context_token: str = "") -> bool:
567
+ """发一个本地图片/文件。真交出去才回 `True`(的回执契约)。
568
+
569
+ *context_token* 是微信那条协议的概念,Telegram 不用它 —— 保留形参
570
+ 是为了与能力协议(`channels/capabilities.py::MediaSendCapable`)同一个
571
+ 签名,`deliver_file` 那侧按属性存在认通道。
572
+ """
573
+ if not self._bot:
574
+ print("[telegram] 没有 Bot 实例,附件发不出去")
575
+ return False
576
+ p = Path(str(file_path or ""))
577
+ if not p.is_file():
578
+ print("[telegram] 要发的文件不存在:%s" % (file_path or "(空)"))
579
+ return False
580
+ chat_id = _chat_id_of(session)
581
+ if chat_id is None:
582
+ print(f"[telegram] 会话 id 不是数字,附件发不出去:{session.session_id!r}")
583
+ return False
584
+ name = filename or p.name
585
+ kind = tg_media.outbound_kind(name)
586
+ try:
587
+ from telegram import InputFile
588
+ with open(p, "rb") as fh:
589
+ upload = InputFile(fh, filename=name)
590
+ if kind == "photo":
591
+ await self._call_with_retry(
592
+ self._bot.send_photo, chat_id=chat_id, photo=upload)
593
+ else:
594
+ await self._call_with_retry(
595
+ self._bot.send_document, chat_id=chat_id,
596
+ document=upload)
597
+ except Exception as exc: # noqa: BLE001
598
+ print(f"[telegram] 附件发送失败({type(exc).__name__}: {exc})")
599
+ return False
600
+ print("[telegram] 附件已发送:%s(%s)" % (name, kind))
601
+ return True
602
+
603
+ async def _drain_delivered(self, session: MessageSession) -> int:
604
+ """把本轮 `deliver_file` 登记的文件发出去,返回真发出去的条数。
605
+
606
+ 判据见 `core/delivery_outbox`:工具是同步的、不能 await 这个循环,
607
+ 所以它只登记;通道在发完回复之后取走发掉,失败时回一句话给用户。
608
+ 三格都要对上:`session_key + channel + user_id`。
609
+ """
610
+ from core import delivery_outbox as _outbox
611
+ from core.session_key import session_key_for
612
+
613
+ try:
614
+ recs = _outbox.take_for(
615
+ session_key=session_key_for(session),
616
+ channel="telegram_channel",
617
+ user_id=str(getattr(session, "session_id", "") or ""))
618
+ except Exception as exc: # noqa: BLE001
619
+ print(f"[telegram] 取待发文件失败({type(exc).__name__}: {exc})")
620
+ return 0
621
+ sent = 0
622
+ for rec in recs:
623
+ if await self.send_media_file(session, rec.get("path", ""),
624
+ rec.get("name", "")):
625
+ sent += 1
626
+ continue
627
+ chat_id = _chat_id_of(session)
628
+ if chat_id is None:
629
+ continue
630
+ try:
631
+ await self._bot.send_message(
632
+ chat_id=chat_id,
633
+ text="文件 %s 没能发出去(原因在框架日志里)。"
634
+ % (rec.get("name") or "?"))
635
+ except Exception: # noqa: BLE001
636
+ pass
637
+ return sent
638
+
639
+ # ------------------------------------------------------------------
640
+ # 入站媒体
641
+ # ------------------------------------------------------------------
642
+
643
+ async def _download_media(self, tg_msg: Any) -> list[tuple[dict, str]]:
644
+ """把这条消息的媒体下到本地,返回 `[(item, 本地路径)]`。
645
+
646
+ 一个异常都不许漏出去:漏出去整条消息连管线都进不去,
647
+ 用户看到的是"这条消息不存在"(飞书那次的真现场)。取不到就
648
+ 跳过这一件,其余照常 —— 并且说出来。
649
+ 20 MB 是 Bot API `getFile` 的硬上限,超了连下载地址都拿不到
650
+ 提前判,别把它报成"下载失败"。
651
+ """
652
+ out: list[tuple[dict, str]] = []
653
+ for item in tg_media.items_of(tg_msg):
654
+ file_id = str(item.get("file_id") or "")
655
+ if not file_id:
656
+ print("[telegram] 媒体没有 file_id,跳过(kind=%s)" % item.get("kind"))
657
+ continue
658
+ size = int(item.get("size") or 0)
659
+ if size > tg_media.MAX_DOWNLOAD_BYTES:
660
+ print("[telegram] 附件太大(%d 字节 > %d),没有下载:%s"
661
+ % (size, tg_media.MAX_DOWNLOAD_BYTES, item.get("name")))
662
+ continue
663
+ try:
664
+ tg_file = await self._bot.get_file(file_id)
665
+ path = _TEMP_DIR / ("%s_%s%s" % (
666
+ item.get("kind") or "file", file_id[-12:],
667
+ tg_media.ext_of(item)))
668
+ await tg_file.download_to_drive(path)
669
+ out.append((item, str(path)))
670
+ print("[telegram] 附件已落盘:%s(%s,%d 字节)"
671
+ % (path.name, item.get("kind"), size))
672
+ except Exception as exc: # noqa: BLE001
673
+ print(f"[telegram] 取附件失败({type(exc).__name__}: {exc})")
674
+ return out
675
+
676
+ # ------------------------------------------------------------------
677
+ # Internal
678
+ # ------------------------------------------------------------------
679
+
680
+ def _make_session(self, update: Any) -> MessageSession:
681
+ from telegram.constants import ChatType
682
+ chat = update.effective_chat
683
+ if chat.type == ChatType.PRIVATE:
684
+ return MessageSession("telegram", MessageType.PRIVATE, str(chat.id))
685
+ return MessageSession("telegram", MessageType.GROUP, str(chat.id))
686
+
687
+ async def _call_with_retry(self, fn, *args, **kwargs):
688
+ """调一次 Bot API;撞上 429 就等它说的秒数,重试一次。
689
+
690
+ `RetryAfter` 必须处理:Telegram 的 per-chat 限速是真实存在的 ——
691
+ 一段长回复切成十几片时就会撞上。不处理的话症状是"最后几片没了",
692
+ 而日志里只有一行 429。
693
+ """
694
+ try:
695
+ return await fn(*args, **kwargs)
696
+ except Exception as exc: # noqa: BLE001
697
+ wait = _retry_after_of(exc)
698
+ if wait is None:
699
+ raise
700
+ print("[telegram] 被限流,%.0f 秒后重试一次" % wait)
701
+ await asyncio.sleep(wait)
702
+ return await fn(*args, **kwargs)
703
+
704
+ async def _send_long(self, message: Any, content: str) -> None:
705
+ """Send, splitting long messages(前缀也算进 4096 的预算)。"""
706
+ for prefix, chunk in _split_for_telegram(content):
707
+ await self._call_with_retry(message.reply_text, prefix + chunk)
708
+
709
+ async def _send_long_via_bot(self, chat_id: int, content: str) -> None:
710
+ """Send via bot (for proactive messages)."""
711
+ for prefix, chunk in _split_for_telegram(content):
712
+ await self._call_with_retry(
713
+ self._bot.send_message, chat_id=chat_id, text=prefix + chunk)
714
+
715
+
716
+ # ------------------------------------------------------------------
717
+ # Helpers
718
+ # ------------------------------------------------------------------
719
+
720
+ def _load_offset(path: Path | None = None) -> int:
721
+ """读回上次的 `update_id + 1`。读不到 / 坏文件,`0`(出声,不静默)。
722
+
723
+ 为什么它非有不可:`getUpdates` 的 offset 只活在进程里。重启后从 0 开始,
724
+ Telegram 会把最近未确认的那批 update 再发一遍(最多 24 小时),
725
+ 而去重缓存(5 分钟 TTL)重启后是空的,用户会收到重复的回复。
726
+ """
727
+ p = Path(path) if path is not None else _OFFSET_PATH
728
+ try:
729
+ data = json.loads(p.read_text(encoding="utf-8"))
730
+ except FileNotFoundError:
731
+ return 0
732
+ except Exception as exc: # noqa: BLE001
733
+ print("[telegram] 游标读不出来,从 0 开始(可能重放积压):%s: %s"
734
+ % (type(exc).__name__, exc))
735
+ return 0
736
+ try:
737
+ return max(0, int((data or {}).get("offset") or 0))
738
+ except (TypeError, ValueError, AttributeError):
739
+ return 0
740
+
741
+
742
+ def _save_offset(value: int, path: Path | None = None) -> None:
743
+ """把游标写回(先写临时文件再 `replace`,半个文件不会留在那儿)。"""
744
+ p = Path(path) if path is not None else _OFFSET_PATH
745
+ try:
746
+ p.parent.mkdir(parents=True, exist_ok=True)
747
+ tmp = p.with_suffix(p.suffix + ".tmp")
748
+ tmp.write_text(json.dumps({"offset": int(value)}), encoding="utf-8")
749
+ tmp.replace(p)
750
+ except Exception as exc: # noqa: BLE001
751
+ # 写不进去也要出声:否则下次重启静默重放
752
+ print("[telegram] 游标写不进去(重启会重放积压):%s: %s"
753
+ % (type(exc).__name__, exc))
754
+
755
+
756
+ def _retry_after_of(exc: BaseException) -> float | None:
757
+ """异常里的 `retry_after` 秒数;不是限流就 `None`。
758
+
759
+ 按属性认,不 import `telegram.error` —— 没装 SDK 也能测。
760
+ PTB 各版本给的是 `int` 或 `timedelta`,两种都认。
761
+ """
762
+ value = getattr(exc, "retry_after", None)
763
+ if value is None:
764
+ return None
765
+ try:
766
+ secs = value.total_seconds() if hasattr(value, "total_seconds") else value
767
+ return max(0.0, float(secs))
768
+ except (TypeError, ValueError):
769
+ return None
770
+
771
+
772
+ def _split_for_telegram(text: str) -> list[tuple[str, str]]:
773
+ """切成 `(前缀, 正文)`,两段加起来 ≤ 4096。
774
+
775
+ 旧写法先按 4096 切、再加 `(i/N)` 前缀,第一片正好 4096 时超限,
776
+ Telegram 拒收,整条回复发不出去(日志只有一行 400)。
777
+ """
778
+ s = str(text or "")
779
+ if len(s) <= TELEGRAM_MAX_MESSAGE_LENGTH:
780
+ return [("", s)]
781
+ chunks = _split_text(s, TELEGRAM_MAX_MESSAGE_LENGTH - _CHUNK_PREFIX_BUDGET)
782
+ n = len(chunks)
783
+ if n <= 1:
784
+ return [("", chunks[0] if chunks else s)]
785
+ return [("(%d/%d)\n" % (i + 1, n), c) for i, c in enumerate(chunks)]
786
+
787
+
788
+ def _chat_id_of(session: MessageSession) -> int | None:
789
+ """会话 id → Telegram 的 chat id。不猜:不是整数就回 `None`。
790
+
791
+ 回 `None` 而不是抛:调用方(`send` / `send_media_file`)要把它变成
792
+ 一个明确的 `False`(没送达要说得出来),而不是炸到调度器里。
793
+ """
794
+ try:
795
+ return int(str(getattr(session, "session_id", "")))
796
+ except (TypeError, ValueError):
797
+ return None
798
+
799
+
800
+ def _split_text(text: str, max_len: int) -> list[str]:
801
+ if len(text) <= max_len:
802
+ return [text]
803
+ chunks: list[str] = []
804
+ remaining = text
805
+ while len(remaining) > max_len:
806
+ split_at = remaining.rfind("\n", 0, max_len)
807
+ if split_at == -1 or split_at < max_len // 2:
808
+ split_at = max_len
809
+ chunks.append(remaining[:split_at])
810
+ remaining = remaining[split_at:].lstrip("\n")
811
+ if remaining:
812
+ chunks.append(remaining)
813
+ return chunks