Example #1
0
        public async Task LeaveAsync()
        {
            if (!_lavaNode.TryGetPlayer(Context.Guild, out var player))
            {
                await ReplyAsync("F**k you.");

                return;
            }

            var voiceChannel = (Context.User as IVoiceState).VoiceChannel ?? player.VoiceChannel;

            if (voiceChannel == null)
            {
                await ReplyAsync("From Where?");

                return;
            }

            try
            {
                await _lavaNode.LeaveAsync(voiceChannel);
                await ReplyAsync($"I'm outta {voiceChannel.Name} bitch.");
            }
            catch (Exception ex)
            {
                await ReplyAsync(ex.Message);
            }
        }
Example #2
0
        public async Task LeaveAsync()
        {
            if (!_lavaNode.TryGetPlayer(Context.Guild, out var player))
            {
                await ReplyAsync("I'm not connected to any voice channels!");

                return;
            }

            var voiceChannel = (Context.User as IVoiceState).VoiceChannel ?? player.VoiceChannel;

            if (voiceChannel == null)
            {
                await ReplyAsync("Not sure which voice channel to disconnect from.");

                return;
            }

            try
            {
                await _lavaNode.LeaveAsync(voiceChannel);
                await ReplyAsync($"I've left {voiceChannel.Name}!");
            }
            catch (Exception ex)
            {
                await this.LogAsync(new LogMessage(LogSeverity.Error, "Music Module", ex.Message));
                await ReplyAsync("Something happened that i can't leave the VC!");
            }
        }
Example #3
0
        public async Task LeaveAsync()
        {
            if (!_lavaNode.TryGetPlayer(Context.Guild, out var player))
            {
                await ReplyAsync("I'm not connected to any voice channels!");

                return;
            }

            var voiceChannel = (Context.User as IVoiceState).VoiceChannel ?? player.VoiceChannel;

            if (voiceChannel == null)
            {
                await ReplyAsync("Not sure which voice channel to disconnect from.");

                return;
            }

            try
            {
                await _lavaNode.LeaveAsync(voiceChannel);
                await ReplyAsync($"I've left {voiceChannel.Name}!");
            }
            catch (Exception exception)
            {
                await ReplyAsync(exception.Message);
            }
        }
Example #4
0
        public async Task <Embed> GetQueueAsync(ShardedCommandContext context)
        {
            if (!_lavaNode.TryGetPlayer(context.Guild, out var player))
            {
                return(EmbedHandler.CreateEmbed(context, "Music Queue",
                                                $"{Global.ENo} | I'm not connected to a voice channel.", EmbedHandler.EmbedMessageType.Error));
            }

            if (player.PlayerState != PlayerState.Playing)
            {
                return(EmbedHandler.CreateEmbed(context, "Music Queue",
                                                $"{Global.ENo} | There's nothing playing at the moment", EmbedHandler.EmbedMessageType.Error));
            }

            var currentTrack = player.Track;
            var artwork      = await currentTrack.FetchArtworkAsync();

            var descriptionBuilder = new StringBuilder();

            if (player.Queue.Count < 1 && player.PlayerState != PlayerState.Playing)
            {
                string title = currentTrack.Title;
                return(EmbedHandler.CreateEmbed(context, $"Now Playing: **{title}**",
                                                "There are no other items in the queue.", EmbedHandler.EmbedMessageType.Success));
            }

            var trackNum = 2;

            foreach (LavaTrack track in player.Queue.Items)
            {
                if (trackNum == 2)
                {
                    descriptionBuilder.Append($"Up Next: **[{track.Title}]** - ({track.Duration})\n\n");
                    trackNum++;
                }
                else
                {
                    descriptionBuilder.Append($"#{trackNum}: **[{track.Title}]** - ({track.Duration})\n\n");
                    trackNum++;
                }
            }


            var embed = new EmbedBuilder
            {
                Title        = $"Queue",
                ThumbnailUrl = artwork,
                Description  = $"Now Playing: [{player.Track.Title}]({player.Track.Duration})\n\n{descriptionBuilder}",
                Color        = Global.NayuColor
            };

            return(embed.Build());
        }
Example #5
0
        public async Task <LavaPlayer?> JoinAsync(ICommandContext context, ITextChannel textChannel, bool sendMsg = true, bool sendAdv = true)
        {
            if (context.Guild == null)
            {
                return(null);
            }
            ;
            _audio.TryGetPlayer(context.Guild, out var guild);
            var usersVc = context.UsersVC() as SocketVoiceChannel;
            var user    = context.User as IGuildUser;

            if (usersVc == null)
            {
                if (sendMsg)
                {
                    await textChannel.SendMessageAsync($":musical_note: {context.User.Mention} You are not in a voice channel.");
                }
                return(null);
            }
            if (guild == null)
            {
                if (sendMsg && sendAdv)
                {
                    await textChannel.SendMessageAsync($":musical_note: {context.User.Mention} Successfuly joined your voice channel!");
                }
                return(await _audio.JoinAsync(context.UsersVC(), textChannel));
            }
            else if (usersVc.Id == guild.VoiceChannel.Id)
            {
                if (sendMsg && sendAdv)
                {
                    await textChannel.SendMessageAsync($":musical_note: {context.User.Mention} We are in the same voice channel already!");
                }
                return(guild);
            }
            else if (usersVc.Users.Count > 1 && !user.HasRole("DJ"))
            {
                if (sendMsg)
                {
                    await textChannel.SendMessageAsync($":musical_note: {context.User.Mention} You don't have the valid permissions to do this action.");
                }
                return(null);
            }
            if (sendMsg && sendAdv)
            {
                await textChannel.SendMessageAsync($":musical_note: {context.User.Mention} Successfuly joined your voice channel!");
            }
            await _audio.LeaveAsync(guild.VoiceChannel);

            return(await _audio.JoinAsync(context.UsersVC(), textChannel));
        }
Example #6
0
        public async Task LeaveAsync()
        {
            if (!_lavaNode.TryGetPlayer(Context.Guild, out var player))
            {
                await ReplyAndDeleteAsync($"{Global.ENo} | I'm not connected to any voice channels!");

                return;
            }

            var voiceChannel = (Context.User as IVoiceState).VoiceChannel ?? player.VoiceChannel;

            if (voiceChannel == null)
            {
                await ReplyAndDeleteAsync($"{Global.ENo} | I cannot disconnect from a voice channel you are not in!");

                return;
            }

            try
            {
                await _lavaNode.LeaveAsync(voiceChannel);
                await ReplyAsync($"✅ **|** I've left **{voiceChannel.Name}**!");
            }
            catch (Exception exception)
            {
                await ReplyAsync(exception.Message);
            }
        }
Example #7
0
        public static async Task EjectAsync(
            this LavaNode node,
            EmbedHelper embedHelper,
            IGuild guild,
            SocketCommandContext context = null)
        {
            if (context == null)
            {
                return;
            }

            if (!node.TryGetPlayer(guild, out var player))
            {
                return;
            }

            player.Queue.Clear();
            await node.LeaveAsync(player.VoiceChannel);

            if (context != null && !context.Guild.TextChannels.Where(x => x.Id == Program.BotConfig.ChannelId).Any())
            {
                return;
            }
            var embed = await EmbedHelper.BuildDefaultEmbed();

            await Program.BotConfig.BotEmbedMessage.ModifyAsync(x => { x.Content = AudioHelper.NoSongsInQueue; x.Embed = embed; });
        }
Example #8
0
        public async Task RemoveFromQueue(int index)
        {
            if (!LavaNode.TryGetPlayer(Context.Guild, out var player))
            {
                await SendWarningAsync("I'm not connected to a voice channel. So I don't have a queue right now");

                return;
            }

            if (player.Queue.Count == 0)
            {
                await SendErrorAsync("There are currently no items in the queue");

                return;
            }

            if (index < 1 || index > player.Queue.Count)
            {
                await SendErrorAsync("Index out of range, please choose a valid index");

                return;
            }

            player.Queue.RemoveAt(index - 1);

            await SendSuccessAsync("Removed from queue");
        }
Example #9
0
        public async Task Seek(TimeSpan timeSpan)
        {
            if (!LavaNode.TryGetPlayer(Context.Guild, out var player))
            {
                await SendWarningAsync("I'm not connected to a voice channel.");

                return;
            }

            if (player.PlayerState != PlayerState.Playing)
            {
                await SendWarningAsync("Woaaah there, I can't seek when nothing is playing.");

                return;
            }

            try
            {
                await player.SeekAsync(timeSpan);
                await SendSuccessAsync($"I've seeked `{player.Track.Title}` to {timeSpan}.");
            }
            catch (Exception exception)
            {
                await SendErrorAsync(exception.Message);
            }
        }
Example #10
0
        public async Task Stop()
        {
            if (!LavaNode.TryGetPlayer(Context.Guild, out var player))
            {
                await SendWarningAsync("I'm not connected to a voice channel.");

                return;
            }

            if (player.PlayerState == PlayerState.Stopped)
            {
                await SendWarningAsync("Woaaah there, I can't stop the stopped forced.");

                return;
            }

            try
            {
                await player.StopAsync();
                await SendWarningAsync("No longer playing anything.");
            }
            catch (Exception exception)
            {
                await SendErrorAsync(exception.Message);
            }
        }
Example #11
0
        public async Task Pause()
        {
            if (!LavaNode.TryGetPlayer(Context.Guild, out var player))
            {
                await SendWarningAsync("I'm not connected to a voice channel.");

                return;
            }

            if (player.PlayerState != PlayerState.Playing)
            {
                await SendWarningAsync("I cannot pause when I'm not playing anything!");

                return;
            }

            try
            {
                await player.PauseAsync();
                await SendSuccessAsync($"Paused: {player.Track.Title}");
            }
            catch (Exception exception)
            {
                await SendErrorAsync(exception.Message);
            }
        }
Example #12
0
 /// <summary>
 ///     Prepare the music player to work for the selected guild.
 /// </summary>
 /// <param name="guild">The guild to load the music player for.</param>
 public Task Prepare(IGuild guild)
 {
     if (!_lavaNode.TryGetPlayer(guild, out _player))
     {
         _player = null;
     }
     return(Task.CompletedTask);
 }
Example #13
0
        public async Task Skip()
        {
            if (!LavaNode.TryGetPlayer(Context.Guild, out var player))
            {
                await SendWarningAsync("I'm not connected to a voice channel.");

                return;
            }

            if (player.PlayerState != PlayerState.Playing)
            {
                await SendWarningAsync("Woaaah there, I can't skip when nothing is playing.");

                return;
            }

            var voiceChannelUsers = ((SocketVoiceChannel)player.VoiceChannel).Users.Where(x => !x.IsBot).ToArray();

            if (MusicService.VoteQueue.Contains(Context.User.Id) && voiceChannelUsers.Count() != 1)
            {
                await SendErrorAsync("You can't vote again.");

                return;
            }

            MusicService.VoteQueue.Add(Context.User.Id);
            var percentage = MusicService.VoteQueue.Count / voiceChannelUsers.Length * 100;

            if (percentage < 85)
            {
                await SendWarningAsync("You need more than 85% votes to skip this song.");

                return;
            }

            try
            {
                var oldTrack     = player.Track;
                var currentTrack = await player.SkipAsync();

                var embed = new EmbedBuilder()
                            .WithAuthor("Skipping Track")
                            .AddField("Skipped", oldTrack.Title)
                            .AddField("Now Playing", currentTrack.Title)
                            .WithColor(Color.Teal)
                            .Build();

                await SendEmbedAsync(embed);
            }
            catch (Exception exception)
            {
                await SendErrorAsync(exception.Message);
            }
        }
Example #14
0
        public async Task StopAsync()
        {
            if (!_lavaNode.TryGetPlayer(Context.Guild, out var player))
            {
                await ReplyAndDeleteAsync(":x: I am not connected to a voice channel.");

                return;
            }

            if (player.PlayerState == PlayerState.Stopped)
            {
                await ReplyAndDeleteAsync(":x: Playback is already stopped.");

                return;
            }

            await player.StopAsync();

            await ReplyAndDeleteAsync("Stopped.");
        }
Example #15
0
        /// <summary>Seeks the current track to specified position.
        /// </summary>
        public async Task SeekTrackAsync(SocketCommandContext context, string positionToSeek)
        {
            var guild = context.Guild;

            if (!_lavaNode.TryGetPlayer(guild, out var player))
            {
                await context.Channel.SendMessageAsync(embed : CustomFormats.CreateErrorEmbed("Could not acquire player."));

                return;
            }

            //Check if player is playing
            if (player.PlayerState is not PlayerState.Playing)
            {
                await context.Channel.SendMessageAsync(embed : CustomFormats.CreateErrorEmbed("No music playing!"));

                return;
            }

            var currentTrack = player.Track;

            if (!TimeSpan.TryParse(positionToSeek, out var positionToSeekParsed))
            {
                await context.Channel.SendMessageAsync(embed : CustomFormats.CreateErrorEmbed("**Invalid position to seek**"));

                return;
            }

            //If user wants to seek to a position greater than the track duration, warn him
            if (positionToSeekParsed > currentTrack.Duration)
            {
                await context.Channel.SendMessageAsync(embed : CustomFormats.CreateErrorEmbed("Position to seek cannot be greater than track duration!"));

                return;
            }

            //If all checks pass, then seek the current track to specified position
            await player.SeekAsync(positionToSeekParsed);

            await context.Message.AddReactionAsync(new Emoji("👍"));
        }
        public static async Task <LavaPlayer> EnsureJoin(this LavaNode node, IVoiceChannel voice, ITextChannel text)
        {
            if (!node.IsConnected)
            {
                throw new InvalidOperationException();
            }

            if (!node.TryGetPlayer(voice.Guild, out var player))
            {
                player = await node.JoinAsync(voice, text);
            }

            return(player);
        }
Example #17
0
        public async Task <IXyloxServiceResult> JoinAsync(ulong guildId, ulong voiceId, ulong textId)
        {
            var voiceChannel = GetDiscordChannel <IVoiceChannel>(voiceId);
            var textChannel  = GetDiscordChannel <ITextChannel>(textId);
            var guild        = GetGuild(guildId);

            if (_lavaNode.TryGetPlayer(guild, out var player))
            {
                return(new XyloxServiceResult {
                    Message = $"I am already joined to {player.VoiceChannel.Name}"
                });
            }


            await _lavaNode.JoinAsync(voiceChannel, textChannel);

            return(new XyloxServiceResult {
                Message = $"Joined {voiceChannel.Name}, bound to {textChannel.Name}"
            });
        }
Example #18
0
        //Если ты останешься один пусть играет трек
        private async Task UserVoiceStateUpdated(SocketUser arg1, SocketVoiceState arg2, SocketVoiceState arg3)
        {
            if (arg1.IsBot)
            {
                return;
            }

            if (arg2.VoiceChannel == arg3.VoiceChannel)
            {
                return;
            }

            //Бот на новом
            if (!(arg3.VoiceChannel is null))
            {
                var newChannel = arg3.VoiceChannel.Users;
                //Бот на новом канале
                var botNewChannel = from user in newChannel
                                    where user.IsBot
                                    select user;

                if (botNewChannel.Count() > 0)
                {
                    if (_lavaNode.TryGetPlayer(botNewChannel.FirstOrDefault().Guild, out var playerNew))
                    {
                        //if (newChannel.Count > 2)
                        //{
                        //    if (playerNew.PlayerState == PlayerState.Playing)
                        //    {
                        //        await playerNew.TextChannel.SendMessageAsync($"{arg1.Username} зашёл. Трек на паузу");
                        //        await playerNew.PauseAsync();
                        //        return;
                        //    }
                        //}
                        if (newChannel.Count == 2)
                        {
                            if (playerNew.PlayerState == PlayerState.Paused)
                            {
                                await playerNew.TextChannel.SendMessageAsync($"Возобновляю  {playerNew.Track.Title}");

                                await playerNew.ResumeAsync();

                                return;
                            }
                        }
                    }
                }
            }
Example #19
0
        public async Task <KeyValuePair <LavaTrack, bool> > PlayAsync(string query, SocketGuild guild, string source = "youtube", SocketVoiceChannel voiceChannel = null, ITextChannel textChannel = null)
        {
            if (voiceChannel != null && textChannel != null && _lavaNode.TryGetPlayer(guild, out var player) == false)
            {
                ConnectAsync(voiceChannel, textChannel).Wait();
            }

            player = _lavaNode.GetPlayer(guild);
            SearchResponse res;

            switch (source)
            {
            case "youtube":
                res = await _lavaNode.SearchYouTubeAsync(query);

                break;

            case "soundcloud":
                res = await _lavaNode.SearchSoundCloudAsync(query);

                break;

            default:
                res = await _lavaNode.SearchYouTubeAsync(query);

                break;
            }

            var track = res.Tracks.FirstOrDefault();

            if (track?.Title == "Track empty" || track is null)
            {
                return(new KeyValuePair <LavaTrack, bool>(null, false));
            }

            if (player.PlayerState == PlayerState.Playing || player.PlayerState == PlayerState.Paused)
            {
                player.Queue.Enqueue(track);
                return(new KeyValuePair <LavaTrack, bool>(track, true));
            }

            await player.PlayAsync(track);

            await player.UpdateVolumeAsync(100);

            return(new KeyValuePair <LavaTrack, bool>(track, false));
        }
Example #20
0
        public async Task PullIt()
        {
            LavaPlayer player;

            _lavaNode.TryGetPlayer(Context.Guild, out player);

            if (player?.PlayerState != PlayerState.Playing)
            {
                await ReplyAsync("I am not playing anything");

                return;
            }

            await _musicService.PullUpTrack(player, player.Track, Context.User);

            await ReplyAsync("Wheel that one up");
        }
Example #21
0
        private async Task <LavaPlayer> IsPlayingConnected()
        {
            if (!LavaNode.TryGetPlayer(Context.Guild, out var player))
            {
                await SendWarningAsync("I'm not connected to a voice channel.");

                return(null);
            }

            if (player.PlayerState == PlayerState.Playing)
            {
                return(player);
            }
            await SendWarningAsync("Woaaah there, I'm not playing any tracks.");

            return(null);
        }
Example #22
0
        private async Task MusicPlayerAutoLeave(SocketVoiceChannel channel)
        {
            var guild = _discord.GetGuild(_config.CurrentValue.MyGuildId);

            if (_lavaSocketClient.TryGetPlayer(guild, out var player))
            {
                if (player.VoiceChannel.Id == channel.Id && !channel.Users.Any(x => !x.IsBot))
                {
                    var textChannel = player.TextChannel;

                    await textChannel.SendMessageAsync($"[Auto] {await _music.StopAsync(guild)}");

                    await _music.LeaveAsync(channel);

                    await textChannel.SendMessageAsync($"[Auto] Rozłączono z kanałem {channel.Name}");
                }
            }
        }
Example #23
0
        public async Task Lyrics()
        {
            if (!_lavaNode.TryGetPlayer(Context.Guild, out var player))
            {
                await ReplyAsync("I'm not connected to a voice channel.");

                return;
            }

            if (player.PlayerState != PlayerState.Playing)
            {
                await ReplyAsync("I'm not playing any tracks.");

                return;
            }

            var lyrics = await player.Track.FetchLyricsFromOVHAsync();

            if (string.IsNullOrWhiteSpace(lyrics))
            {
                await ReplyAsync($"No lyrics found for {player.Track.Title}");

                return;
            }

            var splitLyrics   = lyrics.Split('\n');
            var stringBuilder = new StringBuilder();

            foreach (var line in splitLyrics)
            {
                if (Range.Contains(stringBuilder.Length))
                {
                    await ReplyAsync($"```{stringBuilder}```");

                    stringBuilder.Clear();
                }
                else
                {
                    stringBuilder.AppendLine(line);
                }
            }

            await ReplyAsync("Lyrics for:\n" + player.Track.Title + "\n" + $"```{stringBuilder}```");
        }
Example #24
0
        public async Task Volume(ushort volumeValue)
        {
            if (!LavaNode.TryGetPlayer(Context.Guild, out var player))
            {
                await SendWarningAsync("I'm not connected to a voice channel.");

                return;
            }

            try
            {
                await player.UpdateVolumeAsync(volumeValue);
                await SendSuccessAsync($"I've changed the player volume to {volumeValue}.");
            }
            catch (Exception exception)
            {
                await SendErrorAsync(exception.Message);
            }
        }
Example #25
0
        private async Task OnUserVoiceStateUpdated(SocketUser user, SocketVoiceState oldState, SocketVoiceState newState)
        {
            var guild = newState.VoiceChannel?.Guild ?? oldState.VoiceChannel?.Guild;

            if (guild == null)
            {
                return;
            }
            if (!_lavaNode.TryGetPlayer(guild, out var player))
            {
                return;
            }
            // So this is a guild that has a currently active sora music player. Let's investigate
            if (player.VoiceChannel == null)
            {
                return;                              // shouldn't ever happen but we never know
            }
            SocketVoiceChannel vc = guild.CurrentUser.VoiceChannel;

            if (vc == null)
            {
                return;             // Sora is in none so we'll just ignore this.
            }
            var userCount = vc.Users.Count(x => !x.IsBot);

            if (userCount > 0)
            {
                // Check if channel is AFK channel
                if (guild.AFKChannel?.Id == player.VoiceChannel.Id)
                {
                    // leave this shit
                    await _lavaNode.LeaveAsync(player.VoiceChannel);

                    return;
                }
                // No action required
                return;
            }

            // Otherwise we leave the VC.
            await _lavaNode.LeaveAsync(player.VoiceChannel);
        }
Example #26
0
        public async Task Queue()
        {
            if (!LavaNode.TryGetPlayer(Context.Guild, out var player))
            {
                await SendWarningAsync("I'm not connected to a voice channel. So I don't have a queue right now");

                return;
            }

            if (player.Queue.Count < 1)
            {
                await SendWarningAsync("There is currently no songs in the queue.");

                return;
            }

            var queue = new StringBuilder();
            var pages = new List <EmbedBuilder>();

            for (var index = 0; index < player.Queue.Count; index++)
            {
                if (index != 0 && index % 6 == 0)
                {
                    pages.Add(new EmbedBuilder().AddField("Now Playing", $"{player.Track.Title} 〚{player.Track.Queued.Username}〛").AddField("Up next", queue));
                    queue.Clear();
                }
                queue.Append(
                    $"{index + 1}: {((LavaTrack) player.Queue.ElementAt(index)).Title} 〚{((LavaTrack) player.Queue.ElementAt(index)).Queued.Username}〛\n");
            }

            if (pages.Count == 0 || queue.Length != 0)
            {
                pages.Add(new EmbedBuilder().AddField("Now Playing", $"{player.Track.Title} 〚{player.Track.Queued.Username}〛").AddField("Up next", queue));
            }

            var paginator = new PaginatedMessage(pages, "Music Queue", Color.Teal, Context.User, new AppearanceOptions {
                Timeout = TimeSpan.FromSeconds(15), Style = DisplayStyle.Minimal
            });

            await Paging.SendMessageAsync(Context.Channel, paginator);
        }
Example #27
0
        public async Task Resume()
        {
            if (!LavaNode.TryGetPlayer(Context.Guild, out var player))
            {
                await SendWarningAsync("I'm not connected to a voice channel.");

                return;
            }

            if (player.PlayerState != PlayerState.Paused)
            {
                await SendWarningAsync("I cannot resume when I'm not playing anything!");

                return;
            }

            try
            {
                await player.ResumeAsync();

                var artwork = await player.Track.FetchArtworkAsync();

                var embed = new EmbedBuilder()
                            .WithAuthor("Resumed", Context.User.GetAvatarUrl())
                            .WithTitle(player.Track.Title)
                            .WithUrl(player.Track.Url)
                            .WithThumbnailUrl(artwork)
                            .AddField("Channel", player.Track.Author, true)
                            .AddField("Duration", player.Track.Duration, true)
                            .AddField("Position", player.Track.Position.StripMilliseconds(), true)
                            .WithFooter($"Requested By {player.Track.Queued.Username}")
                            .WithColor(Color.Teal)
                            .Build();

                await SendEmbedAsync(embed);
            }
            catch (Exception exception)
            {
                await SendErrorAsync(exception.Message);
            }
        }
Example #28
0
        public async Task <string> GetCurrentLyricsAsync(ulong guildId)
        {
            if (!_lavaNode.TryGetPlayer(_client.GetGuild(guildId), out var player))
            {
                return("I am not connected to a voice channel");
            }

            if (player.PlayerState != PlayerState.Playing)
            {
                return("Player isn't playing");
            }

            var lyrics = await player.Track.FetchLyricsFromGeniusAsync();

            if (string.IsNullOrWhiteSpace(lyrics))
            {
                return($"No lyrics found for **{player.Track.Title}**");
            }

            var splitLyrics   = lyrics.Split('\n');
            var stringBuilder = new StringBuilder();

            foreach (var line in splitLyrics)
            {
                if (Range.Contains(stringBuilder.Length))
                {
                    return($"```{stringBuilder}```");
                }
                else
                {
                    stringBuilder.AppendLine(line);
                }
            }

            return($"```{stringBuilder}```");
        }
Example #29
0
        public async Task PlayAsync([Remainder] string query)
        {
            var voiceState = Context.User as IVoiceState;

            if (voiceState?.VoiceChannel == null)
            {
                await ReplyAsync("You must be connected to a voice channel!");

                return;
            }

            if (!_lavaNode.TryGetPlayer(Context.Guild, out var player)
                ) //Check if bot is connected to a voice channel in that guild and if not join new one
            {
                try
                {
                    await _lavaNode.JoinAsync(voiceState.VoiceChannel, Context.Channel as ITextChannel);

                    await Context.Channel.SendSuccessAsync("Success", $"Joined {voiceState.VoiceChannel.Name}");
                }
                catch (Exception exception)
                {
                    await Context.Channel.SendErrorAsync("Error", exception.Message);
                }
            }

            if (string.IsNullOrWhiteSpace(query)) //Check if nothing was entered
            {
                await Context.Channel.SendErrorAsync("Error", "Please provide search terms");

                return;
            }

            var players = _lavaNode.GetPlayer(Context.Guild);

            if (query.StartsWith("https://")) //Check if user entered link
            {
                var queries = query.Split(' ');
                foreach (var songQuery in queries)
                {
                    var searchResponse1 = await _lavaNode.SearchAsync(songQuery);

                    if (searchResponse1.LoadStatus == LoadStatus.LoadFailed ||
                        searchResponse1.LoadStatus == LoadStatus.NoMatches)
                    {
                        await Context.Channel.SendErrorAsync("Error", $"I could not find anything for `{songQuery}`");

                        return;
                    }


                    if (players.PlayerState == PlayerState.Playing || players.PlayerState == PlayerState.Paused)
                    {
                        if (!string.IsNullOrWhiteSpace(searchResponse1.Playlist.Name))
                        {
                            foreach (var track in searchResponse1.Tracks)
                            {
                                players.Queue.Enqueue(track);
                            }

                            var track1    = searchResponse1.Tracks[0];
                            var thumbnail = await track1.FetchArtworkAsync(); //get album cover for current song

                            await Context.Channel.Music("Enqued:",
                                                        $"Enqueued `{searchResponse1.Tracks.Count}` songs from the `{searchResponse1.Playlist.Name}` playlist",
                                                        thumbnail ??
                                                        "https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2Ficons.iconarchive.com%2Ficons%2Fiynque%2Fios7-style%2F1024%2FMusic-icon.png&f=1&nofb=1");
                        }
                        else
                        {
                            var track     = searchResponse1.Tracks[0];
                            var thumbnail = await track.FetchArtworkAsync(); //get album cover for current song

                            players.Queue.Enqueue(track);
                            await ReplyAsync($"Enqueued: {track.Title}");

                            await Context.Channel.Music("Enqued:", $"Enqueued `{track.Title}`",
                                                        thumbnail ??
                                                        "https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2Ficons.iconarchive.com%2Ficons%2Fiynque%2Fios7-style%2F1024%2FMusic-icon.png&f=1&nofb=1");
                        }
                    }
                    else
                    {
                        var track = searchResponse1.Tracks[0];
                        var thumb = await track.FetchArtworkAsync(); //get album cover for current song

                        if (!string.IsNullOrWhiteSpace(searchResponse1.Playlist.Name))
                        {
                            for (var i = 0; i < searchResponse1.Tracks.Count; i++)
                            {
                                if (i == 0)
                                {
                                    await players.PlayAsync(track);

                                    await Context.Channel.Music("Now Playing:", $"Now playing `{track.Title}`", thumb);
                                }
                                else
                                {
                                    players.Queue.Enqueue(searchResponse1.Tracks[i]);
                                }
                            }

                            var track1    = searchResponse1.Tracks[0];
                            var thumbnail = await track1.FetchArtworkAsync(); //get album cover for current song

                            await Context.Channel.Music("Enqued:",
                                                        $"Enqueued `{searchResponse1.Tracks.Count}` songs from the `{searchResponse1.Playlist.Name}` playlist",
                                                        thumbnail ??
                                                        "https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2Ficons.iconarchive.com%2Ficons%2Fiynque%2Fios7-style%2F1024%2FMusic-icon.png&f=1&nofb=1");
                        }
                        else
                        {
                            var track1    = searchResponse1.Tracks[0];
                            var durSec    = track1.Duration.Seconds;
                            var durMin    = track1.Duration.Minutes;
                            var thumbnail = await track1.FetchArtworkAsync(); //get album cover for current song

                            await players.PlayAsync(track);

                            await Context.Channel.Music("Now Playing:",
                                                        $"**Now playing:** `{track.Title}`\n**Duration:** `{durMin}:{durSec}`", thumbnail);
                        }
                    }
                }
            }
            else //if query is not a url search youtube
            {
                var searchResponse = await _lavaNode.SearchYouTubeAsync(query);

                if (searchResponse.LoadStatus == LoadStatus.LoadFailed ||
                    searchResponse.LoadStatus == LoadStatus.NoMatches)
                {
                    await Context.Channel.SendErrorAsync("Error", $"I could not find anything for `{query}`");

                    //await ReplyAsync($"I wasn't able to find anything for `{query}`.");
                    return;
                }


                if (players.PlayerState == PlayerState.Playing || players.PlayerState == PlayerState.Paused)
                {
                    var track     = searchResponse.Tracks[0];
                    var thumbnail = await track.FetchArtworkAsync(); //get album cover for current song

                    var durSec = track.Duration.Seconds;
                    var durMin = track.Duration.Minutes;

                    players.Queue.Enqueue(track);
                    await Context.Channel.Music("Enqued:",
                                                $"**Song:** `{track.Title}`\n**Duration:** `{durMin}:{durSec}`",
                                                thumbnail ??
                                                "https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2Ficons.iconarchive.com%2Ficons%2Fiynque%2Fios7-style%2F1024%2FMusic-icon.png&f=1&nofb=1");
                }
                else
                {
                    var track     = searchResponse.Tracks[0];
                    var thumbnail = await track.FetchArtworkAsync(); //get album cover for current song

                    var durSec = track.Duration.Seconds;
                    var durMin = track.Duration.Minutes;

                    await players.PlayAsync(track);

                    await Context.Channel.Music("Playing:",
                                                $"**Song:** `{track.Title}`\n**Duration:** `{durMin}:{durSec}`",
                                                thumbnail ??
                                                "https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2Ficons.iconarchive.com%2Ficons%2Fiynque%2Fios7-style%2F1024%2FMusic-icon.png&f=1&nofb=1");
                }
            }
        }
Example #30
0
        public async Task ShuffleQueue()
        {
            if (!_node.TryGetPlayer(Context.Guild, out var player))
            {
                await ReplyFailureEmbed("I have not joined any Voice Channel yet.");

                return;
            }

            if (!await CheckIfSameVc(player.VoiceChannel))
            {
                return;
            }

            if (player.Queue.Count == 0)
            {
                await ReplyFailureEmbed("Queue empty. Nothing to shuffle");

                return;
            }

            player.Queue.Shuffle();
            await ReplyMusicEmbed("Shuffled queue for you ;)");
        }