// public async Task<string> PlayAsync(string query, IGuild guildId) // { // var _player = _lavaSocketClient.GetPlayer(guildId); // var results = await SearchSongAsync(query); // if (results.LoadStatus == Victoria.Enums.LoadStatus.NoMatches || results.LoadStatus == Victoria.Enums.LoadStatus.LoadFailed) // return "Nie znaleziono"; // var track = results.Tracks.FirstOrDefault(); // if (_player.PlayerState == Victoria.Enums.PlayerState.Playing) // { // _player.Queue.Enqueue(track); // return $"Dodano do kolejki: {track.Title.SongTitleTrim()} ({(track.Duration.Hours > 0 ? track.Duration.ToString(@"hh\:mm\:ss") : track.Duration.ToString(@"mm\:ss"))})"; // } // else // { // await _player.PlayAsync(track); // return $"Teraz odtwarzane: {track.Title.SongTitleTrim()} ({(track.Duration.Hours > 0 ? track.Duration.ToString(@"hh\:mm\:ss") : track.Duration.ToString(@"mm\:ss"))})"; // } // } public async Task <string> PlayAsync(string query, IGuild guildId) { var _player = _lavaSocketClient.GetPlayer(guildId); var results = await SearchSongAsync(query); if (results.LoadStatus == Victoria.Enums.LoadStatus.NoMatches || results.LoadStatus == Victoria.Enums.LoadStatus.LoadFailed) { return("Nie znaleziono"); } var sb = new StringBuilder(); foreach (var track in SongsFromSearchGet(results)) { if (_player.PlayerState == Victoria.Enums.PlayerState.Playing) { _player.Queue.Enqueue(track); sb.AppendLine($"Dodano do kolejki: {track.Title.SongTitleTrim()} ({track.Duration.SongDurationToString()})"); } else { await _player.PlayAsync(track); sb.AppendLine($"Teraz odtwarzane: {track.Title.SongTitleTrim()} ({track.Duration.SongDurationToString()})"); } } return(sb.ToString()); }
private bool SetPlayer(IGuild guild) { if (!NodeHasPlayer(guild)) { return(false); } _player = _lavaNode.GetPlayer(guild); return(true); }
// Called when the bot leaves the channel public async Task <Embed> LeaveAsync(IGuild guild) { try { //Get The Player Via GuildID. var player = _lavaNode.GetPlayer(guild); //if The Player is playing, Stop it. if (player.PlayerState is PlayerState.Playing) { await player.StopAsync(); } //Leave the voice channel. await _lavaNode.LeaveAsync(player.VoiceChannel); await player.DisposeAsync(); Log.Information("Music", $"Bot has left."); return(await EmbedHandler.CreateBasicEmbed("Night Rune", $"Leaving voice channel.", Color.Blue)); } //Tell the user about the error so they can report it back to us. catch (InvalidOperationException ex) { return(await EmbedHandler.CreateErrorEmbed("Music, Leave", ex.Message)); } }
public async Task LeaveAsync() { if (!_lavaNode.HasPlayer(Context.Guild)) { await ReplyAsync("I'm not connected to a channel"); return; } var voiceChannel = _lavaNode.GetPlayer(Context.Guild).VoiceChannel; await _lavaNode.LeaveAsync(voiceChannel); }
public async Task Play([Remainder] string query) { var guild = Context.Guild as IGuild; var player = _lavaNode.GetPlayer(guild); await player.UpdateVolumeAsync(10); var results = await _lavaNode.SearchYouTubeAsync(query); if (results.LoadStatus == LoadStatus.NoMatches || results.LoadStatus == LoadStatus.LoadFailed) { await ReplyAsync("No matches found."); } var track = results.Tracks.FirstOrDefault(); if (player.PlayerState == PlayerState.Playing) { player.Queue.Enqueue(track); await ReplyAsync("Track added to queue."); } else { await player.PlayAsync(track); await ReplyAsync($"Now playing: {track.Title}"); } }
public async Task LeaveAsync() { if (!_lavaNode.HasPlayer(Context.Guild)) { await ReplyAndDeleteAsync(":x: I am not connected to a voice channel."); return; } var channel = _lavaNode.GetPlayer(Context.Guild).VoiceChannel; await _lavaNode.LeaveAsync(channel); await ReplyAndDeleteAsync($"Left **{channel.Name}**."); }
public async Task SkipAsync(ISocketMessageChannel channel, SocketGuildUser user) { var chnl = channel as SocketGuildChannel; var player = _lavaNode.GetPlayer(chnl.Guild); if (player.VoiceChannel != user.VoiceChannel) { return; } VoteEmbed embed = new VoteEmbed(user, player, _client.CurrentUser); RestUserMessage message = await embed.CreateEmbed(channel); VoteEmbed.TrackingVote.Add(message.Id, embed); await DeleteTimeoutAsync(message); }
public async Task <string> PlayAsync(string query, IGuild guild) { _player = _lavaNode.GetPlayer(guild); var results = await _lavaNode.SearchYouTubeAsync(query); if (results.LoadType == LoadType.NoMatches || results.LoadType == LoadType.LoadFailed) { return("**No matches found.**"); } var track = results.Tracks.FirstOrDefault(); if (_player.PlayerState == PlayerState.Playing) { _player.Queue.Enqueue(track); return($"**{track.Title} has been added to the queue**"); } else { await _player.PlayAsync(track); await _client.SetGameAsync(track.Title); return($":ok_hand::rofl:**Now playing {track.Title}**:rofl::ok_hand:"); } }
public async Task Command() { Server server = await DatabaseQueries.GetOrCreateServerAsync(Context.Guild.Id); LavaNode node = ConfigProperties.LavaNode; LavaPlayer player = node.GetPlayer(Context.Guild); if (player == null) { await SendBasicErrorEmbedAsync($"There needs to be an active music player in the " + $"server for this command to work. Start one " + $"by using `{server.CommandPrefix}play <song>`!"); return; } if (player.PlayerState == PlayerState.Playing) { await player.PauseAsync(); await SendBasicSuccessEmbedAsync($"Successfully paused the player."); } else { await SendBasicErrorEmbedAsync($"There is no song currently playing, therefore I have nothing to pause. If " + $"you have previously used the `{server.CommandPrefix}pause` command, " + $"use the `{server.CommandPrefix}resume` command to resume the player."); } }
public async Task Command() { LavaNode node = ConfigProperties.LavaNode; LavaPlayer player = node.GetPlayer(Context.Guild); if (player.Queue.Count > 0) { var skipEmbed = new KaguyaEmbedBuilder { Title = $"Kaguya Music: Skip {Centvrio.Emoji.AudioVideo.FastForward}", Description = $"Successfully skipped `{player.Track.Title}`.\n" + $"Now playing: `{((LavaTrack) player.Queue.Peek()).Title}`" }; await SendEmbedAsync(skipEmbed); } try { await player.SkipAsync(); } catch (Exception) { var skipEmbed = new KaguyaEmbedBuilder { Title = $"Kaguya Music: Skip {Centvrio.Emoji.AudioVideo.FastForward}", Description = $"Successfully skipped `{player.Track.Title}`.\n" + $"There are no more tracks in the queue." }; await SendEmbedAsync(skipEmbed); await player.StopAsync(); } }
public async Task Command() { Server server = await DatabaseQueries.GetOrCreateServerAsync(Context.Guild.Id); LavaNode node = ConfigProperties.LavaNode; LavaPlayer player = node.GetPlayer(Context.Guild); if (player == null) { await SendBasicErrorEmbedAsync($"There needs to be an active music player in the " + $"server for this command to work. Start one " + $"by using `{server.CommandPrefix}play <song>`!"); return; } if (player.PlayerState == PlayerState.Paused) { await player.ResumeAsync(); await SendBasicSuccessEmbedAsync($"Successfully resumed the player."); } else { await SendBasicErrorEmbedAsync($"The player is already actively playing."); } }
private async Task OnWebSocketClosed(WebSocketClosedEventArgs arg) { var player = _lavaNode.GetPlayer(_client.GetGuild(arg.GuildId)); var voiceChannel = player.VoiceChannel; await voiceChannel.DisconnectAsync(); _logger.LogCritical($"Discord WebSocket connection closed with following reason: {arg.Reason}"); }
public async Task Leave() { if (_player == null) { await ReplyAsync("Player not connected to any voice channel!"); return; } await _node.DisconnectAsync(Context.Guild.Id); _player = _node.GetPlayer(Context.Guild.Id); }
public async Task PlayAsync([Remainder] string query) { if (string.IsNullOrWhiteSpace(query)) { await ReplyAsync("Please provide search terms."); return; } if (!_lavaNode.HasPlayer(Context.Guild)) { await ReplyAsync("I'm not connected to a voice channel."); return; } var searchResponse = await _lavaNode.SearchYouTubeAsync(query); if (searchResponse.LoadStatus == LoadStatus.LoadFailed || searchResponse.LoadStatus == LoadStatus.NoMatches) { await ReplyAsync($"I wasn't able to find anything for `{query}`."); return; } var player = _lavaNode.GetPlayer(Context.Guild); if (player.PlayerState == PlayerState.Playing || player.PlayerState == PlayerState.Paused) { var track = searchResponse.Tracks[0]; player.Queue.Enqueue(track); await ReplyAsync($"Enqueued: {track.Title}"); } else { var track = searchResponse.Tracks[0]; await player.PlayAsync(track); await ReplyAsync($"Now Playing: {track.Title}"); } }
public async Task Command() { Server server = await DatabaseQueries.GetOrCreateServerAsync(Context.Guild.Id); LavaNode node = ConfigProperties.LavaNode; LavaPlayer player = node.GetPlayer(Context.Guild); if (player == null) { await SendBasicErrorEmbedAsync($"There needs to be an active music player in the " + $"server for this command to work. Start one " + $"by using `{server.CommandPrefix}play <song>`!"); return; } var embed = new KaguyaEmbedBuilder { Title = $"Kaguya Music: Queue {Centvrio.Emoji.Office.SpiralNotepad}", Description = "" }; if (player.Queue.Count == 0 && player.PlayerState != PlayerState.Playing) { await SendBasicErrorEmbedAsync($"The current player is not playing a song and has nothing in the queue."); return; } if (player.Queue.Count == 0 && player.PlayerState == PlayerState.Playing) { embed.Description = $"**Now Playing:** [{player.Track.Title}]({player.Track.Url})\n" + $"No items in queue."; } if (player.Queue.Count > 0 && player.PlayerState == PlayerState.Playing) { embed.Description = $"**Now Playing:** [{player.Track.Title}]({player.Track.Url})\n\n" + $"**Up Next: {Centvrio.Emoji.AudioVideo.FastDown}\n**"; for (int i = 0; i < (player.Queue.Count < 50 ? player.Queue.Count : 50); i++) { embed.Description += $"`#{i + 1}.` [{((LavaTrack) player.Queue.ToList()[i]).Title}]" + $"({((LavaTrack) player.Queue.ToList()[i]).Url})\n"; } } await SendEmbedAsync(embed); }
public async Task <string> PlayTrack(string query, SocketUser user, SocketGuild guild, bool skipQueue) { if (!_lavaNode.HasPlayer(guild)) { await ConnectToChannelAsync(user, guild); } var player = _lavaNode.GetPlayer(guild); var results = await _lavaNode.SearchYouTubeAsync(query); if (results.LoadStatus == LoadStatus.LoadFailed || results.LoadStatus == LoadStatus.NoMatches) { return("No matches found"); } var track = results.Tracks.FirstOrDefault(); string returnMessage = ""; if (player.PlayerState == PlayerState.Playing && !skipQueue) { player.Queue.Enqueue(track); returnMessage = $"Track {track.Title} is queued"; } else { await player.PlayAsync(track); returnMessage = $"Track {track.Title} is now playing"; } using (var scope = _serviceScope.CreateScope()) { try { var discordTrackService = scope.ServiceProvider.GetService <IDiscordTrackService>(); try { await discordTrackService.AddTrackAsync(user, track.Url); } catch (InvalidUrlException e) { returnMessage = e.ToString(); } catch (DataContextException e) { returnMessage = e.ToString(); } } catch (Exception e) { Console.WriteLine(e); } } return(returnMessage); }
protected override void BeforeExecute(CommandInfo command) { _node = _lavalink.DefaultNode; _player = _node.GetPlayer(Context.Guild.Id); _node.TrackFinished = async(player, track, reason) => { if (player.Queue.Count != 0) { await player.PlayAsync(player.Queue.Dequeue()); } }; base.BeforeExecute(command); }
public async Task Disconnect() { if (!_lavaNode.HasPlayer(Context.Guild)) { await Context.Channel.SendErrorAsync("Music", "I'm not connected to a voice channel."); return; } var player = _lavaNode.GetPlayer(Context.Guild); if (player.PlayerState is PlayerState.Playing) { await player.StopAsync(); } await _lavaNode.LeaveAsync(player.VoiceChannel); await Context.Channel.SendSuccessAsync("Music", "Disconnected from all voice channels!"); }
public static async Task <string> PlayAsync(SocketGuildUser user, IGuild guild, string query) { if (user.VoiceChannel is null) { return("bir kanala gir babun"); } try { var player = _lavaNode.GetPlayer(guild); LavaTrack track; var search = Uri.IsWellFormedUriString(query, UriKind.Absolute) ? await _lavaNode.SearchAsync(query) : await _lavaNode.SearchYouTubeAsync(query); if (search.LoadStatus == LoadStatus.NoMatches) { return($"{query} hakkında bir şey bulamadım :("); } track = search.Tracks.FirstOrDefault(); if (player.Track != null && player.PlayerState is PlayerState.Playing || player.PlayerState is PlayerState.Paused) { player.Queue.Enqueue(track); Console.WriteLine($"[{DateTime.Now}]\t(AUDIO)\tŞarkı sıraya eklendi."); return($"{track.Title} sıraya eklendi."); } await player.PlayAsync(track); Console.WriteLine($"Şuanda Çalan Parça: {track.Title}"); return($"Şuanda Çalan Parça: {track.Title} {track.Duration}"); } catch (Exception ex) { return($"ERROR:\t{ex.Message}"); } }
public async Task <string> MoveAsync(IGuild guild, IVoiceChannel voiceChannel, ITextChannel textChannel) { if (!guildInfo.ContainsKey(guild)) { return("Not currently in a voice channel."); } await lavaNode.MoveChannelAsync(voiceChannel); var player = lavaNode.GetPlayer(guild); if (guildInfo.TryGetValue(guild, out DJGuildInfo val)) { val.voiceChannel = voiceChannel; } return($"Moved from {player.VoiceChannel} to {voiceChannel}."); }
public async Task Skip() { var voiceState = Context.User as IVoiceState; if (voiceState?.VoiceChannel == null) { await ReplyAsync("You must be connected to a voice channel!"); return; } if (!_lavaNode.HasPlayer(Context.Guild)) { await ReplyAsync("First play something moron"); return; } var player = _lavaNode.GetPlayer(Context.Guild); if (voiceState.VoiceChannel != player.VoiceChannel) { await ReplyAsync("Be on the same voice channel reatard"); } if (player.Queue.Count == 0) { await ReplyAsync("no more skipping or u will skip urself"); } var eb = new EmbedBuilder() .WithColor(new Color(255, 255, 255)) .AddField("Skipped OwO", $"Now playing: {player.Track.Title}") .Build(); await player.SkipAsync(); await ReplyAsync(embed : eb); }
public async Task LeaveAsync() { if (_lavaNode.HasPlayer(Context.Guild) is false) { await RespondAsync("Currently not playing."); return; } var player = _lavaNode.GetPlayer(Context.Guild); if (Context.User is IVoiceState user && user.VoiceChannel != player.VoiceChannel) { await RespondAsync("You must be in the same voice channel."); return; } // Stop playing and leave. if (player.PlayerState is PlayerState.Playing) { await player.StopAsync(); } var channel = player.VoiceChannel; await _lavaNode.LeaveAsync(channel); int bitrateKb = channel.Bitrate / 1000; var embed = new EmbedBuilder() .WithTitle(channel.Name) .WithAuthor("Left voice channel", Context.Client.CurrentUser.GetAvatarUrl()) .WithDescription($"{bitrateKb.ToString()} kbps") .WithColor(Config.Value.EmbedColor) .WithFooter($"Region: {channel.RTCRegion ?? "automatic"}") .Build(); Logger.LogTrace($"Left: {channel.Name} in {Context.Guild}"); await RespondAsync(embed : embed); }
public async Task <string> PlayAsync(string query, ulong guildId) { var _player = _lavaNode.GetPlayer(_client.GetGuild(guildId)); var results = await _lavaNode.SearchYouTubeAsync(query); if (results.LoadStatus == LoadStatus.NoMatches || results.LoadStatus == LoadStatus.LoadFailed) { return($"No matches found for '{query}'"); } var track = results.Tracks.FirstOrDefault(); if (_player.PlayerState == PlayerState.Playing) { _player.Queue.Enqueue(track); return($"**{track.Title}** has been added to the queue"); } else { await _player.PlayAsync(track); return($"Now playing **{track.Title}**"); } }
public static async System.Threading.Tasks.Task <bool> MusicCommands(SocketMessage message, CommandContext context, DiscordSocketClient client, LavaNode lava) { if (Validation.CheckCommand(message, "play")) { if ((message.Author as IVoiceState).VoiceChannel == null) { DiscordFunctions.EmbedThis("Music", "You must first join a voice channel!", "red", context); return(true); } var temp = client.GetGuild(context.Guild.Id).CurrentUser.VoiceState; if (temp != null && client.GetGuild(context.Guild.Id).CurrentUser.VoiceChannel != (message.Author as IVoiceState).VoiceChannel) { DiscordFunctions.EmbedThis("Music", "I can't join another voice channel until I'm disconnected from another channel.", "red", context); return(true); } SearchResponse search = new SearchResponse(); var videoId = string.Empty; var timestamp = string.Empty; string query = message.Content.ToLower().Replace("!play ", ""); if (query.ToLower().Contains("www.youtube.com/watch?v=")) { var uri = new Uri(@query); var queryid = HttpUtility.ParseQueryString(uri.Query); if (queryid.AllKeys.Contains("v")) { videoId = queryid["v"]; } else { videoId = uri.Segments.Last(); } if (queryid.AllKeys.Contains("t")) { timestamp = queryid["t"]; } if (timestamp != string.Empty) { videoId = videoId.Replace("&t=" + timestamp, ""); } search = await lava.SearchYouTubeAsync(query.Replace("&t=" + timestamp, "")); } else { search = await lava.SearchYouTubeAsync(query); } LavaTrack track = new LavaTrack(); if (query.ToLower().Contains("www.youtube.com/watch?v=")) { bool found = false; foreach (var vid in search.Tracks) { if (vid.Id.ToLower() == videoId) { track = vid; found = true; break; } } if (found == false) { track = search.Tracks.FirstOrDefault(); } } else { track = search.Tracks.FirstOrDefault(); } var player = lava.HasPlayer(context.Guild) ? lava.GetPlayer(context.Guild) : await lava.JoinAsync((context.User as IVoiceState).VoiceChannel, (ITextChannel)message.Channel); if (player.PlayerState == PlayerState.Playing) { player.Queue.Enqueue(track); DiscordFunctions.EmbedThis("Music", "Enqeued " + track.Title, "orange", context); } else { await player.PlayAsync(track); try { if (timestamp != string.Empty) { if (timestamp.ToLower().Contains("s")) { timestamp = timestamp.ToLower().Replace("s", ""); } await player.SeekAsync(TimeSpan.FromSeconds(Convert.ToDouble(timestamp))); } } catch { } DiscordFunctions.EmbedThis("Music", "Playing " + track.Title, "green", context); } return(true); } else if (Validation.CheckCommand(message, "skip")) { var _player = lava.GetPlayer(context.Guild); if (_player is null || _player.Queue.Count is 0) { DiscordFunctions.EmbedThis("Music", "Nothing in the queue", "orange", context); return(true); } var oldTrack = _player.Track; await _player.SkipAsync(); DiscordFunctions.EmbedThis("Music", "Skipped: " + oldTrack.Title + "\nNow Playing: " + _player.Track.Title, "orange", context); return(true); } else if (Validation.CheckCommand(message, "stop")) { var _player = lava.GetPlayer(context.Guild); if (_player == null) { return(true); } await _player.StopAsync(); DiscordFunctions.EmbedThis("Music", "Stopped player", "orange", context); return(true); } else if (Validation.CheckCommand(message, "volume")) { LavaPlayer _player; try { _player = lava.GetPlayer(context.Guild); } catch { DiscordFunctions.EmbedThis("Music", "Nothing is playing", "orange", context); return(true); } if (string.IsNullOrWhiteSpace(message.Content.Replace("!volume", ""))) { DiscordFunctions.EmbedThis("Music", "Please use a number between 2- 150", "orange", context); return(true); } var vol = Convert.ToUInt16(message.Content.Replace("!volume", "").Trim()); if (vol > 150 || vol <= 2) { DiscordFunctions.EmbedThis("Music", "Please use a number between 2- 150", "orange", context); return(true); } await _player.UpdateVolumeAsync(vol); DiscordFunctions.EmbedThis("Music", "Volume set to: " + vol.ToString(), "green", context); return(true); } else if (Validation.CheckCommand(message, "pause")) { LavaPlayer _player; try { _player = lava.GetPlayer(context.Guild); } catch { DiscordFunctions.EmbedThis("Music", "Nothing is playing", "orange", context); return(true); } if (_player.PlayerState != PlayerState.Paused) { await _player.PauseAsync(); DiscordFunctions.EmbedThis("Music", "Player is Paused", "orange", context); return(true); } else { await _player.ResumeAsync(); DiscordFunctions.EmbedThis("Music", "Playback Resumed", "green", context); return(true); } } else if (Validation.CheckCommand(message, "resume")) { LavaPlayer _player; try { _player = lava.GetPlayer(context.Guild); } catch { DiscordFunctions.EmbedThis("Music", "Nothing is playing", "orange", context); return(true); } if (_player.PlayerState != PlayerState.Paused) { await _player.ResumeAsync(); DiscordFunctions.EmbedThis("Music", "Playback Resumed", "green", context); return(true); } else { DiscordFunctions.EmbedThis("Music", "Playback is not paused", "orange", context); return(true); } } else if (Validation.CheckCommand(message, "join")) { var user = context.User as SocketGuildUser; if (user.VoiceChannel is null) { DiscordFunctions.EmbedThis("Music", "You need to connect to a voice channel", "red", context); return(true); } else { LavaPlayer _player; try { _player = lava.GetPlayer(context.Guild); DiscordFunctions.EmbedThis("Music", "Bot is already in a channel", "red", context); return(true); } catch { await lava.JoinAsync((context.User as IVoiceState).VoiceChannel, (ITextChannel)message.Channel); return(true); } } } else if (Validation.CheckCommand(message, "leave")) { var user = context.User as SocketGuildUser; if (user.VoiceChannel is null) { DiscordFunctions.EmbedThis("Music", "Please join the channel the bot is in to make it leave", "red", context); return(true); } else { LavaPlayer _player; try { _player = lava.GetPlayer(context.Guild); } catch { DiscordFunctions.EmbedThis("Music", "Please join the channel the bot is in to make it leave", "red", context); return(true); } if (_player.VoiceChannel == user.VoiceChannel) { await lava.LeaveAsync((context.User as IVoiceState).VoiceChannel); } else { DiscordFunctions.EmbedThis("Music", "Please join the channel the bot is in to make it leave", "red", context); return(true); } } } return(false); }
public bool IsPlaying(IGuild guild) { return(_lavaNode.GetPlayer(guild).PlayerState == PlayerState.Playing); }
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"); } } }
private async Task UserVoiceStateUpdated(SocketUser socketUser, SocketVoiceState oldSocketVoiceState, SocketVoiceState newSocketVoiceState) { if (socketUser.IsBot) { return; } var member = await _db.ServerMembers.FirstOrDefaultAsync(x => x.DiscordId == socketUser.Id.ToString()); if (member?.IntroSong == null || socketUser.Id == _lastRequestBy) { return; } if (oldSocketVoiceState.VoiceChannel == null) { Console.WriteLine($"User {socketUser.Username} entered the server!"); if (_lavaNode.HasPlayer(newSocketVoiceState.VoiceChannel.Guild)) { await _lavaNode.MoveChannelAsync(newSocketVoiceState.VoiceChannel); } else { await _audioService.JoinChannel(socketUser as IVoiceState, newSocketVoiceState.VoiceChannel.Guild); } var player = _lavaNode.GetPlayer(newSocketVoiceState.VoiceChannel.Guild); await player.UpdateVolumeAsync(7); var searchResponse = await _lavaNode.SearchAsync(member.IntroSong.Url); var track = searchResponse.Tracks[0]; var timespan = member?.IntroSongSeek ?? TimeSpan.Zero; await player.PlayAsync(track); if (member?.IntroSongSeek.HasValue ?? false) { await player.SeekAsync(member.IntroSongSeek); } _lastRequestBy = socketUser.Id; if (_cancelIntro != null && !_cancelIntro.IsCancellationRequested) { _cancelIntro.Cancel(); } _cancelIntro = new CancellationTokenSource(); var cancellationToken = _cancelIntro.Token; Task.Run(async() => { await Task.Delay(TimeSpan.FromSeconds(30), cancellationToken); if (cancellationToken.IsCancellationRequested) { return; } if (player.PlayerState != PlayerState.Disconnected && socketUser.Id == _lastRequestBy) { await _lavaNode.LeaveAsync(newSocketVoiceState.VoiceChannel); } }, cancellationToken); } return; }
public async Task PlayAsync([Remainder] string query) { await Context.Channel.TriggerTypingAsync(); _logger.LogInformation("{username}#{discriminator} executed play ({query}) on {server}/{channel}", Context.User.Username, Context.User.Discriminator, query, Context.Guild?.Name ?? "DM", Context.Channel.Name); if (!CheckIfLavaLinkIsEnabled()) { return; } if (await ServerHelper.CheckIfContextIsDM(Context)) { return; } if (string.IsNullOrWhiteSpace(query)) { await ReplyAsync("Please provide search terms."); return; } if (!_lavaNode.HasPlayer(Context.Guild)) { await ReplyAsync("I'm not connected to a voice channel."); await ReplyAsync("Joining you ;-)"); await JoinAsync(); } //var searchResponse = await _lavaNode.SearchAsync(query); var searchResponse = await _lavaNode.SearchYouTubeAsync(query); if (searchResponse.LoadStatus == LoadStatus.LoadFailed || searchResponse.LoadStatus == LoadStatus.NoMatches) { await ReplyAsync($"I wasn't able to find anything for `{query}`."); return; } var player = _lavaNode.GetPlayer(Context.Guild); if (player.PlayerState == PlayerState.Playing || player.PlayerState == PlayerState.Paused) { if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name)) { foreach (var track in searchResponse.Tracks) { player.Queue.Enqueue(track); } await ReplyAsync($"Enqueued {searchResponse.Tracks.Count} tracks."); } else { var track = searchResponse.Tracks[0]; player.Queue.Enqueue(track); await ReplyAsync($"Enqueued: {track.Title}"); } } else { var track = searchResponse.Tracks[0]; // First result, maybe a random one? if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name)) // Play a playlist, maybe make this an option? { for (var i = 0; i < searchResponse.Tracks.Count; i++) { if (i == 0) { await player.PlayAsync(track); await ReplyAsync($"Now Playing: {track.Title}"); } else { player.Queue.Enqueue(searchResponse.Tracks[i]); } } await ReplyAsync($"Enqueued {searchResponse.Tracks.Count} tracks."); } else { await player.PlayAsync(track); await ReplyAsync($"Now Playing: {track.Title}"); } } }
public async Task QueueAsync(ICommandContext ctx, string query) { LavaPlayer player = _lavaNode.GetPlayer(ctx.Guild); if (string.IsNullOrWhiteSpace(query)) { await player.TextChannel.EmbedAsync(new EmbedBuilder().WithDynamicColor(ctx) .WithAuthor("Playing song", "https://i.imgur.com/fGNKX6x.png") .WithDescription($"{player.Track.PrettyFullTrackWithCurrentPos()}") .WithFooter(player.Track.PrettyFooter(player.Volume))).ConfigureAwait(false); return; } // check if url is youtube bool isYtUrl = Regex.IsMatch(query, @"^(https?\:\/\/)?((www\.)?youtube\.com|youtu\.?be)\/.+$"); // matches youtube playlist // can use to capture playlist ID if needed bool isYtPlaylist = Regex.IsMatch(query, @"^.*(youtu.be\/|list=)([^#\&\?]*).*"); SearchResponse result; if (isYtUrl) { result = await _lavaNode.SearchAsync(query).ConfigureAwait(false); } else { result = await _lavaNode.SearchYouTubeAsync(query).ConfigureAwait(false); } if (result.LoadStatus == LoadStatus.NoMatches) { await ctx.Channel.SendErrorAsync("No matches found.").ConfigureAwait(false); return; } if (result.LoadStatus == LoadStatus.LoadFailed) { await ctx.Channel.SendErrorAsync("Failed to load track.").ConfigureAwait(false); return; } if (isYtPlaylist && result.Tracks.Count > 1) { await QueuePlaylistAsync(ctx, player, result.Tracks).ConfigureAwait(false); return; } LavaTrack track = result.Tracks[0]; // set the queued property so we know which user queued the track track.Queued = ctx.User as IGuildUser; LinkedListNode <LavaTrack> linkedTrack = player.Queue.Enqueue(track); EmbedBuilder embed = new EmbedBuilder().WithDynamicColor(ctx); if (player.PlayerState == PlayerState.Playing || player.PlayerState == PlayerState.Paused) { embed.WithAuthor($"Queued: #{player.Queue.Count}", "https://i.imgur.com/VTRacvz.png") .WithDescription($"{track.PrettyTrack()}") .WithFooter(track.PrettyFooter(player.Volume) + FormatAutoplayAndLoop(player)); IUserMessage msg = await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false); msg.DeleteAfter(10); } else { await player.PlayAsync(linkedTrack).ConfigureAwait(false); embed.WithAuthor("Playing song", "https://i.imgur.com/fGNKX6x.png") .WithDescription($"{track.PrettyTrack()}") .WithFooter(track.PrettyFooter(player.Volume)); await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false); } await ctx.Message.DeleteAsync().ConfigureAwait(false); }
public async Task PlayAsync([Remainder] string searchQuery) { //if (Regex.IsMatch(searchQuery, @"^(spotify:|https:\/\/[a-z]+\.spotify\.com\/)")){ if (Uri.IsWellFormedUriString(searchQuery, UriKind.Absolute) && searchQuery.Contains("spotify")) { searchQuery = await SpotifyToSearchQuery(searchQuery); } if (string.IsNullOrWhiteSpace(searchQuery)) { await ReplyAsync("Please provide search terms."); return; } //Join the voice channel if not already in it if (!_lavaNode.HasPlayer(Context.Guild)) { await JoinAsync(); // Check if properly joined if (!_lavaNode.HasPlayer(Context.Guild)) { return; } } var searchResponse = await _lavaNode.SearchAsync(Uri.IsWellFormedUriString(searchQuery, UriKind.Absolute)?SearchType.Direct : SearchType.YouTube, searchQuery); if (searchResponse.Status is SearchStatus.LoadFailed or SearchStatus.NoMatches) { await ReplyAsync($"I wasn't able to find anything for `{searchQuery}`."); return; } var player = _lavaNode.GetPlayer(Context.Guild); if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name)) { player.Queue.Enqueue(searchResponse.Tracks); await ReplyAsync($"Enqueued {searchResponse.Tracks.Count} songs."); } else { var track = searchResponse.Tracks.FirstOrDefault(); player.Queue.Enqueue(track); await ReplyAsync($"Enqueued {track?.Title}"); await _audioService.LogMusicToDB(track, Context); } if (player.PlayerState is PlayerState.Playing or PlayerState.Paused) { return; } player.Queue.TryDequeue(out var lavaTrack); await player.PlayAsync(x => { x.Track = lavaTrack; x.ShouldPause = false; }); }