Red-Lavalink

0.11.1 · active · verified Mon Apr 13

Red-Lavalink is a client library for the Lavalink audio server, specifically designed for use with Red-DiscordBot but usable in other `discord.py` projects. It enables advanced audio playback features for Discord bots, allowing them to connect to Lavalink nodes for powerful music and audio streaming capabilities. The library is actively maintained, with regular updates to support new `discord.py` versions and Lavalink protocol changes. The current stable version is 0.11.1.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up a basic `discord.py` bot using `red-lavalink` to connect to a Lavalink server, join a voice channel, and play music. It includes commands for joining, playing, and stopping audio. Ensure your `DISCORD_BOT_TOKEN`, `LAVALINK_HOST`, `LAVALINK_PORT`, and `LAVALINK_PASSWORD` are set either as environment variables or replaced directly in the code. A running Lavalink Java server is required.

import lavalink
import os
from discord.ext.commands import Bot, Context
import discord

# Replace with your bot token and Lavalink credentials
BOT_TOKEN = os.environ.get('DISCORD_BOT_TOKEN', 'YOUR_BOT_TOKEN')
LAVALINK_HOST = os.environ.get('LAVALINK_HOST', 'localhost')
LAVALINK_PORT = int(os.environ.get('LAVALINK_PORT', '2333'))
LAVALINK_PASSWORD = os.environ.get('LAVALINK_PASSWORD', 'youshallnotpass')

class MyBot(Bot):
    def __init__(self):
        super().__init__(command_prefix='!', intents=discord.Intents.default())

    async def setup_hook(self):
        # Initialize Lavalink AFTER the bot is ready
        await lavalink.initialize(
            self, 
            host=LAVALINK_HOST, 
            password=LAVALINK_PASSWORD, 
            port=LAVALINK_PORT
        )
        print(f"Lavalink initialized to {LAVALINK_HOST}:{LAVALINK_PORT}")

    async def on_ready(self):
        print(f'Logged in as {self.user} (ID: {self.user.id})')
        print('------')

    async def on_voice_state_update(self, member, before, after):
        # Handle disconnects if the bot is alone in a voice channel
        if member == self.user and not after.channel:
            # Bot disconnected from voice
            player = lavalink.get_player(member.guild.id)
            if player:
                await player.disconnect()

    async def on_lavalink_event(self, player, event, extra=None):
        print(f"Lavalink Event: {event} for player in guild {player.guild.id}")


    @commands.command()
    async def join(self, ctx: Context, *, channel: discord.VoiceChannel = None):
        """Joins a voice channel."""
        if not channel and not ctx.author.voice:
            return await ctx.send("You are not in a voice channel nor specified one.")

        channel = channel or ctx.author.voice.channel
        player = await lavalink.connect(channel)
        await ctx.send(f"Joined {channel.name}")

    @commands.command()
    async def play(self, ctx: Context, *, query: str):
        """Searches and plays a song."""
        player = lavalink.get_player(ctx.guild.id)
        if not player or not player.is_connected:
            return await ctx.send("I am not connected to a voice channel.")

        tracks = await player.search_yt(query)
        if not tracks:
            return await ctx.send("No tracks found.")

        player.add(requester=ctx.author, track=tracks[0])
        if not player.is_playing:
            await player.play()
            await ctx.send(f"Now playing: {tracks[0].title}")
        else:
            await ctx.send(f"Added to queue: {tracks[0].title}")

    @commands.command()
    async def stop(self, ctx: Context):
        """Stops playback and clears the queue."""
        player = lavalink.get_player(ctx.guild.id)
        if not player or not player.is_connected:
            return await ctx.send("I am not connected to a voice channel.")
        
        await player.stop()
        player.queue.clear()
        await ctx.send("Playback stopped and queue cleared.")

bot = MyBot()
bot.run(BOT_TOKEN)

view raw JSON →