python_调用远程服务器上的openclaw
bash
import json
import os
import urllib.error
import urllib.request
import uuid
GATEWAY_TOKEN = "XXX"
def query_openclaw(question: str) -> str:
base_url = os.getenv(
"OPENCLAW_API_BASE", "https://openclaw-api.upvibe.site"
).rstrip("/")
if not GATEWAY_TOKEN or GATEWAY_TOKEN == "请在这里填写 Gateway Token":
raise RuntimeError("请先在代码顶部填写 GATEWAY_TOKEN")
payload = {
"model": "openclaw:main",
# A fresh session prevents one slow request from blocking later queries.
"user": f"local-feishu-search-{uuid.uuid4()}",
"stream": False,
"messages": [
{
"role": "user",
"content": (
"使用 feishu-internal-search 技能查询飞书内部资料。"
"综合相关文档、知识库和群聊记录,形成直接、可执行的答案,"
"根据问题类型控制范围:具体问答应精炼,资料盘点、推荐或查找类问题"
"应尽量完整并按用途分类,不固定来源数量,同时去重和排除弱相关内容;"
"把文档链接紧跟在对应结论或资料项后面,统一写成 "
"[资料名称](URL),不要统一堆在文末;"
"回答简洁直接,不重复解释,只保留关键结论、操作和必要依据。\n\n"
f"查询问题:{question}"
),
}
],
}
request = urllib.request.Request(
f"{base_url}/v1/chat/completions",
data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
headers={
"Authorization": f"Bearer {GATEWAY_TOKEN}",
"Content-Type": "application/json",
},
method="POST",
)
try:
with urllib.request.urlopen(request, timeout=300) as response:
result = json.load(response)
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", errors="replace")
raise RuntimeError(f"OpenClaw API 返回 HTTP {exc.code}: {detail}") from exc
except urllib.error.URLError as exc:
raise RuntimeError("无法连接 OpenClaw 公网 API;请检查网络和 API 地址") from exc
return result["choices"][0]["message"]["content"]
if __name__ == "__main__":
# 在这里填写问题,然后直接点击 VS Code 的"运行 Python 文件"。
QUESTION = "桌面元素捕获不了"
print("正在连接 OpenClaw 并查询飞书资料,请稍候......", flush=True)
print(query_openclaw(QUESTION))