Skip to content

Webhook Integration

Garot Conklin edited this page Dec 8, 2024 · 1 revision

Webhook Integration

Overview

This document details the webhook integration between GitHub and the fleXRPL Discord Bot, including setup, configuration, and event handling.

Setup Process

1. Discord Configuration

/webhook setup channel:#github-events secret:your-webhook-secret

2. GitHub Repository Setup

  1. Navigate to repository settings
  2. Select "Webhooks"
  3. Add webhook:
    Payload URL: https://your-bot-domain.com/webhook
    Content type: application/json
    Secret: your-webhook-secret
    
  4. Select events:
    • Repository events
    • Issues
    • Pull requests
    • Discussions
    • Stars

Webhook Security

Secret Management

# Example webhook secret validation
import hmac
import hashlib

def verify_signature(payload_body, secret, signature):
    expected = hmac.new(
        secret.encode('utf-8'),
        payload_body,
        hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(f"sha256={expected}", signature)

Security Best Practices

  • Rotate webhook secrets regularly
  • Use environment variables
  • Implement rate limiting
  • Validate payload signatures

Event Processing

Supported Events

Event Type Description Default Channel
push Repository pushes #github-activity
pull_request PR activities #pull-requests
issues Issue activities #issues
discussions Discussion activities #discussions

Event Payload Example

{
  "event": "pull_request",
  "action": "opened",
  "repository": {
    "full_name": "fleXRPL/flexrpl-discord-bot"
  },
  "pull_request": {
    "title": "Feature Implementation",
    "user": {
      "login": "username"
    }
  }
}

Message Formatting

Default Templates

Pull Request

🔵 New Pull Request in {repository}
Title: {title}
Author: {author}
{url}

Issues

📝 New Issue in {repository}
Title: {title}
Author: {author}
{url}

Custom Formatting

# Example custom formatter
async def format_message(event_type, payload):
    templates = {
        'pull_request': '🔵 PR: {title}',
        'issues': '📝 Issue: {title}',
        'push': '⬆️ Push: {commits} commits'
    }
    return templates[event_type].format(**payload)

Error Handling

Common Issues

Error Cause Resolution
401 Invalid secret Verify webhook secret
404 Wrong endpoint Check webhook URL
429 Rate limited Implement backoff

Error Recovery

async def process_webhook(payload, retries=3):
    for attempt in range(retries):
        try:
            return await process_event(payload)
        except Exception as e:
            if attempt == retries - 1:
                raise
            await asyncio.sleep(2 ** attempt)

Rate Limiting

GitHub Limits

  • 5000 requests per hour
  • Webhook delivery timeout: 10s
  • Maximum payload size: 25MB

Implementation

from fastapi import FastAPI, HTTPException
from fastapi.middleware.throttling import ThrottlingMiddleware

app = FastAPI()
app.add_middleware(
    ThrottlingMiddleware,
    rate_limit=100,
    time_window=60
)

Monitoring

Metrics Collection

  • Webhook delivery rate
  • Processing success rate
  • Response time
  • Error frequency

Health Checks

@app.get("/health")
async def health_check():
    return {
        "status": "healthy",
        "webhook_processor": "running",
        "last_event": last_event_timestamp
    }

Testing

Local Development

  1. Use ngrok for local webhook testing:

    ngrok http 8000
  2. Configure test webhook:

    Payload URL: https://your-ngrok-url/webhook
    

Test Events

# Test payload
test_payload = {
    "event": "pull_request",
    "action": "opened",
    "repository": {
        "full_name": "test/repo"
    }
}

Deployment

Environment Variables

DISCORD_WEBHOOK_SECRET=your-secret
GITHUB_WEBHOOK_SECRET=your-github-secret
DISCORD_BOT_TOKEN=your-bot-token

Railway.app Configuration

[build]
builder = "nixpacks"
watchPatterns = ["src/**"]

[deploy]
startCommand = "uvicorn main:app --host 0.0.0.0 --port $PORT"
healthcheckPath = "/health"
healthcheckTimeout = 5

Troubleshooting

Common Problems

  1. Webhook Not Delivering

    • Verify URL is correct
    • Check secret matches
    • Confirm events are selected
  2. Message Not Appearing

    • Check channel permissions
    • Verify bot is online
    • Review event configuration
  3. Rate Limiting

    • Implement exponential backoff
    • Monitor usage metrics
    • Optimize payload processing

This documentation is maintained by the fleXRP team.

Clone this wiki locally