84 lines
3.3 KiB
Python
84 lines
3.3 KiB
Python
from pathlib import Path
|
||
|
||
path = Path('/opt/openclaw-dingtalk-bridge/bot.py')
|
||
text = path.read_text(encoding='utf-8')
|
||
start_marker = ' def _run_openclaw(self, session_id: str, prompt: str) -> str:\n'
|
||
end_marker = '\n def _is_image_url(self, raw_url: str) -> bool:\n'
|
||
start = text.find(start_marker)
|
||
end = text.find(end_marker, start)
|
||
if start == -1 or end == -1:
|
||
raise SystemExit('failed to locate _run_openclaw boundaries')
|
||
|
||
replacement = ''' def _run_openclaw(self, session_id: str, prompt: str) -> str:
|
||
cmd = [
|
||
self.openclaw_bin,
|
||
"agent",
|
||
"--session-id",
|
||
session_id,
|
||
"--message",
|
||
prompt,
|
||
"--json",
|
||
"--timeout",
|
||
str(self.openclaw_timeout),
|
||
]
|
||
self.logger.info("openclaw call: session=%s", session_id)
|
||
try:
|
||
proc = subprocess.run(
|
||
cmd,
|
||
capture_output=True,
|
||
text=True,
|
||
timeout=self.openclaw_timeout + 20,
|
||
)
|
||
except subprocess.TimeoutExpired:
|
||
self.logger.error("openclaw call timeout: session=%s timeout=%ss", session_id, self.openclaw_timeout)
|
||
return f"OpenClaw 调用超时(>{self.openclaw_timeout}秒),请重试。"
|
||
if proc.returncode != 0:
|
||
err = (proc.stderr or proc.stdout or "openclaw error").strip()
|
||
return f"OpenClaw 调用失败: {err[:500]}"
|
||
|
||
try:
|
||
raw_stdout = (proc.stdout or "").strip()
|
||
decoder = json.JSONDecoder()
|
||
data = None
|
||
parse_error = None
|
||
try:
|
||
data, _ = decoder.raw_decode(raw_stdout)
|
||
except Exception as exc:
|
||
parse_error = exc
|
||
idx = raw_stdout.find("{")
|
||
while idx != -1:
|
||
candidate = raw_stdout[idx:]
|
||
try:
|
||
data, _ = decoder.raw_decode(candidate)
|
||
break
|
||
except Exception:
|
||
idx = raw_stdout.find("{", idx + 1)
|
||
if data is None:
|
||
raise parse_error
|
||
|
||
payloads = data.get("result", {}).get("payloads", [])
|
||
text_items = [p.get("text", "") for p in payloads if isinstance(p, dict)]
|
||
answer = "\\n".join(t for t in text_items if t).strip()
|
||
if not answer:
|
||
answer = "任务已执行,但未返回文本结果。"
|
||
|
||
if self._is_market_prompt(prompt) and (
|
||
"无法直接从页面抓取" in answer
|
||
or "需要登录后的操作" in answer
|
||
or "工具版本不支持点击交互" in answer
|
||
):
|
||
subject = self._extract_market_subject(prompt)
|
||
fallback = self._run_market_brief(subject)
|
||
return f"已切换为市场分析直连模式({subject}):\\n\\n{fallback}"
|
||
|
||
return answer
|
||
except Exception as exc:
|
||
self.logger.exception("parse openclaw output failed")
|
||
raw = (proc.stdout or "").strip()
|
||
return f"结果解析失败: {exc}.\\n原始输出: {raw[:500]}"
|
||
'''
|
||
|
||
new_text = text[:start] + replacement + text[end:]
|
||
path.write_text(new_text, encoding='utf-8')
|
||
print('patched', path)
|