A Slack chatbot application built with Node.js using the Slack Bolt framework, integrated with AWS Bedrock for intelligent Q&A capabilities using Vercel's AI SDK.
- 🤖 Slack Integration: Full Slack Bot API support with Socket Mode & HTTP API modes
- 🧠 AI-Powered Responses: AWS Bedrock integration via Vercel AI SDK
- 📚 Knowledge Base Support: Query specific knowledge bases through Bedrock Agents
- 🔄 Streaming Responses: Real-time streaming AI responses
- 🔧 Hybrid Architecture: Automatic fallback from Bedrock Agent to direct model access
- 🎯 Enhanced Mentions: Pattern-based mention handling with smart responses
- 📝 Natural Chat Interface: Support for mentions and intuitive text patterns
- ☁️ Serverless Ready: Deploy as AWS Lambda functions with Serverless Framework
- Node.js 18.0.0 or higher
- npm or yarn package manager
- AWS Account with Bedrock access
- Slack App with Bot Token
- Serverless Framework (for Lambda deployment)
git clone <your-repo-url>
cd acorn
npm installCopy the example environment file and configure your credentials:
cp .env.example .envEdit .env with your configuration:
# Slack Bot Configuration (Required)
SLACK_BOT_TOKEN=xoxb-your-bot-token-here
SLACK_SIGNING_SECRET=your-signing-secret-here
SLACK_APP_TOKEN=xapp-your-app-token-here
# AWS Credentials (Required)
AWS_REGION=us-east-1
AWS_ACCESS_KEY_ID=your-access-key-id
AWS_SECRET_ACCESS_KEY=your-secret-access-key
# OR use AWS Profile instead
# AWS_PROFILE=default
# AI Model Configuration
BEDROCK_MODEL_ID=anthropic.claude-3-sonnet-20240229-v1:0
# Knowledge Base Configuration (for RetrieveAndGenerate)
BEDROCK_KNOWLEDGE_BASE_IDS=kb-12345678,kb-87654321- Go to Slack API Apps
- Create a new app or select existing one
- Enable Socket Mode and generate an App Token
- Add Bot Token Scopes:
app_mentions:readchannels:historychat:write
- Install app to your workspace
- Copy tokens to your
.envfile
- Enable Bedrock service in your AWS account
- Request access to Claude models in Bedrock console
- Create Bedrock Knowledge Bases for RetrieveAndGenerate
- Configure AWS credentials in
.env
Development mode (with auto-reload):
npm run devProduction mode:
npm startFor production deployments, the bot can be deployed as AWS Lambda functions using the Serverless Framework.
npm install -g serverlessConfigure AWS credentials for Serverless:
# Option 1: AWS CLI (recommended)
aws configure
# Option 2: Environment variables
export AWS_ACCESS_KEY_ID=your-access-key
export AWS_SECRET_ACCESS_KEY=your-secret-key
export AWS_DEFAULT_REGION=us-east-1
# Option 3: AWS Profile
export AWS_PROFILE=your-profile-nameCreate environment files for different stages:
Development Stage (.env.dev):
SLACK_BOT_TOKEN=xoxb-your-dev-bot-token
SLACK_SIGNING_SECRET=your-dev-signing-secret
AWS_REGION=us-east-1
BEDROCK_MODEL_ID=anthropic.claude-3-sonnet-20240229-v1:0
# Optional: Knowledge base IDs for RetrieveAndGenerate
BEDROCK_KNOWLEDGE_BASE_IDS=kb-dev-123,kb-dev-456
NODE_ENV=development
LOG_LEVEL=debugProduction Stage (.env.prod):
SLACK_BOT_TOKEN=xoxb-your-prod-bot-token
SLACK_SIGNING_SECRET=your-prod-signing-secret
AWS_REGION=us-east-1
BEDROCK_MODEL_ID=anthropic.claude-3-sonnet-20240229-v1:0
# Optional: Knowledge base IDs for RetrieveAndGenerate
BEDROCK_KNOWLEDGE_BASE_IDS=kb-prod-123,kb-prod-456
NODE_ENV=production
LOG_LEVEL=infoFor serverless deployment, configure your Slack app to use HTTP events instead of Socket Mode:
-
Go to your Slack App settings
-
Disable Socket Mode
-
Configure Event Subscriptions:
- Enable Events: Yes
- Request URL:
https://your-api-gateway-url.amazonaws.com/dev/slack/events - Subscribe to Bot Events:
app_mentionmessage.channelsmessage.groupsmessage.immessage.mpim
Deploy to development stage:
npm run deploy:devDeploy to production stage:
npm run deploy:prodDeploy to production:
npx serverless deploy --stage prodAfter deployment, Serverless will output the API Gateway URLs. Update your Slack app configuration with these URLs:
✅ Service deployed to stack acorn-slack-bot-dev
endpoints:
```bash
POST - https://abc123xyz.execute-api.us-east-1.amazonaws.com/dev/slack/events
GET - https://abc123xyz.execute-api.us-east-1.amazonaws.com/dev/health
Copy the events URL to your Slack app configuration.
Copy these URLs to your Slack app configuration.
#### 7. Test Deployment
Test the health endpoint:
```bash
curl https://your-api-gateway-url.amazonaws.com/dev/health
Should return:
{ "status": "ok", "timestamp": "2024-01-01T00:00:00.000Z", "version": "1.0.0" }View Lambda logs:
npm run logs:dev
# or
npm run logs:prodView specific function logs:
npx serverless logs -f slack-events --stage devTo remove the serverless deployment:
npm run remove:dev
# or
npm run remove:prodThe serverless deployment creates:
-
2 Lambda Functions:
slack-events: Handles all Slack Events API interactions (messages, mentions, etc.)health: Health check endpoint
-
API Gateway: HTTP API with CORS enabled
-
IAM Roles: Proper permissions for Bedrock access
-
CloudWatch Logs: Log groups with retention policies
Ask Questions (Natural Chat):
ask: What is the company policy on remote work?
@acorn How do I submit expenses?
@acorn What are the office hours?
Streaming Responses:
stream: Explain machine learning concepts
@acorn stream: Tell me about quantum computing
Knowledge Base Queries:
ask kb1: What are the security guidelines?
ask kb2: Company handbook information
Enhanced Mentions:
@acorn hello # Smart greeting
@acorn help # Show usage help
@acorn status # Check bot health
@acorn info # View configuration details
@acorn stream: explain AI # Stream response via mention
@acorn thanks # Friendly acknowledgment
Bot Status & Info:
@acorn status - Check bot and AI service status
@acorn info - View configuration and usage help
status - Works in channels too
info - Also works in channels
| Pattern | Description |
|---|---|
ask: <question> |
Ask the AI a question |
ask kb1: <question> |
Query specific knowledge base |
stream: <question> |
Get streaming AI response |
@acorn <anything> |
Mention-based interaction (smart responses) |
status or @acorn status |
Show bot status and uptime |
info or @acorn info |
Display AI configuration |
help or @acorn help |
Show usage instructions |
The bot supports two deployment modes:
-
Socket Mode (Development):
- Direct WebSocket connection to Slack
- Requires
SLACK_APP_TOKEN - Ideal for development and testing
- Run with
npm run devornpm start
-
HTTP Mode (Production/Serverless):
- HTTP API endpoints for Slack Events
- Deployed as AWS Lambda functions
- Production-ready with auto-scaling
- Deploy with
npm run deploy:devornpm run deploy:prod
The bot operates in two modes:
-
RetrieveAndGenerate Mode (when
BEDROCK_KNOWLEDGE_BASE_IDSis set):- Uses Bedrock RetrieveAndGenerate API with knowledge base integration
- Session-based context tracking
- Automatic source citation from knowledge bases
- Enhanced retrieval with configurable result count
-
AI SDK Fallback Mode (when no knowledge bases configured):
- Direct model access via Vercel AI SDK
- Streaming support
- General AI conversations
| Variable | Required | Description |
|---|---|---|
SLACK_BOT_TOKEN |
Yes | Slack bot token (xoxb-...) |
SLACK_SIGNING_SECRET |
Yes | Slack app signing secret |
SLACK_APP_TOKEN |
Socket Mode | Slack app token (xapp-...) for Socket Mode |
AWS_REGION |
Yes | AWS region (default: us-east-1) |
AWS_ACCESS_KEY_ID |
Yes* | AWS access key |
AWS_SECRET_ACCESS_KEY |
Yes* | AWS secret key |
AWS_PROFILE |
Yes* | AWS profile (alternative to keys) |
BEDROCK_MODEL_ID |
No | Bedrock model ID (default: Claude 3 Sonnet) |
BEDROCK_KNOWLEDGE_BASE_IDS |
No | Comma-separated knowledge base IDs for RetrieveAndGenerate |
PORT |
No | Server port (default: 3000, Socket Mode only) |
NODE_ENV |
No | Environment (development/production) |
LOG_LEVEL |
No | Logging level (info/debug/error) |
*Either AWS keys OR AWS profile required
| Script | Description |
|---|---|
npm start |
Run in Socket Mode (production) |
npm run dev |
Run in Socket Mode (development with nodemon) |
npm run deploy:dev |
Deploy to AWS Lambda (dev stage) |
npm run deploy:prod |
Deploy to AWS Lambda (prod stage) |
npm run logs:dev |
View Lambda logs (dev stage) |
npm run logs:prod |
View Lambda logs (prod stage) |
npm run remove:dev |
Remove serverless deployment (dev stage) |
npm run remove:prod |
Remove serverless deployment (prod stage) |
npm test |
Run test suite |
npm run lint |
Run ESLint |
npm run lint:fix |
Fix ESLint issues |
- Invite the bot to a Slack channel
- Test basic functionality:
@acorn hello ask: What is 2+2? stream: Explain photosynthesis @acorn status
# Run test suite
npm test
# Run linting
npm run lint
# Fix linting issues
npm run lint:fixCheck if the bot is working correctly:
- Bot Status:
@acorn status- Should show "Running ✅" - AI Services: Check if Bedrock Agent and AI SDK are configured
- Basic Query:
ask: Hello- Should get AI response - Streaming:
stream: Count to 5- Should see real-time updates
Bot doesn't respond (Socket Mode):
- Check Slack tokens are correct
- Verify bot is invited to the channel
- Check Socket Mode is enabled
- Review logs for error messages
Bot doesn't respond (Serverless):
- Check Slack Event URLs are configured correctly
- Verify Socket Mode is disabled
- Check API Gateway endpoints are accessible
- Review CloudWatch logs for errors
AI responses fail:
- Verify AWS credentials and region
- Check Bedrock model access in AWS console
- Ensure model ID is correct
- Check CloudWatch logs for AWS errors
Agent queries fail:
- Verify
BEDROCK_AGENT_IDis correct - Check agent is deployed and active
- Verify knowledge base IDs exist
- Review agent permissions
Streaming doesn't work:
- Check if bot has
chat:writepermission - Verify message update permissions in Slack
- Check for rate limiting
Serverless deployment fails:
- Verify AWS credentials are configured
- Check IAM permissions for CloudFormation
- Ensure Serverless Framework is installed
- Review deployment logs for specific errors
Socket Mode: Enable debug logging:
LOG_LEVEL=debug
NODE_ENV=developmentView application logs:
npm run devServerless Mode: View Lambda logs:
npm run logs:dev
# or specific function
npx serverless logs -f slack-events --stage dev --tailAWS CloudWatch:
- Navigate to CloudWatch in AWS Console
- Check Log Groups:
/aws/lambda/acorn-slack-bot-{stage}-{function} - Look for errors and exceptions
src/
├── app.js # Main application entry (Socket Mode)
├── lambda/ # Serverless Lambda handlers
│ ├── slack-adapter.js # Slack App adapter for Lambda
│ ├── slack-events.js # Events API Lambda handler
│ ├── health.js # Health check handler
│ └── utils.js # Lambda utilities
├── handlers/ # Slack event handlers (shared)
│ ├── messageHandler.js # Direct message patterns
│ ├── eventHandler.js # Slack events (joins, reactions)
│ ├── aiHandler.js # AI text patterns (ask:, stream:, kb queries)
│ └── mentionHandler.js # Enhanced mention handling
├── services/ # External services
│ └── aiService.js # Unified AI service (Bedrock Agent + AI SDK)
└── utils/ # Utilities
├── logger.js # Logging utility
└── responses.js # Response utilities
serverless.yml: Main serverless configuration.env.dev,.env.prod: Environment-specific configurationsscripts/: Deployment automation scripts
- For AI features: Extend
aiHandler.jswith new text patterns, ormentionHandler.jsfor mention-based interactions - For utility features: Add to
messageHandler.jsoreventHandler.js - Register new handlers in
src/app.js - Use
aiService.query()oraiService.stream()for AI interactions - Follow existing error handling patterns and comprehensive logging
- Update documentation
- Fork the repository
- Create feature branch
- Follow existing code patterns
- Add tests for new functionality
- Update documentation
- Submit pull request
MIT License - see LICENSE file for details.
For issues and questions:
- Check troubleshooting section above
- Review application logs
- Check AWS CloudWatch for Bedrock errors
- Verify Slack app configuration