Compare commits

...

20 Commits

Author SHA1 Message Date
DeSqBlocki 6e3e1620d1 added more documentation 2026-09-13 22:10:34 +02:00
DeSqBlocki dd4d6e4817 added achievements for new steal logic 2026-09-13 21:56:18 +02:00
DeSqBlocki b441de286c added ai rulebook 2026-09-13 21:56:01 +02:00
DeSqBlocki 2ca18aae06 updated steal logic 2026-09-13 21:14:56 +02:00
DeSqBlocki 1ef2295c07 snapshot_poker_phase5 2026-09-08 21:49:43 +02:00
DeSqBlocki 6342c4569b snapshot_poker_ui_ux_fix_again_fuckmylife 2026-09-08 21:12:34 +02:00
DeSqBlocki c61e34c241 snapshot_poker_uiux_cleanup_2 2026-09-08 21:05:52 +02:00
DeSqBlocki 82cef1b34a snapshot_poker_uiux_cleanup 2026-09-08 20:51:58 +02:00
DeSqBlocki 136a5902c0 snapshot_poker_phase4_hotfix 2026-09-08 20:17:19 +02:00
DeSqBlocki 903a2f3081 snapshot_poker_phase3 2026-09-08 19:37:02 +02:00
DeSqBlocki 995a2317b9 small changes to UI/UX 2026-08-27 21:35:06 +02:00
DeSqBlocki e3dbb11e12 snapshot migration pre-phase 6, stable 2026-08-27 21:14:27 +02:00
DeSqBlocki 14a059034c snapshot migration subPhase 5.5 2026-08-27 19:50:12 +02:00
DeSqBlocki 9710fc65bf snapshot migration phase 5 2026-08-27 19:34:16 +02:00
DeSqBlocki 42fc848f8c snapshot migration phase 4 2026-08-27 19:19:58 +02:00
DeSqBlocki c2ac7737c0 snapshot rollout phase 1 2026-08-27 18:52:56 +02:00
DeSqBlocki 6a519f3a2d changed achievment to work without followup 2026-08-23 01:19:22 +02:00
DeSqBlocki 338b32430d made achievments easier to discern 2026-08-23 01:00:03 +02:00
DeSqBlocki 9f1a539501 updated readme 2026-08-23 00:52:37 +02:00
DeSqBlocki 425686ec40 added new logic to the new rewards 2026-08-23 00:43:43 +02:00
56 changed files with 19141 additions and 4232 deletions
+3
View File
@@ -1,2 +1,5 @@
node_modules node_modules
.env .env
backup/
*.bak
tests/
+2220
View File
File diff suppressed because it is too large Load Diff
+193 -282
View File
@@ -1,338 +1,280 @@
# ShaiBot # ShaiBot
A modular **Discord.js** bot with a shared Cookie economy, interactive ShaiBot is a modular Discord community bot built around a persistent
Crumb Saucer games, cooperative boss battles, raid planning, and **Cookie economy**, interactive games, player progression, and
community interactions. multiplayer activities.
> **Status:** Active development. Game balance and individual features The bot's main entertainment hub is the **Crumb Saucer**, where players
> may change. can collect and wager Cookies, play casino-style games, attempt Vault
Heists, recover through Bankruptcy, and sit down at a multiplayer Texas
Hold'em table.
## Features ShaiBot also includes persistent player profiles, achievements,
guild-unique badges, cooperative encounters, raid planning, and lighter
community features.
### 🍪 Cookie Economy > **Status:** Active development and stabilization. The major economy,
> profile, achievement, and Poker overhaul is live; current work is
> focused primarily on testing, balancing, and polish.
Cookies are ShaiBot's shared virtual currency. The economy supports ## Highlights
persistent balances, atomic balance checks, transfers, per-user
cooldowns, and a shared bot/house vault.
The bot itself acts as the general Cookie vault: gambling losses and - 🍪 Persistent Cookie economy
penalties can feed the vault, while wins, heists, and rewards can pay - 🎰 Crumb Saucer game hub
Cookies back out. - 🎰 Slots, Blackjack, Roulette, Vault Heist, and Bankruptcy
- ♠️ Persistent 2--6 player Texas Hold'em
- 🏴 Player-to-player Cookie stealing
- 👤 Lifetime player profiles and statistics
- 🏆 Personal achievements
- 🎖️ Guild-unique global badges
- 🔁 All-In and Run It Back progression
- ⚔️ Cooperative Crumble Strike encounters
- 📅 Raid planning and community utilities
- 💾 Mongo-backed persistence and recovery
### 🎰 The Crumb Saucer ## The Crumb Saucer
The **Crumb Saucer** is ShaiBot's Cookie-powered entertainment hub. The **Crumb Saucer** is the main home for ShaiBot's Cookie-powered
games.
#### Slots ### 🍪 Cookie Bakery
- Multiple Cookie wagers Collect Cookies using the same shared collection system as
- Embed-based reel presentation `/cookies collect`.
- Different symbol payouts and jackpots
- Replay support
- Shared Cookie vault
#### Blackjack ### 🎰 Slots
- Hit, Stand, and Double Spin for symbol combinations, jackpots, All-In wagers, and Run It Back
- Dealer stands on 17 streaks.
- Natural Blackjack pays 3:2
- Push returns the wager
- Persistent active hands
- Per-player session ownership
- Safe simultaneous sessions
#### Roulette ### 🃏 Blackjack
A compact European Roulette implementation using **0--36**. Includes Hit, Stand, Double, natural Blackjack, pushes, All-In, and Run
It Back.
Available bets: ### 🎡 Roulette
- 🔴 Red A compact European Roulette game using numbers `0–36`, with Red, Black,
- ⚫ Black Odd, Even, and Zero bets.
- Odd
- Even
- 🟢 Zero
Roulette uses repeated edits of the same embed for a ### 🏦 Vault Heist
rate-limit-conscious pseudo-animation. Zero loses on Red, Black, Odd,
and Even.
#### Vault Heist Attempt to steal from ShaiBot's house vault using different risk/reward
approaches.
Players can attempt to steal directly from ShaiBot's Cookie vault using ### 🆘 Bankruptcy
different risk/reward approaches such as **Sneak**, **Hack**, and
**Smash**. Heist actions share a per-player cooldown so changing
approach does not bypass it.
### ⚔️ Crumble Strike A recovery mechanic for players who need a fresh start, with profile
progression for rebuilding afterward.
**Crumble Strike** is a cooperative Cookie-powered boss battle. ### ♠️ Shai Poker
- A player spawns an encounter. A persistent multiplayer Texas Hold'em game for **2--6 players**.
- Other players join during recruitment.
- The author can start after at least **5 players** have joined.
- Players can join an active encounter later.
- Encounters have a limited lifetime.
- Failure can result in committed Cookies being lost.
Combat actions include: Current defaults:
- **Strike** --- basic damage and Energy generation.
- **Defend** --- reduces incoming damage at an Energy cost.
- **Heal** --- restores party health at an Energy cost.
- **Revive** --- party-wide revival progress. Normal roles add +1 to
every downed player; Healers add +2. Three progress revives a
player.
- **Limit Break** --- consumes the party's global Limit resource for
major damage.
Roles are **DPS**, **Tank**, and **Healer**, with role-specific
proficiencies. The general progression theme includes **Sprout →
Adventurer → Warrior of Light**.
### 🏴 Cookie Stealing
Normal player-to-player stealing is separate from Vault Heist. Steal
difficulty can account for attacker and target wealth, successful steals
can use a randomized percentage with a cap, and failed attempts can
apply a fee that feeds the bot vault.
### 📅 Raid Planner
Raid planning uses Discord embeds and reactions. Participation can be
counted across reactions without automatically removing user reactions,
including a count of unique participants.
### 👈 Poke
A lightweight social command can privately poke another guild member
through DMs. Repeated pokes are bounded to a rate-limit-friendly
maximum.
## Project Structure
A typical layout:
``` text ``` text
ShaiBot/ Buy-in: 1,000 Cookies
├── buttons/ Blinds: 10 / 20
│ ├── crumbSaucer/ Turn timer: 90 seconds
│ └── crumbleStrike/ Pot model: single pot
├── commands/
│ └── applications/
├── events/
├── handlers/
├── modals/
├── utils/
│ ├── cookieEconomy.js
│ ├── crumbBlackjack.js
│ ├── crumbRoulette.js
│ └── crumbleStrike.js
├── index.js
├── package.json
└── .env
``` ```
Interaction modules are loaded into Discord.js collections such as: Poker supports private hole cards, public community cards,
Fold/Check/Call/Bet/Raise/All-In, automatic timeout folding, restart
recovery, host cancellation, safe buy-in/cash-out settlement, Poker
statistics, achievements, and guild-first badges.
``` js Side pots, tournaments, bots, rake, and player-facing equity assistance
client.commands = new Collection(); are intentionally outside the current V1 design.
client.legacyCommands = new Collection();
client.aliases = new Collection(); ## Player Profiles
client.buttons = new Collection();
client.selectMenus = new Collection(); Profiles provide the permanent history behind ShaiBot's progression
client.modals = new Collection(); systems.
```
They track things such as:
- Game wins and losses
- Per-game statistics
- Cookie gains and losses
- Giving and stealing
- Daily activity and streaks
- Social progression
- Run It Back streaks
- Poker history and hand accomplishments
- Achievements
- Global badges
Completed multiplayer game documents do not need to become permanent
history when the meaningful result already belongs in the profile
system.
## Achievements & Global Badges
**Achievements** are personal progression. Any eligible player can earn
them.
**Global badges** are guild-unique distinctions, usually awarded to the
first player in a guild to accomplish something notable.
Progression spans the Cookie economy, stealing, Crumb Saucer games,
activity, social interactions, Poker, and special cross-game challenges.
## Cookie Stealing
Player-to-player stealing is separate from Vault Heist.
The current system accounts for wealth differences, recent pressure on
the victim, percentage-based loot, hard caps, and an hourly exposure
budget.
Detailed balancing and mechanics are documented in
[`COOKIE_LOGIC.md`](COOKIE_LOGIC.md).
## ⚔️ Crumble Strike
Crumble Strike is ShaiBot's cooperative boss-battle system.
Players recruit a party, choose combat roles, commit Cookies, and work
together using actions such as Strike, Defend, Heal, Revive, and Limit
Break.
Encounters use persistent state because they can span many players and
interactions.
## 📅 Raid Planner & Community Features
ShaiBot also includes raid-planning tools and smaller social/community
commands alongside its economy and progression systems.
------------------------------------------------------------------------
# Installation
## Requirements ## Requirements
- Node.js - Node.js
- Discord.js
- MongoDB - MongoDB
- A Discord bot application/token - A Discord bot application/token
- `dotenv` - Dependencies listed in `package.json`
Use the Node.js version required by the dependencies in your Clone and install:
`package.json`.
## Installation
Clone the repository:
``` bash ``` bash
git clone https://github.com/YOUR_USERNAME/ShaiBot.git git clone https://git.desq-gaming.de/Shaiwase/ShaiBot.git
cd ShaiBot cd ShaiBot
```
Install dependencies:
``` bash
npm install npm install
``` ```
Create `.env` in the project root: Create `.env` in the repository root:
``` env ``` env
D_TOKEN=YOUR_DISCORD_BOT_TOKEN D_TOKEN=YOUR_DISCORD_BOT_TOKEN
M_URI=YOUR_MONGODB_CONNECTION_STRING M_URI=YOUR_MONGODB_CONNECTION_STRING
M_DB=YOUR_DATABASE_NAME M_DB=YOUR_DATABASE_NAME
# Optional
BOT_AUTHOR_ID=YOUR_DISCORD_USER_ID
PROFILE_TIMEZONE=Europe/Berlin
``` ```
Start the bot: Never commit `.env`.
Start normally:
``` bash ``` bash
node index.js node index.js
``` ```
For PM2, a typical command is: Or with PM2:
``` bash ``` bash
pm2 start index.js --name ShaiBot pm2 start index.js --name ShaiBot
``` ```
A typical update cycle is:
``` bash
node --check path/to/changed-file.js
pm2 restart ShaiBot
pm2 logs ShaiBot --lines 100
```
## MongoDB ## MongoDB
ShaiBot's Cookie economy intentionally does **not** depend on MongoDB ShaiBot does not require MongoDB multi-document transactions for its
transactions, allowing it to work with deployments that do not support core economy.
replica-set transactions.
If your deployment does not support retryable writes, include: The bot instead relies on atomic updates, unique indexes, optimistic
concurrency, idempotent operations, and recovery logic where
appropriate.
If your Mongo deployment does not support retryable writes, your
connection string may require:
``` text ``` text
retryWrites=false retryWrites=false
``` ```
in the connection string, for example:
``` env
M_URI=mongodb://USER:PASSWORD@HOST:PORT/DATABASE?authSource=admin&retryWrites=false
```
Never commit database credentials. Never commit database credentials.
Important economy collections include: ------------------------------------------------------------------------
``` text # Documentation
items_cookies
cooldown_cookies
items_games
```
`items_cookies` stores balances, `cooldown_cookies` stores action The central README intentionally stays high-level. Detailed
cooldown timestamps, and `items_games` can store persistent game state. implementation rules live in focused manuals:
### Recommended Indexes ------------------------------------------------------------------------------------
Document Purpose
------------------------------------------------ -----------------------------------
[`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) Runtime structure, handlers,
utilities, Mongo persistence,
concurrency, and recovery
Run the shared index initializer after MongoDB connects: [`docs/ECONOMY.md`](docs/ECONOMY.md) Cookie balances, transfers,
cooldowns, house vault, settlement,
and idempotency
``` js [`docs/PROGRESSION.md`](docs/PROGRESSION.md) Profiles, achievements, badges,
const { activity, social progression, and
ensureCookieIndexes maintenance
} = require("./utils/cookieEconomy");
await mClient.connect(); [`docs/GAMES.md`](docs/GAMES.md) Crumb Saucer games, Poker, Crumble
await ensureCookieIndexes(); Strike, and important game rules
```
The intended unique keys are: [`COOKIE_LOGIC.md`](COOKIE_LOGIC.md) Detailed PvP Cookie stealing rules
and balancing
``` text [`AGENTS.md`](AGENTS.md) Repository-wide safety and
items_cookies → userId architecture guide for AI coding
cooldown_cookies → userId + guildId agents
``` ------------------------------------------------------------------------------------
## Discord Intents The current repository code remains the final source of truth.
The current client uses intents including: ------------------------------------------------------------------------
``` js # Development Principles
GatewayIntentBits.Guilds
GatewayIntentBits.GuildMembers
GatewayIntentBits.GuildMessages
GatewayIntentBits.GuildPresences
GatewayIntentBits.GuildMessageReactions
GatewayIntentBits.GuildVoiceStates
GatewayIntentBits.DirectMessages
GatewayIntentBits.MessageContent
```
and partials including: ShaiBot generally favors:
``` js - Shared utilities instead of duplicated game/economy logic
Partials.Channel - Thin Discord command/button wrappers
Partials.Message - Persistent authoritative state where recovery matters
Partials.User - Atomic and idempotent economy operations
Partials.GuildMember - Centralized profile progression
Partials.Reaction - Public game experiences with private sensitive information
``` - Small explicit solutions over unnecessary abstraction
Enable any required privileged intents in the Discord Developer Portal. For stateful changes, always consider duplicate interactions,
simultaneous users, insufficient-balance races, and bot restarts during
## Interaction Design settlement.
ShaiBot generally follows these conventions:
- Public game output uses **embeds**.
- Short private errors/feedback can use **ephemeral messages**.
- Games use **buttons** for interaction.
- Existing messages are edited where practical instead of repeatedly
sending new messages.
- Game/session ownership is preserved so multiple users can play
independently.
- Animation-like effects use rate-limit-conscious message edits.
## Economy Safety
Economy operations favor atomic MongoDB updates for balance checks and
debits.
Transfers avoid MongoDB transactions for deployment compatibility. If a
destination credit fails after a successful debit, the shared economy
utility performs a best-effort compensating credit to the source
account. Administrators should monitor logs for critical compensation
failures.
When adding games, check that the house vault can cover the maximum
possible payout before accepting a wager.
## Adding a Crumb Saucer Game
Preferred pattern:
1. Put shared game logic in `utils/`.
2. Put individual Discord button handlers in the appropriate `buttons/`
directory.
3. Reuse `cookieEconomy.js` rather than implementing separate balance
logic.
4. Preserve the player/session owner through every screen.
5. Check house liquidity before accepting a wager.
6. Prefer editing the current embed for animation/state transitions.
7. Protect wager resolution against rapid repeated interactions.
## Roadmap / TODO
The major planned Cookie systems are implemented or designed. Remaining
work is primarily testing, balancing, and hardening.
- [ ] Verify Slots replay behavior after deployment
- [ ] Deploy and test limited Roulette
- [ ] Verify Crumble Strike AoE Revive behavior
- [ ] Verify Crumble Strike expiration/failure cleanup survives bot
restarts
- [ ] Balance boss HP, damage, healing, Energy, Limit generation,
entry costs, and rewards
- [ ] Stress-test simultaneous gambling interactions
- [ ] Stress-test repeated/double button presses
- [ ] Test insufficient-balance races
- [ ] Test behavior with a nearly empty house vault
- [ ] Consider dynamic Vault Heist payout caps
- [ ] Consider an economy audit/log collection
- [ ] Add more Crumble Strike bosses, lore, and encounter variety
- [ ] Add more Crumb Saucer attractions
## Security ## Security
A suitable `.gitignore` should include at least: Keep at least the following out of version control:
``` gitignore ``` gitignore
node_modules/ node_modules/
@@ -340,39 +282,8 @@ node_modules/
*.log *.log
``` ```
If a Discord token or MongoDB credential is accidentally committed, Rotate Discord or MongoDB credentials immediately if they are exposed.
rotate it immediately.
## Disclaimer
ShaiBot Cookies are fictional in-bot currency with no real-world
monetary value. Crumb Saucer gambling-style games are entertainment
mechanics using that fictional currency.
Final Fantasy XIV names and concepts referenced by community game
features belong to their respective rights holders. ShaiBot is not
affiliated with or endorsed by Square Enix.
## Contributing
Bug reports, balance suggestions, and contributions are welcome.
When contributing:
- Keep commands and button handlers modular.
- Reuse shared economy utilities.
- Avoid blocking the event loop.
- Be mindful of Discord API rate limits.
- Validate interaction ownership.
- Keep database operations safe under concurrent interactions.
## License ## License
Add the license used by the repository here. If the project is open See the repository's current license information, if present.
source, include a `LICENSE` file and replace this section with the
chosen license.
------------------------------------------------------------------------
Made for Discord communities that believe every problem can be improved
with a few more Cookies. 🍪
+27
View File
@@ -0,0 +1,27 @@
const {
buildPokerHubEmbed,
buildPokerHubComponents,
deferPokerReply
} = require("../../utils/pokerDiscord");
module.exports = {
name:
"crumbSaucerPoker",
async execute(
interaction
) {
await deferPokerReply(
interaction
);
return interaction.editReply({
embeds: [
buildPokerHubEmbed()
],
components:
buildPokerHubComponents()
});
}
};
+58
View File
@@ -0,0 +1,58 @@
const {
buildProfileOverview,
buildProfileButtons
} = require("../../utils/profileSystem");
const {
temporaryEphemeralReply
} = require("../../utils/cookieEconomy");
module.exports = {
name: "crumbSaucerProfile",
async execute(interaction) {
const footer =
interaction.message
?.embeds?.[0]
?.footer
?.text;
const [
type,
ownerId
] = footer?.split(":") ?? [];
if (
type !== "crumbSaucer" ||
ownerId !== interaction.user.id
) {
return temporaryEphemeralReply(
interaction,
{
content:
"This isn't your Crumb Saucer session."
}
);
}
const embed =
await buildProfileOverview(
interaction.guildId,
interaction.user,
interaction.user.id
);
return interaction.update({
embeds: [embed],
components:
buildProfileButtons(
"overview",
0,
1
)
});
}
};
+17
View File
@@ -0,0 +1,17 @@
const {
executePokerAction
} = require("../../utils/pokerInteractions");
module.exports = {
name: "pokerAllIn",
async execute(interaction) {
return executePokerAction(
interaction,
{
type: "all_in"
},
"✅ All-In."
);
}
};
+47
View File
@@ -0,0 +1,47 @@
const {
getPokerService
} = require("../../utils/crumbPoker");
const {
deferPokerReply,
editPokerError,
buildJoinPicker
} = require("../../utils/pokerDiscord");
module.exports = {
name:
"pokerBrowse",
async execute(
interaction
) {
await deferPokerReply(
interaction
);
try {
const tables =
await getPokerService()
.listJoinableTables({
guildId:
interaction.guildId,
channelId:
interaction.channelId
});
return interaction.editReply(
buildJoinPicker(
tables
)
);
}
catch (error) {
return editPokerError(
interaction,
error
);
}
}
};
+17
View File
@@ -0,0 +1,17 @@
const {
executePokerAction
} = require("../../utils/pokerInteractions");
module.exports = {
name: "pokerCall",
async execute(interaction) {
return executePokerAction(
interaction,
{
type: "call"
},
"✅ Called."
);
}
};
+85
View File
@@ -0,0 +1,85 @@
const {
EmbedBuilder,
ActionRowBuilder,
ButtonBuilder,
ButtonStyle
} = require("discord.js");
const {
getPokerService
} = require("../../utils/crumbPoker");
const {
POKER_TABLE_FOOTER_PREFIX,
deferPokerReply,
editPokerError,
getPokerGameIdFromInteraction
} = require("../../utils/pokerDiscord");
module.exports = {
name: "pokerCancel",
async execute(interaction) {
await deferPokerReply(interaction);
const gameId =
getPokerGameIdFromInteraction(interaction);
if (!gameId) {
return interaction.editReply({
content: "❌ This Poker table is no longer active.",
embeds: [],
components: []
});
}
try {
const game =
await getPokerService().getTable({ gameId });
if (
String(game.data.ownerId) !==
String(interaction.user.id)
) {
return interaction.editReply({
content: "❌ Only the table owner can cancel this Poker table.",
embeds: [],
components: []
});
}
return interaction.editReply({
content: "",
embeds: [
new EmbedBuilder()
.setTitle("🛑 Cancel Poker Table?")
.setDescription(
[
"All seated players will be safely cashed out.",
"",
"This cannot be undone."
].join("\n")
)
.setFooter({
text: `${POKER_TABLE_FOOTER_PREFIX}:${gameId}`
})
],
components: [
new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId("pokerCancelConfirm")
.setLabel("Cancel Table")
.setEmoji("🛑")
.setStyle(ButtonStyle.Danger),
new ButtonBuilder()
.setCustomId("pokerCancelKeep")
.setLabel("Keep Table")
.setStyle(ButtonStyle.Secondary)
)
]
});
} catch (error) {
return editPokerError(interaction, error);
}
}
};
+50
View File
@@ -0,0 +1,50 @@
const {
getPokerService
} = require("../../utils/crumbPoker");
const {
deferPokerReply,
editPokerError,
getPokerGameIdFromInteraction,
refreshPokerTableMessage
} = require("../../utils/pokerDiscord");
module.exports = {
name: "pokerCancelConfirm",
async execute(interaction) {
await deferPokerReply(interaction);
const gameId =
getPokerGameIdFromInteraction(interaction);
if (!gameId) {
return interaction.editReply({
content: "❌ This Poker table is no longer active.",
embeds: [],
components: []
});
}
try {
const game =
await getPokerService().cancelTable({
gameId,
userId: interaction.user.id
});
await refreshPokerTableMessage(
interaction.client,
game
);
try {
await interaction.deleteReply();
} catch {}
return;
} catch (error) {
return editPokerError(interaction, error);
}
}
};
+17
View File
@@ -0,0 +1,17 @@
const {
deferPokerReply
} = require("../../utils/pokerDiscord");
module.exports = {
name: "pokerCancelKeep",
async execute(interaction) {
await deferPokerReply(interaction);
try {
await interaction.deleteReply();
} catch {}
return;
}
};
+151
View File
@@ -0,0 +1,151 @@
const {
cardToString
} = require("../../utils/pokerEngine");
const {
getPokerService
} = require("../../utils/crumbPoker");
const {
POKER_CARD_RESPONSE_LIFETIME,
deferPokerReply,
editPokerError,
getPokerGameIdFromInteraction
} = require("../../utils/pokerDiscord");
module.exports = {
name:
"pokerCards",
async execute(
interaction
) {
await deferPokerReply(
interaction
);
const gameId =
getPokerGameIdFromInteraction(
interaction
);
if (!gameId) {
return interaction.editReply({
content:
"❌ This Poker table is no longer active.",
embeds: [],
components: []
});
}
try {
const service =
getPokerService();
const [
cards,
game
] =
await Promise.all([
service.viewCards({
gameId,
userId:
interaction.user.id
}),
service.getTable({
gameId
})
]);
const hand =
game.data.hand;
const player =
game.data.players.find(
candidate =>
String(candidate.userId) ===
String(interaction.user.id)
);
const currentPlayer =
hand?.players?.find(
candidate =>
candidate.seat ===
hand.currentSeat
);
const isYourTurn =
Boolean(
player
&&
hand
&&
hand.currentSeat ===
player.seat
);
const communityCards =
hand?.communityCards ?? [];
const lines = [
"### 🃏 Your Cards",
`**${cards.map(cardToString).join(" ")}**`,
"",
"**Community:** " +
(communityCards.length
? communityCards
.map(cardToString)
.join(" ")
: "No community cards yet."),
""
];
if (isYourTurn) {
lines.push(
"👉 **It's YOUR TURN.**",
game.data.turnExpiresAt
? `⏱️ Auto-folds <t:${game.data.turnExpiresAt}:R>.`
: "⏱️ Your turn timer is active."
);
}
else if (currentPlayer) {
lines.push(
`Waiting for <@${currentPlayer.userId}> to act.`
);
}
else {
lines.push(
"The hand is not currently waiting on a player action."
);
}
await interaction.editReply({
content:
lines.join("\n"),
embeds: [],
components: []
});
setTimeout(
() => {
interaction
.deleteReply()
.catch(() => {});
},
POKER_CARD_RESPONSE_LIFETIME
);
return;
}
catch (error) {
return editPokerError(
interaction,
error
);
}
}
};
+67
View File
@@ -0,0 +1,67 @@
const {
getPokerService
} = require("../../utils/crumbPoker");
const {
deferPokerReply,
editPokerError,
getPokerGameIdFromInteraction,
refreshPokerTableMessage
} = require("../../utils/pokerDiscord");
module.exports = {
name:
"pokerCashOut",
async execute(
interaction
) {
await deferPokerReply(
interaction
);
const gameId =
getPokerGameIdFromInteraction(
interaction
);
if (!gameId) {
return interaction.editReply({
content:
"❌ This Poker table is no longer active.",
embeds: [],
components: []
});
}
try {
const result =
await getPokerService()
.cashOut({
gameId,
userId:
interaction.user.id
});
await refreshPokerTableMessage(
interaction.client,
result.game
);
return interaction.editReply({
content:
`✅ Cashed out **${result.amount.toLocaleString()} Cookies** back to your vault.`,
embeds: [],
components: []
});
}
catch (error) {
return editPokerError(
interaction,
error
);
}
}
};
+17
View File
@@ -0,0 +1,17 @@
const {
executePokerAction
} = require("../../utils/pokerInteractions");
module.exports = {
name: "pokerCheck",
async execute(interaction) {
return executePokerAction(
interaction,
{
type: "check"
},
"✅ Checked."
);
}
};
+81
View File
@@ -0,0 +1,81 @@
const {
getPokerService
} = require("../../utils/crumbPoker");
const {
deferPokerReply,
editPokerError,
publishPokerTable,
buildOpenTableLink
} = require("../../utils/pokerDiscord");
module.exports = {
name:
"pokerCreate",
async execute(
interaction
) {
await deferPokerReply(
interaction
);
const service =
getPokerService();
let game = null;
try {
game =
await service.createTable({
guildId:
interaction.guildId,
channelId:
interaction.channelId,
ownerId:
interaction.user.id
});
const published =
await publishPokerTable(
interaction,
game
);
return interaction.editReply({
content:
`✅ Poker table created. **${published.game.data.buyIn.toLocaleString()} Cookies** were moved into your Poker stack.`,
embeds: [],
components:
buildOpenTableLink(
published.game
)
});
}
catch (error) {
if (game) {
try {
await service.cashOut({
gameId:
game.gameId,
userId:
interaction.user.id
});
}
catch (refundError) {
console.error(
`[Poker] Failed to refund unpublished table ${game.gameId}:`,
refundError
);
}
}
return editPokerError(
interaction,
error
);
}
}
};
+17
View File
@@ -0,0 +1,17 @@
const {
executePokerAction
} = require("../../utils/pokerInteractions");
module.exports = {
name: "pokerFold",
async execute(interaction) {
return executePokerAction(
interaction,
{
type: "fold"
},
"✅ Folded."
);
}
};
+73
View File
@@ -0,0 +1,73 @@
const {
getPokerService
} = require("../../utils/crumbPoker");
const {
deferPokerReply,
editPokerError,
getPokerGameIdFromInteraction,
refreshPokerTableMessage,
buildOpenTableLink
} = require("../../utils/pokerDiscord");
module.exports = {
name:
"pokerJoinTable",
async execute(
interaction
) {
await deferPokerReply(
interaction
);
const gameId =
getPokerGameIdFromInteraction(
interaction
);
if (!gameId) {
return interaction.editReply({
content:
"❌ This Poker table is no longer active.",
embeds: [],
components: []
});
}
try {
const game =
await getPokerService()
.joinTable({
gameId,
guildId:
interaction.guildId,
userId:
interaction.user.id
});
await refreshPokerTableMessage(
interaction.client,
game
);
return interaction.editReply({
content:
`✅ Joined the Poker table for **${game.data.buyIn.toLocaleString()} Cookies**.`,
embeds: [],
components:
buildOpenTableLink(
game
)
});
}
catch (error) {
return editPokerError(
interaction,
error
);
}
}
};
+66
View File
@@ -0,0 +1,66 @@
const {
getPokerService
} = require("../../utils/crumbPoker");
const {
deferPokerReply,
editPokerError,
refreshPokerTableMessage,
buildOpenTableLink
} = require("../../utils/pokerDiscord");
module.exports = {
name:
"pokerMyTable",
async execute(
interaction
) {
await deferPokerReply(
interaction
);
try {
const game =
await getPokerService()
.getMyTable({
guildId:
interaction.guildId,
userId:
interaction.user.id
});
if (!game) {
return interaction.editReply({
content:
"❌ You are not currently seated at a Poker table.",
embeds: [],
components: []
});
}
await refreshPokerTableMessage(
interaction.client,
game
);
return interaction.editReply({
content:
"♠️ Your active Poker table:",
embeds: [],
components:
buildOpenTableLink(
game
)
});
}
catch (error) {
return editPokerError(
interaction,
error
);
}
}
};
+13
View File
@@ -0,0 +1,13 @@
const {
executeMinimumRaise
} = require("../../utils/pokerInteractions");
module.exports = {
name: "pokerRaise",
async execute(interaction) {
return executeMinimumRaise(
interaction
);
}
};
+65
View File
@@ -0,0 +1,65 @@
const {
getPokerService
} = require("../../utils/crumbPoker");
const {
deferPokerReply,
editPokerError,
getPokerGameIdFromInteraction,
refreshPokerTableMessage
} = require("../../utils/pokerDiscord");
module.exports = {
name:
"pokerRefresh",
async execute(
interaction
) {
await deferPokerReply(
interaction
);
const gameId =
getPokerGameIdFromInteraction(
interaction
);
if (!gameId) {
return interaction.editReply({
content:
"❌ This Poker table is no longer active.",
embeds: [],
components: []
});
}
try {
const game =
await getPokerService()
.getTable({
gameId
});
await refreshPokerTableMessage(
interaction.client,
game
);
return interaction.editReply({
content:
"✅ Poker table refreshed.",
embeds: [],
components: []
});
}
catch (error) {
return editPokerError(
interaction,
error
);
}
}
};
+67
View File
@@ -0,0 +1,67 @@
const {
getPokerService
} = require("../../utils/crumbPoker");
const {
deferPokerReply,
editPokerError,
getPokerGameIdFromInteraction,
refreshPokerTableMessage
} = require("../../utils/pokerDiscord");
module.exports = {
name:
"pokerStart",
async execute(
interaction
) {
await deferPokerReply(
interaction
);
const gameId =
getPokerGameIdFromInteraction(
interaction
);
if (!gameId) {
return interaction.editReply({
content:
"❌ This Poker table is no longer active.",
embeds: [],
components: []
});
}
try {
const game =
await getPokerService()
.startTableHand({
gameId,
userId:
interaction.user.id
});
await refreshPokerTableMessage(
interaction.client,
game
);
return interaction.editReply({
content:
`✅ Hand **#${game.data.handNumber}** started. Cards have been dealt — use **🃏 Cards** to view your hand.`,
embeds: [],
components: []
});
}
catch (error) {
return editPokerError(
interaction,
error
);
}
}
};
+39 -36
View File
@@ -1,51 +1,54 @@
const { const {
requireProfileOwner,
buildAchievementsEmbed, buildAchievementsEmbed,
buildProfileButtons, buildProfileButtons,
buildProfilePaginationButtons getProfileContextFromFooter,
} = require("../../utils/profileSystem"); requireProfileOwner
} = require(
"../../utils/profileSystem"
);
module.exports = { module.exports = {
name: "profileAchievements", name:
"profileAchievements",
async execute(interaction) { async execute(
const session = await requireProfileOwner( interaction
interaction ) {
); const context =
await requireProfileOwner(
interaction
);
if (!session) { if (!context) {
return; return;
} }
const user = await interaction.client.users.fetch( const user =
session.profileUserId await interaction.client.users.fetch(
); context.profileUserId
);
const result = await buildAchievementsEmbed(
interaction.guildId, const embed =
user, await buildAchievementsEmbed(
0, interaction.guildId,
session.sessionOwnerId user,
); context.sessionOwnerId,
0
const components = [ );
...buildProfileButtons()
]; const pageContext =
getProfileContextFromFooter(
if (result.pageCount > 1) { embed.data.footer?.text
components.push(
buildProfilePaginationButtons(
"profileAchievementsLeft",
"profileAchievementsRight",
result.page,
result.pageCount
)
); );
}
return interaction.update({ return interaction.update({
embeds: [result.embed], embeds: [embed],
components components:
buildProfileButtons(
"achievements",
pageContext?.page ?? 0,
pageContext?.pageCount ?? 1
)
}); });
} }
}; };
+39 -38
View File
@@ -1,53 +1,54 @@
// buttons/profile/achievementsLeft.js
const { const {
requireProfileOwner,
buildAchievementsEmbed, buildAchievementsEmbed,
buildProfileButtons, buildProfileButtons,
buildProfilePaginationButtons getProfileContextFromFooter,
} = require("../../utils/profileSystem"); requireProfileOwner
} = require(
"../../utils/profileSystem"
);
module.exports = { module.exports = {
name: "profileAchievementsLeft", name:
"profileAchievementsLeft",
async execute(interaction) { async execute(
const session = await requireProfileOwner( interaction
interaction ) {
); const context =
await requireProfileOwner(
interaction
);
if (!session) { if (!context) {
return; return;
} }
const user = await interaction.client.users.fetch( const user =
session.profileUserId await interaction.client.users.fetch(
); context.profileUserId
);
const result = await buildAchievementsEmbed(
interaction.guildId, const embed =
user, await buildAchievementsEmbed(
session.page - 1, interaction.guildId,
session.sessionOwnerId user,
); context.sessionOwnerId,
context.page - 1
const components = [ );
...buildProfileButtons()
]; const pageContext =
getProfileContextFromFooter(
if (result.pageCount > 1) { embed.data.footer?.text
components.push(
buildProfilePaginationButtons(
"profileAchievementsLeft",
"profileAchievementsRight",
result.page,
result.pageCount
)
); );
}
return interaction.update({ return interaction.update({
embeds: [result.embed], embeds: [embed],
components components:
buildProfileButtons(
"achievements",
pageContext?.page ?? 0,
pageContext?.pageCount ?? 1
)
}); });
} }
}; };
+39 -38
View File
@@ -1,53 +1,54 @@
// buttons/profile/achievementsRight.js
const { const {
requireProfileOwner,
buildAchievementsEmbed, buildAchievementsEmbed,
buildProfileButtons, buildProfileButtons,
buildProfilePaginationButtons getProfileContextFromFooter,
} = require("../../utils/profileSystem"); requireProfileOwner
} = require(
"../../utils/profileSystem"
);
module.exports = { module.exports = {
name: "profileAchievementsRight", name:
"profileAchievementsRight",
async execute(interaction) { async execute(
const session = await requireProfileOwner( interaction
interaction ) {
); const context =
await requireProfileOwner(
interaction
);
if (!session) { if (!context) {
return; return;
} }
const user = await interaction.client.users.fetch( const user =
session.profileUserId await interaction.client.users.fetch(
); context.profileUserId
);
const result = await buildAchievementsEmbed(
interaction.guildId, const embed =
user, await buildAchievementsEmbed(
session.page + 1, interaction.guildId,
session.sessionOwnerId user,
); context.sessionOwnerId,
context.page + 1
const components = [ );
...buildProfileButtons()
]; const pageContext =
getProfileContextFromFooter(
if (result.pageCount > 1) { embed.data.footer?.text
components.push(
buildProfilePaginationButtons(
"profileAchievementsLeft",
"profileAchievementsRight",
result.page,
result.pageCount
)
); );
}
return interaction.update({ return interaction.update({
embeds: [result.embed], embeds: [embed],
components components:
buildProfileButtons(
"achievements",
pageContext?.page ?? 0,
pageContext?.pageCount ?? 1
)
}); });
} }
}; };
+39 -36
View File
@@ -1,51 +1,54 @@
const { const {
requireProfileOwner,
buildBadgesEmbed, buildBadgesEmbed,
buildProfileButtons, buildProfileButtons,
buildProfilePaginationButtons getProfileContextFromFooter,
} = require("../../utils/profileSystem"); requireProfileOwner
} = require(
"../../utils/profileSystem"
);
module.exports = { module.exports = {
name: "profileBadges", name:
"profileBadges",
async execute(interaction) { async execute(
const session = await requireProfileOwner( interaction
interaction ) {
); const context =
await requireProfileOwner(
interaction
);
if (!session) { if (!context) {
return; return;
} }
const user = await interaction.client.users.fetch( const user =
session.profileUserId await interaction.client.users.fetch(
); context.profileUserId
);
const result = await buildBadgesEmbed(
interaction.guildId, const embed =
user, await buildBadgesEmbed(
0, interaction.guildId,
session.sessionOwnerId user,
); context.sessionOwnerId,
0
const components = [ );
...buildProfileButtons()
]; const pageContext =
getProfileContextFromFooter(
if (result.pageCount > 1) { embed.data.footer?.text
components.push(
buildProfilePaginationButtons(
"profileBadgesLeft",
"profileBadgesRight",
result.page,
result.pageCount
)
); );
}
return interaction.update({ return interaction.update({
embeds: [result.embed], embeds: [embed],
components components:
buildProfileButtons(
"badges",
pageContext?.page ?? 0,
pageContext?.pageCount ?? 1
)
}); });
} }
}; };
+39 -38
View File
@@ -1,53 +1,54 @@
// buttons/profile/badgesLeft.js
const { const {
requireProfileOwner,
buildBadgesEmbed, buildBadgesEmbed,
buildProfileButtons, buildProfileButtons,
buildProfilePaginationButtons getProfileContextFromFooter,
} = require("../../utils/profileSystem"); requireProfileOwner
} = require(
"../../utils/profileSystem"
);
module.exports = { module.exports = {
name: "profileBadgesLeft", name:
"profileBadgesLeft",
async execute(interaction) { async execute(
const session = await requireProfileOwner( interaction
interaction ) {
); const context =
await requireProfileOwner(
interaction
);
if (!session) { if (!context) {
return; return;
} }
const user = await interaction.client.users.fetch( const user =
session.profileUserId await interaction.client.users.fetch(
); context.profileUserId
);
const result = await buildBadgesEmbed(
interaction.guildId, const embed =
user, await buildBadgesEmbed(
session.page - 1, interaction.guildId,
session.sessionOwnerId user,
); context.sessionOwnerId,
context.page - 1
const components = [ );
...buildProfileButtons()
]; const pageContext =
getProfileContextFromFooter(
if (result.pageCount > 1) { embed.data.footer?.text
components.push(
buildProfilePaginationButtons(
"profileBadgesLeft",
"profileBadgesRight",
result.page,
result.pageCount
)
); );
}
return interaction.update({ return interaction.update({
embeds: [result.embed], embeds: [embed],
components components:
buildProfileButtons(
"badges",
pageContext?.page ?? 0,
pageContext?.pageCount ?? 1
)
}); });
} }
}; };
+39 -38
View File
@@ -1,53 +1,54 @@
// buttons/profile/badgesRight.js
const { const {
requireProfileOwner,
buildBadgesEmbed, buildBadgesEmbed,
buildProfileButtons, buildProfileButtons,
buildProfilePaginationButtons getProfileContextFromFooter,
} = require("../../utils/profileSystem"); requireProfileOwner
} = require(
"../../utils/profileSystem"
);
module.exports = { module.exports = {
name: "profileBadgesRight", name:
"profileBadgesRight",
async execute(interaction) { async execute(
const session = await requireProfileOwner( interaction
interaction ) {
); const context =
await requireProfileOwner(
interaction
);
if (!session) { if (!context) {
return; return;
} }
const user = await interaction.client.users.fetch( const user =
session.profileUserId await interaction.client.users.fetch(
); context.profileUserId
);
const result = await buildBadgesEmbed(
interaction.guildId, const embed =
user, await buildBadgesEmbed(
session.page + 1, interaction.guildId,
session.sessionOwnerId user,
); context.sessionOwnerId,
context.page + 1
const components = [ );
...buildProfileButtons()
]; const pageContext =
getProfileContextFromFooter(
if (result.pageCount > 1) { embed.data.footer?.text
components.push(
buildProfilePaginationButtons(
"profileBadgesLeft",
"profileBadgesRight",
result.page,
result.pageCount
)
); );
}
return interaction.update({ return interaction.update({
embeds: [result.embed], embeds: [embed],
components components:
buildProfileButtons(
"badges",
pageContext?.page ?? 0,
pageContext?.pageCount ?? 1
)
}); });
} }
}; };
+33 -20
View File
@@ -1,34 +1,47 @@
const { const {
requireProfileOwner, buildStatsEmbed,
buildProfileStatsEmbed, buildProfileButtons,
buildProfileButtons requireProfileOwner
} = require("../../utils/profileSystem"); } = require(
"../../utils/profileSystem"
);
module.exports = { module.exports = {
name: "profileStats", name:
"profileStats",
async execute(interaction) { async execute(
const session = await requireProfileOwner( interaction
interaction ) {
); const context =
await requireProfileOwner(
interaction
);
if (!session) { if (!context) {
return; return;
} }
const user = await interaction.client.users.fetch( const user =
session.profileUserId await interaction.client.users.fetch(
); context.profileUserId
);
const embed = await buildProfileStatsEmbed( const embed =
interaction.guildId, await buildStatsEmbed(
user, interaction.guildId,
session.sessionOwnerId user,
); context.sessionOwnerId
);
return interaction.update({ return interaction.update({
embeds: [embed], embeds: [embed],
components: buildProfileButtons() components:
buildProfileButtons(
"stats",
0,
1
)
}); });
} }
}; };
File diff suppressed because it is too large Load Diff
+51 -34
View File
@@ -1,46 +1,63 @@
const { SlashCommandBuilder } = require("discord.js"); const {
SlashCommandBuilder
} = require(
"discord.js"
);
const { const {
buildProfileOverview, buildProfileOverview,
buildProfileButtons buildProfileButtons
} = require("../../utils/profileSystem"); } = require(
const { "../../utils/profileSystem"
createInteractionSession );
} = require("../../utils/interactionSession");
module.exports = { module.exports = {
data: new SlashCommandBuilder() data:
.setName("profile") new SlashCommandBuilder()
.setDescription("View a player profile") .setName(
.addUserOption(option => "profile"
option )
.setName("user") .setDescription(
.setDescription("Player to view") "View a player profile"
), )
.addUserOption(
option =>
option
.setName(
"user"
)
.setDescription(
"Player to view"
)
),
async execute(interaction) { async execute(
const user = interaction.options.getUser("user") ?? interaction.user; interaction
) {
const user =
interaction.options.getUser(
"user"
) ??
interaction.user;
const embed = await buildProfileOverview( const sessionOwnerId =
interaction.guildId, interaction.user.id;
user,
interaction.user.id
);
await interaction.reply({ const embed =
await buildProfileOverview(
interaction.guildId,
user,
sessionOwnerId
);
return interaction.reply({
embeds: [embed], embeds: [embed],
components: buildProfileButtons() components:
buildProfileButtons(
"overview",
0,
1
)
}); });
const message = await interaction.fetchReply();
await createInteractionSession(
interaction,
{
messageId: message.id,
ownerId: interaction.user.id,
kind: "profile",
targetId: user.id
}
);
} }
}; };
+538 -324
View File
@@ -1,8 +1,19 @@
const { const {
SlashCommandBuilder, SlashCommandBuilder,
MessageFlags MessageFlags,
EmbedBuilder
} = require("discord.js");
const {
reconcileUserAchievements,
reconcileAllAchievements,
grantMaintenanceReward,
getMaintenanceRewardStatus,
auditProfileData,
DEFAULT_MAINTENANCE_REWARD_ID,
DEFAULT_MAINTENANCE_REWARD_AMOUNT
} = require( } = require(
"discord.js" "../../utils/profileMaintenance"
); );
const { const {
@@ -11,19 +22,6 @@ const {
"../../utils/permissions" "../../utils/permissions"
); );
const {
reconcileProfileAchievements,
auditProfileSystem
} = require(
"../../utils/profileSystem"
);
/*
* ============================================================
* COMMAND
* ============================================================
*/
module.exports = { module.exports = {
data: data:
@@ -31,99 +29,121 @@ module.exports = {
.setName( .setName(
"profileadmin" "profileadmin"
) )
.setDescription( .setDescription(
"Profile and achievement administration." "Administrative profile maintenance tools"
) )
/*
* =================================================
* RECONCILE
* =================================================
*/
.addSubcommand( .addSubcommand(
subcommand => subcommand =>
subcommand subcommand
.setName( .setName(
"reconcile" "reconcile"
) )
.setDescription( .setDescription(
"Re-evaluate stored statistics for achievements." "Backfill database-trackable achievements"
) )
.addUserOption( .addUserOption(
option => option =>
option option
.setName( .setName(
"user" "user"
) )
.setDescription( .setDescription(
"Only reconcile this user's profile." "Only reconcile this user; omit for everyone"
)
.setRequired(
false
) )
) )
.addBooleanOption( .addBooleanOption(
option => option =>
option option
.setName( .setName(
"dry-run" "dry-run"
) )
.setDescription( .setDescription(
"Show what would change without unlocking anything." "Show what would change without writing it"
)
.setRequired(
false
) )
) )
) )
/*
* =================================================
* AUDIT
* =================================================
*/
.addSubcommand( .addSubcommand(
subcommand => subcommand =>
subcommand subcommand
.setName( .setName(
"audit" "audit"
) )
.setDescription( .setDescription(
"Audit the profile and achievement system." "Audit stored profile statistics for inconsistencies"
)
)
.addSubcommand(
subcommand =>
subcommand
.setName(
"maintenance-reward"
)
.setDescription(
"Grant an idempotent maintenance reward to stored profile users"
)
.addStringOption(
option =>
option
.setName(
"reward-id"
)
.setDescription(
`Unique reward ID; defaults to ${DEFAULT_MAINTENANCE_REWARD_ID}`
)
)
.addIntegerOption(
option =>
option
.setName(
"amount"
)
.setDescription(
`Cookies per player; defaults to ${DEFAULT_MAINTENANCE_REWARD_AMOUNT}`
)
.setMinValue(
1
)
)
.addBooleanOption(
option =>
option
.setName(
"dry-run"
)
.setDescription(
"Preview recipients without granting Cookies"
)
)
)
.addSubcommand(
subcommand =>
subcommand
.setName(
"maintenance-status"
)
.setDescription(
"Show maintenance reward claim status"
)
.addStringOption(
option =>
option
.setName(
"reward-id"
)
.setDescription(
`Reward ID; defaults to ${DEFAULT_MAINTENANCE_REWARD_ID}`
)
) )
), ),
/*
* ========================================================
* EXECUTE
* ========================================================
*/
async execute( async execute(
interaction interaction
) { ) {
/* /*
* Runtime authorization. * Allows:
* *
* This intentionally replaces: * - Discord Administrators
* * - BOT_AUTHOR_ID from .env
* .setDefaultMemberPermissions(
* PermissionFlagsBits.Administrator
* )
*
* so BOT_AUTHOR_ID can also invoke the command.
*/ */
if ( if (
@@ -136,280 +156,474 @@ module.exports = {
const subcommand = const subcommand =
interaction.options interaction.options.getSubcommand();
.getSubcommand();
switch ( await interaction.deferReply({
subcommand flags:
) { MessageFlags.Ephemeral
case "reconcile": });
return runReconcile(
interaction
);
case "audit": try {
if (
return runAudit( subcommand ===
interaction "reconcile"
); ) {
const user =
interaction.options.getUser(
default: "user"
return interaction.reply({
content:
"Unknown profile administration action.",
flags:
MessageFlags.Ephemeral
});
}
}
};
/*
* ============================================================
* RECONCILE
* ============================================================
*/
async function runReconcile(
interaction
) {
const target =
interaction.options.getUser(
"user"
);
const dryRun =
interaction.options.getBoolean(
"dry-run"
)
??
false;
/*
* This can touch multiple Mongo documents,
* so acknowledge the interaction first.
*/
await interaction.deferReply({
flags:
MessageFlags.Ephemeral
});
try {
const result =
await reconcileProfileAchievements(
interaction.guildId,
{
userId:
target?.id
??
null,
dryRun
}
);
const lines = [
dryRun
? "### 🔎 Profile Reconciliation — Dry Run"
: "### ✅ Profile Reconciliation Complete",
"",
target
? `Target: ${target}`
: "Target: **Entire Guild**",
"",
`Profiles checked: **${result.profilesChecked ?? 0}**`,
`Achievement unlocks found: **${result.unlocksFound ?? 0}**`
];
if (
!dryRun
) {
lines.push(
`Achievements unlocked: **${result.unlocksApplied ?? 0}**`
);
}
if (
result.skippedEventOnly !==
undefined
) {
lines.push(
`Event-only checks skipped: **${result.skippedEventOnly}**`
);
}
if (
Array.isArray(
result.details
)
&&
result.details.length >
0
) {
const preview =
result.details
.slice(
0,
15
)
.map(
entry => {
if (
typeof entry ===
"string"
) {
return `• ${entry}`;
}
return (
`• <@${entry.userId}> — ` +
`${entry.achievementName ?? entry.achievementId}`
);
}
); );
lines.push( const dryRun =
"", interaction.options.getBoolean(
"### Changes", "dry-run"
...preview ) ?? false;
);
if (user) {
const result =
await reconcileUserAchievements({
guildId:
interaction.guildId,
userId:
user.id,
dryRun
});
return interaction.editReply({
embeds: [
new EmbedBuilder()
.setTitle(
"🛠️ Profile Reconciliation"
)
.setDescription(
`${dryRun ? "Dry run for" : "Reconciled"} ${user}.`
)
.addFields(
{
name:
"New unlocks",
value:
`**${result.unlocked}**`,
inline:
true
},
{
name:
"Definitions checked",
value:
`**${result.checked}**`,
inline:
true
},
{
name:
"Event-only skipped",
value:
`**${result.skippedEventOnly}**`,
inline:
true
}
)
]
});
}
const summary =
await reconcileAllAchievements({
guildId:
interaction.guildId,
dryRun
});
return interaction.editReply({
embeds: [
new EmbedBuilder()
.setTitle(
"🛠️ Profile Reconciliation"
)
.setDescription(
`${dryRun ? "Dry run completed" : "Reconciliation completed"} for stored profile users.`
)
.addFields(
{
name:
"Users",
value:
`**${summary.users}**`,
inline:
true
},
{
name:
"New unlocks",
value:
`**${summary.unlocked}**`,
inline:
true
},
{
name:
"Event-only checks skipped",
value:
`**${summary.skippedEventOnly}**`,
inline:
true
}
)
]
});
}
if ( if (
result.details.length > subcommand ===
preview.length "maintenance-reward"
) { ) {
lines.push( const rewardId =
"", interaction.options.getString(
`*...and ${result.details.length - preview.length} more.*` "reward-id"
); )
??
DEFAULT_MAINTENANCE_REWARD_ID;
const amount =
interaction.options.getInteger(
"amount"
)
??
DEFAULT_MAINTENANCE_REWARD_AMOUNT;
/*
* Safer admin default:
*
* If omitted, maintenance-reward previews
* instead of paying immediately.
*
* Pass dry-run:false explicitly to execute.
*/
const dryRun =
interaction.options.getBoolean(
"dry-run"
)
??
true;
const summary =
await grantMaintenanceReward({
guildId:
interaction.guildId,
rewardId,
amount,
dryRun
});
return interaction.editReply({
embeds: [
new EmbedBuilder()
.setTitle(
dryRun
? "🧪 Maintenance Reward Dry Run"
: "🎁 Maintenance Reward"
)
.setDescription(
dryRun
? "No Cookies were granted. Run again with `dry-run:false` to execute this reward."
: `Maintenance compensation **${rewardId}** has been processed.`
)
.addFields(
{
name:
"Reward ID",
value:
`\`${summary.rewardId}\``,
inline:
false
},
{
name:
"Per player",
value:
`**${summary.amount.toLocaleString()} 🍪**`,
inline:
true
},
{
name:
"Stored profiles",
value:
`**${summary.users}**`,
inline:
true
},
{
name:
dryRun
? "Would receive"
: "Granted",
value:
`**${dryRun ? summary.eligible : summary.granted}**`,
inline:
true
},
{
name:
"Already claimed",
value:
`**${summary.alreadyClaimed}**`,
inline:
true
},
{
name:
"Failed",
value:
`**${summary.failed}**`,
inline:
true
}
)
]
});
} }
if (
subcommand ===
"maintenance-status"
) {
const rewardId =
interaction.options.getString(
"reward-id"
)
??
DEFAULT_MAINTENANCE_REWARD_ID;
const status =
await getMaintenanceRewardStatus({
guildId:
interaction.guildId,
rewardId
});
return interaction.editReply({
embeds: [
new EmbedBuilder()
.setTitle(
"🎁 Maintenance Reward Status"
)
.addFields(
{
name:
"Reward ID",
value:
`\`${status.rewardId}\``,
inline:
false
},
{
name:
"Default amount",
value:
`**${status.amount.toLocaleString()} 🍪**`,
inline:
true
},
{
name:
"Stored profiles",
value:
`**${status.users}**`,
inline:
true
},
{
name:
"Claimed",
value:
`**${status.claimed}**`,
inline:
true
},
{
name:
"Remaining",
value:
`**${status.remaining}**`,
inline:
true
}
)
]
});
}
const audit =
await auditProfileData(
interaction.guildId
);
const issuePreview =
audit.issues
.slice(
0,
10
)
.join(
"\n"
);
return interaction.editReply({
embeds: [
new EmbedBuilder()
.setTitle(
"🔎 Profile Data Audit"
)
.addFields(
{
name:
"Stats documents",
value:
`**${audit.statDocuments}**`,
inline:
true
},
{
name:
"Achievement documents",
value:
`**${audit.achievementDocuments}**`,
inline:
true
},
{
name:
"Active achievements",
value:
`**${audit.activeAchievements}**`,
inline:
true
},
{
name:
"Global badges",
value:
`**${audit.badgeDocuments}** (${audit.claimedBadges} claimed)`,
inline:
true
},
{
name:
"Orphan achievement docs",
value:
`**${audit.orphanAchievementDocs}**`,
inline:
true
},
{
name:
"Issues",
value:
`**${audit.issueCount}**`,
inline:
true
}
)
.setDescription(
issuePreview
? `First issues:\n${issuePreview}`
: "No structural inconsistencies found."
)
]
});
} }
catch (error) {
return interaction.editReply({ console.error(
content: `[ProfileAdmin] ${subcommand} failed:`,
lines.join( error
"\n" );
)
});
} catch (error) {
console.error(
"[ProfileAdmin] Reconciliation failed:",
error
);
return interaction.editReply({ return interaction.editReply({
content: embeds: [
"Profile reconciliation failed. Check the bot logs for details." new EmbedBuilder()
}); .setTitle(
"❌ Profile Admin Error"
)
.setDescription(
"The maintenance action failed. Check the bot logs for details."
)
]
});
}
} }
} };
/*
* ============================================================
* AUDIT
* ============================================================
*/
async function runAudit(
interaction
) {
await interaction.deferReply({
flags:
MessageFlags.Ephemeral
});
try {
const result =
await auditProfileSystem(
interaction.guildId
);
const lines = [
"### 🧾 Profile System Audit",
"",
`Profile documents: **${result.profileDocuments ?? 0}**`,
`Achievement documents: **${result.achievementDocuments ?? 0}**`,
`Active achievement definitions: **${result.activeAchievements ?? 0}**`,
`Legacy achievement definitions: **${result.legacyAchievements ?? 0}**`,
`Guild badges: **${result.badges ?? 0}**`,
`Claimed badges: **${result.claimedBadges ?? 0}**`,
`Available badges: **${result.availableBadges ?? 0}**`
];
if (
Array.isArray(
result.warnings
)
&&
result.warnings.length >
0
) {
lines.push(
"",
"### ⚠️ Warnings",
...result.warnings.map(
warning =>
`• ${warning}`
)
);
}
else {
lines.push(
"",
"✅ No obvious profile-system issues were found."
);
}
return interaction.editReply({
content:
lines.join(
"\n"
)
});
} catch (error) {
console.error(
"[ProfileAdmin] Audit failed:",
error
);
return interaction.editReply({
content:
"Profile audit failed. Check the bot logs for details."
});
}
}
+1 -1
View File
@@ -16,7 +16,7 @@ module.exports = {
"records" "records"
) )
.setDescription( .setDescription(
"View Shai Cookie and Crumb Saucer records" "View Olymp Cookie and Crumb Saucer records"
) )
.addStringOption( .addStringOption(
option => option =>
+185
View File
@@ -0,0 +1,185 @@
# ShaiBot Architecture
This manual describes ShaiBot's implementation structure at a level
useful to maintainers. For exact behavior, the current code remains
authoritative.
## Runtime
`index.js` initializes the Discord client and MongoDB connection,
creates the interaction collections, initializes shared systems/indexes,
loads handlers, and logs the bot in.
Interaction modules are discovered into collections such as:
``` js
client.commands
client.legacyCommands
client.aliases
client.buttons
client.selectMenus
client.modals
```
Before manually wiring a new component into the central router, check
whether the filesystem loader already supports it.
## Preferred Layering
ShaiBot favors:
``` text
Discord command / button / select menu
↓
shared utility
↓
Mongo / economy / profile
```
Discord wrappers should remain thin. Shared rules belong in `utils/`.
A feature reachable from multiple interfaces should normally have one
authoritative implementation.
## Important Shared Utilities
Examples include:
-----------------------------------------------------------------------
Utility Responsibility
----------------------------------- -----------------------------------
`cookieEconomy.js` Cookie balances, transfers,
cooldowns, economy primitives
`crumbCollect.js` Shared Cookie collection
`crumbSlots.js` Slots
`crumbBlackjack.js` Blackjack
`crumbRoulette.js` Roulette
`cookieHeist.js` Vault Heist
`bankruptcy.js` Bankruptcy/recovery
`profileSystem.js` Profiles, achievements, badges,
activity
`profileMaintenance.js` Profile audit/reconciliation
`interactionSession.js` Shared single-owner interaction
sessions
`permissions.js` Administrator/bot-author checks
`pokerEngine.js` Pure Hold'em engine
`crumbPoker.js` Persistent Poker service
`pokerDiscord.js` Poker Discord rendering/components
`pokerProfile.js` Poker progression bridge
`crumbleStrike.js` Cooperative encounter state/combat
-----------------------------------------------------------------------
## MongoDB
Important collections include:
``` text
items_cookies
cooldown_cookies
items_games
items_special_games
stats_profiles
items_achievements
guild_badges
config_achievements
```
Indexes are part of correctness, not only performance.
ShaiBot intentionally avoids requiring multi-document MongoDB
transactions. Depending on the subsystem it instead uses:
- Atomic filtered updates
- Unique indexes
- Optimistic version checks
- Idempotency markers
- Persistent resolution state
- Compensating writes
## Concurrency
Assume users can double-click, spam controls, act simultaneously, race a
timeout, or restart the bot during a transition.
Stateful systems should answer:
``` text
What is authoritative?
Can two interactions both succeed?
Can money move twice?
What happens if the process stops after the first write?
Can the operation safely be retried?
```
Do not rely on process-local flags for correctness that must survive a
restart.
## Discord Interactions
Button visibility is never authorization.
For potentially slow stateful interactions, acknowledge Discord early
using the response style appropriate to that flow.
Do not globally defer every interaction from the central router because
different modules legitimately use `reply`, `update`, `deferReply`, or
`deferUpdate`.
Critical state should not exist only in an embed/footer.
## Permissions
Administrative access is centralized through the shared permission
utility.
Administrative access may include:
``` text
Discord Administrator
OR
BOT_AUTHOR_ID
```
Do not hard-code administrative Discord IDs.
## Deployment
Typical production workflow:
``` bash
node --check path/to/changed-file.js
pm2 restart ShaiBot
pm2 logs ShaiBot --lines 100
```
Syntax checking is useful, but economy and persistent-state changes
still require behavioral testing.
## Maintainer Checklist
Before shipping a stateful change:
- Identify the authoritative state.
- Check duplicate-click behavior.
- Check simultaneous-user behavior.
- Check insufficient-balance behavior.
- Check restart/recovery behavior.
- Check private/public information boundaries.
- Check whether profile tracking can safely fail without corrupting
settlement.
- Inspect Mongo after a controlled live test.
+168
View File
@@ -0,0 +1,168 @@
# ShaiBot Cookie Economy
This manual describes the shared Cookie economy and the rules
maintainers should preserve.
## Source of Truth
`utils/cookieEconomy.js` is the shared economy utility.
Game and command modules should not perform independent ad-hoc balance
mutations when the shared economy already provides the required
operation.
## Balances
Cookie balances live in:
``` text
items_cookies
```
Conceptually:
``` js
{
userId: "...",
cookies: 2500
}
```
Negative changes use an atomic balance filter so a player cannot spend
more Cookies than are available.
Expected insufficient-balance failures use:
``` text
INSUFFICIENT_COOKIES
```
Some subsystems carry expected error identifiers in `error.message`,
while others may also use `error.code`. User-facing formatters should
account for the convention used by that subsystem.
## Transfers
Player-to-player transfers do not require MongoDB transactions.
The safe conceptual sequence is:
``` text
atomic debit source
→ credit destination
→ compensate source if destination credit fails
```
A critical compensation failure must remain visible in logs.
## Cooldowns
Cooldowns live in:
``` text
cooldown_cookies
```
Use the shared cooldown helpers, especially atomic cooldown claiming
when double-clicks or simultaneous requests must not both succeed.
## House Vault
ShaiBot acts as the general house Cookie vault for supported games.
Gambling losses and penalties may feed the vault, while wins, heists,
and rewards may pay out from it.
House-funded features should respect their existing liquidity rules.
## Cookie Collection
`/cookies collect` and the Crumb Saucer Bakery share
`utils/crumbCollect.js`.
They must share:
- the same cooldown
- the same reward generation
- the same balance mutation
- the same profile tracking
Do not create separate collection behavior for the two interfaces.
## PvP Stealing
Normal player-to-player stealing is separate from Vault Heist.
Detailed robbery balancing lives in:
``` text
COOKIE_LOGIC.md
```
The current model includes wealth scaling, victim heat, percentage-based
loot, a hard per-hit cap, and an hourly victim exposure budget.
## Persistent Game Settlement
For simple house games, settlement should still be protected against
repeated resolution.
For lifecycle-heavy multiplayer games such as Poker, Cookie movement is
separated from internal chip movement.
Poker only crosses the Cookie economy boundary for:
``` text
buy-in
cash-out / refund
```
Ordinary Poker betting modifies the table's internal stack state, not
`items_cookies`.
## Idempotent Operations
Recovery-sensitive economy flows can use operation IDs.
Poker temporarily stores markers such as:
``` js
appliedCookieOperations: [
"poker_buyin:...",
"poker_cashout:..."
]
```
The purpose is to prevent a retry after a crash from moving money twice.
Safe lifecycle:
``` text
apply Cookie operation once
→ persist authoritative game state
→ confirm operation is durably represented
→ remove temporary marker
```
Never remove a recovery marker before the surrounding state is safe.
When the final marker is removed, unset the empty field instead of
leaving:
``` js
appliedCookieOperations: []
```
## Economy Invariants
Every economy change should preserve:
``` text
No Cookie duplication.
No unexplained Cookie loss.
No duplicate debit.
No duplicate payout.
No spending below zero.
```
Correctness and recoverability take priority over cosmetic cleanup.
+262
View File
@@ -0,0 +1,262 @@
# ShaiBot Game Manual
This document gives maintainers a compact overview of the main game
systems. Exact rules remain in the owning utilities.
# Crumb Saucer
The Crumb Saucer is ShaiBot's Cookie-powered game hub.
Shared principle:
``` text
Discord controls
→ game utility
→ Cookie economy / profile system
```
## Slots
Core utility:
``` text
utils/crumbSlots.js
```
Features include multiple wagers, symbol payouts, jackpots, All-In
tracking, Run It Back, profile statistics, achievements, and guild-first
triplet badges.
Historical replay facts must come from wager-time metadata rather than
the player's current Cookie balance.
## Blackjack
Core utility:
``` text
utils/crumbBlackjack.js
```
Supports:
- Hit
- Stand
- Double
- Dealer stands on 17
- Natural Blackjack pays 3:2
- Push
- All-In
- Run It Back
Repeated interactions must never resolve/pay the same hand twice.
## Roulette
Core utility:
``` text
utils/crumbRoulette.js
```
European Roulette uses `0–36`.
Simple bets include Red, Black, Odd, Even, and Zero. Zero loses for
Red/Black/Odd/Even.
Animation uses edits of the same message rather than high-frequency
message spam.
## Vault Heist
Core utility:
``` text
utils/cookieHeist.js
```
Vault Heist targets ShaiBot's house vault and is separate from PvP
stealing.
Approaches include Sneak, Hack, and Smash and share the same Heist
cooldown.
## Bankruptcy
Core utility:
``` text
utils/bankruptcy.js
```
Bankruptcy provides a recovery path and tracks post-Bankruptcy
rebuilding in profiles.
Recovery progress should reflect actual balance after Bankruptcy, not
merely lifetime Cookie gains.
## Run It Back
Supported games can track consecutive replay through the explicit Run It
Back action.
A normal/new wager breaks the chain.
Win/loss/push does not inherently break it because the streak represents
the player's decision to immediately replay.
Historical All-In and wager state must be preserved at the time the
wager occurs.
# Poker
Poker is a persistent 2--6 player Texas Hold'em game inside the Crumb
Saucer.
Important files:
``` text
utils/pokerEngine.js
utils/crumbPoker.js
utils/pokerDiscord.js
utils/pokerInteractions.js
utils/pokerProfile.js
handlers/poker.js
buttons/poker/*
selectMenus/poker/*
```
Current defaults:
``` text
Buy-in: 1,000 Cookies
Blinds: 10 / 20
Turn timer: 90 seconds
Pot model: single pot
```
Supported actions:
``` text
Fold
Check
Call
Bet
Raise
All-In
```
## Single-Pot Rule
Poker intentionally has no side pots.
At hand start, the maximum amount each participant can commit is limited
by the smallest participating starting stack.
Chips above that cap remain protected for a later hand.
## Persistence
MongoDB is authoritative for live/recoverable tables.
Poker uses temporary state in:
``` text
items_special_games
```
and optimistic versioning for authoritative updates.
Fully settled games are cleaned up rather than kept permanently as raw
history.
## Economy
Cookies move only at buy-in and cash-out/refund boundaries.
Betting moves internal table chips.
Recovery-sensitive economy operations are idempotent.
## Privacy
Hole cards are private.
The private Cards view may show the requesting player's cards, community
cards, turn status, and remaining turn time.
It must never expose opponent cards.
A player-facing equity/win-percentage calculator is intentionally
excluded from V1 for fairness.
## Turn / Lobby Behavior
Active turns have a 90-second deadline.
Timeout folding uses the same authoritative Fold transition as a normal
player action.
Lobby expiry is disabled while a hand is active and refreshed when a
hand ends.
The internal between-hand state may be called `NEXT_HAND`, but the
user-facing UI presents **HAND COMPLETE**.
## Cancellation / Cleanup
Host cancellation is allowed outside an active hand.
Cancellation safely settles players before deleting the table state.
Confirmation controls should disappear after Confirm or Keep so stale
buttons cannot remain usable.
# Crumble Strike
Core utility:
``` text
utils/crumbleStrike.js
```
Crumble Strike is a persistent cooperative boss battle.
Typical flow:
1. Spawn encounter.
2. Recruit players.
3. Start once requirements are met.
4. Fight within the encounter lifetime.
5. Settle success/failure and committed Cookies.
Combat includes:
``` text
Strike
Defend
Heal
Revive
Limit Break
```
Roles include:
``` text
DPS
Tank
Healer
```
Crumble Strike has more lifecycle complexity than ordinary Saucer games.
Do not copy its persistence model into simpler games unless the new
feature genuinely requires it.
# Raid Planner
Raid planning uses Discord embeds and reactions.
Participation can count unique users across reactions without forcibly
removing reactions.
Be mindful of Discord partials when changing reaction behavior.
+200
View File
@@ -0,0 +1,200 @@
# ShaiBot Profiles, Achievements & Badges
ShaiBot's profile system is the permanent progression layer behind the
economy and games.
## Central Profile System
`utils/profileSystem.js` owns the main profile/progression behavior.
Important collections:
``` text
stats_profiles
items_achievements
guild_badges
config_achievements
```
Game modules should integrate with this system instead of creating
separate progression databases.
## Profiles
Profiles can track:
- Overall game totals
- Per-game statistics
- Cookie gains and losses
- Giving and stealing
- Daily activity
- Win/loss streaks
- Weekday/time-of-day activity
- Social relationships
- Run It Back progression
- Poker history
- Achievement progress
- Badge ownership
Profiles are intended to preserve meaningful long-term history.
## Profile Events
Prefer extending established event metadata rather than inventing
parallel event systems.
Common concepts include:
``` text
game_start
game_result
cookie_gain
cookies_given
steal_success
stolen_from_me
```
New wager metadata should prefer:
``` text
wager
```
Compatibility reads for older `bet`/`previousBet` fields may remain
intentionally.
## Activity
Profile activity uses a configured timezone.
Default:
``` text
Europe/Berlin
```
Activity supports daily streaks, weekly participation, weekday counts,
and broad time buckets.
Avoid making ordinary progression depend on excessively narrow
late-night windows.
## Social Progression
Profiles can store unique relationship sets for gifting and stealing.
Use set-style updates for unique users rather than appending duplicates.
Current social progression is intentionally scaled for a relatively
small community.
## Achievements
Achievements are personal: multiple players can earn the same
achievement.
Supported models include:
### Stat-backed
Best for durable lifetime milestones and reconciliation.
### Composite
Combines multiple durable conditions.
### Event-only
Used when the accomplishment depends on exact event context that cannot
reliably be reconstructed later.
### Hidden
Used for secret/special challenges.
Event-only achievements should not be treated as historically
backfillable when the necessary event was never stored.
## Achievement Notifications
Unlock notification is centralized.
Individual games should not create competing achievement announcement
systems.
## Global Badges
Global badges are guild-unique distinctions.
The common pattern is an atomic claim against an unowned badge:
``` text
guildId
badgeId
ownerId: null
```
then setting the winner.
This prevents simultaneous candidates from both owning the same
guild-first badge.
Achievements and badges are intentionally different:
``` text
Achievement → personal; many owners
Global badge → guild-unique; one owner
```
## ID Stability
Once achievement or badge IDs may exist in MongoDB, treat them as
persistent database identifiers.
Prefer retiring an old definition over renaming/deleting an ID that
players may already own.
## Reconciliation & Audit
Administrative tooling includes:
``` text
/profileadmin audit
/profileadmin reconcile dry-run:true
```
Reconciliation can backfill durable/stat-backed accomplishments.
Event-only achievements may be skipped because historical event context
cannot be invented safely.
When changing progression schemas:
- use idempotent migrations
- preserve existing values
- preserve historical IDs
- dry-run reconciliation first
- do not fabricate data that was never tracked
## Poker History
Poker stores permanent statistics in the profile system rather than
retaining completed raw table documents.
Examples include:
- hands played/won/lost
- Cookies won/lost
- largest pot
- All-Ins
- showdowns
- action counts
- streaks
- hand-rank counters
- pocket Aces wins
- 7-2 wins
- fold wins
- full-table wins
Poker profile tracking occurs after authoritative game state succeeds. A
profile failure must never corrupt a valid pot/economy settlement.
+6 -2
View File
@@ -28,7 +28,8 @@ module.exports = {
if ( if (
interaction.isMentionableSelectMenu() || interaction.isMentionableSelectMenu() ||
interaction.isUserSelectMenu() interaction.isUserSelectMenu() ||
interaction.isStringSelectMenu()
) { ) {
return selectMenuHandler(interaction); return selectMenuHandler(interaction);
} }
@@ -174,6 +175,9 @@ async function sendInteractionError(interaction, content) {
await interaction.reply(payload); await interaction.reply(payload);
} }
} catch (error) { } catch (error) {
console.error("Failed to send interaction error response:", error); console.error(
"Failed to send interaction error response:",
error
);
} }
} }
+313
View File
@@ -0,0 +1,313 @@
const {
getPokerService
} = require("../utils/crumbPoker");
const {
refreshPokerTableMessage
} = require("../utils/pokerDiscord");
const {
announcePokerHandProgress,
createPokerProfileContext,
recordPokerHandProfiles
} = require("../utils/pokerProfile");
const TURN_CHECK_INTERVAL =
5 * 1000;
const LOBBY_CHECK_INTERVAL =
30 * 1000;
const STARTUP_RECOVERY_DELAY =
10 * 1000;
module.exports = client => {
setTimeout(
() => {
recoverPoker(
client
);
},
STARTUP_RECOVERY_DELAY
);
setInterval(
() => {
processPokerTurns(
client
);
},
TURN_CHECK_INTERVAL
);
setInterval(
() => {
processPokerLobbies(
client
);
},
LOBBY_CHECK_INTERVAL
);
console.log(
"[Poker] Recovery and timeout watcher initialized"
);
};
async function refreshResultGame(
client,
result
) {
const game =
result?.game;
if (!game) {
return;
}
await refreshPokerTableMessage(
client,
game
);
}
async function processPokerTurns(
client
) {
if (!client.isReady()) {
return;
}
try {
const results =
await getPokerService()
.processExpiredTurns();
for (const result of results) {
if (result.processed) {
console.log(
`[Poker] Auto-folded ${result.userId} after turn timeout.`
);
await refreshResultGame(
client,
result
);
if (
result.game
?.data
?.hand
?.state ===
"PAYOUT"
) {
try {
await recordPokerHandProfiles(
result.game
);
const context =
await createPokerProfileContext(
client,
result.game
);
if (context) {
await announcePokerHandProgress(
context,
result.game
);
}
}
catch (error) {
console.error(
`[PokerProfile] Timeout profile processing failed for ${result.game.gameId}:`,
error
);
}
}
}
}
}
catch (error) {
console.error(
"[Poker] Turn watcher error:",
error
);
}
}
async function processPokerLobbies(
client
) {
if (!client.isReady()) {
return;
}
try {
const results =
await getPokerService()
.processExpiredLobbies();
for (const result of results) {
if (result.expired) {
console.log(
`[Poker] Expired waiting Poker table ${result.game?.gameId ?? "unknown"}.`
);
await refreshResultGame(
client,
result
);
}
}
}
catch (error) {
console.error(
"[Poker] Lobby watcher error:",
error
);
}
}
async function recoverPoker(
client
) {
if (!client.isReady()) {
return;
}
try {
const service =
getPokerService();
const result =
await service.recover();
const activeTables =
await service.listActiveTables();
/*
* Rehydrate every still-active public Poker table after
* restart, even when no recovery action was necessary.
* Mongo remains authoritative; the Discord embed is only
* a projection of the current stored game state.
*/
for (const game of activeTables) {
try {
await refreshPokerTableMessage(
client,
game
);
if (
game.data?.hand?.state ===
"PAYOUT"
) {
await recordPokerHandProfiles(
game
);
const context =
await createPokerProfileContext(
client,
game
);
if (context) {
await announcePokerHandProgress(
context,
game
);
}
}
}
catch (error) {
console.error(
`[Poker] Failed to refresh active table ${game.gameId}:`,
error
);
}
}
for (
const turn
of result.turns ?? []
) {
if (turn.processed) {
await refreshResultGame(
client,
turn
);
}
}
for (
const lobby
of result.lobbies ?? []
) {
if (lobby.expired) {
await refreshResultGame(
client,
lobby
);
}
}
for (
const closing
of result.closingTables ?? []
) {
await refreshResultGame(
client,
closing
);
}
for (
const cashout
of result.cashouts ?? []
) {
try {
const game =
await service.getTable({
gameId:
cashout.gameId
});
await refreshPokerTableMessage(
client,
game
);
}
catch {}
}
console.log(
`[Poker] Recovery complete: ` +
`${result.memberships.length} membership(s), ` +
`${result.cashouts.length} cash-out(s), ` +
`${result.closingTables.length} closing table(s), ` +
`${result.turns.length} expired turn(s), ` +
`${result.lobbies.length} expired lobby/lobbies, ` +
`${activeTables.length} active table(s) refreshed.`
);
}
catch (error) {
console.error(
"[Poker] Startup recovery error:",
error
);
}
}
-3
View File
@@ -3,9 +3,6 @@
"version": "1.0.0", "version": "1.0.0",
"description": "", "description": "",
"main": "index.js", "main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://git.desq-gaming.de/admin_rb/ShaiBot.git" "url": "https://git.desq-gaming.de/admin_rb/ShaiBot.git"
+70
View File
@@ -0,0 +1,70 @@
const {
getPokerService
} = require("../../utils/crumbPoker");
const {
deferPokerReply,
editPokerError,
refreshPokerTableMessage,
buildOpenTableLink
} = require("../../utils/pokerDiscord");
module.exports = {
name:
"pokerJoinSelect",
async execute(
interaction
) {
await deferPokerReply(
interaction
);
const gameId =
interaction.values?.[0];
if (!gameId) {
return interaction.editReply({
content:
"❌ No Poker table was selected.",
embeds: [],
components: []
});
}
try {
const game =
await getPokerService()
.joinTable({
gameId,
guildId:
interaction.guildId,
userId:
interaction.user.id
});
await refreshPokerTableMessage(
interaction.client,
game
);
return interaction.editReply({
content:
`✅ Joined the Poker table for **${game.data.buyIn.toLocaleString()} Cookies**.`,
embeds: [],
components:
buildOpenTableLink(
game
)
});
}
catch (error) {
return editPokerError(
interaction,
error
);
}
}
};
+12
View File
@@ -166,6 +166,18 @@ async function declareBankruptcy(interaction, userId = interaction.user.id) {
userId, userId,
{ {
type: "cookie_gain", type: "cookie_gain",
source: "bankruptcy",
amount:
BANKRUPTCY_GRANT
}
);
await trackProfileEvent(
interaction,
userId,
{
type: "bankruptcy",
source: "bankruptcy",
amount: BANKRUPTCY_GRANT amount: BANKRUPTCY_GRANT
} }
); );
+308
View File
@@ -268,6 +268,311 @@ async function changeCookies(
} }
/*
* ============================================================
* IDEMPOTENT COOKIE CHANGE
* ============================================================
*
* Applies a Cookie mutation at most once for a user-scoped
* operationId. This is useful for persistent game buy-ins and
* cash-outs that may be retried after a crash or restart.
*
* The Cookie balance mutation and operation marker are written
* atomically to the same user document.
*/
async function changeCookiesOnce(
userId,
amount,
operationId
) {
if (
!Number.isSafeInteger(
amount
)
) {
throw new Error(
"INVALID_COOKIE_AMOUNT"
);
}
if (
typeof operationId !==
"string"
||
!/^[A-Za-z0-9:_-]{1,160}$/.test(
operationId
)
) {
throw new Error(
"INVALID_COOKIE_OPERATION_ID"
);
}
if (
amount ===
0
) {
return {
applied:
false,
balance:
await getCookieBalance(
userId
)
};
}
const {
cookies
} =
getCollections();
const filter = {
userId,
appliedCookieOperations: {
$ne:
operationId
}
};
if (
amount <
0
) {
filter.cookies = {
$gte:
Math.abs(
amount
)
};
}
const update = {
$inc: {
cookies:
amount
},
$addToSet: {
appliedCookieOperations:
operationId
}
};
if (
amount >
0
) {
update.$setOnInsert = {
userId
};
}
try {
const result =
await cookies.updateOne(
filter,
update,
{
upsert:
amount > 0
}
);
if (
result.modifiedCount ===
1
||
result.upsertedCount ===
1
) {
return {
applied:
true,
balance:
await getCookieBalance(
userId
)
};
}
}
catch (error) {
/*
* A concurrent positive retry can race an upsert.
* The unique userId index may reject the losing insert.
* Re-read below and treat an already-recorded operation
* as a successful idempotent retry.
*/
if (
error?.code !==
11000
) {
throw error;
}
}
const document =
await cookies.findOne(
{
userId
},
{
projection: {
cookies:
1,
appliedCookieOperations:
1
}
}
);
const operations =
Array.isArray(
document
?.appliedCookieOperations
)
? document
.appliedCookieOperations
: [];
if (
operations.includes(
operationId
)
) {
return {
applied:
false,
balance:
Math.max(
0,
Number(
document?.cookies ??
0
)
)
};
}
if (
amount <
0
) {
throw new Error(
"INSUFFICIENT_COOKIES"
);
}
throw new Error(
"COOKIE_OPERATION_FAILED"
);
}
async function clearCookieOperation(
userId,
operationId
) {
if (
typeof operationId !==
"string"
||
!/^[A-Za-z0-9:_-]{1,160}$/.test(
operationId
)
) {
throw new Error(
"INVALID_COOKIE_OPERATION_ID"
);
}
const {
cookies
} =
getCollections();
const result =
await cookies.updateOne(
{
userId
},
{
$pull: {
appliedCookieOperations:
operationId
}
}
);
/*
* Keep the Cookie document tidy once the final temporary
* idempotency marker has been cleared.
*/
await cookies.updateOne(
{
userId,
appliedCookieOperations: {
$size: 0
}
},
{
$unset: {
appliedCookieOperations:
""
}
}
);
return result.modifiedCount ===
1;
}
async function hasCookieOperation(
userId,
operationId
) {
if (
typeof operationId !==
"string"
||
!/^[A-Za-z0-9:_-]{1,160}$/.test(
operationId
)
) {
throw new Error(
"INVALID_COOKIE_OPERATION_ID"
);
}
const {
cookies
} =
getCollections();
const document =
await cookies.findOne(
{
userId,
appliedCookieOperations:
operationId
},
{
projection: {
_id:
1
}
}
);
return Boolean(
document
);
}
/* /*
* ============================================================ * ============================================================
* COOKIE TRANSFER * COOKIE TRANSFER
@@ -1188,6 +1493,9 @@ module.exports = {
getCookieBalance, getCookieBalance,
changeCookies, changeCookies,
changeCookiesOnce,
hasCookieOperation,
clearCookieOperation,
transferCookies, transferCookies,
getCooldown, getCooldown,
+20 -13
View File
@@ -24,33 +24,33 @@ const HEIST_COOLDOWN =
const HEIST_METHODS = { const HEIST_METHODS = {
Sneak: { Sneak: {
baseChance: 0.65, baseChance: 0.60,
minStealPercent: 0.01, minStealPercent: 0.01,
maxStealPercent: 0.03, maxStealPercent: 0.03,
maxStealAmount: 5000, maxStealAmount: 5000,
minPenaltyPercent: 0.01, minPenaltyPercent: 0.01,
maxPenaltyPercent: 0.04, maxPenaltyPercent: 0.04,
maxPenaltyAmount: 1500 maxPenaltyAmount: 750
}, },
Hack: { Hack: {
baseChance: 0.45, baseChance: 0.40,
minStealPercent: 0.03, minStealPercent: 0.03,
maxStealPercent: 0.06, maxStealPercent: 0.06,
maxStealAmount: 12500, maxStealAmount: 10000,
minPenaltyPercent: 0.03, minPenaltyPercent: 0.03,
maxPenaltyPercent: 0.07, maxPenaltyPercent: 0.07,
maxPenaltyAmount: 4000 maxPenaltyAmount: 2000
}, },
Smash: { Smash: {
baseChance: 0.25, baseChance: 0.20,
minStealPercent: 0.06, minStealPercent: 0.06,
maxStealPercent: 0.12, maxStealPercent: 0.12,
maxStealAmount: 25000, maxStealAmount: 15000,
minPenaltyPercent: 0.06, minPenaltyPercent: 0.06,
maxPenaltyPercent: 0.12, maxPenaltyPercent: 0.12,
maxPenaltyAmount: 10000 maxPenaltyAmount: 5000
} }
}; };
@@ -72,7 +72,7 @@ async function resolveCookieHeist(
if ( if (
type !== "cookieHeist" || type !== "cookieHeist" ||
ownerId !== ownerId !==
interaction.user.id interaction.user.id
) { ) {
return temporaryEphemeralReply( return temporaryEphemeralReply(
interaction, interaction,
@@ -85,7 +85,7 @@ async function resolveCookieHeist(
const method = const method =
HEIST_METHODS[ HEIST_METHODS[
methodName methodName
]; ];
if (!method) { if (!method) {
@@ -269,17 +269,24 @@ async function resolveCookieHeist(
} }
); );
/*
* ============================================================
* HEIST
* ============================================================
*/
await trackProfileEvent( await trackProfileEvent(
interaction, interaction,
playerId, playerId,
{ {
type: type: "vault_steal",
"vault_steal", source: "heist",
game: "heist",
result: "win",
amount amount
} }
); );
const [ const [
playerAfter, playerAfter,
vaultAfter vaultAfter
+83 -13
View File
@@ -18,7 +18,8 @@ const {
} = require("./cookieEconomy"); } = require("./cookieEconomy");
const { const {
recordGameOutcome recordGameOutcome,
trackProfileEvent
} = require("./profileSystem"); } = require("./profileSystem");
const GAME_COLLECTION = const GAME_COLLECTION =
@@ -112,7 +113,9 @@ async function startBlackjack(
interaction, interaction,
bet, bet,
allowCustomBet = false, allowCustomBet = false,
allIn = false source = "normal",
previousAllIn = false,
previousBet = 0
) { ) {
if ( if (
!allowCustomBet && !allowCustomBet &&
@@ -196,6 +199,9 @@ async function startBlackjack(
getCookieBalance(houseId) getCookieBalance(houseId)
]); ]);
const allIn =
bet === playerBalance;
if (playerBalance < bet) { if (playerBalance < bet) {
return temporaryEphemeralReply( return temporaryEphemeralReply(
interaction, interaction,
@@ -276,6 +282,11 @@ async function startBlackjack(
doubled: doubled:
false, false,
allIn, allIn,
vaultAtBet:
playerBalance,
source,
previousAllIn,
previousBet,
deck, deck,
playerCards, playerCards,
dealerCards, dealerCards,
@@ -285,6 +296,20 @@ async function startBlackjack(
await games.insertOne(game); await games.insertOne(game);
await trackProfileEvent(
interaction,
playerId,
{
type: "game_start",
game: "blackjack",
source,
wager: bet,
allIn,
previousAllIn,
previousBet
}
);
const playerBlackjack = const playerBlackjack =
isBlackjack(playerCards); isBlackjack(playerCards);
@@ -370,7 +395,7 @@ async function startBlackjackAllIn(
interaction, interaction,
balance, balance,
true, true,
true "all_in"
); );
} }
@@ -405,6 +430,9 @@ async function runBlackjackBack(
const bet = const bet =
Number(parts[2]); Number(parts[2]);
const previousAllIn =
parts[3] === "1";
if ( if (
ownerId !== ownerId !==
interaction.user.id interaction.user.id
@@ -435,7 +463,9 @@ async function runBlackjackBack(
interaction, interaction,
bet, bet,
true, true,
false "run_it_back",
previousAllIn,
bet
); );
} }
@@ -803,6 +833,32 @@ async function finishBlackjack(
game, game,
result result
) { ) {
const { db } = getCollections();
const claim = await db
.collection(GAME_COLLECTION)
.updateOne(
{
gameId: game.gameId,
state: "Playing"
},
{
$set: {
state: "Resolving"
}
}
);
if (claim.modifiedCount !== 1) {
return temporaryEphemeralReply(
interaction,
{
content:
"This Blackjack hand is already being resolved."
}
);
}
const houseId = const houseId =
interaction.client.user.id; interaction.client.user.id;
@@ -845,6 +901,23 @@ async function finishBlackjack(
`[Blackjack] House cannot cover payout ${payout} for ${game.userId}` `[Blackjack] House cannot cover payout ${payout} for ${game.userId}`
); );
await db
.collection(GAME_COLLECTION)
.updateOne(
{
gameId: game.gameId,
state: "Resolving"
},
{
$set: {
state: "Finished",
result: "PayoutError",
payout: 0,
finishedAt: getUnixTime()
}
}
);
return interaction.update({ return interaction.update({
embeds: [ embeds: [
new EmbedBuilder() new EmbedBuilder()
@@ -856,7 +929,7 @@ async function finishBlackjack(
) )
.setFooter({ .setFooter({
text: text:
`crumbBlackjackResult:${game.userId}:${game.originalBet}` `crumbBlackjackResult:${game.userId}:${game.originalBet}:${game.allIn ? 1 : 0}`
}) })
], ],
components: components:
@@ -871,9 +944,6 @@ async function finishBlackjack(
); );
} }
const { db } =
getCollections();
await db await db
.collection( .collection(
GAME_COLLECTION GAME_COLLECTION
@@ -883,7 +953,7 @@ async function finishBlackjack(
gameId: gameId:
game.gameId, game.gameId,
state: state:
"Playing" "Resolving"
}, },
{ {
$set: { $set: {
@@ -1010,7 +1080,7 @@ async function finishBlackjack(
) )
.setFooter({ .setFooter({
text: text:
`crumbBlackjackResult:${game.userId}:${game.originalBet}` `crumbBlackjackResult:${game.userId}:${game.originalBet}:${game.allIn ? 1 : 0}`
}); });
return interaction.update({ return interaction.update({
@@ -1258,9 +1328,9 @@ function shuffleDeck(
deck[i], deck[i],
deck[j] deck[j]
] = [ ] = [
deck[j], deck[j],
deck[i] deck[i]
]; ];
} }
} }
+9 -8
View File
@@ -87,14 +87,15 @@ async function collectCookies(
); );
await trackProfileEvent( await trackProfileEvent(
interaction, interaction,
userId, userId,
{ {
type: "cookie_gain", type: "cookie_gain",
amount source: "collect",
} amount
); }
);
const balance = await getCookieBalance( const balance = await getCookieBalance(
+3148
View File
File diff suppressed because it is too large Load Diff
+41 -10
View File
@@ -12,7 +12,8 @@ const {
} = require("./cookieEconomy"); } = require("./cookieEconomy");
const { const {
recordGameOutcome recordGameOutcome,
trackProfileEvent
} = require("./profileSystem"); } = require("./profileSystem");
const ROULETTE_BETS = [ const ROULETTE_BETS = [
@@ -206,7 +207,10 @@ async function startRouletteAllIn(
async function showRouletteChoices( async function showRouletteChoices(
interaction, interaction,
bet, bet,
allIn = false requestedAllIn = false,
source = "normal",
previousAllIn = false,
previousBet = 0
) { ) {
if ( if (
!Number.isSafeInteger(bet) || !Number.isSafeInteger(bet) ||
@@ -262,7 +266,7 @@ async function showRouletteChoices(
}) })
.setFooter({ .setFooter({
text: text:
`crumbRouletteBet:${interaction.user.id}:${bet}:${allIn ? 1 : 0}` `crumbRouletteBet:${interaction.user.id}:${bet}:${requestedAllIn ? 1 : 0}:${source}:${previousAllIn ? 1 : 0}:${previousBet}`
}); });
return interaction.update({ return interaction.update({
@@ -303,6 +307,9 @@ async function runRouletteBack(
const bet = const bet =
Number(parts[2]); Number(parts[2]);
const previousAllIn =
parts[3] === "1";
if ( if (
ownerId !== ownerId !==
interaction.user.id interaction.user.id
@@ -332,7 +339,10 @@ async function runRouletteBack(
return showRouletteChoices( return showRouletteChoices(
interaction, interaction,
bet, bet,
false false,
"run_it_back",
previousAllIn,
bet
); );
} }
@@ -383,8 +393,14 @@ async function playRoulette(
const bet = const bet =
Number(parts[2]); Number(parts[2]);
const allIn = const source =
parts[3] === "1"; parts[4] || "normal";
const previousAllIn =
parts[5] === "1";
const previousBet =
Number(parts[6] ?? 0);
if ( if (
ownerId !== ownerId !==
@@ -476,6 +492,23 @@ async function playRoulette(
throw error; throw error;
} }
const allIn =
bet === playerBalance;
await trackProfileEvent(
interaction,
playerId,
{
type: "game_start",
game: "roulette",
source,
wager: bet,
allIn,
previousAllIn,
previousBet
}
);
await interaction.update({ await interaction.update({
embeds: [ embeds: [
buildSpinEmbed( buildSpinEmbed(
@@ -594,9 +627,7 @@ async function playRoulette(
won && won &&
choiceKey === choiceKey ===
"Zero", "Zero",
allIn: allIn
won &&
allIn
} }
); );
@@ -664,7 +695,7 @@ async function playRoulette(
) )
.setFooter({ .setFooter({
text: text:
`crumbRouletteResult:${playerId}:${bet}` `crumbRouletteResult:${playerId}:${bet}:${allIn ? 1 : 0}`
}); });
return interaction.editReply({ return interaction.editReply({
+197 -52
View File
@@ -14,48 +14,88 @@ const {
requireInteractionSession requireInteractionSession
} = require("./interactionSession"); } = require("./interactionSession");
async function showCrumbSaucer(interaction) {
if (interaction.isButton()) { async function showCrumbSaucer(
const session = await requireInteractionSession(interaction); interaction
) {
if (
interaction.isButton()
) {
const session =
await requireInteractionSession(
interaction
);
if (!session) { if (!session) {
return; return;
} }
const balance = await getCookieBalance(interaction.user.id); const balance =
const embed = buildMainMenuEmbed(interaction.user, balance); await getCookieBalance(
interaction.user.id
);
const embed =
buildMainMenuEmbed(
interaction.user,
balance
);
return interaction.update({ return interaction.update({
embeds: [embed], embeds: [
components: buildMainMenuButtons() embed
],
components:
buildMainMenuButtons()
}); });
} }
const balance = await getCookieBalance(interaction.user.id); const balance =
const embed = buildMainMenuEmbed(interaction.user, balance); await getCookieBalance(
interaction.user.id
);
const embed =
buildMainMenuEmbed(
interaction.user,
balance
);
await interaction.reply({ await interaction.reply({
embeds: [embed], embeds: [
components: buildMainMenuButtons() embed
],
components:
buildMainMenuButtons()
}); });
const message = await interaction.fetchReply(); const message =
await interaction.fetchReply();
await createInteractionSession( await createInteractionSession(
interaction, interaction,
{ {
messageId: message.id, messageId:
ownerId: interaction.user.id, message.id,
kind: "crumbSaucer" ownerId:
interaction.user.id,
kind:
"crumbSaucer"
} }
); );
return message; return message;
} }
function buildMainMenuEmbed(user, balance) {
function buildMainMenuEmbed(
user,
balance
) {
return new EmbedBuilder() return new EmbedBuilder()
.setTitle("🎰 The Crumb Saucer") .setTitle(
"🎰 The Crumb Saucer"
)
.setDescription( .setDescription(
[ [
`Welcome, ${user}!`, `Welcome, ${user}!`,
@@ -75,6 +115,9 @@ function buildMainMenuEmbed(user, balance) {
"### 🎡 Roulette", "### 🎡 Roulette",
"Bet on Red, Black, Odd, Even, or Zero.", "Bet on Red, Black, Odd, Even, or Zero.",
"", "",
"### ♠️ Poker",
"Create or join a 2–6 player Cookie Poker table.",
"",
"### 🏦 Vault Heist", "### 🏦 Vault Heist",
"Attempt to breach ShaiBot's Cookie Vault.", "Attempt to breach ShaiBot's Cookie Vault.",
"", "",
@@ -83,71 +126,172 @@ function buildMainMenuEmbed(user, balance) {
].join("\n") ].join("\n")
) )
.addFields({ .addFields({
name: "Your Vault", name:
value: `**${balance.toLocaleString()} 🍪**` "Your Vault",
value:
`**${balance.toLocaleString()} 🍪**`
}) })
.setFooter({ .setFooter({
text: `crumbSaucer:${user.id}` text:
`crumbSaucer:${user.id}`
}); });
} }
function buildMainMenuButtons() { function buildMainMenuButtons() {
return [ return [
new ActionRowBuilder() new ActionRowBuilder()
.addComponents( .addComponents(
new ButtonBuilder() new ButtonBuilder()
.setCustomId("crumbSaucerSlots") .setCustomId(
.setLabel("Slots") "crumbSaucerSlots"
.setEmoji("🎰") )
.setStyle(ButtonStyle.Primary), .setLabel(
"Slots"
)
.setEmoji(
"🎰"
)
.setStyle(
ButtonStyle.Primary
),
new ButtonBuilder() new ButtonBuilder()
.setCustomId("crumbSaucerBlackjack") .setCustomId(
.setLabel("Blackjack") "crumbSaucerBlackjack"
.setEmoji("🃏") )
.setStyle(ButtonStyle.Success), .setLabel(
"Blackjack"
)
.setEmoji(
"🃏"
)
.setStyle(
ButtonStyle.Primary
),
new ButtonBuilder() new ButtonBuilder()
.setCustomId("crumbSaucerRoulette") .setCustomId(
.setLabel("Roulette") "crumbSaucerRoulette"
.setEmoji("🎡") )
.setStyle(ButtonStyle.Primary), .setLabel(
"Roulette"
)
.setEmoji(
"🎡"
)
.setStyle(
ButtonStyle.Primary
),
new ButtonBuilder() new ButtonBuilder()
.setCustomId("crumbSaucerHeist") .setCustomId(
.setLabel("Vault Heist") "crumbSaucerPoker"
.setEmoji("🏦") )
.setStyle(ButtonStyle.Danger) .setLabel(
"Poker"
)
.setEmoji(
"♠️"
)
.setStyle(
ButtonStyle.Primary
),
new ButtonBuilder()
.setCustomId(
"crumbSaucerHeist"
)
.setLabel(
"Vault Heist"
)
.setEmoji(
"🏦"
)
.setStyle(
ButtonStyle.Danger
)
), ),
new ActionRowBuilder() new ActionRowBuilder()
.addComponents( .addComponents(
new ButtonBuilder() new ButtonBuilder()
.setCustomId("crumbSaucerCollectMenu") .setCustomId(
.setLabel("Cookie Bakery") "crumbSaucerCollectMenu"
.setEmoji("🍪") )
.setStyle(ButtonStyle.Success), .setLabel(
"Cookie Bakery"
)
.setEmoji(
"🍪"
)
.setStyle(
ButtonStyle.Secondary
),
new ButtonBuilder() new ButtonBuilder()
.setCustomId("crumbSaucerBankruptcy") .setCustomId(
.setLabel("Bankruptcy") "crumbSaucerBankruptcy"
.setEmoji("🛟") )
.setStyle(ButtonStyle.Secondary), .setLabel(
"Bankruptcy"
)
.setEmoji(
"🛟"
)
.setStyle(
ButtonStyle.Secondary
),
new ButtonBuilder() new ButtonBuilder()
.setCustomId("sessionClose") .setCustomId(
.setLabel("Close") "crumbSaucerProfile"
.setEmoji("✖️") )
.setStyle(ButtonStyle.Secondary) .setLabel(
"Profile"
)
.setEmoji(
"👤"
)
.setStyle(
ButtonStyle.Secondary
),
new ButtonBuilder()
.setCustomId(
"sessionClose"
)
.setLabel(
"Close"
)
.setEmoji(
"✖️"
)
.setStyle(
ButtonStyle.Danger
)
) )
]; ];
} }
function getCrumbSaucerSessionOwner(interaction) {
const footer = interaction.message?.embeds?.[0]?.footer?.text;
const parts = footer?.split(":") ?? [];
switch (parts[0]) { function getCrumbSaucerSessionOwner(
interaction
) {
const footer =
interaction.message
?.embeds?.[0]
?.footer
?.text;
const parts =
footer?.split(":") ?? [];
switch (
parts[0]
) {
case "crumbSaucer": case "crumbSaucer":
case "crumbSaucerCollect": case "crumbSaucerCollect":
case "crumbSaucerSlots": case "crumbSaucerSlots":
@@ -168,6 +312,7 @@ function getCrumbSaucerSessionOwner(interaction) {
} }
} }
module.exports = { module.exports = {
showCrumbSaucer, showCrumbSaucer,
buildMainMenuEmbed, buildMainMenuEmbed,
+27 -3
View File
@@ -13,7 +13,8 @@ const {
} = require("./cookieEconomy"); } = require("./cookieEconomy");
const { const {
recordGameOutcome recordGameOutcome,
trackProfileEvent
} = require("./profileSystem"); } = require("./profileSystem");
const SLOT_BETS = [ const SLOT_BETS = [
@@ -104,7 +105,10 @@ async function showSlots(interaction) {
async function playSlots( async function playSlots(
interaction, interaction,
bet bet,
source = "normal",
previousAllIn = false,
previousBet = 0
) { ) {
const ownerId = const ownerId =
getSlotsSessionOwner( getSlotsSessionOwner(
@@ -197,6 +201,21 @@ async function playSlots(
throw error; throw error;
} }
await trackProfileEvent(
interaction,
playerId,
{
type: "game_start",
game: "slots",
source,
wager: bet,
allIn:
bet === playerBalance,
previousAllIn,
previousBet
}
);
await interaction.update({ await interaction.update({
embeds: [ embeds: [
buildSpinningEmbed( buildSpinningEmbed(
@@ -321,6 +340,10 @@ async function playSlots(
? "loss" ? "loss"
: "push", : "push",
profit, profit,
triplet:
outcome.type === "triple"
? outcome.symbol
: null,
jackpot: jackpot:
outcome.type === outcome.type ===
"triple" && "triple" &&
@@ -460,7 +483,8 @@ async function runSlotsBack(
return playSlots( return playSlots(
interaction, interaction,
bet bet,
"run_it_back"
); );
} }
+38 -151
View File
@@ -1,118 +1,46 @@
const { const {
PermissionFlagsBits, PermissionFlagsBits,
MessageFlags MessageFlags
} = require( } = require("discord.js");
"discord.js"
);
/*
* ============================================================
* CONFIG
* ============================================================
*
* .env:
*
* BOT_AUTHOR_ID=123456789012345678
*
* Do not hard-code the author ID into commands.
*/
function getBotAuthorId() { function getBotAuthorId() {
return ( return process.env.BOT_AUTHOR_ID ?? null;
process.env.BOT_AUTHOR_ID
??
null
);
} }
/*
* ============================================================
* BOT AUTHOR
* ============================================================
*/
function isBotAuthor( function isBotAuthor(
userId userId
) { ) {
const authorId = const authorId =
getBotAuthorId(); getBotAuthorId();
return Boolean(
if ( authorId &&
!authorId userId &&
|| String(userId) === String(authorId)
!userId
) {
return false;
}
return (
String(
userId
)
===
String(
authorId
)
); );
} }
/*
* ============================================================
* GUILD ADMINISTRATOR
* ============================================================
*/
function isAdministrator( function isAdministrator(
interaction interaction
) { ) {
if ( return (
!interaction interaction
?.memberPermissions ?.memberPermissions
) { ?.has(
return false; PermissionFlagsBits.Administrator
} )
??
false
return interaction );
.memberPermissions
.has(
PermissionFlagsBits.Administrator
);
} }
/*
* ============================================================
* ADMIN COMMAND ACCESS
* ============================================================
*
* Access is granted when:
*
* - the user is the configured bot author
* OR
* - the user has Discord Administrator
*
* Bot author is checked first so the owner can use admin
* utilities even without Discord Administrator in the guild.
*/
function canUseAdminCommands( function canUseAdminCommands(
interaction interaction
) { ) {
if (
!interaction
?.user
?.id
) {
return false;
}
return ( return (
isBotAuthor( isBotAuthor(
interaction.user.id interaction.user.id
@@ -125,57 +53,6 @@ function canUseAdminCommands(
} }
/*
* ============================================================
* STANDARD ACCESS DENIAL
* ============================================================
*
* Administrative access failures are intentionally ephemeral.
*/
async function denyAdminAccess(
interaction,
message =
"You don't have permission to use this command."
) {
const payload = {
content:
message,
flags:
MessageFlags.Ephemeral
};
if (
interaction.replied
||
interaction.deferred
) {
return interaction.followUp(
payload
);
}
return interaction.reply(
payload
);
}
/*
* ============================================================
* REQUIRE ADMIN ACCESS
* ============================================================
*
* Convenience helper:
*
* if (!await requireAdminAccess(interaction)) {
* return;
* }
*/
async function requireAdminAccess( async function requireAdminAccess(
interaction interaction
) { ) {
@@ -188,29 +65,39 @@ async function requireAdminAccess(
} }
await denyAdminAccess( const payload = {
interaction content:
); "You don't have permission to use this command.",
flags:
MessageFlags.Ephemeral
};
if (
interaction.replied ||
interaction.deferred
) {
await interaction.followUp(
payload
);
}
else {
await interaction.reply(
payload
);
}
return false; return false;
} }
/*
* ============================================================
* EXPORTS
* ============================================================
*/
module.exports = { module.exports = {
getBotAuthorId, getBotAuthorId,
isBotAuthor, isBotAuthor,
isAdministrator, isAdministrator,
canUseAdminCommands, canUseAdminCommands,
requireAdminAccess, requireAdminAccess
denyAdminAccess
}; };
File diff suppressed because it is too large Load Diff
+2149
View File
File diff suppressed because it is too large Load Diff
+198
View File
@@ -0,0 +1,198 @@
const {
getPokerService
} = require("./crumbPoker");
const {
deferPokerReply,
editPokerError,
getPokerGameIdFromInteraction,
refreshPokerTableMessage
} = require("./pokerDiscord");
const {
announcePokerHandProgress
} = require("./pokerProfile");
async function executePokerAction(
interaction,
action,
successText
) {
await deferPokerReply(
interaction
);
const gameId =
getPokerGameIdFromInteraction(
interaction
);
if (!gameId) {
return interaction.editReply({
content:
"❌ This Poker control is no longer attached to an active table.",
embeds: [],
components: []
});
}
try {
const service =
getPokerService();
const game =
await service.act({
gameId,
userId:
interaction.user.id,
action
});
await refreshPokerTableMessage(
interaction.client,
game
);
try {
await announcePokerHandProgress(
interaction,
game
);
}
catch (error) {
console.error(
`[PokerProfile] Failed to announce completed hand ${game.gameId}:`,
error
);
}
return interaction.editReply({
content:
typeof successText ===
"function"
? successText(game)
: successText,
embeds: [],
components: []
});
}
catch (error) {
return editPokerError(
interaction,
error
);
}
}
async function executeMinimumRaise(
interaction
) {
await deferPokerReply(
interaction
);
const gameId =
getPokerGameIdFromInteraction(
interaction
);
if (!gameId) {
return interaction.editReply({
content:
"❌ This Poker control is no longer attached to an active table.",
embeds: [],
components: []
});
}
try {
const service =
getPokerService();
const legal =
await service.getLegalPlayerActions({
gameId,
userId:
interaction.user.id
});
const type =
legal.actions?.includes(
"bet"
)
? "bet"
: legal.actions?.includes(
"raise"
)
? "raise"
: null;
if (
!type
||
!Number.isSafeInteger(
legal.minRaiseTo
)
) {
return interaction.editReply({
content:
"❌ A bet or raise is not available right now.",
embeds: [],
components: []
});
}
const game =
await service.act({
gameId,
userId:
interaction.user.id,
action: {
type,
amount:
legal.minRaiseTo
}
});
await refreshPokerTableMessage(
interaction.client,
game
);
try {
await announcePokerHandProgress(
interaction,
game
);
}
catch (error) {
console.error(
`[PokerProfile] Failed to announce completed hand ${game.gameId}:`,
error
);
}
return interaction.editReply({
content:
`✅ ${type === "bet" ? "Bet" : "Raised to"} ${legal.minRaiseTo.toLocaleString()} 🍪`,
embeds: [],
components: []
});
}
catch (error) {
return editPokerError(
interaction,
error
);
}
}
module.exports = {
executePokerAction,
executeMinimumRaise
};
File diff suppressed because it is too large Load Diff
+1479 -112
View File
File diff suppressed because it is too large Load Diff
+2779 -1991
View File
File diff suppressed because it is too large Load Diff