Repository navigation
Expand file tree
/
Copy pathmudae_bot.py
More file actions
5819 lines (5343 loc) · 299 KB
/
Copy pathmudae_bot.py
File metadata and controls
5819 lines (5343 loc) · 299 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 sys
import asyncio
import discord
from discord.ext import commands
import re
import json
import threading
import datetime
from datetime import timezone
import logging
import time
import random
import os
import requests
import subprocess
import traceback
import hashlib
import tempfile
import shutil
from typing import Tuple
def _bootstrap_modular_core():
"""Bridge legacy two-file updaters to the first modular release."""
base_path = os.path.dirname(os.path.abspath(__file__))
manifest_response = requests.get(
"https://raw.githubusercontent.com/misutesu-desu/MudaRemote/refs/heads/main/version.json",
timeout=15,
)
manifest_response.raise_for_status()
entries = list(manifest_response.json().get("source_files", []))
required = {
"mudae_bot.py", "mudae_preset_editor.py", "mudae_core/__init__.py",
"mudae_core/claiming.py", "mudae_core/config.py", "mudae_core/coordinator.py",
"mudae_core/kakera.py", "mudae_core/runtime.py", "mudae_core/secrets.py",
"mudae_core/status.py", "mudae_core/spheres.py", "mudae_core/filters.py",
"mudae_core/webhooks.py", "mudae_core/updater.py", "mudae_core/versioning.py",
}
if not required.issubset({entry.get("path") for entry in entries}):
raise RuntimeError("The modular core manifest is incomplete.")
stage_dir = tempfile.mkdtemp(prefix="mudae-bootstrap-", dir=base_path)
try:
for entry in entries:
relative_path = os.path.normpath(str(entry["path"]).replace("/", os.sep))
if os.path.isabs(relative_path) or os.pardir in relative_path.split(os.sep):
raise RuntimeError("Unsafe source path in update manifest.")
content_response = requests.get(entry["url"], timeout=30)
content_response.raise_for_status()
content = content_response.content
if hashlib.sha256(content).hexdigest().lower() != str(entry.get("sha256", "")).lower():
raise RuntimeError("Core checksum verification failed for {}.".format(relative_path))
staged_path = os.path.join(stage_dir, relative_path)
os.makedirs(os.path.dirname(staged_path), exist_ok=True)
with open(staged_path, "wb") as handle:
handle.write(content)
backup_dir = tempfile.mkdtemp(prefix="mudae-bootstrap-backup-", dir=base_path)
replaced = []
try:
for entry in entries:
relative_path = os.path.normpath(str(entry["path"]).replace("/", os.sep))
destination = os.path.join(base_path, relative_path)
backup = os.path.join(backup_dir, relative_path)
os.makedirs(os.path.dirname(destination), exist_ok=True)
if os.path.exists(destination):
os.makedirs(os.path.dirname(backup), exist_ok=True)
shutil.copy2(destination, backup)
os.replace(os.path.join(stage_dir, relative_path), destination)
replaced.append(relative_path)
except Exception:
for relative_path in reversed(replaced):
destination = os.path.join(base_path, relative_path)
backup = os.path.join(backup_dir, relative_path)
if os.path.exists(backup):
os.replace(backup, destination)
elif os.path.exists(destination):
os.remove(destination)
raise
finally:
shutil.rmtree(backup_dir, ignore_errors=True)
finally:
shutil.rmtree(stage_dir, ignore_errors=True)
try:
from mudae_core import (
ClaimCoordinator, ClaimOutcome, CommandPacer, GlobalIntervalCoordinator, SecretStore, ServerResetCoordinator, UpdateError, apply_update,
active_stagger_seconds, can_resume_claim_interrupted_rolls, calculate_kakera_power_cost, classify_claim_owner, classify_claim_text, clear_status_dirty,
consume_tu_urgent_bypass,
cooldown_deadline, defer_tu_queries, format_update_changelog, harvest_reveal_is_free, has_free_claim_button, initialize_status_tracking,
is_claim_announcement_for_character,
is_newer_version, looks_like_tu_status_snapshot,
humanized_claim_refresh_deadline, mark_status_dirty, pause_interruptible_sleep, prepare_active_presets, record_tu_failure,
record_tu_success, rolls_usage_is_active, set_client_paused, status_dirty_fields, parse_claim_denied_cooldown,
status_message_addresses_identity, status_refresh_reasons, split_command_batches, tu_cache_seconds_remaining, tu_retry_wait, has_perk_eight_discount,
find_refreshed_component_button, get_kakera_emoji_targets, get_regular_kakera_filter_reason, has_op_perk_five_marker,
has_purple_kakera_button, is_character_sphere_emoji, kakera_embed_text,
KakeraPowerLedger, mudae_command_ack_matches, normalize_character_sphere_emoji, parse_kakera_result,
should_refill_kakera_power, sphere_target_matches,
choose_chest_position, choose_harvest_position, count_harvest_bonus_clicks,
normalize_sphere_emoji, parse_sphere_game_status, WebhookDispatcher,
character_series_line, name_or_series_is_configured_wish, series_line_has_emoji,
)
from mudae_core.config import atomic_write_json, load_json, validate_preset
except (ModuleNotFoundError, ImportError) as core_error:
missing_module = str(getattr(core_error, "name", ""))
if missing_module and not missing_module.startswith("mudae_core"):
raise
if not missing_module and "mudae_core" not in str(core_error):
raise
_bootstrap_modular_core()
import importlib
importlib.invalidate_caches()
for loaded_module in list(sys.modules):
if loaded_module == "mudae_core" or loaded_module.startswith("mudae_core."):
sys.modules.pop(loaded_module, None)
from mudae_core import (
ClaimCoordinator, ClaimOutcome, CommandPacer, GlobalIntervalCoordinator, SecretStore, ServerResetCoordinator, UpdateError, apply_update,
active_stagger_seconds, can_resume_claim_interrupted_rolls, calculate_kakera_power_cost, classify_claim_owner, classify_claim_text, clear_status_dirty,
consume_tu_urgent_bypass,
cooldown_deadline, defer_tu_queries, format_update_changelog, harvest_reveal_is_free, has_free_claim_button, initialize_status_tracking,
is_claim_announcement_for_character,
is_newer_version, looks_like_tu_status_snapshot,
humanized_claim_refresh_deadline, mark_status_dirty, pause_interruptible_sleep, prepare_active_presets, record_tu_failure,
record_tu_success, rolls_usage_is_active, set_client_paused, status_dirty_fields, parse_claim_denied_cooldown,
status_message_addresses_identity, status_refresh_reasons, split_command_batches, tu_cache_seconds_remaining, tu_retry_wait, has_perk_eight_discount,
find_refreshed_component_button, get_kakera_emoji_targets, get_regular_kakera_filter_reason, has_op_perk_five_marker,
has_purple_kakera_button, is_character_sphere_emoji, kakera_embed_text,
KakeraPowerLedger, mudae_command_ack_matches, normalize_character_sphere_emoji, parse_kakera_result,
should_refill_kakera_power, sphere_target_matches,
choose_chest_position, choose_harvest_position, count_harvest_bonus_clicks,
normalize_sphere_emoji, parse_sphere_game_status, WebhookDispatcher,
character_series_line, name_or_series_is_configured_wish, series_line_has_emoji,
)
from mudae_core.config import atomic_write_json, load_json, validate_preset
if os.name == 'nt':
import msvcrt
from discord.utils import time_snowflake
try:
from discord.http import Route
except ImportError:
Route = None
# Bot Identification
BOT_NAME = "MudaRemote"
CURRENT_VERSION = "4.8.10"
IS_TERMUX = "TERMUX_VERSION" in os.environ or ("PREFIX" in os.environ and "com.termux" in os.environ["PREFIX"])
# Global Pause State
_global_paused = False
_active_clients = []
_active_clients_lock = threading.Lock()
_menu_active = threading.Event()
_original_terminal_settings = None
_claim_coordinator = ClaimCoordinator()
_server_reset_coordinator = ServerResetCoordinator()
_tu_interval_coordinator = GlobalIntervalCoordinator()
TU_GLOBAL_INTERVAL_SECONDS = 20.0
def _apply_shared_reset_snapshot(client, snapshot):
"""Apply only server-wide reset boundaries, never another user's private state."""
observed_at = getattr(snapshot, "observed_at_utc", None)
claim_deadline = getattr(snapshot, "claim_reset_at_utc", None)
roll_deadline = getattr(snapshot, "roll_reset_at_utc", None)
if observed_at is None:
return
previous_observation = getattr(client, "_shared_reset_observed_at_utc", None)
if previous_observation is not None and observed_at < previous_observation:
return
client._shared_reset_observed_at_utc = observed_at
observed_fields = getattr(snapshot, "observed_fields", frozenset())
previous_roll_deadline = getattr(client, "roll_reset_at_utc", None)
if "rolls" in observed_fields and roll_deadline is not None:
client.roll_reset_at_utc = roll_deadline
roll_boundary_advanced = bool(
previous_roll_deadline is not None
and previous_roll_deadline <= observed_at
and roll_deadline > observed_at
)
if roll_boundary_advanced:
# Saved-roll limits are private account state, but their cycle is
# the shared server roll hour. A peer may advance this deadline
# before this account's own $tu arrives, so reset the local usage
# counters at the observed boundary instead of waiting for a later
# deadline comparison that will now look unchanged.
client.us_pulled_this_cycle = 0
client.us_failed_this_cycle = False
client._us_retry_after = 0.0
# A server peer can tell us that a new roll hour has started, but it
# cannot tell us this account's private roll count. If this account
# had already exhausted its rolls at the old boundary, its cached zero
# must not be carried into the newly announced hour.
if (
getattr(client, "rolling_enabled", False)
and
roll_boundary_advanced
and int(getattr(client, "rolls_left", 0) or 0) <= 0
):
mark_status_dirty(client, {"rolls"}, reason="shared-roll-boundary", urgent=True)
event = getattr(client, "_immediate_check_event", None)
if event is not None:
event.set()
if "claim" not in observed_fields or claim_deadline is None or getattr(client, "pending_claim", None) is not None:
return
current_deadline = getattr(client, "next_claim_reset_at_utc", None)
claimed_character = getattr(client, "last_successfully_claimed_character", None)
if (
current_deadline is not None
and claimed_character
and current_deadline > claim_deadline + datetime.timedelta(minutes=1)
):
# This account claimed after the shared snapshot was produced. Its
# later local deadline must not be moved backwards by stale evidence.
return
client.next_claim_reset_at_utc = claim_deadline
if not getattr(client, "claim_right_available", False):
client.claim_cooldown_until_utc = claim_deadline
old_handle = getattr(client, "_shared_claim_reset_handle", None)
if old_handle is not None and not old_handle.cancelled():
old_handle.cancel()
def unlock_at_shared_boundary():
client._shared_claim_reset_handle = None
if getattr(client, "pending_claim", None) is not None:
return
current = getattr(client, "next_claim_reset_at_utc", None)
now_utc = datetime.datetime.now(datetime.timezone.utc)
if current is None or abs((current - claim_deadline).total_seconds()) > 1.0 or now_utc < current:
return
mark_status_dirty(client, {"claim"}, reason="shared-claim-boundary", urgent=True)
# A shared reset tells us only that the server boundary has passed.
# Do not wake a sleeping status loop here: in snipe-only mode that
# would cut short the configured post-reset humanization delay and
# send $tu at the exact reset. The already scheduled local refresh
# will consume this dirty state at its intended time.
loop = getattr(client, "loop", None)
if loop is not None and loop.is_running():
delay = max(
0.0,
(claim_deadline - datetime.datetime.now(datetime.timezone.utc)).total_seconds(),
)
client._shared_claim_reset_handle = loop.call_later(delay, unlock_at_shared_boundary)
class BotLogger:
_file_lock = threading.Lock()
_max_log_bytes = 5 * 1024 * 1024
_backup_count = 3
COLORS = {
"INFO": "\033[94m", "CLAIM": "\033[92m", "KAKERA": "\033[93m",
"ERROR": "\033[91m", "CHECK": "\033[95m", "RESET": "\033[36m",
"WARN": "\033[33m", "ENDC": "\033[0m"
}
PREFIXES = {
"INFO": "ℹ️ [INFO] ", "CLAIM": "💖 [CLAIM] ", "KAKERA": "💎 [KAKERA] ",
"ERROR": "❌ [ERROR] ", "CHECK": "🔍 [CHECK] ", "RESET": "🔄 [RESET] ",
"WARN": "⚠️ [WARN] "
}
DEBUG_CATEGORY_PATTERNS = {
"claim": ("claim", "wishlist", "wish", "divorce", "$rt", "forcedivorce"),
"kakera": ("kakera", "$mk", "$dk", "power", "react"),
"roll": ("roll", "$us", "key mode", "panic"),
"status": ("$tu", "status", "reset", "cooldown", "available"),
"sphere": ("sphere", "$oh", "$oc", "harvest", "chest"),
"coordination": ("coordinator", "stagger", "preset", "account"),
}
@classmethod
def _debug_category(cls, message):
lowered = str(message or "").casefold()
for category, markers in cls.DEBUG_CATEGORY_PATTERNS.items():
if any(marker in lowered for marker in markers):
return category
return "other"
@classmethod
def log(cls, message, preset_name="MudaRemote", log_type="INFO", client=None):
original_log_type = str(log_type or "INFO").upper()
if original_log_type == "DEBUG" and not getattr(client, 'debug_mode', False):
return
if original_log_type == "DEBUG":
allowed_categories = set(getattr(client, "debug_log_categories", ()) or ())
category = cls._debug_category(message)
if allowed_categories and "all" not in allowed_categories and category not in allowed_categories:
return
log_type_upper = original_log_type
msg_clean = re.sub(r"^\[[^\]]+\]\s*", "", message)
if log_type_upper == "DEBUG":
msg_clean = f"[DEBUG] {msg_clean}"
log_type_upper = "INFO"
timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
preset_aligned = f"[{preset_name[:12]:<12}]"
prefix = cls.PREFIXES.get(log_type_upper, "ℹ️ [INFO] ")
formatted = f"[{timestamp}] {preset_aligned} {prefix} {msg_clean}"
color_code = cls.COLORS.get(log_type_upper, cls.COLORS["INFO"])
console_line = f"{color_code}{formatted}{cls.COLORS['ENDC']}"
try:
print(console_line)
except UnicodeEncodeError:
encoding = getattr(sys.stdout, "encoding", None) or "ascii"
print(console_line.encode(encoding, errors="replace").decode(encoding, errors="replace"))
try:
logs_path = os.path.join(get_base_path(), "logs.txt")
with cls._file_lock:
if os.path.exists(logs_path) and os.path.getsize(logs_path) >= cls._max_log_bytes:
for index in range(cls._backup_count, 0, -1):
source = logs_path if index == 1 else "{}.{}".format(logs_path, index - 1)
destination = "{}.{}".format(logs_path, index)
if os.path.exists(source):
os.replace(source, destination)
with open(logs_path, "a", encoding='utf-8') as f:
f.write(formatted + "\n")
except Exception:
pass
webhook_types = set(getattr(client, "webhook_log_types", ()) or ())
if (
getattr(client, "webhook_url", "")
and (not webhook_types or "ALL" in webhook_types or original_log_type in webhook_types)
):
WebhookDispatcher.enqueue(client.webhook_url, formatted)
REGEX_PATTERNS = {
"KEYS": r'(?:🔑|<:(?:chaos)?key:\d+>)\s*\(\*?\*?([\d,.]+)\*?\*?\)',
"OWNER": r'(?:[Bb]elongs to|[Pp]ertence a|[Pp]ertenece a|[Aa]ppartient [àa])\s+(.+?)$',
"CLAIMS_RANK": r"Claims:\s*#\s*([\d,.]+)",
"LIKES_RANK": r"Likes:\s*#\s*([\d,.]+)",
"DK_STOCK": r"\**(\d+)\**\s*\$dk\s*(?:available|dispon[ií]ve(?:l|is)|no estoque|disponible|en stock|disponibles?)",
"DK_READY": r"\$dk.*?(?:ready|pronto|disponible|prêt|dispon[ií]vel|listo)",
"DK_COOLDOWN": r"(?:next \$dk|próximo \$dk|siguiente \$dk|prochain \$dk).*?\*{0,2}(\d+h)?\s*(\d+)\*{0,2}\s*min",
"DK_POWER": r"(?:power|poder):\s*\*{0,2}(\d+)%\*{0,2}",
"DK_CONSUMPTION": r"(?:each kakera (?:reaction|button) consumes|cada (?:reação|botão|botón) de kakera consume|chaque bouton kakera consomme)\s*(\d+)%",
"P_COOLDOWN": r"(?:next \$p|próximo \$p|prochain \$p).*?\*{0,2}(\d+h)?\s*(\d+)\*{0,2}\s*min",
"RT_RESET": r"(?:\$rt|recarga|enfriamiento|cool).*?(?:\:|in|em|en|dans|left|restante|restam|falta|tiempo|temps|tempo|restantes|restant)\s*:?\s*\*{0,2}(\d+h)?\s*(\d+)\*{0,2}\s*min",
"CLAIM_READY": r"(?:(?:you\s+)?_{0,2}(?:can|pode|puedes|pouvez)_{0,2}\s+(?:claim|se casar|reclamar|vous (?:re)?marier)|(?:claim|marry|casamento|reclamo|mariage).*?(?:is\s+)?(?:ready|available|pronto|dispon[ií]vel|disponible|prêt))",
"CLAIM_RESET": r"(?:next claim|próximo|siguiente|prochain|tempo|temps|falta)\s+(?:reset|reclamo|tempo|temps|um tempo).*?(?:in|em|en|dans|left|restante|restant|falta|dentro de)\s*:?\s*\*{0,2}(\d+h)?\s*(\d+)\*{0,2}\s*min",
"CLAIM_COOLDOWN": r"(?:can't|não pode|no puedes|avant de|falta\s+um\s+tempo).*?(?:claim|casar|reclamar|remarier).*?\*{0,2}(\d+h)?\s*(\d+)\*{0,2}\s*min",
"CLAIM_INTERVAL_COOLDOWN": r"(?:next interval begins in|intervalo comienza en|intervalo começa em|intervalle commence dans)\s*\*{0,2}(\d+h)?\s*(\d+)\*{0,2}\s*min",
"GENERIC_COOLDOWN": r"\*{0,2}(\d+h)?\s*(\d+)\*{0,2}\s*min",
"ROLL_RESET": r"(?:reset in|reinicialização é em|siguiente reinicio.*?en|prochain rolls reset dans)\s+\*{0,2}(\d+h)?\*{0,2}\s*\*{0,2}(\d+)\*{0,2}\s*min",
"KAKERA_COOLDOWN": r"(?:react|pegar|reaccionar).*?\*{0,2}(\d+h)?\s*(\d+)\*{0,2}\s*min",
"MK_BONUS": r"\(\+\*{0,2}([\d,.]+)\*{0,2}\s+\$mk\)",
"ROLLS_COUNT": r"(?:you have|vous avez|tienes|você tem)\s+\*{0,2}([\d,.]+)\*{0,2}\s+rolls?(.*?)(?:left|restantes?|restants?\b)",
"BONUS_ROLLS": r"\(\+\*{0,2}([\d,.]+)\*{0,2}\s+\$(us|mk)\)",
"ROLL_RESET_TU": r"(?:reset|reinicialização|reinicio).*?(?:in|em|en|dans)\s+(?:.*?)\*{0,2}(\d+h)?\*{0,2}\s*\*{0,2}(\d+)\*{0,2}\s*min",
"KAKERA_EARNED": r"\+(\d+)\s*<:kakera:",
"BOLD_TEXT": r"\*\*(.+?)\*\*",
"KAKERA_VALUE": r"\**([\d,.]+)\**<:kakera:",
"MAINTENANCE": r"For\s+(?:some|(\d+))\s+minutes",
"EXTRA_ROLLS": r"\+\**(\d+)\**\s*rolls?",
"USER_BOLD": r"^\s*\*\*([^*]+)\*\*"
}
def parse_hm(m):
if not m: return 0, 0
h_s, m_s = m.groups(default="")
return (int(re.sub(r"\D", "", h_s)) if h_s else 0), (int(re.sub(r"\D", "", m_s)) if m_s else 0)
def parse_timer_minutes(pattern_name, text):
m = re.search(REGEX_PATTERNS[pattern_name], text, re.IGNORECASE)
if not m: return None
h, m_val = parse_hm(m)
return h * 60 + m_val
def first_configured(mapping, *keys):
"""Return the first explicitly configured value, preserving valid zeroes."""
for key in keys:
if key in mapping:
return mapping[key]
return None
def print_log(message, preset_name, log_type="INFO"):
BotLogger.log(message, preset_name, log_type)
def print_system_log(message, log_type="INFO"):
BotLogger.log(message, BOT_NAME, log_type)
def _debug_log_global(client_ref, log_func, preset, message):
BotLogger.log(message, preset, "DEBUG", client_ref)
def get_base_path():
if getattr(sys, 'frozen', False):
return os.path.dirname(sys.executable)
return os.path.dirname(os.path.abspath(__file__))
MUDAE_EMOJI_ASSET_DIR = os.path.join(get_base_path(), "mudae_emoji_assets")
_mudae_emoji_asset_tasks = set()
async def cache_mudae_emoji_asset(emoji):
"""Store a real Mudae custom emoji locally for the preset editor."""
name = str(getattr(emoji, "name", "") or "")
emoji_id = getattr(emoji, "id", None)
if not emoji_id or not re.fullmatch(r"(?:kakera|sp)[A-Za-z0-9]*", name):
return
destination = os.path.join(MUDAE_EMOJI_ASSET_DIR, f"{name}.png")
if os.path.isfile(destination):
return
os.makedirs(MUDAE_EMOJI_ASSET_DIR, exist_ok=True)
url = f"https://cdn.discordapp.com/emojis/{emoji_id}.png?size=64&quality=lossless"
def download():
response = requests.get(url, timeout=(3.05, 10))
response.raise_for_status()
temporary = f"{destination}.tmp"
with open(temporary, "wb") as handle:
handle.write(response.content)
os.replace(temporary, destination)
try:
await asyncio.to_thread(download)
except Exception:
# The picker retains its built-in colour fallback if Discord's CDN is
# unavailable or a custom emoji has been removed.
return
def schedule_mudae_emoji_asset_cache(client, message):
"""Cache real button artwork without delaying roll/claim handling."""
for component in getattr(message, "components", ()) or ():
for button in getattr(component, "children", ()) or ():
emoji = getattr(button, "emoji", None)
name = str(getattr(emoji, "name", "") or "")
if not re.fullmatch(r"(?:kakera|sp)[A-Za-z0-9]*", name):
continue
task_key = (getattr(emoji, "id", None), name)
if not task_key[0] or task_key in _mudae_emoji_asset_tasks:
continue
_mudae_emoji_asset_tasks.add(task_key)
task = client.loop.create_task(cache_mudae_emoji_asset(emoji))
task.add_done_callback(lambda _task, key=task_key: _mudae_emoji_asset_tasks.discard(key))
def _toggle_global_pause():
global _global_paused
_global_paused = not _global_paused
with _active_clients_lock:
for c in _active_clients:
set_client_paused(c, _global_paused)
print_system_log("⏸️ Bot paused. Press 'p' again to resume." if _global_paused else "▶️ Bot resumed. Operations continuing.", "WARN" if _global_paused else "INFO")
def _keyboard_listener_thread():
if os.name == 'nt':
while True:
try:
if _menu_active.is_set():
time.sleep(0.2)
continue
if not msvcrt.kbhit():
time.sleep(0.05)
continue
ch = msvcrt.getch()
if ch in (b'\xe0', b'\x00'):
if msvcrt.kbhit(): msvcrt.getch()
continue
if ch in (b'p', b'P'):
_toggle_global_pause()
except Exception:
time.sleep(5)
else:
if IS_TERMUX:
return
import tty, termios, select
global _original_terminal_settings
try:
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
_original_terminal_settings = old_settings
try:
tty.setcbreak(fd)
while True:
if _menu_active.is_set():
while _menu_active.is_set():
time.sleep(0.1)
try:
termios.tcflush(fd, termios.TCIFLUSH)
tty.setcbreak(fd)
except Exception: pass
continue
if select.select([sys.stdin], [], [], 0.1)[0]:
if _menu_active.is_set(): continue
ch = sys.stdin.read(1)
if ch == '\x1b':
while select.select([sys.stdin], [], [], 0.01)[0]: sys.stdin.read(1)
continue
if ch.lower() == 'p': _toggle_global_pause()
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
except Exception:
while True: time.sleep(5)
def _start_keyboard_listener():
t = threading.Thread(target=_keyboard_listener_thread, daemon=True)
t.start()
try:
_start_keyboard_listener()
except Exception:
pass
UPDATE_URL = "https://raw.githubusercontent.com/misutesu-desu/MudaRemote/refs/heads/main/"
def _confirm_update_in_console(latest_version, changelog):
print(f"\nMudaRemote v{latest_version} is available.\n")
print("Changelog:")
print(changelog)
print()
if not getattr(sys.stdin, "isatty", lambda: False)():
print_system_log("Update confirmation is unavailable in this session. Update skipped.", "WARN")
return False
try:
answer = input("Install this update now? [y/N]: ").strip().lower()
except (EOFError, KeyboardInterrupt):
return False
return answer in {"y", "yes"}
def check_for_updates(confirm_update=None):
if not UPDATE_URL:
return "disabled"
is_frozen = getattr(sys, 'frozen', False)
is_android = os.environ.get("TERMUX_VERSION") == "MudaRemote-Android" or bool(os.environ.get("MUDAREMOTE_RUNTIME_HOME"))
print_system_log(f"Checking for updates... (Current: v{CURRENT_VERSION}, Mode: {'Android' if is_android else ('EXE' if is_frozen else 'Script')})", "RESET")
try:
response = requests.get(f"{UPDATE_URL}version.json", timeout=(3.05, 8.0))
response.raise_for_status()
data = response.json()
latest_version = data.get("version")
if not latest_version or not is_newer_version(latest_version, CURRENT_VERSION):
print_system_log("You are up to date.", "INFO")
return "current"
changelog = format_update_changelog(data)
base_path = get_base_path()
if not is_frozen and not is_android and os.path.isdir(os.path.join(base_path, ".git")):
print(f"\nChangelog for v{latest_version}:\n{changelog}\n")
print_system_log(f"v{latest_version} is available. This is a Git checkout; run 'git pull' so local changes are never overwritten.", "WARN")
return "git"
confirmation = confirm_update or (
(lambda v, c: True) if is_android else _confirm_update_in_console
)
print_system_log(f"v{latest_version} is available. Waiting for update confirmation.", "RESET")
if not confirmation(latest_version, changelog):
print_system_log(f"Update to v{latest_version} was skipped. Your current files and presets were not changed.", "INFO")
return "skipped"
if is_android:
runtime_home = os.environ.get("MUDAREMOTE_RUNTIME_HOME") or os.environ.get("HOME") or base_path
target_path = os.path.join(runtime_home, "python_code")
os.makedirs(target_path, exist_ok=True)
result = apply_update(
requests,
data,
CURRENT_VERSION,
target_path,
frozen=False,
executable=sys.executable,
)
with open(os.path.join(target_path, ".version"), "w", encoding="utf-8") as vh:
vh.write(str(latest_version))
print_system_log(f"Verified Python source update v{latest_version} applied to Android storage. Will be used on next start.", "INFO")
return "source"
result = apply_update(
requests,
data,
CURRENT_VERSION,
base_path,
frozen=is_frozen,
executable=sys.executable,
)
if result == "frozen":
print_system_log("Verified update staged. Restarting via updater...", "RESET")
os._exit(0)
print_system_log("Verified full source update applied. Restarting...", "RESET")
if os.name == 'nt':
subprocess.Popen([sys.executable] + sys.argv, creationflags=subprocess.CREATE_NEW_CONSOLE)
sys.exit()
os.execv(sys.executable, [sys.executable] + sys.argv)
except UpdateError as e:
print_system_log(f"Update was not applied safely: {e}", "WARN")
return "failed"
except Exception as e:
print_system_log(f"Update failed: {e}", "ERROR")
return "failed"
def cleanup_after_update():
"""Compatibility hook retained for older launchers; updates are now transactional."""
presets = {}
presets_path = os.path.join(get_base_path(), "presets.json")
if not os.path.exists(presets_path):
try:
atomic_write_json(presets_path, {})
print_system_log(f"Created missing {presets_path}", "INFO")
except Exception as e:
print_system_log(f"Error creating {presets_path}: {e}", "ERROR")
try:
presets = load_json(presets_path, {})
_secret_store = SecretStore(get_base_path())
for _preset_name, _preset_data in presets.items():
_preset_data["tokens"] = _secret_store.get_tokens(
_preset_name,
_preset_data.get("tokens") or _preset_data.get("token", ""),
)
_preset_data["token"] = _preset_data["tokens"][0] if _preset_data["tokens"] else ""
except Exception as e:
print_system_log(f"Failed to load {presets_path}: {e}", "ERROR")
sys.exit(1)
if os.name == 'nt': os.system('')
TARGET_BOT_ID = 432610292342587392
CLAIM_EMOJIS = ['💖', '💗', '💘', '❤️', '💓', '💕', '♥️']
KAKERA_EMOJIS = ['kakeraY', 'kakeraO', 'kakeraR', 'kakeraW', 'kakeraL', 'kakeraP', 'kakeraD', 'kakeraC', 'kakera']
CHAOS_KAKERA_EMOJIS = ['kakeraY', 'kakeraO', 'kakeraR', 'kakeraW', 'kakeraL', 'kakeraP', 'kakeraD', 'kakeraC', 'kakera']
SPHERE_EMOJIS = ['spP', 'spB', 'spT', 'spG', 'spY', 'spO', 'spR', 'sp', 'spW', 'spL', 'spD', 'spM', 'spP2', 'spB2', 'spT2', 'spG2', 'spY2', 'spO2', 'spR2', 'spW2', 'spL2', 'spD2', 'spU']
async def detect_roll_owner(client, message) -> tuple:
"""
Detects the owner of a roll message.
Returns a tuple of (user_id, username_lowercase).
"""
# 1. If it was rolled via a Slash Command (Interaction)
interaction = getattr(message, "interaction_metadata", None) or getattr(message, "interaction", None)
user = getattr(interaction, "user", None)
if user is not None:
return user.id, str(user.name).casefold()
# 2. Fallback for text commands: scan channel history right before this message
# We look for: $w, $h, $m, $wx, $mx, $hx, $wa, $ha, $ma, $mg, $hg, $wg
commands = {"w", "h", "m", "wx", "mx", "hx", "wa", "ha", "ma", "mg", "hg", "wg", str(getattr(client, "roll_command", "") or "").strip().lower()}
commands.discard("")
pattern = re.compile(r"^\s*" + re.escape(client.mudae_prefix) + r"(?:" + "|".join(map(re.escape, sorted(commands, key=len, reverse=True))) + r")\s*$", re.IGNORECASE)
try:
async for msg in message.channel.history(limit=8, before=message):
if message.created_at and msg.created_at and (message.created_at - msg.created_at).total_seconds() > 10:
break
if pattern.fullmatch((msg.content or "").strip()):
return msg.author.id, msg.author.name.casefold()
except Exception:
pass
# 3. Last fallback: Check embed footer for Mudae ownership text if present
owner_username = None
if message.embeds:
embed = message.embeds[0]
if embed.footer and embed.footer.text:
m = re.search(REGEX_PATTERNS["OWNER"], embed.footer.text)
if m:
owner_username = m.group(1).strip().casefold()
return None, owner_username
def check_is_green(b):
s = getattr(b, 'style', None)
return s is not None and (getattr(s, 'value', None) == 3 or str(s).endswith('success') or str(s) == '3')
def is_character_embed(embed):
return bool(embed and embed.author and embed.author.name and embed.image and embed.image.url and not (embed.thumbnail and embed.thumbnail.url))
def is_free_event(embed):
if not embed or not embed.description: return False
desc = embed.description.lower()
return any(k in desc for k in ["it's free!", "é de graça!", "¡es gratis!", "christmas art contest", "new year's contest"])
def has_claim_option(message, embed, claim_emojis):
if not message.components: return not get_character_owner(embed)
return any(not getattr(btn, "disabled", False) and getattr(getattr(btn, "emoji", None), "name", None) in claim_emojis for comp in message.components for btn in comp.children)
def count_chaos_keys(embed):
if not embed or not embed.description: return 0
matches = re.findall(REGEX_PATTERNS["KEYS"], embed.description, re.IGNORECASE)
return sum(1 for m in matches if int(re.sub(r"[^\d]", "", m)) >= 10)
def get_character_owner(embed):
if not embed or not embed.footer or not embed.footer.text: return None
m = re.search(REGEX_PATTERNS["OWNER"], embed.footer.text)
return m.group(1).strip().lower() if m else None
def is_wished_by_self(message, client_user_id: int) -> bool:
return bool(message and message.content and "wished by" in message.content.lower() and client_user_id in [m.id for m in message.mentions])
def parse_mudae_ranks(embed_description: str) -> Tuple[int, int]:
if not embed_description: return 0, 0
def get_rank(pattern_name):
m = re.search(REGEX_PATTERNS[pattern_name], embed_description, re.IGNORECASE)
return int(m.group(1).replace(",", "").replace(".", "")) if m else 0
return get_rank("CLAIMS_RANK"), get_rank("LIKES_RANK")
def run_bot(token, prefix, target_channel_id, roll_command, min_kakera, delay_seconds, mudae_prefix,
log_function, preset_name, key_mode, start_delay, snipe_mode, snipe_delay,
snipe_ignore_min_kakera_reset, wishlist,
series_snipe_mode, series_snipe_delay, series_wishlist, roll_speed,
kakera_snipe_mode_preset, kakera_snipe_threshold_preset,
enable_reactive_self_snipe_preset, rolling_enabled,
kakera_reaction_snipe_mode_preset, kakera_reaction_snipe_delay_preset,
kakera_reaction_snipe_targets,
character_snipe_targets=None,
humanization_enabled=False, humanization_window_minutes=0, humanization_inactivity_seconds=0,
dk_power_management=True, skip_initial_commands=False, use_slash_rolls=False, only_chaos=False,
reactive_snipe_delay=0.5, time_rolls_to_claim_reset_preset=False,
rt_ignore_min_kakera_for_wishlist_preset=False,
claim_emojis_preset=None, kakera_emojis_preset=None, chaos_emojis_preset=None, sphere_perk_emojis_preset=None,
rt_only_self_rolls_preset=False, reactive_kakera_delay_range_preset=None,
claim_interval_preset=180, roll_interval_preset=60, avoid_list=None,
inactive_hours_preset=None,
auto_us_enabled=False, auto_us_limit=10, auto_us_stop_on_claim=True,
kakera_power_thresholds=None, debug_mode=False, auto_mk_enabled_preset=False,
auto_rolls_enabled=False, auto_rolls_limit=10, auto_rolls_in_key_mode=False,
auto_rolls_only_claim_hour_preset=False,
panic_roll_minutes_preset=5, lurker_mode_preset=False,
bulk_us_enabled_preset=False,
max_dk_power_preset=100,
randomized_claim_reactions_preset=None,
main_account_id_preset="",
scheduled_roll_times_preset=None,
kakera_priority_order_preset=None,
auto_rt_after_claim_preset=False,
mk_only_preset=False,
auto_dk_enabled_preset=True,
command_channel_id_preset="",
enable_snipe_chat_reactions_preset=False,
snipe_chat_messages_preset=None,
farm_character_preset="",
op_perk_5_only_preset=False,
farm_character_enabled_preset=False,
auto_divorce_enabled_preset=False,
auto_divorce_max_kakera_preset=50,
auto_divorce_series_preset=None,
auto_divorce_blacklist_preset=None,
auto_divorce_blacklist_series_preset=None,
mk_bypass_power_check=False,
snipe_channels_preset=None,
max_claim_rank_preset=0,
max_like_rank_preset=0,
auto_p_enabled=True,
enable_hybrid_panic_claim_preset=False,
hybrid_panic_instant_claim_min_kakera_preset=300,
hybrid_panic_instant_claim_max_rank_preset=200,
claim_rounds_thresholds_preset=None,
persistent_stagger_seconds_preset=0,
sphere_click_targets_preset=None,
immediate_kakera_click_preset=True,
farm_forcedivorce_after_claim_preset=False,
farm_forcedivorce_before_roll_preset=True,
farm_forcedivorce_after_other_claim_preset=False,
auto_oh_enabled_preset=False,
auto_oc_enabled_preset=False,
series_snipe_only_self_rolls_preset=False,
forcedivorce_channel_id_preset="",
wish_starwish_kakera_only_preset=False,
auto_mk_full_power_only_preset=False,
auto_divorce_protect_wishes_preset=True,
farm_characters_preset=None,
enable_kakera_snipe_chat_reactions_preset=False,
kakera_snipe_chat_messages_preset=None,
oh_priority_order_preset=None,
oh_unknown_explore_clicks_preset=3,
oc_reward_priority_order_preset=None,
oc_collect_after_red_preset=True,
webhook_url_preset="",
webhook_log_types_preset=None,
debug_log_categories_preset=None,
auto_free_claim_preset=True,
collect_purple_kakera_preset=True,
oh_use_individually_preset=False,
auto_dk_min_power_preset=0,
kakera_snipe_channels_preset=None):
client = commands.Bot(command_prefix=prefix, chunk_guilds_at_startup=False, self_bot=True)
client.is_paused = _global_paused
client._pause_generation = 1 if _global_paused else 0
client.command_pacer = CommandPacer(0.6, 0.8)
with _active_clients_lock: _active_clients.append(client)
discord_logger = logging.getLogger('discord')
discord_logger.propagate = False
handlers = [h for h in discord_logger.handlers if isinstance(h, logging.StreamHandler)]
for h in handlers:
discord_logger.removeHandler(h)
# Bind preset configs
client.preset_name = preset_name
client.min_kakera = min_kakera
client.snipe_mode = snipe_mode
client.snipe_delay = snipe_delay
client.snipe_ignore_min_kakera_reset = snipe_ignore_min_kakera_reset
client.wishlist = set([w.lower() for w in wishlist])
client.series_snipe_mode = series_snipe_mode
client.series_snipe_only_self_rolls = bool(series_snipe_only_self_rolls_preset)
client.series_snipe_delay = series_snipe_delay
client.series_wishlist = set([sw.lower() for sw in series_wishlist])
client.avoid_list = set([a.lower() for a in (avoid_list or [])])
client.snipe_channels = set()
for ch in snipe_channels_preset or []:
try: client.snipe_channels.add(int(ch))
except (TypeError, ValueError): pass
client.kakera_snipe_channels = set()
configured_kakera_snipe_channels = kakera_snipe_channels_preset or snipe_channels_preset or []
for ch in configured_kakera_snipe_channels:
try: client.kakera_snipe_channels.add(int(ch))
except (TypeError, ValueError): pass
client.max_claim_rank = int(max_claim_rank_preset or 0)
client.max_like_rank = int(max_like_rank_preset or 0)
client.muda_name = BOT_NAME
client.claim_right_available = False
# Presets may store Discord snowflakes as strings, while Discord exposes
# message.channel.id as an int. Keep the runtime value normalized so
# own-roll messages are recognized by on_message.
try:
client.target_channel_id = int(target_channel_id)
except (TypeError, ValueError):
client.target_channel_id = target_channel_id
client.roll_command = str(roll_command or "wa").strip().lstrip("/") or "wa"
client.command_channel_id_preset = str(command_channel_id_preset or "").strip()
client.forcedivorce_channel_id_preset = str(forcedivorce_channel_id_preset or "").strip()
client.roll_speed = roll_speed
client.mudae_prefix = mudae_prefix
client.key_mode = key_mode
client.delay_seconds = delay_seconds
client.sniped_messages = set()
client.snipe_happened = False
client.series_sniped_messages = set()
client.series_snipe_happened = False
client.kakera_value_sniped_messages = set()
client.is_actively_rolling = False
client.active_cycle_id = 0
client.tu_lock = None
client.interrupt_rolling = False
client._roll_interrupt_reason = None
client.current_min_kakera_for_roll_claim = client.min_kakera
client.kakera_snipe_mode_active = kakera_snipe_mode_preset
client.kakera_snipe_threshold = kakera_snipe_threshold_preset
client.enable_reactive_self_snipe = enable_reactive_self_snipe_preset
client.auto_free_claim_enabled = bool(auto_free_claim_preset)
client.reactive_snipe_delay = reactive_snipe_delay
client.rolling_enabled = rolling_enabled
client.rt_available = False
client.rt_available_at_utc = None
client.kakera_reaction_snipe_mode_active = kakera_reaction_snipe_mode_preset
client.kakera_reaction_snipe_delay_value = kakera_reaction_snipe_delay_preset
client.kakera_reaction_snipe_targets = set([t.lower() for t in kakera_reaction_snipe_targets])
client.character_snipe_targets = set([t.lower().strip() for t in (character_snipe_targets or []) if t.strip()])
client.kakera_reaction_sniped_messages = set()
client.kakera_react_available = None
client.kakera_react_cooldown_until_utc = None
client.humanization_enabled = humanization_enabled
client.humanization_window_minutes = humanization_window_minutes
client.inactive_hours = inactive_hours_preset or []
client.humanization_inactivity_seconds = humanization_inactivity_seconds
client.auto_dk_enabled = auto_dk_enabled_preset
client.dk_power_management = dk_power_management
client.skip_initial_commands = skip_initial_commands
client.dk_stock_count = 0
client.max_dk_power = max_dk_power_preset
client.auto_dk_min_power = max(0, int(auto_dk_min_power_preset or 0))
client.maintenance_until = None
client.only_chaos = only_chaos
client.mk_only = mk_only_preset
client.auto_us_enabled = auto_us_enabled
client.auto_us_limit = auto_us_limit
client.auto_us_stop_on_claim = auto_us_stop_on_claim
client.bulk_us_enabled = bulk_us_enabled_preset
client.us_pulled_this_cycle = 0
client.mk_rolls_left = 0
client.auto_mk_enabled = auto_mk_enabled_preset
client.auto_mk_full_power_only = bool(auto_mk_full_power_only_preset)
client._mk_full_power_refresh_at = None
client.auto_rolls_enabled = auto_rolls_enabled
client.auto_rolls_limit = auto_rolls_limit
client.auto_rolls_in_key_mode = auto_rolls_in_key_mode
client.auto_rolls_only_claim_hour = auto_rolls_only_claim_hour_preset
client.rolls_item_used_count = 0
client.rolls_used_this_interval_utc = None
client.panic_roll_minutes = panic_roll_minutes_preset if panic_roll_minutes_preset is not None else 5
client.lurker_mode = lurker_mode_preset
client.auto_rt_after_claim = auto_rt_after_claim_preset
client.randomized_claim_reactions = randomized_claim_reactions_preset or ["💖", "💗", "💘", "❤️", "👍", "🔥"]
client.main_account_id = str(main_account_id_preset or "").strip()
client.scheduled_roll_times = scheduled_roll_times_preset or []
client.kakera_priority_order = kakera_priority_order_preset or [
'kakeraP', 'kakeraC', 'kakeraL', 'kakeraW', 'kakeraR', 'kakeraO', 'kakeraD', 'kakeraY', 'kakeraG', 'kakeraT', 'kakera'
]
sphere_click_targets = (
["spG", "spY", "spO", "spR", "spW", "spL", "spD", "spM", "spU"]
if sphere_click_targets_preset is None
else sphere_click_targets_preset
)
client.sphere_click_targets = {
normalize_character_sphere_emoji(target).casefold()
for target in sphere_click_targets
if str(target or "").strip()
}
client.immediate_kakera_click = immediate_kakera_click_preset
# Purple Kakera is free, but in a shared channel every account may race
# for it. Keep legacy presets opt-in by default while allowing each preset
# to opt out independently.
client.collect_purple_kakera = bool(collect_purple_kakera_preset)
client.auto_oh_enabled = bool(auto_oh_enabled_preset)
client.auto_oc_enabled = bool(auto_oc_enabled_preset)
client.oh_use_individually = bool(oh_use_individually_preset)
client.oh_priority_order = [
str(item).strip() for item in (oh_priority_order_preset or []) if str(item).strip()
]
client.oh_unknown_explore_clicks = max(0, int(oh_unknown_explore_clicks_preset or 0))
client.oc_reward_priority_order = [
str(item).strip() for item in (oc_reward_priority_order_preset or []) if str(item).strip()
]
client.oc_collect_after_red = bool(oc_collect_after_red_preset)
client.sphere_game_counts = {"oh": 0, "oc": 0, "oq": 0, "ot": 0}
client.sphere_game_refill_at_utc = None
# run_bot is entered from a worker thread before discord.py creates that
# thread's event loop. Bind per-client locks lazily from their first async task.
client._sphere_game_lock = None
client._kakera_action_lock = None
client._sphere_game_response_future = None
client._sphere_game_response_channel_id = None
client._sphere_game_response_kind = None
client._sphere_game_bonus_clicks = 0
client._sphere_game_bonus_event = None
client._sphere_game_bonus_counts = {}
client._sphere_game_retry_after = {"oh": 0.0, "oc": 0.0}
client._sphere_board_update_events = {}
client._kakera_power_reconcile_handle = None
client.kakera_power_ledger = KakeraPowerLedger()
client._mudae_command_ack_waiters = {}
client._recent_mudae_command_acks = {}
client._rolls_ack_retry_after = 0.0
client._confirmed_kakera_c_bonus_until = 0.0
client.collected_kakera_rolls = []
client.enable_snipe_chat_reactions = enable_snipe_chat_reactions_preset
client.snipe_chat_messages = snipe_chat_messages_preset or ["omg", "ezz"]
client.enable_kakera_snipe_chat_reactions = bool(enable_kakera_snipe_chat_reactions_preset)
client.kakera_snipe_chat_messages = kakera_snipe_chat_messages_preset or ["nice", "free kakera"]
configured_farm_characters = list(farm_characters_preset or [])
if farm_character_preset:
configured_farm_characters.insert(0, farm_character_preset)
client.farm_characters = []
seen_farm_characters = set()
for farm_name in configured_farm_characters:
cleaned_farm_name = str(farm_name or "").strip()
normalized_farm_name = cleaned_farm_name.casefold()
if cleaned_farm_name and normalized_farm_name not in seen_farm_characters:
seen_farm_characters.add(normalized_farm_name)
client.farm_characters.append(cleaned_farm_name)
client.farm_character = client.farm_characters[0] if client.farm_characters else ""
client.farm_character_enabled = farm_character_enabled_preset
client.farm_forcedivorce_after_claim = bool(farm_forcedivorce_after_claim_preset)
client.farm_forcedivorce_before_roll = bool(farm_forcedivorce_before_roll_preset)
client.farm_forcedivorce_after_other_claim = bool(farm_forcedivorce_after_other_claim_preset)
client.forcedivorce_channel = None
client._farm_release_recent = {}
client._farm_release_lock = None
client.op_perk_5_only = op_perk_5_only_preset
client.auto_divorce_protect_wishes = bool(auto_divorce_protect_wishes_preset)
client.wish_starwish_kakera_only = bool(wish_starwish_kakera_only_preset)
client.next_claim_reset_at_utc = None
client.roll_reset_at_utc = None
client.claim_cooldown_until_utc = None
client.is_claiming = False
client.snipe_watch = {}
client.snipe_watch_expiry_seconds = 180
client.snipe_globally_disabled_until = None
client.current_dk_power = None
client.dk_power_revision = 0
client._us_lock = None
client._us_in_flight = False
client._us_pending_amount = 0
client._us_retry_after = 0.0
client.us_failed_this_cycle = False
client.dk_consumption = 35
client.kakera_reacted_messages = set()