Skip to content

10. API Integrations

ad1107 edited this page May 24, 2025 · 1 revision

API Integrations

This guide covers all external APIs used by UtilsBot+, their setup requirements, and troubleshooting information.

📋 Quick Navigation


🤖 Google Gemini AI

Status: Required for AI commands (/ask, /chat)
Cost: Free tier available
Documentation: Google AI Studio

Setup

  1. Get API Key:

  2. Configure Environment:

    GEMINI_API_KEY=your_gemini_api_key_here
  3. Model Configuration:

    import google.generativeai as genai
    genai.configure(api_key=settings.gemini_api_key)
    model = genai.GenerativeModel('models/gemini-1.5-flash')

Usage Limits

Tier Requests/Minute Input Tokens Output Tokens Cost
Free 15 ~1M 8,192 Free
Pro 360 ~2M 32,768 $0.125/1M tokens

Implementation Details

async def generate_response(prompt: str) -> str:
    try:
        response = await model.generate_content_async(
            prompt,
            generation_config=genai.types.GenerationConfig(
                max_output_tokens=1000,
                temperature=0.7
            )
        )
        return response.text
    except Exception as e:
        logger.error(f"Gemini API error: {e}")
        raise

Error Handling

  • Rate Limit Exceeded: 3-minute user cooldown
  • Token Limit: Response truncation with warning
  • API Errors: Graceful fallback with error messages

📸 Screenshot Services

Status: Optional (has fallback)
Primary Service: ScreenshotOne
Fallback: Basic placeholder generation

Primary: ScreenshotOne API

  1. Get API Key:

  2. Configure Environment:

    SCREENSHOT_API_KEY=your_screenshot_api_key
  3. API Parameters:

    params = {
        'url': url,
        'viewport_width': 1920,
        'viewport_height': 1080,
        'format': 'png',
        'full_page': full_page,
        'block_ads': True,
        'cache': True,
        'timeout': 30
    }

Pricing (ScreenshotOne)

Plan Screenshots/Month Price
Free 100 Free
Starter 1,000 $9/month
Pro 10,000 $29/month

Fallback System

Without API key, the bot generates simple placeholder images:

# Creates a 400x300 image with URL text
placeholder = create_placeholder_image(url, 400, 300)

🌍 IP Geolocation

Status: Free service
Service: ip-api.com
Cost: Free (1000 requests/month)

Setup

No API key required! The service provides:

  • Country & Region: Full location details
  • ISP Information: Internet service provider
  • Coordinates: Latitude/longitude
  • Timezone: Local timezone data

Implementation

async def get_ip_info(ip_address: str) -> dict:
    url = f"http://ip-api.com/json/{ip_address}"
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

Response Format

{
    "country": "United States",
    "regionName": "California",
    "city": "Mountain View",
    "isp": "Google LLC",
    "lat": 37.4056,
    "lon": -122.0775,
    "timezone": "America/Los_Angeles",
    "status": "success"
}

Usage Limits

  • Free Tier: 1,000 requests/month
  • Rate Limit: 45 requests/minute
  • Features: Basic geolocation data

⚡ Rate Limiting & Usage

Global Rate Limiting

# Per-user cooldowns
@cooldown(rate=3, per=60)  # 3 commands per minute
async def ai_command(interaction):
    pass

@cooldown(rate=5, per=300)  # 5 screenshots per 5 minutes
async def screenshot_command(interaction):
    pass

Usage Tracking

The bot tracks API usage in the database:

CREATE TABLE api_usage (
    id INTEGER PRIMARY KEY,
    user_discord_id VARCHAR(20),
    api_name VARCHAR(50),  -- 'gemini', 'screenshot', etc.
    usage_count INTEGER DEFAULT 0,
    last_used DATETIME,
    created_at DATETIME
);

Monitoring Commands

/info  # Shows API status and usage
/help  # Displays rate limits per command

🔧 Troubleshooting

Common Issues

"Gemini API Error"

Error: Rate limit exceeded

Solution: Wait 3 minutes or upgrade to Pro tier

"Screenshot Failed"

Error: Failed to capture screenshot

Solutions:

  1. Check if URL is accessible
  2. Verify SCREENSHOT_API_KEY
  3. Ensure bot has "Attach Files" permission

"IP Lookup Failed"

Error: Invalid IP address

Solutions:

  1. Verify IP format (IPv4/IPv6)
  2. Check if IP is private (192.168.x.x won't work)
  3. Ensure bot has internet access

Debug Mode

Enable detailed API logging:

DEBUG=true

Check logs in logs/bot.log for detailed error information.

API Status Checking

# Check if APIs are working
/info  # Shows API connectivity status

Environment Validation

The bot validates all API configurations on startup:

# Validates required API keys
if not settings.gemini_api_key:
    logger.warning("Gemini API key not found - AI commands disabled")

if not settings.screenshot_api_key:
    logger.info("Screenshot API key not found - using fallback mode")

📚 Additional Resources


🔗 External Links

Clone this wiki locally