Files
discord-stock-bot/DEPLOYMENT.md
Michael Simard 584ad2a4f4 Add market close updates and update deployment path for Compose Manager
Bot enhancements:
- Add scheduled update at market close (4:00 PM ET on trading days)
- Implement is_trading_day() method to check weekdays/holidays
- Market close update sends PYPL price at end of trading day

Deployment changes:
- Update all scripts to use Docker Compose Manager plugin path
- New path: /boot/config/plugins/compose.manager/projects/discord-stock-bot
- Container now integrates with Unraid Docker UI Compose section
- Update documentation with plugin integration details

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-03 18:57:13 -06:00

549 lines
12 KiB
Markdown

# Discord Stock Bot - Deployment Guide
This guide provides detailed instructions for deploying and running the Discord stock bot.
## Prerequisites
Before starting the bot, ensure you have the following:
1. **Python 3.9 or higher** installed on your system
2. **Discord Bot Token** from Discord Developer Portal
3. **Discord Channel ID** where the bot will post updates
4. **Finnhub API Key** (free tier available at https://finnhub.io)
5. **Git** (optional, for cloning the repository)
## Quick Start (Local Python)
### 1. Clone or Download the Repository
```bash
# If using Git
git clone ssh://git@git.michaelsimard.ca:28/msimard/discord-stock-bot
cd discord-stock-bot
# Or download and extract the files manually
```
### 2. Install Dependencies
```bash
# Create a virtual environment (recommended)
python3 -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install required packages
pip install -r requirements.txt
```
### 3. Configure Environment Variables
```bash
# Copy the example environment file
cp .env.example .env
# Edit .env with your credentials
nano .env # or use any text editor
```
Required configuration in `.env`:
```env
# Discord Configuration
DISCORD_TOKEN=your_discord_bot_token_here
CHANNEL_ID=your_channel_id_here
# Bot Configuration
COMMAND_PREFIX=!
# Stock Configuration
PRIMARY_TICKER=PYPL
STOCK_API_PROVIDER=finnhub
FINNHUB_API_KEY=your_finnhub_api_key_here
# Scheduling Configuration
UPDATE_INTERVAL_HOURS=1
```
### 4. Run the Bot
```bash
python3 bot.py
```
The bot will start and display connection status in the console.
### 5. Verify Bot is Running
Check the console output for:
```
INFO - Bot connected as [bot_name] (ID: [bot_id])
INFO - Target channel found: #[channel_name]
INFO - Using Finnhub API for stock data
```
## Running in Background
### Using nohup (Unix/Linux/macOS)
```bash
nohup python3 bot.py > bot.log 2>&1 &
```
To stop:
```bash
pkill -f "python3 bot.py"
```
### Using screen (Unix/Linux/macOS)
```bash
screen -S discord-bot
python3 bot.py
# Detach: Press Ctrl+A, then D
# Reattach: screen -r discord-bot
# Kill: screen -X -S discord-bot quit
```
### Using systemd (Linux)
Create `/etc/systemd/system/discord-stock-bot.service`:
```ini
[Unit]
Description=Discord Stock Price Bot
After=network.target
[Service]
Type=simple
User=your_username
WorkingDirectory=/path/to/discord-stock-bot
Environment="PATH=/path/to/discord-stock-bot/venv/bin"
ExecStart=/path/to/discord-stock-bot/venv/bin/python3 bot.py
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
```
Enable and start:
```bash
sudo systemctl daemon-reload
sudo systemctl enable discord-stock-bot
sudo systemctl start discord-stock-bot
sudo systemctl status discord-stock-bot
```
View logs:
```bash
sudo journalctl -u discord-stock-bot -f
```
## Docker Deployment
### Local Docker (Development)
```bash
# Build and run with Docker Compose
docker compose up --build
# Run in background
docker compose up -d
# View logs
docker compose logs -f
# Stop
docker compose down
```
### Docker without Compose
```bash
# Build image
docker build -t discord-stock-bot .
# Run container
docker run -d \
--name discord-stock-bot \
--env-file .env \
--restart unless-stopped \
discord-stock-bot
# View logs
docker logs -f discord-stock-bot
# Stop
docker stop discord-stock-bot
docker rm discord-stock-bot
```
## Unraid Deployment
### Automated Git-Based Deployment (Recommended)
This project includes automated deployment scripts for seamless deployment to Unraid via git.
#### Architecture Flow
```
┌─────────────────┐ git push ┌──────────────────┐
│ Local Machine │ ─────────────────> │ Gitea Server │
│ Development │ │ (port 28) │
└────────┬────────┘ └────────┬─────────┘
│ │
│ ./deploy.sh │
│ (SSH commands) │
│ │
v │
┌─────────────────┐ git pull │
│ Unraid Server │ <───────────────────────────┘
│ 192.168.2.61 │
│ │
│ docker compose │
│ up --build -d │
└─────────────────┘
```
#### Deployment Scripts
**1. `setup-unraid.sh`** - One-time initial setup
- Configures SSH keys on Unraid for git authentication
- Adds git.michaelsimard.ca:28 to SSH config
- Copies .env file to Unraid
- Tests git connectivity
**2. `deploy.sh`** - Deploy/update the bot
- SSHs into Unraid
- Configures git server SSH settings (port 28)
- Clones repository (first run) or pulls latest changes
- Builds and starts Docker container
- Shows deployment status
**3. `manage.sh`** - Daily operations
- `./manage.sh logs` - View live container logs
- `./manage.sh status` - Check container status
- `./manage.sh restart` - Restart the bot
- `./manage.sh stop` - Stop the bot
- `./manage.sh start` - Start the bot
- `./manage.sh rebuild` - Rebuild and restart
- `./manage.sh shell` - SSH to Unraid in bot directory
#### Deployment Process
**Initial Setup (one-time):**
```bash
# 1. Ensure you have local .env configured
cp .env.example .env
# Edit .env with your credentials
# 2. Run initial setup
./setup-unraid.sh
# This will:
# - Configure SSH on Unraid for git server (port 28)
# - Generate SSH key on Unraid if needed
# - Display public key to add to Gitea
# - Copy .env to Unraid server
# - Test git connectivity
```
**Deploy the Bot:**
```bash
# Deploy to Unraid
./deploy.sh
# This will:
# - SSH into Unraid (root@192.168.2.61)
# - Ensure git SSH config is set (port 28)
# - Clone or pull latest code from Gitea
# - Build Docker image
# - Start container in background
```
**Manage the Bot:**
```bash
# View logs
./manage.sh logs
# Check status
./manage.sh status
# Restart after config changes
./manage.sh restart
```
#### Update Workflow
```bash
# 1. Make changes locally
vim bot.py
# 2. Commit and push to git
git add .
git commit -m "Update feature"
git push
# 3. Deploy to Unraid
./deploy.sh
# 4. Verify deployment
./manage.sh logs
```
#### Configuration Details
- **Unraid Host**: `root@192.168.2.61`
- **Deployment Path**: `/boot/config/plugins/compose.manager/projects/discord-stock-bot`
- **Git Repository**: `git@git.michaelsimard.ca:msimard/discord-stock-bot.git`
- **Git Server Port**: 28 (configured in SSH config)
- **Integration**: Docker Compose Manager plugin (stack appears in Unraid Docker tab)
#### Troubleshooting Automated Deployment
**SSH Connection Issues:**
```bash
# Test SSH connection
ssh root@192.168.2.61
# Test git access from Unraid
ssh root@192.168.2.61 "git ls-remote git@git.michaelsimard.ca:msimard/discord-stock-bot.git HEAD"
```
**Git Authentication Fails:**
```bash
# Re-run setup to regenerate keys
./setup-unraid.sh
# Manually add SSH key to Gitea:
# https://git.michaelsimard.ca/user/settings/keys
```
**Container Won't Start:**
```bash
# Check .env exists on Unraid
ssh root@192.168.2.61 "cat /boot/config/plugins/compose.manager/projects/discord-stock-bot/.env"
# View detailed logs
./manage.sh logs
# Check in Unraid UI: Docker tab > Compose section
```
### Method 1: Docker Compose
1. Copy the project directory to your Unraid server:
```bash
scp -r discord-stock-bot/ root@unraid-server:/mnt/user/appdata/
```
2. SSH into Unraid and navigate to the directory:
```bash
ssh root@unraid-server
cd /mnt/user/appdata/discord-stock-bot
```
3. Create and configure `.env` file
4. Run with Docker Compose:
```bash
docker compose up -d
```
### Method 2: Unraid Docker Template
1. Build and push your image to Docker Hub:
```bash
docker build -t your-username/discord-stock-bot:latest .
docker login
docker push your-username/discord-stock-bot:latest
```
2. In Unraid web UI:
- Navigate to Docker tab
- Click "Add Container"
- Configure:
- **Name**: discord-stock-bot
- **Repository**: your-username/discord-stock-bot:latest
- **Network Type**: bridge
- **Add Variables**:
- DISCORD_TOKEN
- CHANNEL_ID
- PRIMARY_TICKER
- STOCK_API_PROVIDER
- FINNHUB_API_KEY
- COMMAND_PREFIX
- TZ (America/New_York)
3. Click "Apply"
## Obtaining Required Credentials
### Discord Bot Token
1. Go to https://discord.com/developers/applications
2. Click "New Application"
3. Navigate to "Bot" section
4. Click "Add Bot"
5. Enable "Message Content Intent" under Privileged Gateway Intents
6. Click "Reset Token" and copy the token
7. Navigate to OAuth2 > URL Generator
8. Select scopes: `bot`
9. Select permissions: Send Messages, Embed Links, Read Messages/View Channels
10. Use generated URL to invite bot to your server
### Discord Channel ID
1. Enable Developer Mode in Discord (User Settings > Advanced > Developer Mode)
2. Right-click the desired channel
3. Click "Copy Channel ID"
### Finnhub API Key
1. Visit https://finnhub.io/register
2. Create a free account
3. Copy your API key from the dashboard
## Troubleshooting
### Bot Does Not Connect
**Issue**: Bot shows "Could not find channel with ID"
**Solution**:
- Verify the bot has been invited to the server
- Check that CHANNEL_ID is correct
- Ensure bot has permissions to view the channel
### Stock Data Not Available
**Issue**: "Unable to retrieve data for ticker"
**Solution**:
- Verify FINNHUB_API_KEY is correct
- Check Finnhub API status
- Try a different ticker (e.g., AAPL) to test API connection
### Rate Limiting
**Issue**: "429 Too Many Requests"
**Solution**:
- This occurs with Yahoo Finance after excessive queries
- Switch to Finnhub by setting `STOCK_API_PROVIDER=finnhub`
- Wait 1-24 hours for rate limit to reset
### Import Errors
**Issue**: ModuleNotFoundError
**Solution**:
```bash
pip install -r requirements.txt
```
### Bot Crashes on Startup
**Issue**: Bot exits immediately
**Solution**:
- Check all required environment variables are set
- Verify Python version: `python3 --version` (must be 3.9+)
- Check logs for specific error messages
## Monitoring
### Check Bot Status
```bash
# Local Python
ps aux | grep "python3 bot.py"
# Docker
docker ps | grep discord-stock-bot
# Systemd
sudo systemctl status discord-stock-bot
```
### View Logs
```bash
# Local Python (if using nohup)
tail -f bot.log
# Docker Compose
docker compose logs -f
# Docker
docker logs -f discord-stock-bot
# Systemd
sudo journalctl -u discord-stock-bot -f
```
## Stopping the Bot
```bash
# Local Python
pkill -f "python3 bot.py"
# Docker Compose
docker compose down
# Docker
docker stop discord-stock-bot
# Systemd
sudo systemctl stop discord-stock-bot
```
## Updating the Bot
```bash
# Pull latest changes
git pull origin main
# Reinstall dependencies (if changed)
pip install -r requirements.txt
# Restart bot
pkill -f "python3 bot.py"
python3 bot.py
# Or with Docker
docker compose down
docker compose up --build -d
```
## Bot Commands
Once running, the bot responds to these commands in Discord:
- `!stock <TICKER>` - Get current stock price for any ticker
- `!price <TICKER>` - Alternative command for stock price
- `!market` - Check if NYSE is currently open
- `!ping` - Check bot responsiveness
**Hourly Updates**: The bot automatically posts PYPL price updates every hour during NYSE market hours (9:30 AM - 4:00 PM ET, Monday-Friday).
## Security Notes
- Never commit `.env` file to version control
- Keep your Discord token and API keys secure
- Regularly rotate API keys
- Use environment variables for all sensitive data
- Run bot with minimal necessary permissions
## Support
For issues or questions:
- Check logs for error messages
- Verify all configuration values
- Ensure all prerequisites are installed
- Review README.md for additional information