forked from sstklen/trump-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchatbot_server.py
More file actions
1860 lines (1615 loc) · 70.1 KB
/
chatbot_server.py
File metadata and controls
1860 lines (1615 loc) · 70.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
川普密碼 — 聊天機器人(Gemini Flash + 群眾智慧回收)
功能:
1. 網頁聊天介面 — 讓任何人問 Trump Code 的信號和預測
2. Gemini Flash 回答 — 便宜(3 把 key 免費額度輪用)
3. 群眾智慧回收 — 收集用戶的邏輯建議,餵回學習循環
架構:
Opus 分析結果 → 當 system prompt → Gemini Flash 回答用戶
用戶提出邏輯 → 存到 crowd_insights.json → Opus 下次分析時參考
啟動:
python3 chatbot_server.py
→ 瀏覽器打開 http://localhost:8888
"""
from __future__ import annotations
import json
import hashlib
import time
import urllib.request
import urllib.error
from collections import defaultdict
from datetime import datetime, timezone
from http.server import HTTPServer, BaseHTTPRequestHandler
from pathlib import Path
from typing import Any
BASE = Path(__file__).parent
DATA = BASE / "data"
ANALYTICS_FILE = DATA / "analytics.json"
# === 訪客追蹤系統 ===
_analytics_cache = {
'total_requests': 0,
'total_unique_ips': 0,
'daily': {}, # {"2026-03-16": {"views": 10, "unique_ips": ["hash1","hash2"], "pages": {"/": 5, "/api/signals": 3}}}
'hourly': {}, # {"2026-03-16T14": 5}
'pages': {}, # {"/": 100, "/api/signals": 50}
'user_agents': {}, # {"Mozilla": 30, "GPTBot": 5}
}
def _load_analytics():
"""啟動時載入分析數據"""
global _analytics_cache
if ANALYTICS_FILE.exists():
try:
with open(ANALYTICS_FILE, encoding='utf-8') as f:
_analytics_cache = json.load(f)
except Exception:
pass
def _save_analytics():
"""每 50 次請求存一次檔"""
try:
with open(ANALYTICS_FILE, 'w', encoding='utf-8') as f:
json.dump(_analytics_cache, f, ensure_ascii=False, indent=2)
except Exception:
pass
def _track_request(ip: str, path: str, user_agent: str):
"""記錄每次請求"""
now = datetime.now(timezone.utc)
today = now.strftime('%Y-%m-%d')
hour_key = now.strftime('%Y-%m-%dT%H')
ip_hash = hashlib.sha256(ip.encode()).hexdigest()[:12]
_analytics_cache['total_requests'] = _analytics_cache.get('total_requests', 0) + 1
# 每日統計
if today not in _analytics_cache.get('daily', {}):
_analytics_cache.setdefault('daily', {})[today] = {'views': 0, 'unique_ips': [], 'pages': {}}
day = _analytics_cache['daily'][today]
day['views'] += 1
if ip_hash not in day.get('unique_ips', []):
day.setdefault('unique_ips', []).append(ip_hash)
day.setdefault('pages', {})[path] = day['pages'].get(path, 0) + 1
# 每小時統計
_analytics_cache.setdefault('hourly', {})[hour_key] = _analytics_cache.get('hourly', {}).get(hour_key, 0) + 1
# 頁面統計
_analytics_cache.setdefault('pages', {})[path] = _analytics_cache.get('pages', {}).get(path, 0) + 1
# User-Agent 分類
ua_short = 'Unknown'
ua_lower = (user_agent or '').lower()
if 'gptbot' in ua_lower: ua_short = 'GPTBot'
elif 'claudebot' in ua_lower: ua_short = 'ClaudeBot'
elif 'perplexitybot' in ua_lower: ua_short = 'PerplexityBot'
elif 'googlebot' in ua_lower: ua_short = 'Googlebot'
elif 'bingbot' in ua_lower: ua_short = 'Bingbot'
elif 'twitterbot' in ua_lower: ua_short = 'TwitterBot'
elif 'facebookexternalhit' in ua_lower: ua_short = 'FacebookBot'
elif 'chrome' in ua_lower: ua_short = 'Chrome'
elif 'safari' in ua_lower: ua_short = 'Safari'
elif 'firefox' in ua_lower: ua_short = 'Firefox'
elif 'curl' in ua_lower: ua_short = 'curl'
elif 'python' in ua_lower: ua_short = 'Python'
_analytics_cache.setdefault('user_agents', {})[ua_short] = _analytics_cache.get('user_agents', {}).get(ua_short, 0) + 1
# 算 unique IPs 總數
all_ips = set()
for d in _analytics_cache.get('daily', {}).values():
all_ips.update(d.get('unique_ips', []))
_analytics_cache['total_unique_ips'] = len(all_ips)
# 每 50 次存檔
if _analytics_cache['total_requests'] % 50 == 0:
_save_analytics()
# 啟動時載入
_load_analytics()
def _load(filename: str) -> dict | list | None:
"""安全載入 data/ 下的 JSON 檔案。"""
path = DATA / filename
if not path.exists():
return None
with open(path, encoding='utf-8') as f:
return json.load(f)
# === 每日額度門檻 ===
# 1 把 Gemini key 的免費額度 ≈ 500 次/天
# 3 把 key 共 1500,但只用 1 把的量當每日上限(其他留 buffer)
DAILY_GLOBAL_LIMIT = 500 # 全站每日總量
DAILY_PER_USER = 15 # 每人每日最多幾則(500/30人≈15)
RATE_LIMIT_COOLDOWN = 3 # 每則之間至少幾秒
MSG_MIN_LENGTH = 5 # 最短幾個字
MSG_MAX_LENGTH = 800 # 最長幾個字
INSIGHT_MIN_LENGTH = 20 # 洞見最短字數
BANNED_PATTERNS = [ # 垃圾訊息關鍵字
'http://', 'https://', '.com/', 'click here',
'buy now', 'free money', 'airdrop', 'giveaway',
]
# 每日計數器(UTC 日期切換時自動重置)
_daily_state = {
'date': '', # 當天日期,換日自動重置
'global_count': 0, # 全站今日用量
'per_user': defaultdict(int), # 每人今日用量
'last_msg': defaultdict(float), # 每人上次發訊時間
}
# === Gemini Flash 三把 Key 輪用 ===
# 從環境變數讀取,不寫死在代碼裡
# export GEMINI_KEYS="key1,key2,key3"
import os as _os
_keys_str = _os.environ.get('GEMINI_KEYS', '')
GEMINI_KEYS = [k.strip() for k in _keys_str.split(',') if k.strip()]
if not GEMINI_KEYS:
print("⚠️ 請設定 GEMINI_KEYS 環境變數: export GEMINI_KEYS=\'key1,key2,key3\'")
print(" 沒有 key 的話聊天功能無法使用")
_key_index = 0 # 輪用指標
GEMINI_MODEL = "gemini-2.5-flash"
CROWD_INSIGHTS_FILE = DATA / "crowd_insights.json"
GAME_CURRENT_FILE = DATA / "game_current.json"
GAME_PLAYERS_FILE = DATA / "game_players.json"
GAME_HISTORY_FILE = DATA / "game_history.json"
GAME_ROUND_HOURS = 6
PORT = 8888
def _check_rate_limit(ip: str) -> tuple[str | None, dict]:
"""
每日額度檢查。
回傳:(錯誤訊息或None, 當日統計)
換日自動重置所有計數器。
"""
now = time.time()
today = datetime.now(timezone.utc).strftime('%Y-%m-%d')
anon = _anon_id(ip)
# 換日 → 重置
if _daily_state['date'] != today:
_daily_state['date'] = today
_daily_state['global_count'] = 0
_daily_state['per_user'] = defaultdict(int)
_daily_state['last_msg'] = defaultdict(float)
stats = {
'daily_used': _daily_state['global_count'],
'daily_limit': DAILY_GLOBAL_LIMIT,
'daily_remaining': DAILY_GLOBAL_LIMIT - _daily_state['global_count'],
'your_used': _daily_state['per_user'][anon],
'your_limit': DAILY_PER_USER,
}
# 全站每日上限
if _daily_state['global_count'] >= DAILY_GLOBAL_LIMIT:
return (f"今天的額度用完了({DAILY_GLOBAL_LIMIT}/{DAILY_GLOBAL_LIMIT})。"
f"明天 UTC 0:00 重置,到時再來!", stats)
# 每人每日上限
if _daily_state['per_user'][anon] >= DAILY_PER_USER:
return (f"你今天已經聊了 {DAILY_PER_USER} 則。"
f"明天再來吧!把機會留給其他人 😊", stats)
# 冷卻時間
last = _daily_state['last_msg'].get(anon, 0)
if now - last < RATE_LIMIT_COOLDOWN:
return (f"慢一點,{RATE_LIMIT_COOLDOWN} 秒後再發。", stats)
# 通過 → 計數
_daily_state['global_count'] += 1
_daily_state['per_user'][anon] += 1
_daily_state['last_msg'][anon] = now
stats['daily_used'] = _daily_state['global_count']
stats['daily_remaining'] = DAILY_GLOBAL_LIMIT - _daily_state['global_count']
stats['your_used'] = _daily_state['per_user'][anon]
return (None, stats)
def _check_message(text: str) -> str | None:
"""
檢查訊息品質。
回傳 None = 通過,回傳字串 = 被擋。
"""
if len(text) < MSG_MIN_LENGTH:
return "訊息太短了,多寫幾個字吧。"
if len(text) > MSG_MAX_LENGTH:
return f"訊息太長了(最多 {MSG_MAX_LENGTH} 字),精簡一下。"
if any(p in text.lower() for p in BANNED_PATTERNS):
return "請不要貼連結或廣告。"
return None
def _anon_id(ip: str) -> str:
"""把 IP 匿名化成短 hash,不存原始 IP。"""
return hashlib.sha256(ip.encode()).hexdigest()[:8]
def _next_key() -> str:
"""輪用三把 key,每次呼叫換一把。"""
global _key_index
key = GEMINI_KEYS[_key_index % len(GEMINI_KEYS)]
_key_index += 1
return key
def _load_system_context() -> str:
"""載入 Opus 分析結果當 system prompt。"""
context_parts = []
# Opus 分析
opus_file = DATA / "opus_analysis.json"
if opus_file.exists():
with open(opus_file, encoding='utf-8') as f:
opus = json.load(f)
context_parts.append("=== Opus 分析摘要 ===")
context_parts.append(f"系統狀態: {opus.get('overall_system_health', '?')}")
context_parts.append(f"重點: {opus.get('priority_action', '?')}")
if opus.get('pattern_shift_detected'):
context_parts.append(f"模式變化: {opus.get('pattern_shift_details', '')[:200]}")
# 模型排行
briefing_file = DATA / "opus_briefing.json"
if briefing_file.exists():
with open(briefing_file, encoding='utf-8') as f:
briefing = json.load(f)
perf = briefing.get('model_performance', {})
if perf:
context_parts.append("\n=== 模型排行 ===")
for mid, s in sorted(perf.items(), key=lambda x: -x[1].get('win_rate', 0)):
context_parts.append(
f" {s.get('name', mid)}: {s.get('win_rate', 0):.1f}% 命中率, "
f"{s.get('avg_return', 0):+.3f}% 報酬, {s.get('total_trades', 0)} 筆"
)
# 日報
report_file = DATA / "daily_report.json"
if report_file.exists():
with open(report_file, encoding='utf-8') as f:
report = json.load(f)
context_parts.append(f"\n=== 最新日報 ({report.get('date', '?')}) ===")
context_parts.append(f"推文數: {report.get('posts_today', 0)}")
context_parts.append(f"信號: {', '.join(report.get('signals_detected', []))}")
direction = report.get('direction_summary', {})
context_parts.append(f"共識: {direction.get('consensus', '?')} "
f"(多{direction.get('LONG', 0)} / 空{direction.get('SHORT', 0)})")
# 信號信心度
sc_file = DATA / "signal_confidence.json"
if sc_file.exists():
with open(sc_file, encoding='utf-8') as f:
sc = json.load(f)
context_parts.append(f"\n=== 信號信心度 ===")
for sig, conf in sorted(sc.items()):
context_parts.append(f" {sig}: {conf:.0%}")
return '\n'.join(context_parts)
SYSTEM_PROMPT_TEMPLATE = """你是「川普密碼」(Trump Code) 的 AI 助手。
你的工作:回答用戶關於 Trump 推文分析、股市預測、預測市場套利的問題。
語氣:專業但友善,像跟朋友聊股市。用中文回答。
重要規則:
1. 永遠提醒:這不是投資建議,歷史規律不保證未來
2. 有數據就用數據回答,沒有就誠實說「我不確定」
3. 如果用戶提出有趣的交易邏輯或觀察,在回答最後加上 [💡用戶洞見] 標記,簡述他們的邏輯
4. 不要編造數據
以下是系統最新的分析數據:
{context}
如果用戶問你不知道的事,引導他們到 GitHub: https://github.com/sstklen/trump-code"""
def call_gemini(user_message: str, history: list[dict] | None = None) -> str:
"""呼叫 Gemini Flash,自動輪用三把 key。"""
system_context = _load_system_context()
system_prompt = SYSTEM_PROMPT_TEMPLATE.format(context=system_context)
# 組合對話歷史
contents = []
if history:
for msg in history[-6:]: # 只保留最近 6 輪
contents.append({
"role": "user" if msg['role'] == 'user' else "model",
"parts": [{"text": msg['text']}],
})
contents.append({"role": "user", "parts": [{"text": user_message}]})
payload = {
"system_instruction": {"parts": [{"text": system_prompt}]},
"contents": contents,
"generationConfig": {
"temperature": 0.7,
"maxOutputTokens": 1000,
},
}
# 嘗試三把 key
last_error = None
for attempt in range(len(GEMINI_KEYS)):
key = _next_key()
url = f"https://generativelanguage.googleapis.com/v1beta/models/{GEMINI_MODEL}:generateContent?key={key}"
try:
data = json.dumps(payload).encode('utf-8')
req = urllib.request.Request(url, data=data, headers={
"Content-Type": "application/json",
}, method="POST")
with urllib.request.urlopen(req, timeout=30) as resp:
result = json.loads(resp.read().decode('utf-8'))
text = result['candidates'][0]['content']['parts'][0]['text']
# 檢查是否有用戶洞見標記
if '[💡用戶洞見]' in text or '[用戶洞見]' in text:
_save_crowd_insight(user_message, text)
return text
except urllib.error.HTTPError as e:
last_error = f"HTTP {e.code}"
if e.code == 429:
continue # key 額度用完,換下一把
break
except Exception as e:
last_error = str(e)
break
return f"抱歉,AI 暫時無法回應({last_error})。請稍後再試。"
def _save_crowd_insight(user_message: str, ai_response: str, anon_id: str = "") -> None:
"""
儲存用戶的交易邏輯洞見,供 Opus 下次分析時參考。
品質門檻:
- 用戶原文至少 20 字(太短的不是認真的邏輯)
- AI 提取的洞見至少 10 字
- 不含垃圾關鍵字
"""
# 門檻 1:長度
if len(user_message) < INSIGHT_MIN_LENGTH:
return # 太短,不收
# 門檻 2:垃圾過濾
if any(p in user_message.lower() for p in BANNED_PATTERNS):
return
# 提取洞見部分
insight_text = ""
if '[💡用戶洞見]' in ai_response:
insight_text = ai_response.split('[💡用戶洞見]')[-1].strip()
elif '[用戶洞見]' in ai_response:
insight_text = ai_response.split('[用戶洞見]')[-1].strip()
if len(insight_text) < 10:
return # AI 沒有提取出有意義的洞見
# 通過門檻 → 存檔
insights: list[dict] = []
if CROWD_INSIGHTS_FILE.exists():
with open(CROWD_INSIGHTS_FILE, encoding='utf-8') as f:
insights = json.load(f)
insights.append({
'timestamp': datetime.now(timezone.utc).isoformat(),
'anon_id': anon_id, # 匿名 hash,不存 IP
'user_logic': user_message[:500],
'ai_extracted': insight_text[:300],
'status': 'NEW', # Opus 處理後改成 REVIEWED / ADOPTED / REJECTED
'votes': 0, # 未來可讓其他用戶投票
})
# 最多保留 500 條
insights = insights[-500:]
with open(CROWD_INSIGHTS_FILE, 'w', encoding='utf-8') as f:
json.dump(insights, f, ensure_ascii=False, indent=2)
def _now_iso() -> str:
return datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')
def _iso_to_ts(value: Any) -> float | None:
if not isinstance(value, str) or not value:
return None
try:
return datetime.fromisoformat(value.replace('Z', '+00:00')).timestamp()
except Exception:
return None
def _ts_to_iso(ts: float) -> str:
try:
return datetime.fromtimestamp(ts, timezone.utc).isoformat().replace('+00:00', 'Z')
except Exception:
return _now_iso()
def _is_game_expired(game: dict | None, now_ts: float | None = None) -> bool:
if not isinstance(game, dict):
return False
expires_ts = _iso_to_ts(game.get('expires_at'))
if expires_ts is None:
return False
return (now_ts or time.time()) > expires_ts
def _safe_int(value: Any, default: int = 0) -> int:
try:
return int(value)
except (TypeError, ValueError):
return default
def _direction_from_change(change: Any) -> str | None:
try:
value = float(change)
except (TypeError, ValueError):
return None
if value > 0.1:
return 'UP'
if value < -0.1:
return 'DOWN'
return 'FLAT'
def _load_json_file(path: Path, default: dict | list | None) -> dict | list | None:
if not path.exists():
return default
try:
with open(path, encoding='utf-8') as f:
return json.load(f)
except Exception:
return default
def _save_json_file(path: Path, data: dict | list) -> bool:
try:
with open(path, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
return True
except Exception:
return False
def _load_game_current():
data = _load_json_file(GAME_CURRENT_FILE, None)
return data if isinstance(data, dict) else None
def _save_game_current(game):
if isinstance(game, dict):
_save_json_file(GAME_CURRENT_FILE, game)
def _load_game_players():
if not GAME_PLAYERS_FILE.exists():
_save_game_players({})
data = _load_json_file(GAME_PLAYERS_FILE, {})
return data if isinstance(data, dict) else {}
def _save_game_players(players):
if isinstance(players, dict):
_save_json_file(GAME_PLAYERS_FILE, players)
def _load_game_history():
if not GAME_HISTORY_FILE.exists():
_save_game_history([])
data = _load_json_file(GAME_HISTORY_FILE, [])
return data if isinstance(data, list) else []
def _save_game_history(history):
if isinstance(history, list):
_save_json_file(GAME_HISTORY_FILE, history)
def _find_latest_signal():
predictions = _load('rt_predictions.json') or []
if not isinstance(predictions, list):
return None
latest = None
latest_key = ''
for pred in predictions:
if not isinstance(pred, dict) or pred.get('status') != 'LIVE':
continue
sort_key = f"{pred.get('created_at', '')}|{pred.get('id', '')}"
if latest is None or sort_key > latest_key:
latest = pred
latest_key = sort_key
return latest
def _build_game_round(signal: dict) -> dict | None:
signal_id = signal.get('id')
if not signal_id:
return None
# 用現在時間開始計時(不管信號多舊,新局一律從現在算 6 小時)
now_ts = time.time()
created_at = _now_iso()
expires_at = _ts_to_iso(now_ts + GAME_ROUND_HOURS * 3600)
return {
'signal_id': signal_id,
'post_preview': signal.get('post_preview', ''),
'signal_types': signal.get('signal_types', []) if isinstance(signal.get('signal_types'), list) else [],
'ai_direction': signal.get('predicted_direction'),
'ai_confidence': signal.get('confidence'),
'spy_at_signal': signal.get('spy_at_signal'),
'created_at': created_at,
'expires_at': expires_at,
'votes': {},
'resolved': False,
'result': None,
}
def _pick_verify_value(signal: dict) -> tuple[float | None, str | None]:
for key in ('verify_6h', 'verify_3h', 'verify_1h'):
value = signal.get(key)
if value is None:
continue
try:
return float(value), key
except (TypeError, ValueError):
continue
return None, None
def _crowd_direction(votes: dict[str, str]) -> str | None:
counts = {'UP': 0, 'DOWN': 0, 'FLAT': 0}
for direction in votes.values():
if direction in counts:
counts[direction] += 1
max_votes = max(counts.values()) if counts else 0
if max_votes == 0:
return None
leaders = [direction for direction, count in counts.items() if count == max_votes]
if len(leaders) != 1:
return None
return leaders[0]
def _maybe_start_new_round():
current = _load_game_current()
now_ts = time.time()
# 有進行中的局且未過期 → 繼續玩
if current and not current.get('resolved') and not _is_game_expired(current, now_ts):
return current
# 過期且未 resolve → 嘗試開獎
if current and not current.get('resolved') and _is_game_expired(current, now_ts):
current = _resolve_if_needed(current)
# resolve 成功或失敗都繼續往下找新局
# 已 resolve 或無局 → 找信號開新局
latest_signal = _find_latest_signal()
if latest_signal:
new_game = _build_game_round(latest_signal)
if new_game:
_save_game_current(new_game)
return new_game
# 真的沒有任何信號 → 回傳現有局
return current
def _resolve_if_needed(game):
if not isinstance(game, dict):
return None
if game.get('resolved') or not _is_game_expired(game):
return game
predictions = _load('rt_predictions.json') or []
if not isinstance(predictions, list):
return game
signal_id = game.get('signal_id')
signal = next(
(item for item in predictions if isinstance(item, dict) and item.get('id') == signal_id),
None,
)
if not signal:
return game
verify_value, verify_source = _pick_verify_value(signal)
actual_direction = _direction_from_change(verify_value)
if actual_direction is None:
# 過期超過 2 小時仍無 verify 數據 → 強制 VOID,不卡死
expires_ts = _iso_to_ts(game.get('expires_at')) or 0
if time.time() - expires_ts > 7200:
game['resolved'] = True
game['result'] = {'actual_direction': 'VOID', 'spy_change': None, 'verify_source': None,
'ai_correct': None, 'crowd_correct': None, 'crowd_direction': None,
'winning_votes': 0, 'total_votes': len(game.get('votes', {})),
'void_reason': 'no verify data after 2h timeout'}
game['resolved_at'] = _now_iso()
_save_game_current(game)
return game
votes = game.get('votes')
if not isinstance(votes, dict):
votes = {}
valid_votes = {
anon_id: direction
for anon_id, direction in votes.items()
if direction in {'UP', 'DOWN', 'FLAT'}
}
players = _load_game_players()
winners = []
ai_direction = game.get('ai_direction')
for anon_id, direction in valid_votes.items():
profile = players.get(anon_id)
if not isinstance(profile, dict):
profile = {}
correct = direction == actual_direction
delta = 10 if correct else -5
if correct and ai_direction and ai_direction != actual_direction:
delta += 25
score = _safe_int(profile.get('score'))
wins = _safe_int(profile.get('wins'))
streak = _safe_int(profile.get('streak'))
profile['nickname'] = (profile.get('nickname') or f'anon-{anon_id[:4]}')[:40]
profile['score'] = score + delta
profile['wins'] = wins + (1 if correct else 0)
profile['streak'] = streak + 1 if correct else 0
players[anon_id] = profile
if correct:
winners.append(anon_id)
crowd_direction = _crowd_direction(valid_votes)
result = {
'actual_direction': actual_direction,
'spy_change': verify_value,
'verify_source': verify_source,
'ai_correct': ai_direction == actual_direction if ai_direction else None,
'crowd_correct': crowd_direction == actual_direction if crowd_direction else None,
'crowd_direction': crowd_direction,
'winning_votes': len(winners),
'total_votes': len(valid_votes),
}
game['votes'] = valid_votes
game['resolved'] = True
game['result'] = result
game['resolved_at'] = _now_iso()
_save_game_current(game)
_save_game_players(players)
history = _load_game_history()
if not any(isinstance(item, dict) and item.get('signal_id') == signal_id for item in history):
history.append({
'signal_id': signal_id,
'created_at': game.get('created_at'),
'resolved_at': game.get('resolved_at'),
'post_preview': game.get('post_preview', ''),
'actual_direction': actual_direction,
'spy_change': verify_value,
'verify_source': verify_source,
'ai_direction': ai_direction,
'ai_correct': result['ai_correct'],
'crowd_direction': crowd_direction,
'crowd_correct': result['crowd_correct'],
'total_votes': len(valid_votes),
'winning_votes': len(winners),
})
_save_game_history(history)
return game
# =====================================================================
# 網頁介面(內嵌 HTML)
# =====================================================================
HTML_PAGE = """<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>川普密碼 Trump Code</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: #0a0a0f;
color: #e0e0e0;
height: 100vh;
display: flex;
flex-direction: column;
}
header {
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
padding: 16px 24px;
border-bottom: 1px solid #333;
display: flex;
align-items: center;
gap: 12px;
}
header h1 {
font-size: 20px;
color: #ffd700;
}
header .badge {
background: #2d5a27;
color: #7dff6e;
padding: 2px 10px;
border-radius: 12px;
font-size: 11px;
}
.chat-area {
flex: 1;
overflow-y: auto;
padding: 20px;
display: flex;
flex-direction: column;
gap: 16px;
}
.msg {
max-width: 80%;
padding: 12px 16px;
border-radius: 16px;
line-height: 1.6;
font-size: 14px;
white-space: pre-wrap;
}
.msg.user {
align-self: flex-end;
background: #1e3a5f;
color: #fff;
border-bottom-right-radius: 4px;
}
.msg.ai {
align-self: flex-start;
background: #1a1a2e;
border: 1px solid #333;
border-bottom-left-radius: 4px;
}
.msg.ai .insight {
background: #2d5a27;
color: #7dff6e;
padding: 8px 12px;
border-radius: 8px;
margin-top: 8px;
font-size: 12px;
}
.msg.system {
align-self: center;
color: #888;
font-size: 12px;
padding: 4px;
}
.input-area {
padding: 16px 20px;
background: #111;
border-top: 1px solid #333;
display: flex;
gap: 10px;
}
.input-area input {
flex: 1;
padding: 12px 16px;
border: 1px solid #444;
border-radius: 24px;
background: #1a1a2e;
color: #fff;
font-size: 14px;
outline: none;
}
.input-area input:focus { border-color: #ffd700; }
.input-area button {
padding: 12px 24px;
background: #ffd700;
color: #000;
border: none;
border-radius: 24px;
font-weight: bold;
cursor: pointer;
font-size: 14px;
}
.input-area button:hover { background: #ffed4a; }
.input-area button:disabled { opacity: 0.5; cursor: not-allowed; }
footer {
text-align: center;
padding: 8px;
font-size: 11px;
color: #555;
}
footer a { color: #888; }
</style>
</head>
<body>
<header>
<h1>🔴 川普密碼 Trump Code</h1>
<span class="badge">AI 即時分析</span>
</header>
<div class="chat-area" id="chat">
<div class="msg system">⚠️ 這不是投資建議。歷史規律不保證未來表現。</div>
<div class="msg ai">嗨!我是川普密碼的 AI 助手。我可以回答你關於:
• Trump 今天發了什麼推文?信號是什麼?
• 模型的命中率排行
• 預測市場的套利機會
• 你有什麼交易邏輯想跟我討論的?
你的想法對我們很重要——好的交易邏輯會被收錄到系統裡 💡</div>
</div>
<div class="input-area">
<input type="text" id="input" placeholder="問我任何關於川普密碼的問題..." autofocus>
<button id="send" onclick="sendMessage()">發送</button>
</div>
<footer>
<a href="https://github.com/sstklen/trump-code" target="_blank">GitHub</a> ·
Powered by Gemini Flash + Opus Analysis
</footer>
<script>
const chat = document.getElementById('chat');
const input = document.getElementById('input');
const sendBtn = document.getElementById('send');
let history = [];
input.addEventListener('keydown', e => { if (e.key === 'Enter') sendMessage(); });
async function sendMessage() {
const text = input.value.trim();
if (!text) return;
// 顯示用戶訊息
addMsg(text, 'user');
input.value = '';
sendBtn.disabled = true;
// 顯示載入
const loadingId = addMsg('思考中...', 'ai');
try {
const resp = await fetch('/api/chat', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({message: text, history: history}),
});
const data = await resp.json();
// 更新回應
document.getElementById(loadingId).innerHTML = formatResponse(data.reply);
history.push({role: 'user', text: text});
history.push({role: 'ai', text: data.reply});
// 保留最近 10 輪
if (history.length > 20) history = history.slice(-20);
} catch (e) {
document.getElementById(loadingId).textContent = '抱歉,連線失敗。請重試。';
}
sendBtn.disabled = false;
input.focus();
}
function addMsg(text, role) {
const id = 'msg-' + Date.now();
const div = document.createElement('div');
div.className = 'msg ' + role;
div.id = id;
div.textContent = text;
chat.appendChild(div);
chat.scrollTop = chat.scrollHeight;
return id;
}
function formatResponse(text) {
// 處理洞見標記
if (text.includes('[💡用戶洞見]')) {
const parts = text.split('[💡用戶洞見]');
return parts[0] + '<div class="insight">💡 你的邏輯已被記錄!' + parts[1] + '</div>';
}
return text.replace(/\\n/g, '<br>');
}
</script>
</body>
</html>"""
# =====================================================================
# HTTP Server
# =====================================================================
class ChatHandler(BaseHTTPRequestHandler):
def _get_ip(self) -> str:
return self.headers.get('X-Forwarded-For', self.client_address[0]).split(',')[0].strip()
def _json_response(self, code: int, data: dict):
self.send_response(code)
self.send_header('Content-Type', 'application/json; charset=utf-8')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(json.dumps(data, ensure_ascii=False).encode('utf-8'))
def do_GET(self):
# 追蹤每個 GET 請求(排除 favicon)
if self.path != '/favicon.ico':
_track_request(
self._get_ip(),
self.path.split('?')[0],
self.headers.get('User-Agent', '')
)
if self.path == '/' or self.path == '/index.html' or self.path == '/insights' or self.path == '/insights.html':
# 首頁 = 儀表板(恢復原狀)
insights_file = BASE / 'public' / 'insights.html'
if insights_file.exists():
self.send_response(200)
self.send_header('Content-Type', 'text/html; charset=utf-8')
self.end_headers()
self.wfile.write(insights_file.read_bytes())
else:
self.send_response(200)
self.send_header('Content-Type', 'text/html; charset=utf-8')
self.end_headers()
self.wfile.write(HTML_PAGE.encode('utf-8'))
elif self.path in ('/robots.txt', '/sitemap.xml', '/llms.txt'):
# SEO/AEO 靜態檔案
fname = self.path.lstrip('/')
fpath = BASE / 'public' / fname
if fpath.exists():
ct = 'text/plain; charset=utf-8' if fname.endswith('.txt') else 'application/xml; charset=utf-8'
self.send_response(200)
self.send_header('Content-Type', ct)
self.send_header('Cache-Control', 'public, max-age=3600')
self.end_headers()