@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.
- package/LICENSE +201 -201
- package/NOTICE +45 -45
- package/THIRD-PARTY-FRONTEND.md +5266 -5266
- package/THIRD-PARTY-PYTHON.md +162 -153
- package/THIRD-PARTY.md +316 -316
- package/apps/desktop/quotes.txt +56 -56
- package/bus/core.py +671 -671
- package/bus/loaders/channel_loader.py +64 -64
- package/bus/loaders/skill_md.py +676 -676
- package/bus/skill_state.py +124 -124
- package/channels/cli_channel/manifest.yaml +5 -5
- package/channels/dingtalk_channel/manifest.yaml +12 -12
- package/channels/feishu_channel/manifest.yaml +12 -12
- package/channels/qq_bot_channel/__init__.py +1 -1
- package/channels/qq_bot_channel/handler.py +881 -881
- package/channels/qq_bot_channel/manifest.yaml +4 -4
- package/channels/telegram_channel/__init__.py +1 -1
- package/channels/telegram_channel/handler.py +813 -813
- package/channels/telegram_channel/manifest.yaml +4 -4
- package/channels/telegram_channel/media.py +231 -231
- package/channels/textfmt.py +58 -58
- package/channels/wechat_channel/__init__.py +1 -1
- package/channels/wechat_channel/auth.py +23 -5
- package/channels/wechat_channel/manifest.yaml +5 -5
- package/channels/wechat_channel/media.py +178 -178
- package/config.yaml +2 -2
- package/core/activity.py +3 -0
- package/core/agent_loop.py +390 -55
- package/core/approval.py +17 -6
- package/core/artifacts.py +7 -0
- package/core/auto_review.py +23 -5
- package/core/channel_configs.py +34 -2
- package/core/channel_turns.py +759 -759
- package/core/child_approval.py +150 -0
- package/core/config_requirements.py +205 -0
- package/core/cron/runner.py +118 -6
- package/core/cron/store.py +14 -5
- package/core/cron/tools.py +17 -5
- package/core/endpoint.py +141 -0
- package/core/events.py +23 -0
- package/core/i18n.py +329 -329
- package/core/ice/store.py +191 -191
- package/core/inbound.py +193 -193
- package/core/jobs.py +19 -3
- package/core/last_good.py +150 -150
- package/core/llm_errors.py +227 -227
- package/core/llm_retry.py +230 -230
- package/core/memory/compressor.py +1214 -1214
- package/core/memory/manager.py +14 -0
- package/core/model_configs.py +80 -0
- package/core/pipeline/scheduler.py +2 -2
- package/core/pipeline/stages/agent_loop.py +24 -4
- package/core/pipeline/stages/pre_process.py +58 -7
- package/core/prompt_assembler.py +680 -680
- package/core/rg.py +255 -255
- package/core/security.py +1544 -1544
- package/core/settings_baseline.py +70 -1
- package/core/shell.py +5 -17
- package/core/skill_settings.py +7 -2
- package/core/state_registry.py +19 -0
- package/core/subagent.py +64 -3
- package/core/task_tool.py +1 -1
- package/core/tasks_notify.py +69 -4
- package/core/tiers.py +9 -3
- package/core/tool_outcome.py +108 -0
- package/core/update_tui.py +158 -0
- package/core/version.py +2 -2
- package/core/web_cache.py +152 -0
- package/crannia_tray.py +278 -278
- package/creators/models.json +4 -4
- package/data/settings.example.json +67 -0
- package/licenses/GPL-3.0.txt +619 -619
- package/licenses/LGPL-2.1.txt +502 -502
- package/licenses/LGPL-3.0.txt +165 -165
- package/licenses/MIT-chat-on-wechat.txt +18 -18
- package/licenses/MIT-deepseek-harness.txt +21 -21
- package/licenses/Molio-LICENSE.txt +44 -44
- package/locales/en.json +9 -4
- package/main.py +154 -154
- package/mcpx/manager.py +522 -522
- package/mcpx/servers/__init__.py +22 -22
- package/mcpx/servers/web_search.py +321 -33
- package/package.json +14 -9
- package/providers/anthropic/client.py +772 -772
- package/providers/cost_table.json +3779 -3779
- package/providers/deepseek/client.py +20 -20
- package/providers/deepseek/manifest.yaml +2 -2
- package/providers/factory.py +136 -136
- package/providers/lmstudio/client.py +2 -2
- package/providers/metadata.py +80 -80
- package/providers/model_capabilities.json +6665 -6665
- package/providers/moonshot/client.py +12 -12
- package/providers/ollama/client.py +2 -2
- package/providers/openai/client.py +13 -13
- package/providers/openrouter/client.py +2 -2
- package/providers/qwen/__init__.py +1 -1
- package/providers/qwen/client.py +2 -2
- package/providers/qwen/manifest.yaml +16 -16
- package/providers/rate_limiter.py +144 -144
- package/providers/siliconflow/client.py +2 -2
- package/providers/validation.py +171 -171
- package/providers/window_table.json +8909 -8909
- package/sbom.json +4413 -4296
- package/skills/entertainment/SKILL.md +35 -35
- package/skills/entertainment/__init__.py +1 -1
- package/skills/entertainment/handler.py +91 -91
- package/skills/entertainment/manifest.yaml +26 -26
- package/skills/file_parser/GUIDANCE.md +10 -10
- package/skills/file_parser/handler.py +177 -4
- package/skills/file_parser/manifest.yaml +22 -1
- package/skills/github/SKILL.md +32 -32
- package/skills/github/__init__.py +1 -1
- package/skills/github/manifest.yaml +5 -0
- package/skills/mail_parser/SKILL.md +68 -68
- package/skills/mail_parser/__init__.py +1 -1
- package/skills/mail_parser/handler.py +806 -806
- package/skills/mail_parser/manifest.yaml +5 -0
- package/skills/media_gen/GUIDANCE.md +19 -19
- package/skills/media_gen/SKILL.md +43 -43
- package/skills/media_gen/__init__.py +1 -1
- package/skills/media_gen/handler.py +430 -430
- package/skills/media_gen/manifest.yaml +93 -88
- package/skills/office_parser/cell_validation.py +127 -127
- package/skills/office_parser/excel_transform.py +936 -936
- package/skills/office_parser/layout_spec.py +243 -243
- package/skills/office_parser/pptx_export/console_encoding.py +27 -27
- package/skills/office_parser/pptx_export/resource_paths.py +88 -88
- package/skills/office_parser/pptx_export/svg_finalize/__init__.py +12 -12
- package/skills/office_parser/pptx_export/svg_finalize/align_embed_images.py +575 -575
- package/skills/office_parser/pptx_export/svg_finalize/crop_images.py +366 -366
- package/skills/office_parser/pptx_export/svg_finalize/embed_icons.py +498 -498
- package/skills/office_parser/pptx_export/svg_finalize/embed_images.py +288 -288
- package/skills/office_parser/pptx_export/svg_finalize/fix_image_aspect.py +388 -388
- package/skills/office_parser/pptx_export/svg_finalize/flatten_tspan.py +818 -818
- package/skills/office_parser/pptx_export/svg_finalize/svg_rect_to_path.py +345 -345
- package/skills/office_parser/pptx_export/svg_to_pptx/__init__.py +14 -14
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/__init__.py +1 -1
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/context.py +186 -186
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/converter.py +781 -781
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/elements.py +2490 -2490
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/paths.py +429 -429
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/styles.py +656 -656
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/__init__.py +1 -1
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/builder.py +1267 -1267
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/dimensions.py +155 -155
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/discovery.py +101 -101
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/media.py +141 -141
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/narration.py +236 -236
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/notes.py +257 -257
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/slide_xml.py +136 -136
- package/skills/office_parser/pptx_export/svg_to_pptx/tspan_flattener.py +44 -44
- package/skills/office_parser/pptx_export/svg_to_pptx/use_expander.py +129 -129
- package/skills/office_parser/references/LICENSE-Office-Word-MCP-Server.txt +20 -20
- package/skills/office_parser/references/LICENSE-excel-mcp-server.txt +21 -21
- package/skills/office_parser/references/layout_library.md +816 -816
- package/skills/office_parser/references/ppt-master/LICENSE +21 -21
- package/skills/office_parser/references/ppt-master/references/executor-base.md +474 -474
- package/skills/office_parser/references/ppt-master/references/shared-standards.md +1002 -1002
- package/skills/office_parser/references/ppt-master/references/strategist.md +880 -880
- package/skills/office_parser/references/ppt-master/references/template-designer.md +402 -402
- package/skills/office_parser/references/ppt-master/references/visual-review.md +240 -240
- package/skills/office_parser/references/ppt-master/references/visual-styles/_index.md +106 -106
- package/skills/office_parser/references/ppt-master/references/visual-styles/blueprint.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/brutalist.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/chalkboard.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/dark-tech.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/data-journalism.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/editorial.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/glassmorphism.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/ink-notes.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/ink-wash.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/memphis.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/paper-cut.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/photo-editorial.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/pixel-art.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/sketch-notes.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/soft-rounded.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/swiss-minimal.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/vintage-poster.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/zine.md +37 -37
- package/skills/office_parser/references/spec_lock.md +235 -235
- package/skills/office_parser/soffice.py +68 -68
- package/skills/office_parser/word_tools.py +2909 -2909
- package/tui/crannia.cmd +134 -0
- package/tui/crannia_tui/__init__.py +1 -0
- package/tui/crannia_tui/__main__.py +223 -0
- package/tui/crannia_tui/app.py +1318 -0
- package/tui/crannia_tui/app.tcss +153 -0
- package/tui/crannia_tui/approval.py +85 -0
- package/tui/crannia_tui/backend.py +279 -0
- package/tui/crannia_tui/channel.py +472 -0
- package/tui/crannia_tui/client.py +125 -0
- package/tui/crannia_tui/clipboard.py +62 -0
- package/tui/crannia_tui/commands.py +65 -0
- package/tui/crannia_tui/doctor.py +304 -0
- package/tui/crannia_tui/events.py +84 -0
- package/tui/crannia_tui/headless.py +152 -0
- package/tui/crannia_tui/i18n.py +164 -0
- package/tui/crannia_tui/locales/en.json +263 -0
- package/tui/crannia_tui/outcome.py +62 -0
- package/tui/crannia_tui/paths.py +181 -0
- package/tui/crannia_tui/probe.py +53 -0
- package/tui/crannia_tui/profile.py +169 -0
- package/tui/crannia_tui/render.py +209 -0
- package/tui/crannia_tui/settings.py +134 -0
- package/tui/crannia_tui/setup.py +380 -0
- package/tui/crannia_tui/term.py +116 -0
- package/tui/crannia_tui/ui.py +1236 -0
- package/tui/crannia_tui/update.py +389 -0
- package/vendor/ripgrep/COPYING.txt +3 -3
- package/vendor/ripgrep/LICENSE-MIT.txt +21 -21
- package/vendor/ripgrep/NOTICE-vscode-ripgrep.txt +13 -13
- package/vendor/ripgrep/README.md +51 -51
- package/vendor/ripgrep/UNLICENSE.txt +24 -24
- package/vendor/ripgrep/package-source.json +19 -19
- package/web/__main__.py +15 -0
- package/web/server.py +168 -19
- package/web/static/img/channel-telegram.svg +1 -1
- package/web/static/img/channel-wechat.svg +1 -1
- package/web/templates/logs.html +49 -49
- package/web/templates/models.html +46 -46
|
@@ -1,881 +1,881 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
"""QQ 机器人通道 —— 官方 Bot API v2。
|
|
3
|
-
|
|
4
|
-
收发都走官方接口,不需要协议端(不用另跑一个小号来转)。
|
|
5
|
-
|
|
6
|
-
收:取网关地址,连 WebSocket,认证后靠心跳保活,事件由 op 0 派发。
|
|
7
|
-
发:私聊 POST /v2/users/<openid>/messages,
|
|
8
|
-
群聊换 /v2/groups/<group_openid>/messages。
|
|
9
|
-
|
|
10
|
-
被动回复有两条限制:同一条消息最多回四次;群聊窗口五分钟、私聊三十分钟。
|
|
11
|
-
超出就退回主动消息(不带 msg_id)。这两个数只有 `_ReplyBudget` 一处口径,
|
|
12
|
-
别在调用点再写一遍:写两处就会一处改了一处没改,症状是「偶尔这条回不出去」。
|
|
13
|
-
|
|
14
|
-
凭据(appId / appSecret)读 `data/qq_bot_credentials.json`,与微信那一份同形状。
|
|
15
|
-
那份文件在 `DEFAULT_FORBIDDEN_PATHS` 里 —— 模型能读到自己就写的那份 json,
|
|
16
|
-
等于把机器人交出去了。
|
|
17
|
-
|
|
18
|
-
群消息走的是 `GROUP_AT_MESSAGE_CREATE`,即平台只推「@ 我」的那些。
|
|
19
|
-
「不 @ 也能收」取决于平台侧的开关,代码这一层没有可判的输入。
|
|
20
|
-
"""
|
|
21
|
-
|
|
22
|
-
from __future__ import annotations
|
|
23
|
-
|
|
24
|
-
import asyncio
|
|
25
|
-
import json
|
|
26
|
-
import os
|
|
27
|
-
import time
|
|
28
|
-
from pathlib import Path
|
|
29
|
-
from typing import Any
|
|
30
|
-
|
|
31
|
-
from channels.base import (
|
|
32
|
-
Channel,
|
|
33
|
-
ChannelMetadata,
|
|
34
|
-
Message,
|
|
35
|
-
MessageSession,
|
|
36
|
-
MessageType,
|
|
37
|
-
)
|
|
38
|
-
from channels.converter import MessageConverter
|
|
39
|
-
from channels.message import File, Image, MessageChain, Plain, Voice
|
|
40
|
-
from core import channel_turns
|
|
41
|
-
|
|
42
|
-
# 官方地址。沙箱换 `https://sandbox.api.sgroup.qq.com`(配置 `base_url` 可覆盖)。
|
|
43
|
-
DEFAULT_API_BASE = "https://api.sgroup.qq.com"
|
|
44
|
-
DEFAULT_TOKEN_URL = "https://bots.qq.com/app/getAppAccessToken"
|
|
45
|
-
|
|
46
|
-
#: 群与私聊消息事件那一位(C2C_MESSAGE_CREATE / GROUP_AT_MESSAGE_CREATE)。
|
|
47
|
-
#: 只订这一位:频道消息是另一套形状,本通道不处理。
|
|
48
|
-
INTENT_GROUP_AND_C2C = 1 << 25
|
|
49
|
-
|
|
50
|
-
#: 单条消息的字符上限。超了要切,切的时候留出 "(i/N)" 前缀的位置。
|
|
51
|
-
MAX_MESSAGE_LENGTH = 5000
|
|
52
|
-
_CHUNK_PREFIX_BUDGET = 12
|
|
53
|
-
|
|
54
|
-
#: 被动回复的次数上限与窗口(秒)。
|
|
55
|
-
PASSIVE_LIMIT = 4
|
|
56
|
-
PASSIVE_TTL = {"c2c": 1800, "group": 300}
|
|
57
|
-
|
|
58
|
-
#: 事件去重的保留时长(秒)。重连后平台会重放没确认的事件。
|
|
59
|
-
_DEDUP_TTL = 600.0
|
|
60
|
-
_DEDUP_MAX = 4000
|
|
61
|
-
|
|
62
|
-
_CRED_PATH = Path("data/qq_bot_credentials.json")
|
|
63
|
-
_TEMP_DIR = Path("data/workdata/qqbot_files")
|
|
64
|
-
|
|
65
|
-
#: 下载入站媒体的上限。超过就只在正文里说一句,不落盘。
|
|
66
|
-
_MAX_DOWNLOAD_BYTES = 30 * 1024 * 1024
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
def _load_credentials() -> dict:
|
|
70
|
-
"""这条通道当前的凭据。
|
|
71
|
-
|
|
72
|
-
先问配置条目账本(默认那条),读不到再看老的单文件 —— 老部署升级上来时
|
|
73
|
-
账本会从那个文件播种,所以第二条只照顾"播种之前就被问"的那一瞬。
|
|
74
|
-
"""
|
|
75
|
-
try:
|
|
76
|
-
from core import channel_configs as _cc
|
|
77
|
-
saved = _cc.credentials_for("qq_bot")
|
|
78
|
-
if saved:
|
|
79
|
-
return saved
|
|
80
|
-
except Exception: # noqa: BLE001
|
|
81
|
-
pass
|
|
82
|
-
if not _CRED_PATH.exists():
|
|
83
|
-
return {}
|
|
84
|
-
try:
|
|
85
|
-
with open(_CRED_PATH, "r", encoding="utf-8") as f:
|
|
86
|
-
data = json.load(f)
|
|
87
|
-
return data if isinstance(data, dict) else {}
|
|
88
|
-
except (OSError, json.JSONDecodeError) as exc:
|
|
89
|
-
print("[qq_bot] 读凭据文件失败(%s: %s)" % (type(exc).__name__, exc))
|
|
90
|
-
return {}
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
def _c2c_openid(data: dict) -> str:
|
|
94
|
-
"""C2C 事件里的回话对象。
|
|
95
|
-
|
|
96
|
-
平台把 `user_openid` 放在哪儿会变:见过在 `author` 里、在 `from_user`
|
|
97
|
-
里、也有直接放事件顶层的。三处都认,第一次命中就用。
|
|
98
|
-
|
|
99
|
-
只认这三处是有意的:认不出的形状不猜。上层会把键名打出来
|
|
100
|
-
(不打值 —— 那是用户的 openid),下一次现场就能把它补进这张表。
|
|
101
|
-
"""
|
|
102
|
-
for box in (data.get("author"), data.get("from_user"), data):
|
|
103
|
-
if isinstance(box, dict) and box.get("user_openid"):
|
|
104
|
-
return str(box["user_openid"])
|
|
105
|
-
return ""
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
def _split_text(text: str, max_len: int) -> list[str]:
|
|
109
|
-
"""按换行切段,尽量不把一行切断。
|
|
110
|
-
|
|
111
|
-
返回的每段都含前缀预算之外的位置,调用方再加 "(i/N)"。
|
|
112
|
-
"""
|
|
113
|
-
limit = max(1, max_len - _CHUNK_PREFIX_BUDGET)
|
|
114
|
-
if len(text) <= limit:
|
|
115
|
-
return [text]
|
|
116
|
-
out: list[str] = []
|
|
117
|
-
cur = ""
|
|
118
|
-
for line in text.split("\n"):
|
|
119
|
-
while len(line) > limit:
|
|
120
|
-
if cur:
|
|
121
|
-
out.append(cur)
|
|
122
|
-
cur = ""
|
|
123
|
-
out.append(line[:limit])
|
|
124
|
-
line = line[limit:]
|
|
125
|
-
candidate = line if not cur else cur + "\n" + line
|
|
126
|
-
if len(candidate) > limit:
|
|
127
|
-
out.append(cur)
|
|
128
|
-
cur = line
|
|
129
|
-
else:
|
|
130
|
-
cur = candidate
|
|
131
|
-
if cur or not out:
|
|
132
|
-
out.append(cur)
|
|
133
|
-
return out
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
class _Seen:
|
|
137
|
-
"""最近处理过的 msg_id。重连后平台会重放事件,不去重就是重复回话。"""
|
|
138
|
-
|
|
139
|
-
def __init__(self, ttl: float = _DEDUP_TTL, max_items: int = _DEDUP_MAX) -> None:
|
|
140
|
-
self._ttl = ttl
|
|
141
|
-
self._max = max_items
|
|
142
|
-
self._items: dict[str, float] = {}
|
|
143
|
-
|
|
144
|
-
def first_time(self, msg_id: str) -> bool:
|
|
145
|
-
"""这条消息以前没见过就记下来并返回 True。空 id 一律当新消息。"""
|
|
146
|
-
key = str(msg_id or "")
|
|
147
|
-
if not key:
|
|
148
|
-
return True
|
|
149
|
-
now = time.monotonic()
|
|
150
|
-
self._trim(now)
|
|
151
|
-
if key in self._items:
|
|
152
|
-
return False
|
|
153
|
-
self._items[key] = now
|
|
154
|
-
return True
|
|
155
|
-
|
|
156
|
-
def _trim(self, now: float) -> None:
|
|
157
|
-
stale = [k for k, t in self._items.items() if now - t > self._ttl]
|
|
158
|
-
for k in stale:
|
|
159
|
-
self._items.pop(k, None)
|
|
160
|
-
if len(self._items) <= self._max:
|
|
161
|
-
return
|
|
162
|
-
for k in list(self._items)[: len(self._items) - self._max]:
|
|
163
|
-
self._items.pop(k, None)
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
class _ReplyBudget:
|
|
167
|
-
"""被动回复的次数与窗口,外加「这个会话最近一条消息 id」的缓存。
|
|
168
|
-
|
|
169
|
-
每次发送前向 `reserve` 要一个 msg_id:要得到就以被动回复发出去,
|
|
170
|
-
要不到就退回主动消息。两种都发得出去,区别只在平台侧算不算配额。
|
|
171
|
-
"""
|
|
172
|
-
|
|
173
|
-
def __init__(self) -> None:
|
|
174
|
-
self._counts: dict[str, list] = {}
|
|
175
|
-
self._last: dict[str, tuple[str, str, float]] = {}
|
|
176
|
-
|
|
177
|
-
def remember(self, target_key: str, scope: str, msg_id: str) -> None:
|
|
178
|
-
"""记下这个会话最近一条收到的消息,供没有上下文的发送当回复目标。"""
|
|
179
|
-
if msg_id:
|
|
180
|
-
self._last[target_key] = (msg_id, scope, time.monotonic())
|
|
181
|
-
|
|
182
|
-
def last_for(self, target_key: str) -> tuple[str, str]:
|
|
183
|
-
rec = self._last.get(target_key)
|
|
184
|
-
if rec is None:
|
|
185
|
-
return "", ""
|
|
186
|
-
msg_id, scope, at = rec
|
|
187
|
-
if time.monotonic() - at > PASSIVE_TTL.get(scope, PASSIVE_TTL["group"]):
|
|
188
|
-
self._last.pop(target_key, None)
|
|
189
|
-
return "", ""
|
|
190
|
-
return msg_id, scope
|
|
191
|
-
|
|
192
|
-
def reserve(self, scope: str, msg_id: str) -> tuple[str, int]:
|
|
193
|
-
"""给这次发送挑一个可用的被动回复 id。
|
|
194
|
-
|
|
195
|
-
返回 `(msg_id, msg_seq)`。挑不出来时返回 `("", 0)`,调用方按主动消息发。
|
|
196
|
-
`msg_seq` 在同一条 msg_id 下逐次加一,平台靠它区分同一条消息的多次回复。
|
|
197
|
-
"""
|
|
198
|
-
if not msg_id:
|
|
199
|
-
return "", 0
|
|
200
|
-
now = time.monotonic()
|
|
201
|
-
ttl = PASSIVE_TTL.get(scope, PASSIVE_TTL["group"])
|
|
202
|
-
rec = self._counts.get(msg_id)
|
|
203
|
-
if rec is None:
|
|
204
|
-
self._counts[msg_id] = [1, now, 1]
|
|
205
|
-
self._trim(now)
|
|
206
|
-
return msg_id, 1
|
|
207
|
-
count, first, seq = rec
|
|
208
|
-
if now - first > ttl or count >= PASSIVE_LIMIT:
|
|
209
|
-
return "", 0
|
|
210
|
-
rec[0] = count + 1
|
|
211
|
-
rec[2] = seq + 1
|
|
212
|
-
return msg_id, seq + 1
|
|
213
|
-
|
|
214
|
-
def _trim(self, now: float) -> None:
|
|
215
|
-
if len(self._counts) <= _DEDUP_MAX:
|
|
216
|
-
return
|
|
217
|
-
longest = max(PASSIVE_TTL.values())
|
|
218
|
-
for k in [k for k, rec in self._counts.items() if now - rec[1] > longest]:
|
|
219
|
-
self._counts.pop(k, None)
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
class _TokenManager:
|
|
223
|
-
"""appId / appSecret 换 access_token,过期前刷新。
|
|
224
|
-
|
|
225
|
-
token 有效期约两小时。提前一分钟换,避免"刚好到期那一次请求"被拒。
|
|
226
|
-
"""
|
|
227
|
-
|
|
228
|
-
def __init__(self, app_id: str, app_secret: str, token_url: str) -> None:
|
|
229
|
-
self._app_id = app_id
|
|
230
|
-
self._app_secret = app_secret
|
|
231
|
-
self._token_url = token_url
|
|
232
|
-
self._token = ""
|
|
233
|
-
self._expires_at = 0.0
|
|
234
|
-
|
|
235
|
-
def invalidate(self) -> None:
|
|
236
|
-
self._token = ""
|
|
237
|
-
self._expires_at = 0.0
|
|
238
|
-
|
|
239
|
-
async def current(self, session) -> str:
|
|
240
|
-
if self._token and time.monotonic() < self._expires_at:
|
|
241
|
-
return self._token
|
|
242
|
-
payload = {"appId": self._app_id, "clientSecret": self._app_secret}
|
|
243
|
-
async with session.post(self._token_url, json=payload, timeout=20) as resp:
|
|
244
|
-
data = await resp.json(content_type=None)
|
|
245
|
-
token = str((data or {}).get("access_token") or "")
|
|
246
|
-
if not token:
|
|
247
|
-
raise RuntimeError("取 access_token 失败:%s"
|
|
248
|
-
% json.dumps(data, ensure_ascii=False)[:200])
|
|
249
|
-
# expires_in 有时是字符串,直接拿去做算术会抛。
|
|
250
|
-
try:
|
|
251
|
-
life = float((data or {}).get("expires_in") or 7200)
|
|
252
|
-
except (TypeError, ValueError):
|
|
253
|
-
life = 7200.0
|
|
254
|
-
self._token = token
|
|
255
|
-
self._expires_at = time.monotonic() + max(60.0, life - 60.0)
|
|
256
|
-
return token
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
class QQBotMessageConverter(MessageConverter):
|
|
260
|
-
"""QQ 事件 → MessageChain。
|
|
261
|
-
|
|
262
|
-
只做排版,不下载任何东西:媒体由通道那边下好再把本地路径交进来,
|
|
263
|
-
与 Telegram 那一份同样的分工(转换器不碰网络,测试里也就不需要网络)。
|
|
264
|
-
"""
|
|
265
|
-
|
|
266
|
-
def to_internal(self, platform_message: Any,
|
|
267
|
-
media: list[tuple[dict, str]] | None = None) -> MessageChain:
|
|
268
|
-
"""*platform_message* 是事件里的 `d` 字典。
|
|
269
|
-
|
|
270
|
-
*media* 是 `[(附件条目, 本地路径)]`。下不下来的附件由调用方
|
|
271
|
-
放进 `undelivered`,这里替它说一句实话。
|
|
272
|
-
"""
|
|
273
|
-
data = platform_message or {}
|
|
274
|
-
chain = MessageChain()
|
|
275
|
-
|
|
276
|
-
text = str(data.get("content") or "").strip()
|
|
277
|
-
if text:
|
|
278
|
-
chain.add(Plain(text))
|
|
279
|
-
|
|
280
|
-
for item, path in (media or []):
|
|
281
|
-
chain.add(self._component(item, path))
|
|
282
|
-
|
|
283
|
-
for item in (data.get("_undelivered") or []):
|
|
284
|
-
name = item.get("filename") or item.get("content_type") or "附件"
|
|
285
|
-
chain.add(Plain("[附件 %s 没有下载下来,用户可能以为你看到了]" % name))
|
|
286
|
-
|
|
287
|
-
return chain
|
|
288
|
-
|
|
289
|
-
@staticmethod
|
|
290
|
-
def _component(item: dict, path: str):
|
|
291
|
-
ctype = str(item.get("content_type") or "").lower()
|
|
292
|
-
name = str(item.get("filename") or "file")
|
|
293
|
-
size = int(item.get("size") or 0)
|
|
294
|
-
if ctype.startswith("image"):
|
|
295
|
-
return Image(local_path=path, mime_type=ctype or "image/png")
|
|
296
|
-
if ctype.startswith("voice") or ctype.startswith("audio"):
|
|
297
|
-
voice = Voice(url="", duration_seconds=0)
|
|
298
|
-
voice.local_path = path
|
|
299
|
-
return voice
|
|
300
|
-
return File(name=name, local_path=path, mime_type=ctype or
|
|
301
|
-
"application/octet-stream", size_bytes=size)
|
|
302
|
-
|
|
303
|
-
def to_platform(self, message_chain: MessageChain, **kwargs: Any) -> dict[str, Any]:
|
|
304
|
-
"""出一条纯文本正文。QQ 的文本消息只有一个 content 字段。"""
|
|
305
|
-
return {"content": message_chain.content}
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
class QQBotChannel(Channel):
|
|
309
|
-
"""QQ 机器人适配器:WebSocket 收,REST 发。"""
|
|
310
|
-
|
|
311
|
-
def __init__(self, config: dict | None = None, scheduler=None,
|
|
312
|
-
session_pool=None) -> None:
|
|
313
|
-
super().__init__(config)
|
|
314
|
-
self._converter = QQBotMessageConverter()
|
|
315
|
-
self._scheduler = scheduler
|
|
316
|
-
self._pool = session_pool
|
|
317
|
-
self._running = False
|
|
318
|
-
self._session = None
|
|
319
|
-
self._ws = None
|
|
320
|
-
self._seq: int | None = None
|
|
321
|
-
self._tokens: _TokenManager | None = None
|
|
322
|
-
self._budget = _ReplyBudget()
|
|
323
|
-
self._seen = _Seen()
|
|
324
|
-
|
|
325
|
-
self.refresh_credentials()
|
|
326
|
-
cfg = (config or {}).get("channel", {}).get("qq_bot", {}) or {}
|
|
327
|
-
self._api_base = str(cfg.get("base_url") or DEFAULT_API_BASE).rstrip("/")
|
|
328
|
-
self._token_url = str(cfg.get("token_url") or DEFAULT_TOKEN_URL)
|
|
329
|
-
self._bot_openid = ""
|
|
330
|
-
#: 代理每次 `run()` 现取。通道实例是进程内长活的,在 `__init__` 里定死
|
|
331
|
-
#: 的话,先起通道再开代理就只能重启整个应用才生效,而症状是「界面显示
|
|
332
|
-
#: 运行中、QQ 里发消息没回应」。
|
|
333
|
-
self._proxy = self._resolve_proxy()
|
|
334
|
-
|
|
335
|
-
def refresh_credentials(self) -> None:
|
|
336
|
-
"""重新读一次凭据(配置条目账本优先,其次老的单文件与环境变量)。
|
|
337
|
-
|
|
338
|
-
通道实例是进程内长活的:`init_bus` 启动时只装一次。凭据在
|
|
339
|
-
`__init__` 里读死的话,用户在设置页填完再点「启动」,那条实例拿的
|
|
340
|
-
还是启动时那份空值 —— 卡片上写着「已配置」(那是现读账本的),
|
|
341
|
-
通道却说「没有配置 AppID / AppSecret」(这是老实例说的),
|
|
342
|
-
两块界面互相打架,而两边各自都对。
|
|
343
|
-
|
|
344
|
-
与代理同一条理由(见 `_proxy` 那段注释):先起通道、后填凭据是可
|
|
345
|
-
预期的操作顺序,不该要求用户为此重启整个应用。
|
|
346
|
-
"""
|
|
347
|
-
cfg = (self.config or {}).get("channel", {}).get("qq_bot", {}) or {}
|
|
348
|
-
try:
|
|
349
|
-
creds = _load_credentials()
|
|
350
|
-
except Exception as exc: # noqa: BLE001
|
|
351
|
-
print("[qq_bot] 读凭据失败(%s: %s)" % (type(exc).__name__, exc))
|
|
352
|
-
creds = {}
|
|
353
|
-
self._app_id = str(cfg.get("app_id") or creds.get("app_id")
|
|
354
|
-
or os.environ.get("QQ_BOT_APP_ID") or "")
|
|
355
|
-
self._app_secret = str(cfg.get("app_secret") or creds.get("app_secret")
|
|
356
|
-
or os.environ.get("QQ_BOT_APP_SECRET") or "")
|
|
357
|
-
|
|
358
|
-
def meta(self) -> ChannelMetadata:
|
|
359
|
-
return ChannelMetadata(
|
|
360
|
-
name="qq_bot_channel",
|
|
361
|
-
description="QQ Bot adapter — official Bot API v2",
|
|
362
|
-
platform_type="qq_bot",
|
|
363
|
-
support_multimodal=True,
|
|
364
|
-
)
|
|
365
|
-
|
|
366
|
-
def _resolve_proxy(self) -> str:
|
|
367
|
-
"""三档代理里此刻生效的那一个地址。`direct` 档一律直连。"""
|
|
368
|
-
cfg = (self.config or {}).get("channel", {}).get("qq_bot", {}) or {}
|
|
369
|
-
from core import net_proxy as _np
|
|
370
|
-
mode, url = _np.state()
|
|
371
|
-
if mode == "direct":
|
|
372
|
-
base = ""
|
|
373
|
-
elif mode == "manual":
|
|
374
|
-
base = url
|
|
375
|
-
else:
|
|
376
|
-
base = os.environ.get("HTTPS_PROXY", "")
|
|
377
|
-
return str(cfg.get("proxy") or base or "")
|
|
378
|
-
|
|
379
|
-
# 启动与主循环
|
|
380
|
-
|
|
381
|
-
async def run(self) -> None:
|
|
382
|
-
"""连网关,断了自己重连。整个方法不返回,直到 `terminate()`。"""
|
|
383
|
-
import aiohttp
|
|
384
|
-
|
|
385
|
-
#: 按一下「启动」时现读一次 —— 用户可能刚刚才把凭据填进设置页,
|
|
386
|
-
#: 而这条实例是框架启动时就建好的(见 `refresh_credentials`)。
|
|
387
|
-
self.refresh_credentials()
|
|
388
|
-
if not (self._app_id and self._app_secret):
|
|
389
|
-
self._fail_start("没有配置 AppID / AppSecret(设置 → 通道 → QQ)")
|
|
390
|
-
return
|
|
391
|
-
|
|
392
|
-
self._running = True
|
|
393
|
-
self._proxy = self._resolve_proxy()
|
|
394
|
-
if self._proxy:
|
|
395
|
-
from core.net_proxy import redact as _redact
|
|
396
|
-
print("[qq_bot] 使用代理:%s" % _redact(self._proxy))
|
|
397
|
-
backoff = 2.0
|
|
398
|
-
try:
|
|
399
|
-
proxy = self._proxy or None
|
|
400
|
-
async with aiohttp.ClientSession(
|
|
401
|
-
timeout=aiohttp.ClientTimeout(total=None)) as session:
|
|
402
|
-
self._session = session
|
|
403
|
-
self._tokens = _TokenManager(self._app_id, self._app_secret,
|
|
404
|
-
self._token_url)
|
|
405
|
-
while self._running:
|
|
406
|
-
try:
|
|
407
|
-
await self._gateway_once(proxy)
|
|
408
|
-
backoff = 2.0
|
|
409
|
-
except asyncio.CancelledError:
|
|
410
|
-
raise
|
|
411
|
-
except Exception as exc:
|
|
412
|
-
if not self._running:
|
|
413
|
-
break
|
|
414
|
-
self._fail_start("%s: %s" % (type(exc).__name__, exc))
|
|
415
|
-
print("[qq_bot] 网关断开,%d 秒后重连" % int(backoff))
|
|
416
|
-
await asyncio.sleep(backoff)
|
|
417
|
-
backoff = min(backoff * 2, 60.0)
|
|
418
|
-
finally:
|
|
419
|
-
self._running = False
|
|
420
|
-
self._session = None
|
|
421
|
-
self._ws = None
|
|
422
|
-
|
|
423
|
-
def _fail_start(self, message: str) -> None:
|
|
424
|
-
"""起不来时留一条记录,界面上那张通道卡读得到。
|
|
425
|
-
|
|
426
|
-
只 print 到终端等于没有:桌面壳里没有终端,卡片只会回到「未运行」。
|
|
427
|
-
"""
|
|
428
|
-
print("[qq_bot] %s" % message)
|
|
429
|
-
try:
|
|
430
|
-
from core import incidents as _inc
|
|
431
|
-
_inc.note("qq_bot_channel", "channel", message,
|
|
432
|
-
component_tpl="QQ 通道启动失败:{msg}",
|
|
433
|
-
component_vars={"msg": message},
|
|
434
|
-
error_tpl="{msg}", error_vars={"msg": message})
|
|
435
|
-
except Exception as exc:
|
|
436
|
-
print("[qq_bot] 记事故失败(%s: %s)" % (type(exc).__name__, exc))
|
|
437
|
-
|
|
438
|
-
async def _gateway_once(self, proxy: str | None) -> None:
|
|
439
|
-
"""连一次网关,直到它自己断开或要求重连。"""
|
|
440
|
-
import aiohttp
|
|
441
|
-
|
|
442
|
-
token = await self._tokens.current(self._session)
|
|
443
|
-
headers = {"Authorization": "QQBot %s" % token}
|
|
444
|
-
async with self._session.get(self._api_base + "/gateway",
|
|
445
|
-
headers=headers, proxy=proxy) as resp:
|
|
446
|
-
info = await resp.json(content_type=None)
|
|
447
|
-
url = str((info or {}).get("url") or "")
|
|
448
|
-
if not url:
|
|
449
|
-
raise RuntimeError("网关地址没取到:%s"
|
|
450
|
-
% json.dumps(info, ensure_ascii=False)[:200])
|
|
451
|
-
|
|
452
|
-
async with self._session.ws_connect(url, proxy=proxy,
|
|
453
|
-
heartbeat=None) as ws:
|
|
454
|
-
self._ws = ws
|
|
455
|
-
heartbeat: asyncio.Task | None = None
|
|
456
|
-
try:
|
|
457
|
-
async for frame in ws:
|
|
458
|
-
if frame.type != aiohttp.WSMsgType.TEXT:
|
|
459
|
-
continue
|
|
460
|
-
try:
|
|
461
|
-
payload = json.loads(frame.data)
|
|
462
|
-
except json.JSONDecodeError:
|
|
463
|
-
continue
|
|
464
|
-
op = payload.get("op")
|
|
465
|
-
data = payload.get("d") or {}
|
|
466
|
-
|
|
467
|
-
if op == 10:
|
|
468
|
-
interval = float(data.get("heartbeat_interval") or 30000) / 1000.0
|
|
469
|
-
await self._identify(ws, token)
|
|
470
|
-
heartbeat = asyncio.create_task(
|
|
471
|
-
self._heartbeat_loop(ws, interval))
|
|
472
|
-
continue
|
|
473
|
-
|
|
474
|
-
if op == 11:
|
|
475
|
-
continue
|
|
476
|
-
if op == 7:
|
|
477
|
-
print("[qq_bot] 平台要求重连")
|
|
478
|
-
return
|
|
479
|
-
if op == 9:
|
|
480
|
-
self._seq = None
|
|
481
|
-
await self._identify(ws, token)
|
|
482
|
-
continue
|
|
483
|
-
if op != 0:
|
|
484
|
-
continue
|
|
485
|
-
|
|
486
|
-
self._seq = payload.get("s")
|
|
487
|
-
await self._dispatch(str(payload.get("t") or ""), data)
|
|
488
|
-
finally:
|
|
489
|
-
if heartbeat is not None:
|
|
490
|
-
heartbeat.cancel()
|
|
491
|
-
|
|
492
|
-
@staticmethod
|
|
493
|
-
def identify_payload(token: str) -> dict:
|
|
494
|
-
"""认证帧。`token` 前面必须带 `QQBot ` 前缀,少了平台直接拒。"""
|
|
495
|
-
return {"op": 2, "d": {
|
|
496
|
-
"token": "QQBot %s" % token,
|
|
497
|
-
"intents": INTENT_GROUP_AND_C2C,
|
|
498
|
-
"shard": [0, 1],
|
|
499
|
-
"properties": {},
|
|
500
|
-
}}
|
|
501
|
-
|
|
502
|
-
@staticmethod
|
|
503
|
-
def message_body(content: str, reply_id: str = "", seq: int = 0) -> dict:
|
|
504
|
-
"""一条文本消息的请求体。带 reply_id 就是被动回复,不带就是主动消息。"""
|
|
505
|
-
body: dict[str, Any] = {"content": content, "msg_type": 0}
|
|
506
|
-
if reply_id:
|
|
507
|
-
body["msg_id"] = reply_id
|
|
508
|
-
body["msg_seq"] = int(seq or 1)
|
|
509
|
-
return body
|
|
510
|
-
|
|
511
|
-
@staticmethod
|
|
512
|
-
def file_upload_payload(data: bytes, name: str) -> dict:
|
|
513
|
-
"""素材上传的请求体(文件那一类)。
|
|
514
|
-
|
|
515
|
-
`srv_send_msg: False` = 只传素材、不立刻发一条 —— 拿回 `file_info`
|
|
516
|
-
之后再发媒体消息,这样那条消息能挂上被动回复的 `msg_id`。
|
|
517
|
-
|
|
518
|
-
形状单独留一处:探针(`scripts/probe_qq_bot.py`)也用它,
|
|
519
|
-
两边各写一份的话,真机上验过的就不是通道发出去的那一份了。
|
|
520
|
-
"""
|
|
521
|
-
import base64
|
|
522
|
-
|
|
523
|
-
return {"file_type": 4,
|
|
524
|
-
"file_data": base64.b64encode(data).decode("ascii"),
|
|
525
|
-
"srv_send_msg": False,
|
|
526
|
-
"file_name": name}
|
|
527
|
-
|
|
528
|
-
@staticmethod
|
|
529
|
-
def media_message_body(file_info: str, reply_id: str = "",
|
|
530
|
-
seq: int = 0) -> dict:
|
|
531
|
-
"""一条文件消息的请求体(`msg_type=7` + `file_info`)。"""
|
|
532
|
-
body: dict[str, Any] = {"content": "", "msg_type": 7,
|
|
533
|
-
"media": {"file_info": file_info}}
|
|
534
|
-
if reply_id:
|
|
535
|
-
body["msg_id"] = reply_id
|
|
536
|
-
body["msg_seq"] = int(seq or 1)
|
|
537
|
-
return body
|
|
538
|
-
|
|
539
|
-
async def _identify(self, ws, token: str) -> None:
|
|
540
|
-
await ws.send_str(json.dumps(self.identify_payload(token)))
|
|
541
|
-
|
|
542
|
-
async def _heartbeat_loop(self, ws, interval: float) -> None:
|
|
543
|
-
"""每隔 interval 秒发一次心跳,带上最后一次收到的事件序号。"""
|
|
544
|
-
try:
|
|
545
|
-
while True:
|
|
546
|
-
await asyncio.sleep(interval)
|
|
547
|
-
await ws.send_str(json.dumps({"op": 1, "d": self._seq}))
|
|
548
|
-
except asyncio.CancelledError:
|
|
549
|
-
raise
|
|
550
|
-
except Exception as exc:
|
|
551
|
-
print("[qq_bot] 心跳停了(%s: %s)" % (type(exc).__name__, exc))
|
|
552
|
-
|
|
553
|
-
async def _dispatch(self, event_type: str, data: dict) -> None:
|
|
554
|
-
if event_type == "READY":
|
|
555
|
-
user = data.get("user") or {}
|
|
556
|
-
self._bot_openid = str(user.get("id") or "")
|
|
557
|
-
print("[qq_bot] 已连接(bot id=%s)" % (self._bot_openid or "?"))
|
|
558
|
-
try:
|
|
559
|
-
from core import incidents as _inc
|
|
560
|
-
_inc.resolve("qq_bot_channel", "channel")
|
|
561
|
-
except Exception:
|
|
562
|
-
pass
|
|
563
|
-
return
|
|
564
|
-
if event_type not in ("C2C_MESSAGE_CREATE", "GROUP_AT_MESSAGE_CREATE"):
|
|
565
|
-
return
|
|
566
|
-
try:
|
|
567
|
-
await self._handle_message(event_type, data)
|
|
568
|
-
except Exception as exc:
|
|
569
|
-
print("[qq_bot] 处理消息出错(%s: %s)" % (type(exc).__name__, exc))
|
|
570
|
-
|
|
571
|
-
# 入站
|
|
572
|
-
|
|
573
|
-
async def _handle_message(self, event_type: str, data: dict) -> None:
|
|
574
|
-
msg_id = str(data.get("id") or "")
|
|
575
|
-
if not self._seen.first_time(msg_id):
|
|
576
|
-
return
|
|
577
|
-
|
|
578
|
-
if event_type == "GROUP_AT_MESSAGE_CREATE":
|
|
579
|
-
scope = "group"
|
|
580
|
-
target_id = str(data.get("group_openid") or "")
|
|
581
|
-
author = data.get("author") or {}
|
|
582
|
-
sender_id = str(author.get("member_openid") or author.get("id") or "")
|
|
583
|
-
sender_name = str(author.get("member_openid") or "")
|
|
584
|
-
message_type = MessageType.GROUP
|
|
585
|
-
else:
|
|
586
|
-
scope = "c2c"
|
|
587
|
-
target_id = _c2c_openid(data)
|
|
588
|
-
sender_id = target_id
|
|
589
|
-
sender_name = str((data.get("author") or {}).get("username")
|
|
590
|
-
or (data.get("from_user") or {}).get("username")
|
|
591
|
-
or "")
|
|
592
|
-
message_type = MessageType.PRIVATE
|
|
593
|
-
|
|
594
|
-
if not target_id:
|
|
595
|
-
#: 只打键名,不打值 —— 那些值里是用户的 openid。
|
|
596
|
-
#: 打出来是为了下一次现场能把它补进 `_c2c_openid` 那张表。
|
|
597
|
-
print("[qq_bot] 这条事件没有回话对象,跳过(t=%s,顶层键=%s)"
|
|
598
|
-
% (event_type, ",".join(sorted(str(k) for k in data))))
|
|
599
|
-
return
|
|
600
|
-
|
|
601
|
-
media, undelivered = await self._download_attachments(
|
|
602
|
-
data.get("attachments") or [])
|
|
603
|
-
enriched = dict(data)
|
|
604
|
-
#: 下不下来的那几条要让模型知道 —— 静默丢掉会让它对着空气说话。
|
|
605
|
-
enriched["_undelivered"] = undelivered
|
|
606
|
-
chain = self._converter.to_internal(enriched, media=media)
|
|
607
|
-
if chain.is_empty:
|
|
608
|
-
return
|
|
609
|
-
|
|
610
|
-
session = MessageSession(
|
|
611
|
-
platform=self.meta().name,
|
|
612
|
-
message_type=message_type,
|
|
613
|
-
session_id=target_id,
|
|
614
|
-
)
|
|
615
|
-
self._budget.remember(str(session), scope, msg_id)
|
|
616
|
-
|
|
617
|
-
text = chain.content[:80] if chain.content else "[媒体]"
|
|
618
|
-
print("[qq_bot] %s 收到消息:%s" % (scope, text))
|
|
619
|
-
|
|
620
|
-
message = Message(
|
|
621
|
-
sender_id=sender_id,
|
|
622
|
-
sender_name=sender_name,
|
|
623
|
-
message_chain=chain,
|
|
624
|
-
message_type=message_type,
|
|
625
|
-
session=session,
|
|
626
|
-
#: 平台消息号。管线用它去重,不传那道闸就恒不触发。
|
|
627
|
-
message_id=msg_id,
|
|
628
|
-
)
|
|
629
|
-
event = self.commit_event(message)
|
|
630
|
-
|
|
631
|
-
if not self._scheduler:
|
|
632
|
-
return
|
|
633
|
-
|
|
634
|
-
async def _on_reply(reply: str) -> None:
|
|
635
|
-
await self._reply_and_drain(session, scope, target_id, msg_id, reply)
|
|
636
|
-
|
|
637
|
-
await channel_turns.intake(self, event, on_reply=_on_reply)
|
|
638
|
-
|
|
639
|
-
async def _download_attachments(self, items: list) -> tuple[list, list]:
|
|
640
|
-
"""把附件下到本地,返回 `([(条目, 路径)], [没下下来的条目])`。
|
|
641
|
-
|
|
642
|
-
一个异常都不许漏出去:漏出去整条消息连管线都进不去。
|
|
643
|
-
"""
|
|
644
|
-
media: list[tuple[dict, str]] = []
|
|
645
|
-
undelivered: list = []
|
|
646
|
-
for item in items:
|
|
647
|
-
url = str((item or {}).get("url") or "")
|
|
648
|
-
if not url:
|
|
649
|
-
undelivered.append(item)
|
|
650
|
-
continue
|
|
651
|
-
try:
|
|
652
|
-
path = await self._download_one(item, url)
|
|
653
|
-
except Exception as exc:
|
|
654
|
-
print("[qq_bot] 下载附件失败(%s: %s)"
|
|
655
|
-
% (type(exc).__name__, exc))
|
|
656
|
-
path = ""
|
|
657
|
-
if path:
|
|
658
|
-
media.append((item, path))
|
|
659
|
-
else:
|
|
660
|
-
undelivered.append(item)
|
|
661
|
-
return media, undelivered
|
|
662
|
-
|
|
663
|
-
async def _download_one(self, item: dict, url: str) -> str:
|
|
664
|
-
size = int((item or {}).get("size") or 0)
|
|
665
|
-
if size > _MAX_DOWNLOAD_BYTES:
|
|
666
|
-
print("[qq_bot] 附件太大(%d 字节),不下载" % size)
|
|
667
|
-
return ""
|
|
668
|
-
name = str((item or {}).get("filename") or "")
|
|
669
|
-
suffix = Path(name).suffix or ".bin"
|
|
670
|
-
# 目录在这里建、不在 `__init__` 里建:通道对象启动时就会构造,
|
|
671
|
-
# 在那时候建目录,任何"只是把通道导进来"的地方都会往工作目录里落一个空夹。
|
|
672
|
-
_TEMP_DIR.mkdir(parents=True, exist_ok=True)
|
|
673
|
-
dest = _TEMP_DIR / ("%s%s" % (time.strftime("%Y%m%d%H%M%S"), suffix))
|
|
674
|
-
async with self._session.get(url, proxy=self._proxy or None) as resp:
|
|
675
|
-
if resp.status != 200:
|
|
676
|
-
return ""
|
|
677
|
-
data = await resp.read()
|
|
678
|
-
if len(data) > _MAX_DOWNLOAD_BYTES:
|
|
679
|
-
return ""
|
|
680
|
-
dest.write_bytes(data)
|
|
681
|
-
return str(dest)
|
|
682
|
-
|
|
683
|
-
# 出站
|
|
684
|
-
|
|
685
|
-
async def _reply_and_drain(self, session: MessageSession, scope: str,
|
|
686
|
-
target_id: str, msg_id: str,
|
|
687
|
-
response: str | None) -> None:
|
|
688
|
-
"""先回话,再把本轮登记的文件发出去。
|
|
689
|
-
|
|
690
|
-
顺序是判据:用户先看到那句话,再收到附件。取件放在 finally 里,
|
|
691
|
-
发送这一段抛了文件也照样走。
|
|
692
|
-
"""
|
|
693
|
-
try:
|
|
694
|
-
if response:
|
|
695
|
-
await self._send_text(scope, target_id, response, msg_id)
|
|
696
|
-
finally:
|
|
697
|
-
try:
|
|
698
|
-
await self._drain_delivered(session)
|
|
699
|
-
except Exception as exc:
|
|
700
|
-
print("[qq_bot] 发待交付文件时出错(%s: %s)"
|
|
701
|
-
% (type(exc).__name__, exc))
|
|
702
|
-
|
|
703
|
-
async def _send_text(self, scope: str, target_id: str, text: str,
|
|
704
|
-
msg_id: str = "") -> bool:
|
|
705
|
-
chunks = _split_text(text, MAX_MESSAGE_LENGTH)
|
|
706
|
-
total = len(chunks)
|
|
707
|
-
ok = True
|
|
708
|
-
for i, chunk in enumerate(chunks, 1):
|
|
709
|
-
body = chunk if total == 1 else "(%d/%d)\n%s" % (i, total, chunk)
|
|
710
|
-
if not await self._send_one(scope, target_id, body, msg_id):
|
|
711
|
-
ok = False
|
|
712
|
-
return ok
|
|
713
|
-
|
|
714
|
-
async def _send_one(self, scope: str, target_id: str, content: str,
|
|
715
|
-
msg_id: str = "") -> bool:
|
|
716
|
-
"""发一条纯文本。被动配额用完就退回主动消息,两条路都算发送。"""
|
|
717
|
-
reply, seq = self._budget.reserve(scope, msg_id)
|
|
718
|
-
payload = self.message_body(content, reply, seq)
|
|
719
|
-
url = "%s/v2/%s/%s/messages" % (
|
|
720
|
-
self._api_base,
|
|
721
|
-
"users" if scope == "c2c" else "groups",
|
|
722
|
-
target_id,
|
|
723
|
-
)
|
|
724
|
-
try:
|
|
725
|
-
token = await self._tokens.current(self._session)
|
|
726
|
-
headers = {"Authorization": "QQBot %s" % token,
|
|
727
|
-
"Content-Type": "application/json"}
|
|
728
|
-
async with self._session.post(url, json=payload, headers=headers,
|
|
729
|
-
proxy=self._proxy or None) as resp:
|
|
730
|
-
if resp.status in (200, 201, 202):
|
|
731
|
-
return True
|
|
732
|
-
status, body = resp.status, await resp.text()
|
|
733
|
-
print("[qq_bot] 发送被拒(%d):%s" % (status, body[:200]))
|
|
734
|
-
return False
|
|
735
|
-
except Exception as exc:
|
|
736
|
-
print("[qq_bot] 发送失败(%s: %s)" % (type(exc).__name__, exc))
|
|
737
|
-
return False
|
|
738
|
-
|
|
739
|
-
async def send(self, session: MessageSession, content: str | MessageChain) -> bool:
|
|
740
|
-
"""没有上下文的一条回复(定时任务、后台回报)。
|
|
741
|
-
|
|
742
|
-
拿得到这个会话最近那条消息就按被动回复发,拿不到就发主动消息。
|
|
743
|
-
"""
|
|
744
|
-
text = content if isinstance(content, str) else content.content
|
|
745
|
-
scope = "group" if session.message_type is MessageType.GROUP else "c2c"
|
|
746
|
-
msg_id, _ = self._budget.last_for(str(session))
|
|
747
|
-
return await self._send_text(scope, str(session.session_id), text, msg_id)
|
|
748
|
-
|
|
749
|
-
async def send_note(self, session: MessageSession, text: str,
|
|
750
|
-
event=None) -> bool:
|
|
751
|
-
"""一句旁白。不能走 `send()`:那个会顺手把本轮待交付文件发掉,
|
|
752
|
-
用户会先看到文件再看到回答。
|
|
753
|
-
"""
|
|
754
|
-
scope = "group" if session.message_type is MessageType.GROUP else "c2c"
|
|
755
|
-
msg_id, _ = self._budget.last_for(str(session))
|
|
756
|
-
return await self._send_text(scope, str(session.session_id), text, msg_id)
|
|
757
|
-
|
|
758
|
-
async def send_media_file(self, session: MessageSession, file_path: str,
|
|
759
|
-
filename: str = "", context_token: str = "") -> bool:
|
|
760
|
-
"""发一个本地文件:先传素材拿 file_info,再发一条媒体消息。
|
|
761
|
-
|
|
762
|
-
返回 False 不算送达。上传接口对文件类型有白名单,失败时如实说。
|
|
763
|
-
"""
|
|
764
|
-
path = Path(file_path or "")
|
|
765
|
-
if not path.is_file():
|
|
766
|
-
print("[qq_bot] 要发的文件不存在:%s" % file_path)
|
|
767
|
-
return False
|
|
768
|
-
scope = "group" if session.message_type is MessageType.GROUP else "c2c"
|
|
769
|
-
target_id = str(session.session_id)
|
|
770
|
-
name = filename or path.name
|
|
771
|
-
url = "%s/v2/%s/%s/files" % (
|
|
772
|
-
self._api_base, "users" if scope == "c2c" else "groups", target_id)
|
|
773
|
-
try:
|
|
774
|
-
token = await self._tokens.current(self._session)
|
|
775
|
-
headers = {"Authorization": "QQBot %s" % token,
|
|
776
|
-
"Content-Type": "application/json"}
|
|
777
|
-
#: file_type 4 = 文件。素材要先传上去,平台不接受本地路径。
|
|
778
|
-
payload = self.file_upload_payload(path.read_bytes(), name)
|
|
779
|
-
async with self._session.post(url, json=payload, headers=headers,
|
|
780
|
-
proxy=self._proxy or None) as resp:
|
|
781
|
-
if resp.status not in (200, 201, 202):
|
|
782
|
-
status, body = resp.status, await resp.text()
|
|
783
|
-
print("[qq_bot] 上传文件被拒(%d):%s" % (status, body[:200]))
|
|
784
|
-
return False
|
|
785
|
-
info = await resp.json(content_type=None)
|
|
786
|
-
except Exception as exc:
|
|
787
|
-
print("[qq_bot] 上传文件失败(%s: %s)" % (type(exc).__name__, exc))
|
|
788
|
-
return False
|
|
789
|
-
|
|
790
|
-
file_info = str((info or {}).get("file_info") or "")
|
|
791
|
-
if not file_info:
|
|
792
|
-
print("[qq_bot] 上传成功但没拿到 file_info,没法发消息")
|
|
793
|
-
return False
|
|
794
|
-
|
|
795
|
-
msg_id, _ = self._budget.last_for(str(session))
|
|
796
|
-
reply, seq = self._budget.reserve(scope, msg_id)
|
|
797
|
-
msg = self.media_message_body(file_info, reply, seq)
|
|
798
|
-
api = "%s/v2/%s/%s/messages" % (
|
|
799
|
-
self._api_base, "users" if scope == "c2c" else "groups", target_id)
|
|
800
|
-
try:
|
|
801
|
-
token = await self._tokens.current(self._session)
|
|
802
|
-
headers = {"Authorization": "QQBot %s" % token,
|
|
803
|
-
"Content-Type": "application/json"}
|
|
804
|
-
async with self._session.post(api, json=msg, headers=headers,
|
|
805
|
-
proxy=self._proxy or None) as resp:
|
|
806
|
-
if resp.status in (200, 201, 202):
|
|
807
|
-
return True
|
|
808
|
-
status, body = resp.status, await resp.text()
|
|
809
|
-
print("[qq_bot] 发送文件消息被拒(%d):%s" % (status, body[:200]))
|
|
810
|
-
return False
|
|
811
|
-
except Exception as exc:
|
|
812
|
-
print("[qq_bot] 发送文件消息失败(%s: %s)" % (type(exc).__name__, exc))
|
|
813
|
-
return False
|
|
814
|
-
|
|
815
|
-
async def _drain_delivered(self, session: MessageSession) -> int:
|
|
816
|
-
"""把本轮登记的文件发出去,返回真发出去的条数。
|
|
817
|
-
|
|
818
|
-
工具是同步的、不能 await 这个循环,所以它只登记;通道在回话之后
|
|
819
|
-
取走发掉。三格都要对上:会话键、通道名、用户 id。
|
|
820
|
-
"""
|
|
821
|
-
from core import delivery_outbox as _outbox
|
|
822
|
-
from core.session_key import session_key_for
|
|
823
|
-
|
|
824
|
-
try:
|
|
825
|
-
recs = _outbox.take_for(
|
|
826
|
-
session_key=session_key_for(session),
|
|
827
|
-
channel="qq_bot_channel",
|
|
828
|
-
user_id=str(getattr(session, "session_id", "") or ""))
|
|
829
|
-
except Exception as exc:
|
|
830
|
-
print("[qq_bot] 取待发文件失败(%s: %s)" % (type(exc).__name__, exc))
|
|
831
|
-
return 0
|
|
832
|
-
sent = 0
|
|
833
|
-
for rec in recs:
|
|
834
|
-
if await self.send_media_file(session, rec.get("path", ""),
|
|
835
|
-
rec.get("name", "")):
|
|
836
|
-
sent += 1
|
|
837
|
-
continue
|
|
838
|
-
await self.send_note(session, "文件 %s 没能发出去(原因在框架日志里)。"
|
|
839
|
-
% (rec.get("name") or "?"))
|
|
840
|
-
return sent
|
|
841
|
-
|
|
842
|
-
async def test_connection(self) -> dict:
|
|
843
|
-
"""问一次 /users/@me。连得上说明 token 与网络都通。"""
|
|
844
|
-
#: 同 `run()`:探活多半就是"刚填完凭据、按一下试试"的那一下。
|
|
845
|
-
self.refresh_credentials()
|
|
846
|
-
if not (self._app_id and self._app_secret):
|
|
847
|
-
return {"ok": False, "message": "没有配置 AppID / AppSecret"}
|
|
848
|
-
#: 每次都自建会话。探活是从别的线程(设置页那个请求)进来的,
|
|
849
|
-
#: 借通道自己那条会话会把两个事件循环缠在一起。
|
|
850
|
-
session = None
|
|
851
|
-
try:
|
|
852
|
-
import aiohttp
|
|
853
|
-
session = aiohttp.ClientSession()
|
|
854
|
-
tokens = _TokenManager(self._app_id, self._app_secret, self._token_url)
|
|
855
|
-
token = await tokens.current(session)
|
|
856
|
-
async with session.get(
|
|
857
|
-
self._api_base + "/users/@me",
|
|
858
|
-
headers={"Authorization": "QQBot %s" % token},
|
|
859
|
-
proxy=self._proxy or None) as resp:
|
|
860
|
-
if resp.status != 200:
|
|
861
|
-
body = await resp.text()
|
|
862
|
-
return {"ok": False, "message": "QQ 接口返回 %d:%s"
|
|
863
|
-
% (resp.status, body[:200])}
|
|
864
|
-
data = await resp.json(content_type=None) or {}
|
|
865
|
-
return {"ok": True, "message": "QQ 机器人:%s"
|
|
866
|
-
% (data.get("username") or data.get("id") or "已连接")}
|
|
867
|
-
except Exception as exc:
|
|
868
|
-
return {"ok": False, "message": "%s: %s" % (type(exc).__name__, exc)}
|
|
869
|
-
finally:
|
|
870
|
-
if session is not None:
|
|
871
|
-
await session.close()
|
|
872
|
-
|
|
873
|
-
async def terminate(self) -> None:
|
|
874
|
-
self._running = False
|
|
875
|
-
ws = self._ws
|
|
876
|
-
self._ws = None
|
|
877
|
-
if ws is not None:
|
|
878
|
-
try:
|
|
879
|
-
await ws.close()
|
|
880
|
-
except Exception:
|
|
881
|
-
pass
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""QQ 机器人通道 —— 官方 Bot API v2。
|
|
3
|
+
|
|
4
|
+
收发都走官方接口,不需要协议端(不用另跑一个小号来转)。
|
|
5
|
+
|
|
6
|
+
收:取网关地址,连 WebSocket,认证后靠心跳保活,事件由 op 0 派发。
|
|
7
|
+
发:私聊 POST /v2/users/<openid>/messages,
|
|
8
|
+
群聊换 /v2/groups/<group_openid>/messages。
|
|
9
|
+
|
|
10
|
+
被动回复有两条限制:同一条消息最多回四次;群聊窗口五分钟、私聊三十分钟。
|
|
11
|
+
超出就退回主动消息(不带 msg_id)。这两个数只有 `_ReplyBudget` 一处口径,
|
|
12
|
+
别在调用点再写一遍:写两处就会一处改了一处没改,症状是「偶尔这条回不出去」。
|
|
13
|
+
|
|
14
|
+
凭据(appId / appSecret)读 `data/qq_bot_credentials.json`,与微信那一份同形状。
|
|
15
|
+
那份文件在 `DEFAULT_FORBIDDEN_PATHS` 里 —— 模型能读到自己就写的那份 json,
|
|
16
|
+
等于把机器人交出去了。
|
|
17
|
+
|
|
18
|
+
群消息走的是 `GROUP_AT_MESSAGE_CREATE`,即平台只推「@ 我」的那些。
|
|
19
|
+
「不 @ 也能收」取决于平台侧的开关,代码这一层没有可判的输入。
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import asyncio
|
|
25
|
+
import json
|
|
26
|
+
import os
|
|
27
|
+
import time
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
from typing import Any
|
|
30
|
+
|
|
31
|
+
from channels.base import (
|
|
32
|
+
Channel,
|
|
33
|
+
ChannelMetadata,
|
|
34
|
+
Message,
|
|
35
|
+
MessageSession,
|
|
36
|
+
MessageType,
|
|
37
|
+
)
|
|
38
|
+
from channels.converter import MessageConverter
|
|
39
|
+
from channels.message import File, Image, MessageChain, Plain, Voice
|
|
40
|
+
from core import channel_turns
|
|
41
|
+
|
|
42
|
+
# 官方地址。沙箱换 `https://sandbox.api.sgroup.qq.com`(配置 `base_url` 可覆盖)。
|
|
43
|
+
DEFAULT_API_BASE = "https://api.sgroup.qq.com"
|
|
44
|
+
DEFAULT_TOKEN_URL = "https://bots.qq.com/app/getAppAccessToken"
|
|
45
|
+
|
|
46
|
+
#: 群与私聊消息事件那一位(C2C_MESSAGE_CREATE / GROUP_AT_MESSAGE_CREATE)。
|
|
47
|
+
#: 只订这一位:频道消息是另一套形状,本通道不处理。
|
|
48
|
+
INTENT_GROUP_AND_C2C = 1 << 25
|
|
49
|
+
|
|
50
|
+
#: 单条消息的字符上限。超了要切,切的时候留出 "(i/N)" 前缀的位置。
|
|
51
|
+
MAX_MESSAGE_LENGTH = 5000
|
|
52
|
+
_CHUNK_PREFIX_BUDGET = 12
|
|
53
|
+
|
|
54
|
+
#: 被动回复的次数上限与窗口(秒)。
|
|
55
|
+
PASSIVE_LIMIT = 4
|
|
56
|
+
PASSIVE_TTL = {"c2c": 1800, "group": 300}
|
|
57
|
+
|
|
58
|
+
#: 事件去重的保留时长(秒)。重连后平台会重放没确认的事件。
|
|
59
|
+
_DEDUP_TTL = 600.0
|
|
60
|
+
_DEDUP_MAX = 4000
|
|
61
|
+
|
|
62
|
+
_CRED_PATH = Path("data/qq_bot_credentials.json")
|
|
63
|
+
_TEMP_DIR = Path("data/workdata/qqbot_files")
|
|
64
|
+
|
|
65
|
+
#: 下载入站媒体的上限。超过就只在正文里说一句,不落盘。
|
|
66
|
+
_MAX_DOWNLOAD_BYTES = 30 * 1024 * 1024
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _load_credentials() -> dict:
|
|
70
|
+
"""这条通道当前的凭据。
|
|
71
|
+
|
|
72
|
+
先问配置条目账本(默认那条),读不到再看老的单文件 —— 老部署升级上来时
|
|
73
|
+
账本会从那个文件播种,所以第二条只照顾"播种之前就被问"的那一瞬。
|
|
74
|
+
"""
|
|
75
|
+
try:
|
|
76
|
+
from core import channel_configs as _cc
|
|
77
|
+
saved = _cc.credentials_for("qq_bot")
|
|
78
|
+
if saved:
|
|
79
|
+
return saved
|
|
80
|
+
except Exception: # noqa: BLE001
|
|
81
|
+
pass
|
|
82
|
+
if not _CRED_PATH.exists():
|
|
83
|
+
return {}
|
|
84
|
+
try:
|
|
85
|
+
with open(_CRED_PATH, "r", encoding="utf-8") as f:
|
|
86
|
+
data = json.load(f)
|
|
87
|
+
return data if isinstance(data, dict) else {}
|
|
88
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
89
|
+
print("[qq_bot] 读凭据文件失败(%s: %s)" % (type(exc).__name__, exc))
|
|
90
|
+
return {}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _c2c_openid(data: dict) -> str:
|
|
94
|
+
"""C2C 事件里的回话对象。
|
|
95
|
+
|
|
96
|
+
平台把 `user_openid` 放在哪儿会变:见过在 `author` 里、在 `from_user`
|
|
97
|
+
里、也有直接放事件顶层的。三处都认,第一次命中就用。
|
|
98
|
+
|
|
99
|
+
只认这三处是有意的:认不出的形状不猜。上层会把键名打出来
|
|
100
|
+
(不打值 —— 那是用户的 openid),下一次现场就能把它补进这张表。
|
|
101
|
+
"""
|
|
102
|
+
for box in (data.get("author"), data.get("from_user"), data):
|
|
103
|
+
if isinstance(box, dict) and box.get("user_openid"):
|
|
104
|
+
return str(box["user_openid"])
|
|
105
|
+
return ""
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _split_text(text: str, max_len: int) -> list[str]:
|
|
109
|
+
"""按换行切段,尽量不把一行切断。
|
|
110
|
+
|
|
111
|
+
返回的每段都含前缀预算之外的位置,调用方再加 "(i/N)"。
|
|
112
|
+
"""
|
|
113
|
+
limit = max(1, max_len - _CHUNK_PREFIX_BUDGET)
|
|
114
|
+
if len(text) <= limit:
|
|
115
|
+
return [text]
|
|
116
|
+
out: list[str] = []
|
|
117
|
+
cur = ""
|
|
118
|
+
for line in text.split("\n"):
|
|
119
|
+
while len(line) > limit:
|
|
120
|
+
if cur:
|
|
121
|
+
out.append(cur)
|
|
122
|
+
cur = ""
|
|
123
|
+
out.append(line[:limit])
|
|
124
|
+
line = line[limit:]
|
|
125
|
+
candidate = line if not cur else cur + "\n" + line
|
|
126
|
+
if len(candidate) > limit:
|
|
127
|
+
out.append(cur)
|
|
128
|
+
cur = line
|
|
129
|
+
else:
|
|
130
|
+
cur = candidate
|
|
131
|
+
if cur or not out:
|
|
132
|
+
out.append(cur)
|
|
133
|
+
return out
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class _Seen:
|
|
137
|
+
"""最近处理过的 msg_id。重连后平台会重放事件,不去重就是重复回话。"""
|
|
138
|
+
|
|
139
|
+
def __init__(self, ttl: float = _DEDUP_TTL, max_items: int = _DEDUP_MAX) -> None:
|
|
140
|
+
self._ttl = ttl
|
|
141
|
+
self._max = max_items
|
|
142
|
+
self._items: dict[str, float] = {}
|
|
143
|
+
|
|
144
|
+
def first_time(self, msg_id: str) -> bool:
|
|
145
|
+
"""这条消息以前没见过就记下来并返回 True。空 id 一律当新消息。"""
|
|
146
|
+
key = str(msg_id or "")
|
|
147
|
+
if not key:
|
|
148
|
+
return True
|
|
149
|
+
now = time.monotonic()
|
|
150
|
+
self._trim(now)
|
|
151
|
+
if key in self._items:
|
|
152
|
+
return False
|
|
153
|
+
self._items[key] = now
|
|
154
|
+
return True
|
|
155
|
+
|
|
156
|
+
def _trim(self, now: float) -> None:
|
|
157
|
+
stale = [k for k, t in self._items.items() if now - t > self._ttl]
|
|
158
|
+
for k in stale:
|
|
159
|
+
self._items.pop(k, None)
|
|
160
|
+
if len(self._items) <= self._max:
|
|
161
|
+
return
|
|
162
|
+
for k in list(self._items)[: len(self._items) - self._max]:
|
|
163
|
+
self._items.pop(k, None)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class _ReplyBudget:
|
|
167
|
+
"""被动回复的次数与窗口,外加「这个会话最近一条消息 id」的缓存。
|
|
168
|
+
|
|
169
|
+
每次发送前向 `reserve` 要一个 msg_id:要得到就以被动回复发出去,
|
|
170
|
+
要不到就退回主动消息。两种都发得出去,区别只在平台侧算不算配额。
|
|
171
|
+
"""
|
|
172
|
+
|
|
173
|
+
def __init__(self) -> None:
|
|
174
|
+
self._counts: dict[str, list] = {}
|
|
175
|
+
self._last: dict[str, tuple[str, str, float]] = {}
|
|
176
|
+
|
|
177
|
+
def remember(self, target_key: str, scope: str, msg_id: str) -> None:
|
|
178
|
+
"""记下这个会话最近一条收到的消息,供没有上下文的发送当回复目标。"""
|
|
179
|
+
if msg_id:
|
|
180
|
+
self._last[target_key] = (msg_id, scope, time.monotonic())
|
|
181
|
+
|
|
182
|
+
def last_for(self, target_key: str) -> tuple[str, str]:
|
|
183
|
+
rec = self._last.get(target_key)
|
|
184
|
+
if rec is None:
|
|
185
|
+
return "", ""
|
|
186
|
+
msg_id, scope, at = rec
|
|
187
|
+
if time.monotonic() - at > PASSIVE_TTL.get(scope, PASSIVE_TTL["group"]):
|
|
188
|
+
self._last.pop(target_key, None)
|
|
189
|
+
return "", ""
|
|
190
|
+
return msg_id, scope
|
|
191
|
+
|
|
192
|
+
def reserve(self, scope: str, msg_id: str) -> tuple[str, int]:
|
|
193
|
+
"""给这次发送挑一个可用的被动回复 id。
|
|
194
|
+
|
|
195
|
+
返回 `(msg_id, msg_seq)`。挑不出来时返回 `("", 0)`,调用方按主动消息发。
|
|
196
|
+
`msg_seq` 在同一条 msg_id 下逐次加一,平台靠它区分同一条消息的多次回复。
|
|
197
|
+
"""
|
|
198
|
+
if not msg_id:
|
|
199
|
+
return "", 0
|
|
200
|
+
now = time.monotonic()
|
|
201
|
+
ttl = PASSIVE_TTL.get(scope, PASSIVE_TTL["group"])
|
|
202
|
+
rec = self._counts.get(msg_id)
|
|
203
|
+
if rec is None:
|
|
204
|
+
self._counts[msg_id] = [1, now, 1]
|
|
205
|
+
self._trim(now)
|
|
206
|
+
return msg_id, 1
|
|
207
|
+
count, first, seq = rec
|
|
208
|
+
if now - first > ttl or count >= PASSIVE_LIMIT:
|
|
209
|
+
return "", 0
|
|
210
|
+
rec[0] = count + 1
|
|
211
|
+
rec[2] = seq + 1
|
|
212
|
+
return msg_id, seq + 1
|
|
213
|
+
|
|
214
|
+
def _trim(self, now: float) -> None:
|
|
215
|
+
if len(self._counts) <= _DEDUP_MAX:
|
|
216
|
+
return
|
|
217
|
+
longest = max(PASSIVE_TTL.values())
|
|
218
|
+
for k in [k for k, rec in self._counts.items() if now - rec[1] > longest]:
|
|
219
|
+
self._counts.pop(k, None)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
class _TokenManager:
|
|
223
|
+
"""appId / appSecret 换 access_token,过期前刷新。
|
|
224
|
+
|
|
225
|
+
token 有效期约两小时。提前一分钟换,避免"刚好到期那一次请求"被拒。
|
|
226
|
+
"""
|
|
227
|
+
|
|
228
|
+
def __init__(self, app_id: str, app_secret: str, token_url: str) -> None:
|
|
229
|
+
self._app_id = app_id
|
|
230
|
+
self._app_secret = app_secret
|
|
231
|
+
self._token_url = token_url
|
|
232
|
+
self._token = ""
|
|
233
|
+
self._expires_at = 0.0
|
|
234
|
+
|
|
235
|
+
def invalidate(self) -> None:
|
|
236
|
+
self._token = ""
|
|
237
|
+
self._expires_at = 0.0
|
|
238
|
+
|
|
239
|
+
async def current(self, session) -> str:
|
|
240
|
+
if self._token and time.monotonic() < self._expires_at:
|
|
241
|
+
return self._token
|
|
242
|
+
payload = {"appId": self._app_id, "clientSecret": self._app_secret}
|
|
243
|
+
async with session.post(self._token_url, json=payload, timeout=20) as resp:
|
|
244
|
+
data = await resp.json(content_type=None)
|
|
245
|
+
token = str((data or {}).get("access_token") or "")
|
|
246
|
+
if not token:
|
|
247
|
+
raise RuntimeError("取 access_token 失败:%s"
|
|
248
|
+
% json.dumps(data, ensure_ascii=False)[:200])
|
|
249
|
+
# expires_in 有时是字符串,直接拿去做算术会抛。
|
|
250
|
+
try:
|
|
251
|
+
life = float((data or {}).get("expires_in") or 7200)
|
|
252
|
+
except (TypeError, ValueError):
|
|
253
|
+
life = 7200.0
|
|
254
|
+
self._token = token
|
|
255
|
+
self._expires_at = time.monotonic() + max(60.0, life - 60.0)
|
|
256
|
+
return token
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
class QQBotMessageConverter(MessageConverter):
|
|
260
|
+
"""QQ 事件 → MessageChain。
|
|
261
|
+
|
|
262
|
+
只做排版,不下载任何东西:媒体由通道那边下好再把本地路径交进来,
|
|
263
|
+
与 Telegram 那一份同样的分工(转换器不碰网络,测试里也就不需要网络)。
|
|
264
|
+
"""
|
|
265
|
+
|
|
266
|
+
def to_internal(self, platform_message: Any,
|
|
267
|
+
media: list[tuple[dict, str]] | None = None) -> MessageChain:
|
|
268
|
+
"""*platform_message* 是事件里的 `d` 字典。
|
|
269
|
+
|
|
270
|
+
*media* 是 `[(附件条目, 本地路径)]`。下不下来的附件由调用方
|
|
271
|
+
放进 `undelivered`,这里替它说一句实话。
|
|
272
|
+
"""
|
|
273
|
+
data = platform_message or {}
|
|
274
|
+
chain = MessageChain()
|
|
275
|
+
|
|
276
|
+
text = str(data.get("content") or "").strip()
|
|
277
|
+
if text:
|
|
278
|
+
chain.add(Plain(text))
|
|
279
|
+
|
|
280
|
+
for item, path in (media or []):
|
|
281
|
+
chain.add(self._component(item, path))
|
|
282
|
+
|
|
283
|
+
for item in (data.get("_undelivered") or []):
|
|
284
|
+
name = item.get("filename") or item.get("content_type") or "附件"
|
|
285
|
+
chain.add(Plain("[附件 %s 没有下载下来,用户可能以为你看到了]" % name))
|
|
286
|
+
|
|
287
|
+
return chain
|
|
288
|
+
|
|
289
|
+
@staticmethod
|
|
290
|
+
def _component(item: dict, path: str):
|
|
291
|
+
ctype = str(item.get("content_type") or "").lower()
|
|
292
|
+
name = str(item.get("filename") or "file")
|
|
293
|
+
size = int(item.get("size") or 0)
|
|
294
|
+
if ctype.startswith("image"):
|
|
295
|
+
return Image(local_path=path, mime_type=ctype or "image/png")
|
|
296
|
+
if ctype.startswith("voice") or ctype.startswith("audio"):
|
|
297
|
+
voice = Voice(url="", duration_seconds=0)
|
|
298
|
+
voice.local_path = path
|
|
299
|
+
return voice
|
|
300
|
+
return File(name=name, local_path=path, mime_type=ctype or
|
|
301
|
+
"application/octet-stream", size_bytes=size)
|
|
302
|
+
|
|
303
|
+
def to_platform(self, message_chain: MessageChain, **kwargs: Any) -> dict[str, Any]:
|
|
304
|
+
"""出一条纯文本正文。QQ 的文本消息只有一个 content 字段。"""
|
|
305
|
+
return {"content": message_chain.content}
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
class QQBotChannel(Channel):
|
|
309
|
+
"""QQ 机器人适配器:WebSocket 收,REST 发。"""
|
|
310
|
+
|
|
311
|
+
def __init__(self, config: dict | None = None, scheduler=None,
|
|
312
|
+
session_pool=None) -> None:
|
|
313
|
+
super().__init__(config)
|
|
314
|
+
self._converter = QQBotMessageConverter()
|
|
315
|
+
self._scheduler = scheduler
|
|
316
|
+
self._pool = session_pool
|
|
317
|
+
self._running = False
|
|
318
|
+
self._session = None
|
|
319
|
+
self._ws = None
|
|
320
|
+
self._seq: int | None = None
|
|
321
|
+
self._tokens: _TokenManager | None = None
|
|
322
|
+
self._budget = _ReplyBudget()
|
|
323
|
+
self._seen = _Seen()
|
|
324
|
+
|
|
325
|
+
self.refresh_credentials()
|
|
326
|
+
cfg = (config or {}).get("channel", {}).get("qq_bot", {}) or {}
|
|
327
|
+
self._api_base = str(cfg.get("base_url") or DEFAULT_API_BASE).rstrip("/")
|
|
328
|
+
self._token_url = str(cfg.get("token_url") or DEFAULT_TOKEN_URL)
|
|
329
|
+
self._bot_openid = ""
|
|
330
|
+
#: 代理每次 `run()` 现取。通道实例是进程内长活的,在 `__init__` 里定死
|
|
331
|
+
#: 的话,先起通道再开代理就只能重启整个应用才生效,而症状是「界面显示
|
|
332
|
+
#: 运行中、QQ 里发消息没回应」。
|
|
333
|
+
self._proxy = self._resolve_proxy()
|
|
334
|
+
|
|
335
|
+
def refresh_credentials(self) -> None:
|
|
336
|
+
"""重新读一次凭据(配置条目账本优先,其次老的单文件与环境变量)。
|
|
337
|
+
|
|
338
|
+
通道实例是进程内长活的:`init_bus` 启动时只装一次。凭据在
|
|
339
|
+
`__init__` 里读死的话,用户在设置页填完再点「启动」,那条实例拿的
|
|
340
|
+
还是启动时那份空值 —— 卡片上写着「已配置」(那是现读账本的),
|
|
341
|
+
通道却说「没有配置 AppID / AppSecret」(这是老实例说的),
|
|
342
|
+
两块界面互相打架,而两边各自都对。
|
|
343
|
+
|
|
344
|
+
与代理同一条理由(见 `_proxy` 那段注释):先起通道、后填凭据是可
|
|
345
|
+
预期的操作顺序,不该要求用户为此重启整个应用。
|
|
346
|
+
"""
|
|
347
|
+
cfg = (self.config or {}).get("channel", {}).get("qq_bot", {}) or {}
|
|
348
|
+
try:
|
|
349
|
+
creds = _load_credentials()
|
|
350
|
+
except Exception as exc: # noqa: BLE001
|
|
351
|
+
print("[qq_bot] 读凭据失败(%s: %s)" % (type(exc).__name__, exc))
|
|
352
|
+
creds = {}
|
|
353
|
+
self._app_id = str(cfg.get("app_id") or creds.get("app_id")
|
|
354
|
+
or os.environ.get("QQ_BOT_APP_ID") or "")
|
|
355
|
+
self._app_secret = str(cfg.get("app_secret") or creds.get("app_secret")
|
|
356
|
+
or os.environ.get("QQ_BOT_APP_SECRET") or "")
|
|
357
|
+
|
|
358
|
+
def meta(self) -> ChannelMetadata:
|
|
359
|
+
return ChannelMetadata(
|
|
360
|
+
name="qq_bot_channel",
|
|
361
|
+
description="QQ Bot adapter — official Bot API v2",
|
|
362
|
+
platform_type="qq_bot",
|
|
363
|
+
support_multimodal=True,
|
|
364
|
+
)
|
|
365
|
+
|
|
366
|
+
def _resolve_proxy(self) -> str:
|
|
367
|
+
"""三档代理里此刻生效的那一个地址。`direct` 档一律直连。"""
|
|
368
|
+
cfg = (self.config or {}).get("channel", {}).get("qq_bot", {}) or {}
|
|
369
|
+
from core import net_proxy as _np
|
|
370
|
+
mode, url = _np.state()
|
|
371
|
+
if mode == "direct":
|
|
372
|
+
base = ""
|
|
373
|
+
elif mode == "manual":
|
|
374
|
+
base = url
|
|
375
|
+
else:
|
|
376
|
+
base = os.environ.get("HTTPS_PROXY", "")
|
|
377
|
+
return str(cfg.get("proxy") or base or "")
|
|
378
|
+
|
|
379
|
+
# 启动与主循环
|
|
380
|
+
|
|
381
|
+
async def run(self) -> None:
|
|
382
|
+
"""连网关,断了自己重连。整个方法不返回,直到 `terminate()`。"""
|
|
383
|
+
import aiohttp
|
|
384
|
+
|
|
385
|
+
#: 按一下「启动」时现读一次 —— 用户可能刚刚才把凭据填进设置页,
|
|
386
|
+
#: 而这条实例是框架启动时就建好的(见 `refresh_credentials`)。
|
|
387
|
+
self.refresh_credentials()
|
|
388
|
+
if not (self._app_id and self._app_secret):
|
|
389
|
+
self._fail_start("没有配置 AppID / AppSecret(设置 → 通道 → QQ)")
|
|
390
|
+
return
|
|
391
|
+
|
|
392
|
+
self._running = True
|
|
393
|
+
self._proxy = self._resolve_proxy()
|
|
394
|
+
if self._proxy:
|
|
395
|
+
from core.net_proxy import redact as _redact
|
|
396
|
+
print("[qq_bot] 使用代理:%s" % _redact(self._proxy))
|
|
397
|
+
backoff = 2.0
|
|
398
|
+
try:
|
|
399
|
+
proxy = self._proxy or None
|
|
400
|
+
async with aiohttp.ClientSession(
|
|
401
|
+
timeout=aiohttp.ClientTimeout(total=None)) as session:
|
|
402
|
+
self._session = session
|
|
403
|
+
self._tokens = _TokenManager(self._app_id, self._app_secret,
|
|
404
|
+
self._token_url)
|
|
405
|
+
while self._running:
|
|
406
|
+
try:
|
|
407
|
+
await self._gateway_once(proxy)
|
|
408
|
+
backoff = 2.0
|
|
409
|
+
except asyncio.CancelledError:
|
|
410
|
+
raise
|
|
411
|
+
except Exception as exc:
|
|
412
|
+
if not self._running:
|
|
413
|
+
break
|
|
414
|
+
self._fail_start("%s: %s" % (type(exc).__name__, exc))
|
|
415
|
+
print("[qq_bot] 网关断开,%d 秒后重连" % int(backoff))
|
|
416
|
+
await asyncio.sleep(backoff)
|
|
417
|
+
backoff = min(backoff * 2, 60.0)
|
|
418
|
+
finally:
|
|
419
|
+
self._running = False
|
|
420
|
+
self._session = None
|
|
421
|
+
self._ws = None
|
|
422
|
+
|
|
423
|
+
def _fail_start(self, message: str) -> None:
|
|
424
|
+
"""起不来时留一条记录,界面上那张通道卡读得到。
|
|
425
|
+
|
|
426
|
+
只 print 到终端等于没有:桌面壳里没有终端,卡片只会回到「未运行」。
|
|
427
|
+
"""
|
|
428
|
+
print("[qq_bot] %s" % message)
|
|
429
|
+
try:
|
|
430
|
+
from core import incidents as _inc
|
|
431
|
+
_inc.note("qq_bot_channel", "channel", message,
|
|
432
|
+
component_tpl="QQ 通道启动失败:{msg}",
|
|
433
|
+
component_vars={"msg": message},
|
|
434
|
+
error_tpl="{msg}", error_vars={"msg": message})
|
|
435
|
+
except Exception as exc:
|
|
436
|
+
print("[qq_bot] 记事故失败(%s: %s)" % (type(exc).__name__, exc))
|
|
437
|
+
|
|
438
|
+
async def _gateway_once(self, proxy: str | None) -> None:
|
|
439
|
+
"""连一次网关,直到它自己断开或要求重连。"""
|
|
440
|
+
import aiohttp
|
|
441
|
+
|
|
442
|
+
token = await self._tokens.current(self._session)
|
|
443
|
+
headers = {"Authorization": "QQBot %s" % token}
|
|
444
|
+
async with self._session.get(self._api_base + "/gateway",
|
|
445
|
+
headers=headers, proxy=proxy) as resp:
|
|
446
|
+
info = await resp.json(content_type=None)
|
|
447
|
+
url = str((info or {}).get("url") or "")
|
|
448
|
+
if not url:
|
|
449
|
+
raise RuntimeError("网关地址没取到:%s"
|
|
450
|
+
% json.dumps(info, ensure_ascii=False)[:200])
|
|
451
|
+
|
|
452
|
+
async with self._session.ws_connect(url, proxy=proxy,
|
|
453
|
+
heartbeat=None) as ws:
|
|
454
|
+
self._ws = ws
|
|
455
|
+
heartbeat: asyncio.Task | None = None
|
|
456
|
+
try:
|
|
457
|
+
async for frame in ws:
|
|
458
|
+
if frame.type != aiohttp.WSMsgType.TEXT:
|
|
459
|
+
continue
|
|
460
|
+
try:
|
|
461
|
+
payload = json.loads(frame.data)
|
|
462
|
+
except json.JSONDecodeError:
|
|
463
|
+
continue
|
|
464
|
+
op = payload.get("op")
|
|
465
|
+
data = payload.get("d") or {}
|
|
466
|
+
|
|
467
|
+
if op == 10:
|
|
468
|
+
interval = float(data.get("heartbeat_interval") or 30000) / 1000.0
|
|
469
|
+
await self._identify(ws, token)
|
|
470
|
+
heartbeat = asyncio.create_task(
|
|
471
|
+
self._heartbeat_loop(ws, interval))
|
|
472
|
+
continue
|
|
473
|
+
|
|
474
|
+
if op == 11:
|
|
475
|
+
continue
|
|
476
|
+
if op == 7:
|
|
477
|
+
print("[qq_bot] 平台要求重连")
|
|
478
|
+
return
|
|
479
|
+
if op == 9:
|
|
480
|
+
self._seq = None
|
|
481
|
+
await self._identify(ws, token)
|
|
482
|
+
continue
|
|
483
|
+
if op != 0:
|
|
484
|
+
continue
|
|
485
|
+
|
|
486
|
+
self._seq = payload.get("s")
|
|
487
|
+
await self._dispatch(str(payload.get("t") or ""), data)
|
|
488
|
+
finally:
|
|
489
|
+
if heartbeat is not None:
|
|
490
|
+
heartbeat.cancel()
|
|
491
|
+
|
|
492
|
+
@staticmethod
|
|
493
|
+
def identify_payload(token: str) -> dict:
|
|
494
|
+
"""认证帧。`token` 前面必须带 `QQBot ` 前缀,少了平台直接拒。"""
|
|
495
|
+
return {"op": 2, "d": {
|
|
496
|
+
"token": "QQBot %s" % token,
|
|
497
|
+
"intents": INTENT_GROUP_AND_C2C,
|
|
498
|
+
"shard": [0, 1],
|
|
499
|
+
"properties": {},
|
|
500
|
+
}}
|
|
501
|
+
|
|
502
|
+
@staticmethod
|
|
503
|
+
def message_body(content: str, reply_id: str = "", seq: int = 0) -> dict:
|
|
504
|
+
"""一条文本消息的请求体。带 reply_id 就是被动回复,不带就是主动消息。"""
|
|
505
|
+
body: dict[str, Any] = {"content": content, "msg_type": 0}
|
|
506
|
+
if reply_id:
|
|
507
|
+
body["msg_id"] = reply_id
|
|
508
|
+
body["msg_seq"] = int(seq or 1)
|
|
509
|
+
return body
|
|
510
|
+
|
|
511
|
+
@staticmethod
|
|
512
|
+
def file_upload_payload(data: bytes, name: str) -> dict:
|
|
513
|
+
"""素材上传的请求体(文件那一类)。
|
|
514
|
+
|
|
515
|
+
`srv_send_msg: False` = 只传素材、不立刻发一条 —— 拿回 `file_info`
|
|
516
|
+
之后再发媒体消息,这样那条消息能挂上被动回复的 `msg_id`。
|
|
517
|
+
|
|
518
|
+
形状单独留一处:探针(`scripts/probe_qq_bot.py`)也用它,
|
|
519
|
+
两边各写一份的话,真机上验过的就不是通道发出去的那一份了。
|
|
520
|
+
"""
|
|
521
|
+
import base64
|
|
522
|
+
|
|
523
|
+
return {"file_type": 4,
|
|
524
|
+
"file_data": base64.b64encode(data).decode("ascii"),
|
|
525
|
+
"srv_send_msg": False,
|
|
526
|
+
"file_name": name}
|
|
527
|
+
|
|
528
|
+
@staticmethod
|
|
529
|
+
def media_message_body(file_info: str, reply_id: str = "",
|
|
530
|
+
seq: int = 0) -> dict:
|
|
531
|
+
"""一条文件消息的请求体(`msg_type=7` + `file_info`)。"""
|
|
532
|
+
body: dict[str, Any] = {"content": "", "msg_type": 7,
|
|
533
|
+
"media": {"file_info": file_info}}
|
|
534
|
+
if reply_id:
|
|
535
|
+
body["msg_id"] = reply_id
|
|
536
|
+
body["msg_seq"] = int(seq or 1)
|
|
537
|
+
return body
|
|
538
|
+
|
|
539
|
+
async def _identify(self, ws, token: str) -> None:
|
|
540
|
+
await ws.send_str(json.dumps(self.identify_payload(token)))
|
|
541
|
+
|
|
542
|
+
async def _heartbeat_loop(self, ws, interval: float) -> None:
|
|
543
|
+
"""每隔 interval 秒发一次心跳,带上最后一次收到的事件序号。"""
|
|
544
|
+
try:
|
|
545
|
+
while True:
|
|
546
|
+
await asyncio.sleep(interval)
|
|
547
|
+
await ws.send_str(json.dumps({"op": 1, "d": self._seq}))
|
|
548
|
+
except asyncio.CancelledError:
|
|
549
|
+
raise
|
|
550
|
+
except Exception as exc:
|
|
551
|
+
print("[qq_bot] 心跳停了(%s: %s)" % (type(exc).__name__, exc))
|
|
552
|
+
|
|
553
|
+
async def _dispatch(self, event_type: str, data: dict) -> None:
|
|
554
|
+
if event_type == "READY":
|
|
555
|
+
user = data.get("user") or {}
|
|
556
|
+
self._bot_openid = str(user.get("id") or "")
|
|
557
|
+
print("[qq_bot] 已连接(bot id=%s)" % (self._bot_openid or "?"))
|
|
558
|
+
try:
|
|
559
|
+
from core import incidents as _inc
|
|
560
|
+
_inc.resolve("qq_bot_channel", "channel")
|
|
561
|
+
except Exception:
|
|
562
|
+
pass
|
|
563
|
+
return
|
|
564
|
+
if event_type not in ("C2C_MESSAGE_CREATE", "GROUP_AT_MESSAGE_CREATE"):
|
|
565
|
+
return
|
|
566
|
+
try:
|
|
567
|
+
await self._handle_message(event_type, data)
|
|
568
|
+
except Exception as exc:
|
|
569
|
+
print("[qq_bot] 处理消息出错(%s: %s)" % (type(exc).__name__, exc))
|
|
570
|
+
|
|
571
|
+
# 入站
|
|
572
|
+
|
|
573
|
+
async def _handle_message(self, event_type: str, data: dict) -> None:
|
|
574
|
+
msg_id = str(data.get("id") or "")
|
|
575
|
+
if not self._seen.first_time(msg_id):
|
|
576
|
+
return
|
|
577
|
+
|
|
578
|
+
if event_type == "GROUP_AT_MESSAGE_CREATE":
|
|
579
|
+
scope = "group"
|
|
580
|
+
target_id = str(data.get("group_openid") or "")
|
|
581
|
+
author = data.get("author") or {}
|
|
582
|
+
sender_id = str(author.get("member_openid") or author.get("id") or "")
|
|
583
|
+
sender_name = str(author.get("member_openid") or "")
|
|
584
|
+
message_type = MessageType.GROUP
|
|
585
|
+
else:
|
|
586
|
+
scope = "c2c"
|
|
587
|
+
target_id = _c2c_openid(data)
|
|
588
|
+
sender_id = target_id
|
|
589
|
+
sender_name = str((data.get("author") or {}).get("username")
|
|
590
|
+
or (data.get("from_user") or {}).get("username")
|
|
591
|
+
or "")
|
|
592
|
+
message_type = MessageType.PRIVATE
|
|
593
|
+
|
|
594
|
+
if not target_id:
|
|
595
|
+
#: 只打键名,不打值 —— 那些值里是用户的 openid。
|
|
596
|
+
#: 打出来是为了下一次现场能把它补进 `_c2c_openid` 那张表。
|
|
597
|
+
print("[qq_bot] 这条事件没有回话对象,跳过(t=%s,顶层键=%s)"
|
|
598
|
+
% (event_type, ",".join(sorted(str(k) for k in data))))
|
|
599
|
+
return
|
|
600
|
+
|
|
601
|
+
media, undelivered = await self._download_attachments(
|
|
602
|
+
data.get("attachments") or [])
|
|
603
|
+
enriched = dict(data)
|
|
604
|
+
#: 下不下来的那几条要让模型知道 —— 静默丢掉会让它对着空气说话。
|
|
605
|
+
enriched["_undelivered"] = undelivered
|
|
606
|
+
chain = self._converter.to_internal(enriched, media=media)
|
|
607
|
+
if chain.is_empty:
|
|
608
|
+
return
|
|
609
|
+
|
|
610
|
+
session = MessageSession(
|
|
611
|
+
platform=self.meta().name,
|
|
612
|
+
message_type=message_type,
|
|
613
|
+
session_id=target_id,
|
|
614
|
+
)
|
|
615
|
+
self._budget.remember(str(session), scope, msg_id)
|
|
616
|
+
|
|
617
|
+
text = chain.content[:80] if chain.content else "[媒体]"
|
|
618
|
+
print("[qq_bot] %s 收到消息:%s" % (scope, text))
|
|
619
|
+
|
|
620
|
+
message = Message(
|
|
621
|
+
sender_id=sender_id,
|
|
622
|
+
sender_name=sender_name,
|
|
623
|
+
message_chain=chain,
|
|
624
|
+
message_type=message_type,
|
|
625
|
+
session=session,
|
|
626
|
+
#: 平台消息号。管线用它去重,不传那道闸就恒不触发。
|
|
627
|
+
message_id=msg_id,
|
|
628
|
+
)
|
|
629
|
+
event = self.commit_event(message)
|
|
630
|
+
|
|
631
|
+
if not self._scheduler:
|
|
632
|
+
return
|
|
633
|
+
|
|
634
|
+
async def _on_reply(reply: str) -> None:
|
|
635
|
+
await self._reply_and_drain(session, scope, target_id, msg_id, reply)
|
|
636
|
+
|
|
637
|
+
await channel_turns.intake(self, event, on_reply=_on_reply)
|
|
638
|
+
|
|
639
|
+
async def _download_attachments(self, items: list) -> tuple[list, list]:
|
|
640
|
+
"""把附件下到本地,返回 `([(条目, 路径)], [没下下来的条目])`。
|
|
641
|
+
|
|
642
|
+
一个异常都不许漏出去:漏出去整条消息连管线都进不去。
|
|
643
|
+
"""
|
|
644
|
+
media: list[tuple[dict, str]] = []
|
|
645
|
+
undelivered: list = []
|
|
646
|
+
for item in items:
|
|
647
|
+
url = str((item or {}).get("url") or "")
|
|
648
|
+
if not url:
|
|
649
|
+
undelivered.append(item)
|
|
650
|
+
continue
|
|
651
|
+
try:
|
|
652
|
+
path = await self._download_one(item, url)
|
|
653
|
+
except Exception as exc:
|
|
654
|
+
print("[qq_bot] 下载附件失败(%s: %s)"
|
|
655
|
+
% (type(exc).__name__, exc))
|
|
656
|
+
path = ""
|
|
657
|
+
if path:
|
|
658
|
+
media.append((item, path))
|
|
659
|
+
else:
|
|
660
|
+
undelivered.append(item)
|
|
661
|
+
return media, undelivered
|
|
662
|
+
|
|
663
|
+
async def _download_one(self, item: dict, url: str) -> str:
|
|
664
|
+
size = int((item or {}).get("size") or 0)
|
|
665
|
+
if size > _MAX_DOWNLOAD_BYTES:
|
|
666
|
+
print("[qq_bot] 附件太大(%d 字节),不下载" % size)
|
|
667
|
+
return ""
|
|
668
|
+
name = str((item or {}).get("filename") or "")
|
|
669
|
+
suffix = Path(name).suffix or ".bin"
|
|
670
|
+
# 目录在这里建、不在 `__init__` 里建:通道对象启动时就会构造,
|
|
671
|
+
# 在那时候建目录,任何"只是把通道导进来"的地方都会往工作目录里落一个空夹。
|
|
672
|
+
_TEMP_DIR.mkdir(parents=True, exist_ok=True)
|
|
673
|
+
dest = _TEMP_DIR / ("%s%s" % (time.strftime("%Y%m%d%H%M%S"), suffix))
|
|
674
|
+
async with self._session.get(url, proxy=self._proxy or None) as resp:
|
|
675
|
+
if resp.status != 200:
|
|
676
|
+
return ""
|
|
677
|
+
data = await resp.read()
|
|
678
|
+
if len(data) > _MAX_DOWNLOAD_BYTES:
|
|
679
|
+
return ""
|
|
680
|
+
dest.write_bytes(data)
|
|
681
|
+
return str(dest)
|
|
682
|
+
|
|
683
|
+
# 出站
|
|
684
|
+
|
|
685
|
+
async def _reply_and_drain(self, session: MessageSession, scope: str,
|
|
686
|
+
target_id: str, msg_id: str,
|
|
687
|
+
response: str | None) -> None:
|
|
688
|
+
"""先回话,再把本轮登记的文件发出去。
|
|
689
|
+
|
|
690
|
+
顺序是判据:用户先看到那句话,再收到附件。取件放在 finally 里,
|
|
691
|
+
发送这一段抛了文件也照样走。
|
|
692
|
+
"""
|
|
693
|
+
try:
|
|
694
|
+
if response:
|
|
695
|
+
await self._send_text(scope, target_id, response, msg_id)
|
|
696
|
+
finally:
|
|
697
|
+
try:
|
|
698
|
+
await self._drain_delivered(session)
|
|
699
|
+
except Exception as exc:
|
|
700
|
+
print("[qq_bot] 发待交付文件时出错(%s: %s)"
|
|
701
|
+
% (type(exc).__name__, exc))
|
|
702
|
+
|
|
703
|
+
async def _send_text(self, scope: str, target_id: str, text: str,
|
|
704
|
+
msg_id: str = "") -> bool:
|
|
705
|
+
chunks = _split_text(text, MAX_MESSAGE_LENGTH)
|
|
706
|
+
total = len(chunks)
|
|
707
|
+
ok = True
|
|
708
|
+
for i, chunk in enumerate(chunks, 1):
|
|
709
|
+
body = chunk if total == 1 else "(%d/%d)\n%s" % (i, total, chunk)
|
|
710
|
+
if not await self._send_one(scope, target_id, body, msg_id):
|
|
711
|
+
ok = False
|
|
712
|
+
return ok
|
|
713
|
+
|
|
714
|
+
async def _send_one(self, scope: str, target_id: str, content: str,
|
|
715
|
+
msg_id: str = "") -> bool:
|
|
716
|
+
"""发一条纯文本。被动配额用完就退回主动消息,两条路都算发送。"""
|
|
717
|
+
reply, seq = self._budget.reserve(scope, msg_id)
|
|
718
|
+
payload = self.message_body(content, reply, seq)
|
|
719
|
+
url = "%s/v2/%s/%s/messages" % (
|
|
720
|
+
self._api_base,
|
|
721
|
+
"users" if scope == "c2c" else "groups",
|
|
722
|
+
target_id,
|
|
723
|
+
)
|
|
724
|
+
try:
|
|
725
|
+
token = await self._tokens.current(self._session)
|
|
726
|
+
headers = {"Authorization": "QQBot %s" % token,
|
|
727
|
+
"Content-Type": "application/json"}
|
|
728
|
+
async with self._session.post(url, json=payload, headers=headers,
|
|
729
|
+
proxy=self._proxy or None) as resp:
|
|
730
|
+
if resp.status in (200, 201, 202):
|
|
731
|
+
return True
|
|
732
|
+
status, body = resp.status, await resp.text()
|
|
733
|
+
print("[qq_bot] 发送被拒(%d):%s" % (status, body[:200]))
|
|
734
|
+
return False
|
|
735
|
+
except Exception as exc:
|
|
736
|
+
print("[qq_bot] 发送失败(%s: %s)" % (type(exc).__name__, exc))
|
|
737
|
+
return False
|
|
738
|
+
|
|
739
|
+
async def send(self, session: MessageSession, content: str | MessageChain) -> bool:
|
|
740
|
+
"""没有上下文的一条回复(定时任务、后台回报)。
|
|
741
|
+
|
|
742
|
+
拿得到这个会话最近那条消息就按被动回复发,拿不到就发主动消息。
|
|
743
|
+
"""
|
|
744
|
+
text = content if isinstance(content, str) else content.content
|
|
745
|
+
scope = "group" if session.message_type is MessageType.GROUP else "c2c"
|
|
746
|
+
msg_id, _ = self._budget.last_for(str(session))
|
|
747
|
+
return await self._send_text(scope, str(session.session_id), text, msg_id)
|
|
748
|
+
|
|
749
|
+
async def send_note(self, session: MessageSession, text: str,
|
|
750
|
+
event=None) -> bool:
|
|
751
|
+
"""一句旁白。不能走 `send()`:那个会顺手把本轮待交付文件发掉,
|
|
752
|
+
用户会先看到文件再看到回答。
|
|
753
|
+
"""
|
|
754
|
+
scope = "group" if session.message_type is MessageType.GROUP else "c2c"
|
|
755
|
+
msg_id, _ = self._budget.last_for(str(session))
|
|
756
|
+
return await self._send_text(scope, str(session.session_id), text, msg_id)
|
|
757
|
+
|
|
758
|
+
async def send_media_file(self, session: MessageSession, file_path: str,
|
|
759
|
+
filename: str = "", context_token: str = "") -> bool:
|
|
760
|
+
"""发一个本地文件:先传素材拿 file_info,再发一条媒体消息。
|
|
761
|
+
|
|
762
|
+
返回 False 不算送达。上传接口对文件类型有白名单,失败时如实说。
|
|
763
|
+
"""
|
|
764
|
+
path = Path(file_path or "")
|
|
765
|
+
if not path.is_file():
|
|
766
|
+
print("[qq_bot] 要发的文件不存在:%s" % file_path)
|
|
767
|
+
return False
|
|
768
|
+
scope = "group" if session.message_type is MessageType.GROUP else "c2c"
|
|
769
|
+
target_id = str(session.session_id)
|
|
770
|
+
name = filename or path.name
|
|
771
|
+
url = "%s/v2/%s/%s/files" % (
|
|
772
|
+
self._api_base, "users" if scope == "c2c" else "groups", target_id)
|
|
773
|
+
try:
|
|
774
|
+
token = await self._tokens.current(self._session)
|
|
775
|
+
headers = {"Authorization": "QQBot %s" % token,
|
|
776
|
+
"Content-Type": "application/json"}
|
|
777
|
+
#: file_type 4 = 文件。素材要先传上去,平台不接受本地路径。
|
|
778
|
+
payload = self.file_upload_payload(path.read_bytes(), name)
|
|
779
|
+
async with self._session.post(url, json=payload, headers=headers,
|
|
780
|
+
proxy=self._proxy or None) as resp:
|
|
781
|
+
if resp.status not in (200, 201, 202):
|
|
782
|
+
status, body = resp.status, await resp.text()
|
|
783
|
+
print("[qq_bot] 上传文件被拒(%d):%s" % (status, body[:200]))
|
|
784
|
+
return False
|
|
785
|
+
info = await resp.json(content_type=None)
|
|
786
|
+
except Exception as exc:
|
|
787
|
+
print("[qq_bot] 上传文件失败(%s: %s)" % (type(exc).__name__, exc))
|
|
788
|
+
return False
|
|
789
|
+
|
|
790
|
+
file_info = str((info or {}).get("file_info") or "")
|
|
791
|
+
if not file_info:
|
|
792
|
+
print("[qq_bot] 上传成功但没拿到 file_info,没法发消息")
|
|
793
|
+
return False
|
|
794
|
+
|
|
795
|
+
msg_id, _ = self._budget.last_for(str(session))
|
|
796
|
+
reply, seq = self._budget.reserve(scope, msg_id)
|
|
797
|
+
msg = self.media_message_body(file_info, reply, seq)
|
|
798
|
+
api = "%s/v2/%s/%s/messages" % (
|
|
799
|
+
self._api_base, "users" if scope == "c2c" else "groups", target_id)
|
|
800
|
+
try:
|
|
801
|
+
token = await self._tokens.current(self._session)
|
|
802
|
+
headers = {"Authorization": "QQBot %s" % token,
|
|
803
|
+
"Content-Type": "application/json"}
|
|
804
|
+
async with self._session.post(api, json=msg, headers=headers,
|
|
805
|
+
proxy=self._proxy or None) as resp:
|
|
806
|
+
if resp.status in (200, 201, 202):
|
|
807
|
+
return True
|
|
808
|
+
status, body = resp.status, await resp.text()
|
|
809
|
+
print("[qq_bot] 发送文件消息被拒(%d):%s" % (status, body[:200]))
|
|
810
|
+
return False
|
|
811
|
+
except Exception as exc:
|
|
812
|
+
print("[qq_bot] 发送文件消息失败(%s: %s)" % (type(exc).__name__, exc))
|
|
813
|
+
return False
|
|
814
|
+
|
|
815
|
+
async def _drain_delivered(self, session: MessageSession) -> int:
|
|
816
|
+
"""把本轮登记的文件发出去,返回真发出去的条数。
|
|
817
|
+
|
|
818
|
+
工具是同步的、不能 await 这个循环,所以它只登记;通道在回话之后
|
|
819
|
+
取走发掉。三格都要对上:会话键、通道名、用户 id。
|
|
820
|
+
"""
|
|
821
|
+
from core import delivery_outbox as _outbox
|
|
822
|
+
from core.session_key import session_key_for
|
|
823
|
+
|
|
824
|
+
try:
|
|
825
|
+
recs = _outbox.take_for(
|
|
826
|
+
session_key=session_key_for(session),
|
|
827
|
+
channel="qq_bot_channel",
|
|
828
|
+
user_id=str(getattr(session, "session_id", "") or ""))
|
|
829
|
+
except Exception as exc:
|
|
830
|
+
print("[qq_bot] 取待发文件失败(%s: %s)" % (type(exc).__name__, exc))
|
|
831
|
+
return 0
|
|
832
|
+
sent = 0
|
|
833
|
+
for rec in recs:
|
|
834
|
+
if await self.send_media_file(session, rec.get("path", ""),
|
|
835
|
+
rec.get("name", "")):
|
|
836
|
+
sent += 1
|
|
837
|
+
continue
|
|
838
|
+
await self.send_note(session, "文件 %s 没能发出去(原因在框架日志里)。"
|
|
839
|
+
% (rec.get("name") or "?"))
|
|
840
|
+
return sent
|
|
841
|
+
|
|
842
|
+
async def test_connection(self) -> dict:
|
|
843
|
+
"""问一次 /users/@me。连得上说明 token 与网络都通。"""
|
|
844
|
+
#: 同 `run()`:探活多半就是"刚填完凭据、按一下试试"的那一下。
|
|
845
|
+
self.refresh_credentials()
|
|
846
|
+
if not (self._app_id and self._app_secret):
|
|
847
|
+
return {"ok": False, "message": "没有配置 AppID / AppSecret"}
|
|
848
|
+
#: 每次都自建会话。探活是从别的线程(设置页那个请求)进来的,
|
|
849
|
+
#: 借通道自己那条会话会把两个事件循环缠在一起。
|
|
850
|
+
session = None
|
|
851
|
+
try:
|
|
852
|
+
import aiohttp
|
|
853
|
+
session = aiohttp.ClientSession()
|
|
854
|
+
tokens = _TokenManager(self._app_id, self._app_secret, self._token_url)
|
|
855
|
+
token = await tokens.current(session)
|
|
856
|
+
async with session.get(
|
|
857
|
+
self._api_base + "/users/@me",
|
|
858
|
+
headers={"Authorization": "QQBot %s" % token},
|
|
859
|
+
proxy=self._proxy or None) as resp:
|
|
860
|
+
if resp.status != 200:
|
|
861
|
+
body = await resp.text()
|
|
862
|
+
return {"ok": False, "message": "QQ 接口返回 %d:%s"
|
|
863
|
+
% (resp.status, body[:200])}
|
|
864
|
+
data = await resp.json(content_type=None) or {}
|
|
865
|
+
return {"ok": True, "message": "QQ 机器人:%s"
|
|
866
|
+
% (data.get("username") or data.get("id") or "已连接")}
|
|
867
|
+
except Exception as exc:
|
|
868
|
+
return {"ok": False, "message": "%s: %s" % (type(exc).__name__, exc)}
|
|
869
|
+
finally:
|
|
870
|
+
if session is not None:
|
|
871
|
+
await session.close()
|
|
872
|
+
|
|
873
|
+
async def terminate(self) -> None:
|
|
874
|
+
self._running = False
|
|
875
|
+
ws = self._ws
|
|
876
|
+
self._ws = None
|
|
877
|
+
if ws is not None:
|
|
878
|
+
try:
|
|
879
|
+
await ws.close()
|
|
880
|
+
except Exception:
|
|
881
|
+
pass
|