jay0826 commited on
Commit
f068dff
·
verified ·
1 Parent(s): 93e41fe

更新 5 個檔(discordbot.py、vb_health.py、vb_recent.py、recent.npz…)

Browse files
Files changed (3) hide show
  1. discordbot.py +71 -1
  2. vb_health.py +5 -0
  3. vb_recent.py +186 -0
discordbot.py CHANGED
@@ -5650,9 +5650,49 @@ async def _cwa_fc_loop():
5650
  await asyncio.sleep(CWA_FC_SEC)
5651
 
5652
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5653
  @bot.tree.command(name="rain", description="這裡會不會下雨:定點現況+上風處有沒有雨要過來")
5654
  @app_commands.describe(place="地點(例:大安、板橋、內湖)。不填=整個盆地概況",
5655
  詳細="True=附判斷依據、校準、衛星等細節(預設只給會改變決定的幾行)")
 
5656
  async def cmd_rain(interaction: discord.Interaction, place: Optional[str] = None,
5657
  詳細: Optional[bool] = False):
5658
  await interaction.response.defer()
@@ -5669,6 +5709,7 @@ async def cmd_rain(interaction: discord.Interaction, place: Optional[str] = None
5669
  return
5670
 
5671
  p = (place or "").strip()
 
5672
  if not p:
5673
  await interaction.followup.send(_wx.format_report(_wx.assess(sts)))
5674
  return
@@ -5770,6 +5811,7 @@ _verify_all_lock = asyncio.Lock() # 整體驗證一次只跑一份(很貴
5770
  @bot.tree.command(name="rain_verify_gbm",
5771
  description="GBM 模型的實測成績(按場次計,真值=你周圍 3 km)")
5772
  @app_commands.describe(place="地點(例:大安、板橋、內湖);「整體」=所有定點合併。不填=台北車站")
 
5773
  async def cmd_rain_verify_gbm(interaction: discord.Interaction,
5774
  place: Optional[str] = None):
5775
  """★與 /rain_verify 是兩回事:那支驗規則式、真值是「盆地任一站」、按快照計;
@@ -5782,6 +5824,7 @@ async def cmd_rain_verify_gbm(interaction: discord.Interaction,
5782
  with _wx_lock:
5783
  snaps = list(_wx_snaps)
5784
  p = (place or "").strip()
 
5785
  if p in ("整體", "全部", "all"):
5786
  # ★整體=每個定點各重放一次再合併,20 個點要好幾分鐘——
5787
  # 先回一句、放背景算、算完貼到頻道,不讓指令乾等到逾時。
@@ -8018,16 +8061,20 @@ async def cmd_wiki(interaction: discord.Interaction, query: str):
8018
 
8019
  @bot.tree.command(name="weather", description="查詢台灣城市即時天氣")
8020
  @app_commands.describe(city="城市名稱,例如:台北、高雄")
 
8021
  async def cmd_weather(interaction: discord.Interaction, city: str):
8022
  await interaction.response.defer()
 
8023
  result = await asyncio.to_thread(fetch_weather, city)
8024
  await interaction.followup.send(result or "天氣查詢失敗喵~")
8025
 
8026
 
8027
  @bot.tree.command(name="simbrief", description="查詢 SimBrief 最新航路規劃")
8028
  @app_commands.describe(username="SimBrief 飛行員用戶名")
 
8029
  async def cmd_simbrief(interaction: discord.Interaction, username: str):
8030
  await interaction.response.defer()
 
8031
  try:
8032
  result = await asyncio.wait_for(
8033
  asyncio.to_thread(get_simbrief_ofp, username), timeout=20.0
@@ -8055,6 +8102,7 @@ async def valorant_news(interaction: discord.Interaction):
8055
 
8056
  @valorant_group.command(name="player", description="查詢玩家段位與最近對戰")
8057
  @app_commands.describe(player="玩家名稱#Tag,例如:PlayerName#1234(Tag 為 # 後面的數字)")
 
8058
  async def valorant_player(interaction: discord.Interaction, player: str):
8059
  if "#" not in player:
8060
  await interaction.response.send_message(
@@ -8066,6 +8114,8 @@ async def valorant_player(interaction: discord.Interaction, player: str):
8066
  return
8067
  name, tag = player.split("#", 1)
8068
  name, tag = name.strip(), tag.strip()
 
 
8069
  if not name or not tag:
8070
  await interaction.response.send_message(
8071
  "名稱或 Tag 不能是空的喵~\n例如:`/valorant player PlayerName#1234`",
@@ -8133,6 +8183,7 @@ async def _osu_finish(interaction: discord.Interaction, msg, text: str) -> None:
8133
  app_commands.Choice(name="穩(預設):只列你常打範圍內的圖", value="穩"),
8134
  app_commands.Choice(name="挑戰:放寬到你最高星數 +0.5", value="挑戰"),
8135
  ])
 
8136
  async def osu_farm(interaction: discord.Interaction, 玩家: str,
8137
  mods: Optional[app_commands.Choice[str]] = None,
8138
  難度: Optional[app_commands.Choice[str]] = None):
@@ -8140,6 +8191,7 @@ async def osu_farm(interaction: discord.Interaction, 玩家: str,
8140
  filt = mods.value if mods else "any"
8141
  mode = 難度.value if 難度 else "穩"
8142
  who = 玩家.strip()
 
8143
  key = f"{who.lower()}|{filt}|{mode}"
8144
  hit = _osu_cache.get(key)
8145
  if hit and time.time() - hit[0] < OSU_CACHE_S:
@@ -8178,9 +8230,11 @@ async def osu_farm(interaction: discord.Interaction, 玩家: str,
8178
 
8179
  @osu_group.command(name="edge", description="跟同水準玩家比,你在哪類圖(星數/mods/AR/BPM/CS/長度)佔優勢或劣勢")
8180
  @app_commands.describe(玩家="osu! 使用者名稱或數字 ID")
 
8181
  async def osu_edge(interaction: discord.Interaction, 玩家: str):
8182
  await interaction.response.defer()
8183
  who = 玩家.strip()
 
8184
  key = f"edge|{who.lower()}"
8185
  hit = _osu_cache.get(key)
8186
  if hit and time.time() - hit[0] < OSU_CACHE_S:
@@ -8230,8 +8284,10 @@ async def delta_news(interaction: discord.Interaction):
8230
 
8231
  @delta_group.command(name="player", description="查詢三角洲行動玩家資訊")
8232
  @app_commands.describe(username="遊戲內用戶名稱")
 
8233
  async def delta_player(interaction: discord.Interaction, username: str):
8234
  await interaction.response.defer()
 
8235
  result = await asyncio.to_thread(get_delta_player, username)
8236
  await interaction.followup.send(result)
8237
 
@@ -8249,10 +8305,12 @@ async def delta_player(interaction: discord.Interaction, username: str):
8249
  app_commands.Choice(name="手機", value="手機"),
8250
  ],
8251
  )
 
8252
  async def delta_build(interaction: discord.Interaction, item: str,
8253
  mode: Optional[app_commands.Choice[str]] = None,
8254
  platform: Optional[app_commands.Choice[str]] = None):
8255
  await interaction.response.defer()
 
8256
  mode_v = mode.value if mode else None
8257
  platform_v = platform.value if platform else None
8258
  # 抓最近頻道歷史(篩選與三角洲配置相關的討論)
@@ -8308,7 +8366,15 @@ async def sb_item_autocomplete(interaction: discord.Interaction, current: str):
8308
  Thread(target=_warm, daemon=True).start()
8309
  return []
8310
  matches = sb_match_items(current or "ENCHANTED", products.keys(), limit=25)
8311
- return [app_commands.Choice(name=sb_pretty_name(m)[:100], value=m) for m in matches]
 
 
 
 
 
 
 
 
8312
 
8313
 
8314
  async def _sb_resolve_or_reply(interaction: discord.Interaction, item: str) -> Optional[str]:
@@ -8320,9 +8386,11 @@ async def _sb_resolve_or_reply(interaction: discord.Interaction, item: str) -> O
8320
  return None
8321
  key = item.strip().upper().replace(" ", "_")
8322
  if key in products:
 
8323
  return key
8324
  matches = sb_match_items(item, products.keys(), limit=5)
8325
  if len(matches) == 1:
 
8326
  return matches[0]
8327
  if matches:
8328
  opts = "\n".join(f"・`{m}`({sb_pretty_name(m)})" for m in matches)
@@ -8865,9 +8933,11 @@ async def memory_save(interaction: discord.Interaction,
8865
 
8866
  @memory_group.command(name="search", description="從本頻道已存的對話紀錄裡,用關鍵字撈回原文")
8867
  @app_commands.describe(keyword="要找的關鍵字(例:航班、改槍、某個人名)")
 
8868
  async def memory_search(interaction: discord.Interaction, keyword: str):
8869
  await interaction.response.defer()
8870
  try:
 
8871
  result = await asyncio.to_thread(search_channel_messages, interaction.channel_id, keyword)
8872
  except Exception as e:
8873
  result = f"搜尋失敗喵:`{str(e)[:150]}`"
 
5650
  await asyncio.sleep(CWA_FC_SEC)
5651
 
5652
 
5653
+ # ── 斜線指令的近期記憶(2026-09-10,主人):常打的參數值用 Tab 選 ────────────
5654
+ # 每個 (人, 指令, 參數) 記最近 30 個值,存 Supabase cmd_recent(DDL 在 SUPABASE_SETUP.md;沒建表就只在記憶體)。
5655
+ # autocomplete 回呼只碰記憶體(第一次碰到那個人才讀一次資料庫,走 to_thread 不擋 event loop);
5656
+ # 指令真的跑了才 _recent_note(不記 autocomplete 時打到一半的字)。模組沒載入就只剩固定清單,指令照常。
5657
+ try:
5658
+ import vb_recent as _RC
5659
+ _RC.configure(SUPABASE_URL, SUPABASE_KEY)
5660
+ except Exception as _rc_e:
5661
+ _RC = None
5662
+ print(f"近期記憶未載入:{_rc_e}", flush=True)
5663
+
5664
+
5665
+ def _recent_ac(cmd: str, opt: str, extra=()):
5666
+ """回一個 autocomplete 回呼:這個人最近打過的值在前,固定清單(extra)補滿 25 個。"""
5667
+ async def _cb(interaction: discord.Interaction, current: str):
5668
+ vals = []
5669
+ try:
5670
+ if _RC is not None:
5671
+ vals = await asyncio.to_thread(_RC.suggest, str(interaction.user.id), cmd, opt, current or "", tuple(extra))
5672
+ else:
5673
+ cur = (current or "").strip().lower()
5674
+ vals = [e for e in extra if not cur or cur in str(e).lower()]
5675
+ except Exception as _e:
5676
+ if _RC is not None:
5677
+ _RC._quiet("ac", _e)
5678
+ return [app_commands.Choice(name=str(v)[:100], value=str(v)[:100]) for v in vals[:25]]
5679
+ return _cb
5680
+
5681
+
5682
+ def _recent_note(interaction: discord.Interaction, cmd: str, opt: str, value) -> None:
5683
+ """指令真的跑了才記。空值不記;失敗不影響指令。"""
5684
+ if _RC is None:
5685
+ return
5686
+ try:
5687
+ _RC.record(str(interaction.user.id), cmd, opt, value)
5688
+ except Exception as _e:
5689
+ _RC._quiet("note", _e)
5690
+
5691
+
5692
  @bot.tree.command(name="rain", description="這裡會不會下雨:定點現況+上風處有沒有雨要過來")
5693
  @app_commands.describe(place="地點(例:大安、板橋、內湖)。不填=整個盆地概況",
5694
  詳細="True=附判斷依據、校準、衛星等細節(預設只給會改變決定的幾行)")
5695
+ @app_commands.autocomplete(place=_recent_ac("rain", "place", tuple(_wx.TAIPEI_SPOTS)))
5696
  async def cmd_rain(interaction: discord.Interaction, place: Optional[str] = None,
5697
  詳細: Optional[bool] = False):
5698
  await interaction.response.defer()
 
5709
  return
5710
 
5711
  p = (place or "").strip()
5712
+ _recent_note(interaction, "rain", "place", p)
5713
  if not p:
5714
  await interaction.followup.send(_wx.format_report(_wx.assess(sts)))
5715
  return
 
5811
  @bot.tree.command(name="rain_verify_gbm",
5812
  description="GBM 模型的實測成績(按場次計,真值=你周圍 3 km)")
5813
  @app_commands.describe(place="地點(例:大安、板橋、內湖);「整體」=所有定點合併。不填=台北車站")
5814
+ @app_commands.autocomplete(place=_recent_ac("rain", "place", tuple(_wx.TAIPEI_SPOTS) + ("整體",)))
5815
  async def cmd_rain_verify_gbm(interaction: discord.Interaction,
5816
  place: Optional[str] = None):
5817
  """★與 /rain_verify 是兩回事:那支驗規則式、真值是「盆地任一站」、按快照計;
 
5824
  with _wx_lock:
5825
  snaps = list(_wx_snaps)
5826
  p = (place or "").strip()
5827
+ _recent_note(interaction, "rain", "place", p)
5828
  if p in ("整體", "全部", "all"):
5829
  # ★整體=每個定點各重放一次再合併,20 個點要好幾分鐘——
5830
  # 先回一句、放背景算、算完貼到頻道,不讓指令乾等到逾時。
 
8061
 
8062
  @bot.tree.command(name="weather", description="查詢台灣城市即時天氣")
8063
  @app_commands.describe(city="城市名稱,例如:台北、高雄")
8064
+ @app_commands.autocomplete(city=_recent_ac("weather", "city", ("台北", "新北", "桃園", "新竹", "台中", "台南", "高雄")))
8065
  async def cmd_weather(interaction: discord.Interaction, city: str):
8066
  await interaction.response.defer()
8067
+ _recent_note(interaction, "weather", "city", city)
8068
  result = await asyncio.to_thread(fetch_weather, city)
8069
  await interaction.followup.send(result or "天氣查詢失敗喵~")
8070
 
8071
 
8072
  @bot.tree.command(name="simbrief", description="查詢 SimBrief 最新航路規劃")
8073
  @app_commands.describe(username="SimBrief 飛行員用戶名")
8074
+ @app_commands.autocomplete(username=_recent_ac("simbrief", "username"))
8075
  async def cmd_simbrief(interaction: discord.Interaction, username: str):
8076
  await interaction.response.defer()
8077
+ _recent_note(interaction, "simbrief", "username", username)
8078
  try:
8079
  result = await asyncio.wait_for(
8080
  asyncio.to_thread(get_simbrief_ofp, username), timeout=20.0
 
8102
 
8103
  @valorant_group.command(name="player", description="查詢玩家段位與最近對戰")
8104
  @app_commands.describe(player="玩家名稱#Tag,例如:PlayerName#1234(Tag 為 # 後面的數字)")
8105
+ @app_commands.autocomplete(player=_recent_ac("valorant", "player"))
8106
  async def valorant_player(interaction: discord.Interaction, player: str):
8107
  if "#" not in player:
8108
  await interaction.response.send_message(
 
8114
  return
8115
  name, tag = player.split("#", 1)
8116
  name, tag = name.strip(), tag.strip()
8117
+ if name and tag:
8118
+ _recent_note(interaction, "valorant", "player", f"{name}#{tag}")
8119
  if not name or not tag:
8120
  await interaction.response.send_message(
8121
  "名稱或 Tag 不能是空的喵~\n例如:`/valorant player PlayerName#1234`",
 
8183
  app_commands.Choice(name="穩(預設):只列你常打範圍內的圖", value="穩"),
8184
  app_commands.Choice(name="挑戰:放寬到你最高星數 +0.5", value="挑戰"),
8185
  ])
8186
+ @app_commands.autocomplete(玩家=_recent_ac("osu", "玩家"))
8187
  async def osu_farm(interaction: discord.Interaction, 玩家: str,
8188
  mods: Optional[app_commands.Choice[str]] = None,
8189
  難度: Optional[app_commands.Choice[str]] = None):
 
8191
  filt = mods.value if mods else "any"
8192
  mode = 難度.value if 難度 else "穩"
8193
  who = 玩家.strip()
8194
+ _recent_note(interaction, "osu", "玩家", who)
8195
  key = f"{who.lower()}|{filt}|{mode}"
8196
  hit = _osu_cache.get(key)
8197
  if hit and time.time() - hit[0] < OSU_CACHE_S:
 
8230
 
8231
  @osu_group.command(name="edge", description="跟同水準玩家比,你在哪類圖(星數/mods/AR/BPM/CS/長度)佔優勢或劣勢")
8232
  @app_commands.describe(玩家="osu! 使用者名稱或數字 ID")
8233
+ @app_commands.autocomplete(玩家=_recent_ac("osu", "玩家"))
8234
  async def osu_edge(interaction: discord.Interaction, 玩家: str):
8235
  await interaction.response.defer()
8236
  who = 玩家.strip()
8237
+ _recent_note(interaction, "osu", "玩家", who)
8238
  key = f"edge|{who.lower()}"
8239
  hit = _osu_cache.get(key)
8240
  if hit and time.time() - hit[0] < OSU_CACHE_S:
 
8284
 
8285
  @delta_group.command(name="player", description="查詢三角洲行動玩家資訊")
8286
  @app_commands.describe(username="遊戲內用戶名稱")
8287
+ @app_commands.autocomplete(username=_recent_ac("delta", "username"))
8288
  async def delta_player(interaction: discord.Interaction, username: str):
8289
  await interaction.response.defer()
8290
+ _recent_note(interaction, "delta", "username", username)
8291
  result = await asyncio.to_thread(get_delta_player, username)
8292
  await interaction.followup.send(result)
8293
 
 
8305
  app_commands.Choice(name="手機", value="手機"),
8306
  ],
8307
  )
8308
+ @app_commands.autocomplete(item=_recent_ac("delta", "item"))
8309
  async def delta_build(interaction: discord.Interaction, item: str,
8310
  mode: Optional[app_commands.Choice[str]] = None,
8311
  platform: Optional[app_commands.Choice[str]] = None):
8312
  await interaction.response.defer()
8313
+ _recent_note(interaction, "delta", "item", item)
8314
  mode_v = mode.value if mode else None
8315
  platform_v = platform.value if platform else None
8316
  # 抓最近頻道歷史(篩選與三角洲配置相關的討論)
 
8366
  Thread(target=_warm, daemon=True).start()
8367
  return []
8368
  matches = sb_match_items(current or "ENCHANTED", products.keys(), limit=25)
8369
+ # ★最近用過的物品排前面(vb_recent 的 ("sb", "item");只碰記憶體,第一次才讀資料庫)
8370
+ recent: List[str] = []
8371
+ try:
8372
+ if _RC is not None:
8373
+ recent = await asyncio.to_thread(_RC.suggest, str(interaction.user.id), "sb", "item", current or "")
8374
+ except Exception:
8375
+ recent = []
8376
+ ids = [m for m in recent if m in products] + [m for m in matches if m not in recent]
8377
+ return [app_commands.Choice(name=sb_pretty_name(m)[:100], value=m) for m in ids[:25]]
8378
 
8379
 
8380
  async def _sb_resolve_or_reply(interaction: discord.Interaction, item: str) -> Optional[str]:
 
8386
  return None
8387
  key = item.strip().upper().replace(" ", "_")
8388
  if key in products:
8389
+ _recent_note(interaction, "sb", "item", key)
8390
  return key
8391
  matches = sb_match_items(item, products.keys(), limit=5)
8392
  if len(matches) == 1:
8393
+ _recent_note(interaction, "sb", "item", matches[0])
8394
  return matches[0]
8395
  if matches:
8396
  opts = "\n".join(f"・`{m}`({sb_pretty_name(m)})" for m in matches)
 
8933
 
8934
  @memory_group.command(name="search", description="從本頻道已存的對話紀錄裡,用關鍵字撈回原文")
8935
  @app_commands.describe(keyword="要找的關鍵字(例:航班、改槍、某個人名)")
8936
+ @app_commands.autocomplete(keyword=_recent_ac("memory", "keyword"))
8937
  async def memory_search(interaction: discord.Interaction, keyword: str):
8938
  await interaction.response.defer()
8939
  try:
8940
+ _recent_note(interaction, "memory", "keyword", keyword)
8941
  result = await asyncio.to_thread(search_channel_messages, interaction.channel_id, keyword)
8942
  except Exception as e:
8943
  result = f"搜尋失敗喵:`{str(e)[:150]}`"
vb_health.py CHANGED
@@ -207,6 +207,11 @@ def _runtime_lines() -> List[str]:
207
  out.append(WD.line())
208
  except Exception as e:
209
  out.append("看門狗:(讀不到:%s)" % type(e).__name__)
 
 
 
 
 
210
  return out
211
 
212
 
 
207
  out.append(WD.line())
208
  except Exception as e:
209
  out.append("看門狗:(讀不到:%s)" % type(e).__name__)
210
+ try:
211
+ import vb_recent as RCT
212
+ out.append(RCT.line())
213
+ except Exception as e:
214
+ out.append("指令近期記憶:(讀不到:%s)" % type(e).__name__)
215
  return out
216
 
217
 
vb_recent.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """斜線指令的「近期記憶」:每個人常打的參數值,下次打指令時用 Tab 就能選(Discord autocomplete)。
3
+
4
+ ★為什麼(2026-09-10,主人):`/rain 大安`、`/osu farm 某個名字` 這種每次都一樣的字不該每次重打。
5
+ ★做法:每個 (使用者, 指令, 參數) 記最近 KEEP 個值(次數+最後時間)。autocomplete 時依「最近先」排、
6
+ 依已輸入的字過濾(子字串、不分大小寫);固定清單(例如 /rain 的地點)接在後面補滿 LIMIT 個。
7
+ 存 Supabase `cmd_recent`(重啟不掉;DDL 在 SUPABASE_SETUP.md),沒設就只在記憶體。
8
+ ★autocomplete 只有 3 秒:資料庫只在**第一次**碰到那個人時讀一次,之後全在記憶體;寫入走背景執行緒,失敗走 vb_quiet。
9
+ ★隱私:只記「參數值」(地名、玩家名、物品名),只給本人看(依 user_id),不記訊息內容。
10
+ ★同一個記憶可以跨指令共用:/rain 與 /rain_verify_gbm 都用 (rain, place),/osu farm 與 /osu edge 都用 (osu, 玩家)。
11
+ """
12
+ import datetime as dt
13
+ import threading
14
+ import time
15
+ from typing import Any, Dict, Iterable, List, Optional, Set, Tuple
16
+
17
+ TABLE = "cmd_recent"
18
+ KEEP = 30 # 每個 (人, 指令, 參數) 最多記幾個值
19
+ LIMIT = 25 # Discord autocomplete 最多 25 個選項
20
+ MAX_LEN = 100 # Discord 選項值上限
21
+ UA = {"User-Agent": "vanilla-bot recent/1.0"}
22
+
23
+ _LOCK = threading.Lock()
24
+ _MEM: Dict[str, Dict[Tuple[str, str], Dict[str, List[float]]]] = {} # uid → {(cmd, opt): {value: [n, last_epoch]}}
25
+ _LOADED: Set[str] = set()
26
+ _STORE: Optional["Store"] = None
27
+ _STAT: Dict[str, Any] = {"writes": 0, "write_err": 0, "loads": 0, "load_err": 0, "last_err": ""}
28
+
29
+
30
+ class Store:
31
+ """Supabase(PostgREST)。get/post 可注入(測試)。沒有 url/key 就是純記憶體。"""
32
+
33
+ def __init__(self, url: str = "", key: str = "", get=None, post=None):
34
+ self.url, self.key = url.rstrip("/"), key
35
+ if (get is None or post is None) and self.on:
36
+ import requests
37
+ get, post = get or requests.get, post or requests.post
38
+ self.get, self.post = get, post
39
+
40
+ @property
41
+ def on(self) -> bool:
42
+ return bool(self.url and self.key)
43
+
44
+ def _headers(self) -> Dict[str, str]:
45
+ return {"apikey": self.key, "Authorization": "Bearer " + self.key,
46
+ "Content-Type": "application/json", **UA}
47
+
48
+ def load(self, uid: str) -> List[Dict[str, Any]]:
49
+ if not self.on:
50
+ return []
51
+ r = self.get("%s/rest/v1/%s" % (self.url, TABLE), headers=self._headers(), timeout=8,
52
+ params={"select": "cmd,opt,value,n,last", "user_id": "eq." + uid,
53
+ "order": "last.desc", "limit": "500"})
54
+ if r.status_code != 200:
55
+ raise RuntimeError("HTTP %d %s" % (r.status_code, str(getattr(r, "text", ""))[:80]))
56
+ return r.json() or []
57
+
58
+ def upsert(self, rows: List[Dict[str, Any]]) -> None:
59
+ if not self.on or not rows:
60
+ return
61
+ r = self.post("%s/rest/v1/%s" % (self.url, TABLE), json=rows, timeout=10,
62
+ headers={**self._headers(), "Prefer": "resolution=merge-duplicates,return=minimal"})
63
+ if r.status_code not in (200, 201, 204):
64
+ raise RuntimeError("HTTP %d %s" % (r.status_code, str(getattr(r, "text", ""))[:80]))
65
+
66
+
67
+ def configure(url: str = "", key: str = "", get=None, post=None) -> None:
68
+ global _STORE
69
+ with _LOCK:
70
+ _STORE = Store(url, key, get, post)
71
+ _MEM.clear()
72
+ _LOADED.clear()
73
+
74
+
75
+ def _quiet(where: str, e: Exception) -> None:
76
+ _STAT["last_err"] = "%s: %s" % (type(e).__name__, str(e)[:80])
77
+ try:
78
+ import vb_quiet as Q
79
+ Q.quiet("recent." + where, e)
80
+ except Exception:
81
+ pass
82
+
83
+
84
+ def _epoch(s: Any) -> float:
85
+ try:
86
+ return dt.datetime.fromisoformat(str(s).replace("Z", "+00:00")).timestamp()
87
+ except Exception:
88
+ return 0.0
89
+
90
+
91
+ def _ensure_loaded(uid: str) -> None:
92
+ """第一次碰到這個人才讀資料庫;讀失敗也標成已載入(不要每次 autocomplete 都撞資料庫)。"""
93
+ with _LOCK:
94
+ if uid in _LOADED:
95
+ return
96
+ store = _STORE
97
+ _LOADED.add(uid)
98
+ if store is None or not store.on:
99
+ return
100
+ try:
101
+ rows = store.load(uid)
102
+ _STAT["loads"] += 1
103
+ except Exception as e:
104
+ _STAT["load_err"] += 1
105
+ _quiet("load", e)
106
+ return
107
+ with _LOCK:
108
+ m = _MEM.setdefault(uid, {})
109
+ for r in rows:
110
+ try:
111
+ d = m.setdefault((str(r["cmd"]), str(r["opt"])), {})
112
+ v = str(r["value"])
113
+ if v not in d:
114
+ d[v] = [float(r.get("n") or 1), _epoch(r.get("last"))]
115
+ except Exception:
116
+ continue
117
+
118
+
119
+ def record(uid: str, cmd: str, opt: str, value: Any, now: Optional[float] = None,
120
+ persist: bool = True) -> bool:
121
+ """記一次。空值、太長的值不記。回有沒有記。"""
122
+ v = str(value or "").strip()
123
+ if not v or len(v) > MAX_LEN:
124
+ return False
125
+ _ensure_loaded(uid)
126
+ t = now if now is not None else time.time()
127
+ with _LOCK:
128
+ d = _MEM.setdefault(uid, {}).setdefault((cmd, opt), {})
129
+ n = d[v][0] + 1 if v in d else 1.0
130
+ d[v] = [n, t]
131
+ if len(d) > KEEP: # 只留最近 KEEP 個
132
+ for old in sorted(d, key=lambda k: d[k][1])[:len(d) - KEEP]:
133
+ d.pop(old, None)
134
+ store = _STORE
135
+ if persist and store is not None and store.on:
136
+ row = {"user_id": uid, "cmd": cmd, "opt": opt, "value": v, "n": int(n),
137
+ "last": dt.datetime.fromtimestamp(t, dt.timezone.utc).isoformat()}
138
+
139
+ def _w() -> None:
140
+ try:
141
+ store.upsert([row])
142
+ _STAT["writes"] += 1
143
+ except Exception as e:
144
+ _STAT["write_err"] += 1
145
+ _quiet("write", e)
146
+ threading.Thread(target=_w, daemon=True, name="vb_recent").start()
147
+ return True
148
+
149
+
150
+ def suggest(uid: str, cmd: str, opt: str, current: str = "", extra: Iterable[str] = (),
151
+ limit: int = LIMIT) -> List[str]:
152
+ """這個人在這個參數打過的值,最近的在前、只留含 current 的;再用 extra(固定清單)補滿。"""
153
+ _ensure_loaded(uid)
154
+ cur = (current or "").strip().lower()
155
+ with _LOCK:
156
+ d = dict(_MEM.get(uid, {}).get((cmd, opt), {}))
157
+ vals = [v for v in sorted(d, key=lambda k: (-d[k][1], -d[k][0])) if not cur or cur in v.lower()]
158
+ seen = set(vals)
159
+ for e in extra:
160
+ e = str(e)
161
+ if len(vals) >= limit:
162
+ break
163
+ if e in seen or (cur and cur not in e.lower()) or len(e) > MAX_LEN:
164
+ continue
165
+ vals.append(e)
166
+ seen.add(e)
167
+ return vals[:limit]
168
+
169
+
170
+ def line() -> str:
171
+ with _LOCK:
172
+ users = len(_MEM)
173
+ n = sum(len(d) for m in _MEM.values() for d in m.values())
174
+ on = bool(_STORE and _STORE.on)
175
+ return "指令近期記憶:%d 人、%d 個值在記憶體;存 %s;寫 %d(失敗 %d)、讀 %d(失敗 %d)%s" % (
176
+ users, n, "Supabase" if on else "記憶體", _STAT["writes"], _STAT["write_err"], _STAT["loads"], _STAT["load_err"],
177
+ (";最近錯誤 " + _STAT["last_err"]) if _STAT["last_err"] else "")
178
+
179
+
180
+ def reset() -> None:
181
+ global _STORE
182
+ with _LOCK:
183
+ _STORE = None
184
+ _MEM.clear()
185
+ _LOADED.clear()
186
+ _STAT.update(writes=0, write_err=0, loads=0, load_err=0, last_err="")