import motor.motor_asyncio import os import json import logging from datetime import datetime logger = logging.getLogger(__name__) class DatabaseManager: def __init__(self, uri=None): # Fallback for local testing if MONGO_URI is not set self.uri = uri or os.getenv('MONGO_URI') if not self.uri: logger.warning("⚠️ MONGO_URI is not set in environment. Falling back to local JSON mode.") self.client = None self.db = None else: self.client = motor.motor_asyncio.AsyncIOMotorClient(self.uri) self.db = self.client['bytebet_db'] logger.info("✅ Connected to MongoDB Atlas.") # --- Migration Logic --- async def migrate_from_json(self): if not self.db: return json_files = { 'user_balances.json': self.db.balances, 'slaves.json': self.db.slaves, 'delayed_transfers.json': self.db.transfers, 'work_cooldowns.json': self.db.cooldowns, 'user_inventory.json': self.db.inventory, 'lottery_data.json': self.db.lottery, 'stock_market_data.json': self.db.stocks } for filename, collection in json_files.items(): if os.path.exists(filename): try: with open(filename, 'r') as file: data = json.load(file) # Check if already migrated count = await collection.count_documents({}) if count > 0: logger.info(f"⏩ {filename} already migrated.") continue logger.info(f"📦 Migrating {filename} to MongoDB...") if filename == 'user_balances.json': docs = [] for guild_id, users in data.items(): for user_id, bal in users.items(): docs.append({'guild_id': guild_id, 'user_id': user_id, 'wallet': bal['wallet'], 'bank': bal['bank']}) if docs: await collection.insert_many(docs) elif filename == 'slaves.json': docs = [] for guild_id, slaves in data.items(): for slave_id, info in slaves.items(): docs.append({'guild_id': guild_id, 'slave_id': slave_id, **info}) if docs: await collection.insert_many(docs) elif filename == 'delayed_transfers.json': if data: await collection.insert_many(data) elif filename == 'work_cooldowns.json': docs = [] for guild_id, users in data.items(): for user_id, ts in users.items(): docs.append({'guild_id': guild_id, 'user_id': user_id, 'type': 'work', 'expires_at': ts}) if docs: await collection.insert_many(docs) elif filename == 'user_inventory.json': docs = [] for guild_id, users in data.items(): for user_id, items in users.items(): docs.append({'guild_id': guild_id, 'user_id': user_id, 'items': items}) if docs: await collection.insert_many(docs) elif filename == 'lottery_data.json': # Lottery data is usually global or per-guild, adding guild_id as 'global' data['guild_id'] = 'global' await collection.insert_one(data) elif filename == 'stock_market_data.json': docs = [] for symbol, info in data.items(): docs.append({'symbol': symbol, **info}) if docs: await collection.insert_many(docs) logger.info(f"✅ Migrated {filename} successfully.") # Optionally rename the file to avoid re-migration # os.rename(filename, f"{filename}.bak") except Exception as e: logger.error(f"❌ Error migrating {filename}: {e}") # --- Balance Ops --- async def get_balance(self, guild_id, user_id): if not self.db: return None # Use local fallback if needed doc = await self.db.balances.find_one({'guild_id': str(guild_id), 'user_id': str(user_id)}) return doc or {'guild_id': str(guild_id), 'user_id': str(user_id), 'wallet': 500, 'bank': 0} async def update_balance(self, guild_id, user_id, wallet, bank): if not self.db: return await self.db.balances.update_one( {'guild_id': str(guild_id), 'user_id': str(user_id)}, {'$set': {'wallet': wallet, 'bank': bank}}, upsert=True ) async def get_server_balances(self, guild_id): if not self.db: return {} cursor = self.db.balances.find({'guild_id': str(guild_id)}) balances = {} async for doc in cursor: balances[doc['user_id']] = {'wallet': doc['wallet'], 'bank': doc['bank']} return balances # --- Cooldown Ops --- async def get_cooldown(self, guild_id, user_id, cooldown_type): if not self.db: return None doc = await self.db.cooldowns.find_one({'guild_id': str(guild_id), 'user_id': str(user_id), 'type': cooldown_type}) return doc['expires_at'] if doc else None async def set_cooldown(self, guild_id, user_id, cooldown_type, expires_at): if not self.db: return await self.db.cooldowns.update_one( {'guild_id': str(guild_id), 'user_id': str(user_id), 'type': cooldown_type}, {'$set': {'expires_at': expires_at}}, upsert=True ) # --- Slavery Ops --- async def get_slave_data(self, guild_id): if not self.db: return {} cursor = self.db.slaves.find({'guild_id': str(guild_id)}) slaves = {} async for doc in cursor: sid = doc['slave_id'] data = doc.copy() del data['_id'], data['slave_id'], data['guild_id'] slaves[sid] = data return slaves async def update_slave(self, guild_id, slave_id, data): if not self.db: return await self.db.slaves.update_one( {'guild_id': str(guild_id), 'slave_id': str(slave_id)}, {'$set': data}, upsert=True ) async def remove_slave(self, guild_id, slave_id): if not self.db: return await self.db.slaves.delete_one({'guild_id': str(guild_id), 'slave_id': str(slave_id)}) # --- Stock Ops --- async def get_stocks(self): if not self.db: return {} cursor = self.db.stocks.find({}) stocks = {} async for doc in cursor: symbol = doc['symbol'] data = doc.copy() del data['_id'], data['symbol'] stocks[symbol] = data return stocks async def update_stock(self, symbol, data): if not self.db: return await self.db.stocks.update_one( {'symbol': symbol}, {'$set': data}, upsert=True ) # --- Lottery Ops --- async def get_lottery(self): if not self.db: return None return await self.db.lottery.find_one({'guild_id': 'global'}) async def update_lottery(self, data): if not self.db: return await self.db.lottery.update_one( {'guild_id': 'global'}, {'$set': data}, upsert=True ) # --- Inventory Ops --- async def get_inventory(self, guild_id, user_id): if not self.db: return {} doc = await self.db.inventory.find_one({'guild_id': str(guild_id), 'user_id': str(user_id)}) return doc['items'] if doc else {} async def update_inventory(self, guild_id, user_id, items): if not self.db: return await self.db.inventory.update_one( {'guild_id': str(guild_id), 'user_id': str(user_id)}, {'$set': {'items': items}}, upsert=True ) # --- Portfolio Ops --- async def get_portfolio(self, guild_id, user_id): if not self.db: return {} doc = await self.db.portfolios.find_one({'guild_id': str(guild_id), 'user_id': str(user_id)}) return doc['stocks'] if doc else {} async def update_portfolio(self, guild_id, user_id, stocks): if not self.db: return await self.db.portfolios.update_one( {'guild_id': str(guild_id), 'user_id': str(user_id)}, {'$set': {'stocks': stocks}}, upsert=True )