Giter Site home page Giter Site logo

ecliptia / moonlink.js Goto Github PK

View Code? Open in Web Editor NEW
56.0 3.0 5.0 1.88 MB

MoonLink.js is a simple package for lavalink client, perfect for you to create your discord bot with songs, and very simple and easy to use.

Home Page: https://moonlink.js.org

License: Open Software License 3.0

TypeScript 83.51% JavaScript 16.49%
bot discord discord-js lavalink music nodejs easy

moonlink.js's Introduction

Imagine a Music...

MoonImage NPM

Made with ♥️ in - Brazil

Codacy Badge Downloads Version install size node Netlify Status

Envision a musical journey where creativity knows no bounds, accompanied by the enchantment of the holiday season. 🌌 Moonlink.js invites you to unlock your complete musical potential, designed exclusively for Lavalink clients. Step into a world of seamless communication and fluid interaction, where Moonlink.js elevates your projects to new heights, sprinkled with holiday charm. With full TypeScript support, it empowers your creativity and productivity. 🎵

Table of Contents

Features

Moonlink.js offers essential features for creating exceptional music bots:

  1. Seamless Communication: Developed for Lavalink clients, it ensures an uninterrupted musical experience. 🎧

  2. Full TypeScript Support: Enjoy complete TypeScript support to enhance your productivity and creativity. 💻

  3. Active Community: Be part of a community of passionate developers and benefit from our active support system. Our project is not just about minimizing package size but maximizing its quality and potential for developers. 🤝

Documentation

For comprehensive documentation and more examples, visit moonlink.js.org. 📖

Installation

npm install moonlink.js
yarn add moonlink.js
pnpm install moonlink.js
bun install moonlink.js

How to Use

// Creating an instance of the Discord.js clien
const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.GuildVoiceStates
    ]
});

// Configuring the Moonlink.js package
client.moon = new MoonlinkManager(
    [
        {
            host: "localhost",
            port: 2333,
            secure: true,
            password: "password"
        }
    ],
    {
        /* Options */
    },
    (guild, sPayload) => {
        // Sending payload information to the server
        client.guilds.cache.get(guild).shard.send(JSON.parse(sPayload));
    }
);

// Event: Node created
client.moon.on("nodeCreate", node => {
    console.log(`${node.host} was connected, and the magic is in the air`);
});

// Event: Track start
client.moon.on("trackStart", async (player, track) => {
    // Sending a message when the track starts playing
    client.channels.cache
        .get(player.textChannel)
        .send(`${track.title} is playing now, bringing holiday joy`);
});

// Event: Track end
client.moon.on("trackEnd", async (player, track) => {
    // Sending a message when the track finishes playing
    client.channels.cache
        .get(player.textChannel)
        .send(`The track is over, but the magic continues`);
});

// Event: Ready
client.on("ready", () => {
    // Initializing the Moonlink.js package with the client's user ID
    client.moon.init(client.user.id);
});

// Event: Raw data
client.on("raw", data => {
    // Updating the Moonlink.js package with the necessary data
    client.moon.packetUpdate(data);
});

// Event: Interaction created
client.on("interactionCreate", async interaction => {
    if (!interaction.isChatInputCommand()) return;
    let commandName = interaction.commandName;
    if (commandName === "play") {
        if (!interaction.member.voice.channel) {
            // Responding with a message if the user is not in a voice channel
            return interaction.reply({
                content: `You are not in a voice channel`,
                ephemeral: true
            });
        }

        let query = interaction.options.getString("query");
        let player = client.moon.players.create({
            guildId: interaction.guild.id,
            voiceChannel: interaction.member.voice.channel.id,
            textChannel: interaction.channel.id,
            autoPlay: true
        });

        if (!player.connected) {
            // Connecting to the voice channel if not already connected
            player.connect({
                setDeaf: true,
                setMute: false
            });
        }

        let res = await client.moon.search({
            query,
            source: "youtube",
            requester: interaction.user.id
        });

        if (res.loadType === "loadfailed") {
            // Responding with an error message if loading fails
            return interaction.reply({
                content: `:x: Load failed - the system is not cooperating.`
            });
        } else if (res.loadType === "empty") {
            // Responding with a message if the search returns no results
            return interaction.reply({
                content: `:x: No matches found!`
            });
        }

        if (res.loadType === "playlist") {
            interaction.reply({
                content: `${res.playlistInfo.name} This playlist has been added to the waiting list, spreading joy`
            });

            for (const track of res.tracks) {
                // Adding tracks to the queue if it's a playlist
                player.queue.add(track);
            }
        } else {
            player.queue.add(res.tracks[0]);
            interaction.reply({
                content: `${res.tracks[0].title} was added to the waiting list`
            });
        }

        if (!player.playing) {
            // Starting playback if not already playing
            player.play();
        }
});

// Logging in with the Discord token
client.login(process.env["DISCORD_TOKEN"]);

Contributors

We would like to express our gratitude to the amazing individuals who contributed to this project. Their hard work and dedication have been instrumental in making it a success. 🎉

  1. 1Lucas1apk - Lead Developer, responsible for project architecture and key feature implementation. 🚀

  2. MotoG.js - Project Ideator and Designer, contributing to the concept and visual design. 🎨

  3. WilsontheWolf - Contributed to the track position logic in real time, rather than just receiving the payload from lavalink.

  4. PiscesXD - First sponsor and contributed to making the shuffle method reversible, and autoLeave.

  5. Suryansh - Second contributor and helped discover bugs 🌷

Other contributors: Nah, ItzGG, SuperPlayerBot, ddemile, Tasty-Kiwi, rrm, WilsontheWolf, Aertic, 'Forster, Fireball, Ghos't, loulou310 - Xotak

We sincerely thank all the contributors mentioned above and everyone who contributed to this project in any way. Your support is truly appreciated. 🙏

Final Thanks

Thank you to everyone who contributed to the growth of moonlink.js, reporting bugs, installing the package and everyone else's patience, I apologize for any time I wasn't able to help someone

have a great day :)

License

This project is licensed under the Open Software License ("OSL") v. 3.0 - see the LICENSE file for details.

Support

Join our Discord server at Moonlink.js - Imagine a Music Bot to connect with other users, ask questions, and participate in discussions. 🤝

For any inquiries or assistance, we're here to help! 🌟

moonlink.js's People

Contributors

1lucas1apk avatar motog100 avatar notjag avatar dependabot[bot] avatar snyk-bot avatar ddemile avatar thepedroo avatar actions-user avatar

Stargazers

Moon Carli.js avatar DeadEye'z avatar David Gustavo Herrera De La Cruz avatar Sanchit Jain avatar  avatar RonaldZav avatar raf avatar Kevin Siddhpura avatar Royston Ang avatar Pedro Nícolas Gomes de Souza avatar Youbin Choi avatar MrScarySpaceCat avatar Enda avatar X1x0 avatar Munish Khatri avatar  avatar Xotak avatar  avatar Dorian Oszczęda avatar Suryansh Singh avatar  avatar MeatReed avatar Otoniel Borja avatar Saintno avatar Nitidez avatar HashCollision avatar Alex avatar Sarcaster! avatar Khouw Devin Nathanael avatar Raphaël avatar Nansess avatar Carlos Júnior avatar  avatar Justin Lindo avatar Vepp avatar Mr. Kofy avatar Webster avatar Fyphen avatar Emir Kabal avatar  avatar Evan avatar Debadithya Ray Barman avatar My Name avatar Grzegorz Szwyngiel avatar Dominykas M. avatar Henry Bao avatar Meridian avatar Mohammad Faizan avatar 0zul avatar Jonas Franke avatar JustEvil avatar YoungChief avatar Sudhan avatar NotWrench avatar Σspectrø avatar  avatar

Watchers

Suryansh Singh avatar  avatar Raphaël avatar

moonlink.js's Issues

(Bug): player.destroy() causes error, Key path doesn't exist

Describe the bug
player.destroy() causes a error which could cause the execution to stop if not handled properly.

To Reproduce
use the player.destroy() function, for eg when all members leave

Expected behavior
Player should be destroyed without an errors

Additional context
Error

C:\Users\Website\Desktop\Musico\node_modules\moonlink.js\dist\src\@Utils\MoonlinkDatabase.js:52                               keys.forEach(k => {                                                                                                        ^                                                                                                        Error: @Moonlink(Database) - Key path "players.1077418717668982854" does not exist                                        at C:\Users\Website\Desktop\Musico\node_modules\moonlink.js\dist\src\@Utils\MoonlinkDatabase.js:57:23                 at Array.forEach (<anonymous>)                                                                                        at MoonlinkDatabase.delete (C:\Users\Website\Desktop\Musico\node_modules\moonlink.js\dist\src\@Utils\MoonlinkDatabase.js:52:14)                                                                                                             at PlayerManager.delete (C:\Users\Website\Desktop\Musico\node_modules\moonlink.js\dist\src\@Managers\PlayerManager.js:140:36)                                                                                                               at MoonlinkPlayer.destroy (C:\Users\Website\Desktop\Musico\node_modules\moonlink.js\dist\src\@Entities\MoonlinkPlayer.js:308:36)                                                                                                            at processTicksAndRejections (node:internal/process/task_queues:95:5)                                                                                                                                                                  

Moon events

    this.moon.on("nodeCreate", (node) => {
      console.log(`${node.host} was connected, and the magic is in the air`);
    });
    this.moon.on("trackEnd", async (player, track) => {
      // Sending a message when the track finishes playing
      let channel = this.channels.cache.get(player.textChannel);
      if (!channel) return;
      if (channel.type === ChannelType.GuildText) {
        channel.send(`${track.title} has finished playing, spreading joy`);
      }
    });
    this.moon.on("trackStart", async (player, track) => {
      // Sending a message when the track starts playing
      let channel = this.channels.cache.get(player.textChannel);
      if (!channel) return;
      if (channel.type === ChannelType.GuildText) {
        channel.send(`${track.title} is now playing!`);
      }
    });
    this.on("raw", (data) => {
      // Updating the Moonlink.js package with the necessary data
      this.moon.packetUpdate(data);
    });

player.destroy function

  console.log("Voice state has been updated");
    const chanID = oldState.channelId;
    if (!chanID) return;
    const vc = await newState.guild.channels.fetch(chanID);
    if (vc?.type !== ChannelType.GuildVoice) return;
    const player = client.moon.players.get(newState.guild.id);
    if (!player) return;
    if (!vc) return;
    console.log(vc.members.size);
    if (oldState.channelId === player.voiceChannel) {
      if (vc.members.size === 1) {
        const textchannel = await newState.guild.channels.fetch(
          player.textChannel
        );
        if (!textchannel) return;
        if (textchannel.type !== ChannelType.GuildText) return;
        await textchannel.send(
          "I have left the voice channel because I was lonely"
        );

        await player.destroy();
      }
    }

Real Time Position Updates

Right now, when I get the current tracks position it is just whatever the websocket sent last. This can (and will often) be several seconds off. This can be seen when I executed this code:
setInterval(() => console.log(lava.players.get(message.guild.id)?.current?.position), 1000)
Which resulted in:
image
As you can see, there isn't any change for several seconds.

You can get the desired effect like so (modified from https://github.com/WilsontheWolf/lavalink/blob/master/src/classes/Player.js#L80-L83)

function calcPosition(player) {
    if (player.paused) return player.current.position;
    return player.current.position + (Date.now() - player.current.time); // Note this could cause some weird values if your clock is not synced with the lavalink instances clock. This is probably ignorable.
}

However, I would perfer to not have to write this code myself. I am wondering if we could have some sort of getter on player (because player.current doesn't have a class), so I can just call player.position to get the current position. Thanks

Seek is not working

When using player.seek(), it throws an error.
After further investigation, it seems that this.current is null in the method.
image
image

skip error

<player>.skip()

If you use the method above, the music will move on to the next song, but all the songs in the queue will disappear.

Ideas that come before I sleep

Changing some parts of the code that I thought about before going to sleep, and I'll put them here so I don't lose them

Random ideas:

  • Change the players method to a class
  • Also change the nodes to another class
    As if it were their personalized structure

It has been rethought and if you make this change it may cause information errors

  • Change the database so it can be modified in different ways, for example combining with firebase, and among other databases :)

  • Change the name of the @rest directory, because that name doesn't make sense
    One word that could be is (Synergies), its meaning tells everything about the codes within the file

  • The interfaces in just one file instead of being mirrored by the code, and in addition I can reuse

  • When a node is unavailable and has players on them, make it play the players from those nodes to others that are online

  • Store track requester information without losing the class that comes from the Member constructor

  • Bug that I found has to be fixed, when it tries to connect to a non-existent server it takes minutes, and then a huge spam comes in the Debug that the node was destroyed until it gives Max Call

  • Add other things to MoonlinkTrack to make the track more dynamic in terms of information

  • Separate the JSON from the database generates in a different folder

  • Replace MoonlinkWebsocket with the original code

  • Debug is missing information, I need to detail more about what is happening in the package

check lavalink status

how can i make the bot check the server status if its online or not
and if its online how many clients connected to it

(Bug): voiceRegion and empty

Describe the bug
The PlayerManager.cache attribute is empty ({}). This is causing issue with the attemptConnection method for that class (file)

To Reproduce
Steps to reproduce the behavior:

  1. Launch bot with or without sharding (happen with both)
  2. Try to connect/log PlayerManager
  3. PlayerManager.cache is empty, leading to errors in PlayerManager

Expected behavior
The bot connects/The cache have the right values

Screenshots

Won't do a screenshot of my console, here's full console output :

❯ node bot.js
�={"op":"ready","resumed":false,"sessionId":"ypvqy2s4x5lbok5a"}
�~{"op":"stats","frameStats":null,"players":0,"playingPlayers":0,"uptime":1682695,"memory":{"free":77562136,"used":178290408,"allocated":255852544,"reservable":1520435200},"cpu":{"cores":8,"systemLoad":0.03271721460976983,"lavalinkLoad":0.0011935803738660987}}
[20:32:50.229] WARN (9581): UNSHARDED
[20:32:50.230] INFO (9581): Ready! Logged in as Un Bot de test#5999
[20:32:50.244] INFO (9581): localhost was connected. Lavalink ready
<ref *1> PlayerManager {
  _manager: <ref *2> MoonlinkManager {
    _events: [Object: null prototype] {
      nodeCreate: [Function (anonymous)],
      trackStart: [Array]
    },
    _eventsCount: 2,
    _maxListeners: undefined,
    clientId: '715944203430920334',
    _nodes: [ [Object] ],
    _SPayload: [Function (anonymous)],
    players: [Circular *1],
    nodes: NodeManager {
      initiated: true,
      _manager: [Circular *2],
      map: [Map]
    },
    version: '3.2.88',
    options: {
      clientName: '@Moonlink/3.2.88 (https://github.com/Ecliptia/moonlink.js)',
      clientId: '715944203430920334'
    },
    initiated: true,
    [Symbol(shapeMode)]: false,
    [Symbol(kCapture)]: false
  },
  cache: {},
  voices: {}
}
�~{"op":"stats","frameStats":null,"players":0,"playingPlayers":0,"uptime":1742695,"memory":{"free":77227960,"used":178624584,"allocated":255852544,"reservable":1520435200},"cpu":{"cores":8,"systemLoad":0.02032248631939513,"lavalinkLoad":0.0012708121531307811}}
�~{"op":"stats","frameStats":null,"players":0,"playingPlayers":0,"uptime":1802695,"memory":{"free":76929384,"used":178923160,"allocated":255852544,"reservable":1520435200},"cpu":{"cores":8,"systemLoad":0.010754709100781022,"lavalinkLoad":0.0012917097236574552}}
�~{"op":"stats","frameStats":null,"players":0,"playingPlayers":0,"uptime":1862695,"memory":{"free":76743864,"used":179108680,"allocated":255852544,"reservable":1520435200},"cpu":{"cores":8,"systemLoad":0.01025266235122155,"lavalinkLoad":0.0012708121531307811}}
�~{"op":"stats","frameStats":null,"players":0,"playingPlayers":0,"uptime":1922695,"memory":{"free":76195776,"used":179656768,"allocated":255852544,"reservable":1520435200},"cpu":{"cores":8,"systemLoad":0.010880233893703664,"lavalinkLoad":0.0012916666666666667}}
/home/user/yadb/node_modules/moonlink.js/dist/src/@Managers/PlayerManager.js:76
                this.cache[guildId].voiceRegion = voiceRegion[1];
                                                             ^

TypeError: Cannot read properties of null (reading '1')
    at PlayerManager.attemptConnection (/home/user/yadb/node_modules/moonlink.js/dist/src/@Managers/PlayerManager.js:76:62)
    at MoonlinkManager.packetUpdate (/home/user/yadb/node_modules/moonlink.js/dist/src/@Managers/MoonlinkManager.js:144:26)
    at Client.<anonymous> (/home/user/yadb/bot.js:115:17)
    at Client.emit (node:events:519:28)
    at WebSocketManager.<anonymous> (/home/user/yadb/node_modules/discord.js/src/client/websocket/WebSocketManager.js:236:19)
    at WebSocketManager.emit (/home/user/yadb/node_modules/@vladfrangu/async_event_emitter/dist/index.js:282:31)
    at WebSocketShard.<anonymous> (/home/user/yadb/node_modules/@discordjs/ws/dist/index.js:1173:51)
    at WebSocketShard.emit (/home/user/yadb/node_modules/@vladfrangu/async_event_emitter/dist/index.js:282:31)
    at WebSocketShard.onMessage (/home/user/yadb/node_modules/@discordjs/ws/dist/index.js:988:14)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Node.js v21.6.1

Looks like voices is not populated too

Tried with the example script, also broken.

Seems that the code introduced in 647d8aa broke

Additional context
None

Error: connect ECONNREFUSED ::1:2333

Code:
In client

public moon = new MoonlinkManager(config.servers, {}, (guild: string, sPayLoad: unknown) => {
        this.guilds.cache.get(guild)?.shard.send(sPayLoad);
    });

play.ts

import { ApplicationCommandOptionType } from "discord.js";
import { Command } from "../../utils/commands";
import { LoggerType } from "../../utils/logger";
import chalk from "chalk";

export default new Command({
    name: "play",
    description: "play a song!",
    cooldown: 3000,
    botPermission: [],
    options: [
        {
            name: 'song',
            description: 'Which song?',
            required: true,
            type: ApplicationCommandOptionType.String
        },
    ],
    run: async ({ client, interaction }) => {
        const query = interaction.options.getString('song', true);
        const { channel } = interaction.member.voice;
        if(!channel) return client.sendError(interaction, 'Please join an voice channel!');

        let player = client.moon.players.get(`${interaction?.guild?.id}`);
        
        if(!player) player = client.moon.players.create({
            guildId: `${interaction?.guild?.id}`,
            textChannel: `${interaction?.channel?.id}`,
            voiceChannel: `${channel.id}`,
        });

        const res = await client.moon.search(query);
        
        if (res.loadType === "LOAD_FAILED") {
            return interaction.reply({
              content: `:x: Load failed. `
            }); //if there is an error when loading the tracks, it informs that there is an error
          } else if (res.loadType === "NO_MATCHES") {
            return interaction.reply({
              content: `:x: No matches!`
            }); // nothing was found
          }
          if (res.loadType === 'PLAYLIST_LOADED') {
            interaction.reply({
              content: `${res?.playlistInfo?.name} this playlist has been added to the waiting list`
            })
            for (const track of res.tracks) {
              //if it's a playlist it will merge all the tracks and add it to the queue
              player.queue.add(track);
            }
          } else {
            player.queue.add(res.tracks[0])
            interaction.reply({
              content: `${res.tracks[0].sourceName} was added to the waiting list`
            })
          }
          if (!player.playing) player.play()
    }
});

Full error: ```ts
Error: connect ECONNREFUSED ::1:2333
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 2333
}


SearchResult.playlist is undefined

SearchResult.playlist is wrong, in the code the property with the info of the playlist is SearchResult.playlistInfo not SearchResult.playlist who is undefined

(Bug): Shuffle

Describe the bug
Shuffle is not working properly
To Reproduce
Add a playlist
Activate shuffle
And wait to select the song when trackEnd is called
But it doesn't happen as it should

Expected behavior
Choose a random track from the queue

Screenshots
Without

Additional context
Also modify for following things

Make it show the shuffling, instead of picking a random track. This can benefit commands like queue which shows how the shuffle went

Make the reversal system

Shuffle with loop active in the queue

Also don't do it the old way, because a new track could be added and the shuffling wouldn't work, it has to be more altomatic

Credits: Reported by users on the moonlink.js server

(Bug): Moonlink(Database) - Failed to save data

Describe the bug
After about a day of leaving the bot on, an error occurs in the database. If an error occurs in the database and you run it again, the error Error @Moonlink(Database) - Failed to fetch data (Error): will occur, but if you access the database folder and run the bot again, it will operate normally.

To Reproduce
Steps to reproduce the behavior:

  1. Turn on the bot and leave it for about a day.
  2. Throw Moonlink(Database) Error - Data storage failure error occurs.

Expected behavior
Even if the bot is turned on for a long time, data must continue to be saved without Error: @Moonlink(Database) - Failed to save data.

Screenshots

2024-03-11 12:47:57.352 [ ERROR ] [ Bot ]  Error: @Moonlink(Database) - Failed to save data
    at MoonlinkDatabase.save (C:\Users\Administrator\discord\node_modules\moonlink.js\dist\src@Utils\MoonlinkDatabase.js:109:19)
    at MoonlinkDatabase.set (C:\Users\Administrator\discord\node_modules\moonlink.js\dist\src@Utils\MoonlinkDatabase.js:23:14)
    at MoonlinkQueue.setQueue (C:\Users\Administrator\discord\node_modules\moonlink.js\dist\src@Entities\MoonlinkQueue.js:96:17)
    at MoonlinkQueue.add (C:\Users\Administrator\discord\node_modules\moonlink.js\dist\src@Entities\MoonlinkQueue.js:28:14)
    at SlashCommand.execute (C:\Users\Administrator\discord\src\commands\music\play.ts:95:20)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at Event.execute (C:\Users\Administrator\discord\src\events\onInteraction.ts:21:13)
2024-03-11 12:47:57.387 [ ERROR ] [ main ]
 Error  EMFILE: too many open files, open 'C:\Users\Administrator\discord\logs\latest.log', -4066, EMFILE, open, C:\Users\Administrator\discord\logs\latest.log
error stack:

2024-03-11 12:47:57.401 [ ERROR ] [ main ]
 Error  ENOENT: no such file or directory, mkdir 'C:\Users\Administrator\discord\20240311-0000-01-C:\Users\Administrator\discord\logs', -4058, ENOENT, mkdir, C:\Users\Administrator\discord\20240311-0000-01-C:\Users\Administrator\discord\logs
error stack:

Additional context
I think the corresponding error occurs, and in my bot log system, Error EMFILE: too many open files, open 'C:\Users\Administrator\discord\logs\latest.log', -4066, EMFILE, open, C:\Users\Administrator\discord\logs\latest.log error stack: error, it seems that an error occurred while saving the file.

(Bug): When you restart the bot, moonlinkjs resuming the music but the `<player>.playing` variable returns false

Describe the bug
When you restart the bot, moonlinkjs resuming the music but the <player>.playing variable returns false. Even if the music continues where it left off, the trackEnd event gets emitted.

To Reproduce
Steps to reproduce the behavior:

  1. Set manager options resume and autoResume to true
  2. Play a music using <player>.play() by checking with <player>.playing
  3. Restart the bot
  4. Play a music again
  5. The manager will cause an unexpected behavior like the music gets skipped, the music player is undefined, <player>.playing returns false.

Expected behavior
Players shouldnt be deleted from the manager, <player>.playing should return true and trackEnd event shouldnt be emited

Screenshots
Capture
Capture1

Additional context
moonlinkjs version: 3.6.4
lavalink version: latest v4

Player.seek method is not working

Using Player.seek is not working, when I put seconds i just go back to the start and when I put milliseconds I have an error or it just go back to the start.
Here's my code:

const [first, second, third] = (interaction.options.get("position")?.value as string).split(":").map((x: number | string) => isNaN(x as number) ? 0 : Number(x));
const totalTime = third ? first * 3600 + second * 60 + third : second ? first * 60 + second : first;
let player = moon.players.get(interaction.guildId!)

if (!player) return interaction.reply({ content: localizations.noQueue.get(), ephemeral: true })

console.log(`Current track duration: ${formatTime(player.current.duration / 1000).toString()} (${player.current.duration})`)

if (totalTime > player.current.duration) return await interaction.reply({
    embeds: [
        new EmbedBuilder({
            color: Colors.Red,
            description: localizations.tooFar.get()
        })
    ]
});


console.log("Total time: " + totalTime)
console.log("Seek: " + await player.seek(totalTime));
await interaction.reply({ 
    embeds: [
        new EmbedBuilder({
            color: Colors.Blurple,
            description: localizations.seek.get({ time: formatTime(totalTime).toString() })
        })
    ] 
});

image

(Bug): trackEnd not issued on last track

Describe the bug
I have setup a listener with the "trackStart" event which works most of the time but on more than one occasion the event doesn't fire at all

To Reproduce
Steps to reproduce the behavior:

  1. Setup a listener on track start
  2. Play a track quite a few times as the issue is sporadic
  3. Event wont fire once or twice randomly

Expected behavior
Event fires

(Feature): Add more events

Is your feature request related to a problem? Please describe.
No

Describe the solution you'd like
Add more change events for some properties requested on the moonlink.js server by a user

Additional context
...

Fix bugs and add Features

Tip

This issue is to list things that I should fix, and add features

  • Bug found when trying to reconnect with the nodes again, it doesn't go away after the 1st attempt
  • Resume not working
  • Discovering that sources in search is not working either
  • ClientName with some kind of error for some
  • Reorganize the part of modifying the track current information
  • Redo the play method to use previous ones instead of pulling from the database
  • Also modify the events emitted by lavalink that uses the MoonlinkPlayer class and change to use its map instead of the class
  • detailed state of nodes activity
  • Correcting resume
  • Adding system to move players when a working node disconnects

Bug(FILE.EXTENSION): SyntaxError: Unexpected end of JSON input

Description of the problem

When using the play command, the messages are sent but the music does not start playing and these errors appear:

Excuse me if it is an error in my code.

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at MoonlinkNode.message (C:\Users\ronal\Documents\GitHub\mahiro\node_modules\moonlink.js\dist\src\@Entities\MoonlinkNode.js:139:28)
    at MoonlinkWebSocket.emit (node:events:517:28)
    at Socket.<anonymous> (C:\Users\ronal\Documents\GitHub\mahiro\node_modules\moonlink.js\dist\src\@Services\MoonlinkWebSocket.js:120:34)
    at Socket.emit (node:events:517:28)
    at addChunk (node:internal/streams/readable:368:12)
    at readableAddChunk (node:internal/streams/readable:341:9)
    at Readable.push (node:internal/streams/readable:278:10)
    at TCP.onStreamRead (node:internal/stream_base_commons:190:23) Promise {
  <rejected> SyntaxError: Unexpected end of JSON input
      at JSON.parse (<anonymous>)
      at MoonlinkNode.message (C:\Users\ronal\Documents\GitHub\mahiro\node_modules\moonlink.js\dist\src\@Entities\MoonlinkNode.js:139:28)
      at MoonlinkWebSocket.emit (node:events:517:28)
      at Socket.<anonymous> (C:\Users\ronal\Documents\GitHub\mahiro\node_modules\moonlink.js\dist\src\@Services\MoonlinkWebSocket.js:120:34)
      at Socket.emit (node:events:517:28)
      at addChunk (node:internal/streams/readable:368:12)
      at readableAddChunk (node:internal/streams/readable:341:9)
      at Readable.push (node:internal/streams/readable:278:10)
      at TCP.onStreamRead (node:internal/stream_base_commons:190:23)
}
Emitted data that has not been implemented; opcode: 10
Emitted data that has not been implemented; opcode: 4
Emitted data that has not been implemented; opcode: 10

Step by Step

I'm running this command:

const { EmbedBuilder, ApplicationCommandOptionType } = require("discord.js")

module.exports = {
    name: "play",
    description: "Write a song.",
	options: [
		{
			name: "search",
            description: "Select an member.",
            type: ApplicationCommandOptionType.String,
            required: true
		},
	],
		
		
    run: async (client, interaction, lang) => {
        let query = interaction.options.getString("search");

    if (!interaction.member.voice.channel) {
        // Responding with a message if the user is not in a voice channel
        return interaction.reply({
            content: `You are not in a voice channel`,
            ephemeral: true
        });
    }

    let player = client.moon.players.create({
        guildId: interaction.guild.id,
        voiceChannel: interaction.member.voice.channel.id,
        textChannel: interaction.channel.id,
        autoPlay: true
    });

    if (!player.connected) {
        player.connect({
            setDeaf: true,
            setMute: false
        });
    }

    let res = await client.moon.search({
        query,
        source: "youtube",
        requester: interaction.user.id
    });

    if (res.loadType === "loadfailed") {
        return interaction.reply({
            content: `:x: Load failed - the system is not cooperating.`
        });
    } else if (res.loadType === "empty") {
        return interaction.reply({
            content: `:x: No matches found!`
        });
    }

    const embed = new EmbedBuilder()
    .setDescription(lang.embeds.song_added_to_queue.content.description.replace(/<musicname>/, res.tracks[0].title).replace(/<musicurl>/, res.tracks[0].url))
    .setThumbnail(res.tracks[0].artworkUrl)
    .setColor("#ffc200")

    if (res.loadType === "playlist") {
        interaction.reply({
            content: `${res.playlistInfo.name} This playlist has been added to the waiting list, spreading joy`
        });

        for (const track of res.tracks) {
            // Adding tracks to the queue if it's a playlist
            player.queue.add(track);
        }
    } else {
        player.queue.add(res.tracks[0]);
        interaction.reply({
            embeds: [embed]
        });
    }

    if (!player.playing) {
        player.play();
    }

}}

and this returns:

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at MoonlinkNode.message (C:\Users\ronal\Documents\GitHub\mahiro\node_modules\moonlink.js\dist\src\@Entities\MoonlinkNode.js:139:28)
    at MoonlinkWebSocket.emit (node:events:517:28)
    at Socket.<anonymous> (C:\Users\ronal\Documents\GitHub\mahiro\node_modules\moonlink.js\dist\src\@Services\MoonlinkWebSocket.js:120:34)
    at Socket.emit (node:events:517:28)
    at addChunk (node:internal/streams/readable:368:12)
    at readableAddChunk (node:internal/streams/readable:341:9)
    at Readable.push (node:internal/streams/readable:278:10)
    at TCP.onStreamRead (node:internal/stream_base_commons:190:23) Promise {
  <rejected> SyntaxError: Unexpected end of JSON input
      at JSON.parse (<anonymous>)
      at MoonlinkNode.message (C:\Users\ronal\Documents\GitHub\mahiro\node_modules\moonlink.js\dist\src\@Entities\MoonlinkNode.js:139:28)
      at MoonlinkWebSocket.emit (node:events:517:28)
      at Socket.<anonymous> (C:\Users\ronal\Documents\GitHub\mahiro\node_modules\moonlink.js\dist\src\@Services\MoonlinkWebSocket.js:120:34)
      at Socket.emit (node:events:517:28)
      at addChunk (node:internal/streams/readable:368:12)
      at readableAddChunk (node:internal/streams/readable:341:9)
      at Readable.push (node:internal/streams/readable:278:10)
      at TCP.onStreamRead (node:internal/stream_base_commons:190:23)
}
Emitted data that has not been implemented; opcode: 10
Emitted data that has not been implemented; opcode: 4
Emitted data that has not been implemented; opcode: 10

Package Version

3.6.4

First of all, please confirm:

  • Have you checked if there isn't already another issue with the same problem either on GitHub or on the Discord server?
  • Have you checked if there hasn't been a recent commit fixing this problem?
  • Are you using the latest version?
  • I agree to behave and wait patiently

(Bug): Resume system

Describe the bug
The system was supposed to make the summary automatically, but apparently there are some errors to be fixed

To Reproduce
Steps to reproduce the behavior:
Add the tracks, activate the parameter to summarize, then turn off the bot or some miracle make the connection disconnect, connect or reconnect with the name, wait to summarize and see the results

Expected behavior
player.playing as true,

Screenshots
No

Additional context
Reported by Discord user : piton

Typescript errors

Hello, i'm building a discord bot with typescript but i have some typescript erros :
image
image

(Bug): Queue loop not working properly

Describe the bug
When enabling queue loop, only the first track of the queue is repeated. The tracks waiting in queue aren't played.

To Reproduce
Steps to reproduce the behavior:
1 - Queue 2+ tracks
2 - Enable loop with player.setLoop(2)
3 - Only the first track of the queue is played

Expected behavior
The full queue is played repeatedly

Screenshots
None

Additional context
Tried to edit to code a bit. It seems that @Entities/MoonlinkNode.js:339 is problematic (player.current = queue.shift();). Removing that line successfully make the queue loop, but it adds each song once each loop (ie. 1st loop : each song is played one time, 2nd loop : each song is played 2 times, ...)

status are 0

stats: {
players: 0,
playingPlayers: 0,
uptime: 0,
memory: { free: 0, used: 0, allocated: 0, reservable: 0 },
cpu: { cores: 0, systemLoad: 0, lavalinkLoad: 0 },
frameStats: { sent: 0, nulled: 0, deficit: 0 }
},

reconnect after lavalink server restart

how can i make the bot auto reconnect to lavalink server after the server restart
i'm getting this error when the server restart [ @Moonlink/Manager ]: No lavalink server connected

(Feature): Store the MoonlinkPlayer class in the map instead of its structure

Is your feature request related to a problem? Please describe.

There are possibilities of the data not being synchronized and there may also be a fee for it to be lost or it may be replaced.

Some of the codes can use it at the same time, for example playerUpdate being called, and a function also changing some parameter, colliding and leaving some incorrect information.

Describe the solution you'd like

Instead of using the structure, I will change it to the class itself, as if creating a cache and this information can be synchronized

Additional context

Modify following codes

  • MoonlinkPlayers
  • MoonlinkNodes
  • Structures
  • ( Players moved to PlayersManager file)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.