Beispiel #1
0
        /// <summary>
        /// Queues serached (YouTube/Soundcloud) songs to the player queue
        /// </summary>
        /// <param name="player">Instance of <see cref="LavaPlayer" /> for the guild</param>
        /// <param name="search"><see cref="Victoria.Responses.Rest.SearchResponse"/></param>
        /// <param name="startTime">Start time of the track</param>
        /// <param name="requester">Requester of the track</param>
        /// <returns></returns>
        public async Task QueueTracksToPlayer(LavaPlayer player, Victoria.Responses.Rest.SearchResponse search, TimeSpan?startTime = null, IGuildUser requester = null)
        {
            _ = Task.Run(async() =>
            {
                List <LavaTrack> lavaTracks;
                string newQueue;
                if (search.LoadStatus == LoadStatus.PlaylistLoaded)
                {
                    lavaTracks = search.Tracks.ToList();
                }
                else
                {
                    lavaTracks = new List <LavaTrack>
                    {
                        search.Tracks.First()
                    };
                }
                if (player.PlayerState == PlayerState.Playing || player.PlayerState == PlayerState.Paused)
                {
                    foreach (var track in lavaTracks)
                    {
                        player.Queue.Enqueue(track.CreateMuseTrack(requester));
                    }
                    //Pause flag needed!
                    newQueue   = await GetNewEmbedQueueString(player);
                    var emebed = await embedHelper.BuildMusicEmbed(player, Color.DarkTeal, player.PlayerState == PlayerState.Paused);
                    await Program.BotConfig.BotEmbedMessage.ModifyAsync(x =>
                    {
                        x.Content = string.Format(QueueMayHaveSongs, newQueue);
                        x.Embed   = emebed;
                    });
                }
                else
                {
                    foreach (var track in lavaTracks)
                    {
                        player.Queue.Enqueue(track.CreateMuseTrack(requester));
                    }

                    _ = player.Queue.TryDequeue(out var newTrack);

                    if (startTime == null)
                    {
                        await player.PlayAsync(newTrack);
                    }
                    else
                    {
                        await player.PlayAsync(newTrack, startTime.Value, newTrack.Duration);
                    }
                }
            });

            await Task.CompletedTask;
        }
Beispiel #2
0
        public static async Task PauseResumeAsync(
            this LavaPlayer player,
            EmbedHelper embedHelper,
            bool paused,
            SocketCommandContext context = null)
        {
            await((paused) ? player.ResumeAsync() : player.PauseAsync());

            if (context != null && context.Guild.TextChannels.Any(x => x.Id == Program.BotConfig.ChannelId) == false)
            {
                return;
            }

            var embed = await embedHelper.BuildMusicEmbed(player, Color.DarkTeal, !paused);

            await Program.BotConfig.BotEmbedMessage.ModifyAsync(x => x.Embed = embed);
        }
Beispiel #3
0
        public AudioHelper(LavaNode lavanode, EmbedHelper eh)
        {
            Node        = lavanode;
            embedHelper = eh;

            // TODO: Make SpotifyClient own class
            if (Program.BotConfig.SpotifyClientId != "" && Program.BotConfig.SpotifySecret != "")
            {
                var config   = SpotifyClientConfig.CreateDefault();
                var request  = new ClientCredentialsRequest(Program.BotConfig.SpotifyClientId, Program.BotConfig.SpotifySecret);
                var response = new OAuthClient(config).RequestToken(request);
                var spotify  = new SpotifyClient(config.WithToken(response.Result.AccessToken));
                Spotify           = spotify;
                _disconnectTokens = new ConcurrentDictionary <ulong, CancellationTokenSource>();
                SpotifyLogin      = true;
            }


            // Handler for when a LavaTrack is started
            // args: TrackStartEventArgs
            Node.OnTrackStarted += async(args) =>
            {
                var player = args.Player;
                var queue  = await GetNewEmbedQueueString(player);

                var embed = await embedHelper.BuildMusicEmbed(player, Color.DarkTeal);

                //If for some reason Volume is set to 0 (100%) it will set to default volume
                if (player.Volume == 0)
                {
                    await player.UpdateVolumeAsync(Program.BotConfig.Volume);
                }

                var content = queue switch
                {
                    "" => NoSongsInQueue,
                    _ => string.Format(QueueMayHaveSongs, queue)
                };

                await Program.BotConfig.BotEmbedMessage.ModifyAsync(x =>
                {
                    x.Embed   = embed;
                    x.Content = content;
                });

                if (!_disconnectTokens.TryGetValue(args.Player.VoiceChannel.Id, out var value))
                {
                    return;
                }
                if (value.IsCancellationRequested)
                {
                    return;
                }

                value.Cancel(true);
            };

            // Handler for when a LavaTrack is ended, stopped, or skipped
            // args: TrackEndedEventArgs
            Node.OnTrackEnded += async(args) =>
            {
                var player = args.Player;

                if (RepeatFlag)
                {
                    await player.PlayAsync(RepeatTrack);

                    return;
                }

                RepeatFlag = false;

                if (!args.Reason.ShouldPlayNext())
                {
                    return;
                }

                if (!player.Queue.TryDequeue(out var track) && player.Queue.Count == 0)
                {
                    var embed = await EmbedHelper.BuildDefaultEmbed();

                    await Program.BotConfig.BotEmbedMessage.ModifyAsync(x =>
                    {
                        x.Content = NoSongsInQueue;
                        x.Embed   = embed;
                    });

                    if (!StayFlag)
                    {
                        _ = InitiateDisconnectAsync(args.Player, TimeSpan.FromMinutes(15));
                    }
                    return;
                }

                await args.Player.PlayAsync(track);
            };

            // Handler for when a LavaTrack throws an exception
            // args: TrackExceptionEventArgs
            Node.OnTrackException += async(args) =>
            {
                var player       = args.Player;
                var errorMessage = args.ErrorMessage switch
                {
                    "This video cannot be viewed anonymously." => "This video most likely hasn't premiered yet.",
                    "Received unexpected response from YouTube." => "YouTube is most likely down.",
                    _ => "Video might still be processing, try again later."
                };
                var msg = await embedHelper.BuildTrackErrorEmbed($"[{player.Track.Title}]({player.Track.Url})\n{errorMessage}");

                await player.TextChannel.SendAndRemove(embed : msg);

                if (player.Queue.Count == 0)
                {
                    //If no songs in queue it will stop playback to reset the embed
                    await player.StopAsync();

                    return;
                }
                //If queue has any songs it will skip to the next track
                await player.SkipAsync();

                return;
            };

            // Handler for when a LavaTrack gets stuck
            // args: TrackStuckEventArgs
            Node.OnTrackStuck += async(args) =>
            {
                var player = args.Player;
                var msg    = await embedHelper.BuildTrackErrorEmbed($"[{player.Track.Title}]({player.Track.Url})\nTrack got stuck, moving on...");

                await player.TextChannel.SendAndRemove(embed : msg);

                if (player.Queue.Count == 0)
                {
                    //If no songs in queue it will stop playback to reset the embed
                    await player.StopAsync();

                    return;
                }
                //If queue has any songs it will skip to the next track
                await player.SkipAsync();

                return;
            };
        }

        /// <summary>
        /// Initiates a disconnect from the voice channel
        /// </summary>
        /// <param name="player">Instance of LavaPlayer for the guild</param>
        /// <param name="timeSpan">TimeSpan for length before disconnecting</param>
        /// <returns></returns>
        private async Task InitiateDisconnectAsync(LavaPlayer player, TimeSpan timeSpan)
        {
            if (!_disconnectTokens.TryGetValue(player.VoiceChannel.Id, out var value))
            {
                value = new CancellationTokenSource();
                _disconnectTokens.TryAdd(player.VoiceChannel.Id, value);
            }
            else if (value.IsCancellationRequested)
            {
                _disconnectTokens.TryUpdate(player.VoiceChannel.Id, new CancellationTokenSource(), value);
                value = _disconnectTokens[player.VoiceChannel.Id];
            }

            var isCancelled = SpinWait.SpinUntil(() => value.IsCancellationRequested, timeSpan);

            if (isCancelled)
            {
                return;
            }

            await Node.LeaveAsync(player.VoiceChannel);

            var msg = await embedHelper.BuildMessageEmbed("Muse has disconnected due to inactivity.");

            await player.TextChannel.SendAndRemove(embed : msg);
        }