nonebot-plugin-aawfqq 0.23.1__py3-none-any.whl
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.
- nonebot_plugin_aawfqq/__init__.py +18 -0
- nonebot_plugin_aawfqq/media.py +50 -0
- nonebot_plugin_aawfqq/router.py +179 -0
- nonebot_plugin_aawfqq-0.23.1.dist-info/METADATA +7 -0
- nonebot_plugin_aawfqq-0.23.1.dist-info/RECORD +7 -0
- nonebot_plugin_aawfqq-0.23.1.dist-info/WHEEL +5 -0
- nonebot_plugin_aawfqq-0.23.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""AAWarframe QQ 官方插件:只负责事件、媒体与消息发送。"""
|
|
2
|
+
|
|
3
|
+
from nonebot import require
|
|
4
|
+
from nonebot.plugin import PluginMetadata
|
|
5
|
+
|
|
6
|
+
__plugin_meta__ = PluginMetadata(
|
|
7
|
+
name="aawfqq",
|
|
8
|
+
description="AAWarframe 官方 QQ 协议插件",
|
|
9
|
+
usage="使用帮助命令查看 Warframe 机器人支持的查询功能",
|
|
10
|
+
type="application",
|
|
11
|
+
supported_adapters={"~qq"},
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
require("nonebot_plugin_aawfcore")
|
|
15
|
+
|
|
16
|
+
from .router import setup # noqa: E402
|
|
17
|
+
|
|
18
|
+
setup()
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""QQ CDN 附件下载:只在协议层使用,禁止非 QQ 地址和重定向越域。"""
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
from urllib.parse import urljoin, urlsplit
|
|
5
|
+
|
|
6
|
+
import httpx
|
|
7
|
+
|
|
8
|
+
MAX_IMAGE_BYTES = 12 * 1024 * 1024
|
|
9
|
+
ALLOWED_DOMAINS = ("qq.com", "qq.com.cn", "qpic.cn")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
async def download_image(url: str) -> bytes | None:
|
|
13
|
+
async with httpx.AsyncClient(timeout=25) as client:
|
|
14
|
+
for _ in range(4):
|
|
15
|
+
parts = urlsplit(url)
|
|
16
|
+
domain = (parts.hostname or "").lower()
|
|
17
|
+
if (
|
|
18
|
+
parts.scheme not in {"http", "https"}
|
|
19
|
+
or not any(domain == item or domain.endswith("." + item) for item in ALLOWED_DOMAINS)
|
|
20
|
+
or parts.username or parts.password
|
|
21
|
+
or parts.port not in {None, 80, 443}
|
|
22
|
+
):
|
|
23
|
+
return None
|
|
24
|
+
async with client.stream("GET", url, follow_redirects=False) as response:
|
|
25
|
+
if response.is_redirect:
|
|
26
|
+
url = urljoin(url, response.headers.get("location", ""))
|
|
27
|
+
continue
|
|
28
|
+
response.raise_for_status()
|
|
29
|
+
declared = response.headers.get("content-length")
|
|
30
|
+
if declared and declared.isdecimal() and int(declared) > MAX_IMAGE_BYTES:
|
|
31
|
+
raise ValueError("图片超过 12 MB")
|
|
32
|
+
data = bytearray()
|
|
33
|
+
async for chunk in response.aiter_bytes(chunk_size=65536):
|
|
34
|
+
data.extend(chunk)
|
|
35
|
+
if len(data) > MAX_IMAGE_BYTES:
|
|
36
|
+
raise ValueError("图片超过 12 MB")
|
|
37
|
+
return bytes(data)
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def decode_inline(value: str) -> bytes | None:
|
|
42
|
+
if not value.startswith("base64://"):
|
|
43
|
+
return None
|
|
44
|
+
encoded = value[len("base64://"):]
|
|
45
|
+
if len(encoded) > (MAX_IMAGE_BYTES + 2) // 3 * 4 + 16:
|
|
46
|
+
raise ValueError("图片超过 12 MB")
|
|
47
|
+
image = base64.b64decode(encoded, validate=True)
|
|
48
|
+
if len(image) > MAX_IMAGE_BYTES:
|
|
49
|
+
raise ValueError("图片超过 12 MB")
|
|
50
|
+
return image
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""QQ 官方消息事件和收发。所有业务判断、渲染和订阅存储在 core。"""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import base64
|
|
5
|
+
import logging
|
|
6
|
+
|
|
7
|
+
from nonebot import get_bots, get_driver, on_message
|
|
8
|
+
from nonebot.adapters import Bot, Event
|
|
9
|
+
from nonebot.adapters.qq import Message, MessageSegment
|
|
10
|
+
from nonebot.matcher import Matcher
|
|
11
|
+
from nonebot.typing import T_State
|
|
12
|
+
from nonebot_plugin_aawfcore.client import CoreClient, decode_image
|
|
13
|
+
|
|
14
|
+
from .media import download_image
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
client = CoreClient()
|
|
18
|
+
task: asyncio.Task | None = None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def session(bot: Bot, event: Event):
|
|
22
|
+
if group := getattr(event, "group_openid", None):
|
|
23
|
+
return str(bot.self_id), "qq-group:" + str(group), event.get_user_id()
|
|
24
|
+
if getattr(event, "channel_id", None) and getattr(event, "guild_id", None):
|
|
25
|
+
return (
|
|
26
|
+
str(bot.self_id), "qq-channel:" + str(event.channel_id), event.get_user_id()
|
|
27
|
+
)
|
|
28
|
+
return str(bot.self_id), None, event.get_user_id()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
async def event_image(event: Event) -> bytes:
|
|
32
|
+
message = event.get_message()
|
|
33
|
+
images = [segment for segment in message if segment.type == "image"]
|
|
34
|
+
if not images:
|
|
35
|
+
quoted = getattr(event, "get_reply_message", lambda: None)()
|
|
36
|
+
images = [segment for segment in quoted if segment.type == "image"] if quoted else []
|
|
37
|
+
if len(images) != 1:
|
|
38
|
+
raise ValueError("请附上或引用一张紫卡图片。")
|
|
39
|
+
url = images[0].data.get("url")
|
|
40
|
+
if not isinstance(url, str):
|
|
41
|
+
raise ValueError("图片地址不可用,请重新发送。")
|
|
42
|
+
content = await download_image(url)
|
|
43
|
+
if not content:
|
|
44
|
+
raise ValueError("无法下载紫卡图片,请重新发送。")
|
|
45
|
+
return content
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def pages(segments: list[dict]) -> list[Message]:
|
|
49
|
+
"""QQ 官方一个发送请求只带一张媒体;多张图片按顺序拆分。"""
|
|
50
|
+
result, message, media = [], Message(), False
|
|
51
|
+
for part in segments:
|
|
52
|
+
kind = part["type"]
|
|
53
|
+
if kind == "image":
|
|
54
|
+
if media:
|
|
55
|
+
result.append(message)
|
|
56
|
+
message, media = Message(), False
|
|
57
|
+
message += MessageSegment.file_image(decode_image(part))
|
|
58
|
+
media = True
|
|
59
|
+
elif kind == "text":
|
|
60
|
+
message += MessageSegment.text(part["text"])
|
|
61
|
+
elif kind == "at":
|
|
62
|
+
message += MessageSegment.mention_user(part["user_id"])
|
|
63
|
+
elif kind == "reply":
|
|
64
|
+
message += MessageSegment.reference(part["message_id"])
|
|
65
|
+
else:
|
|
66
|
+
raise ValueError(f"不支持的 QQ 消息段:{kind}")
|
|
67
|
+
if message:
|
|
68
|
+
result.append(message)
|
|
69
|
+
return result
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
async def accept(bot: Bot, event: Event, matcher: Matcher, state: T_State):
|
|
73
|
+
bot_id, group_id, user_id = session(bot, event)
|
|
74
|
+
|
|
75
|
+
async def execute_query():
|
|
76
|
+
image_base64 = None
|
|
77
|
+
if state["aawf_feature"] == "riven_analysis":
|
|
78
|
+
async with client.ocr_download():
|
|
79
|
+
image_base64 = base64.b64encode(await event_image(event)).decode("ascii")
|
|
80
|
+
return await client.query(
|
|
81
|
+
feature=state["aawf_feature"], arguments=state["aawf_arguments"],
|
|
82
|
+
bot_id=bot_id, group_id=group_id, user_id=user_id,
|
|
83
|
+
image_base64=image_base64,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
try:
|
|
87
|
+
if state["aawf_feature"] == "riven_analysis":
|
|
88
|
+
# Reserve BEFORE any network operation or reply lookup.
|
|
89
|
+
async with client.ocr_admission():
|
|
90
|
+
result = await execute_query()
|
|
91
|
+
else:
|
|
92
|
+
result = await execute_query()
|
|
93
|
+
for page in pages(result["segments"]):
|
|
94
|
+
await bot.send(event, page)
|
|
95
|
+
except ValueError as exc:
|
|
96
|
+
await bot.send(event, MessageSegment.text(str(exc)))
|
|
97
|
+
except Exception:
|
|
98
|
+
logger.exception("QQ 官方回复失败")
|
|
99
|
+
try:
|
|
100
|
+
await bot.send(event, MessageSegment.text("查询暂不可用,请稍后重试。"))
|
|
101
|
+
except Exception:
|
|
102
|
+
logger.warning("QQ 官方文本回退失败,可能超出回复窗口", exc_info=True)
|
|
103
|
+
await matcher.finish()
|
|
104
|
+
|
|
105
|
+
async def deliver(bot: Bot, delivery: dict):
|
|
106
|
+
contents = pages(delivery["segments"])
|
|
107
|
+
target = delivery["group_id"]
|
|
108
|
+
if target.startswith("qq-group:"):
|
|
109
|
+
for page in contents:
|
|
110
|
+
await bot.send_to_group(group_openid=target[len("qq-group:"):], message=page)
|
|
111
|
+
elif target.startswith("qq-channel:"):
|
|
112
|
+
for page in contents:
|
|
113
|
+
await bot.send_to_channel(channel_id=target[len("qq-channel:"):], message=page)
|
|
114
|
+
else:
|
|
115
|
+
raise ValueError("不是 QQ 官方会话")
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
async def notifications():
|
|
119
|
+
while True:
|
|
120
|
+
try:
|
|
121
|
+
bots = {
|
|
122
|
+
str(bot.self_id): bot for bot in get_bots().values()
|
|
123
|
+
if getattr(bot, "type", None) == "QQ"
|
|
124
|
+
}
|
|
125
|
+
if bots:
|
|
126
|
+
for item in await client.claim(list(bots), protocol="qq"):
|
|
127
|
+
try:
|
|
128
|
+
await deliver(bots[item["bot_id"]], item)
|
|
129
|
+
except asyncio.CancelledError:
|
|
130
|
+
raise
|
|
131
|
+
except Exception as exc:
|
|
132
|
+
logger.warning("QQ 官方订阅推送失败", exc_info=True)
|
|
133
|
+
await client.ack(item["id"], ok=False, error=type(exc).__name__)
|
|
134
|
+
else:
|
|
135
|
+
await client.ack(item["id"], ok=True)
|
|
136
|
+
except asyncio.CancelledError:
|
|
137
|
+
raise
|
|
138
|
+
except Exception:
|
|
139
|
+
logger.exception("QQ 官方订阅推送轮询异常")
|
|
140
|
+
await asyncio.sleep(5)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def setup():
|
|
144
|
+
async def rule(bot: Bot, event: Event, state: T_State) -> bool:
|
|
145
|
+
if getattr(bot, "type", None) != "QQ":
|
|
146
|
+
return False
|
|
147
|
+
_, group_id, user_id = session(bot, event)
|
|
148
|
+
try:
|
|
149
|
+
route = await client.route(
|
|
150
|
+
text=event.get_plaintext(), starts=list(get_driver().config.command_start),
|
|
151
|
+
user_id=user_id, group_id=group_id,
|
|
152
|
+
)
|
|
153
|
+
except Exception:
|
|
154
|
+
logger.exception("核心 API 命令匹配失败")
|
|
155
|
+
return False
|
|
156
|
+
if not route["matched"]:
|
|
157
|
+
return False
|
|
158
|
+
state["aawf_feature"] = route["feature"]
|
|
159
|
+
state["aawf_arguments"] = route["arguments"]
|
|
160
|
+
return True
|
|
161
|
+
|
|
162
|
+
matcher = on_message(rule=rule, block=True, priority=10)
|
|
163
|
+
matcher.handle()(accept)
|
|
164
|
+
|
|
165
|
+
driver = get_driver()
|
|
166
|
+
|
|
167
|
+
@driver.on_startup
|
|
168
|
+
async def startup():
|
|
169
|
+
global task
|
|
170
|
+
task = asyncio.create_task(notifications())
|
|
171
|
+
|
|
172
|
+
@driver.on_shutdown
|
|
173
|
+
async def shutdown():
|
|
174
|
+
global task
|
|
175
|
+
if task is not None:
|
|
176
|
+
task.cancel()
|
|
177
|
+
await asyncio.gather(task, return_exceptions=True)
|
|
178
|
+
task = None
|
|
179
|
+
await client.close()
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
nonebot_plugin_aawfqq/__init__.py,sha256=OzJWqnZzI6f1ikeoBXzFg-1L4BUJ0roXLoceo0VPFyk,478
|
|
2
|
+
nonebot_plugin_aawfqq/media.py,sha256=kxDp_zpQohUmh7Y2PzAzxm7zjvPC1PrtRzGHupyicnQ,2015
|
|
3
|
+
nonebot_plugin_aawfqq/router.py,sha256=gVfs7EzruZYAWYIznCmxzqKagSsPhqCgd4yA5PEhM3U,6677
|
|
4
|
+
nonebot_plugin_aawfqq-0.23.1.dist-info/METADATA,sha256=TdRfW5_9bmtpZAXHMGyRgsk7ZfqYho4wOh7cHfadjoY,254
|
|
5
|
+
nonebot_plugin_aawfqq-0.23.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
6
|
+
nonebot_plugin_aawfqq-0.23.1.dist-info/top_level.txt,sha256=_1bUiWTjSMPG8FCAo8Es87jDRmidNDwCU6_EcNr6pvg,22
|
|
7
|
+
nonebot_plugin_aawfqq-0.23.1.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
nonebot_plugin_aawfqq
|