generate a better oc member list, and fetch it better too

This commit is contained in:
2026-01-12 20:56:49 -05:00
parent ee6dbc1df2
commit 05d34af924
6 changed files with 299 additions and 64 deletions

View File

@@ -29,25 +29,59 @@ module.exports = {
}
}
let members = [];
// Fetch own faction members
try {
// Fetch own faction members
members = await torn.faction.members();
} catch (e) {
console.error("inactive: Failed to fetch members", e);
return interaction.editReply('Failed to fetch faction members from API.');
}
// Fetch currently active/planned/recruiting crimes to check for current participation
const activeUserIds = new Set();
try {
const categories = ['recruiting', 'planned', 'active'];
const promises = categories.map(cat => torn.faction.crimes({ category: cat, limit: 100 })); // limit 100 to catch most
const results = await Promise.all(promises);
results.forEach(crimes => {
if (crimes && Array.isArray(crimes)) {
crimes.forEach(crime => {
// Only consider truly active/pending statuses
const completedStatuses = ['Successful', 'Failure', 'Canceled', 'Expired', 'Timeout'];
if (completedStatuses.includes(crime.status)) {
return;
}
if (crime.slots && Array.isArray(crime.slots)) {
crime.slots.forEach(slot => {
if (slot.user && slot.user.id) {
activeUserIds.add(slot.user.id);
}
});
}
});
}
});
console.log(`inactive: Found ${activeUserIds.size} users currently in crimes.`);
} catch (e) {
console.error("inactive: Failed to fetch current crimes", e);
}
const inactiveUsers = [];
// Check each member
for (const member of members) {
const userId = member.id;
// Skip if user is currently in a crime
if (activeUserIds.has(userId)) continue;
const userName = member.name;
const userStat = stats[userId];
if (!userStat) {
// Never seen in tracking
if (!userStat || !userStat.lastSeen) {
// Never seen in tracking or no lastSeen data
inactiveUsers.push({
id: userId,
name: userName,
@@ -60,6 +94,7 @@ module.exports = {
id: userId,
name: userName,
lastSeen: new Date(userStat.lastSeen),
lastCrimeId: userStat.lastCrimeId,
daysInactive: Math.floor((Date.now() - userStat.lastSeen) / (24 * 60 * 60 * 1000))
});
}
@@ -92,7 +127,14 @@ module.exports = {
value = "Never seen in OCs (since tracking started)";
} else {
const ts = Math.floor(user.lastSeen.getTime() / 1000);
value = `Last crime: <t:${ts}:d>\n(<t:${ts}:R>)`;
let dateStr = `<t:${ts}:d>`;
if (user.lastCrimeId) {
const url = `https://www.torn.com/factions.php?step=your&type=1#/tab=crimes&crimeId=${user.lastCrimeId}`;
dateStr = `[Last crime](${url}): <t:${ts}:d>`;
} else {
dateStr = `Last crime: <t:${ts}:d>`;
}
value = `${dateStr}\n(<t:${ts}:R>)`;
}
embed.addFields({

View File

@@ -1,7 +1,7 @@
const { SlashCommandBuilder } = require('discord.js');
const fs = require('fs');
const path = require('path');
const { getMemberMap, processCrimes } = require('../../utils/ocLogic');
const { fetchAndProcessHistory } = require('../../utils/ocLogic');
const torn = require('../../torn.js');
module.exports = {
@@ -18,68 +18,21 @@ module.exports = {
await interaction.deferReply();
const days = interaction.options.getInteger('days') || 30;
const now = Date.now();
const fromTimestamp = Math.floor((now - (days * 24 * 60 * 60 * 1000)) / 1000);
const statsPath = path.join(__dirname, '../../data/ocStats.json');
// Load existing stats
let stats = {};
if (fs.existsSync(statsPath)) {
try {
stats = JSON.parse(fs.readFileSync(statsPath, 'utf8'));
} catch (e) {
console.error("scanOC: Failed to load ocStats.json", e);
}
}
// Fetch faction members
const memberMap = await getMemberMap(torn);
await interaction.editReply(`Scanning OCs from the last ${days} days...`);
let crimesList = [];
const categories = ['recruiting', 'planned', 'active', 'successful', 'failed'];
try {
const updates = await fetchAndProcessHistory(torn, statsPath, days);
for (const cat of categories) {
try {
// Fetch with a higher limit since we are scanning back further
const crimes = await torn.faction.crimes({
from: fromTimestamp,
sort: 'ASC',
category: cat,
limit: 300 // Reasonable batch size?
});
if (crimes && Array.isArray(crimes)) {
crimesList = crimesList.concat(crimes);
}
} catch (e) {
console.error(`scanOC: Failed to fetch crimes for category '${cat}'`, e);
if (updates > 0) {
await interaction.editReply(`Scan complete. Updated stats for ${updates} users.`);
} else {
await interaction.editReply(`Scan complete. No new updates needed.`);
}
}
if (crimesList.length === 0) {
return interaction.editReply(`Scan complete. No OCs found in the last ${days} days.`);
}
// Process with utility
const updates = await processCrimes(crimesList, stats, memberMap, torn);
// Save
if (updates > 0) {
try {
const dir = path.dirname(statsPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
fs.writeFileSync(statsPath, JSON.stringify(stats, null, 4));
await interaction.editReply(`Scan complete. Processed ${crimesList.length} crimes. Updated stats for ${updates} users.`);
} catch (e) {
console.error("scanOC: Failed to save stats", e);
await interaction.editReply(`Scan complete, but failed to save stats: ${e.message}`);
}
} else {
await interaction.editReply(`Scan complete. Processed ${crimesList.length} crimes. No new updates needed.`);
} catch (e) {
console.error("scanOC: Failed to scan history", e);
await interaction.editReply(`Scan failed: ${e.message}`);
}
},
};