-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1394 lines (1125 loc) · 45.3 KB
/
app.py
File metadata and controls
1394 lines (1125 loc) · 45.3 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
import os
import json
import uuid
import threading
import websocket
import socketio as socketio_client
from flask import Flask, jsonify, request
from flask_cors import CORS
from flask_socketio import SocketIO
from dotenv import load_dotenv
import time
import datetime
import re
# --------------------
# Helper function for timestamp
# --------------------
def ts():
return datetime.datetime.now().strftime("%d.%m.%Y - %H:%M")
# --------------------
# Load ENV variables
# --------------------
load_dotenv()
# Debug setting (show/hide RAW events)
DEBUG_EVENTS = os.getenv("DEBUG", "1") == "1"
# Streamer 1
LABEL_STREAMER1 = os.getenv("LABEL_STREAMER1", "Streamer1")
SE_TWITCH_TOKEN = os.getenv("SE_TWITCH_TOKEN")
SE_KICK_TOKEN = os.getenv("SE_KICK_TOKEN")
KICK_APP_KEY = os.getenv("KICK_APP_KEY")
KICK_CLUSTER = os.getenv("KICK_CLUSTER")
KICK_CHATROOM_ID = os.getenv("KICK_CHATROOM_ID")
TIPEEE_API_KEY = os.getenv("TIPEEE_API_KEY")
# Twitch IRC (Streamer 1)
TWITCH_IRC_TOKEN = os.getenv("TWITCH_IRC_TOKEN")
TWITCH_IRC_NICK = os.getenv("TWITCH_IRC_NICK")
TWITCH_IRC_CHANNEL = os.getenv("TWITCH_IRC_CHANNEL") # ohne '#'
# Streamer 2
LABEL_STREAMER2 = os.getenv("LABEL_STREAMER2", "Streamer2")
SE2_TWITCH_TOKEN = os.getenv("SE2_TWITCH_TOKEN")
SE2_KICK_TOKEN = os.getenv("SE2_KICK_TOKEN")
KICK_APP_KEY2 = os.getenv("KICK_APP_KEY2")
KICK_CLUSTER2 = os.getenv("KICK_CLUSTER2")
KICK_CHATROOM_ID2 = os.getenv("KICK_CHATROOM_ID2")
TIPEEE_API_KEY2 = os.getenv("TIPEEE_API_KEY2")
# Twitch IRC (Streamer 2)
TWITCH_IRC_TOKEN2 = os.getenv("TWITCH_IRC_TOKEN2")
TWITCH_IRC_NICK2 = os.getenv("TWITCH_IRC_NICK2")
TWITCH_IRC_CHANNEL2 = os.getenv("TWITCH_IRC_CHANNEL2") # ohne '#'
# --------------------
# Load config
# --------------------
with open("config.json", "r", encoding="utf-8") as f:
CONFIG1 = json.load(f)
CONFIG2 = None
if SE2_TWITCH_TOKEN: # only load if token for Streamer 2 is present
try:
with open("config2.json", "r", encoding="utf-8") as f:
CONFIG2 = json.load(f)
except FileNotFoundError:
print(f"[{ts()}] [WARN] SE2_TWITCH_TOKEN is set, but config2.json is missing!")
# --------------------
# Flask + SocketIO setup
# --------------------
app = Flask(__name__)
CORS(app)
socketio = SocketIO(app, cors_allowed_origins="*")
# --------------------
# Timer variables
# --------------------
remaining = CONFIG1["timer"]["start_minutes"] * 60
paused = True
lock = threading.Lock()
# --------------------
# Happy Hour
# --------------------
HAPPY_MULTIPLIER = float(os.getenv("HAPPY_MULTIPLIER", "1"))
happy_active = False
happy_remaining = 0 # Countdown in Sekunden
STATE_FILE = "state.json"
LOG_FILE = "events.log"
TIME_ADD_LOG = "time_add.log"
# === DONATION GOAL ===
DONATION_GOAL_FILE = "donation_goal.json"
DONATION_GOAL_STATE = {
"current": 0.0
}
def load_donation_goal():
if os.path.exists(DONATION_GOAL_FILE):
try:
with open(DONATION_GOAL_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except:
pass
return {"current": 0.0}
def save_donation_goal():
with open(DONATION_GOAL_FILE, "w", encoding="utf-8") as f:
json.dump(DONATION_GOAL_STATE, f)
# === END DONATION GOAL ===
# === GOALS ===
GOALS_FILE = "goals.json"
GOAL_STATE_FILE = "goal_state.json"
def load_goal_state():
if not os.path.exists(GOAL_STATE_FILE):
return {"written_goals": []}
try:
with open(GOAL_STATE_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except:
return {"written_goals": []}
def save_goal_state(state):
with open(GOAL_STATE_FILE, "w", encoding="utf-8") as f:
json.dump(state, f, indent=2, ensure_ascii=False)
goal_state = load_goal_state()
def load_goals():
if not os.path.exists(GOALS_FILE):
return {"total_minutes_supported": 0.0, "goals": []}
try:
with open(GOALS_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
# ensure keys
if "total_minutes_supported" not in data:
data["total_minutes_supported"] = 0.0
else:
# migrate int -> float
try:
data["total_minutes_supported"] = float(data["total_minutes_supported"])
except:
data["total_minutes_supported"] = 0.0
if "goals" not in data or not isinstance(data["goals"], list):
data["goals"] = []
for g in data["goals"]:
g.setdefault("hours", 0)
g.setdefault("title", "")
g.setdefault("reached", False)
return data
except Exception as e:
print(f"[{ts()}] [GOALS] Error while loading {GOALS_FILE}:", e)
return {"total_minutes_supported": 0.0, "goals": []}
def save_goals():
try:
with open(GOALS_FILE, "w", encoding="utf-8") as f:
json.dump(goals_data, f, indent=2, ensure_ascii=False)
except Exception as e:
print(f"[{ts()}] [GOALS] Error while saving {GOALS_FILE}:", e)
def log_goal_reached(goal):
try:
ts_str = ts()
line = f"[{ts_str}] [GOAL] 🎯 Ziel erreicht: {goal['hours']} Stunden – {goal['title']}\n"
with open(TIME_ADD_LOG, "a", encoding="utf-8") as f:
f.write(line)
# --- Nur neues Goal anhängen, niemals gesamte Datei überschreiben ---
title = goal["title"]
if title not in goal_state["written_goals"]:
goal_state["written_goals"].append(title)
save_goal_state(goal_state)
append_text = (" | " if os.path.exists("goal.txt") and os.path.getsize("goal.txt") > 0 else "") + title
with open("goal.txt", "a", encoding="utf-8") as f:
f.write(append_text)
except Exception as e:
print(f"[{ts()}] [GOALS] Error while logging goal:", e)
goals_data = load_goals()
# --- goal.txt Auto-Rebuild deaktiviert (manueller Modus) ---
print(f"[{ts()}] [GOALS] goal.txt rebuild skipped (manual mode)")
def check_goals_reached():
total_hours = float(goals_data.get("total_minutes_supported", 0.0)) / 60.0
updated = False
for goal in goals_data.get("goals", []):
if not goal.get("reached") and total_hours >= float(goal.get("hours", 0)):
goal["reached"] = True
updated = True
print(f"[{ts()}] [GOAL] 🎯 Ziel erreicht: {goal['hours']} Stunden – {goal['title']}")
log_goal_reached(goal)
socketio.emit("goal_reached", goal)
if updated:
save_goals()
# === END GOALS ===
def add_support_minutes(mins):
"""Add positive minutes (float) to total support, persist and re-check goals."""
try:
mins = float(mins)
except Exception:
return
if mins <= 0:
return
with lock:
goals_data["total_minutes_supported"] = float(goals_data.get("total_minutes_supported", 0.0)) + mins
# slightly round to avoid floating point artifacts
goals_data["total_minutes_supported"] = round(goals_data["total_minutes_supported"], 2)
save_goals()
# outside of the lock
check_goals_reached()
def save_state():
try:
with open(STATE_FILE, "w", encoding="utf-8") as f:
json.dump({"remaining": remaining, "paused": paused}, f)
except Exception as e:
print(f"[{ts()}] [STATE] Error while saving:", e)
def load_state():
global remaining, paused
if os.path.exists(STATE_FILE):
try:
with open(STATE_FILE, "r", encoding="utf-8") as f:
state = json.load(f)
remaining = state.get("remaining", remaining)
paused = state.get("paused", paused)
print(f"[{ts()}] [STATE] Restored: {remaining//60} minutes, paused={paused}")
except Exception as e:
print(f"[{ts()}] [STATE] Error while loading:", e)
def log_event(platform, data):
if not DEBUG_EVENTS:
return # do nothing when debug=0
try:
ts_str = ts()
with open(LOG_FILE, "a", encoding="utf-8") as f:
f.write(f"[{ts_str}] [{platform}] RAW EVENT: {json.dumps(data, ensure_ascii=False)}\n")
except Exception as e:
print(f"[{ts()}] [LOG] Error while writing to events.log:", e)
def log_time_add(platform, minutes_to_add, remaining_seconds, label=None):
"""Write time addition summary (same as console) to a separate logfile"""
try:
ts_str = ts()
if label:
line = f"[{ts_str}] [{platform}] {label} | +{minutes_to_add} minutes\n"
else:
line = f"[{ts_str}] [{platform}] +{minutes_to_add} minutes\n"
with open(TIME_ADD_LOG, "a", encoding="utf-8") as f:
f.write(line)
except Exception as e:
print(f"[{ts()}] [LOG] Error while writing to time_add.log:", e)
# Load existing state on startup
load_state()
DONATION_GOAL_STATE.update(load_donation_goal())
# --------------------
# Timer loop
# --------------------
def timer_loop():
global remaining, paused, happy_active, happy_remaining
counter = 0
while True:
with lock:
if not paused and remaining > 0:
remaining -= 1
# Happy Hour Countdown – läuft nur, wenn Timer nicht pausiert
if happy_active and not paused:
happy_remaining -= 1
if happy_remaining <= 0:
happy_active = False
happy_remaining = 0
print(f"[{ts()}] [HAPPY] Happy Hour expired")
socketio.emit("timer_update", {"remaining": remaining, "paused": paused})
# save state every 300 seconds (= 5 minutes)
counter += 1
if counter >= 30:
save_state()
counter = 0
socketio.sleep(1)
# --------------------
# Handle events
# --------------------
community_gift_groups = set() # Gift-Bundle activityGroups
pending_gifted_subs = {} # ag -> {"platform":..., "tier":..., "ts":..., "config":...}
def minutes_for_tier(cfg, tier_raw):
if tier_raw in ["1000", "prime"]:
return cfg["twitch"]["sub_t1"]
if tier_raw == "2000":
return cfg["twitch"]["sub_t2"]
if tier_raw == "3000":
return cfg["twitch"]["sub_t3"]
return cfg["twitch"]["sub_t1"]
def fmt_minutes(val: float):
val = float(val)
return int(val) if val.is_integer() else round(val, 1)
def check_pending_gift(activity_group):
"""
Wird verzögert (10s) aufgerufen.
Wenn bis dahin KEIN communityGiftPurchase mit derselben activityGroup registriert wurde,
behandeln wir den gespeicherten gifted subscriber als Einzelgift.
"""
info = pending_gifted_subs.pop(activity_group, None)
if not info:
return # nothing pending (or already recognized as a bundle)
# If the group has already been marked as a bundle -> ignore
if activity_group in community_gift_groups:
return
platform = info["platform"]
tier_raw = info["tier"]
cfg = info["config"]
add_min = minutes_for_tier(cfg, tier_raw) * get_current_multiplier()
with lock:
global remaining
remaining += add_min * 60
save_state()
new_state = {"remaining": remaining, "paused": paused}
add_support_minutes(add_min)
label = "Gifted Sub"
m = fmt_minutes(add_min)
prefix = ""
if get_current_multiplier() != 1.0:
prefix = f"[HAPPY HOUR x{HAPPY_MULTIPLIER}] "
msg = f"[{ts()}] {prefix}[{platform}] {label} | +{m} minutes"
print(msg)
log_time_add(platform, m, remaining, prefix + label)
socketio.start_background_task(socketio.emit, "timer_update", new_state)
def apply_minutes(platform, minutes_to_add, label, username="", count=1):
"""Helper to apply minutes, log, emit including username."""
if minutes_to_add <= 0:
return
# Happy Hour
multiplier = get_current_multiplier()
if multiplier != 1.0:
minutes_to_add = minutes_to_add * multiplier
with lock:
global remaining
remaining += int(round(minutes_to_add * 60))
save_state()
new_state = {"remaining": remaining, "paused": paused}
add_support_minutes(minutes_to_add)
m = fmt_minutes(minutes_to_add)
prefix = ""
if get_current_multiplier() != 1.0:
prefix = f"[HAPPY HOUR x{HAPPY_MULTIPLIER}] "
print(f"[{ts()}] {prefix}[{platform}] {label} | +{m} minutes (by {username})")
log_time_add(platform, m, remaining, prefix + label)
socketio.start_background_task(socketio.emit, "timer_update", new_state)
socketio.emit("time_added", {
"platform": platform,
"label": prefix + label,
"minutes": m,
"username": username,
"count": count
})
def get_current_multiplier():
global happy_active, happy_remaining
if happy_active and happy_remaining > 0:
return HAPPY_MULTIPLIER
return 1.0
# --------------------
# Donation Goal Logic
# --------------------
def add_donation_amount(amount):
goal = CONFIG1.get("donation_goal")
if not goal or not goal.get("enabled"):
return True # kein Goal → normaler Ablauf
target = float(goal.get("amount_eur", 0))
DONATION_GOAL_STATE["current"] += float(amount)
DONATION_GOAL_STATE["current"] = round(
min(DONATION_GOAL_STATE["current"], target),
2
)
save_donation_goal()
socketio.emit("donation_goal_update", {
"current": DONATION_GOAL_STATE["current"],
"target": target
})
return DONATION_GOAL_STATE["current"] >= target
def handle_event(platform, data, config):
global remaining, community_gift_groups, pending_gifted_subs
# ------------------------
# 🎯 USERNAME-EXTRAKTION
# ------------------------
username = None
# StreamElements activities
if "data" in data:
d = data["data"]
if isinstance(d, dict):
username = d.get("username") or d.get("sender") or d.get("user")
# SoundAlerts Chat (IRC)
if username is None and data.get("type") == "message":
# Beispiel: "Losty löst SoundXY mit 50 Bits aus"
m = re.search(r"^(.+?)\s+löst\s+", data.get("data", {}).get("text", ""))
if m:
username = m.group(1)
# Kick Gifts → Username NICHT überschreiben
if data.get("type") == "kick_gift" and "username" in data:
username = data["username"]
else:
# Kick Chat Nickname
if username is None and "nickname" in data:
username = data["nickname"]
# Fallback
if username is None:
username = ""
minutes_to_add = 0.0
# RAW event to logfile + optional console
if DEBUG_EVENTS:
try:
print(f"[{ts()}] [{platform}] RAW EVENT: {json.dumps(data, indent=2, ensure_ascii=False)}")
except Exception:
print(f"[{ts()}] [{platform}] RAW EVENT (non-json-printable)")
etype = data.get("type")
text = data.get("data", {}).get("text", "")
# --- WICHTIG ---
# Nur IRC-Chat filtern – NICHT StreamElements, NICHT Kick!
# Sonst blockiert man ALLE Subs/Bits/Donations etc.
if platform.endswith("-IRC"):
# Bei IRC müssen wir ALLES blocken,
# außer dem SoundAlerts-Bits-Pattern.
if etype == "message" and re.search(
r"(.+?) löst (.+?) mit (\d+)\s*Bits aus",
text, flags=re.IGNORECASE
) is None:
return
# From here on, only log and process relevant events
log_event(platform, data)
# Twitch/Kick subs via StreamElements
if etype == "subscriber":
d = data.get("data", {})
provider = str(data.get("provider", "")).lower()
tier_raw = str(d.get("tier", "1000")).lower()
gifted = d.get("gifted", False)
ag = data.get("activityGroup")
# 🔹 Wenn dieser Sub zu einem bekannten Gift-Bundle gehört → ignorieren
if ag and ag in community_gift_groups:
if DEBUG_EVENTS:
print(f"[{ts()}] [{platform}] Subscriber in gift bundle (activityGroup={ag}) ignored")
return
# --- Kick subs ---
if "kick" in provider or "kick" in platform.lower():
if "kick" in config:
minutes_to_add = float(config["kick"]["sub"])
# --- Twitch subs ---
else:
if gifted:
if ag:
pending_gifted_subs[ag] = {
"platform": platform,
"tier": tier_raw,
"ts": time.time(),
"config": config
}
threading.Timer(10.0, check_pending_gift, args=(ag,)).start()
return
else:
minutes_to_add = float(minutes_for_tier(config, tier_raw))
else:
minutes_to_add = float(minutes_for_tier(config, tier_raw))
# Gifted subs (Bundle)
# Gifted subs (Bundle)
elif etype == "communityGiftPurchase":
d = data.get("data", {})
gift_amount = int(d.get("amount", 1))
provider = str(data.get("provider", "")).lower()
ag = data.get("activityGroup")
# Bundle markieren (egal ob Twitch oder Kick)
if ag:
community_gift_groups.add(ag)
pending_gifted_subs.pop(ag, None)
# Kick-Bundle: Konstante Minuten pro Sub aus config["kick"]["sub"]
if "kick" in provider or "kick" in platform.lower():
per_sub = float(config["kick"]["sub"])
minutes_to_add = gift_amount * per_sub
# Twitch-Bundle: Minuten je nach Tier
else:
tier_raw = str(d.get("tier", "1000")).lower()
minutes_to_add = gift_amount * minutes_for_tier(config, tier_raw)
# Bits (normale Twitch-Cheers aus SE-Activities)
elif etype == "cheer":
bits = int(data.get("data", {}).get("amount", 0))
minutes_to_add = round((bits / 100.0) * float(config["twitch"]["bits_per_100"]), 2)
# Donations via Tipeee
elif etype == "donation" and "tipeee" in config:
amount = float(data.get("amount", 0))
if not add_donation_amount(amount):
msg = f"Donation Goal +{amount:.2f} €"
print(f"[{ts()}] [DONATION-GOAL] {msg}")
log_time_add(platform, 0, remaining, msg)
return
minutes_to_add = amount * float(config["tipeee"]["minutes_per_eur"])
# Donations via StreamElements
elif etype == "tip" and "streamelements" in config:
amount = float(data.get("data", {}).get("amount", 0))
if not add_donation_amount(amount):
msg = f"Donation Goal +{amount:.2f} €"
print(f"[{ts()}] [DONATION-GOAL] {msg}")
log_time_add(platform, 0, remaining, msg)
return
minutes_to_add = amount * float(config["streamelements"]["minutes_per_eur"])
# Kick gifts via Chat
elif etype == "kick_gift":
if "kick" in config:
amount = int(data.get("amount", 0))
minutes_to_add = float((amount // 100) * int(config["kick"]["kicks_per_100"]))
# --- Apply time addition ---
if minutes_to_add > 0:
# passendes Label bestimmen
label = ""
if etype == "subscriber":
if 'gifted' in locals() and gifted:
label = "Gifted Sub"
else:
if tier_raw == "prime":
label = "Prime Sub"
elif tier_raw == "1000":
label = "T1 Sub"
elif tier_raw == "2000":
label = "T2 Sub"
elif tier_raw == "3000":
label = "T3 Sub"
else:
label = "Sub"
elif etype == "communityGiftPurchase":
label = f"Gift Bundle"
elif etype == "cheer":
bits = int(data.get("data", {}).get("amount", 0))
label = f"Bits ({bits})"
elif etype == "donation":
label = f"Donation ({amount:.2f} €)"
elif etype == "tip":
label = f"Tip ({amount:.2f} €)"
elif etype == "kick_gift":
kicks = int(data.get("amount", 0))
label = f"Kicks ({kicks})"
else:
label = etype.capitalize()
# --- Anzahl Subs bestimmen ---
sub_count = 1 # Standardwert
if etype == "communityGiftPurchase":
sub_count = int(data.get("data", {}).get("amount", 1))
elif etype == "subscriber" and data.get("data", {}).get("gifted", False):
sub_count = 1 # Einzelgift
# --- Zeit anwenden ---
apply_minutes(platform, float(minutes_to_add), label, username=username, count=sub_count)
# SoundAlerts Bits aus IRC
if etype == "message":
text = data.get("data", {}).get("text", "")
match = re.search(r"(.+?) löst (.+?) mit (\d+)\s*Bits aus", text, flags=re.IGNORECASE)
if match:
user = match.group(1)
alert_name = match.group(2)
bits = int(match.group(3))
# Minuten berechnen
minutes_to_add = round((bits / 100.0) * float(config["twitch"]["bits_per_100"]), 2)
# Plattform-Kennung anpassen
nice_platform = platform.replace("-IRC", "-SoundAlerts")
# Timer erhöhen
apply_minutes(
nice_platform,
minutes_to_add,
f"SoundAlerts {bits} Bits",
username=user
)
return # handled
# --------------------
# StreamElements WS with auto-reconnect (activities only)
# --------------------
def start_client(name, token, config):
url = "wss://astro.streamelements.com"
def run_ws():
def on_open(ws):
print(f"[{ts()}] [{name}] Connected")
def on_message(ws, message):
try:
msg = json.loads(message)
except Exception:
if DEBUG_EVENTS:
print(f"[{ts()}] [{name}] Non-JSON message: {message}")
return
if msg.get("type") == "welcome":
subscribe(ws, "channel.activities", token, name)
elif msg.get("type") == "message":
data = msg.get("data")
handle_event(name, data, config)
def on_error(ws, error):
print(f"[{ts()}] [{name}] Error: {error}")
def on_close(ws, close_status_code, close_msg):
print(f"[{ts()}] [{name}] Connection closed, reconnecting in 1s")
time.sleep(1)
run_ws()
def subscribe(ws, topic, token, name):
sub = {
"type": "subscribe",
"nonce": str(uuid.uuid4()),
"data": {"topic": topic, "token": token, "token_type": "jwt"},
}
ws.send(json.dumps(sub))
print(f"[{ts()}] [{name}] Subscribed to {topic}")
ws = websocket.WebSocketApp(
url,
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close,
)
ws.run_forever()
threading.Thread(target=run_ws, daemon=True).start()
# --------------------
# Twitch IRC Chat (for SoundAlerts parsing)
# --------------------
def start_twitch_chat(name, oauth_token, nick, channel, config):
"""
Connects to Twitch IRC via WebSocket and forwards chat lines to handle_event
so SoundAlerts messages can be parsed and counted.
"""
if not oauth_token or not nick or not channel:
print(f"[{ts()}] [INFO] Twitch IRC for {name} skipped (missing ENV)")
return
url = "wss://irc-ws.chat.twitch.tv:443"
chan = f"#{channel}"
def run_irc():
def on_open(ws):
print(f"[{ts()}] [{name}] IRC connected -> JOIN {chan}")
# Twitch IRC capabilities (we don't strictly need tags here)
ws.send("CAP REQ :twitch.tv/tags twitch.tv/commands\r\n")
ws.send(f"PASS {oauth_token}\r\n")
ws.send(f"NICK {nick}\r\n")
ws.send(f"JOIN {chan}\r\n")
def on_message(ws, message):
# Twitch IRC can bunch multiple messages separated by \r\n
for raw in message.split("\r\n"):
if not raw:
continue
if DEBUG_EVENTS:
print(f"[{ts()}] [{name}] IRC RAW: {raw}")
# PING -> PONG
if raw.startswith("PING"):
ws.send("PONG :tmi.twitch.tv\r\n")
continue
# Parse PRIVMSG to extract text
# Example:
# @tags :username!username@username.tmi.twitch.tv PRIVMSG #channel :message text here
try:
if " PRIVMSG " in raw:
parts = raw.split(" PRIVMSG ", 1)
trailing = parts[1].split(" :", 1)
if len(trailing) == 2:
# --- Sender aus IRC extrahieren ---
try:
prefix = raw.split("!", 1)[0]
sender = prefix.split(":")[-1]
except:
sender = ""
# --- Nur SoundAlerts darf triggern ---
if sender.lower() != "soundalerts":
return
# --- Text extrahieren und Event weitergeben ---
text = trailing[1]
fake = {"type": "message", "data": {"text": text}}
handle_event(name, fake, config)
except Exception as e:
print(f"[{ts()}] [{name}] IRC parse error:", e)
def on_error(ws, error):
print(f"[{ts()}] [{name}] IRC error:", error)
def on_close(ws, close_status_code, close_msg):
print(f"[{ts()}] [{name}] IRC closed, reconnect in 3s")
time.sleep(3)
run_irc()
ws = websocket.WebSocketApp(
url,
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close
)
ws.run_forever()
threading.Thread(target=run_irc, daemon=True).start()
# --------------------
# Kick Chat Listener (for Kick Gifts via Chat)
# --------------------
def connect_kick_chat(name, app_key, cluster, chatroom_id, config):
if not app_key or not cluster or not chatroom_id:
print(f"[{ts()}] [INFO] KickChat for {name} skipped (missing ENV)")
return
url = f"wss://ws-{cluster}.pusher.com/app/{app_key}?protocol=7"
def on_open(ws):
print(f"[{ts()}] [{name}] KickChat connected")
ws.send(json.dumps({
"event": "pusher:subscribe",
"data": {"channel": f"chatrooms.{chatroom_id}.v2"}
}))
def on_message(ws, message):
try:
payload = json.loads(message)
if payload.get("event") == "App\\Events\\ChatMessageEvent":
inner = json.loads(payload["data"])
text = inner.get("content", "")
if DEBUG_EVENTS:
print(f"[{ts()}] [{name}] RAW CHAT EVENT: {json.dumps(inner, indent=2, ensure_ascii=False)}")
log_event(name, inner)
m = re.search(r"gifted\s+(\d+)\s+KICK", text, re.IGNORECASE)
if m:
amount = int(m.group(1))
# echten Gifter aus dem Chat-Text extrahieren
m_user = re.match(r"@(.+?)\s+just gifted", text, re.IGNORECASE)
if m_user:
username = m_user.group(1)
else:
username = "Someone"
fake_event = {"type": "kick_gift", "amount": amount, "username": username}
handle_event(name, fake_event, config)
except Exception as e:
print(f"[{ts()}] [{name}] KickChat parse error:", e)
def on_close(ws, *a):
print(f"[{ts()}] [{name}] KickChat closed, reconnect in 5s")
time.sleep(2)
connect_kick_chat(name, app_key, cluster, chatroom_id, config)
def on_error(ws, error):
print(f"[{ts()}] [{name}] KickChat error:", error)
ws = websocket.WebSocketApp(
url,
on_open=on_open,
on_message=on_message,
on_close=on_close,
on_error=on_error
)
threading.Thread(target=ws.run_forever, daemon=True).start()
# --------------------
# TipeeeStream (donations only)
# --------------------
def start_tipeee(name, api_key, config):
if not api_key:
print(f"[{ts()}] [INFO] {name} skipped (no TIPEEE_API_KEY)")
return
sio = socketio_client.Client(reconnection=True)
@sio.event
def connect():
print(f"[{ts()}] [{name}] Connected to Tipeee -> listening for donations")
@sio.event
def disconnect():
print(f"[{ts()}] [{name}] Disconnected from Tipeee")
@sio.on("new-event")
def on_new_event(data):
try:
ev = data.get("event", {})
if ev.get("type") == "donation":
params = ev.get("parameters", {}) if isinstance(ev.get("parameters", {}), dict) else {}
amount = float(params.get("amount", 0))
user = params.get("username", "Unknown")
if DEBUG_EVENTS:
print(f"[{ts()}] [{name}] RAW TIPEEE EVENT: {json.dumps(ev, indent=2, ensure_ascii=False)}")
log_event(name, ev)
fake = {"type": "donation", "amount": amount, "user": user}
handle_event(name, fake, config)
except Exception as e:
print(f"[{ts()}] [{name}] Tipeee parse error:", e)
def run():
url = f"https://sso.tipeeestream.com:443?access_token={api_key}"
try:
sio.connect(url, transports=["websocket", "polling"])
sio.wait()
except Exception as e:
print(f"[{ts()}] [{name}] Tipeee connection error:", e)
time.sleep(1)
run()
threading.Thread(target=run, daemon=True).start()
# --------------------
# Flask routes
# --------------------
@app.route("/")
def index():
return "Subathon timer is running!"
@app.route("/rewards")
def rewards():
streamer = request.args.get("streamer", "1")
if streamer == "1":
cfg = CONFIG1
elif streamer == "2" and CONFIG2:
cfg = CONFIG2
else:
return jsonify({"error": "Streamer not available"}), 400
rewards_list = [
{"name": "T 1 Sub", "minutes": cfg["twitch"]["sub_t1"]},
{"name": "T 2 Sub", "minutes": cfg["twitch"]["sub_t2"]},
{"name": "T 3 Sub", "minutes": cfg["twitch"]["sub_t3"]},
{"name": "100 Bits", "minutes": cfg["twitch"]["bits_per_100"]},
]
if "tipeee" in cfg:
rewards_list.append({"name": "1 € Donation", "minutes": cfg["tipeee"]["minutes_per_eur"]})
if "streamelements" in cfg:
rewards_list.append({"name": "1 € Donation", "minutes": cfg["streamelements"]["minutes_per_eur"]})
if "kick" in cfg:
rewards_list.append({"name": "Kick Sub", "minutes": cfg["kick"]["sub"]})
rewards_list.append({"name": "100 Kicks", "minutes": cfg["kick"]["kicks_per_100"]})
return jsonify(rewards_list)
@app.route("/state")
def get_state():
return jsonify({"remaining": remaining, "paused": paused})
@app.route("/pause")
def pause_timer():
global paused, happy_active
with lock:
paused = True
# Happy Hour ebenfalls pausieren
if happy_active:
happy_active = False # Multiplier deaktivieren
save_state()
return jsonify({"remaining": remaining, "paused": paused})
@app.route("/donation_goal")
def donation_goal():
goal = CONFIG1.get("donation_goal", {})
return jsonify({
"enabled": goal.get("enabled", False),
"current": DONATION_GOAL_STATE["current"],
"target": goal.get("amount_eur", 0)
})
@app.route("/resume")
def resume_timer():
global paused, happy_active, happy_remaining
with lock:
paused = False
# Happy Hour wieder aktivieren, falls noch Restzeit vorhanden ist
if happy_remaining > 0:
happy_active = True
save_state()
return jsonify({"remaining": remaining, "paused": paused})
@app.route("/toggle")
def toggle_timer():
global paused
with lock:
paused = not paused
save_state()
return jsonify({"remaining": remaining, "paused": paused})
@app.route("/time")
def change_time():