-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
615 lines (522 loc) · 23 KB
/
Copy pathmain.py
File metadata and controls
615 lines (522 loc) · 23 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
import asyncio
import time
import threading
import random
from urllib.parse import urlsplit, urlunsplit
import aiohttp
from discord.ext import commands
from core import config, log
from core.config import AccountConfig
from core.activation import check_activation
from cogs.utils import ActivityCoordinator
from cogs.tracker import get_tracker
from cogs.vote_handler import VoteHandler
class PokeGrindBot:
"""Single bot instance for one account"""
def __init__(self, account_config: AccountConfig, startup_delay: float = 0):
self.account = account_config
self.startup_delay = (
startup_delay # Seconds to wait before running startup commands
)
self.startup_delay_anchor_ts = time.time()
self._proxy_config = self.account.proxy
self._proxy_options = self._resolve_proxy_options(self._proxy_config) if self._proxy_config else {}
self._proxy_enabled = bool(self._proxy_options)
self._proxy_connect_failures = 0
self._proxy_max_connect_failures = self._resolve_proxy_failover_threshold(self._proxy_config)
self._connection_reached_ready = False
self._proxy_invalid_warned = False
self.bot = self._build_bot_client()
self.coordinator = None
self._setup_events()
self._should_disconnect = False
self._reconnect_at = 0
self._disconnect_no_rod = False
self._manual_paused = False
@staticmethod
def _resolve_proxy_options(proxy_cfg: dict) -> dict:
url = str(proxy_cfg.get("url", "")).strip()
if not url:
return {}
if "://" not in url:
url = f"http://{url}"
parsed = urlsplit(url)
if not parsed.scheme or not parsed.hostname or not parsed.port:
return {}
# Strip userinfo from URL and pass auth explicitly.
username = str(proxy_cfg.get("username", "")).strip()
password = str(proxy_cfg.get("password", ""))
if parsed.username and not username:
username = parsed.username
password = parsed.password or ""
clean_netloc = parsed.hostname
if parsed.port:
clean_netloc = f"{clean_netloc}:{parsed.port}"
clean_url = urlunsplit(
(parsed.scheme, clean_netloc, parsed.path or "", parsed.query or "", parsed.fragment or "")
)
options = {
"proxy": clean_url,
"proxy_gateway": bool(proxy_cfg.get("proxy_gateway", True)),
}
if username:
options["proxy_auth"] = aiohttp.BasicAuth(username, password)
return options
@staticmethod
def _resolve_proxy_failover_threshold(proxy_cfg: dict) -> int:
raw = proxy_cfg.get("max_connect_failures", 3) if isinstance(proxy_cfg, dict) else 3
try:
return max(1, int(raw))
except (TypeError, ValueError):
return 3
def _handle_proxy_connect_failure(self) -> bool:
"""Return True when proxy was disabled and we should retry immediately."""
if not self._proxy_enabled or self._connection_reached_ready:
return False
self._proxy_connect_failures += 1
if self._proxy_connect_failures < self._proxy_max_connect_failures:
log.warning(
"proxy",
(
f"[{self.account.name}] Proxy connect failed "
f"({self._proxy_connect_failures}/{self._proxy_max_connect_failures}); retrying with proxy"
),
)
return False
self._proxy_enabled = False
log.warning(
"proxy",
(
f"[{self.account.name}] Proxy connect failed "
f"{self._proxy_connect_failures} times - falling back to direct IP"
),
)
return True
def _build_bot_client(self) -> commands.Bot:
options = {"command_prefix": ">", "self_bot": True}
if self._proxy_enabled and self._proxy_options:
options.update(self._proxy_options)
proxy_host = urlsplit(self._proxy_options["proxy"]).hostname or "proxy"
log.info("proxy", f"[{self.account.name}] Proxy enabled ({proxy_host})")
elif self._proxy_config and not self._proxy_options and not self._proxy_invalid_warned:
self._proxy_invalid_warned = True
log.warning("proxy", f"[{self.account.name}] Invalid proxy config; using direct connection")
return commands.Bot(**options)
def _get_cog_modules(self):
"""Get cog modules; fishing is always loaded, activation is via rod detection"""
return ["cogs.hunting", "cogs.fishing", "cogs.items"]
def _setup_events(self):
account_name = self.account.name
@self.bot.event
async def on_ready():
self._connection_reached_ready = True
if self._proxy_enabled and self._proxy_connect_failures:
self._proxy_connect_failures = 0
await self._initialize_coordinator()
log.startup(f"[{account_name}] Logged in as {self.bot.user}")
@self.bot.event
async def on_error(event, *args, **kwargs):
log.error("error", f"[{account_name}] Event error in {event}")
@self.bot.event
async def on_disconnect():
log.warning("warning", f"[{account_name}] Disconnected from Discord")
@self.bot.event
async def on_resumed():
log.info("resume", f"[{account_name}] Connection resumed")
async def _initialize_coordinator(self):
if self.coordinator and self.coordinator.running:
log.warning("warning", f"[{self.account.name}] Coordinator already initialized - skipping duplicate on_ready")
return
hunting = self.bot.get_cog("Hunting")
fishing = self.bot.get_cog("Fishing")
items = self.bot.get_cog("Items")
if hunting:
self.coordinator = ActivityCoordinator(
self.bot,
account_name=self.account.name,
continue_fishing_after_hunt_limit=self.account.continue_fishing_after_hunt_limit,
patreon=self.account.patreon,
)
self.coordinator.set_cogs(hunting, fishing, items)
self.coordinator.set_bot_instance(self)
hunting.set_coordinator(self.coordinator)
hunting.set_account_config(self.account)
if fishing:
fishing.set_coordinator(self.coordinator)
fishing.set_account_config(self.account)
fishing._active = False
if items:
items.set_coordinator(self.coordinator)
items.set_account_config(self.account)
if self._manual_paused:
log.warning(
"keyboard",
f"[{self.account.name}] Account is paused - activity loops will not start",
)
self.coordinator.stop()
else:
asyncio.create_task(self.coordinator.run_loop())
# Attach vote handler; uses account's own topgg_session
vote_handler = VoteHandler(
account_name=self.account.name,
topgg_session=self.account.topgg_session,
proxy=self.account.proxy,
)
self.coordinator.vote_handler = vote_handler
async def _load_cogs(self):
for cog in self._get_cog_modules():
try:
await self.bot.load_extension(cog)
log.startup(f"[{self.account.name}] Loaded: {cog}")
except Exception as e:
log.error("error", f"[{self.account.name}] Failed to load {cog}: {e}")
def schedule_disconnect(self, reconnect_at: float):
"""Schedule disconnection and reconnection at specified time"""
self._should_disconnect = True
self._reconnect_at = reconnect_at
if self.coordinator:
self.coordinator.stop()
asyncio.create_task(self._disconnect())
async def _disconnect(self):
"""Disconnect from Discord"""
try:
if self._disconnect_no_rod:
log.warning(
"disconnect",
f"[{self.account.name}] Disconnecting (no fishing rod detected)",
)
else:
log.warning(
"disconnect",
f"[{self.account.name}] Disconnecting until limit reset...",
)
await self.bot.close()
except Exception as e:
log.error("error", f"[{self.account.name}] Disconnect error: {e}")
def disconnect_for_no_rod(self):
"""Permanently disconnect this account when no fishing rod is available."""
self._disconnect_no_rod = True
if self.coordinator:
self.coordinator.stop()
asyncio.create_task(self._disconnect())
async def start(self):
while True:
try:
if self._disconnect_no_rod:
log.info("disconnect", f"[{self.account.name}] Account stopped (no fishing rod)")
break
# Check if we should wait before reconnecting
if self._should_disconnect and self._reconnect_at > 0:
wait_time = self._reconnect_at - time.time()
if wait_time > 0:
hours = int(wait_time // 3600)
minutes = int((wait_time % 3600) // 60)
log.info(
"disconnect",
f"[{self.account.name}] Waiting {hours}h {minutes}m until reconnect...",
)
await asyncio.sleep(wait_time)
self._should_disconnect = False
self._reconnect_at = 0
log.info(
"reconnect",
f"[{self.account.name}] Reconnecting after limit reset...",
)
# Create a fresh bot instance for each connection
self._connection_reached_ready = False
self.bot = self._build_bot_client()
self._setup_events()
self.coordinator = None
async with self.bot:
await self._load_cogs()
await self.bot.start(self.account.token)
if self._disconnect_no_rod:
break
except Exception as e:
if self._disconnect_no_rod:
break
log.error("error", f"[{self.account.name}] Connection error: {e}")
if self._handle_proxy_connect_failure():
continue
if self._should_disconnect:
# Don't reconnect immediately if we're supposed to wait
continue
log.info(
"resume", f"[{self.account.name}] Reconnecting in 30 seconds..."
)
await asyncio.sleep(30)
def stop(self):
if self.coordinator:
self.coordinator.stop()
def pause(self) -> bool:
"""Pause account activity loops without disconnecting the client."""
was_paused = self._manual_paused
self._manual_paused = True
if self.coordinator and self.coordinator.running:
self.coordinator.stop()
return not was_paused
def unpause(self) -> bool:
"""Resume account activity loops after a manual pause."""
was_paused = self._manual_paused
self._manual_paused = False
if not was_paused:
return False
if self.coordinator and not self.coordinator.running:
self.coordinator.running = True
asyncio.create_task(self.coordinator.run_loop())
return True
@property
def is_paused(self) -> bool:
return self._manual_paused
class MultiAccountManager:
"""Manages multiple bot instances"""
def __init__(self):
self.bots = []
self._loop = None
self._awaiting_pause_account = False
self._pause_input_buffer = ""
self._pending_account_action = None
@staticmethod
def _account_startup_delay_seconds() -> int:
"""Independent per-account startup delay derived from a random fatigue start-point."""
# Each account gets its own random session progress anchor (0..1).
fatigue_start = random.random()
# Bell-shape similar to in-session fatigue: middle progress tends to feel "slower".
bell_center = 0.62
bell_sigma = 0.24
bell = pow(2.718281828, -((fatigue_start - bell_center) ** 2) / (2.0 * (bell_sigma ** 2)))
# Independent sample per account; no order/index influence.
fatigue_factor = 1.0 + (0.75 * bell * max(0.75, min(1.25, random.normalvariate(1.0, 0.18))))
base_delay = random.uniform(10.0, 35.0)
sampled = random.normalvariate(base_delay * fatigue_factor, 6.5)
return int(max(6.0, min(95.0, round(sampled))))
def _get_banner_lines(self):
return [
"======================================================================",
" ____ ___ _ __ _____ ____ ____ ___ _ _ ____ ",
" | _ \\ / _ \\| |/ /| ____/ ___| _ \\|_ _| \\ | | _ \\ ",
" | |_) | | | | ' / | _|| | _| |_) || || \\| | | | |",
" | __/| |_| | . \\ | |__| |_| | _ < | || |\\ | |_| |",
" |_| \\___/|_|\\_\\|_____\\____|_| \\_\\___|_| \\_|____/ ",
" made by: DragonBlz",
"======================================================================",
]
def _get_hotkey_lines(self, accounts=None):
lines = [
"Hotkeys",
" [U] Trigger /items view on all accounts",
" [P] Pause one account by number (type number + Enter)",
" [R] Unpause one account by number (type number + Enter)",
" [L] Toggle continue fishing after hunt limit (all accounts)",
" [Ctrl+C] Stop all accounts",
]
if accounts:
lines.append("")
lines.append("Account Numbers")
for i, account in enumerate(accounts, start=1):
lines.append(f" [{i}] {account.name}")
return lines
def _start_keyboard_listener(self):
"""Background thread listening for console keypresses."""
try:
import msvcrt # Windows only
except ImportError:
log.warning("keyboard", "Keyboard listener not available (non-Windows)")
return
def _listener():
while True:
try:
if msvcrt.kbhit():
key_bytes = msvcrt.getch()
if key_bytes in (b"\x00", b"\xe0"):
# Swallow arrow/function key second byte.
msvcrt.getch()
continue
key = key_bytes.decode("utf-8", errors="ignore").lower()
if self._awaiting_pause_account:
if key_bytes == b"\r":
self._on_hotkey_account_action_submit()
elif key_bytes == b"\x1b":
self._awaiting_pause_account = False
self._pause_input_buffer = ""
self._pending_account_action = None
log.info("keyboard", "Action cancelled")
elif key_bytes == b"\x08":
self._pause_input_buffer = self._pause_input_buffer[:-1]
elif key.isdigit():
self._pause_input_buffer += key
continue
if key == "u":
self._on_hotkey_items()
elif key == "p":
self._on_hotkey_pause_prompt()
elif key == "r":
self._on_hotkey_unpause_prompt()
elif key == "l":
self._on_hotkey_toggle_hunt_limit_fishing()
except Exception:
pass
time.sleep(0.1)
thread = threading.Thread(target=_listener, daemon=True)
thread.start()
def _on_hotkey_items(self):
"""Called from keyboard thread; schedules items check on the async loop."""
if not self._loop:
return
log.info("keyboard", "[U] pressed - triggering /items view on all accounts")
for bot in self.bots:
if bot.coordinator and bot.coordinator.running:
if bot.coordinator.is_hunt_limited_without_rod():
log.info(
"keyboard",
f"[{bot.account.name}] Skipping hotkey /items view (hunt limit reached and fishing will not continue)",
)
continue
asyncio.run_coroutine_threadsafe(
bot.coordinator.trigger_manual_items_check(),
self._loop,
)
def _on_hotkey_toggle_hunt_limit_fishing(self):
"""Toggle whether fishing continues after hunt limit (all running accounts)."""
if not self._loop:
return
asyncio.run_coroutine_threadsafe(
self._toggle_hunt_limit_fishing_all(),
self._loop,
)
def _on_hotkey_pause_prompt(self):
if not self.bots:
log.warning("keyboard", "No accounts are running")
return
self._awaiting_pause_account = True
self._pause_input_buffer = ""
self._pending_account_action = "pause"
log.info("keyboard", "[P] pressed - enter account number, then press [Enter]")
for i, bot in enumerate(self.bots, start=1):
state = "paused" if bot.is_paused else "running"
log.info("keyboard", f" [{i}] {bot.account.name} ({state})")
def _on_hotkey_unpause_prompt(self):
if not self.bots:
log.warning("keyboard", "No accounts are running")
return
self._awaiting_pause_account = True
self._pause_input_buffer = ""
self._pending_account_action = "unpause"
log.info("keyboard", "[R] pressed - enter account number, then press [Enter]")
for i, bot in enumerate(self.bots, start=1):
state = "paused" if bot.is_paused else "running"
log.info("keyboard", f" [{i}] {bot.account.name} ({state})")
def _on_hotkey_account_action_submit(self):
raw = self._pause_input_buffer.strip()
self._awaiting_pause_account = False
self._pause_input_buffer = ""
action = self._pending_account_action
self._pending_account_action = None
if not raw:
log.warning("keyboard", "No account number entered - action cancelled")
return
try:
account_number = int(raw)
except ValueError:
log.warning("keyboard", f"Invalid account number '{raw}'")
return
if not self._loop:
return
if action == "pause":
asyncio.run_coroutine_threadsafe(
self._pause_account_by_number(account_number),
self._loop,
)
elif action == "unpause":
asyncio.run_coroutine_threadsafe(
self._unpause_account_by_number(account_number),
self._loop,
)
async def _pause_account_by_number(self, account_number: int):
if account_number < 1 or account_number > len(self.bots):
log.warning("keyboard", f"Account #{account_number} not found")
return
bot = self.bots[account_number - 1]
paused_now = bot.pause()
if paused_now:
log.warning("keyboard", f"Paused account #{account_number}: {bot.account.name}")
else:
log.info("keyboard", f"Account #{account_number} is already paused: {bot.account.name}")
async def _unpause_account_by_number(self, account_number: int):
if account_number < 1 or account_number > len(self.bots):
log.warning("keyboard", f"Account #{account_number} not found")
return
bot = self.bots[account_number - 1]
resumed_now = bot.unpause()
if resumed_now:
log.info("keyboard", f"Unpaused account #{account_number}: {bot.account.name}")
else:
log.info("keyboard", f"Account #{account_number} is not paused: {bot.account.name}")
async def _toggle_hunt_limit_fishing_all(self):
coordinators = [
bot.coordinator
for bot in self.bots
if bot.coordinator and bot.coordinator.running
]
if not coordinators:
log.warning("keyboard", "No running coordinators to toggle")
return
target_enabled = not all(
coordinator.continue_fishing_after_hunt_limit
for coordinator in coordinators
)
for bot in self.bots:
coordinator = bot.coordinator
if not coordinator:
continue
coordinator.set_continue_fishing_after_hunt_limit(target_enabled)
log.info(
"keyboard",
f"[{bot.account.name}] ContinueFishingAfterHuntLimit={target_enabled}",
)
mode_text = "continue" if target_enabled else "stop"
log.info(
"keyboard",
f"[L] toggled - fishing will {mode_text} after hunt limit is reached",
)
async def start_all(self):
self._loop = asyncio.get_event_loop()
accounts = config.accounts
tracker = get_tracker()
# Configure CLI first so all logs render beneath the static header.
log.configure_cli(
banner_lines=self._get_banner_lines(),
hotkey_lines=self._get_hotkey_lines(accounts),
clear_every=100,
)
log.update_catch_info(tracker.get_all_account_stats_lines())
if not accounts:
log.error("error", "No accounts configured!")
return
log.startup(f"Starting {len(accounts)} account(s)...")
# Start keyboard listener
self._start_keyboard_listener()
# Create bot instances immediately; each account gets its own startup cooldown.
tasks = []
for i, account in enumerate(accounts):
startup_delay = self._account_startup_delay_seconds()
log.startup(
f"[#{i + 1} {account.name}] Loading account (startup commands in ~{startup_delay}s)"
)
bot = PokeGrindBot(account, startup_delay=startup_delay)
self.bots.append(bot)
tasks.append(asyncio.create_task(bot.start()))
await asyncio.gather(*tasks)
def stop_all(self):
for bot in self.bots:
bot.stop()
def main():
check_activation()
manager = MultiAccountManager()
try:
asyncio.run(manager.start_all())
except KeyboardInterrupt:
log.info("info", "Shutting down all accounts...")
manager.stop_all()
if __name__ == "__main__":
main()