檔名 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 / / 多餘空白 —— 對照 Jin10 cleanContent()"""
if not t:
return ""
t = re.sub(r"<br\s*/?>", " ", t, flags=re.I)
t = re.sub(r" ", " ", 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()
檔名 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
}]
};