> ## Knowledge Base Index
> Fetch the complete knowledge base index at: https://help.squarecloud.app/sitemap.xml
> Use this file to discover available pages before exploring further.
> Pure-Markdown content can be obtained by appending a '.md' suffix to the content URLs listed in the sitemap (without the trailing slash).

# How to create a music bot (Lavalink)

# How to Host a Music Bot with Lavalink on Square Cloud

If you've ever tried to create or host a Discord music bot recently, you know that processing audio directly within the bot's application can consume a lot of CPU and cause stuttering during playback. The professional solution to this is **Lavalink**, a standalone Java-based audio server specifically optimized for Discord.

In this tutorial, you will learn step-by-step how to host both the Lavalink server and your music bot on **Square Cloud**, ensuring stability and high-quality audio 24/7.

---

## 🛠️ Solution Architecture

To make the system work, we will split the project into two independent applications within Square Cloud:

1. **The Lavalink Server:** Responsible for connecting to YouTube/Spotify/SoundCloud, downloading the audio, decoding, and broadcasting it.
2. **The Discord Bot:** Responsible for receiving user commands (`!play`, `!skip`) and managing the queue, sending playback instructions to Lavalink.

---

## Step 1: Configuring and Hosting Lavalink

Lavalink needs a configuration file called `application.yml` and the executable `.jar` file.

### 1. Lavalink File Structure
Create a folder on your computer named `lavalink-server` with the following files:

* `lavalink.jar` (Download the latest version from the official Lavalink GitHub repository)
* `application.yml`

### 2. Configuring `application.yml`
This is the file that defines the port and password your bot will use to connect. Use the base configuration below:

```yaml
server:
  port: 80
  address: 0.0.0.0
lavalink:
  server:
    password: "YOUR_SUPER_SECURE_PASSWORD"
    sources:
      youtube: true
      bandcamp: true
      soundcloud: true
      twitch: true
      vimeo: true
      mixer: false
      http: true
      local: false
    filters:
      volume: true
      equalizer: true
    bufferDurationMs: 400
    youtubePlaylistLoadLimit: 6 // Playlist page limit
    playerUpdateInterval: 5
    youtubeSearchEnabled: true
    soundcloudSearchEnabled: true
    gc-warnings: true
```

> ⚠️ **Memory Note:** Lavalink runs on the JVM (Java Virtual Machine), which tends to be resource-intensive. We recommend allocating at least **512MB** of RAM to prevent crashes when loading heavy tracks.

### 3. Uploading to Square Cloud
1. Compress the files (`lavalink.jar`, `application.yml`) into a **.zip** file.
2. Go to the Square Cloud Dashboard, click **New application**, attach the zip file, select the jar file as the main file, and check "publish to web".
3. Once uploaded, go to your Lavalink's **Settings** tab on Square Cloud and copy the **Public Domain** from the **Network** tab (e.g., `your-lavalink.squareweb.app`).

---

## Step 2: Configuring the Music Bot

Now that the audio server is online, you can choose your preferred programming language to build the bot. Below are examples in **Node.js** and **Python**.

### Option A: Python Implementation (using `wavelink`)

For Python projects, the `wavelink` library is the most robust and modern integration with Lavalink.

#### 1. Required files:
* `main.py`
* `requirements.txt`

#### 2. Dependencies (`requirements.txt`):
```text
discord.py
wavelink
```

#### 3. Bot Code (`main.py`):
```python
import discord
from discord.ext import commands
import wavelink

class MusicBot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.default()
        intents.message_content = True
        super().__init__(command_prefix="!", intents=intents)

    async def setup_hook(self):
        # Configures the Lavalink node pointing to Square Cloud
        node = wavelink.Node(
            uri="[https://your-lavalink.squareweb.app:443](https://your-lavalink.squareweb.app:443)", # Generated domain with port 443 (SSL)
            password="YOUR_SUPER_SECURE_PASSWORD"
        )
        await wavelink.Pool.connect(nodes=[node], client=self)

bot = MusicBot()

@bot.event
async def on_ready():
    print(f"Bot logged in as {bot.user}")

@bot.event
async def on_wavelink_node_ready(payload: wavelink.NodeReadyEventPayload):
    print(f"Lavalink Node \"{payload.node.identifier}\" is connected and ready!")

@bot.command()
async def play(ctx: commands.Context, *, search: str):
    if not ctx.author.voice:
        return await ctx.send("You need to be in a voice channel!")

    # Connects to the voice channel if not connected
    if not ctx.voice_client:
        vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
    else:
        vc: wavelink.Player = ctx.voice_client

    # Searches for the song
    tracks = await wavelink.Tracks.search(search)
    if not tracks:
        return await ctx.send("No song found.")

    track = tracks[0]
    await vc.play(track)
    await ctx.send(f"Now playing: **{track.title}**")

bot.run("YOUR_DISCORD_BOT_TOKEN")
```

---

### Option B: Node.js Implementation (using `erela.js`)

If you prefer JavaScript/TypeScript, you can use the structure below.

#### 1. Required files:
* `index.js`
* `package.json`

#### 2. Dependencies (`package.json`):
```json
{
  "dependencies": {
    "discord.js": "^14.x",
    "erela.js": "^2.x"
  }
}
```

#### 3. Bot Code (`index.js`):
```javascript
const { Client, GatewayIntentBits } = require("discord.js");
const { Manager } = require("erela.js");

const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent,
        GatewayIntentBits.GuildVoiceStates
    ]
});

client.manager = new Manager({
    nodes: [
        {
            host: "your-lavalink.squareweb.app", // Domain provided by Square Cloud
            port: 443, // Default secure port for HTTPS/WSS
            password: "YOUR_SUPER_SECURE_PASSWORD",
            secure: true // Forces the use of Square Cloud's SSL/TLS
        }
    ],
    send(id, payload) {
        const guild = client.guilds.cache.get(id);
        if (guild) guild.shard.send(payload);
    }
});

client.on("raw", (d) => client.manager.updateVoiceState(d));

client.once("ready", () => {
    console.log(`Bot logged in as ${client.user.tag}`);
    client.manager.init(client.user.id);
});

client.manager.on("nodeConnect", node => console.log(`Lavalink Node "${node.options.identifier}" connected.`));
client.manager.on("nodeError", (node, error) => console.log(`Node Error: ${error.message}`));

client.login("YOUR_DISCORD_BOT_TOKEN");
```

---

## Step 3: Putting It All Together

1. On the Square Cloud dashboard, start your **Lavalink Server** and make sure it displays the `Online` status.
2. Choose one of the options above (Python or Node.js), and place all the files from the chosen bot's folder into a **.zip** file.
3. Upload the bot's zip file to Square Cloud using the **New application** button.
4. Start the bot and open the logs terminal. If the connection is successful, you will see the message confirming that the Lavalink Node is ready.

---

## 💡 Optimization and Troubleshooting Tips

* **Connection Error (WebSocket Error / Connection Refused):** Square Cloud manages web domains under secure connections with their own SSL certificates. Therefore, when configuring your bot (whether in Python or Node.js), you must use the public port `443` and enable the `secure / https / wss` parameter, instead of trying to access the internal port `80` directly.
* **Audio Drops and Latency:** Audio processing relies heavily on available CPU. Monitor Lavalink resources in the Dashboard. If you notice recurring spikes of 100% CPU usage when decoding streams, consider increasing the allocated resources for both the Lavalink server and the bot to ensure more processing cores.
* **Bot Stability:** Music bots tend to accumulate very large queue objects in RAM. Frequently monitor the bot's consumption to mitigate *Memory Leaks* by performing periodic cleanups of inactive queues.

---

## ⚠️ The Big Challenge: YouTube IP Restrictions (Sign-in Required)

If you set everything up correctly and, when trying to play a song, the bot simply skips the track or displays an error like `403 Forbidden` or `Sign-in required`, you have just run into YouTube's protection.

YouTube aggressively blocks requests coming from **datacenter IPs** (such as Square Cloud, AWS, Google Cloud servers, etc.) to prevent abuse and audio web scraping. Since thousands of bots share the same IP ranges of large servers, these IPs quickly end up on the platform's "blacklist".

### How to bypass this problem?

To make your Lavalink on Square Cloud work stably with YouTube links, you have three main paths:

1. **Use the Youtube-Source Plugin with Cookies:** The latest versions of Lavalink sources allow you to export a cookies file from an alternative YouTube account (using browser extensions like *Get cookies.txt LOCALLY*) and configure it on the server. This simulates a real, authenticated user.
2. **Switch to Alternative Sources:** Configuring the bot to natively use **SoundCloud**, **Bandcamp**, or **Twitch** as default search engines in `application.yml` completely bypasses the YouTube block. For **Spotify**, remember that plugins only convert song metadata (name and artist) to search for it on an audio platform; therefore, the final audio will still need to come from a source that is not blocked (like SoundCloud).

## Version compatibility (Lavalink v3 vs v4) and connection

Always use a **Lavalink version that matches your bot's client (wrapper)**: **Lavalink v4 is REST-based and won't talk to a v3 client**, which drops the WebSocket. Network recap on Square Cloud: the **Lavalink server binds to port 80** and the **client connects on port 443 with `secure: true`**. If you hit `WebSocket closed abnormally (1006)`, see [Lavalink closed abnormally (1006): how to fix](https://help.squarecloud.app/en-us/article/lavalink-closed-abnormally-1006-how-to-fix-17dv349/).