nonebot-plugin-aawfcore 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.
Files changed (151) hide show
  1. nonebot_plugin_aawfcore/__init__.py +24 -0
  2. nonebot_plugin_aawfcore/admin/__init__.py +3 -0
  3. nonebot_plugin_aawfcore/admin/control.py +206 -0
  4. nonebot_plugin_aawfcore/admin/server.py +284 -0
  5. nonebot_plugin_aawfcore/admin/static/app.js +56 -0
  6. nonebot_plugin_aawfcore/admin/static/index.html +14 -0
  7. nonebot_plugin_aawfcore/admin/static/style.css +2 -0
  8. nonebot_plugin_aawfcore/api.py +151 -0
  9. nonebot_plugin_aawfcore/assets/offline.tar.gz +0 -0
  10. nonebot_plugin_aawfcore/bootstrap.py +164 -0
  11. nonebot_plugin_aawfcore/client.py +79 -0
  12. nonebot_plugin_aawfcore/commands/__init__.py +3 -0
  13. nonebot_plugin_aawfcore/commands/parsing.py +176 -0
  14. nonebot_plugin_aawfcore/commands/router.py +119 -0
  15. nonebot_plugin_aawfcore/config.py +28 -0
  16. nonebot_plugin_aawfcore/grq/__init__.py +8 -0
  17. nonebot_plugin_aawfcore/grq/catalog.py +86 -0
  18. nonebot_plugin_aawfcore/grq/index.py +95 -0
  19. nonebot_plugin_aawfcore/grq/json_store.py +83 -0
  20. nonebot_plugin_aawfcore/grq/links.py +146 -0
  21. nonebot_plugin_aawfcore/grq/manager.py +472 -0
  22. nonebot_plugin_aawfcore/grq/models.py +56 -0
  23. nonebot_plugin_aawfcore/grq/normalizer.py +39 -0
  24. nonebot_plugin_aawfcore/grq/patches.py +17 -0
  25. nonebot_plugin_aawfcore/grq/registry.py +89 -0
  26. nonebot_plugin_aawfcore/grq/rewards.py +72 -0
  27. nonebot_plugin_aawfcore/grq/search.py +56 -0
  28. nonebot_plugin_aawfcore/grq/sources.py +294 -0
  29. nonebot_plugin_aawfcore/grq/storage.py +24 -0
  30. nonebot_plugin_aawfcore/infrastructure/__init__.py +3 -0
  31. nonebot_plugin_aawfcore/infrastructure/cache.py +68 -0
  32. nonebot_plugin_aawfcore/infrastructure/http.py +103 -0
  33. nonebot_plugin_aawfcore/infrastructure/images.py +55 -0
  34. nonebot_plugin_aawfcore/infrastructure/ocr_worker.py +112 -0
  35. nonebot_plugin_aawfcore/infrastructure/riven_ocr.py +128 -0
  36. nonebot_plugin_aawfcore/infrastructure/storage.py +34 -0
  37. nonebot_plugin_aawfcore/infrastructure/wiki_http.py +142 -0
  38. nonebot_plugin_aawfcore/infrastructure/wiki_transport.py +47 -0
  39. nonebot_plugin_aawfcore/initialization/__init__.py +3 -0
  40. nonebot_plugin_aawfcore/initialization/market.py +59 -0
  41. nonebot_plugin_aawfcore/initialization/nodes.py +55 -0
  42. nonebot_plugin_aawfcore/initialization/pipeline.py +285 -0
  43. nonebot_plugin_aawfcore/initialization/rules.py +247 -0
  44. nonebot_plugin_aawfcore/initialization/wfcd.py +129 -0
  45. nonebot_plugin_aawfcore/localization/__init__.py +3 -0
  46. nonebot_plugin_aawfcore/localization/relics.py +115 -0
  47. nonebot_plugin_aawfcore/localization/resolver.py +57 -0
  48. nonebot_plugin_aawfcore/localization/resources.py +68 -0
  49. nonebot_plugin_aawfcore/localization/riven_attributes.py +62 -0
  50. nonebot_plugin_aawfcore/localization/rivens.py +53 -0
  51. nonebot_plugin_aawfcore/models/__init__.py +3 -0
  52. nonebot_plugin_aawfcore/models/arbitration.py +25 -0
  53. nonebot_plugin_aawfcore/models/bounties.py +43 -0
  54. nonebot_plugin_aawfcore/models/common.py +251 -0
  55. nonebot_plugin_aawfcore/models/errors.py +11 -0
  56. nonebot_plugin_aawfcore/models/market.py +86 -0
  57. nonebot_plugin_aawfcore/models/operations.py +40 -0
  58. nonebot_plugin_aawfcore/models/relics.py +37 -0
  59. nonebot_plugin_aawfcore/models/riven_market.py +34 -0
  60. nonebot_plugin_aawfcore/models/riven_values.py +20 -0
  61. nonebot_plugin_aawfcore/models/rivens.py +51 -0
  62. nonebot_plugin_aawfcore/models/trend.py +48 -0
  63. nonebot_plugin_aawfcore/models/void_trader.py +42 -0
  64. nonebot_plugin_aawfcore/models/wiki.py +41 -0
  65. nonebot_plugin_aawfcore/models/worldstate.py +176 -0
  66. nonebot_plugin_aawfcore/protocols/__init__.py +1 -0
  67. nonebot_plugin_aawfcore/protocols/message.py +71 -0
  68. nonebot_plugin_aawfcore/protocols/qq.py +181 -0
  69. nonebot_plugin_aawfcore/providers/__init__.py +3 -0
  70. nonebot_plugin_aawfcore/providers/market.py +150 -0
  71. nonebot_plugin_aawfcore/providers/riven_market.py +39 -0
  72. nonebot_plugin_aawfcore/providers/rivens.py +99 -0
  73. nonebot_plugin_aawfcore/providers/wiki.py +44 -0
  74. nonebot_plugin_aawfcore/providers/worldstate.py +35 -0
  75. nonebot_plugin_aawfcore/rendering/__init__.py +3 -0
  76. nonebot_plugin_aawfcore/rendering/assets/css/base.css +274 -0
  77. nonebot_plugin_aawfcore/rendering/assets/css/relics.css +15 -0
  78. nonebot_plugin_aawfcore/rendering/assets/css/riven_analysis.css +14 -0
  79. nonebot_plugin_aawfcore/rendering/assets/css/riven_market.css +10 -0
  80. nonebot_plugin_aawfcore/rendering/assets/css/riven_values.css +13 -0
  81. nonebot_plugin_aawfcore/rendering/assets/css/themes/default.css +10 -0
  82. nonebot_plugin_aawfcore/rendering/assets/css/trader.css +12 -0
  83. nonebot_plugin_aawfcore/rendering/assets/css/trend.css +15 -0
  84. nonebot_plugin_aawfcore/rendering/charts.py +47 -0
  85. nonebot_plugin_aawfcore/rendering/renderer.py +396 -0
  86. nonebot_plugin_aawfcore/rendering/templates/arbitration.html +12 -0
  87. nonebot_plugin_aawfcore/rendering/templates/archimedea.html +25 -0
  88. nonebot_plugin_aawfcore/rendering/templates/attributes.html +12 -0
  89. nonebot_plugin_aawfcore/rendering/templates/base.html +26 -0
  90. nonebot_plugin_aawfcore/rendering/templates/bounties.html +33 -0
  91. nonebot_plugin_aawfcore/rendering/templates/bounty_rewards.html +7 -0
  92. nonebot_plugin_aawfcore/rendering/templates/card.html +29 -0
  93. nonebot_plugin_aawfcore/rendering/templates/challenge_bounties.html +16 -0
  94. nonebot_plugin_aawfcore/rendering/templates/commands.html +8 -0
  95. nonebot_plugin_aawfcore/rendering/templates/fissures.html +42 -0
  96. nonebot_plugin_aawfcore/rendering/templates/market.html +26 -0
  97. nonebot_plugin_aawfcore/rendering/templates/nightwave.html +18 -0
  98. nonebot_plugin_aawfcore/rendering/templates/operations.html +38 -0
  99. nonebot_plugin_aawfcore/rendering/templates/relics.html +28 -0
  100. nonebot_plugin_aawfcore/rendering/templates/riven_analysis.html +10 -0
  101. nonebot_plugin_aawfcore/rendering/templates/riven_market.html +18 -0
  102. nonebot_plugin_aawfcore/rendering/templates/riven_values.html +29 -0
  103. nonebot_plugin_aawfcore/rendering/templates/trend.html +30 -0
  104. nonebot_plugin_aawfcore/rendering/templates/void_trader.html +21 -0
  105. nonebot_plugin_aawfcore/rendering/templates/weekly.html +16 -0
  106. nonebot_plugin_aawfcore/rendering/viewmodels.py +106 -0
  107. nonebot_plugin_aawfcore/services/__init__.py +3 -0
  108. nonebot_plugin_aawfcore/services/arbitration.py +170 -0
  109. nonebot_plugin_aawfcore/services/archimedea.py +117 -0
  110. nonebot_plugin_aawfcore/services/bounties.py +217 -0
  111. nonebot_plugin_aawfcore/services/calendar.py +60 -0
  112. nonebot_plugin_aawfcore/services/cetus.py +12 -0
  113. nonebot_plugin_aawfcore/services/challenge_bounties.py +116 -0
  114. nonebot_plugin_aawfcore/services/circuit.py +93 -0
  115. nonebot_plugin_aawfcore/services/clan.py +47 -0
  116. nonebot_plugin_aawfcore/services/common.py +18 -0
  117. nonebot_plugin_aawfcore/services/cycles.py +125 -0
  118. nonebot_plugin_aawfcore/services/fissures.py +80 -0
  119. nonebot_plugin_aawfcore/services/market.py +100 -0
  120. nonebot_plugin_aawfcore/services/nightwave.py +103 -0
  121. nonebot_plugin_aawfcore/services/operations.py +136 -0
  122. nonebot_plugin_aawfcore/services/relics.py +98 -0
  123. nonebot_plugin_aawfcore/services/riven_analysis.py +176 -0
  124. nonebot_plugin_aawfcore/services/riven_market.py +84 -0
  125. nonebot_plugin_aawfcore/services/riven_values.py +146 -0
  126. nonebot_plugin_aawfcore/services/rivens.py +164 -0
  127. nonebot_plugin_aawfcore/services/steel_path.py +27 -0
  128. nonebot_plugin_aawfcore/services/trend.py +65 -0
  129. nonebot_plugin_aawfcore/services/void_trader.py +81 -0
  130. nonebot_plugin_aawfcore/services/weekly.py +55 -0
  131. nonebot_plugin_aawfcore/services/wiki.py +26 -0
  132. nonebot_plugin_aawfcore/services/wiki_store.py +92 -0
  133. nonebot_plugin_aawfcore/services/worldstate.py +78 -0
  134. nonebot_plugin_aawfcore/subscriptions/__init__.py +5 -0
  135. nonebot_plugin_aawfcore/subscriptions/rules.py +143 -0
  136. nonebot_plugin_aawfcore/subscriptions/service.py +437 -0
  137. nonebot_plugin_aawfcore/subscriptions/sources.py +186 -0
  138. nonebot_plugin_aawfcore/subscriptions/store.py +528 -0
  139. nonebot_plugin_aawfcore/subscriptions/targets.py +192 -0
  140. nonebot_plugin_aawfcore/worldstate/__init__.py +3 -0
  141. nonebot_plugin_aawfcore/worldstate/parsers/__init__.py +3 -0
  142. nonebot_plugin_aawfcore/worldstate/parsers/bounties.py +39 -0
  143. nonebot_plugin_aawfcore/worldstate/parsers/challenge_bounties.py +72 -0
  144. nonebot_plugin_aawfcore/worldstate/parsers/common.py +31 -0
  145. nonebot_plugin_aawfcore/worldstate/parsers/cycles.py +88 -0
  146. nonebot_plugin_aawfcore/worldstate/parsers/location_bounties.py +19 -0
  147. nonebot_plugin_aawfcore/worldstate/seeded_random.py +24 -0
  148. nonebot_plugin_aawfcore-0.23.1.dist-info/METADATA +38 -0
  149. nonebot_plugin_aawfcore-0.23.1.dist-info/RECORD +151 -0
  150. nonebot_plugin_aawfcore-0.23.1.dist-info/WHEEL +5 -0
  151. nonebot_plugin_aawfcore-0.23.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,151 @@
1
+ """AAWarframe 核心内部 HTTP/ASGI API。
2
+
3
+ 不暴露公网端口。协议插件通过 httpx.ASGITransport 调用这些端点;
4
+ 核心不 import QQ/OneBot 类、也不处理平台消息事件。
5
+ """
6
+
7
+ import base64
8
+ import logging
9
+ from datetime import datetime, timezone
10
+ from typing import Literal
11
+
12
+ from fastapi import FastAPI, HTTPException
13
+ from pydantic import BaseModel, Field
14
+
15
+ from .bootstrap import get_runtime
16
+ from .commands.router import dispatch
17
+
18
+ logger = logging.getLogger(__name__)
19
+ app = FastAPI(title="AAWarframe Core API", version="1", docs_url=None, redoc_url=None)
20
+ MAX_IMAGE_BYTES = 12 * 1024 * 1024
21
+
22
+
23
+ class RouteRequest(BaseModel):
24
+ text: str = Field(max_length=4000)
25
+ starts: list[str] = Field(default_factory=lambda: ["/", ""])
26
+ user_id: str = Field(max_length=180)
27
+ group_id: str | None = Field(default=None, max_length=240)
28
+
29
+
30
+ class QueryRequest(BaseModel):
31
+ feature: str = Field(max_length=80)
32
+ arguments: str = Field(default="", max_length=4000)
33
+ bot_id: str = Field(max_length=180)
34
+ user_id: str = Field(max_length=180)
35
+ group_id: str | None = Field(default=None, max_length=240)
36
+ image_base64: str | None = None
37
+
38
+
39
+ class ClaimsRequest(BaseModel):
40
+ bot_ids: list[str] = Field(max_length=40)
41
+ protocol: Literal["qq", "onebot"]
42
+
43
+
44
+ class AckRequest(BaseModel):
45
+ ok: bool
46
+ error: str = Field(default="", max_length=200)
47
+
48
+
49
+ def pack(message) -> dict:
50
+ """标准消息协议:message_type + 按顺序排列的 text/image/at/reply 段。"""
51
+ segments = []
52
+ for item in message:
53
+ kind = item.type
54
+ if kind == "text":
55
+ segments.append({"type": "text", "text": item.data["text"]})
56
+ elif kind == "image":
57
+ value = item.data.get("file")
58
+ if isinstance(value, bytes):
59
+ payload = base64.b64encode(value).decode("ascii")
60
+ elif isinstance(value, str) and value.startswith("base64://"):
61
+ payload = value[len("base64://"):]
62
+ else:
63
+ raise ValueError("核心只允许返回二进制或 Base64 图片,不接受本地路径")
64
+ segments.append({"type": "image", "data_base64": payload})
65
+ elif kind == "at":
66
+ segments.append({"type": "at", "user_id": str(item.data["qq"])})
67
+ elif kind == "reply":
68
+ segments.append({"type": "reply", "message_id": str(item.data["id"])})
69
+ else:
70
+ raise ValueError(f"未知核心消息类型:{kind}")
71
+ types = {segment["type"] for segment in segments}
72
+ message_type = (
73
+ "image" if types == {"image"} else "text" if types == {"text"}
74
+ else "mixed" if segments else "none"
75
+ )
76
+ return {"message_type": message_type, "segments": segments}
77
+
78
+
79
+ @app.post("/v1/route")
80
+ async def route(payload: RouteRequest):
81
+ runtime = get_runtime()
82
+ parsed = runtime.control.route(
83
+ payload.text.lstrip(), set(payload.starts), payload.user_id, payload.group_id,
84
+ )
85
+ if parsed is None:
86
+ return {"matched": False}
87
+ feature, arguments = parsed
88
+ return {"matched": True, "feature": feature, "arguments": arguments}
89
+
90
+
91
+ @app.post("/v1/query")
92
+ async def query(payload: QueryRequest):
93
+ if payload.feature not in {cmd.feature for cmd in get_runtime().control.settings.commands}:
94
+ raise HTTPException(400, detail="未知查询功能")
95
+ image = None
96
+ if payload.image_base64 is not None:
97
+ if len(payload.image_base64) > (MAX_IMAGE_BYTES + 2) // 3 * 4 + 16:
98
+ raise HTTPException(413, detail="图片超过 12 MB")
99
+ try:
100
+ image = base64.b64decode(payload.image_base64, validate=True)
101
+ except ValueError:
102
+ raise HTTPException(400, detail="图片编码无效") from None
103
+ if len(image) > MAX_IMAGE_BYTES:
104
+ raise HTTPException(413, detail="图片超过 12 MB")
105
+ scope = (
106
+ (payload.bot_id, payload.group_id, payload.user_id)
107
+ if payload.group_id is not None else None
108
+ )
109
+ message = await dispatch(payload.feature, payload.arguments, image, subscriber=scope)
110
+ return pack(message)
111
+
112
+
113
+ @app.post("/v1/notifications/claim")
114
+ async def claim(payload: ClaimsRequest):
115
+ runtime = get_runtime()
116
+ service = runtime.subscriptions
117
+ now = datetime.now(timezone.utc)
118
+ # 仅取本协议当前在线 bot 的通知。消息发送权完全留在协议插件。
119
+ deliveries = service.store.claim_due(
120
+ now, set(payload.bot_ids), protocol=payload.protocol
121
+ )
122
+ result = []
123
+ for delivery in deliveries:
124
+ try:
125
+ message = await service.prepare_delivery(delivery, now)
126
+ result.append({
127
+ "id": delivery.id,
128
+ "bot_id": delivery.bot_id,
129
+ "group_id": delivery.group_id,
130
+ "user_id": delivery.user_id,
131
+ "attempts": delivery.attempts,
132
+ **pack(message),
133
+ })
134
+ except Exception as exc:
135
+ logger.exception("订阅通知格式化失败:%s", delivery.id)
136
+ service.store.mark_failed(delivery.id, delivery.attempts, now, type(exc).__name__)
137
+ return {"deliveries": result}
138
+
139
+
140
+ @app.post("/v1/notifications/{delivery_id}/ack")
141
+ async def acknowledge(delivery_id: int, payload: AckRequest):
142
+ service = get_runtime().subscriptions
143
+ now = datetime.now(timezone.utc)
144
+ if payload.ok:
145
+ service.store.mark_sent(delivery_id, now)
146
+ else:
147
+ service.store.mark_failed(
148
+ delivery_id, service.store.delivery_attempts(delivery_id), now,
149
+ payload.error or "platform_send_failed",
150
+ )
151
+ return {"ok": True}
@@ -0,0 +1,164 @@
1
+ # Desc: 实现 nonebot_plugin_aawfcore 层的 bootstrap 功能。
2
+ # Date: 2026-11-15
3
+ # Author: Aameow
4
+
5
+ import asyncio
6
+ import logging
7
+
8
+ import httpx
9
+ from nonebot import get_driver, get_plugin_config
10
+
11
+ from .admin.control import Control
12
+ from .admin.server import AdminServer
13
+ from .config import Config
14
+ from .grq import GameResourceQuery, configure_grq
15
+ from .infrastructure.http import HttpClient
16
+ from .infrastructure.images import ItemImages
17
+ from .infrastructure.riven_ocr import RivenOCR
18
+ from .infrastructure.wiki_http import WikiHttpClient
19
+ from .initialization.pipeline import ensure_offline, initialize
20
+ from .providers.market import MarketProvider
21
+ from .providers.riven_market import RivenMarketProvider
22
+ from .providers.rivens import RivenProvider
23
+ from .providers.wiki import WikiProvider
24
+ from .providers.worldstate import WorldStateProvider
25
+ from .rendering.renderer import CardRenderer
26
+ from .services.arbitration import ArbitrationService
27
+ from .services.market import MarketService
28
+ from .services.relics import RelicService
29
+ from .services.riven_market import RivenMarketService
30
+ from .services.riven_values import RivenValuesService
31
+ from .services.riven_analysis import RivenAnalysisService
32
+ from .services.rivens import RivenService
33
+ from .services.trend import TrendService
34
+ from .services.wiki import WikiService
35
+ from .services.worldstate import WorldStateService
36
+ from .services.void_trader import VoidTraderService
37
+ from .subscriptions import SubscriptionService
38
+
39
+
40
+ class Runtime:
41
+ def __init__(self, config: Config):
42
+ ensure_offline(config.aawarframe_cache_dir)
43
+ self.grq = GameResourceQuery(config.aawarframe_cache_dir / "registry.sqlite3")
44
+ configure_grq(self.grq)
45
+ self.arbitration = ArbitrationService(self.grq, config.aawarframe_cache_dir)
46
+ self.control = Control(
47
+ self.grq,
48
+ {
49
+ "http_timeout": config.aawarframe_http_timeout,
50
+ "worldstate_ttl": config.aawarframe_worldstate_ttl,
51
+ "market_ttl": config.aawarframe_market_ttl,
52
+ },
53
+ )
54
+ self.admin = AdminServer(self, config) if config.aawarframe_admin_enabled else None
55
+ self.http = HttpClient(config.aawarframe_http_timeout)
56
+ self.world_http = (
57
+ HttpClient(
58
+ config.aawarframe_http_timeout, proxy=str(config.aawarframe_worldstate_proxy)
59
+ )
60
+ if config.aawarframe_worldstate_proxy
61
+ else self.http
62
+ )
63
+ self.world_provider = WorldStateProvider(
64
+ self.world_http, config.aawarframe_cache_dir, config.aawarframe_worldstate_ttl
65
+ )
66
+ self.images = ItemImages(self.http)
67
+ self.market_provider = MarketProvider(
68
+ self.http, config.aawarframe_cache_dir, config.aawarframe_market_ttl, images=self.images
69
+ )
70
+ self.riven_provider = RivenProvider(self.http, config.aawarframe_cache_dir)
71
+ self.rivens = RivenService(self.riven_provider)
72
+ self.riven_values = RivenValuesService()
73
+ self.ocr = RivenOCR(config.aawarframe_ocr_python)
74
+ self.riven_analysis = RivenAnalysisService(self.ocr)
75
+ self.riven_task: asyncio.Task[None] | None = None
76
+ self.world = WorldStateService(self.world_provider)
77
+ self.trader = VoidTraderService(self.world_provider)
78
+ self.market = MarketService(self.market_provider)
79
+ self.relics = RelicService(self.market_provider)
80
+ self.trend = TrendService(self.market)
81
+ self.riven_market_provider = RivenMarketProvider(self.http, config.aawarframe_market_ttl)
82
+ self.riven_market = RivenMarketService(self.riven_market_provider)
83
+ self.wiki_http = WikiHttpClient(config.aawarframe_http_timeout)
84
+ self.wiki_provider = WikiProvider(self.wiki_http)
85
+ self.wiki = WikiService(self.wiki_provider, config.aawarframe_cache_dir / "wiki.sqlite3")
86
+ self.renderer = CardRenderer(config.aawarframe_render_concurrency, config.aawarframe_theme)
87
+ self.subscriptions = SubscriptionService(
88
+ config.aawarframe_cache_dir, self.world_provider,
89
+ arbitration=self.arbitration, market=self.market,
90
+ riven_market=self.riven_market, renderer=self.renderer,
91
+ )
92
+ self.control.apply = self.apply_options
93
+ self.apply_options(self.control.settings.options)
94
+
95
+ def apply_options(self, options):
96
+ for http in {self.http, self.world_http, self.wiki_http}:
97
+ http.client.timeout = httpx.Timeout(options.http_timeout)
98
+ self.world_provider.cache.ttl = options.worldstate_ttl
99
+ self.market_provider.cache.ttl = options.market_ttl
100
+ self.riven_market_provider.cache.ttl = options.market_ttl
101
+ self.wiki_provider.cache.ttl = options.wiki_ttl
102
+ self.wiki_http.interval = options.wiki_interval
103
+
104
+ def start(self) -> None:
105
+ if self.admin and self.admin.task is None:
106
+ try:
107
+ self.admin.start()
108
+ except Exception:
109
+ logging.getLogger(__name__).exception("管理台启动失败")
110
+ self.subscriptions.start()
111
+ if self.riven_task is None or self.riven_task.done():
112
+ self.riven_task = asyncio.create_task(self.riven_provider.run_daily())
113
+
114
+ async def close(self) -> None:
115
+ await self.subscriptions.close()
116
+ if self.admin:
117
+ await self.admin.close()
118
+ if self.riven_task is not None:
119
+ self.riven_task.cancel()
120
+ await asyncio.gather(self.riven_task, return_exceptions=True)
121
+ self.riven_task = None
122
+ await self.ocr.close()
123
+ self.wiki.close()
124
+ await self.wiki_provider.close()
125
+ await self.wiki_http.close()
126
+ await self.renderer.close()
127
+ await self.world_provider.close()
128
+ await self.market_provider.close()
129
+ await self.riven_market_provider.close()
130
+ await self.images.close()
131
+ if self.world_http is not self.http:
132
+ await self.world_http.close()
133
+ await self.http.close()
134
+ self.grq.close()
135
+ configure_grq(None)
136
+
137
+
138
+ _runtime: Runtime | None = None
139
+
140
+
141
+ def get_runtime() -> Runtime:
142
+ global _runtime
143
+ if _runtime is None:
144
+ _runtime = Runtime(get_plugin_config(Config))
145
+ return _runtime
146
+
147
+
148
+ def setup() -> None:
149
+ driver = get_driver()
150
+
151
+ @driver.on_startup
152
+ async def startup():
153
+ # 资源准备失败时使用离线数据,再启动机器人运行时。
154
+ config = get_plugin_config(Config)
155
+ if config.aawarframe_data_auto_update:
156
+ await initialize(config.aawarframe_cache_dir)
157
+ get_runtime().start()
158
+
159
+ @driver.on_shutdown
160
+ async def shutdown():
161
+ global _runtime
162
+ if _runtime is not None:
163
+ await _runtime.close()
164
+ _runtime = None
@@ -0,0 +1,79 @@
1
+ """供各协议包调用的 HTTP API 客户端。
2
+
3
+ 默认 ASGITransport(进程内 HTTP,无 TCP 监听/令牌泄漏);协议间统一 JSON
4
+ 消息格式。未来远程部署时可替换为带鉴权的真实 HTTP transport。
5
+ """
6
+
7
+ import asyncio
8
+ from contextlib import asynccontextmanager
9
+
10
+ import httpx
11
+
12
+ from .api import app
13
+
14
+
15
+ class CoreClient:
16
+ def __init__(self):
17
+ self._client = httpx.AsyncClient(
18
+ transport=httpx.ASGITransport(app=app),
19
+ base_url="http://aawfcore.internal",
20
+ timeout=httpx.Timeout(60.0),
21
+ )
22
+
23
+ async def call(self, endpoint: str, data: dict) -> dict:
24
+ result = await self._client.post(endpoint, json=data)
25
+ result.raise_for_status()
26
+ return result.json()
27
+
28
+ async def route(self, **payload) -> dict:
29
+ return await self.call("/v1/route", payload)
30
+
31
+ async def query(self, **payload) -> dict:
32
+ return await self.call("/v1/query", payload)
33
+
34
+ async def claim(self, bot_ids: list[str], protocol: str) -> list[dict]:
35
+ result = await self.call("/v1/notifications/claim", {
36
+ "bot_ids": bot_ids, "protocol": protocol,
37
+ })
38
+ return result["deliveries"]
39
+
40
+ async def ack(self, delivery_id: int, *, ok: bool, error: str = ""):
41
+ await self.call(
42
+ f"/v1/notifications/{delivery_id}/ack",
43
+ {"ok": ok, "error": error[:200]},
44
+ )
45
+
46
+ @asynccontextmanager
47
+ async def ocr_admission(self):
48
+ # One in-process Core runtime: both QQ and OneBot share the same quota.
49
+ from .bootstrap import get_runtime
50
+ from .models.errors import UserInputError
51
+
52
+ try:
53
+ async with get_runtime().ocr.admission():
54
+ yield
55
+ except UserInputError as exc:
56
+ # The protocol layer should show a user-readable capacity error.
57
+ raise ValueError(str(exc)) from None
58
+
59
+ @asynccontextmanager
60
+ async def ocr_download(self):
61
+ from .bootstrap import get_runtime
62
+ from .infrastructure.riven_ocr import DOWNLOAD_TIMEOUT
63
+
64
+ ocr = get_runtime().ocr
65
+ try:
66
+ async with asyncio.timeout(DOWNLOAD_TIMEOUT):
67
+ async with ocr.download_slots:
68
+ yield
69
+ except TimeoutError:
70
+ raise ValueError('图片下载超时,请稍后重试。') from None
71
+
72
+ async def close(self):
73
+ await self._client.aclose()
74
+
75
+
76
+ def decode_image(segment: dict) -> bytes:
77
+ import base64
78
+
79
+ return base64.b64decode(segment["data_base64"], validate=True)
@@ -0,0 +1,3 @@
1
+ # 作用:初始化 commands 模块。
2
+ # 编写日期:2026-11-07
3
+ # 作者:Aameow
@@ -0,0 +1,176 @@
1
+ # Desc: 解析查询参数和紫卡词条修正。
2
+ # Date: 2026-11-15
3
+ # Author: Aameow
4
+
5
+ import re
6
+ import shlex
7
+
8
+ from ..grq import get_grq
9
+ from ..grq.normalizer import normalize_name
10
+ from ..localization.riven_attributes import match_attributes
11
+ from ..models.errors import UserInputError
12
+ from ..models.market import MarketQuery
13
+ from ..models.riven_market import RivenMarketQuery
14
+
15
+ USAGE = "用法:wm 物品名 / wm 满级物品名;可选 --rank 等级、--subtype 子类型。物品名允许空格。"
16
+
17
+
18
+ def parse_market_query(text: str) -> MarketQuery:
19
+ try:
20
+ tokens = shlex.split(text)
21
+ except ValueError as exc:
22
+ raise UserInputError("物品名引号不完整。" + USAGE) from exc
23
+ names = []
24
+ options = {}
25
+ index = 0
26
+ while index < len(tokens):
27
+ token = tokens[index]
28
+ if token.startswith("--"):
29
+ if token not in {"--rank", "--subtype"} or token in options:
30
+ raise UserInputError("未知或重复选项。" + USAGE)
31
+ if index + 1 >= len(tokens) or tokens[index + 1].startswith("--"):
32
+ raise UserInputError("选项缺少值。" + USAGE)
33
+ options[token] = tokens[index + 1]
34
+ index += 2
35
+ else:
36
+ names.append(token)
37
+ index += 1
38
+ name = " ".join(names).strip()
39
+ max_rank = name.startswith("满级") or name.endswith("满级")
40
+ if name.startswith("满级"):
41
+ name = name[2:].strip()
42
+ if name.endswith("满级"):
43
+ name = name[:-2].strip()
44
+ if not name:
45
+ raise UserInputError(USAGE)
46
+ rank = None
47
+ if "--rank" in options:
48
+ if max_rank or not options["--rank"].isascii() or not options["--rank"].isdigit():
49
+ raise UserInputError("等级须为非负整数,且不能与满级同时使用。")
50
+ rank = int(options["--rank"])
51
+ if len(name) > 200:
52
+ raise UserInputError("物品名称过长(最多 200 字符)。")
53
+ return MarketQuery(name=name, max_rank=max_rank, rank=rank, subtype=options.get("--subtype"))
54
+
55
+
56
+ def parse_trend_query(text: str) -> MarketQuery:
57
+ try:
58
+ return parse_market_query(text)
59
+ except UserInputError as exc:
60
+ raise UserInputError(str(exc).replace("wm ", "趋势 ")) from exc
61
+
62
+
63
+ def parse_relic_query(text: str, command: str) -> str:
64
+ query = text.strip()
65
+ if not query or len(query) > 200:
66
+ example = "阿利乌双枪p 枪机" if command == "部件" else "古纪A1"
67
+ raise UserInputError(f"用法:{command} {example},名称最长 200 字。")
68
+ return query
69
+
70
+
71
+ def parse_wiki_query(text: str) -> str:
72
+ query = text.strip()
73
+ if not query:
74
+ raise UserInputError("用法:wk 关键词,例如 wk 伯斯顿。")
75
+ if len(query) > 200:
76
+ raise UserInputError("Wiki 关键词过长(最多 200 字符)。")
77
+ return query
78
+
79
+
80
+ def parse_riven_page(text: str) -> int:
81
+ value = text.strip()
82
+ if not value:
83
+ return 1
84
+ if len(value) > 6 or not value.isascii() or not value.isdigit() or int(value) < 1:
85
+ raise UserInputError("用法:zk 2 或 zk已洗 2,可追加“热度”;页码必须是正整数。")
86
+ return int(value)
87
+
88
+
89
+ def parse_riven_ranking(text: str) -> tuple[int, str]:
90
+ tokens = text.split()
91
+ if tokens.count("热度") > 1:
92
+ raise UserInputError("用法:zk 3 热度 或 zk已洗 3 热度;默认按中位价排序。")
93
+ sort_by = "popularity" if "热度" in tokens else "median"
94
+ tokens = [token for token in tokens if token != "热度"]
95
+ if len(tokens) > 1:
96
+ raise UserInputError("用法:zk 3 热度 或 zk已洗 3 热度;默认按中位价排序。")
97
+ return parse_riven_page(tokens[0] if tokens else ""), sort_by
98
+
99
+
100
+ def parse_riven_statistics_query(text: str) -> str:
101
+ query = text.strip()
102
+ if not query:
103
+ raise UserInputError("用法:zk 武器名称,例如:zk 伯斯顿。")
104
+ if len(query) > 200:
105
+ raise UserInputError("武器名称过长(最多 200 字符)。")
106
+ return query
107
+
108
+
109
+ def parse_riven_values(text: str) -> tuple[str, str]:
110
+ text = text.strip()
111
+ parts = text.rsplit(maxsplit=1)
112
+ layout = "3+1"
113
+ if parts and re.fullmatch(r"\d+\s*[++]\s*\d+", parts[-1]):
114
+ layout = parts.pop().replace("+", "+")
115
+ text = parts[0] if parts else ""
116
+ if layout not in {"2+0", "2+1", "3+0", "3+1"}:
117
+ raise UserInputError("词条修正支持 2+0、2+1、3+0、3+1。")
118
+ if not text or len(text) > 200:
119
+ raise UserInputError("用法:数值 武器名 [2+0 / 2+1 / 3+0 / 3+1],默认 3+1。")
120
+ return text, layout
121
+
122
+
123
+ def parse_riven_market(text: str) -> RivenMarketQuery:
124
+ usage = "用法:wmr 武器名 [正面词条] [负任意 / 负词条名];发送“词条”查看名称与缩写。"
125
+ guide = "词条无法识别,请发送“词条”查看名称与缩写映射。"
126
+ if len(text) > 500:
127
+ raise UserInputError("查询内容过长。" + usage)
128
+ try:
129
+ tokens = shlex.split(text)
130
+ except ValueError as exc:
131
+ raise UserInputError("武器名引号不完整。" + usage) from exc
132
+ negative = None
133
+ if len(tokens) > 1 and tokens[-1].startswith("负"):
134
+ suffix = tokens.pop()[1:]
135
+ if suffix == "任意":
136
+ negative = "has"
137
+ else:
138
+ stats = match_attributes(suffix)
139
+ if not stats or len(stats) != 1:
140
+ raise UserInputError("负面请填写“负任意”或一个词条,例如“负变焦”。" + guide)
141
+ negative = stats[0]
142
+ if not tokens:
143
+ raise UserInputError(usage)
144
+ index = get_grq().domains["Riven"]
145
+ # 优先保留完整武器名;未知词条不能被模糊武器匹配吞掉。
146
+ exact = [
147
+ i for i in range(1, len(tokens) + 1)
148
+ if normalize_name(" ".join(tokens[:i])) in index.names
149
+ or " ".join(tokens[:i]) in index.external
150
+ ]
151
+ boundary = max(exact) if exact else next(
152
+ (i for i in range(1, len(tokens)) if match_attributes(" ".join(tokens[i:]))),
153
+ len(tokens) if len(tokens) == 1 else None,
154
+ )
155
+ if boundary is None:
156
+ raise UserInputError(guide)
157
+ positives = match_attributes(" ".join(tokens[boundary:]))
158
+ if positives is None or (boundary < len(tokens) and not positives):
159
+ raise UserInputError(guide)
160
+ if len(positives) > 3:
161
+ raise UserInputError("最多指定 3 个正面词条。发送“词条”查看映射。")
162
+ if len(set(positives)) != len(positives) or negative in positives:
163
+ raise UserInputError("正负词条不能重复。")
164
+ weapon = " ".join(tokens[:boundary])
165
+ if len(weapon) > 200:
166
+ raise UserInputError(usage)
167
+ return RivenMarketQuery(weapon=weapon, positives=positives, negative=negative)
168
+
169
+
170
+ def parse_bounty_index(text: str, command: str = "地球") -> int | None:
171
+ value = text.strip()
172
+ if not value:
173
+ return None
174
+ if not value.isascii() or not value.isdigit() or len(value) > 2 or int(value) < 1:
175
+ raise UserInputError(f"用法:{command} 查看概览,{command} 1 查看指定任务;编号须为正整数。")
176
+ return int(value)