A resilient Slack bot built with Slack Bolt, Drizzle ORM, and PostgreSQL that can delete messages and threads in whitelisted channels. The bot follows OOP principles and DRY methodology for maintainable code.
- Automatic Message Deletion: Automatically deletes messages from non-whitelisted users using Slack's
chat.deleteAPI - Queue System: Processes deletions in a queue with rate limiting (300 deletions/minute)
- Rate Limit Protection: Automatically removes users who send messages too rapidly to prevent bot rate limiting
- Whitelist Management: Control which users and channels the bot operates on
- Resilient Design: Retry logic, error handling, and graceful degradation
- Database Tracking: Track all deleted messages and queue status in PostgreSQL
- Slash Commands: Easy-to-use commands for whitelist and queue management
The bot is built using Object-Oriented Programming principles with the following key components:
- MessageDeletionBot: Main bot class handling Slack events and commands
- SlackService: Handles all Slack API interactions with retry logic
- MessageQueueService: Manages message deletion queue with rate limiting and rate limit protection
- DatabaseService: Manages database operations using Drizzle ORM
- Database Schema: PostgreSQL tables for whitelists, queue, and rate limit protection
- Node.js 18+
- PostgreSQL database
- Slack App with appropriate permissions
- Clone the repository and install dependencies:
npm install- Set up environment variables:
cp env.example .env- Configure your
.envfile with:SLACK_BOT_TOKEN: Your Slack bot token (xoxb-...)SLACK_USER_TOKEN: Your Slack user token (xoxp-...) - needed for deleting messagesSLACK_SIGNING_SECRET: Your Slack app signing secretSLACK_APP_TOKEN: Your Slack app token (xapp-...)DATABASE_URL: PostgreSQL connection stringPORT: Server port (default: 3000)
- Generate database migrations:
npm run db:generate- Run migrations:
npm run db:migrate- (Optional) Seed with example data:
npm run db:seednpm run devnpm run build
npm startYour Slack app needs the following OAuth scopes:
Bot Token Scopes:
channels:history- To read channel historygroups:history- To read private channel historyim:history- To read direct message historympim:history- To read group direct message historyusers:read- To get user informationchannels:read- To get channel information
User Token Scopes (for message deletion):
chat:write- To delete messageschannels:write- To delete messages in channelsgroups:write- To delete messages in private channelsim:write- To delete messages in direct messagesmpim:write- To delete messages in group direct messages
Important: You need both a bot token and a user token. The user token is required because bots cannot delete messages from other users - only users can delete messages.
Event subscriptions:
message.channelsmessage.groupsmessage.immessage.mpimapp_mention
Slash commands:
/add-user/remove-user/add-channel/remove-channel/list-whitelist/whitelist-me/queue-status
Add a user to the whitelist:
/add-user U1234567890
Add yourself to the whitelist:
/whitelist-me
Add a channel to the whitelist:
/add-channel C1234567890
List all whitelisted users and channels:
/list-whitelist
The bot automatically deletes messages from non-whitelisted users in whitelisted channels. This provides a way to keep channels clean by only allowing specific users to post.
Messages are processed in a queue with rate limiting:
- Rate Limit: 300 deletions per minute (200ms delay between calls)
- Queue Processing: Messages are processed every 500ms for fast response
- Retry Logic: Failed deletions are retried up to 3 times
- Status Tracking: Monitor queue status with
/queue-status
The bot automatically protects itself from rate limiting:
- Threshold: 8 messages per 10 seconds triggers protection
- Action: Rapid users are automatically removed from whitelist
- Purpose: Prevents users from overwhelming the bot and hitting Slack's rate limits
- Tracking: User message counts are tracked and reset every 10 seconds
Get help:
@bot help
Check bot status:
@bot status
user_id(Primary Key): Slack user IDusername: Slack usernameadded_at: Timestamp when addedis_active: Whether the user is currently whitelisted
channel_id(Primary Key): Slack channel IDchannel_name: Slack channel nameadded_at: Timestamp when addedis_active: Whether the channel is currently whitelisted
id(Primary Key): Unique message identifiermessage_ts: Slack message timestampchannel_id: Channel where message was deleteduser_id: User who triggered the deletiondeleted_at: Timestamp of deletionis_thread: Whether it was a thread deletionthread_ts: Thread timestamp (if applicable)
id(Primary Key): Unique queue identifiermessage_ts: Slack message timestamp to deletechannel_id: Channel where message is locateduser_id: User who sent the messagequeued_at: When message was queued for deletionprocessed_at: When deletion was attemptedstatus: Queue status (pending, processing, completed, failed)retry_count: Number of retry attemptserror_message: Error details if deletion failed
user_id(Primary Key): Slack user IDmessage_count: Number of messages sent in current windowlast_message_at: Timestamp of last messageis_spamming: Whether user is currently flagged for rate limit protectionspam_detected_at: When rate limit protection was first triggered
The bot includes several resilience features:
- Retry Logic: Failed API calls are retried with exponential backoff
- Rate Limiting: Built-in delays to respect Slack's rate limits
- Error Logging: Comprehensive error logging for debugging
- Graceful Shutdown: Proper cleanup on SIGINT/SIGTERM
- Database Transactions: Safe database operations
- Validation: Input validation for all commands
src/
├── bot/
│ └── MessageDeletionBot.ts # Main bot class
├── database/
│ ├── connection.ts # Database connection
│ └── schema.ts # Database schema
├── services/
│ ├── DatabaseService.ts # Database operations
│ └── SlackService.ts # Slack API operations
├── scripts/
│ ├── migrate.ts # Migration runner
│ └── seed.ts # Database seeder
└── index.ts # Application entry point
- Extend the appropriate service class
- Add new command handlers in
MessageDeletionBot - Update database schema if needed
- Create migration for schema changes
- Add tests for new functionality
MIT License - see LICENSE file for details.