Event System Overview
Faculty Bot uses Poise’s event handling system to respond to Discord events like messages, voice state changes, and button interactions. All event handling logic is centralized insrc/eventhandler.rs.
Event Handler Registration
The event handler is registered inmain.rs during framework initialization:
src/main.rs
Main Event Listener
The central event listener matches on different event types:src/eventhandler.rs
Event Types
Ready Event
Fired when the bot successfully connects to Discord:src/eventhandler.rs
- Log bot startup information
- Spawn background tasks (meal plan posting, RSS monitoring, metrics logging)
- Initialize any startup routines
Message Event
Fired when any message is sent in a channel the bot can see:src/eventhandler.rs
- Award XP for user activity
- Implement logarithmic scaling to prevent high-level users from gaining XP too quickly
- Generate level-up notifications with custom images
- Ignore bot messages and command invocations
Voice State Update Event
Fired when a user’s voice state changes (joins, leaves, moves channels):src/eventhandler.rs
- Create temporary voice channels when users join the “Create Channel”
- Give channel creator MANAGE_CHANNELS permission
- Automatically delete temporary channels when they become empty
- Track temporary channels in database to distinguish from permanent channels
Interaction Create Event
Fired when a user interacts with a component (button, select menu, modal):src/eventhandler.rs
- mensaplan_notify_button: Gives user the meal plan notification role
- reverify: Opens a modal for email re-verification
- Default: Shows “not implemented” message
Modals
Define modals using Poise’s modal system:src/eventhandler.rs
Helper Functions
Give User Mensaplan Role
src/eventhandler.rs
Not Implemented Handler
src/eventhandler.rs
Adding New Event Handlers
Available Events
Common Poise events you can handle:Ready: Bot connected to DiscordMessage: New message sentMessageUpdate: Message editedMessageDelete: Message deletedGuildMemberAddition: User joined serverGuildMemberRemoval: User left serverVoiceStateUpdate: Voice state changedInteractionCreate: Button/select/modal interactionReactionAdd: Reaction added to messageReactionRemove: Reaction removed from message
Best Practices
- Keep handlers focused: Each handler should do one thing well
- Extract helper functions: Move complex logic to separate functions
- Error handling: Always use
?operator and convert errors properly - Avoid blocking: Use async operations, never block the event loop
- Database efficiency: Batch operations when possible
- Spawn long tasks: Use
tokio::spawnfor long-running operations - Log appropriately: Use
tracingmacros for debugging
Next Steps
- Learn about Background Tasks
- Understand Database Operations
- Explore Internationalization