fix(moderation): improve autodeleter resilience and DB connection stability#308
Conversation
…bility Rewrite the autodeleter background loop to eliminate Discord API rate limiting (error 40062). Recent messages (< 14 days) are now bulk-deleted via channel.delete_messages() — up to 100 per API call instead of one at a time. Older messages are individually deleted with a 1 s sleep and capped at 50 per tick so each loop iteration stays under ~1 minute. Per-channel errors no longer abort the whole tick; a 429 from any channel logs a warning and skips remaining channels for that run. Also add pool_pre_ping=True to the SQLAlchemy engine so stale connections from a DB restart are transparently recycled before use. Co-Authored-By: Claude <noreply@anthropic.com>
|
Warning Rate limit exceeded
⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the 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. ℹ️ Review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughEngine creation now uses Changes
Estimated Code Review Effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@NerdyPy/modules/moderation.py`:
- Around line 175-183: The inner except blocks that catch HTTPException around
m.thread.delete() currently swallow all HTTP errors; update both occurrences
(the loop over bulk where you call m.thread.delete() and the second similar
thread-delete block) to detect rate-limit responses and re-raise them: in each
except HTTPException as e, if getattr(e, "status", None) == 429 or (hasattr(e,
"response") and e.response is not None and e.response.status == 429) then raise
e, otherwise continue to swallow/ignore; keep the existing asyncio.sleep and
non-429 handling unchanged so rate-limit errors propagate to the outer handler
that enforces stopping.
- Around line 152-158: The fetch window logic currently grabs the oldest
fetch_limit messages and then preserves the newest message_limit within that
truncated slice; change the history fetch to retrieve newest-first (use
channel.history(..., oldest_first=False) or remove oldest_first=True) so
candidates contains newest messages first, then compute to_delete as
candidates[message_limit:] if message_limit > 0 else candidates to preserve the
actual newest messages in the channel; additionally, in the thread deletion
except blocks around thread.delete() (and the analogous individual-message
thread deletion) re-raise or propagate rate-limit errors instead of swallowing
them by checking the caught HTTPException (or discord.HTTPException) for a 429
status (e.g., if getattr(e, "status", None) == 429: raise) and only suppress
non-429 errors.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 87da4abe-4295-4f54-941d-18ffd6ec6eec
📒 Files selected for processing (2)
NerdyPy/bot.pyNerdyPy/modules/moderation.py
…hread deletes Switch history fetch to newest-first so keep_messages correctly preserves the actual newest N messages in the channel, not just the newest within a truncated oldest-first window (which would silently delete messages that should have been kept on channels with large backlogs). Re-raise 429 HTTPExceptions from thread.delete() calls in both the bulk and individual deletion paths so rate-limit signals propagate to the outer handler that stops processing remaining channels for the run. Co-Authored-By: Claude <noreply@anthropic.com>
|
Note Docstrings generation - SUCCESS |
Docstrings generation was requested by @karaktaka. * #308 (comment) The following files were modified: * `NerdyPy/bot.py` * `NerdyPy/modules/moderation.py`
Remove unnecessary pass statements from both thread-delete except blocks; the if ex.status == 429: raise is already a valid statement body so pass was redundant. Replace with an inline comment to preserve intent. Update test_autodelete_deletes_old_messages to supply the mock history in newest-first order ([newer_msg, old_msg]) to match the oldest_first=False fetch; candidates[1:] then correctly targets old_msg for deletion. Co-Authored-By: Claude <noreply@anthropic.com>
Docstrings generation was requested by @karaktaka. * #308 (comment) The following files were modified: * `NerdyPy/bot.py` * `NerdyPy/modules/moderation.py`
…bility (#308) Co-authored-by: Claude <noreply@anthropic.com>
Summary
channel.delete_messages()— up to 100 messages per API call instead of one at a time. This eliminates the40062per-resource rate limit errors that were hitting every 5-minute tick.Noneguard: Fixed a latent crash if the bot has left a guild that still has anAutoDeleteconfig.pool_pre_ping=Trueto the SQLAlchemy engine so stale connections after a DB restart are transparently recycled before use, preventing the cascade ofOperationalErrorfailures that would otherwise follow anAdminShutdown.Test plan
KeepMessages=Ncorrectly preserves the newest N candidatesDeletePinnedMessage=True🤖 Generated with Claude Code
Summary by CodeRabbit
Bug Fixes
New Features