Skip to content

Conversation

@DhruvK278
Copy link
Contributor

@DhruvK278 DhruvK278 commented Jul 23, 2025

Migrates Discord bot commands from legacy prefix-based commands to Discord slash commands using app_commands. Enabled ephemeral messages for enhanced security. Refactors cog startup to load dynamically after the event loop starts, improving reliability and startup order. Updates thread handling, message classification, and agent response logic for better maintainability and user experience. Adds 'discord-py' dependency in pyproject.toml.

Closes #108

📝 Description

This pull request refactors the entire Discord bot integration to modernize its command structure and improve its reliability and user experience. The primary change is the migration from legacy prefix commands '!' to the officially recommended slash commands '/', which allows for enhanced security features like ephemeral messages for sensitive information.

The verification process has been updated to no longer rely on Direct Messages (DMs). Instead, the authentication link is sent as a private, ephemeral message directly in the channel where the command was used, improving both security and user experience.

Additionally, the application's startup logic has been overhauled to fix critical race conditions, ensuring background tasks and command cogs are loaded only after the main asynchronous event loop is running. This resolves persistent startup errors and makes the bot's initialization more robust.

🔧 Changes Made

✅ Migrated to Slash Commands

  • All prefix-based commands (e.g., !verify_github) have been converted to use slash commands (e.g., /verify_github) via discord.app_commands.

📬 Removed Direct Messaging

  • The verification process no longer relies on DMs.
  • Authentication links are now sent directly in the channel as private ephemeral messages.

👻 Enabled Ephemeral Responses

  • The /verify_github and /verification_status commands now use ephemeral responses, ensuring that replies are only visible to the user who triggered the command.

⚙️ Refactored Startup Logic

  • Discord command cog loading is now handled by the app's asynchronous lifespan manager.
  • This resolves RuntimeError: no running event loop and ensures background tasks initialize correctly.

🧹 Robust Task Management

  • The background task for cleaning up expired verification tokens is now reliably triggered using a Cog.listener() on the on_ready event.

📦 Dependency Update

  • Added discord-py to pyproject.toml to guarantee the correct version is installed during setup.

📷 Screenshots or Visual Changes (if applicable)

Before
image

After
image

🤝 Collaboration

This issue was fixed by @DhruvK278

✅ Checklist

  • I have read the contributing guidelines.
  • I have added tests that prove my fix is effective or that my feature works.
  • I have added necessary documentation (if applicable).
  • Any dependent changes have been merged and published in downstream modules.

Summary by CodeRabbit

  • New Features

    • All Discord bot commands are now available as slash commands for easier access and improved user experience.
  • Improvements

    • Streamlined bot responses in threads with simplified welcome messages.
    • Enhanced error handling and reliability for Discord interactions.
    • Ephemeral (private) messaging for verification and help commands to improve user privacy.
    • More robust management of Discord threads and message classification.
    • Dynamic asynchronous loading of Discord command extensions during startup for better stability.
  • Chores

    • Updated dependencies to include the latest Discord library.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 23, 2025

Walkthrough

The Discord bot integration was refactored to use slash commands instead of prefix-based commands, with improved separation of control flow for slash commands, thread messages, and new messages. Command handlers were updated for the new interaction model, cog loading was made dynamic and asynchronous, and error handling was enhanced throughout. The Discord library dependency was specified in the project configuration.

Changes

File(s) Change Summary
backend/integrations/discord/bot.py Disabled prefix commands, explicitly synced slash commands with error handling, refined message and thread handling, and improved logging.
backend/integrations/discord/cogs.py Converted text commands to slash commands using interactions, improved ephemeral responses, added on_ready listener, and dynamic cog setup.
backend/main.py Changed to dynamic async loading of Discord cog extension during startup, improved error handling and background task management.
pyproject.toml Added discord-py dependency with version constraint >=2.5.2,<3.0.0.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Discord
    participant DiscordBot
    participant DevRelCommands

    User->>Discord: Sends message or uses slash command
    Discord->>DiscordBot: Delivers message or interaction
    alt Slash Command
        DiscordBot->>DevRelCommands: Handles interaction (slash command)
        DevRelCommands->>DiscordBot: Responds via interaction response
    else Message in Thread
        DiscordBot->>DiscordBot: Detects active thread, handles as follow-up
        DiscordBot->>User: Responds in thread
    else New Message in Main Channel
        DiscordBot->>DiscordBot: Classifies message
        DiscordBot->>DiscordBot: Handles DevRel message (may create thread)
        DiscordBot->>User: Responds in new thread
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~80 minutes

Possibly related PRs

Suggested reviewers

  • smokeyScraper

Poem

In Discord’s warren, commands once hopped—
From “!” to slash, the old ways dropped.
Threads are tidier, replies more clear,
Ephemeral help now whispers near.
With cogs that load as tasks arise,
This bunny bot is sleek and wise!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3972511 and 0231d01.

📒 Files selected for processing (4)
  • backend/integrations/discord/bot.py (4 hunks)
  • backend/integrations/discord/cogs.py (7 hunks)
  • backend/main.py (2 hunks)
  • pyproject.toml (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • pyproject.toml
🚧 Files skipped from review as they are similar to previous changes (3)
  • backend/integrations/discord/bot.py
  • backend/main.py
  • backend/integrations/discord/cogs.py
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🔭 Outside diff range comments (1)
pyproject.toml (1)

11-11: Critical: Conflicting Discord library dependencies

The project already has py-cord on line 11, which is a fork of discord.py. Adding discord-py creates a conflict as both libraries provide the same discord module namespace. This will cause import errors and runtime issues.

You should use either py-cord or discord-py, not both. Since the codebase appears to be using py-cord features (based on the imports in other files), remove this line.

Apply this diff to fix the dependency conflict:

-    "discord-py (>=2.5.2,<3.0.0)",

Also applies to: 28-28

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8fdf2d4 and 514bf8c.

⛔ Files ignored due to path filters (1)
  • poetry.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • backend/integrations/discord/bot.py (4 hunks)
  • backend/integrations/discord/cogs.py (7 hunks)
  • backend/main.py (3 hunks)
  • pyproject.toml (1 hunks)
🧠 Learnings (2)
backend/main.py (2)

Learnt from: smokeyScraper
PR: #87
File: backend/app/api/v1/health.py:1-12
Timestamp: 2025-06-28T23:14:21.089Z
Learning: In the Devr.AI project, the application is designed to run from the backend directory, making import paths like from main import DevRAIApplication correct for the current setup. Import path adjustments for deployment will be configured later during the deployment process.

Learnt from: smokeyScraper
PR: #87
File: tests/test_supabase.py:1-3
Timestamp: 2025-06-28T23:15:13.374Z
Learning: In the Devr.AI project, smokeyScraper prefers to defer test updates and fixes (like missing imports after module reorganization) to separate PRs rather than expanding the scope of module update/chore PRs to include comprehensive test refactoring.

backend/integrations/discord/bot.py (2)

Learnt from: smokeyScraper
PR: #75
File: backend/app/agents/devrel/agent.py:34-35
Timestamp: 2025-06-13T21:56:19.183Z
Learning: In the Devr.AI backend, the DevRelAgent follows a singleton pattern where only one instance exists for the entire application lifetime, using InMemorySaver with thread-based conversation management to persist user conversations across sessions.

Learnt from: smokeyScraper
PR: #76
File: backend/app/agents/shared/base_agent.py:22-44
Timestamp: 2025-06-14T05:57:43.872Z
Learning: In the Devr.AI codebase, user_id directly maps as thread_id for memory persistence in the agent system, ensuring thread_id is always non-empty and unique per user.

🧬 Code Graph Analysis (1)
backend/integrations/discord/bot.py (2)
backend/app/classification/classification_router.py (1)
  • ClassificationRouter (10-59)
backend/app/core/orchestration/queue_manager.py (2)
  • QueuePriority (12-15)
  • enqueue (73-92)
🧰 Additional context used
🧠 Learnings (2)
backend/main.py (2)

Learnt from: smokeyScraper
PR: #87
File: backend/app/api/v1/health.py:1-12
Timestamp: 2025-06-28T23:14:21.089Z
Learning: In the Devr.AI project, the application is designed to run from the backend directory, making import paths like from main import DevRAIApplication correct for the current setup. Import path adjustments for deployment will be configured later during the deployment process.

Learnt from: smokeyScraper
PR: #87
File: tests/test_supabase.py:1-3
Timestamp: 2025-06-28T23:15:13.374Z
Learning: In the Devr.AI project, smokeyScraper prefers to defer test updates and fixes (like missing imports after module reorganization) to separate PRs rather than expanding the scope of module update/chore PRs to include comprehensive test refactoring.

backend/integrations/discord/bot.py (2)

Learnt from: smokeyScraper
PR: #75
File: backend/app/agents/devrel/agent.py:34-35
Timestamp: 2025-06-13T21:56:19.183Z
Learning: In the Devr.AI backend, the DevRelAgent follows a singleton pattern where only one instance exists for the entire application lifetime, using InMemorySaver with thread-based conversation management to persist user conversations across sessions.

Learnt from: smokeyScraper
PR: #76
File: backend/app/agents/shared/base_agent.py:22-44
Timestamp: 2025-06-14T05:57:43.872Z
Learning: In the Devr.AI codebase, user_id directly maps as thread_id for memory persistence in the agent system, ensuring thread_id is always non-empty and unique per user.

🧬 Code Graph Analysis (1)
backend/integrations/discord/bot.py (2)
backend/app/classification/classification_router.py (1)
  • ClassificationRouter (10-59)
backend/app/core/orchestration/queue_manager.py (2)
  • QueuePriority (12-15)
  • enqueue (73-92)
🔇 Additional comments (9)
backend/main.py (1)

14-16: Good refactoring to address race conditions

Removing the direct import and loading the cog dynamically after the event loop starts is the correct approach to fix the race condition issues mentioned in the PR objectives.

backend/integrations/discord/bot.py (4)

21-21: Correct implementation to disable prefix commands

Setting command_prefix=None properly disables traditional prefix commands, aligning with the migration to slash commands.


39-43: Good addition of slash command syncing

The implementation correctly syncs slash commands on bot startup with appropriate error handling. This ensures slash commands are registered with Discord.


50-61: Well-structured message filtering logic

The implementation correctly:

  1. Ignores slash command interactions to prevent duplicate processing
  2. Detects messages in active threads and processes them without re-classification
  3. Maintains conversation context in threads

This aligns perfectly with the slash command migration objectives.


120-134: Improved thread management and user experience

The thread management enhancements are well-implemented:

  • Proper validation of thread existence and archive status
  • Cleanup of stale thread references
  • Concise, professional welcome message

These changes improve reliability and user experience.

backend/integrations/discord/cogs.py (4)

20-26: Excellent fix for the token cleanup race condition

Moving the cleanup task initialization from __init__ to on_ready properly addresses the race condition mentioned in the PR objectives. The is_running() check prevents duplicate task instances, which is a good defensive programming practice.


45-57: Correct implementation of slash commands with ephemeral responses

The slash command conversion is properly implemented:

  • Uses @app_commands.command decorator
  • Handles discord.Interaction correctly
  • Sets ephemeral=True for privacy

This aligns with the PR objective of using ephemeral messages for enhanced security.


104-180: Well-implemented OAuth flow with proper defer handling

The /verify_github command implementation is excellent:

  • Correctly uses defer(ephemeral=True) for potentially long operations
  • Uses followup.send() after deferring
  • Comprehensive error handling and user feedback
  • Maintains privacy with ephemeral messages throughout

This provides a secure and user-friendly verification experience.


182-184: Correct setup function for dynamic cog loading

The async setup function properly integrates with Discord.py's extension loading system, enabling the dynamic loading implemented in main.py.

@DhruvK278
Copy link
Contributor Author

Hi @smokeyScraper I have added the coderabbit suggestions, Please have a look
Thanks.

@DhruvK278 DhruvK278 changed the title Refactor Discord bot to use slash commands and dynamic cog loading feat:Refactor Discord bot to use slash commands and use ephemeral message Jul 24, 2025
@DhruvK278 DhruvK278 changed the title feat:Refactor Discord bot to use slash commands and use ephemeral message feat: Refactor Discord bot to use slash commands and use ephemeral message Jul 24, 2025
@DhruvK278 DhruvK278 changed the title feat: Refactor Discord bot to use slash commands and use ephemeral message BugFix: Refactor Discord bot to use slash commands and use ephemeral message Jul 24, 2025
Copy link
Contributor

@smokeyScraper smokeyScraper left a comment

Choose a reason for hiding this comment

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

could you please address the requested change?
rest of the logic seems GTG.

Comment on lines 56 to 60
if is_in_active_thread:
# If it's an active thread, it's part of an ongoing conversation.
# We don't need to classify it again, just handle it.
await self._handle_devrel_message(message, {"needs_devrel": True})
return
Copy link
Contributor

Choose a reason for hiding this comment

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

!!! BUG here !!!
Any message within the thread is classified to be handled by DevRel as we are skipping classification logic.

Interaction

image

Please revert to the previous logic itself.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Fixed!!

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
backend/main.py (1)

47-53: Consider making Discord cog loading failure more explicit

The dynamic cog loading implementation correctly addresses the race condition by ensuring the event loop is running. The error handling is well-structured and catches appropriate exceptions.

However, consider whether Discord cog loading failure should be treated as a fatal error since the Discord integration appears to be a core feature. Currently, the application continues running even if the cog fails to load.

If Discord functionality is essential, consider this approach:

             try:
                 await self.discord_bot.load_extension("integrations.discord.cogs")
+                logger.info("Discord cog extension loaded successfully")
             except (ImportError, commands.ExtensionError) as e:
                 logger.error("Failed to load Discord cog extension: %s", e)
+                # Uncomment the next line if Discord functionality is essential
+                # raise RuntimeError(f"Critical Discord cog loading failed: {e}")
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 52b2962 and 3972511.

📒 Files selected for processing (3)
  • backend/integrations/discord/bot.py (4 hunks)
  • backend/integrations/discord/cogs.py (7 hunks)
  • backend/main.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • backend/integrations/discord/bot.py
  • backend/integrations/discord/cogs.py
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: smokeyScraper
PR: AOSSIE-Org/Devr.AI#87
File: tests/test_supabase.py:1-3
Timestamp: 2025-06-28T23:15:13.374Z
Learning: In the Devr.AI project, smokeyScraper prefers to defer test updates and fixes (like missing imports after module reorganization) to separate PRs rather than expanding the scope of module update/chore PRs to include comprehensive test refactoring.
Learnt from: smokeyScraper
PR: AOSSIE-Org/Devr.AI#85
File: tests/test_supabase.py:1-3
Timestamp: 2025-06-28T14:45:55.244Z
Learning: In the Devr.AI project, smokeyScraper prefers to defer comprehensive test refactoring to separate PRs/efforts when doing major backend restructuring, rather than expanding the scope of the current refactoring PR to include test updates.
backend/main.py (2)

Learnt from: smokeyScraper
PR: #87
File: backend/app/api/v1/health.py:1-12
Timestamp: 2025-06-28T23:14:21.089Z
Learning: In the Devr.AI project, the application is designed to run from the backend directory, making import paths like from main import DevRAIApplication correct for the current setup. Import path adjustments for deployment will be configured later during the deployment process.

Learnt from: smokeyScraper
PR: #87
File: tests/test_supabase.py:1-3
Timestamp: 2025-06-28T23:15:13.374Z
Learning: In the Devr.AI project, smokeyScraper prefers to defer test updates and fixes (like missing imports after module reorganization) to separate PRs rather than expanding the scope of module update/chore PRs to include comprehensive test refactoring.

🔇 Additional comments (3)
backend/main.py (3)

15-17: LGTM: Clean migration to dynamic cog loading

The import changes correctly reflect the shift from synchronous to asynchronous cog loading. The comment clearly documents the change in approach, which will help future maintainers understand the architecture.


61-61: Excellent error handling improvement

Re-raising the exception after cleanup ensures proper resource management. This prevents resource leaks if startup fails and follows the cleanup-then-reraise pattern, which is a best practice for exception handling in resource management scenarios.


67-67: Good refactoring for improved readability

Removing the intermediate variable makes the code more concise while maintaining the same functionality. This is a clean improvement that enhances readability.

@DhruvK278 DhruvK278 closed this Jul 26, 2025
@DhruvK278 DhruvK278 force-pushed the Bug/Bot_leaks_auth#108 branch from b3bd8e2 to 1356976 Compare July 26, 2025 07:27
Migrates Discord bot commands from legacy prefix-based to modern slash commands using discord.py app_commands. Refactors DevRelCommands cog to use slash commands, improves token cleanup task management, and updates verification flows for ephemeral responses. Discord bot now loads cogs dynamically during async startup, and the Discord dependency is added to pyproject.toml.
@DhruvK278 DhruvK278 reopened this Jul 26, 2025
@smokeyScraper smokeyScraper merged commit ae8dfc1 into AOSSIE-Org:main Jul 26, 2025
1 check passed
@smokeyScraper
Copy link
Contributor

Merged!
Cheers @DhruvK278 !!!

This is a great improvement on the UX side.
ThankYou for contributing :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BUG: Bot leaks authentication link in public channel when user's DMs are blocked

2 participants