Skip to content

Development Setup

Julian Speckmann edited this page Jan 27, 2026 · 1 revision

Development Setup

Set up your local development environment for contributing to the SourceXchange Sync Bot.

Prerequisites

Before you begin, ensure you have:

  • Node.js 18 or higher (Download)
  • Git (Download)
  • A code editor (VS Code recommended)
  • Discord Bot Token (for testing)
  • SourceXchange API Token (for testing)

Initial Setup

1. Fork the Repository

  1. Go to sourcexchange-sync-bot
  2. Click the Fork button in the top-right corner
  3. Select your GitHub account

2. Clone Your Fork

git clone https://github.com/YOUR_USERNAME/sourcexchange-sync-bot.git
cd sourcexchange-sync-bot

3. Add Upstream Remote

git remote add upstream https://github.com/KingIronMan2011/sourcexchange-sync-bot.git
git remote -v

You should see:

origin    https://github.com/YOUR_USERNAME/sourcexchange-sync-bot.git (fetch)
origin    https://github.com/YOUR_USERNAME/sourcexchange-sync-bot.git (push)
upstream  https://github.com/KingIronMan2011/sourcexchange-sync-bot.git (fetch)
upstream  https://github.com/KingIronMan2011/sourcexchange-sync-bot.git (push)

4. Install Dependencies

npm install

5. Configure Development Environment

Create a .env file for development:

cp .env.example .env

Edit .env with your development credentials:

# Discord Bot Configuration
DISCORD_TOKEN=your_development_bot_token
CLIENT_ID=your_development_application_id

# SourceXchange API Configuration
API_BASE_URL=https://sourcexchange.net/api/v1
API_TOKEN=your_development_api_token
PRODUCT_ID=your_test_product_id

# Discord Role Configuration
DISCORD_ROLE_ID=your_test_role_id

# Environment
NODE_ENV=development

⚠️ Important: Use separate tokens for development and production!

Development Workflow

Running the Bot

Start the bot in development mode:

npm start

For automatic restarts on file changes, use nodemon:

npm install -g nodemon
nodemon bot.js

Code Quality

Format Code with Prettier

# Format all files
npm run format

# Check formatting without changes
npm run format:check

Lint Code with ESLint

# Run ESLint
npm run lint

# Auto-fix issues
npm run lint:fix

Before Committing

Always run both checks:

npm run format
npm run lint:fix

Project Structure

sourcexchange-sync-bot/
├── .github/
│   ├── FUNDING.yml          # GitHub Sponsors configuration
│   └── workflows/
│       └── ci.yml           # GitHub Actions CI/CD
├── bot.js                   # Main bot file
├── .env.example             # Environment variables template
├── .env                     # Your local config (gitignored)
├── .gitignore              # Git ignore rules
├── .prettierrc             # Prettier configuration
├── eslint.config.js        # ESLint configuration
├── LICENSE.md              # MIT License
├── package.json            # Dependencies and scripts
└── README.md               # Project overview

Key Files Explained

bot.js

Main bot logic containing:

  • Discord client initialization
  • Slash command definitions
  • API integration functions
  • Command handlers

Key Functions:

  • apiGet(path) - Fetch data from SourceXchange API
  • getUserProductAccesses(discordId) - Get user's purchased products
  • deployCommands() - Register slash commands with Discord

.env

Environment configuration:

  • Discord bot credentials
  • SourceXchange API settings
  • Feature flags

package.json

Project metadata and scripts:

  • npm start - Run the bot
  • npm run format - Format code
  • npm run lint - Check code quality

Making Changes

1. Create a Branch

git checkout -b feature/your-feature-name

Branch naming conventions:

  • feature/ - New features
  • fix/ - Bug fixes
  • docs/ - Documentation updates
  • refactor/ - Code refactoring

Examples:

git checkout -b feature/add-multi-product-support
git checkout -b fix/role-hierarchy-check
git checkout -b docs/update-installation-guide

2. Make Your Changes

Edit the code in your editor. For VS Code users:

Recommended Extensions:

  • ESLint
  • Prettier - Code formatter
  • GitLens

3. Test Your Changes

  1. Start your test bot:

    npm start
  2. Test in your development Discord server:

    • Run /products command
    • Run /sync command
    • Verify error handling
    • Check edge cases
  3. Review console output for errors

4. Format and Lint

npm run format
npm run lint:fix

5. Commit Changes

git add .
git commit -m "feat: add multi-product support"

Commit Message Format:

<type>: <description>

[optional body]

Types:

  • feat: - New feature
  • fix: - Bug fix
  • docs: - Documentation only
  • style: - Code style (formatting, no logic change)
  • refactor: - Code refactoring
  • test: - Adding tests
  • chore: - Maintenance tasks

Examples:

git commit -m "feat: add support for multiple products"
git commit -m "fix: handle missing role gracefully"
git commit -m "docs: update API integration guide"

6. Push to Your Fork

git push origin feature/your-feature-name

7. Create Pull Request

  1. Go to your fork on GitHub
  2. Click "Compare & pull request"
  3. Fill out the PR template
  4. Submit the pull request

Keeping Your Fork Updated

Sync with Upstream

# Fetch latest changes
git fetch upstream

# Switch to main branch
git checkout main

# Merge upstream changes
git merge upstream/main

# Push to your fork
git push origin main

Rebase Your Branch

If main has changed since you created your branch:

git checkout feature/your-feature-name
git rebase main

Resolve any conflicts, then:

git push origin feature/your-feature-name --force

Testing

Manual Testing Checklist

Before submitting a PR, test:

  • /products command works
  • /sync command works
  • Role is added when user has product
  • Role is removed when user doesn't have product
  • Error messages are clear
  • Bot handles missing permissions gracefully
  • Bot handles API errors gracefully
  • Logging is appropriate (not too verbose)

Test Scenarios

Scenario 1: User Has Product

  1. User purchases product on SourceXchange
  2. User links Discord account
  3. User runs /sync
  4. Verify role is granted

Scenario 2: User Doesn't Have Product

  1. User doesn't own product
  2. User runs /sync
  3. Verify appropriate message
  4. Verify no role granted

Scenario 3: User Lost Access

  1. User has role
  2. User's product access expires
  3. User runs /sync
  4. Verify role is removed

Scenario 4: Discord Not Linked

  1. User hasn't linked Discord
  2. User runs /products or /sync
  3. Verify clear error message

Scenario 5: Permission Issues

  1. Bot doesn't have "Manage Roles"
  2. User runs /sync
  3. Verify graceful error handling

Debugging

Enable Verbose Logging

Set in .env:

NODE_ENV=development

This enables:

  • API request/response logging
  • Detailed error messages
  • Command execution traces

Common Debug Points

Add console logs at key points:

// API calls
console.log("Fetching product accesses for user:", discordId);

// Role management
console.log("Current roles:", member.roles.cache.map(r => r.name));
console.log("Target role:", role.name);
console.log("Has product:", hasProduct);
console.log("Has role:", hasRole);

// Error handling
catch (error) {
  console.error("Full error:", error);
  console.error("Error message:", error.message);
  console.error("Error stack:", error.stack);
}

Using VS Code Debugger

Create .vscode/launch.json:

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Launch Bot",
      "skipFiles": ["<node_internals>/**"],
      "program": "${workspaceFolder}/bot.js",
      "envFile": "${workspaceFolder}/.env"
    }
  ]
}

Set breakpoints and press F5 to debug.

Environment Setup Tips

Create Test Discord Server

  1. Create a new Discord server for testing
  2. Invite your development bot
  3. Create test roles
  4. Test in isolation from production

Use Separate SourceXchange Products

  • Create test products on SourceXchange
  • Use test product IDs in development
  • Avoid affecting production users

Bot Token Security

⚠️ Never commit tokens!

  • Keep .env in .gitignore
  • Use separate development tokens
  • Regenerate tokens if exposed
  • Use environment variables in CI/CD

CI/CD Pipeline

The project uses GitHub Actions for automated checks.

Workflows

Located in .github/workflows/ci.yml:

  • ✅ Prettier formatting check
  • ✅ ESLint validation
  • Runs on: push, pull requests

Local CI Simulation

Run the same checks locally:

npm run format:check
npm run lint

Fix any issues before pushing.

Production Deployment

Using PM2

Install PM2:

npm install -g pm2

Start bot:

pm2 start bot.js --name sourcexchange-bot
pm2 save
pm2 startup

Monitor:

pm2 logs sourcexchange-bot
pm2 status

Using systemd (Linux)

Create /etc/systemd/system/sourcexchange-bot.service:

[Unit]
Description=SourceXchange Sync Bot
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/path/to/sourcexchange-sync-bot
Environment=NODE_ENV=production
ExecStart=/usr/bin/node bot.js
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

Enable and start:

sudo systemctl enable --now sourcexchange-bot
sudo systemctl status sourcexchange-bot

View logs:

sudo journalctl -u sourcexchange-bot -f

Using Docker (Optional)

Create Dockerfile:

FROM node:24-alpine

WORKDIR /

COPY package*.json ./
RUN npm ci --only=production

COPY . .

CMD ["node", "bot.js"]

Build and run:

docker build -t sourcexchange-bot .
docker run -d --name sourcexchange-bot --env-file .env sourcexchange-bot

Resources

Documentation

Tools

Community

Related Pages

Clone this wiki locally