# CLI Reference

Sonora v1.2.8 provides a comprehensive command-line interface for debugging, management, and automation.

# Table of Contents

  • Overview
  • Installation
  • Core Commands
  • Debug Commands
  • Management Commands
  • Automation
  • Configuration

# Overview

The Sonora CLI (sonoractl) provides tools for:

  • Environment validation and health checks
  • Real-time debugging and monitoring
  • Session management and snapshots
  • Performance profiling and optimization
  • Plugin management and development
  • Batch operations and automation

# Getting Help

# Show all commands
sonoractl --help

# Get help for specific command
sonoractl <command> --help

# Show version
sonoractl --version

# Installation

# System Installation

# Install Sonora
pip install sonora

# Verify installation
sonoractl --version

# Development Installation

# Clone repository
git clone https://github.com/code-xon/sonora.git
cd sonora

# Install with CLI
pip install -e .

# Core Commands

# Environment & Health

# Check environment and dependencies
sonoractl doctor

# Quick health check
sonoractl health-check --host localhost --port 2333

# Validate configuration
sonoractl validate-config

# Show system information
sonoractl info

# Lavalink Management

# Test Lavalink connection
sonoractl lavalink test --host localhost --port 2333

# Get Lavalink statistics
sonoractl lavalink stats

# Check Lavalink version
sonoractl lavalink version

# Monitor Lavalink performance
sonoractl lavalink monitor --interval 5

# Debug Commands

# Real-time Monitoring

# Start wiretap (protocol debugging)
sonoractl wiretap start --port 8080

# Monitor player activity
sonoractl monitor players --guild-id 123456789

# Track queue changes
sonoractl monitor queue --guild-id 123456789

# Debug autoplay decisions
sonoractl debug autoplay --guild-id 123456789

# Performance Profiling

# Profile current performance
sonoractl profile

# Run performance benchmarks
sonoractl benchmark

# Memory usage analysis
sonoractl profile memory

# CPU usage tracking
sonoractl profile cpu --duration 60

# Log Analysis

# View recent logs
sonoractl logs tail --lines 50

# Search logs for errors
sonoractl logs grep "ERROR" --last 1h

# Export logs for analysis
sonoractl logs export --output logs.json --last 24h

# Management Commands

# Session Management

# Save current session
sonoractl snapshot save --name "my_session"

# List saved snapshots
sonoractl snapshot list

# Load session snapshot
sonoractl snapshot restore --name "my_session"

# Delete old snapshots
sonoractl snapshot cleanup --older-than 7d

# Plugin Management

# List installed plugins
sonoractl plugin list

# Enable plugin
sonoractl plugin enable my_plugin

# Disable plugin
sonoractl plugin disable my_plugin

# Show plugin information
sonoractl plugin info my_plugin

# Install plugin from URL
sonoractl plugin install https://example.com/plugin.zip

# Uninstall plugin
sonoractl plugin uninstall my_plugin

# Queue Operations

# Inspect queue for guild
sonoractl queue inspect --guild-id 123456789

# Clear queue
sonoractl queue clear --guild-id 123456789

# Export queue to file
sonoractl queue export --guild-id 123456789 --output queue.json

# Import queue from file
sonoractl queue import --guild-id 123456789 --input queue.json

# Autoplay Control

# Show autoplay status
sonoractl autoplay status --guild-id 123456789

# Change autoplay strategy
sonoractl autoplay strategy --guild-id 123456789 --strategy similar_genre

# Enable/disable autoplay
sonoractl autoplay toggle --guild-id 123456789 --state on

# Get autoplay recommendations
sonoractl autoplay recommend --guild-id 123456789 --count 5

# Automation

# Batch Operations

# Bulk user management
sonoractl batch users --action ban --users user1,user2,user3

# Mass queue operations
sonoractl batch queue --action clear --guilds 123,456,789

# Bulk plugin updates
sonoractl batch plugins --action update --all

# Scheduled Tasks

# Schedule regular backups
sonoractl schedule backup --interval 1h --retention 7d

# Automated cleanup
sonoractl schedule cleanup --interval 24h

# Performance monitoring
sonoractl schedule monitor --interval 5m

# Scripting Integration

# Use in shell scripts
#!/bin/bash
if sonoractl health-check --quiet; then
    echo "Sonora is healthy"
else
    echo "Sonora health check failed"
    exit 1
fi

# JSON output for scripting
sonoractl snapshot list --format json | jq '.snapshots[0].name'

# Configuration

# CLI Configuration

# Set default host
sonoractl config set lavalink.host localhost

# Set default port
sonoractl config set lavalink.port 2333

# Configure logging
sonoractl config set log.level DEBUG

# Show current configuration
sonoractl config show

# Environment Variables

# Override configuration
export SONORACTL_LAVALINK_HOST=remote-server.com
export SONORACTL_LAVALINK_PORT=2333
export SONORACTL_LOG_LEVEL=INFO

# Use in commands
sonoractl lavalink test  # Uses environment variables

# Configuration Files

# Use custom config file
sonoractl --config /path/to/config.json doctor

# Export current configuration
sonoractl config export --output config.json

# Import configuration
sonoractl config import --input config.json

# Advanced Usage

# Interactive Mode

# Start interactive CLI
sonoractl interactive

# Available commands in interactive mode:
# help, exit, doctor, monitor, debug, etc.

# Remote Management

# Connect to remote Sonora instance
sonoractl remote connect --host sonora.example.com --port 8080

# Execute commands remotely
sonoractl remote exec "snapshot save backup"

# Monitor remote instance
sonoractl remote monitor

# Custom Commands

# Create custom CLI commands
from sonoractl.commands import register_command

@register_command
def my_custom_command(args):
    """Custom command description"""
    print("Executing custom command")
    # Your logic here

# Use the command
sonoractl my-custom-command --option value

# API Integration

# Use CLI programmatically
import subprocess
import json

def get_queue_status(guild_id):
    result = subprocess.run([
        'sonoractl', 'queue', 'inspect',
        '--guild-id', str(guild_id),
        '--format', 'json'
    ], capture_output=True, text=True)

    if result.returncode == 0:
        return json.loads(result.stdout)
    else:
        raise Exception(f"CLI command failed: {result.stderr}")

# Troubleshooting

# Common Issues

Command not found

# Check if installed
which sonoractl

# Reinstall if missing
pip install --force-reinstall sonora

Permission denied

# Run with sudo if needed (not recommended)
sudo sonoractl doctor

# Or fix permissions
chmod +x $(which sonoractl)

Connection failed

# Check Lavalink status
sonoractl lavalink test

# Verify configuration
sonoractl config show

Plugin errors

# Check plugin status
sonoractl plugin list

# View plugin logs
sonoractl logs grep "plugin" --last 1h

# Debug Mode

# Enable verbose output
sonoractl --verbose doctor

# Debug specific command
sonoractl --debug lavalink test

# Log all CLI activity
sonoractl config set log.level DEBUG

# Performance Issues

# Profile CLI commands
time sonoractl doctor

# Check memory usage
sonoractl profile memory

# Monitor command execution
sonoractl monitor commands --duration 60

# Examples

# Development Workflow

# Daily development routine
sonoractl doctor                    # Check environment
sonoractl test run                  # Run test suite
sonoractl profile                   # Performance check
sonoractl snapshot save dev_backup  # Backup current state

# Production Monitoring

# Production health checks
sonoractl health-check --comprehensive
sonoractl monitor performance --alert-threshold 80
sonoractl logs analyze --last 1h

# Troubleshooting Session

# Debug a failing bot
sonoractl wiretap start --port 8080  # Monitor protocol
sonoractl debug player --guild-id 123  # Debug specific player
sonoractl logs export --output debug_logs.json  # Export logs
sonoractl snapshot save debug_snapshot  # Save state

# Automation Scripts

#!/bin/bash
# Daily maintenance script

echo "Starting daily maintenance..."

# Health check
if ! sonoractl doctor --quiet; then
    echo "Health check failed!"
    exit 1
fi

# Backup
sonoractl snapshot save "daily_$(date +%Y%m%d)"

# Cleanup old backups
sonoractl snapshot cleanup --older-than 30d

# Performance report
sonoractl profile > "perf_$(date +%Y%m%d).txt"

echo "Maintenance completed successfully!"

This comprehensive CLI reference covers all aspects of managing Sonora v1.2.8 from the command line.

# Show all available commands
sonoractl --help

# Get help for specific command
sonoractl <command> --help

# Use custom Lavalink connection
sonoractl --host 127.0.0.1 --port 2333 --password yourpass <command>

# Environment Commands

# doctor - Environment Diagnostics

Check your environment and dependencies for issues.

sonoractl doctor

Output:

🔍 Sonora Doctor - Environment Check
==================================================
✅ Python: 3.12.1
✅ aiohttp: installed
✅ pydantic: installed
✅ cryptography: installed (optional)
✅ psutil: installed (optional)
🔗 Lavalink: 127.0.0.1:2333
   Use 'sonoractl health-check' to test connection

✅ All checks passed!

Checks Performed:

  • Python version compatibility
  • Required package installation
  • Optional dependency status
  • Lavalink connection configuration

# health-check - Lavalink Health Check

Test connection to your Lavalink server.

sonoractl health-check
sonoractl health-check --host lavalink.example.com --port 2333

Output:

🔗 Testing Lavalink connection...
✅ Connection successful
📊 Lavalink v4.0.0
🎵 Loaded 1200 audio sources
⚡ Uptime: 2h 15m

Tests Performed:

  • Network connectivity
  • Authentication
  • Lavalink version compatibility
  • Audio source availability
  • Server statistics

# Development Commands

# debug - Interactive Debug Monitor

Start an interactive debugging session.

sonoractl debug

Features:

  • Real-time player monitoring
  • Queue inspection
  • Event logging
  • Performance metrics
  • Interactive commands

# profile - Performance Profiling

Profile Sonora's performance and memory usage.

sonoractl profile

Output:

📊 Sonora Performance Profile
==================================================
Execution time: 2.34s
Memory peak: 45.2 MB
Memory current: 32.1 MB

Top 5 most time-consuming functions:
  1. track_loading (0.456s)
  2. queue_processing (0.234s)
  3. filter_application (0.123s)
  4. network_operations (0.089s)
  5. event_dispatch (0.045s)

# benchmark - Performance Benchmarking

Run comprehensive performance benchmarks.

sonoractl benchmark

Tests Performed:

  • Track loading throughput
  • Queue operation performance
  • Memory usage patterns
  • Concurrent operation handling
  • Network latency simulation

# Session Management

# snapshot save - Save Session State

Create a snapshot of current player state.

sonoractl snapshot save

Output:

📸 Session snapshot saved: guild_123_1703123456.json
💡 Use 'sonoractl snapshot list' to see all snapshots

# snapshot list - List Saved Snapshots

Show all available session snapshots.

sonoractl snapshot list

Output:

📁 Saved snapshots:
  • guild_123_1703123456.json (2 minutes ago)
  • guild_456_1703123400.json (5 minutes ago)
  • guild_789_1703123300.json (10 minutes ago)

# snapshot restore - Restore Session State

Restore player state from a snapshot.

sonoractl snapshot restore guild_123_1703123456.json

Output:

🔄 Restoring session from guild_123_1703123456.json...
✅ Session restored successfully
📊 Restored: 1 current track, 5 queued tracks, active filters

# Plugin Management

# plugin list - List Installed Plugins

Show all installed and available plugins.

sonoractl plugin list

Output:

🔌 Installed Plugins:
  ✅ YouTube (v2.1.0) - enabled
  ✅ Spotify (v1.8.3) - enabled
  ✅ SoundCloud (v1.5.2) - disabled
  ⚠️  Bandcamp (v0.9.1) - update available

Available Plugins:
  🆕 Tidal (v1.0.0)
  🆕 Deezer (v1.0.0)

# plugin enable - Enable Plugin

Enable a specific plugin.

sonoractl plugin enable spotify

Output:

🔌 Enabling plugin: spotify
✅ Plugin 'spotify' enabled successfully
🔄 Restarting plugin system...

# plugin disable - Disable Plugin

Disable a specific plugin.

sonoractl plugin disable bandcamp

Output:

🔌 Disabling plugin: bandcamp
✅ Plugin 'bandcamp' disabled successfully

# plugin info - Plugin Information

Show detailed information about a plugin.

sonoractl plugin info youtube

Output:

🔌 Plugin Information: YouTube
=====================================
Status: ✅ Enabled
Version: 2.1.0
Author: Sonora Team
Description: Official YouTube search and playback
Permissions: track.read, track.modify
Dependencies: None
Last Updated: 2024-12-01
Homepage: https://github.com/code-xon/sonora-youtube

# Autoplay Management

# autoplay status - Autoplay Status

Check current autoplay configuration and status.

sonoractl autoplay status

Output:

🎵 Autoplay Status
==================
Status: ✅ Enabled
Strategy: similar_artist
Fallback Playlist: global_fallback
Max History: 50 tracks
Smart Shuffle: ✅ Enabled
Recent Recommendations: 12
Success Rate: 94.2%

# autoplay strategy - Set Autoplay Strategy

Change the autoplay recommendation strategy.

sonoractl autoplay strategy similar_genre

Available Strategies:

  • similar_artist - Recommend tracks by same artist
  • similar_genre - Recommend tracks in similar genres
  • popularity - Recommend popular tracks
  • random - Random track selection

Output:

🎵 Changed autoplay strategy to: similar_genre
✅ Strategy updated successfully

# Queue Management

# queue inspect - Queue Inspection

Inspect the current queue state for a guild.

sonoractl queue inspect --guild-id 123456789

Output:

📋 Queue Inspection - Guild 123456789
======================================
Current Track:
  🎵 "Never Gonna Give You Up" by Rick Astley
  📊 Position: 1:23 / 3:32 (38%)
  🔊 Volume: 75%

Upcoming (5 tracks):
  1. "Take On Me" by a-ha
  2. "Billie Jean" by Michael Jackson
  3. "Sweet Child O' Mine" by Guns N' Roses
  4. "Livin' on a Prayer" by Bon Jovi
  5. "Wonderwall" by Oasis

History (3 tracks):
  • "Bohemian Rhapsody" by Queen
  • "Stairway to Heaven" by Led Zeppelin
  • "Hotel California" by Eagles

Queue Stats:
  📊 Total tracks: 8
  🔄 Loop mode: none
  🔀 Shuffle: disabled
  📈 Skip fatigue threshold: 3
  🎯 Smart features: enabled

# Wiretap Debugging

# wiretap start - Start Protocol Wiretap

Begin capturing Lavalink protocol packets for debugging.

sonoractl wiretap start

Output:

🎯 Starting Lavalink protocol wiretap...
📡 Capturing packets on all connections
💡 Use 'sonoractl wiretap stop' to stop and view captured packets
🔍 Real-time monitoring enabled

# wiretap stop - Stop Wiretap and Show Results

Stop packet capture and display captured packets.

sonoractl wiretap stop

Output:

🛑 Wiretap stopped
📦 Captured 47 packets (showing last 10):

  1. [OUT] play - {"track": "QAAA...", "guildId": "123"}
  2. [IN]  playerUpdate - {"guildId": "123", "state": {"position": 15000}}
  3. [OUT] volume - {"guildId": "123", "volume": 75}
  4. [IN]  playerUpdate - {"guildId": "123", "state": {"volume": 75}}
  5. [OUT] seek - {"guildId": "123", "position": 30000}
  6. [IN]  playerUpdate - {"guildId": "123", "state": {"position": 30000}}
  7. [OUT] filters - {"guildId": "123", "volume": 1.0, "equalizer": [...]}
  8. [IN]  playerUpdate - {"guildId": "123", "state": {"filters": {...}}}
  9. [OUT] pause - {"guildId": "123", "pause": true}
 10. [IN]  playerUpdate - {"guildId": "123", "state": {"paused": true}}

# Advanced Options

# Global Options

# Set custom Lavalink connection
sonoractl --host lavalink.example.com --port 2333 --password mypass command

# Set log level
sonoractl --log-level DEBUG command

# Use JSON output for scripting
sonoractl --json command

# Configuration Files

Create a configuration file for repeated use:

# Create .sonoractl config file
cat > .sonoractl << EOF
host=lavalink.example.com
port=2333
password=mypass
log_level=INFO
EOF

# CLI will automatically use these settings
sonoractl doctor

# Batch Operations

# Process multiple guilds
for guild_id in 123 456 789; do
  echo "Processing guild $guild_id..."
  sonoractl queue inspect --guild-id $guild_id
done

# Bulk plugin management
sonoractl plugin list | grep disabled | while read plugin; do
  sonoractl plugin enable "$plugin"
done

# Error Handling

# Common Error Messages

Connection Failed:

❌ Failed to connect to Lavalink
   Check that Lavalink is running and accessible
   Verify host, port, and password settings

Plugin Not Found:

❌ Plugin 'unknown' not found
   Use 'sonoractl plugin list' to see available plugins

Snapshot Restore Failed:

❌ Failed to restore snapshot
   Snapshot may be corrupted or from incompatible version
   Check snapshot file integrity

# Debug Mode

Enable verbose logging for troubleshooting:

export SONORA_LOG_LEVEL=DEBUG
sonoractl --log-level DEBUG command

# Integration Examples

# Shell Scripts

#!/bin/bash
# Daily maintenance script

echo "🔍 Running daily Sonora maintenance..."

# Health check
if ! sonoractl health-check > /dev/null 2>&1; then
    echo "❌ Lavalink health check failed!"
    exit 1
fi

# Clean old snapshots (older than 7 days)
sonoractl snapshot list | grep "week" | while read snapshot; do
    rm ".sonora_snapshots/$snapshot"
done

# Update plugins
sonoractl plugin list | grep "update available" | while read plugin; do
    echo "Updating $plugin..."
    # Plugin update logic here
done

echo "✅ Maintenance completed successfully"

# Monitoring Integration

#!/bin/bash
# Nagios/Icinga compatible check

OUTPUT=$(sonoractl health-check 2>&1)
EXIT_CODE=$?

if [ $EXIT_CODE -eq 0 ]; then
    echo "OK - $OUTPUT"
    exit 0
else
    echo "CRITICAL - $OUTPUT"
    exit 2
fi

# CI/CD Integration

# .github/workflows/deploy.yml
- name: Health Check
  run: sonoractl health-check

- name: Performance Test
  run: sonoractl benchmark

- name: Create Deployment Snapshot
  run: sonoractl snapshot save

The Sonora CLI provides powerful tools for development, debugging, and production management of your music bot infrastructure.