Example #1
0
        public async Task NowPlaying(CommandContext ctx)
        {
            if (ctx.Member.VoiceState == null || ctx.Member.VoiceState.Channel == null)
            {
                await ctx.RespondAsync("You are not in a vc.");

                return;
            }
            LavalinkNodeConnection  node = ctx.Client.GetLavalink().ConnectedNodes.Values.First();
            LavalinkGuildConnection conn = node.GetGuildConnection(ctx.Member.VoiceState.Guild);

            if (conn == null)
            {
                await ctx.RespondAsync("Lavalink not connected");

                return;
            }
            if (conn.CurrentState.CurrentTrack == null)
            {
                await ctx.RespondAsync("Nothing playing");

                return;
            }
            DiscordEmbedBuilder builder = new DiscordEmbedBuilder
            {
                Title       = "Playing: ",
                Description = "Showing currently playing song",
                Color       = DiscordColor.Red,
                Footer      = new DiscordEmbedBuilder.EmbedFooter
                {
                    Text = $"Repeat: {LavalinkService.Instance.Repeats[ctx.Guild]}"
                }
            };

            builder.AddField($"1: Channel: {conn.CurrentState.CurrentTrack.Author}",
                             $"[{conn.CurrentState.CurrentTrack.Title}]({conn.CurrentState.CurrentTrack.Uri}) - {conn.CurrentState.CurrentTrack.Length}");
            await ctx.RespondAsync(builder.Build());

            return;
        }
Example #2
0
        public async Task PlayNextSongIfExists(CommandContext ctx, LavalinkNodeConnection lavalinkNodeConnection, LavalinkGuildConnection lavalinkGuildConnection, Uri uri)
        {
            Messaging messaging = new Messaging(ctx);

            if (queues[ctx.Guild.Id].Count > 0)
            {
                LavalinkTrack track = (LavalinkTrack)queues[ctx.Guild.Id].Dequeue();
                await lavalinkGuildConnection.PlayAsync(track);

                await messaging.RespondContent(false, track.Length)($"🎤 {track.Author} - {track.Title}");

                if (loops[ctx.Guild.Id] && uri != null)
                {
                    LavalinkTrack newTrack = lavalinkNodeConnection.Rest.GetTracksAsync(uri).GetAwaiter().GetResult().Tracks.First();
                    queues[ctx.Guild.Id].Enqueue(newTrack);
                }
            }
            else
            {
                await messaging.RespondContent()("Queue has finished.");
            }
        }
Example #3
0
        public async Task RepeatMode(CommandContext ctx, [RemainingText][Description("Repeatmode (\"single\", \"all\" or \"off\")")] string mode)
        {
            if (ctx.Member.VoiceState == null || ctx.Member.VoiceState.Channel == null)
            {
                await ctx.RespondAsync("You are not in a vc.");

                return;
            }
            LavalinkNodeConnection  node = ctx.Client.GetLavalink().ConnectedNodes.Values.First();
            LavalinkGuildConnection conn = node.GetGuildConnection(ctx.Member.VoiceState.Guild);

            if (conn == null)
            {
                await ctx.RespondAsync("Lavalink not connected");

                return;
            }
            if (conn.CurrentState.CurrentTrack == null)
            {
                await ctx.RespondAsync("Nothing playing");

                return;
            }
            await ctx.TriggerTypingAsync();

            var repeatMode = mode switch
            {
                string a when a.ToLower().Contains("all") => Repeaters.all,
                string b when b.ToLower().Contains("single") => Repeaters.single,
                string b when b.ToLower().Contains("off") => Repeaters.off,
                _ => Repeaters.all,
            };

            LavalinkService.Instance.Repeats?.Remove(ctx.Guild);
            LavalinkService.Instance.Repeats.Add(ctx.Guild, repeatMode);

            await ctx.RespondAsync($"Repeatmode set to: {LavalinkService.Instance.Repeats[ctx.Guild]}");
        }
Example #4
0
        private Task Ready(DiscordClient client, ReadyEventArgs e)
        {
            this._lavalinkNodeConnection = this._lavalinkExtension?.ConnectedNodes?.FirstOrDefault().Value;

            return(Task.CompletedTask);
        }
Example #5
0
        public async Task RunAsync()
        {
            ReadConfig.Read();
            var  varrepo = new VariableRepository(ReadConfig.Config.ConnectionString);
            bool result;

#if DEBUG
            result = varrepo.Read(3, out Variable prefix);             //get testPrefix if in designmode
#else
            result = varrepo.Read(2, out Variable prefix);             //otherwise get default prefix
#endif
            DiscordConfiguration config = new DiscordConfiguration
            {
                Token         = ReadConfig.Config.Token,
                TokenType     = TokenType.Bot,
                AutoReconnect = true,
#if DEBUG
                MinimumLogLevel = Microsoft.Extensions.Logging.LogLevel.Debug,
#endif
                Intents = DiscordIntents.All
            };

            Client = new DiscordClient(config);

            //Register client events
            Client.Ready += Events.OnClientReady;
            Client.GuildDownloadCompleted      += Events.Client_GuildDownloadCompleted;
            Client.MessageCreated              += Events.MessageCreated;
            Client.MessageUpdated              += Events.MessageUpdated;
            Client.MessageDeleted              += Events.MessageDeleted;
            Client.GuildMemberAdded            += Events.MemberAdded;
            Client.MessageReactionAdded        += Events.ReactionAdded;
            Client.MessageReactionRemoved      += Events.ReactionRemoved;
            Client.VoiceStateUpdated           += Events.VoiceStateUpdated;
            Client.ClientErrored               += Events.ClientErrored;
            Client.ComponentInteractionCreated += Events.ComponentTriggered;

            //Register client events for logging
            Client.GuildBanAdded       += Logger.BanAdded;
            Client.GuildBanRemoved     += Logger.BanRemoved;
            Client.GuildMemberUpdated  += Logger.MemberUpdated;
            Client.ChannelUpdated      += Logger.ChannelUpdated;
            Client.GuildRoleUpdated    += Logger.RoleUpdated;
            Client.MessageUpdated      += Logger.MessageEdited;
            Client.MessageDeleted      += Logger.MessageDeleted;
            Client.MessagesBulkDeleted += Logger.BulkMessagesDeleted;
            //Client.GuildEmojisUpdated += Logger.EmojiUpdated;
            Client.VoiceStateUpdated += Logger.VoiceUpdate;


            //Register timer events
            SystemService.Instance.WarnTimer.Elapsed += Events.TimerTick;

            //Register Logger events
            SystemService.Instance.Logger.RaiseLogEvent += Events.OnLog;

            Client.UseInteractivity(new InteractivityConfiguration
            {
                Timeout              = TimeSpan.FromMinutes(5),
                PollBehaviour        = PollBehaviour.KeepEmojis,
                AckPaginationButtons = true
            });

            CommandsNextConfiguration commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes      = new string[] { prefix.Value },
                EnableMentionPrefix = true
            };
            Commands = Client.UseCommandsNext(commandsConfig);

            //Register commands
            Commands.RegisterCommands <AuditCommands>();
            Commands.RegisterCommands <EmbedCommands>();
            Commands.RegisterCommands <InfoCommands>();
            Commands.RegisterCommands <LavalinkCommands>();
            Commands.RegisterCommands <ReactionCommands>();
            Commands.RegisterCommands <RuleCommands>();
            Commands.RegisterCommands <TechnicalCommands>();
            Commands.RegisterCommands <WarnCommands>();
            Commands.RegisterCommands <EventCommands>();

            //Register command events
            Commands.CommandErrored += Events.CommandErrored;

            SlashCommands = Client.UseSlashCommands();

            //Register interactions
            SlashCommands.RegisterCommands <WarnInteractions>(699555747591094344);

            //Register interaction events
            SlashCommands.ContextMenuErrored += Events.ContextMenuErrored;

            await Client.ConnectAsync();

            LavalinkNodeConnection lavaNode = null;
            lavaNode = await ConnectLavaNodeAsync();

            if (lavaNode != null)
            {
                //Register lava commands
                lavaNode.PlaybackFinished += Events.PlaybackFinished;
            }

            await Task.Delay(-1);
        }
Example #6
0
 public Emzi0767.Utilities.AsyncEventHandler <LavalinkGuildConnection, TrackFinishEventArgs> PlayNextSong(CommandContext ctx, LavalinkNodeConnection lavalinkNodeConnection, LavalinkGuildConnection lavalinkGuildConnection)
 {
     return(async(LavalinkGuildConnection g, TrackFinishEventArgs e) =>
     {
         await PlayNextSongIfExists(ctx, lavalinkNodeConnection, lavalinkGuildConnection, e.Track.Uri);
     });
 }
Example #7
0
        public async Task SkipSong(CommandContext ctx, LavalinkNodeConnection lavalinkNodeConnection, LavalinkGuildConnection lavalinkGuildConnection)
        {
            await lavalinkGuildConnection.StopAsync();

            await PlayNextSongIfExists(ctx, lavalinkNodeConnection, lavalinkGuildConnection, null);
        }
Example #8
0
        public async Task EnqueueTrack(CommandContext ctx, [RemainingText] string input)
        {
            _Cmdctx = ctx;

            if (ctx.Member?.VoiceState?.Channel == null)
            {
                await ctx.RespondAsync("You must be connected to a voice channel to use this command.");

                return;
            }

            var lavaconfig = new LavalinkConfiguration
            {
                Password = ""
            };

            if (_LavalinkNode == null || !_LavalinkNode.IsConnected)
            {
                _LavalinkNode = await _Lavalink.ConnectAsync(lavaconfig);
            }

            if ((_LavalinkGuild == null || !_LavalinkGuild.IsConnected))
            {
                _LavalinkGuild = await _LavalinkNode.ConnectAsync(ctx.Member.VoiceState.Channel);

                _LavalinkGuild.PlaybackFinished += PlayTrack;
            }

            var tracks = new LavalinkLoadResult();

            Uri uri;

            if (Uri.TryCreate(input, UriKind.Absolute, out uri))
            {
                tracks = await _LavalinkNode.GetTracksAsync(uri);
            }
            else
            {
                tracks = await _LavalinkNode.GetTracksAsync(input);
            }

            switch (tracks.LoadResultType)
            {
            case LavalinkLoadResultType.SearchResult:

            case LavalinkLoadResultType.TrackLoaded:
                _Playlist.Enqueue(tracks.Tracks.First());
                await ctx.RespondAsync($"**[Enqueued]** {tracks.Tracks.First().Title}");

                break;

            case LavalinkLoadResultType.PlaylistLoaded:
                foreach (LavalinkTrack track in tracks.Tracks)
                {
                    _Playlist.Enqueue(track);
                }
                await ctx.RespondAsync($"Playlist Loaded.");

                break;

            case LavalinkLoadResultType.LoadFailed:
                await ctx.RespondAsync($"Track could not be loaded.");

                break;

            case LavalinkLoadResultType.NoMatches:
                await ctx.RespondAsync($"Track Not Found.");

                break;

            default:
                await ctx.RespondAsync($"Error.");

                return;
            }

            if (string.IsNullOrEmpty(_LavalinkGuild.CurrentState.CurrentTrack.Title))
            {
                _LavalinkGuild.Play(_Playlist.Peek());
            }
        }
 internal NodeDisconnectedEventArgs(LavalinkNodeConnection node)
 {
     this.LavalinkNode = node;
 }
Example #10
0
 internal NodeDisconnectedEventArgs(LavalinkNodeConnection node, bool isClean)
 {
     this.LavalinkNode = node;
     this.IsCleanClose = isClean;
 }
Example #11
0
 public InfoCommands(Bot bot, LavalinkService lavalink)
 {
     this.Bot      = bot;
     this.Lavalink = lavalink.LavalinkNode;
 }
Example #12
0
        public static async Task <LavalinkGuildConnection> GetGuildConnection(CommandContext ctx, DiscordChannel channel, LavalinkNodeConnection lavalinkNodeConnection)
        {
            if (channel == null)
            {
                channel = ctx.Member?.VoiceState?.Channel;
            }

            if (channel == null)
            {
                throw new InvalidOperationException("You need to be in a voice channel.");
            }

            if (lavalinkNodeConnection.GetGuildConnection(ctx.Guild) != null)
            {
                throw new InvalidOperationException("I am already connected in this guild.");
            }

            return(await lavalinkNodeConnection.ConnectAsync(channel));
        }
Example #13
0
 private Task Lavalink_Disconnected(LavalinkNodeConnection ll, NodeDisconnectedEventArgs e)
 {
     this.Lavalink      = null;
     this.LavalinkVoice = null;
     return(Task.CompletedTask);
 }
Example #14
0
        public async Task Queue(CommandContext ctx)
        {
            //if (queueTokens.ContainsKey(ctx.Member.Id))
            //         {
            //	queueTokens[ctx.Member.Id].Cancel();
            //	queueTokens.Remove(ctx.Member.Id);
            //         }

            if (ctx.Member.VoiceState == null || ctx.Member.VoiceState.Channel == null)
            {
                await ctx.RespondAsync("You are not in a vc.");

                return;
            }
            LavalinkNodeConnection  node = ctx.Client.GetLavalink().ConnectedNodes.Values.First();
            LavalinkGuildConnection conn = node.GetGuildConnection(ctx.Member.VoiceState.Guild);

            if (conn == null)
            {
                await ctx.RespondAsync("Lavalink not connected");

                return;
            }
            if (conn.CurrentState.CurrentTrack == null)
            {
                await ctx.RespondAsync("Nothing playing");

                return;
            }
            DiscordEmbedBuilder builder = new DiscordEmbedBuilder
            {
                Title       = "Queue: ",
                Description = "Showing all in queue",
                Color       = DiscordColor.Red
            };

            builder.AddField($"1: Channel: {conn.CurrentState.CurrentTrack.Author}",
                             $"[{conn.CurrentState.CurrentTrack.Title}]({conn.CurrentState.CurrentTrack.Uri}) - {conn.CurrentState.CurrentTrack.Length}");
            List <Page> pages   = new List <Page>();
            int         index   = 1;
            int         counter = 1;

            if (!LavalinkService.Instance.Queues.ContainsKey(conn.Guild))
            {
                await ctx.RespondAsync(builder.Build());

                return;
            }
            foreach (LavalinkTrack track in LavalinkService.Instance.Queues[conn.Guild])
            {
                index++;
                counter++;
                builder.AddField($"{index}: Channel: {track.Author}", $"[{track.Title}]({track.Uri}) - {track.Length}");
                if (counter == 10)
                {
                    pages.Add(new Page {
                        Embed = builder.Build()
                    });
                    builder.ClearFields();
                    counter = 0;
                }
                else if (index == LavalinkService.Instance.Queues[conn.Guild].Count + 1)
                {
                    builder.WithFooter($"Repeat: {LavalinkService.Instance.Repeats[ctx.Guild]}");
                    pages.Add(new Page {
                        Embed = builder.Build()
                    });
                }
            }
            _ = ctx.Channel.SendPaginatedMessageAsync(ctx.User, pages, PaginationBehaviour.WrapAround, ButtonPaginationBehavior.DeleteMessage);
        }
Example #15
0
        public async Task Play(CommandContext ctx, [Description("The search request")][RemainingText] string search)
        {
            if (ctx.Member.VoiceState == null || ctx.Member.VoiceState.Channel == null)
            {
                await ctx.RespondAsync("You are not in a VC.");

                return;
            }
            LavalinkNodeConnection node = ctx.Client.GetLavalink().ConnectedNodes.Values.First();
            await node.ConnectAsync(ctx.Member.VoiceState.Channel);

            LavalinkGuildConnection conn = node.GetGuildConnection(ctx.Member.VoiceState.Guild);

            if (conn == null)
            {
                await ctx.RespondAsync("Lavalink not connected.");

                return;
            }
            LavalinkLoadResult loadResult = await node.Rest.GetTracksAsync(search, LavalinkSearchType.Youtube);

            if (loadResult.LoadResultType == LavalinkLoadResultType.LoadFailed ||
                loadResult.LoadResultType == LavalinkLoadResultType.NoMatches)
            {
                await ctx.RespondAsync($"Track search failed for {search}");

                return;
            }
            DiscordEmbedBuilder resultsEmbed = new DiscordEmbedBuilder
            {
                Title       = "I found this for you on Youtube:",
                Description = "Respond with the number you would like to play!",
                Color       = DiscordColor.Red
            };
            int index = 0;

            foreach (LavalinkTrack result in loadResult.Tracks)
            {
                index++;
                resultsEmbed.AddField($"{index}:", $"[{result.Title}]({result.Uri})");
                if (index == 10)
                {
                    break;
                }
            }
            DiscordMessage selectOne = await ctx.RespondAsync(resultsEmbed.Build());

            InteractivityExtension interactivity = ctx.Client.GetInteractivity();
            var selection = await interactivity.WaitForMessageAsync(x => x.Channel == ctx.Channel && x.Author == ctx.User);

            LavalinkTrack track = loadResult.Tracks.ElementAt(int.Parse(selection.Result.Content) - 1);

            if (LavalinkService.Instance.Queues != null && LavalinkService.Instance.Queues.ContainsKey(ctx.Guild))
            {
                LavalinkService.Instance.Queues[ctx.Guild].Add(track);
                DiscordEmbedBuilder embedBuilder = new DiscordEmbedBuilder
                {
                    Title       = "Added to playlist:",
                    Description = $"[{track.Title}]({track.Uri})",
                    Color       = DiscordColor.Red
                };
                await ctx.RespondAsync(embedBuilder.Build());
            }
            else if (conn.CurrentState.CurrentTrack != null)
            {
                if (LavalinkService.Instance.Queues == null)
                {
                    LavalinkService.Instance.Queues  = new Dictionary <DiscordGuild, List <LavalinkTrack> >();
                    LavalinkService.Instance.Repeats = new Dictionary <DiscordGuild, Repeaters>
                    {
                        { ctx.Guild, Repeaters.off }
                    };
                }
                LavalinkService.Instance.Queues.Add(ctx.Guild, new List <LavalinkTrack> {
                    track
                });
                DiscordEmbedBuilder embedBuilder = new DiscordEmbedBuilder
                {
                    Title       = "Added to playlist:",
                    Description = $"[{track.Title}]({track.Uri})",
                    Color       = DiscordColor.Red
                };
                await ctx.RespondAsync(embedBuilder.Build());
            }
            else
            {
                await conn.PlayAsync(track);

                LavalinkService.Instance.Repeats = new Dictionary <DiscordGuild, Repeaters>
                {
                    { ctx.Guild, Repeaters.off }
                };
                DiscordEmbedBuilder embedBuilder = new DiscordEmbedBuilder
                {
                    Title       = "Now playing:",
                    Description = $"[{track.Title}]({track.Uri})",
                    Color       = DiscordColor.Red
                };
                await ctx.RespondAsync(embedBuilder.Build());
            }
            await selectOne.DeleteAsync();

            await selection.Result.DeleteAsync();
        }
Example #16
0
        public async Task Import(CommandContext ctx, [Description("Playlist URL")] Uri playlistURL)
        {
            if (ctx.Member.VoiceState == null || ctx.Member.VoiceState.Channel == null)
            {
                await ctx.RespondAsync("You are not in a vc.");

                return;
            }
            LavalinkNodeConnection node = ctx.Client.GetLavalink().ConnectedNodes.Values.First();
            await node.ConnectAsync(ctx.Member.VoiceState.Channel);

            LavalinkGuildConnection conn = node.GetGuildConnection(ctx.Member.VoiceState.Guild);

            if (conn == null)
            {
                await ctx.RespondAsync("Lavalink not connected.");

                return;
            }
            LavalinkLoadResult loadResult = await conn.GetTracksAsync(playlistURL);

            if (loadResult.LoadResultType == LavalinkLoadResultType.LoadFailed || loadResult.LoadResultType == LavalinkLoadResultType.NoMatches)
            {
                await ctx.RespondAsync($"Playlist search failed for {playlistURL}");

                return;
            }

            foreach (LavalinkTrack track in loadResult.Tracks)
            {
                if (LavalinkService.Instance.Queues != null && LavalinkService.Instance.Queues.ContainsKey(ctx.Guild))
                {
                    LavalinkService.Instance.Queues[ctx.Guild].Add(track);
                }
                else if (conn.CurrentState.CurrentTrack != null)
                {
                    LavalinkService.Instance.Queues = new Dictionary <DiscordGuild, List <LavalinkTrack> >
                    {
                        { ctx.Guild, new List <LavalinkTrack> {
                              track
                          } }
                    };
                    LavalinkService.Instance.Repeats = new Dictionary <DiscordGuild, Repeaters>
                    {
                        { ctx.Guild, Repeaters.off }
                    };
                }
                else
                {
                    await conn.PlayAsync(track);

                    DiscordEmbedBuilder embedBuilder = new DiscordEmbedBuilder
                    {
                        Title       = "Now playing:",
                        Description = $"[{track.Title}]({track.Uri})",
                        Color       = DiscordColor.Red
                    };
                    await ctx.RespondAsync(embedBuilder.Build());

                    await Task.Delay(1000);
                }
            }
            await ctx.RespondAsync("Done (i think).");
        }