-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
1691 lines (1361 loc) · 57.7 KB
/
Copy pathdatabase.py
File metadata and controls
1691 lines (1361 loc) · 57.7 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 asyncpg
import os
from datetime import datetime
from typing import List, Dict, Optional
# Database connection pool
pool: Optional[asyncpg.Pool] = None
async def setup_database():
"""Initialize database connection and create tables"""
global pool
database_url = os.getenv('DATABASE_URL')
if not database_url:
print("WARNING: DATABASE_URL not set. Database features will not work.")
return
try:
# Create connection pool
print("Creating database connection pool...", flush=True)
pool = await asyncpg.create_pool(database_url, min_size=2, max_size=10)
print("Database connection pool created", flush=True)
# Create tables
async with pool.acquire() as conn:
# Guilds table - stores server configurations
await conn.execute('''
CREATE TABLE IF NOT EXISTS guilds (
guild_id BIGINT PRIMARY KEY,
spawn_channels BIGINT[],
spawn_interval_min INTEGER DEFAULT 180,
spawn_interval_max INTEGER DEFAULT 600,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
)
''')
# Catches table - stores all Pokemon catches
await conn.execute('''
CREATE TABLE IF NOT EXISTS catches (
id SERIAL PRIMARY KEY,
user_id BIGINT NOT NULL,
guild_id BIGINT NOT NULL,
pokemon_name TEXT NOT NULL,
pokemon_id INTEGER NOT NULL,
pokemon_types TEXT[],
is_shiny BOOLEAN DEFAULT FALSE,
caught_at TIMESTAMP DEFAULT NOW()
)
''')
# Create indexes for faster queries
await conn.execute('''
CREATE INDEX IF NOT EXISTS idx_catches_user
ON catches(user_id, guild_id)
''')
await conn.execute('''
CREATE INDEX IF NOT EXISTS idx_catches_guild
ON catches(guild_id)
''')
# Battlepass table - tracks user progression
await conn.execute('''
CREATE TABLE IF NOT EXISTS user_battlepass (
user_id BIGINT NOT NULL,
guild_id BIGINT NOT NULL,
season INTEGER DEFAULT 1,
xp INTEGER DEFAULT 0,
level INTEGER DEFAULT 1,
last_updated TIMESTAMP DEFAULT NOW(),
PRIMARY KEY (user_id, guild_id, season)
)
''')
# Packs table - tracks user's pack inventory by type
await conn.execute('''
CREATE TABLE IF NOT EXISTS user_packs (
id SERIAL PRIMARY KEY,
user_id BIGINT NOT NULL,
guild_id BIGINT NOT NULL,
pack_name TEXT NOT NULL,
pack_config JSONB NOT NULL,
acquired_at TIMESTAMP DEFAULT NOW()
)
''')
# Create index for faster pack queries
await conn.execute('''
CREATE INDEX IF NOT EXISTS idx_user_packs
ON user_packs(user_id, guild_id)
''')
# Battlepass rewards table - defines rewards for each level
await conn.execute('''
CREATE TABLE IF NOT EXISTS battlepass_rewards (
season INTEGER NOT NULL,
level INTEGER NOT NULL,
reward_type TEXT NOT NULL,
reward_value INTEGER NOT NULL,
PRIMARY KEY (season, level)
)
''')
# Pokemon stats table - for battle system (per individual catch)
await conn.execute('''
CREATE TABLE IF NOT EXISTS pokemon_stats (
catch_id INTEGER PRIMARY KEY,
level INTEGER DEFAULT 1,
experience INTEGER DEFAULT 0,
battles_won INTEGER DEFAULT 0,
battles_lost INTEGER DEFAULT 0
)
''')
# Pokemon species stats table - shared XP/level for all Pokemon of same species
await conn.execute('''
CREATE TABLE IF NOT EXISTS pokemon_species_stats (
user_id BIGINT NOT NULL,
guild_id BIGINT NOT NULL,
pokemon_id INTEGER NOT NULL,
pokemon_name TEXT NOT NULL,
level INTEGER DEFAULT 1,
experience INTEGER DEFAULT 0,
battles_won INTEGER DEFAULT 0,
battles_lost INTEGER DEFAULT 0,
PRIMARY KEY (user_id, guild_id, pokemon_id)
)
''')
# Battle history table
await conn.execute('''
CREATE TABLE IF NOT EXISTS battle_history (
id SERIAL PRIMARY KEY,
guild_id BIGINT NOT NULL,
winner_id BIGINT NOT NULL,
loser_id BIGINT NOT NULL,
winner_pokemon_id INTEGER NOT NULL,
loser_pokemon_id INTEGER NOT NULL,
winner_pokemon_name TEXT NOT NULL,
loser_pokemon_name TEXT NOT NULL,
turns_taken INTEGER NOT NULL,
battle_date TIMESTAMP DEFAULT NOW()
)
''')
# Create index for battle history
await conn.execute('''
CREATE INDEX IF NOT EXISTS idx_battle_history_users
ON battle_history(winner_id, loser_id, guild_id)
''')
# Daily quests table
await conn.execute('''
CREATE TABLE IF NOT EXISTS daily_quests (
user_id BIGINT NOT NULL,
guild_id BIGINT NOT NULL,
quest_date DATE NOT NULL,
quest_1_type TEXT,
quest_1_target INTEGER,
quest_1_progress INTEGER DEFAULT 0,
quest_1_completed BOOLEAN DEFAULT FALSE,
quest_1_reward INTEGER,
quest_2_type TEXT,
quest_2_target INTEGER,
quest_2_progress INTEGER DEFAULT 0,
quest_2_completed BOOLEAN DEFAULT FALSE,
quest_2_reward INTEGER,
quest_3_type TEXT,
quest_3_target INTEGER,
quest_3_progress INTEGER DEFAULT 0,
quest_3_completed BOOLEAN DEFAULT FALSE,
quest_3_reward INTEGER,
PRIMARY KEY (user_id, guild_id, quest_date)
)
''')
# Rain usage tracking table (48-hour cooldown per user)
await conn.execute('''
CREATE TABLE IF NOT EXISTS rain_usage (
user_id BIGINT NOT NULL,
guild_id BIGINT NOT NULL,
last_used_at TIMESTAMP,
PRIMARY KEY (user_id, guild_id)
)
''')
# User currency table - Pokedollars
await conn.execute('''
CREATE TABLE IF NOT EXISTS user_currency (
user_id BIGINT NOT NULL,
guild_id BIGINT NOT NULL,
balance INTEGER DEFAULT 0,
total_earned INTEGER DEFAULT 0,
total_spent INTEGER DEFAULT 0,
last_updated TIMESTAMP DEFAULT NOW(),
PRIMARY KEY (user_id, guild_id)
)
''')
# Shop items table - defines items available in shop
await conn.execute('''
CREATE TABLE IF NOT EXISTS shop_items (
id SERIAL PRIMARY KEY,
item_type TEXT NOT NULL,
item_name TEXT NOT NULL UNIQUE,
description TEXT,
price INTEGER NOT NULL,
stock_unlimited BOOLEAN DEFAULT TRUE,
is_active BOOLEAN DEFAULT TRUE,
pack_config JSONB
)
''')
# Gym badges table - tracks which gyms users have beaten
await conn.execute('''
CREATE TABLE IF NOT EXISTS gym_badges (
user_id BIGINT NOT NULL,
guild_id BIGINT NOT NULL,
gym_name TEXT NOT NULL,
earned_at TIMESTAMP DEFAULT NOW(),
PRIMARY KEY (user_id, guild_id, gym_name)
)
''')
# Trainer battle cooldowns - tracks /trainer command usage
await conn.execute('''
CREATE TABLE IF NOT EXISTS trainer_cooldowns (
user_id BIGINT NOT NULL,
guild_id BIGINT NOT NULL,
battles_used INTEGER DEFAULT 0,
cooldown_reset TIMESTAMP DEFAULT NOW(),
PRIMARY KEY (user_id, guild_id)
)
''')
# Initialize Season 1 rewards if not already present
print("Initializing Season 1 rewards...", flush=True)
await _initialize_season1_rewards(conn)
print("Season 1 rewards initialized", flush=True)
# Initialize shop items
print("Initializing shop items...", flush=True)
await _initialize_shop_items(conn)
print("Shop items initialized", flush=True)
# Migration: Add is_shiny column if it doesn't exist
print("Checking for database migrations...", flush=True)
try:
await conn.execute('''
ALTER TABLE catches
ADD COLUMN IF NOT EXISTS is_shiny BOOLEAN DEFAULT FALSE
''')
print("Migration complete: is_shiny column added", flush=True)
except Exception as e:
print(f"Migration note: {e}", flush=True)
# Migration: Update rain_usage table structure (from has_used to last_used_at)
try:
# Check if old column exists
has_old_column = await conn.fetchval('''
SELECT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_name = 'rain_usage' AND column_name = 'has_used'
)
''')
if has_old_column:
print("Migrating rain_usage table from has_used to last_used_at...", flush=True)
# Drop old column if it exists
await conn.execute('ALTER TABLE rain_usage DROP COLUMN IF EXISTS has_used')
print("Migration complete: rain_usage.has_used removed", flush=True)
# Add new column if it doesn't exist
await conn.execute('''
ALTER TABLE rain_usage
ADD COLUMN IF NOT EXISTS last_used_at TIMESTAMP
''')
print("Migration complete: rain_usage.last_used_at added", flush=True)
except Exception as e:
print(f"Migration note (rain_usage): {e}", flush=True)
print("Database tables created successfully", flush=True)
except Exception as e:
print(f"Error setting up database: {e}", flush=True)
import traceback
traceback.print_exc()
raise
async def close_database():
"""Close database connection pool"""
global pool
if pool:
await pool.close()
print("Database connection pool closed")
# Guild management functions
async def get_guild_config(guild_id: int) -> Optional[Dict]:
"""Get configuration for a guild"""
if not pool:
return None
async with pool.acquire() as conn:
row = await conn.fetchrow(
'SELECT * FROM guilds WHERE guild_id = $1',
guild_id
)
if row:
return dict(row)
return None
async def set_spawn_channel(guild_id: int, channel_id: int):
"""Set or add a spawn channel for a guild"""
if not pool:
return
async with pool.acquire() as conn:
# Check if guild exists
exists = await conn.fetchval(
'SELECT EXISTS(SELECT 1 FROM guilds WHERE guild_id = $1)',
guild_id
)
if exists:
# Add channel to existing array (if not already present)
await conn.execute('''
UPDATE guilds
SET spawn_channels = array_append(
COALESCE(spawn_channels, ARRAY[]::BIGINT[]), $2::BIGINT
),
updated_at = NOW()
WHERE guild_id = $1
AND NOT ($2::BIGINT = ANY(COALESCE(spawn_channels, ARRAY[]::BIGINT[])))
''', guild_id, channel_id)
else:
# Create new guild entry
await conn.execute('''
INSERT INTO guilds (guild_id, spawn_channels)
VALUES ($1, ARRAY[$2]::BIGINT[])
''', guild_id, channel_id)
async def remove_spawn_channel(guild_id: int, channel_id: int):
"""Remove a spawn channel from a guild"""
if not pool:
return
async with pool.acquire() as conn:
await conn.execute('''
UPDATE guilds
SET spawn_channels = array_remove(spawn_channels, $2::BIGINT),
updated_at = NOW()
WHERE guild_id = $1
''', guild_id, channel_id)
async def get_all_spawn_channels() -> Dict[int, List[int]]:
"""Get all spawn channels for all guilds"""
if not pool:
return {}
async with pool.acquire() as conn:
rows = await conn.fetch('''
SELECT guild_id, spawn_channels
FROM guilds
WHERE spawn_channels IS NOT NULL
AND array_length(spawn_channels, 1) > 0
''')
result = {}
for row in rows:
result[row['guild_id']] = list(row['spawn_channels'])
return result
# Pokemon catch functions
async def add_catch(user_id: int, guild_id: int, pokemon_name: str,
pokemon_id: int, pokemon_types: List[str], is_shiny: bool = False):
"""Record a Pokemon catch"""
if not pool:
return
async with pool.acquire() as conn:
await conn.execute('''
INSERT INTO catches (user_id, guild_id, pokemon_name, pokemon_id, pokemon_types, is_shiny)
VALUES ($1, $2, $3, $4, $5, $6)
''', user_id, guild_id, pokemon_name, pokemon_id, pokemon_types, is_shiny)
async def get_user_catches(user_id: int, guild_id: int) -> List[Dict]:
"""Get all catches for a user in a specific guild"""
if not pool:
return []
async with pool.acquire() as conn:
rows = await conn.fetch('''
SELECT pokemon_name, pokemon_id, pokemon_types, caught_at
FROM catches
WHERE user_id = $1 AND guild_id = $2
ORDER BY caught_at DESC
''', user_id, guild_id)
return [dict(row) for row in rows]
async def get_user_catch_counts(user_id: int, guild_id: int) -> Dict[str, int]:
"""Get count of each Pokemon caught by a user"""
if not pool:
return {}
async with pool.acquire() as conn:
rows = await conn.fetch('''
SELECT pokemon_name, COUNT(*) as count
FROM catches
WHERE user_id = $1 AND guild_id = $2
GROUP BY pokemon_name
ORDER BY count DESC
''', user_id, guild_id)
return {row['pokemon_name']: row['count'] for row in rows}
async def get_pokemon_with_counts(user_id: int, guild_id: int, sort_by: str = 'most_caught') -> List[Dict]:
"""Get Pokemon with counts, sorted by various criteria"""
if not pool:
return []
async with pool.acquire() as conn:
# Base query
base_query = '''
SELECT
pokemon_name,
pokemon_id,
COUNT(*) as count,
MAX(caught_at) as last_caught
FROM catches
WHERE user_id = $1 AND guild_id = $2
GROUP BY pokemon_name, pokemon_id
'''
# Add sorting
if sort_by == 'most_caught':
order_by = 'ORDER BY count DESC, pokemon_name ASC'
elif sort_by == 'alphabetical':
order_by = 'ORDER BY pokemon_name ASC'
elif sort_by == 'pokedex_number':
order_by = 'ORDER BY pokemon_id ASC'
elif sort_by == 'rarest':
order_by = 'ORDER BY count ASC, pokemon_name ASC'
elif sort_by == 'recently_caught':
order_by = 'ORDER BY last_caught DESC'
else:
order_by = 'ORDER BY count DESC, pokemon_name ASC'
query = f'{base_query} {order_by}'
rows = await conn.fetch(query, user_id, guild_id)
return [dict(row) for row in rows]
async def get_legendary_pokemon(user_id: int, guild_id: int) -> List[Dict]:
"""Get only legendary Pokemon from Gen 1, 2, and 3"""
if not pool:
return []
# Gen 1: Articuno (144), Zapdos (145), Moltres (146), Mewtwo (150), Mew (151)
# Gen 2: Raikou (243), Entei (244), Suicune (245), Lugia (249), Ho-Oh (250), Celebi (251)
# Gen 3: Regirock (377), Regice (378), Registeel (379), Latias (380), Latios (381), Kyogre (382), Groudon (383), Rayquaza (384), Jirachi (385), Deoxys (386)
legendary_ids = [144, 145, 146, 150, 151, 243, 244, 245, 249, 250, 251, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386]
async with pool.acquire() as conn:
rows = await conn.fetch('''
SELECT
pokemon_name,
pokemon_id,
COUNT(*) as count,
MAX(caught_at) as last_caught
FROM catches
WHERE user_id = $1 AND guild_id = $2 AND pokemon_id = ANY($3)
GROUP BY pokemon_name, pokemon_id
ORDER BY pokemon_id ASC
''', user_id, guild_id, legendary_ids)
return [dict(row) for row in rows]
async def get_shiny_pokemon(user_id: int, guild_id: int) -> List[Dict]:
"""Get only shiny Pokemon"""
if not pool:
return []
async with pool.acquire() as conn:
rows = await conn.fetch('''
SELECT
pokemon_name,
pokemon_id,
COUNT(*) as count,
MAX(caught_at) as last_caught
FROM catches
WHERE user_id = $1 AND guild_id = $2 AND is_shiny = TRUE
GROUP BY pokemon_name, pokemon_id
ORDER BY pokemon_id ASC
''', user_id, guild_id)
return [dict(row) for row in rows]
# Leaderboard functions
async def get_leaderboard_most_caught(guild_id: int, limit: int = 10) -> List[Dict]:
"""Get leaderboard by total Pokemon caught"""
if not pool:
return []
async with pool.acquire() as conn:
rows = await conn.fetch('''
SELECT
user_id,
COUNT(*) as total_caught
FROM catches
WHERE guild_id = $1
GROUP BY user_id
ORDER BY total_caught DESC
LIMIT $2
''', guild_id, limit)
return [dict(row) for row in rows]
async def get_leaderboard_unique(guild_id: int, limit: int = 10) -> List[Dict]:
"""Get leaderboard by unique Pokemon caught"""
if not pool:
return []
async with pool.acquire() as conn:
rows = await conn.fetch('''
SELECT
user_id,
COUNT(DISTINCT pokemon_name) as unique_pokemon
FROM catches
WHERE guild_id = $1
GROUP BY user_id
ORDER BY unique_pokemon DESC
LIMIT $2
''', guild_id, limit)
return [dict(row) for row in rows]
async def get_leaderboard_legendaries(guild_id: int, limit: int = 10) -> List[Dict]:
"""Get leaderboard by legendary Pokemon caught"""
if not pool:
return []
# All legendaries from Gen 1, 2, and 3
legendary_ids = [144, 145, 146, 150, 151, 243, 244, 245, 249, 250, 251, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386]
async with pool.acquire() as conn:
rows = await conn.fetch('''
SELECT
user_id,
COUNT(*) as legendary_count
FROM catches
WHERE guild_id = $1 AND pokemon_id = ANY($2)
GROUP BY user_id
ORDER BY legendary_count DESC
LIMIT $3
''', guild_id, legendary_ids, limit)
return [dict(row) for row in rows]
async def get_leaderboard_shinies(guild_id: int, limit: int = 10) -> List[Dict]:
"""Get leaderboard by shiny Pokemon caught"""
if not pool:
return []
async with pool.acquire() as conn:
rows = await conn.fetch('''
SELECT
user_id,
COUNT(*) as shiny_count
FROM catches
WHERE guild_id = $1 AND is_shiny = TRUE
GROUP BY user_id
ORDER BY shiny_count DESC
LIMIT $2
''', guild_id, limit)
return [dict(row) for row in rows]
async def get_leaderboard_collection_value(guild_id: int, limit: int = 10) -> List[Dict]:
"""Get leaderboard by total collection value (based on sell prices)"""
if not pool:
return []
async with pool.acquire() as conn:
rows = await conn.fetch('''
SELECT
user_id,
SUM(
CASE
WHEN pokemon_id IN (144, 145, 146, 150, 151) THEN 100
WHEN pokemon_id IN (3, 6, 9, 59, 65, 68, 76, 94, 103, 112, 115, 130, 131, 142, 143) THEN 50
WHEN pokemon_id IN (1, 2, 3, 4, 5, 6, 7, 8, 9) THEN 30
ELSE 10
END
) as collection_value
FROM catches
WHERE guild_id = $1
GROUP BY user_id
ORDER BY collection_value DESC
LIMIT $2
''', guild_id, limit)
return [dict(row) for row in rows]
async def get_rarest_pokemon_in_server(guild_id: int) -> Optional[Dict]:
"""Get the rarest Pokemon in the server (least caught overall)"""
if not pool:
return None
async with pool.acquire() as conn:
# Find Pokemon with the lowest catch count across all users
row = await conn.fetchrow('''
WITH pokemon_counts AS (
SELECT
pokemon_name,
pokemon_id,
COUNT(*) as total_caught,
COUNT(DISTINCT user_id) as unique_owners
FROM catches
WHERE guild_id = $1
GROUP BY pokemon_name, pokemon_id
)
SELECT * FROM pokemon_counts
ORDER BY total_caught ASC, unique_owners ASC
LIMIT 1
''', guild_id)
return dict(row) if row else None
async def get_user_with_rarest(guild_id: int) -> Optional[Dict]:
"""Get user who owns the rarest Pokemon in the server"""
if not pool:
return None
rarest = await get_rarest_pokemon_in_server(guild_id)
if not rarest:
return None
async with pool.acquire() as conn:
# Find first user who caught this rarest Pokemon
row = await conn.fetchrow('''
SELECT user_id, caught_at
FROM catches
WHERE guild_id = $1 AND pokemon_name = $2
ORDER BY caught_at ASC
LIMIT 1
''', guild_id, rarest['pokemon_name'])
if row:
return {
'user_id': row['user_id'],
'pokemon_name': rarest['pokemon_name'],
'pokemon_id': rarest['pokemon_id'],
'total_caught': rarest['total_caught'],
'unique_owners': rarest['unique_owners'],
'caught_at': row['caught_at']
}
return None
async def get_user_stats(user_id: int, guild_id: int) -> Dict:
"""Get catch statistics for a user"""
if not pool:
return {'total': 0, 'unique': 0}
async with pool.acquire() as conn:
stats = await conn.fetchrow('''
SELECT
COUNT(*) as total,
COUNT(DISTINCT pokemon_name) as unique
FROM catches
WHERE user_id = $1 AND guild_id = $2
''', user_id, guild_id)
return dict(stats) if stats else {'total': 0, 'unique': 0}
# Trading functions
async def get_user_pokemon_for_trade(user_id: int, guild_id: int) -> List[Dict]:
"""Get user's Pokemon with individual catch IDs for trading/battles"""
if not pool:
return []
async with pool.acquire() as conn:
rows = await conn.fetch('''
SELECT id, pokemon_name, pokemon_id, caught_at, is_shiny
FROM catches
WHERE user_id = $1 AND guild_id = $2
ORDER BY pokemon_name ASC, caught_at DESC
''', user_id, guild_id)
return [dict(row) for row in rows]
async def execute_trade(catch_id1: int, catch_id2: int, user_id1: int, user_id2: int, guild_id: int) -> bool:
"""Execute a trade by swapping ownership of two Pokemon"""
if not pool:
return False
async with pool.acquire() as conn:
# Start a transaction
async with conn.transaction():
# Verify both catches exist and belong to the right users
catch1 = await conn.fetchrow('''
SELECT user_id, guild_id FROM catches WHERE id = $1
''', catch_id1)
catch2 = await conn.fetchrow('''
SELECT user_id, guild_id FROM catches WHERE id = $1
''', catch_id2)
# Validate the trade
if not catch1 or not catch2:
return False
if catch1['user_id'] != user_id1 or catch1['guild_id'] != guild_id:
return False
if catch2['user_id'] != user_id2 or catch2['guild_id'] != guild_id:
return False
# Execute the swap
await conn.execute('''
UPDATE catches SET user_id = $2 WHERE id = $1
''', catch_id1, user_id2)
await conn.execute('''
UPDATE catches SET user_id = $2 WHERE id = $1
''', catch_id2, user_id1)
return True
# Battle system functions
async def get_pokemon_level(catch_id: int) -> int:
"""Get the level of a specific caught Pokemon"""
if not pool:
return 1
async with pool.acquire() as conn:
level = await conn.fetchval('''
SELECT level FROM pokemon_stats WHERE catch_id = $1
''', catch_id)
return level if level else 1
async def record_battle(guild_id: int, winner_id: int, loser_id: int,
winner_pokemon_id: int, loser_pokemon_id: int,
winner_pokemon_name: str, loser_pokemon_name: str,
turns_taken: int):
"""Record a battle result"""
if not pool:
return
async with pool.acquire() as conn:
# Record battle history
await conn.execute('''
INSERT INTO battle_history
(guild_id, winner_id, loser_id, winner_pokemon_id, loser_pokemon_id,
winner_pokemon_name, loser_pokemon_name, turns_taken)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
''', guild_id, winner_id, loser_id, winner_pokemon_id, loser_pokemon_id,
winner_pokemon_name, loser_pokemon_name, turns_taken)
# Update winner's Pokemon stats
await conn.execute('''
INSERT INTO pokemon_stats (catch_id, battles_won)
VALUES ($1, 1)
ON CONFLICT (catch_id)
DO UPDATE SET battles_won = pokemon_stats.battles_won + 1
''', winner_pokemon_id)
# Update loser's Pokemon stats
await conn.execute('''
INSERT INTO pokemon_stats (catch_id, battles_lost)
VALUES ($1, 1)
ON CONFLICT (catch_id)
DO UPDATE SET battles_lost = pokemon_stats.battles_lost + 1
''', loser_pokemon_id)
async def get_battle_stats(user_id: int, guild_id: int) -> Dict:
"""Get battle statistics for a user"""
if not pool:
return {'wins': 0, 'losses': 0}
async with pool.acquire() as conn:
wins = await conn.fetchval('''
SELECT COUNT(*) FROM battle_history
WHERE winner_id = $1 AND guild_id = $2
''', user_id, guild_id)
losses = await conn.fetchval('''
SELECT COUNT(*) FROM battle_history
WHERE loser_id = $1 AND guild_id = $2
''', user_id, guild_id)
return {'wins': wins or 0, 'losses': losses or 0}
async def get_species_level(user_id: int, guild_id: int, pokemon_id: int, pokemon_name: str) -> int:
"""Get the level of a Pokemon species for a user"""
if not pool:
return 1
async with pool.acquire() as conn:
level = await conn.fetchval('''
SELECT level FROM pokemon_species_stats
WHERE user_id = $1 AND guild_id = $2 AND pokemon_id = $3
''', user_id, guild_id, pokemon_id)
return level if level else 1
async def get_multiple_species_levels(user_id: int, guild_id: int, pokemon_ids: list) -> dict:
"""Get levels for multiple Pokemon species at once. Returns dict of {pokemon_id: level}"""
if not pool or not pokemon_ids:
return {pid: 1 for pid in pokemon_ids}
async with pool.acquire() as conn:
rows = await conn.fetch('''
SELECT pokemon_id, level FROM pokemon_species_stats
WHERE user_id = $1 AND guild_id = $2 AND pokemon_id = ANY($3)
''', user_id, guild_id, pokemon_ids)
# Create dict with levels, defaulting to 1 if not found
level_dict = {pid: 1 for pid in pokemon_ids}
for row in rows:
level_dict[row['pokemon_id']] = row['level']
return level_dict
async def add_species_xp(user_id: int, guild_id: int, pokemon_id: int, pokemon_name: str, xp_amount: int, is_win: bool = True) -> Dict:
"""Add XP to a Pokemon species and handle level ups"""
if not pool:
return None
async with pool.acquire() as conn:
# Get or create species entry
species = await conn.fetchrow('''
INSERT INTO pokemon_species_stats (user_id, guild_id, pokemon_id, pokemon_name, experience, level)
VALUES ($1, $2, $3, $4, $5, 1)
ON CONFLICT (user_id, guild_id, pokemon_id)
DO UPDATE SET experience = pokemon_species_stats.experience + $5
RETURNING *
''', user_id, guild_id, pokemon_id, pokemon_name, xp_amount)
# Update win/loss count
if is_win:
await conn.execute('''
UPDATE pokemon_species_stats
SET battles_won = battles_won + 1
WHERE user_id = $1 AND guild_id = $2 AND pokemon_id = $3
''', user_id, guild_id, pokemon_id)
else:
await conn.execute('''
UPDATE pokemon_species_stats
SET battles_lost = battles_lost + 1
WHERE user_id = $1 AND guild_id = $2 AND pokemon_id = $3
''', user_id, guild_id, pokemon_id)
# Calculate new level (100 XP per level, no cap)
new_level = (species['experience'] // 100) + 1
old_level = species['level']
# Update level if it changed
if new_level != old_level:
await conn.execute('''
UPDATE pokemon_species_stats
SET level = $1
WHERE user_id = $2 AND guild_id = $3 AND pokemon_id = $4
''', new_level, user_id, guild_id, pokemon_id)
return {
'leveled_up': True,
'old_level': old_level,
'new_level': new_level,
'current_xp': species['experience'],
'pokemon_name': pokemon_name
}
return {
'leveled_up': False,
'level': new_level,
'current_xp': species['experience'],
'pokemon_name': pokemon_name
}
# Battlepass functions (LEGACY - kept for historical data, no longer actively used)
async def _initialize_season1_rewards(conn):
"""Initialize Season 1 battlepass rewards"""
# Define Season 1 rewards - packs at levels 5, 10, 15, 20, 25, 30, 35, 40, 45, 50
season1_rewards = [
(1, 5, 'pack', 1),
(1, 10, 'pack', 2),
(1, 15, 'pack', 1),
(1, 20, 'pack', 3),
(1, 25, 'pack', 2),
(1, 30, 'pack', 3),
(1, 35, 'pack', 2),
(1, 40, 'pack', 4),
(1, 45, 'pack', 3),
(1, 50, 'pack', 5),
]
for season, level, reward_type, reward_value in season1_rewards:
await conn.execute('''
INSERT INTO battlepass_rewards (season, level, reward_type, reward_value)
VALUES ($1, $2, $3, $4)
ON CONFLICT (season, level) DO NOTHING
''', season, level, reward_type, reward_value)
async def _initialize_shop_items(conn):
"""Initialize shop items with pack configurations"""
import json
# Define shop items with pack configurations
shop_items = [
('pack', 'Basic Pack', 'Standard pack with a few random Pokemon', 100, {
'min_pokemon': 3,
'max_pokemon': 5,
'shiny_chance': 0.0001, # 0.01%
'legendary_chance': 0.05, # 5%
'mega_pack_chance': 0,
'mega_pack_size': 0
}),
('pack', 'Booster Pack', 'Enhanced pack with better odds and more Pokemon!', 250, {
'min_pokemon': 5,
'max_pokemon': 8,
'shiny_chance': 0.0005, # 0.05%
'legendary_chance': 0.10, # 10%
'mega_pack_chance': 0.15, # 15%
'mega_pack_size': 12
}),
('pack', 'Premium Pack', 'Premium pack with guaranteed rare Pokemon and excellent shiny odds!', 500, {
'min_pokemon': 8,
'max_pokemon': 12,
'shiny_chance': 0.001, # 0.1%
'legendary_chance': 0.20, # 20%
'mega_pack_chance': 0.25, # 25%
'mega_pack_size': 15,
'guaranteed_rare': True
}),
('pack', 'Elite Trainer Pack', 'Elite pack for serious trainers! Multiple guaranteed rares with amazing shiny rates!', 1000, {
'min_pokemon': 12,
'max_pokemon': 18,
'shiny_chance': 0.005, # 0.5%
'legendary_chance': 0.40, # 40%
'mega_pack_chance': 0.35, # 35%
'mega_pack_size': 20,
'guaranteed_rare': True,
'guaranteed_rare_count': 3
}),
('pack', 'Master Collection', 'Ultimate pack! Guaranteed shiny or multiple legendaries with the best odds!', 2500, {
'min_pokemon': 20,
'max_pokemon': 25,
'shiny_chance': 0.01, # 1%
'legendary_chance': 0.60, # 60%
'mega_pack_chance': 0.50, # 50%
'mega_pack_size': 30,
'guaranteed_shiny_or_legendaries': True,
'guaranteed_legendary_count': 3
}),
]
for item_type, item_name, description, price, pack_config in shop_items: