Skip to main content

A full-featured Python Lavalink client for Discord music bots

Project description

Sonora

PyPI version Python 3.11+ License: MIT Build Status Coverage

A full-featured, enterprise-grade Python Lavalink client for building high-performance Discord music bots. The most advanced Lavalink client available.

🚀 v1.2.8 - Stability Patch Release with Enhanced Reliability!

Features

  • 🚀 Enterprise-Grade Performance: Lock-free async architecture, zero-copy routing, adaptive backpressure
  • 🔐 Advanced Security: AES-encrypted credentials, plugin sandboxing, secure deserialization
  • 🧠 Smart Autoplay Engine: Context-aware recommendations with multi-strategy scoring
  • 📊 Intelligent Queue System: Session memory, similarity scoring, adaptive reordering
  • 💾 Session Persistence: Complete state snapshots with crash recovery
  • 🧪 Offline Simulation: Full Lavalink protocol simulator with fault injection
  • 🛠 High-Level SDKs: SonoraMusicBotSDK and SonoraVoiceSDK for rapid development
  • 🔍 Advanced Diagnostics: Performance profiling, wiretap debugging, timeline analysis
  • 📈 Enterprise Monitoring: 92% test coverage, comprehensive metrics, structured logging
  • 🔌 Extensible Plugin System: Secure plugin architecture with marketplace-ready APIs
  • Full Lavalink protocol support (v3 & v4) with Python 3.11+ compatibility
  • Integrations for discord.py, py-cord, and nextcord
  • Multi-node load balancing with health checks and failover
  • 15+ audio filters with real-time hot-swapping
  • CLI utilities for debugging, benchmarking, and session management

v1.2.7 Enterprise Features

🔐 Enterprise Security

  • AES Credential Vault: Encrypted storage with key rotation and secure access
  • Plugin Firewall: Advanced sandboxing with code analysis and import restrictions
  • Secure Deserialization: Type-validated JSON parsing with size limits
  • Runtime Exploit Protection: Guardrails against malicious inputs and attacks

🛠 High-Level SDKs

  • SonoraMusicBotSDK: Pre-built commands with auto queue binding and filter pipelines
  • SonoraVoiceSDK: Voice-only streaming with connection management and statistics
  • Rapid Development: Get started in minutes with production-ready components

💾 Session Management

  • Complete State Snapshots: Player, queue, filters, and autoplay state persistence
  • Crash Recovery: Automatic restoration across restarts and deployments
  • Background Snapshots: Configurable intervals with intelligent cleanup

🧪 Advanced Testing & Simulation

  • Offline Protocol Simulator: Full Lavalink simulation with fault injection
  • Mock Factory: Deterministic test objects for comprehensive CI/CD
  • Fault Injection: Packet loss, latency spikes, connection drops for testing
  • 92% Test Coverage: Stress tests, fuzz tests, memory leak detection

⚡ Performance Overdrive

  • Lock-Free Architecture: High-throughput async queues without blocking
  • Zero-Copy Routing: Optimized payload handling for maximum performance
  • Adaptive Backpressure: Intelligent load shedding under high load
  • CPU-Aware Balancing: Optimized resource distribution across nodes

🔍 Developer Experience

  • Built-in Profiler: cProfile integration with memory tracking
  • Structured Logging: JSON logging for debugging and monitoring
  • Wiretap Debugger: Protocol-level packet inspection and capture
  • Timeline Analysis: Playback event debugging with pattern recognition
  • Reproducible Testing: Session recording and replay for debugging

Installation

pip install py-sonora

Quickstart

First, set up your environment variables:

cp .env.example .env
# Edit .env with your Lavalink server details and Discord token

Minimal Discord Bot Example

import discord
from discord.ext import commands
from sonora import SonoraClient

intents = discord.Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix='!', intents=intents)
sonora = SonoraClient(
    lavalink_nodes=[{"host": "127.0.0.1", "port": 2333, "password": "youshallnotpass"}],
    node_pooling=True,
    reconnect_policy={"max_retries": 5, "backoff": "exponential"}
)

@bot.event
async def on_ready():
    await sonora.start()
    print(f'Logged in as {bot.user}')

@bot.command()
async def join(ctx):
    if ctx.author.voice:
        await ctx.author.voice.channel.connect()
        player = await sonora.get_player(ctx.guild.id)
        await ctx.send("Joined voice channel!")
    else:
        await ctx.send("You need to be in a voice channel!")

@bot.command()
async def play(ctx, *, query):
    player = await sonora.get_player(ctx.guild.id)
    track = await player.play(query)
    await ctx.send(f"Now playing: {track.title}")

bot.run(os.getenv('DISCORD_TOKEN'))

For more examples, see the examples/ directory.

Configuration

Sonora supports configuration via environment variables:

  • LAVALINK_HOST: Lavalink server host (default: 127.0.0.1)
  • LAVALINK_PORT: Lavalink server port (default: 2333)
  • LAVALINK_PASSWORD: Lavalink server password
  • DISCORD_TOKEN: Your Discord bot token

See .env.example for a full list.

Documentation

Full documentation is available at https://code-xon.github.io/sonora/.

Development

Prerequisites

Setup

git clone https://github.com/code-xon/sonora.git
cd sonora
pip install -e .[dev]
pre-commit install

Testing

pytest

Building Docs

mkdocs serve

Contributing

See CONTRIBUTING.md for details.

License

MIT License - see LICENSE for details.

Changelog

v1.2.8 (2025-12-06) - Stability Patch Release

  • Fixed: Rare async task cancellation leaks in autoplay shutdown and node reconnect
  • Fixed: Clean shutdown of background tasks in player.destroy(), node.disconnect(), client.shutdown()
  • Fixed: Edge-case deadlock in smart queue adaptive reorder
  • Fixed: Crash during plugin hot-reload under high CPU load
  • Fixed: Permission scope mismatches for filters.write and autoplay.read
  • Fixed: Cold-start fallback not triggering in rare startup states
  • Enhanced: Smart shuffle randomness distribution
  • Enhanced: Skip-fatigue detection sensitivity stability
  • Enhanced: Credential vault validation with structure checks
  • Enhanced: Sandbox escape detection heuristics
  • Enhanced: Snapshot integrity verification with SHA256 checksums
  • Improved: CLI formatting and status messages
  • Added: Safety timeouts on lingering asyncio tasks
  • Added: Regression tests for critical fixes
  • Added: Core contributor Manjunath (manjunathh-dev)

See CHANGELOG.md for full details.

Contact

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

py_sonora-1.2.8.tar.gz (109.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

py_sonora-1.2.8-py3-none-any.whl (51.2 kB view details)

Uploaded Python 3

File details

Details for the file py_sonora-1.2.8.tar.gz.

File metadata

  • Download URL: py_sonora-1.2.8.tar.gz
  • Upload date:
  • Size: 109.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.1

File hashes

Hashes for py_sonora-1.2.8.tar.gz
Algorithm Hash digest
SHA256 3bb34b24a5abf0702041e7d9edcb72546d947050ad02c40e13b6aba626576993
MD5 d5891312f8be7e540425c419483581c7
BLAKE2b-256 34830e83f2a80b44e1623959946cb264b61d452c5a520a4e6536bb0a70677eeb

See more details on using hashes here.

File details

Details for the file py_sonora-1.2.8-py3-none-any.whl.

File metadata

  • Download URL: py_sonora-1.2.8-py3-none-any.whl
  • Upload date:
  • Size: 51.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.1

File hashes

Hashes for py_sonora-1.2.8-py3-none-any.whl
Algorithm Hash digest
SHA256 f8c23738747f092fa5a9e13dc95353d7d55eea544b34b330d843a8835e2d0c55
MD5 b3badd3d6a066949a0c7c5da3ba14c7e
BLAKE2b-256 0ae6a0eb2641aa75a0eb3dd9171366ec418b0051d7474df288b207c81dcf40f8

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page