aurudubot / server /db.js
Alexainc
fix syntax error in olinda bot logic
451a23a
Raw
History Blame Contribute Delete
3.36 kB
const mongoose = require('mongoose');
const { User, Village } = require('./models');
require('dotenv').config();
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/aurudu_krida';
if (!process.env.MONGODB_URI) {
console.warn('โš ๏ธ WARNING: MONGODB_URI is not set. Defaulting to local instance.');
}
mongoose.connect(MONGODB_URI, {
serverSelectionTimeoutMS: 5000,
socketTimeoutMS: 45000,
})
.then(async () => {
console.log('Connected to MongoDB ๐ŸŒฟ');
// Drop problematic old indexes if they exist
try {
await User.collection.dropIndex('tgId_1');
console.log('Dropped old User tgId index');
} catch (e) { }
try {
await Village.collection.dropIndex('villageId_1');
console.log('Dropped old Village villageId index');
} catch (e) { }
})
.catch(err => {
console.error('โŒ MongoDB connection error:', err.message);
});
async function recordWin(gameType, winnerTgId, villageId, winnerName, villageName, isVillageBattle = false) {
if (!winnerTgId) return;
try {
// 1. Update User Stats
let user = await User.findById(winnerTgId);
if (!user) {
user = new User({ _id: winnerTgId, name: winnerName });
}
user.name = winnerName; // Update name in case it changed
user.totalWins += 1;
if (user.gameStats[gameType] !== undefined) {
user.gameStats[gameType] += 1;
}
user.lastVillageId = villageId;
user.lastVillageName = villageName;
user.lastSeen = new Date();
await user.save();
// 2. Update Village Stats
if (villageId && villageId !== 'Global') {
let village = await Village.findById(villageId);
if (!village) {
village = new Village({ _id: villageId, name: villageName });
}
village.points += isVillageBattle ? 20 : 10; // 2x points for battle
village.lastActive = new Date();
await village.save();
}
console.log(`๐Ÿ† Recorded win for ${winnerName} in ${gameType} (${villageName})`);
} catch (error) {
console.error('Error recording win:', error);
}
}
async function getVillageLeaderboard() {
return await Village.find().sort({ points: -1 }).limit(10);
}
async function getGameLeaderboard(gameType, villageId = null) {
const query = {};
if (villageId && villageId !== 'Global' && villageId !== 'Global Village') {
query.lastVillageId = villageId;
}
if (gameType && gameType !== 'global') {
query[`gameStats.${gameType}`] = { $gt: 0 };
return await User.find(query)
.sort({ [`gameStats.${gameType}`]: -1 })
.limit(10);
}
return await User.find(query).sort({ totalWins: -1 }).limit(10);
}
async function getUserProfile(tgId) {
if (!tgId) return null;
return await User.findById(tgId);
}
async function getVillagePlayers(villageId) {
if (!villageId || villageId === 'Global' || villageId === 'Global Village') return [];
return await User.find({ lastVillageId: villageId }).sort({ totalWins: -1 }).limit(10);
}
module.exports = {
recordWin,
getVillageLeaderboard,
getGameLeaderboard,
getVillagePlayers,
getUserProfile
};