Skip to content

GitHub Integration: Contribution Tracking, XP Rewards & Auto-Roles#1

Open
CodeWithInferno wants to merge 3 commits into
masterfrom
feat/github-integration
Open

GitHub Integration: Contribution Tracking, XP Rewards & Auto-Roles#1
CodeWithInferno wants to merge 3 commits into
masterfrom
feat/github-integration

Conversation

@CodeWithInferno

Copy link
Copy Markdown
Member

Summary

Complete GitHub integration system for LOKUSMD Discord Bot with contribution tracking, XP rewards, and automated role assignment.

Features

🔐 GitHub Account Verification

  • OAuth 2.0 verification with secure callback handling
  • Bio verification as fallback method
  • Database persistence with encryption
  • Beautiful success pages and error handling

📊 Contribution Tracking

  • Fetch commits, PRs, issues, and reviews from lokus-ai/lokus
  • Individual contribution tracking with duplicate prevention
  • Contribution streaks (current and longest)
  • Detailed statistics storage

💬 Commands (11 total)

  • /github stats [@user] - View contribution statistics
  • /github leaderboard [timeframe] - Top 10 contributors (all-time/weekly/monthly)
  • /profile [@user] - Combined Discord + GitHub profile
  • /github verify-bio <username> - Start bio verification
  • /github verify-bio-confirm - Complete bio verification

🎯 XP Rewards

  • Commit: 20 XP
  • PR opened: 50 XP
  • PR merged: 150 XP
  • Issue created: 50 XP
  • PR review: 75 XP
  • Automatic level-up notifications

🏅 Auto-Role Assignment

  • Contributor (5+ PRs) - Green #57F287
  • Core Contributor (20+ PRs) - Blue #5865F2
  • Maintainer (50+ PRs) - Purple #EB459E
  • Bug Hunter (10+ issues) - Orange #FEE75C
  • Code Reviewer (25+ reviews) - Red #ED4245
  • Automatic DM notifications on assignment

⚡ Automation

  • Daily Sync (2 AM) - Updates all GitHub stats and awards XP
  • Weekly Showcase (Monday 10 AM) - Highlights top contributor
  • PR Review Webhooks - Real-time XP awards
  • Release Announcements - Auto-post new releases

Technical Details

Files Created (7 new services/schedulers)

  • src/services/githubBioVerification.ts - Bio verification
  • src/services/githubContributionService.ts - Contribution tracking
  • src/services/githubRoleService.ts - Role assignment
  • src/schedules/githubSyncScheduler.ts - Daily sync
  • src/schedules/developerShowcaseScheduler.ts - Weekly showcase
  • src/web/routes/auth.ts - OAuth callback
  • src/web/public/github-success.html - Success page

Files Modified

  • src/enhanced-bot.ts - New command handlers, XP integration
  • src/services/githubOAuth.ts - Database persistence
  • src/webhooks/githubWebhook.ts - PR review handling
  • register-commands.js - New commands
  • start-bot.sh - Auto-registration

Database Schema

  • github_users - Verified accounts
  • github_stats - Contribution statistics
  • github_contributions - Individual contributions
  • contribution_streaks - Streak tracking

Security

  • CSRF protection with state validation
  • Token encryption in database
  • Rate limit handling
  • Webhook signature verification

Testing

Tested locally with:

  • OAuth verification flow
  • Bio verification flow
  • All command handlers
  • XP reward system
  • Role assignment
  • Schedulers initialization

Configuration

Required environment variables:

GITHUB_CLIENT_ID=your_oauth_app_id
GITHUB_CLIENT_SECRET=your_oauth_secret
GITHUB_REDIRECT_URI=http://localhost:3000/auth/github/callback
GITHUB_TOKEN=your_personal_access_token

Deployment

  1. Set up GitHub OAuth App
  2. Add environment variables to .env
  3. Run ./start-bot.sh (auto-registers commands and starts bot)
  4. Bot will initialize schedulers automatically

Stats

  • 39 files changed
  • 12,439 insertions
  • ~3,250 lines of new code
  • 0 breaking changes

## Features Added

### GitHub Account Verification
- OAuth verification flow with secure callback handling
- Bio verification fallback for users without OAuth access
- Database persistence for verified accounts
- Beautiful success page for OAuth completions

### Contribution Tracking
- Fetch commits, PRs, issues, and reviews from lokus-ai/lokus repo
- Track individual contributions with duplicate prevention
- Calculate contribution streaks (current and longest)
- Store detailed stats in SQLite database

### Commands
- /github stats [@user] - View contribution statistics
- /github leaderboard [timeframe] - Top 10 contributors
- /profile [@user] - Combined Discord + GitHub profile
- /github verify-bio <username> - Bio verification
- /github verify-bio-confirm - Complete bio verification

### XP Rewards System
- Commit: 20 XP
- PR opened: 50 XP
- PR merged: 150 XP
- Issue created: 50 XP
- PR review: 75 XP
- Automatic level-up detection

### Auto-Role Assignment
- Contributor (5+ PRs) - Green
- Core Contributor (20+ PRs) - Blue
- Maintainer (50+ PRs) - Purple
- Bug Hunter (10+ issues) - Orange
- Code Reviewer (25+ reviews) - Red
- Automatic DM notifications on role assignment

### Automation
- Daily sync at 2 AM - Updates all users' GitHub stats
- Weekly showcase on Monday 10 AM - Highlights top contributor
- PR review webhooks - Award XP in real-time
- Release announcements - Auto-post new releases

### Technical Improvements
- Added OAuth callback route with CSRF protection
- Database schema for github_users, github_stats, github_contributions, contribution_streaks
- Rate limit handling for GitHub API
- Comprehensive error handling and logging
- One-command bot startup with auto-registration

## Files Modified
- src/enhanced-bot.ts - Main bot with new command handlers
- src/services/githubOAuth.ts - Added database persistence
- src/webhooks/githubWebhook.ts - Enhanced PR review handling
- register-commands.js - Added new commands
- start-bot.sh - Auto-register commands on startup

## Files Created
- src/services/githubBioVerification.ts - Bio verification service
- src/services/githubContributionService.ts - Contribution tracking
- src/services/githubRoleService.ts - Auto-role assignment
- src/schedules/githubSyncScheduler.ts - Daily sync job
- src/schedules/developerShowcaseScheduler.ts - Weekly showcase
- src/web/routes/auth.ts - OAuth callback handler
- src/web/public/github-success.html - Success page
- setup-clean-onboarding.js - Clean onboarding setup
- update-onboarding.js - Update existing onboarding

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/web/server.ts
Comment on lines +6 to +12
import express, { Express, Request, Response, NextFunction } from 'express';
import helmet from 'helmet';
import cors from 'cors';
import path from 'path';
import logger from '../utils/logger';
import { redisConnection } from '../database/redis';
import { pool } from '../database/connection';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Import database modules that do not exist

The new web server and route files import redisConnection and pool from ../database/redis and ../database/connection, but no src/database directory or modules were added in this commit (the repo only has src/utils/database.ts). TypeScript will fail to compile with “Cannot find module '../database/connection'” as soon as any of these files are built, so the entire dashboard cannot start. Either add the missing database layer or point these imports at the existing database utilities.

Useful? React with 👍 / 👎.

Comment thread src/web/routes/auth.ts
Comment on lines +36 to +53
// Get user from database
const result = await pool.query(`
SELECT
id, discord_id, username, discriminator, avatar_url,
xp, level, reputation_score
FROM users
WHERE discord_id = $1
`, [discord_id]);

if (result.rows.length === 0) {
throw Errors.unauthorized('Invalid credentials');
}

const user = result.rows[0];

// Check if user is banned
if (user.ban_status) {
throw Errors.forbidden('Account is banned');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Banned users never blocked in login route

The login handler selects only id, discord_id, username, discriminator, avatar_url, xp, level, and reputation_score from users but later checks user.ban_status. Because ban_status is not part of the result set, user.ban_status is always undefined and the forbidden branch never executes, allowing banned accounts to authenticate by supplying only a Discord ID.

Useful? React with 👍 / 👎.

Comment on lines 2 to +27
import crypto from 'crypto';
import { EmbedBuilder, TextChannel, ButtonBuilder, ActionRowBuilder, ButtonStyle } from 'discord.js';
import { GitHubService } from '../services/githubService';
import { GitHubPRReviewService } from '../services/githubPRReviews';
import { GitHubWebhookPayload } from '../types';
import { ExtendedClient } from '../types';
import logger from '../utils/logger';
import { config } from '../utils/config';
import { Pool } from 'pg';

export class GitHubWebhookHandler {
private githubService: GitHubService;
private prReviewService: GitHubPRReviewService;
private client: ExtendedClient;
private app: express.Application;
private webhookSecret: string;
private db: Pool;
private rateLimitMap: Map<string, { count: number; resetAt: number }>;
private readonly RATE_LIMIT_WINDOW = 60000; // 1 minute
private readonly RATE_LIMIT_MAX = 50; // 50 requests per minute

constructor(client: ExtendedClient, githubService: GitHubService) {
constructor(client: ExtendedClient, githubService: GitHubService, prReviewService: GitHubPRReviewService, db: Pool) {
this.client = client;
this.githubService = githubService;
this.prReviewService = prReviewService;
this.db = db;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Webhook handler references missing GitHubPRReviewService

The webhook handler now imports GitHubPRReviewService from ../services/githubPRReviews and requires it in the constructor, but no such service file exists in the repository and no call sites were updated to provide the new arguments. Building the project will throw a module resolution error and the handler cannot be instantiated.

Useful? React with 👍 / 👎.

- Add all remaining service files
- Add command implementations
- Add database setup files
- Add utility scripts and configurations
- Update dependencies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant