Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Music lag when searching. #4

Open
Zigecek opened this issue Nov 10, 2020 · 1 comment
Open

Music lag when searching. #4

Zigecek opened this issue Nov 10, 2020 · 1 comment
Labels

Comments

@Zigecek
Copy link

Zigecek commented Nov 10, 2020

Hello, I have a problem. I have a music bot witch is using ytsearcher. But there is a problem; when I listening the music and use command to add new track to queue (the command is using ytsearcher too), bot lag the music for about 0,5s.

Here is my code:

const Discord = require('discord.js'); // Require discord.js
const ytdl = require('ytdl-core')
const botFile = require('../bot');
const bot = botFile.bot;
const { YTSearcher } = require('ytsearcher');
var fetchVideoInfo = require('youtube-infofix');

const mongoose = require('mongoose');
const Guild = require('../models/guild');
const Config = require('../models/Config');

var prefix = '';

const queue = new Map();

const searcher = new YTSearcher({
    key: process.env.YOUTUBE_API_KEY,
    revealed: true
});

bot.on('message', message => { // When the bot receive a message


    Guild.findOne({ // Místo "Guild" použijte vlastní model.
        guildID: message.guild.id // Podle čeho hledat
    }, (err, Gres) => { //err - Možná chyba, Gres - Výsledek hledání.
        if (err) { //Když je chyba, zruší funkci a chybu napíše do konzole.
            return console.error(err);
        }

        prefix = Gres.prefix;

        const serverQueue = queue.get(message.guild.id);


        if (message.content.startsWith(prefix)) {
            const args = message.content.slice(prefix.length).trim().split(/ +/g);
            const command = args.shift().toLowerCase();

            if (command == 'play' || command == 'p') {
                execute(message, serverQueue);
            } else if (command == 'stop') {
                stop(message, serverQueue);
            } else if (command == 'skip') {
                skip(message, serverQueue);
            } else if (command == 'search') {

            }


            async function execute(message, serverQueue) {
                const voiceChannel = message.member.voice.channel;
                if (!voiceChannel) {
                    const Embed = new Discord.MessageEmbed()
                        .setColor('#ff9745')
                        .setURL('https://discord.js.org/')
                        .setAuthor('Zigger', 'https://cdn.discordapp.com/app-icons/763859712340262972/010d590a764af0c59b999ad024cf89cb.png?size=128')
                        .setDescription('Pro použití tohoto příkazu, musíte být v hlasovém kanále!');
                    message.channel.send(Embed);
                    return;
                }
                const permissions = voiceChannel.permissionsFor(message.client.user);
                if (!permissions.has('CONNECT') || !permissions.has('SPEAK')) {
                    const Embed = new Discord.MessageEmbed()
                        .setColor('#ff9745')
                        .setURL('https://discord.js.org/')
                        .setAuthor('Zigger', 'https://cdn.discordapp.com/app-icons/763859712340262972/010d590a764af0c59b999ad024cf89cb.png?size=128')
                        .setDescription('Nemám práva k mluvení nebo připojení!');
                    message.channel.send(Embed);
                    return;
                }
                message.channel.send(':red_circle: **Vyhledávám** :mag_right: `' + args.join(" ") + '`')
                searcher.search(args.join(' ')).then((result) => {



                    console.log(result);

                    fetchVideoInfo(result.first.id).then(function (videoInfo) {

                        let song = {
                            title: videoInfo.title,
                            url: videoInfo.url,
                            duration: sec2time(videoInfo.duration),
                            thumbnail: videoInfo.thumbnailUrl,
                            views: videoInfo.views
                        }
                        let queueConstructor = {
                            txtChannel: message.channel,
                            vChannel: voiceChannel,
                            connection: null,
                            songs: [],
                            volume: 10,
                            playing: true
                        };

                        if (!serverQueue) {
                            queue.set(message.guild.id, queueConstructor);

                            queueConstructor.songs.push(song);

                            try {
                                voiceChannel.join().then((connection) => {
                                    message.guild.me.voice.setSelfDeaf(true);
                                    queueConstructor.connection = connection;
                                    play(message.guild, queueConstructor.songs[0])
                                });
                            } catch (err) {
                                console.error(err);
                                queue.delete(message.guild.id);

                                Config.findOne({ // Místo "Guild" použijte vlastní model.
                                    index: 'config' // Podle čeho hledat
                                }, (err, Gres) => { //err - Možná chyba, Gres - Výsledek hledání.
                                    if (err) { //Když je chyba, zruší funkci a chybu napíše do konzole.
                                        return console.error(err);
                                    }
                                    const Embed = new Discord.MessageEmbed()
                                        .setColor('#ff9745')
                                        .setURL('https://discord.js.org/')
                                        .setAuthor('Zigger', 'https://cdn.discordapp.com/app-icons/763859712340262972/010d590a764af0c59b999ad024cf89cb.png?size=128')
                                        .setDescription('Nastala chyba: ' + err + '\nProsím kontaktuj správce bota:\n<@' + Gres.adminDiscordID + '>');
                                    return message.channel.send(Embed);
                                });

                            }

                        } else {
                            serverQueue.songs.push(song);
                            const Embed = new Discord.MessageEmbed()
                                .setColor('#ff9745')
                                .setTitle(':musical_note: Přidáno do fronty :musical_note:')
                                .setDescription(song.url)
                                .setImage(song.thumbnail)
                                .addFields({
                                    name: '`Název:`', value: song.title
                                }, {
                                    name: '`Délka:`', value: song.duration
                                }, {
                                    name: '`Zhlédnutí:`', value: song.views
                                });
                            return serverQueue.txtChannel.send(Embed);
                        }
                    });
                });
            }
            async function searchFunc(message, serverQueue) {

            }
            function play(guild, song) {
                const serverQueue = queue.get(guild.id);
                if (!song) {
                    queue.delete(serverQueue.txtChannel.guild.id);
                    serverQueue.vChannel.leave();
                    return;
                }
                const dispatcher = serverQueue.connection
                    .play(ytdl(song.url))
                    .on('finish', () => {
                        serverQueue.songs.shift();
                        play(guild, serverQueue.songs[0]);
                    });

                const Embed = new Discord.MessageEmbed()
                    .setColor('#ff9745')
                    .setTitle(':musical_note: Právě hraje :musical_note:')
                    .setDescription(serverQueue.songs[0].url)
                    .setImage(serverQueue.songs[0].thumbnail)
                    .addFields({
                        name: '`Název:`', value: serverQueue.songs[0].title
                    }, {
                        name: '`Délka:`', value: serverQueue.songs[0].duration
                    }, {
                        name: '`Zhlédnutí:`', value: serverQueue.songs[0].views
                    });
                return serverQueue.txtChannel.send(Embed);
            }
            function stop(message, serverQueue) {
                if (!message.member.voice.channel) {
                    const Embed = new Discord.MessageEmbed()
                        .setColor('#ff9745')
                        .setURL('https://discord.js.org/')
                        .setAuthor('Zigger', 'https://cdn.discordapp.com/app-icons/763859712340262972/010d590a764af0c59b999ad024cf89cb.png?size=128')
                        .setDescription('Pro použití tohoto příkazu, musíte být v hlasovém kanále.');
                    return message.channel.send(Embed);
                }
                if (serverQueue == []) {
                    serverQueue.connection.dispatcher.end();
                } else {
                    serverQueue.connection.dispatcher.end();
                    serverQueue.songs = [];
                }
            }
            function skip(message, serverQueue) {
                if (!message.member.voice.channel) {
                    const Embed = new Discord.MessageEmbed()
                        .setColor('#ff9745')
                        .setURL('https://discord.js.org/')
                        .setAuthor('Zigger', 'https://cdn.discordapp.com/app-icons/763859712340262972/010d590a764af0c59b999ad024cf89cb.png?size=128')
                        .setDescription('Pro použití tohoto příkazu, musíte být v hlasovém kanále.');
                    return message.channel.send(Embed);
                }
                if (!serverQueue) {
                    const Embed = new Discord.MessageEmbed()
                        .setColor('#ff9745')
                        .setURL('https://discord.js.org/')
                        .setAuthor('Zigger', 'https://cdn.discordapp.com/app-icons/763859712340262972/010d590a764af0c59b999ad024cf89cb.png?size=128')
                        .setDescription('Ve frontě nic není.');
                    return message.channel.send(Embed);
                }

                message.channel.send(':fast_forward: **Přeskočeno** :thumbsup:');
                serverQueue.connection.dispatcher.end();
            }
        }
    });
});

bot.on('voiceStateUpdate', (oldMember, newMember) => {
    let newUserChannel = newMember.voiceChannel
    let oldUserChannel = oldMember.voiceChannel


    if (oldUserChannel === undefined && newUserChannel !== undefined) {

        if (newMember == bot) {
            newMember.guild.me.voice.setSelfDeaf(true);
        }

    } else if (newUserChannel === undefined) {

        // User leaves a voice channel

    }
});

function sec2time(timeInSeconds) {
    var pad = function (num, size) { return ('000' + num).slice(size * -1); },
        time = parseFloat(timeInSeconds).toFixed(3),
        hours = Math.floor(time / 60 / 60),
        minutes = Math.floor(time / 60) % 60,
        seconds = Math.floor(time - minutes * 60),
        milliseconds = time.slice(-3);

    return pad(hours, 2) + ':' + pad(minutes, 2) + ':' + pad(seconds, 2);
}

Please help, how can I fix that,
every response is good.

@wzhouwzhou
Copy link
Owner

Can you elaborate a bit on the bot lagging the music?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants