Skip to content

Resolve PR #2 review comments: startup, reminders, callbacks, and persistence - #3

Merged
gamblecodezcom merged 2 commits into
mainfrom
codex/main-0h114g
Feb 19, 2026
Merged

Resolve PR #2 review comments: startup, reminders, callbacks, and persistence#3
gamblecodezcom merged 2 commits into
mainfrom
codex/main-0h114g

Conversation

@gamblecodezcom

@gamblecodezcom gamblecodezcom commented Feb 19, 2026

Copy link
Copy Markdown
Owner

User description

Motivation

  • Harden bot startup so bot.launch() is awaited and failures are handled explicitly to avoid unhandled rejections and silent crashes.
  • Prevent incorrect reminder/callback/flow behavior observed in review (stale pending flows, hanging Telegram spinners, duplicate auto-completion, invalid image URLs, and reminders to locked users).
  • Improve operational reliability by adding durable state persistence and safer broadcast/winner selection primitives.

Description

  • Replaced unawaited bot.launch() with an async startBot() that calls loadStateSafe(), restores giveaway timers, await bot.launch(), logs success, and process.exit(1) on startup failure.
  • Added JSON-backed persistence (bot_state.json) with Map/Set serialization/deserialization for userStore, promoStore, and giveawayStore, plus periodic flush (every 5s) and save-on-shutdown hooks (SIGINT/SIGTERM) and restore logic for running giveaways.
  • Fixed weekly reminder eligibility by excluding users with user.wagerBonus.notifyAttempts >= 3 so locked users are no longer re-reminded.
  • Added safe callback answering helper answerCbSafe(ctx, ...) and applied it to regex callback handlers that have early-return paths so ctx.answerCbQuery() is always invoked before returning.
  • Improved pending-action hygiene by adding beginPendingAction() which clears any prior pendingAction before starting a new multi-step flow and a /cancel command to clear stale flows.
  • Adjusted walkthrough behavior by removing automatic marking of steps on render (completion only via walk_done) and made image sends robust by validating URLs (isValidHttpUrl) and falling back to text on errors.
  • Hardened giveaway handling: gw_cancel_yes now clears all scheduled reminder timers and empties giveaway.reminders; restore routines re-schedule reminders and timers on startup.
  • Made broadcast delivery robust with pacing (~35ms), 429-aware retry/backoff logic, and admin logging of success/failure counts; replaced Math.random() with crypto.randomInt in pickRandomUnique for secure randomness.
  • Added small infrastructure: bot.use() middleware to ensure users are loaded and markStateDirty() tracking to minimize unnecessary writes.

Testing

  • Ran static syntax check with node --check index.js which completed successfully.
  • Verified the specific review items in-source (startup await, reminder gating, callback answerCbQuery paths, walkthrough marking and image fallback, pending-action clearing, giveaway reminder cleanup, broadcast rate-limiting, and randomInt usage) by updating and re-checking the file.
  • No runtime/integration Telegram tests were executed as part of this change; recommend validation in a staging bot with a valid BOT_TOKEN and ADMIN_IDS to exercise DM delivery, callback interactions, scheduled reminders, and persistence restore behavior.

Codex Task

Summary by CodeRabbit

  • New Features
    • Telegram bot with user account creation and verification flows
    • Promo code distribution, tracking, and redemption system
    • Giveaway platform with eligibility verification and random winner selection
    • Admin controls for giveaway management, editing, and moderation
    • Automated countdown reminders for active giveaways
    • Persistent data storage with backup and recovery
    • Interactive walkthrough tutorial with image support

CodeAnt-AI Description

Persist bot state to survive restarts and fix reminder/callback/workflow reliability

What Changed

  • Bot now saves user, promo, and giveaway state to disk and restores running giveaways and timers on restart so user progress and active giveaways survive process restarts.
  • Weekly wager reminders skip users locked by repeated attempts or who opted out, preventing repeated reminder spam to the same users.
  • Pending multi-step flows are managed and can be cancelled with /cancel; starting a new flow clears any stale pending action so users no longer get stuck in old flows.
  • Callback handlers always attempt to acknowledge the Telegram callback safely to avoid hanging spinners when handlers return early.
  • Walkthrough steps no longer auto-mark complete on render; marking is explicit and images are validated so broken image links fall back to text.
  • Giveaways: admin cancel clears scheduled reminders and timers; reminders are re-scheduled on startup; finalization posts winners and DMs winners reliably.
  • Admin broadcasts are paced and include retry/backoff for rate limits, with admin logging of sent/failed counts to surface delivery failures.
  • Random winner selection uses secure randomness for fair selection.

Impact

✅ Durable user state across restarts
✅ Fewer repeated reminder messages to locked users
✅ Clearer broadcast delivery results and fewer hanging Telegram spinners

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

@codeant-ai

codeant-ai Bot commented Feb 19, 2026

Copy link
Copy Markdown

CodeAnt AI is reviewing your PR.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@coderabbitai

coderabbitai Bot commented Feb 19, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@gamblecodezcom has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 19 minutes and 2 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📝 Walkthrough

Walkthrough

A comprehensive Telegram bot implementation using Telegraf is introduced with full-featured functionality including user management, promo codes, giveaways with eligibility checks, admin controls, state persistence, and periodic task scheduling. The bot enforces verification flows, tracks user participation, and stores state to a JSON file.

Changes

Cohort / File(s) Summary
Telegram Bot Implementation
index.js
Complete bot engine with user profile management, in-memory state stores, inline keyboards for UI flows, command handlers (start, help, walkthrough, admin), giveaway lifecycle management with eligibility validation and winner selection, promo claim handling, admin broadcasting with retry logic, and persistent state recovery with timer restoration.

Sequence Diagrams

sequenceDiagram
    participant User as Telegram User
    participant Bot as Bot (Telegraf)
    participant State as State Store
    participant File as bot_state.json
    
    User->>Bot: /start command
    Bot->>State: Check if user exists
    alt User not in system
        Bot->>State: Create default user profile
        Bot->>Bot: Present age gate keyboard
    else User exists
        Bot->>Bot: Show main menu keyboard
    end
    State->>File: Mark state dirty (scheduled persist)
    Bot->>User: Send welcome message with keyboard
Loading
sequenceDiagram
    participant Admin as Admin User
    participant Bot as Bot (Telegraf)
    participant State as State Store
    participant User as Participant User
    participant File as bot_state.json
    
    Admin->>Bot: /admin_giveaway_create
    Bot->>Admin: Request giveaway details (pending action)
    Admin->>Bot: Provide title, description, duration
    Bot->>State: Create giveaway, schedule expiry timer
    State->>File: Persist giveaway entry
    Bot->>Admin: Confirm creation
    
    loop Participant Flow
        User->>Bot: Click "Join Giveaway" button
        Bot->>State: Check eligibility (linked username, joins, age, verification, promos, walkthrough)
        alt Eligible
            Bot->>State: Add user to giveaway participants
            Bot->>User: Confirm participation
        else Not Eligible
            Bot->>User: Show eligibility failure reason
        end
    end
    
    loop Countdown Phase
        Bot->>Bot: Scheduled reminder at T-1h, T-10m
        Bot->>User: Send participation reminders
    end
    
    Bot->>Bot: Giveaway expires (timer fires)
    Bot->>State: Select random unique winner from participants
    Bot->>User: Notify winner
    Bot->>Admin: Notify admin of giveaway completion
    State->>File: Finalize and persist giveaway result
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Poem

🐰 A telegram hopper with state so neat,
Giveaways, promos, and users to greet!
From /start to the winner's crown,
This bot hops the town up and down! 🎉

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 3.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly references the PR objectives: resolving review comments from PR #2 across startup, reminders, callbacks, and persistence—all major changes documented in the PR summary.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/main-0h114g

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codeant-ai codeant-ai Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files label Feb 19, 2026
Comment thread index.js
{ title: '1) First Time Setup Wizard', body: 'Use /start, pass age gate, and open the main menu.' },
{ title: '2) Create Runewager Account', body: `Open signup link and create your account: ${LINKS.runewagerSignup}` },
{ title: '3) Generate Discord Verification Code', body: 'Go to Profile → Generate Code in Runewager.', imageUrl: DISCORD_CODE_GENERATION_IMAGE_URL },
{ title: '4) Verify in Discord', body: `Join Runewager Discord and post code in #web-link channel:\n${LINKS.runewagerDiscord}\n${LINKS.discordWebLink}`, imageUrl: DISCORD_VERIFY_IMAGE_URL },

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: The walkthrough step text hardcodes a specific promo code from promoStore.code, but admins can later change the promo via the admin panel, leading to stale and incorrect instructions for users; removing the hardcoded code from the walkthrough and referring generically to the current promo code avoids this mismatch. [logic error]

Severity Level: Major ⚠️
- ⚠️ Walkthrough step can display outdated promo code instructions.
- ⚠️ New users may follow wrong promo setup guidance.
Suggested change
{ title: '4) Verify in Discord', body: `Join Runewager Discord and post code in #web-link channel:\n${LINKS.runewagerDiscord}\n${LINKS.discordWebLink}`, imageUrl: DISCORD_VERIFY_IMAGE_URL },
{ title: '5) Enter Promo Code', body: 'Open promo input page and enter the current promo code shown in the bot.', imageUrl: PROMO_ENTRY_IMAGE_URL },
Steps of Reproduction ✅
1. Start the bot with `node index.js`; on startup `buildWalkthroughCatalog()` at
`index.js:1536-1572` runs once and populates `walkthroughCatalog` (defined at
`index.js:215`) with step 5 text using the initial `promoStore.code` value defined at
`index.js:56-64`.

2. As an admin (ID present in `ADMIN_IDS`), run `/admin` in any chat to open the admin
keyboard via the handler at `index.js:495-501`, then tap "✏️ Edit Promo Code" which
triggers `admin_edit_code` at `index.js:782-789`.

3. Respond with a new promo code string and confirm via the "✅ Confirm" button handled by
`admin_edit_code_yes` at `index.js:1448-1455`, which updates `promoStore.code` to the new
value while leaving the already-constructed `walkthroughCatalog` unchanged.

4. As a regular user, run `/walkthrough` (handler at `index.js:481-485`) or tap "🧭 Guided
Walkthrough" (callback `menu_walkthrough` at `index.js:748-754`), causing
`sendWalkthroughStep()` at `index.js:1508-1533` to render step 5 with the stale hardcoded
body using the old promo code, while current promo flows such as `menu_claim_bonus` at
`index.js:605-637` display the updated `promoStore.code`, leading to conflicting
instructions.
Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** index.js
**Line:** 1540:1540
**Comment:**
	*Logic Error: The walkthrough step text hardcodes a specific promo code from `promoStore.code`, but admins can later change the promo via the admin panel, leading to stale and incorrect instructions for users; removing the hardcoded code from the walkthrough and referring generically to the current promo code avoids this mismatch.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
👍 | 👎

@codeant-ai

codeant-ai Bot commented Feb 19, 2026

Copy link
Copy Markdown

CodeAnt AI finished reviewing your PR.

@gamblecodezcom
gamblecodezcom merged commit 839de56 into main Feb 19, 2026
@gamblecodezcom
gamblecodezcom deleted the codex/main-0h114g branch February 19, 2026 23:50
gamblecodezcom added a commit that referenced this pull request Feb 20, 2026
Audit PR #3 merge and fix walkthrough promo-code staleness
@gamblecodezcom
gamblecodezcom restored the codex/main-0h114g branch February 20, 2026 00:15
@gamblecodezcom
gamblecodezcom deleted the codex/main-0h114g branch February 20, 2026 05:02
gamblecodezcom added a commit that referenced this pull request Feb 20, 2026
Resolve PR #2 review comments: startup, reminders, callbacks, and persistence
gamblecodezcom added a commit that referenced this pull request Feb 20, 2026
Audit PR #3 merge and fix walkthrough promo-code staleness
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

codex size:XXL This PR changes 1000+ lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant