# -*- coding: utf-8 -*- """聊天直接用指令(2026-11-21 主人:「整個邏輯都要修正,他應該要熟知所有指令的功能並直接使用」)。 設計:docs/superpowers/specs/2026-11-21-chat-command-tools-design.md 這裡只放不碰網路、好測的部分: - build_specs:從指令樹(bot.tree.get_commands())產生工具清單,每支指令/子指令一個工具 - KIND:直接跑(run)/先問(ask,按鈕確認才做)/不給(off) - gemini_decls/openai_tools:轉成兩家的工具格式 - to_namespace:模型給的參數 → 指令要的(顯示名、型別、選項) - ShimInteraction:代打指令用的假 interaction(送出的東西照樣貼在頻道、收集成文字交給模型) 真正跑指令、等結果、確認按鈕在 discordbot(要用 bot 和事件迴圈)。""" import json import re from types import SimpleNamespace from typing import Any, Dict, List, Optional, Tuple # ── 分類:沒列到的新指令一律「先問」 ── RUN = { "rain", "typhoon", "youtube", "wiki", "simbrief", "valorant", "delta", "news", "help", "osu farm", "osu edge", "osu curve", "osu record", "sb price", "sb election", "sb picks", "sb track", "sb holdings", "sb flip", "sb levels", "sb chart", "sb portfolio", # 有填數字=會改設定 → ask_args 改成先問 "memory search", "memory show", "note list", "reviews place", "admin status", "admin health", "admin usage", } OFF = {"osu import"} # 備援模型(Groq 每分鐘 8K token)只帶這些常用、直接跑的 COMPACT = {"rain", "typhoon", "wiki", "news", "youtube", "sb price", "sb election", "sb picks", "sb flip", "sb levels", "osu farm", "valorant", "delta", "simbrief", "weather_world", "read_webpage", "web_search"} # 要先問、但備援也要帶的(★2026-11-23 主人:「連 /web 都不會用」——做網頁是常見的要求) COMPACT_ASK = {"web"} # 參數有填就會改東西的(填了改成先問) ASK_IF_ARGS = {"sb portfolio"} # 指令參數型別(discord AppCommandOptionType 的值) _T_STR, _T_INT, _T_BOOL, _T_USER, _T_CHAN, _T_ROLE, _T_MENT, _T_NUM, _T_ATT = 3, 4, 5, 6, 7, 8, 9, 10, 11 _UNSUPPORTED = {_T_USER, _T_CHAN, _T_ROLE, _T_MENT, _T_ATT} _ASCII_ID = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,40}$") MAX_RESULT = 2500 # 每支指令交給模型最多幾個字 def kind_of(qual: str) -> str: if qual in OFF: return "off" return "run" if qual in RUN else "ask" def _tval(t) -> int: return int(getattr(t, "value", t) or 0) def _leaves(cmds, prefix: str = ""): for c in cmds: subs = getattr(c, "commands", None) qual = (prefix + " " + c.name).strip() if subs is not None and not hasattr(c, "_params"): yield from _leaves(subs, qual) else: yield qual, c def build_specs(commands) -> List[Dict[str, Any]]: """指令樹 → 工具清單。每個:tool(工具名)、qual(/後面那串)、desc、kind、params、cmd(指令物件)。""" out = [] for qual, c in _leaves(commands): kind = kind_of(qual) if kind == "off": continue params, skip = [], False for i, p in enumerate(getattr(c, "parameters", None) or []): t = _tval(getattr(p, "type", _T_STR)) if t in _UNSUPPORTED: if getattr(p, "required", False): skip = True # 必填的附檔/成員:模型給不出來 → 整支不給 break continue disp = getattr(p, "display_name", None) or p.name key = disp if _ASCII_ID.match(disp) else (p.name if _ASCII_ID.match(p.name) else f"arg{i + 1}") choices = [(str(ch.name), ch.value) for ch in (getattr(p, "choices", None) or [])] params.append({"key": key, "display": disp, "type": t, "required": bool(getattr(p, "required", False)), "desc": (getattr(p, "description", "") or "").strip(), "choices": choices}) if skip: continue tool = re.sub(r"[^A-Za-z0-9_]", "_", qual.replace(" ", "_"))[:60] out.append({"tool": tool, "qual": qual, "desc": (getattr(c, "description", "") or "").strip(), "kind": kind, "params": params, "cmd": c}) return out def _param_schema(p: Dict[str, Any], dmax: int) -> Dict[str, Any]: t = p["type"] js = {"type": {_T_INT: "integer", _T_NUM: "number", _T_BOOL: "boolean"}.get(t, "string")} d = p["desc"] if p["key"] != p["display"]: d = f"({p['display']}){d}" if p["choices"]: d += ";可選:" + "、".join(f"{n}={v}" for n, v in p["choices"][:25]) if t == _T_STR: js["enum"] = [str(v) for _n, v in p["choices"][:25]] if d: js["description"] = d[:dmax] return js def json_schema(spec: Dict[str, Any], dmax: int = 120) -> Dict[str, Any]: props = {p["key"]: _param_schema(p, dmax) for p in spec["params"]} req = [p["key"] for p in spec["params"] if p["required"]] sch: Dict[str, Any] = {"type": "object", "properties": props} if req: sch["required"] = req return sch def _tool_desc(spec: Dict[str, Any], dmax: int) -> str: tail = "(會改東西:香草會先貼確認按鈕,主人按了才做)" if spec["kind"] == "ask" else "" return (f"/{spec['qual']}:{spec['desc']}"[:dmax] + tail) def gemini_decls(specs, dmax: int = 120) -> List[Dict[str, Any]]: """給 types.FunctionDeclaration(**d) 用的 dict。""" out = [] for s in specs: d = {"name": s["tool"], "description": _tool_desc(s, dmax)} if s["params"]: # 沒參數的不送空的 schema(Gemini 可能不收) d["parameters_json_schema"] = json_schema(s, dmax) out.append(d) return out def openai_tools(specs, dmax: int = 160, compact: bool = False) -> List[Dict[str, Any]]: """compact:只帶 COMPACT 那幾支、說明壓短(給 Groq 備援)。""" return [{"type": "function", "function": {"name": s["tool"], "description": _tool_desc(s, dmax), "parameters": json_schema(s, dmax)}} for s in specs if not compact or (s["qual"] in COMPACT and s["kind"] == "run") or s["qual"] in COMPACT_ASK] def _coerce(p: Dict[str, Any], v: Any) -> Any: t = p["type"] if p["choices"]: for n, cv in p["choices"]: # 模型給值或給名字都認 if str(v) == str(cv) or str(v) == n: return cv raise ValueError(f"{p['display']} 只能是:" + "、".join(str(cv) for _n, cv in p["choices"])) if t == _T_INT: return int(float(v)) if t == _T_NUM: return float(v) if t == _T_BOOL: return v if isinstance(v, bool) else str(v).strip().lower() in ("1", "true", "yes", "是", "對") return str(v) def to_namespace(spec: Dict[str, Any], args: Optional[Dict[str, Any]]) -> Tuple[SimpleNamespace, Dict[str, Any]]: """模型給的參數 → (指令要的 namespace(顯示名當 key), 給人看的 {顯示名: 值})。缺必填 → ValueError。""" args = dict(args or {}) vals: Dict[str, Any] = {} for p in spec["params"]: v = args.get(p["key"], args.get(p["display"])) if v is None or (isinstance(v, str) and not v.strip() and p["type"] == _T_STR): if p["required"]: raise ValueError(f"缺少必填的參數 {p['display']}") continue vals[p["display"]] = _coerce(p, v) return SimpleNamespace(**vals), vals def effective_kind(spec: Dict[str, Any], shown: Dict[str, Any]) -> str: if spec["qual"] in ASK_IF_ARGS and shown: return "ask" return spec["kind"] def command_line(spec: Dict[str, Any], shown: Dict[str, Any]) -> str: """給人看的指令:/sb hold 物品:X 價格:1""" return "/" + spec["qual"] + "".join(f" {k}:{v}" for k, v in shown.items()) def page_excerpt(text: str, find: str = "", limit: int = 3800, head: int = 400) -> str: """網頁正文 → 給模型看的一段:有 find 就給開頭(常有日期)+每個關鍵字附近;沒有或找不到就給開頭 limit 字。""" t = (text or "").strip() if len(t) <= limit: return t words = [w for w in re.split(r"[\s,,、;;//]+", find or "") if len(w) >= 2][:6] low = t.lower() spans = [] for w in words: i = low.find(w.lower()) n = 0 while i >= 0 and n < 4: spans.append((max(0, i - 300), min(len(t), i + 600))) i = low.find(w.lower(), i + len(w)) n += 1 if not spans: return t[:limit] spans.sort() merged = [list(spans[0])] for a, b in spans[1:]: if a <= merged[-1][1]: merged[-1][1] = max(merged[-1][1], b) else: merged.append([a, b]) out = t[:head] for a, b in merged: a = max(a, head) if b <= a: continue piece = "\n…\n" + t[a:b] if len(out) + len(piece) > limit: out += piece[:max(0, limit - len(out))] break out += piece return out def call_key(tool: str, args: Optional[Dict[str, Any]]) -> str: return tool + "|" + json.dumps(args or {}, ensure_ascii=False, sort_keys=True, default=str) # ── 卡片 → 文字 ── def embed_text(e) -> str: out = [] for attr in ("title", "description"): v = getattr(e, attr, None) if v: out.append(str(v)) for f in getattr(e, "fields", None) or []: out.append(f"{getattr(f, 'name', '')}:{getattr(f, 'value', '')}") ft = getattr(getattr(e, "footer", None), "text", None) if ft: out.append(str(ft)) return "\n".join(out) def view_text(view) -> str: """新版卡片(LayoutView/Container/TextDisplay)裡的文字。舊的 View(只有按鈕)回空。""" walk = getattr(view, "walk_children", None) if walk is None: return "" out = [] try: for it in walk(): c = getattr(it, "content", None) if isinstance(c, str) and c.strip(): out.append(c) except Exception: return "" return "\n".join(out) def message_text(content=None, embed=None, embeds=None, file=None, files=None, view=None, **_kw) -> str: parts = [] if content: parts.append(str(content)) vt = view_text(view) if view is not None else "" if vt: parts.append(vt) for e in ([embed] if embed is not None else []) + list(embeds or []): t = embed_text(e) if t: parts.append(t) fl = ([file] if file is not None else []) + list(files or []) if fl: parts.append("〔附檔:" + "、".join(str(getattr(f, "filename", "") or "圖") for f in fl) + "〕") return "\n".join(parts) _SEND_KEYS = {"content", "embed", "embeds", "file", "files", "view", "allowed_mentions", "suppress_embeds", "silent", "delete_after", "poll", "stickers"} _EDIT_KEYS = {"content", "embed", "embeds", "attachments", "view", "allowed_mentions", "suppress", "delete_after"} def _clean(kw: Dict[str, Any], keys) -> Dict[str, Any]: return {k: v for k, v in kw.items() if k in keys and v is not None} class _Followup: def __init__(self, shim): self._s = shim async def send(self, content=None, **kw): return await self._s._send(content, kw) class _Response: def __init__(self, shim): self._s = shim self._done = False def is_done(self) -> bool: return self._done async def defer(self, *a, **kw): self._done = True async def send_message(self, content=None, **kw): self._done = True await self._s._send(content, kw) async def edit_message(self, **kw): self._done = True await self._s.edit_original_response(**kw) async def send_modal(self, *_a, **_k): raise RuntimeError("聊天代打不能開表單,請主人自己打這個指令") class _Channel: """代打時的 interaction.channel:send 照樣送、順便收文字;其他屬性轉給真的頻道。""" def __init__(self, shim, real): self._s, self._real = shim, real async def send(self, content=None, **kw): return await self._s._send(content, kw, plain=True) def __getattr__(self, name): return getattr(self._real, name) class ShimInteraction: """把聊天訊息包成指令用的 interaction。送出:第一則回覆主人那則訊息,之後接在頻道; ephemeral(只給一個人看)在伺服器頻道裡辦不到 → 改私訊發問的人(在私訊裡就照常)。""" def __init__(self, message, command, client=None, namespace=None, qual: str = ""): self._msg = message self.user = message.author self.guild = getattr(message, "guild", None) self.guild_id = getattr(self.guild, "id", None) self.channel = _Channel(self, message.channel) self.channel_id = getattr(message.channel, "id", None) self.client = client self.command = command self.namespace = namespace or SimpleNamespace() self.data = {"name": qual, "options": [{"name": k, "value": v} for k, v in vars(self.namespace).items()]} self.message = None self.id = getattr(message, "id", 0) self.created_at = getattr(message, "created_at", None) self.extras: Dict[str, Any] = {} self.locale = self.guild_locale = None self.response = _Response(self) self.followup = _Followup(self) self.sent: List[Any] = [] # 送出去的訊息(依序) self.texts: Dict[int, str] = {} # id(訊息) → 文字(編輯會更新) self.private: List[str] = [] # 改私訊的那些文字 self._first = None async def _send(self, content, kw, plain: bool = False): eph = bool(kw.get("ephemeral")) and self.guild is not None text = message_text(content, **kw) send_kw = _clean(dict(kw, content=content), _SEND_KEYS) if eph: self.private.append(text) try: m = await self.user.send(**send_kw) except Exception: m = None return m if self._first is None and not plain: m = await self._msg.reply(mention_author=False, **send_kw) self._first = m else: m = await self._msg.channel.send(**send_kw) self.sent.append(m) self.texts[id(m)] = text return m async def original_response(self): return self._first async def edit_original_response(self, **kw): if self._first is None: return await self._send(kw.get("content"), kw) m = await self._first.edit(**_clean(kw, _EDIT_KEYS)) or self._first old = self.texts.get(id(self._first), "") new = message_text(kw.get("content"), kw.get("embed"), kw.get("embeds"), view=kw.get("view")) self.texts[id(self._first)] = new or old return m async def delete_original_response(self): if self._first is not None: await self._first.delete() def collected(self) -> str: pub = "\n\n".join(t for t in (self.texts.get(id(m), "") for m in self.sent) if t) priv = "\n\n".join(t for t in self.private if t) out = pub if priv: out += ("\n\n" if out else "") + "【私人內容:已私訊主人,不要在頻道複述細節】\n" + priv return out[:MAX_RESULT]