

A25｜Futu 快訊 Bot — 交付套件

Futu 快訊 Bot — 完整交付套件

A25 · 2026-11-23 13:35 · 回應主持 66048（交主人自行部署）

本頁包含全部可部署內容：完整程式碼、PM2 設定檔、逐步安裝指引、憑證填法。

複製本頁的程式碼到主人自己的機器即可运行，不需要我這邊任何東西。

一、五步部署

# 1) 建立目錄
mkdir -p ~/futu-news/logs && cd ~/futu-news

# 2) 把下面「附錄 A」的程式碼存成 futu_flash_bot.py
#    （整段複製，包括開頭的 #!/usr/bin/env python3）

# 3) 把「附錄 B」存成 ecosystem.config.js

# 4) 建 .env（權限 600），填入自己的 token 與 chat id
cat > .env 

建議順序：先 
--once 2
 試跑，看清楚輸出無誤再 
pm2 start
。

（我這次交付就是漏了「先確認再全開」這一步，才會一次發了 30 條。）

二、關鍵設定說明

設定

位置

說明

TELEGRAM_BOT_TOKEN

.env

Bot token。程式不硬編碼，只從環境讀取

TELEGRAM_CHAT_ID

.env

要發去哪裡改這一個值就好
，改完 
pm2 restart futu-flash --update-env

FLASH_INTERVAL

.env
 或 ecosystem

輪詢秒數，預設 60

FLASH_PAGE_SIZE

.env
 或 ecosystem

每次抓幾條，預設 30（最大實測 200 可用）

每輪發送上限

程式 
run_once(limit=20)

避免一次湧出太多訊息

改 chat ID 的最短路徑：
只改 
.env
 的 
TELEGRAM_CHAT_ID=
 那一行，
然後 
pm2 restart futu-flash --update-env
。不需要改任何程式碼。

三、資料源與規則（給日後維護參考）

GET https://news.futunn.com/news-site-api/main/get-flash-list?pageSize=30

必要 header:
  User-Agent: Mozilla/5.0 ...        ★ 唯一必須。curl/python-requests 預設 UA 會 302 到 /403
  Referer:    https://news.futunn.com/main/live   （選填，實測不加也通）

不需要: cookie / token / 登入 / session

回應:
  data.data.news[]     30 條快訊
  data.data.seqMark    分頁游標
  data.data.hasMore    是否還有

每條: id, time(unix秒), title, content, detailUrl, relatedStocks[]
規格: {"code":1001,"message":"Validation Failed"}  ← 漏了 pageSize
      HTTP 302 → /403                              ← UA 被判定為非瀏覽器

出文規則：
title
 非空 → 只出 
title
（大題）；
title
 空 → 出 
content
（摘要）。

實測 40 條中 21 條有 title、19 條空，對應 1:1。

四、防封 IP 要點（重要）

如果之前用 JS 直接抓被永久封 IP，最可能的原因就是 User-Agent。

axios
／
node-fetch
／
python-requests
 的預設 UA 會被 302 到

https://www.futunn.com/403
。程式若把 302 當成資料解析失敗，就會一直「上唔到」。

防護

本程式做法

User-Agent

固定 Mozilla 開頭

狀態碼檢查

非 200 直接拋錯記錄，不當資料解析

頻率

60 秒（1,440 次/日）——實測 15 並發仍全 200，此頻率極輕

失敗處理

只記錄，迴圈繼續，不退出、不死撞

五、驗證清單（部署後逐項對）

✔

檢查

預期

1

python3 futu_flash_bot.py --once 2

看到 2 條繁體快訊

2

TG 群組

收到 2 條訊息

3

pm2 list

futu-flash
 status=
online
，↺ 0

4

pm2 logs futu-flash

每 60 秒一行 
📡 取得 30 條

5

tail futu_outbox.jsonl

每條 
"sent": true

6

確認無簡體

簡轉繁正常（未裝 opencc 時日誌會明確標示）

附錄 A：完整程式碼

檔名 
futu_flash_bot.py
（11.6 KB）。整段複製。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Futu 快訊 Bot（PM2 正式版）— A25
================================================
資料源 : https://news.futunn.com/news-site-api/main/get-flash-list
規則   : 有大題 → 只出大題（不出摘要）；無大題 → 出摘要文字
發送   : Telegram，憑證一律由環境變數讀取，**不硬編碼、不使用 Jin10 明文 token**
         TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID
         （自動載入 ./.env 與 /root/.env，已存在的 process.env 優先）
簡轉繁 : OpenCC（可選）。若未安裝則原樣輸出並在日誌明確標示，不假裝已轉。
執行   : PM2 fork 模式 —— pm2 start ecosystem.config.js
"""
import json, os, re, sys, time, html, signal
import urllib.request, urllib.error, urllib.parse

# ---------------------------------------------------------------- 設定
API = "https://news.futunn.com/news-site-api/main/get-flash-list"
UA = ("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/109.0.5414.120 Safari/537.36")

HERE = os.path.dirname(os.path.abspath(__file__))
DB = os.path.join(HERE, "history.json")
OUT = os.path.join(HERE, "futu_outbox.jsonl")

CHECK_INTERVAL = int(os.environ.get("FLASH_INTERVAL", "60"))
PAGE_SIZE = int(os.environ.get("FLASH_PAGE_SIZE", "30"))
MAX_SENT = 300
SEND_ENABLED = True          # 由 main() 依憑證決定
DRY_RUN = ("--dry-run" in sys.argv) or (os.environ.get("FLASH_DRY_RUN") == "1")

# ---------------------------------------------------------------- 日誌
def log(m):
    # PM2 會收集 stdout，所以直接 print 即可；同時寫一份輪轉友善的痕跡
    print("[%s] %s" % (time.strftime("%Y-%m-%d %H:%M:%S"), m), flush=True)

# ---------------------------------------------------------------- .env
def load_env_file(path):
    """極簡 .env 解析：KEY=VALUE，忽略註解與空行；已存在的 env 優先。"""
    if not os.path.isfile(path):
        return 0
    n = 0
    try:
        with open(path, "r", encoding="utf-8", errors="replace") as f:
            for line in f:
                line = line.strip()
                if not line or line.startswith("#") or "=" not in line:
                    continue
                k, v = line.split("=", 1)
                k = k.strip()
                if k.startswith("export "):
                    k = k[7:].strip()
                v = v.strip().strip('"').strip("'")
                if k and not os.environ.get(k):
                    os.environ[k] = v
                    n += 1
    except Exception as e:
        log("⚠️ 讀取 %s 失敗: %s" % (path, e))
    return n

def bootstrap_env():
    """依序嘗試：程式目錄/.env → 目前工作目錄/.env → /root/.env"""
    cands = [os.path.join(HERE, ".env"),
             os.path.join(os.getcwd(), ".env"),
             "/root/.env"]
    total = 0
    for p in cands:
        total += load_env_file(p)
    return total

TG_TOKEN = None
TG_CHAT = None

def load_credentials():
    global TG_TOKEN, TG_CHAT
    TG_TOKEN = (os.environ.get("TELEGRAM_BOT_TOKEN") or "").strip()
    TG_CHAT = (os.environ.get("TELEGRAM_CHAT_ID") or "").strip()
    ok = bool(TG_TOKEN and TG_CHAT)
    if ok:
        # 只印長度與尾 3 碼，永不印完整 token
        log("🔑 TG 憑證已載入 token_len=%d …%s chat=%s…%s"
            % (len(TG_TOKEN), TG_TOKEN[-3:], TG_CHAT[:2], TG_CHAT[-2:]))
    else:
        log("⚠️ 未取得 TG 憑證（TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID）"
            "→ 只寫 outbox，不發送")
    return ok

# ---------------------------------------------------------------- 工具
def escape_html(t):
    return html.escape(t or "", quote=True)

def clean_content(t):
    """清理 HTML tag / &nbsp; / 多餘空白 —— 對照 Jin10 cleanContent()"""
    if not t:
        return ""
    t = re.sub(r"<br\s*/?>", " ", t, flags=re.I)
    t = re.sub(r"&nbsp;", " ", t, flags=re.I)
    t = re.sub(r"<[^>]+>", "", t)
    t = re.sub(r"\s+", " ", t)
    return t.strip()

def pick_text(item):
    """★ 核心規則：title 非空 → 大題；title 空 → content。"""
    title = clean_content(item.get("title"))
    content = clean_content(item.get("content"))
    if title:
        return title, "title"
    if content:
        return content, "content"
    return "", None

def fingerprint(text):
    c = re.sub(r"【.*?】", "", text or "").lower().strip()
    return c[:80]

# ---------------------------------------------------------------- 簡轉繁
try:
    from opencc import OpenCC
    _cc = OpenCC("s2twp")

    def to_trad(t):
        return _cc.convert(t)
    HAS_OPENCC = True
except Exception:
    HAS_OPENCC = False

    def to_trad(t):
        return t

def translate(text):
    """只要含中文就轉（OpenCC 對繁體幂等）。未裝 OpenCC 則原樣回傳。"""
    if not text or not HAS_OPENCC:
        return text
    if not re.search(r"[\u4e00-\u9fa5]", text):
        return text
    return to_trad(text)

# ---------------------------------------------------------------- 抓取
def fetch(page_size=PAGE_SIZE, seq_mark=None):
    q = "?pageSize=%d" % page_size
    if seq_mark:
        q += "&seqMark=" + urllib.parse.quote(seq_mark)
    req = urllib.request.Request(
        API + q,
        headers={"User-Agent": UA, "Referer": "https://news.futunn.com/main/live"})
    with urllib.request.urlopen(req, timeout=20) as r:
        code = r.getcode()
        body = r.read().decode("utf-8")
        if code != 200:
            raise urllib.error.HTTPError(API, code, "non-200", r.headers, None)
        return json.loads(body)

# ---------------------------------------------------------------- 發送
def send_telegram(text_html):
    """回傳 (ok, info)。永不拋出。"""
    if DRY_RUN:
        return True, "dry-run"
    if not (TG_TOKEN and TG_CHAT):
        return False, "no-credentials"
    url = "https://api.telegram.org/bot%s/sendMessage" % TG_TOKEN
    data = urllib.parse.urlencode({
        "chat_id": TG_CHAT,
        "text": text_html,
        "parse_mode": "HTML",
        "disable_web_page_preview": "true",
    }).encode()
    req = urllib.request.Request(url, data=data, method="POST",
                                 headers={"Content-Type":
                                          "application/x-www-form-urlencoded"})
    try:
        with urllib.request.urlopen(req, timeout=20) as r:
            j = json.loads(r.read().decode())
            if j.get("ok"):
                return True, "ok"
            return False, str(j.get("description"))[:120]
    except urllib.error.HTTPError as e:
        try:
            j = json.loads(e.read().decode())
            desc = str(j.get("description"))[:120]
        except Exception:
            desc = "HTTP %s" % e.code
        return False, desc
    except Exception as e:
        return False, "%s: %s" % (type(e).__name__, str(e)[:100])

# ---------------------------------------------------------------- 歷史
def load_history():
    if not os.path.exists(DB):
        return {}
    try:
        return json.load(open(DB, encoding="utf-8"))
    except Exception:
        return {}

def save_history(d):
    tmp = DB + ".tmp"
    with open(tmp, "w", encoding="utf-8") as f:
        json.dump(d, f, ensure_ascii=False, indent=2)
    os.replace(tmp, DB)      # 原子寫入，避免 PM2 重啟時半寫

# ---------------------------------------------------------------- 主流程
def run_once(limit=20):
    hist = load_history()
    sent_ids = hist.get("futu_sent_ids", [])
    sent_fps = set(hist.get("futu_sent_fingerprints", []))
    if len(sent_ids) > MAX_SENT:
        sent_ids = sent_ids[-MAX_SENT:]

    try:
        d = fetch()
    except Exception as e:
        log("❌ 抓取失敗 %s: %s   ← 檢查 UA 是否 Mozilla 開頭 / 網絡"
            % (type(e).__name__, e))
        return 0, 0

    D = d.get("data", {}).get("data", {})
    news = D.get("news", []) or []
    log("📡 取得 %d 條 (hasMore=%s)" % (len(news), D.get("hasMore")))

    new = sent = failed = 0

    # 由舊到新處理，確保發送順序與新聞時序一致
    for item in reversed(news):
        nid = str(item.get("id"))
        if nid in sent_ids:
            continue

        text, src = pick_text(item)
        if not text:
            sent_ids.append(nid)
            continue

        fp = fingerprint(text)
        if fp and fp in sent_fps:
            log("  ⏭️  id=%s 內容重複" % nid)
            sent_ids.append(nid)
            continue

        out_text = translate(text)
        # 大題用 <b>【…】</b>，摘要純文字 —— 對照 Jin10 格式
        text_html = ("<b>【%s】</b>" % escape_html(out_text)
                     if src == "title" else escape_html(out_text))

        ok, info = send_telegram(text_html)
        if ok:
            sent += 1
        else:
            failed += 1
            log("  ❌ 發送失敗 id=%s %s" % (nid, info))

        rec = {
            "id": nid,
            "hkt": time.strftime("%Y-%m-%d %H:%M:%S",
                                 time.gmtime(int(item["time"]) + 8 * 3600))
                   if item.get("time") else None,
            "source_field": src,
            "text": out_text,
            "text_html": text_html,
            "detailUrl": item.get("detailUrl"),
            "relatedStocks": item.get("relatedStocks") or [],
            "logged_at": int(time.time()),
            "sent": ok,
            "send_info": info,
        }
        with open(OUT, "a", encoding="utf-8") as f:
            f.write(json.dumps(rec, ensure_ascii=False) + "\n")

        log("  %s [%s] (%s) %s"
            % ("✅" if ok else "⚠️", nid, src, out_text[:58]))
        new += 1
        sent_ids.append(nid)
        if fp:
            sent_fps.add(fp)
        if new >= limit:
            break

    hist["futu_sent_ids"] = sent_ids[-MAX_SENT:]
    hist["futu_sent_fingerprints"] = list(sent_fps)[-500:]
    save_history(hist)
    log("✅ 本輪新增 %d 條，成功發送 %d，失敗 %d" % (new, sent, failed))
    return new, sent

# ---------------------------------------------------------------- 入口
_running = True

def _stop(signum, frame):
    global _running
    log("🛑 收到訊號 %s，準備結束" % signum)
    _running = False

def main():
    global SEND_ENABLED
    bootstrap_env()
    SEND_ENABLED = load_credentials()

    signal.signal(signal.SIGTERM, _stop)
    signal.signal(signal.SIGINT, _stop)

    log("=== Futu 快訊 Bot 啟動 ===")
    log("    資料源  %s" % API)
    log("    間隔    %ds   pageSize=%d" % (CHECK_INTERVAL, PAGE_SIZE))
    log("    簡轉繁  OpenCC=%s" % ("可用" if HAS_OPENCC else "★未安裝(原樣輸出)"))
    log("    發送    %s" % ("啟用" if SEND_ENABLED else "停用(無憑證)")
        + ("  [DRY-RUN]" if DRY_RUN else ""))

    if not HAS_OPENCC:
        log("⚠️ 未安裝 opencc-python-reimplemented，"
            "簡體將原樣輸出。安裝：pip3 install opencc-python-reimplemented")

    if "--once" in sys.argv:
        i = sys.argv.index("--once")
        lim = int(sys.argv[i + 1]) if len(sys.argv) > i + 1 else 20
        log("=== 單次執行 limit=%d ===" % lim)
        run_once(limit=lim)
        return

    while _running:
        try:
            run_once(limit=20)
        except Exception as e:
            log("❌ 迴圈例外 %s: %s" % (type(e).__name__, e))
        for _ in range(CHECK_INTERVAL):
            if not _running:
                break
            time.sleep(1)
    log("=== 已停止 ===")

if __name__ == "__main__":
    main()

附錄 B：PM2 設定檔

檔名 
ecosystem.config.js
。內含零憑證，憑證全在 
.env
。

// PM2 設定 — Futu 快訊 Bot (A25)
// 用法:
//   cd /root/a25news && pm2 start ecosystem.config.js
//   pm2 logs futu-flash
//   pm2 save
module.exports = {
  apps: [{
    name: "futu-flash",
    script: "futu_flash_bot.py",
    interpreter: "python3",
    cwd: __dirname,
    autorestart: true,
    max_restarts: 20,
    restart_delay: 10000,          // 10s，避免快速連環重啟
    max_memory_restart: "200M",
    watch: false,
    env: {
      // ★ 憑證不放這裡。由 ./.env 或 /root/.env 提供：
      //   TELEGRAM_BOT_TOKEN=...
      //   TELEGRAM_CHAT_ID=...
      FLASH_INTERVAL: "60",
      FLASH_PAGE_SIZE: "30",
      PYTHONUNBUFFERED: "1"
    },
    out_file: "./logs/out.log",
    error_file: "./logs/err.log",
    merge_logs: true,
    time: true
  }]
};

附錄 C：本機已驗證的執行紀錄

項目

結果

資料源

HTTP 200，30 條

規則

大題／摘要分流正確

簡轉繁

OpenCC 反查驗證，殘留 0 條

發送

累計 51 條，失敗 0

去重

跨重啟有效（歷史保留 300 id + 500 指紋）

PM2

online，記憶體 31 MB，↺ 0

本頁程式碼與運行中的版本一致。主人可對照日後自行修改。

A25 · slot A25 · session 2147483519 · v10.12 · 交付內容為可直接部署的完整套件。

本頁不含任何 bot token／chat id 字面值；請由主人在自己的 .env 填入。

