converted ShaiBot casino to Nut Economy

This commit is contained in:
2026-08-19 14:10:38 +02:00
parent a126de21d4
commit 1957991182
55 changed files with 8905 additions and 751 deletions
+168 -30
View File
@@ -60,83 +60,199 @@ async function selectMenuHandler(interaction) {
}
}
function getParticipantWeight(participant, now = Date.now()) {
// Never selected before -> strongly favor them
if (!participant.lastExpertAt) {
return 6;
}
const lastExpertAt = new Date(participant.lastExpertAt).getTime();
// Invalid date safety
if (Number.isNaN(lastExpertAt)) {
return 6;
}
const daysSinceExpert = Math.max(
0,
(now - lastExpertAt) / (24 * 60 * 60 * 1000)
);
/*
* Square-root weighting prevents very old participants
* from completely dominating the random selection.
*
* Examples:
* 1 day -> ~1.41
* 7 days -> ~2.83
* 30 days -> ~5.57
*/
return Math.sqrt(daysSinceExpert + 1);
}
function weightedRandom(participants) {
if (!participants.length) {
return null;
}
const weightedParticipants = participants.map(participant => ({
participant,
weight: getParticipantWeight(participant)
}));
const totalWeight = weightedParticipants.reduce(
(total, item) => total + item.weight,
0
);
let random = Math.random() * totalWeight;
for (const item of weightedParticipants) {
random -= item.weight;
if (random <= 0) {
return item.participant;
}
}
// Floating-point safety fallback
return weightedParticipants[weightedParticipants.length - 1].participant;
}
async function selectWgeParticipant(
participateColl,
{ excludeUserId = null } = {}
) {
const filter = {
status: true
};
if (excludeUserId) {
filter.userID = {
$ne: excludeUserId
};
}
const participants = await participateColl
.find(filter)
.toArray();
return weightedRandom(participants);
}
async function modalSubmitHandler(interaction) {
if (interaction.customId !== 'wgeBaseModal') return;
if (interaction.customId !== 'wgeBaseModal') {
return;
}
const db = mClient.db('neo-db');
const wgeColl = db.collection('timer_wge');
const participateColl = db.collection('items_wge');
const historyWgeColl = db.collection('history_wge');
const assigningUser = interaction.user;
const selectedUserId = interaction.components[0].component.values[0];
const topic = interaction.fields.getTextInputValue('wgeTopicInput');
const defaultAssignedTime = 7 * 24 * 60 * 60 * 1000; // 7 days
// Get current running WGE so we can exclude the current expert
const selectedUserId =
interaction.components[0].component.values[0];
const topic = interaction.fields.getTextInputValue(
'wgeTopicInput'
);
const defaultAssignedTime =
7 * 24 * 60 * 60 * 1000;
// Get current running WGE so the previous expert
// cannot immediately be selected again.
const prevWge = await wgeColl.findOne({
debug: false,
state: 'running'
});
let assignedUser;
let selectedParticipant;
// Random assignment
// ---------------------------------
// RANDOM / WEIGHTED ASSIGNMENT
// ---------------------------------
if (selectedUserId === process.env.D_ID) {
const randomParticipant = await participateColl.aggregate([
selectedParticipant = await selectWgeParticipant(
participateColl,
{
$match: {
status: true,
...(prevWge && {
userID: { $ne: prevWge.assignedUser }
})
}
},
{ $sample: { size: 1 } }
]).toArray();
excludeUserId: prevWge?.assignedUser
}
);
if (randomParticipant.length === 0) {
if (!selectedParticipant) {
return interaction.reply({
content: 'There are no eligible participants available.',
content:
'There are no eligible participants available.',
flags: MessageFlags.Ephemeral
});
}
const member = await interaction.guild.members
.fetch(selectedParticipant.userID)
.catch(() => null);
if (!member) {
return interaction.reply({
content:
'The selected participant could not be found in the server.',
flags: MessageFlags.Ephemeral
});
}
const member = await interaction.guild.members.fetch(randomParticipant[0].userID);
assignedUser = member.user;
}
// Manual assignment
// ---------------------------------
// MANUAL ASSIGNMENT
// ---------------------------------
else {
const participant = await participateColl.findOne({
selectedParticipant = await participateColl.findOne({
userID: selectedUserId,
status: true
});
if (!participant) {
if (!selectedParticipant) {
return interaction.reply({
content: `<@${selectedUserId}> is not participating!`,
content:
`<@${selectedUserId}> is not participating!`,
flags: MessageFlags.Ephemeral
});
}
if (prevWge && selectedUserId === prevWge.assignedUser) {
if (
prevWge &&
selectedUserId === prevWge.assignedUser
) {
return interaction.reply({
content: `<@${selectedUserId}> was the previous expert and cannot be selected again this round.`,
content:
`<@${selectedUserId}> was the previous expert and cannot be selected again this round.`,
flags: MessageFlags.Ephemeral
});
}
assignedUser = { id: selectedUserId };
assignedUser = {
id: selectedUserId
};
}
// Archive previous WGE
// ---------------------------------
// ARCHIVE PREVIOUS WGE
// ---------------------------------
if (prevWge) {
await historyWgeColl.insertOne({
assignedUser: prevWge.assignedUser,
assigningUser: prevWge.assigningUser,
timeRemaining: prevWge.timeRemaining,
topic: prevWge.topic,
debug: prevWge.debug,
createdAt: prevWge.createdAt
});
@@ -150,7 +266,28 @@ async function modalSubmitHandler(interaction) {
});
}
// Create new WGE
const assignedAt = new Date();
// ---------------------------------
// UPDATE PARTICIPANT STATISTICS
// ---------------------------------
await participateColl.updateOne(
{
_id: selectedParticipant._id
},
{
$set: {
lastExpertAt: assignedAt
},
$inc: {
expertCount: 1
}
}
);
// ---------------------------------
// CREATE NEW WGE
// ---------------------------------
await wgeColl.insertOne({
assignedUser: assignedUser.id,
assigningUser: assigningUser.id,
@@ -169,10 +306,11 @@ async function modalSubmitHandler(interaction) {
topic,
debug: false,
createdAt: new Date()
createdAt: assignedAt
});
return interaction.reply({
content: `<@${assignedUser.id}> is the next expert! Their topic is **${topic}**`
content:
`<@${assignedUser.id}> is the next expert! Their topic is **${topic}**`
});
}
+139 -35
View File
@@ -1,4 +1,4 @@
const { mClient } = require("..");
const { mClient } = require('..');
async function getMember(client, userId) {
const guild = client.guilds.cache.get(process.env.D_GuildID);
@@ -7,15 +7,89 @@ async function getMember(client, userId) {
return null;
}
// Cache first
let member = guild.members.cache.get(userId);
// Fallback to API fetch
if (!member) {
member = await guild.members.fetch(userId).catch(() => null);
return (
guild.members.cache.get(userId) ||
await guild.members.fetch(userId).catch(() => null)
);
}
function getParticipantWeight(participant, now = Date.now()) {
// Never selected before -> strongly favor them
if (!participant.lastExpertAt) {
return 6;
}
return member;
const lastExpertAt = new Date(participant.lastExpertAt).getTime();
// Invalid date safety
if (Number.isNaN(lastExpertAt)) {
return 6;
}
const daysSinceExpert = Math.max(
0,
(now - lastExpertAt) / (24 * 60 * 60 * 1000)
);
/*
* Square-root weighting prevents very old participants
* from completely dominating the random selection.
*
* Examples:
* 1 day -> ~1.41
* 7 days -> ~2.83
* 30 days -> ~5.57
*/
return Math.sqrt(daysSinceExpert + 1);
}
function weightedRandom(participants) {
if (!participants.length) {
return null;
}
const weightedParticipants = participants.map(participant => ({
participant,
weight: getParticipantWeight(participant)
}));
const totalWeight = weightedParticipants.reduce(
(total, item) => total + item.weight,
0
);
let random = Math.random() * totalWeight;
for (const item of weightedParticipants) {
random -= item.weight;
if (random <= 0) {
return item.participant;
}
}
// Floating-point safety fallback
return weightedParticipants[weightedParticipants.length - 1].participant;
}
async function selectWgeParticipant(
participateColl,
{ excludeUserId = null } = {}
) {
const filter = {
status: true
};
if (excludeUserId) {
filter.userID = {
$ne: excludeUserId
};
}
const participants = await participateColl
.find(filter)
.toArray();
return weightedRandom(participants);
}
module.exports = {
@@ -35,50 +109,55 @@ module.exports = {
return;
}
// Notify previous assignee via DM
const previousMember = await getMember(client, timer.assignedUser);
// Notify previous expert
const previousMember = await getMember(
client,
timer.assignedUser
);
if (previousMember) {
await previousMember.send(
`❌ Timer ran out: **${timer.topic}** ...Re-assigning randomly...`
).catch(() => {});
).catch(error => {
console.error(
`timerComplete: Failed to DM ${timer.assignedUser}:`,
error
);
});
}
// Find the configured WGE channel
// Get configured WGE channel
const wgeChannelConfig = await channelColl.findOne({
purpose: 'wge',
guildID: process.env.D_GuildID
});
if (!wgeChannelConfig) {
console.error('timerComplete: WGE channel configuration not found.');
console.error(
'timerComplete: WGE channel configuration not found.'
);
return;
}
const channel = client.channels.cache.get(wgeChannelConfig.channelID);
const channel = client.channels.cache.get(
wgeChannelConfig.channelID
);
if (!channel) {
console.error('timerComplete: WGE channel not found.');
return;
}
// Pick a random participant, excluding the previous assignee
const randomParticipant = await participateColl.aggregate([
// Weighted random selection.
// Previous expert is explicitly excluded.
const selectedParticipant = await selectWgeParticipant(
participateColl,
{
$match: {
status: true,
userID: { $ne: timer.assignedUser }
}
},
{
$sample: {
size: 1
}
excludeUserId: timer.assignedUser
}
]).toArray();
);
// Nobody else is available
if (!randomParticipant.length) {
if (!selectedParticipant) {
await channel.send({
content:
`The timer for <@${timer.assignedUser}> has run out, ` +
@@ -89,12 +168,12 @@ module.exports = {
}
const newMember = await guild.members
.fetch(randomParticipant[0].userID)
.fetch(selectedParticipant.userID)
.catch(() => null);
if (!newMember) {
console.error(
`timerComplete: Could not fetch selected user ${randomParticipant[0].userID}.`
`timerComplete: Could not fetch selected user ${selectedParticipant.userID}.`
);
return;
}
@@ -102,14 +181,36 @@ module.exports = {
const newAssignedUser = newMember.user;
const wgeDefaultAssignedTime =
7 * 24 * 60 * 60 * 1000; // 7 days
7 * 24 * 60 * 60 * 1000;
// Remove the expired timer specifically
const assignedAt = new Date();
/*
* Update participant statistics.
*
* $inc automatically creates expertCount with value 1
* if the field does not exist yet.
*/
await participateColl.updateOne(
{
_id: selectedParticipant._id
},
{
$set: {
lastExpertAt: assignedAt
},
$inc: {
expertCount: 1
}
}
);
// Remove the expired timer
await wgeColl.deleteOne({
_id: timer._id
});
// Create the new timer
// Create new timer
await wgeColl.insertOne({
assignedUser: newAssignedUser.id,
assigningUser: timer.assigningUser,
@@ -128,14 +229,17 @@ module.exports = {
topic: timer.topic,
debug: false,
createdAt: new Date()
createdAt: assignedAt
});
// Announce reassignment
await channel.send({
content:
`The timer for <@${timer.assignedUser}> has run out! Assigning randomly...\n` +
`<@${newAssignedUser.id}> is the next expert! Their topic is still **${timer.topic}**`
});
console.log(
`timerComplete: Reassigned WGE from ${timer.assignedUser} to ${newAssignedUser.id}.`
);
}
};