Ejemplo n.º 1
0
        private static async Task HandleRequest(JukeboxConnection connection, JukeboxRequest request)
        {
            connection.CurrentRequest = request;

            IVoiceState   voiceState = (IVoiceState)request.User;
            YoutubeClient youtube    = new();
            // Try to look up the video's manifest from YouTube
            StreamManifest streamManifest = await youtube.Videos.Streams.GetManifestAsync(request.VideoId);

            if (streamManifest != null)
            {
                // Get a reference to the audio-only stream from YouTube for the specified video
                IStreamInfo streamInfo = streamManifest.GetAudioOnly().WithHighestBitrate();

                if (streamInfo != null)
                {
                    // Ensure that the bot is connected to the requesting user's channel
                    await EnsureConnectedToUsersChannel(connection, voiceState);

                    // Create a new stream object to send audio to the Discord channel
                    using AudioOutStream audioOutStream = connection.AudioClient.CreatePCMStream(AudioApplication.Music);
                    // Start ffmpeg.exe and prepare to start capturing the output
                    using Process ffmpeg = CreateFfmpeg();
                    Task ffmpegOutputTask = ffmpeg.StandardOutput.BaseStream.CopyToAsync(audioOutStream);

                    // Transfer the audio data from YouTube to the ffmpeg input stream
                    await youtube.Videos.Streams.CopyToAsync(streamInfo, ffmpeg.StandardInput.BaseStream);

                    ffmpeg.StandardInput.BaseStream.Close();

                    // Wait until all output has been captured from ffmpeg and sent to Discord
                    ffmpegOutputTask.Wait();

                    // By this point the song has finished playing
                    await connection.AudioClient.SetSpeakingAsync(false);

                    connection.LastActivity   = DateTime.Now;
                    connection.CurrentRequest = null;
                }
            }
        }
Ejemplo n.º 2
0
        public static async Task <string> JoinAsync(IGuild guild, IVoiceState voiceState, ITextChannel channel)
        {
            if (_lavaNode.HasPlayer(guild))
            {
                return("ikiye mi bölüneyim ?");
            }
            if (voiceState.VoiceChannel is null)
            {
                return("bir yere gir babun");
            }

            try
            {
                await _lavaNode.JoinAsync(voiceState.VoiceChannel, channel);

                return($"{voiceState.VoiceChannel.Name} kanalına geldik sa");
            }
            catch (Exception ex)
            {
                return($"HATA\n{ex.Message}");
            }
        }
Ejemplo n.º 3
0
        // Called when the bot joins the channel
        public async Task <Embed> ConnectAsync(IGuild guild, IVoiceState voiceState, ITextChannel textChannel)
        {
            if (_lavaNode.HasPlayer(guild))
            {
                return(await EmbedHandler.CreateErrorEmbed("Music, Join", "I'm already connected to a voice channel!"));
            }

            if (voiceState.VoiceChannel is null)
            {
                return(await EmbedHandler.CreateErrorEmbed("Music, Join", "You must be connected to a voice channel!"));
            }

            try
            {
                await _lavaNode.JoinAsync(voiceState.VoiceChannel, textChannel);

                return(await EmbedHandler.CreateBasicEmbed("Music, Join", $"Joined {voiceState.VoiceChannel.Name}.", Color.Green));
            }
            catch (Exception ex)
            {
                return(await EmbedHandler.CreateErrorEmbed("Music, Join", ex.Message));
            }
        }
Ejemplo n.º 4
0
        private async void CleanUpBeforeNext(Stream stream, ulong id, IVoiceState state)
        {
            await stream.FlushAsync();

            var guild = Program.GetGuild(id);

            guild.IsPlaying      = false;
            guild.CurrentPlaying = null;
            _cancelToken.Dispose();
            var songs = Program.GetGuild(id).Songs;

            if (songs.Count > 0)
            {
                await PlayNext(id, state);

                return;
            }
            else
            {
                Program.SetGame("cute music!");
                await guild.LeaveAudio(Program.Client.Guilds.First(x => x.Id == id) as IGuild);
            }
        }
Ejemplo n.º 5
0
            private Task _client_UserVoiceStateUpdated(IUser iusr, IVoiceState before, IVoiceState after)
            {
                var usr = iusr as IGuildUser;

                if (usr == null)
                {
                    return(Task.CompletedTask);
                }

                var beforeVch = before.VoiceChannel;
                var afterVch  = after.VoiceChannel;

                if (beforeVch == afterVch)
                {
                    return(Task.CompletedTask);
                }

                LogSetting logSetting;

                if (!GuildLogSettings.TryGetValue(usr.Guild.Id, out logSetting) ||
                    !logSetting.LogVoicePresence)
                {
                    return(Task.CompletedTask);
                }

                ITextChannel logChannel;

                if ((logChannel = TryGetLogChannel(usr.Guild, logSetting, LogChannelType.Voice)) == null)
                {
                    return(Task.CompletedTask);
                }

                string str = null;

                if (beforeVch?.Guild == afterVch?.Guild)
                {
                    str = $"🎙`{prettyCurrentTime}`👤__**{usr.Username}#{usr.Discriminator}**__ moved from **{beforeVch.Name}** to **{afterVch.Name}** voice channel.";
                }
                else if (beforeVch == null)
                {
                    str = $"🎙`{prettyCurrentTime}`👤__**{usr.Username}#{usr.Discriminator}**__ has joined **{afterVch.Name}** voice channel.";
                }
                else if (afterVch == null)
                {
                    str = $"🎙`{prettyCurrentTime}`👤__**{usr.Username}#{usr.Discriminator}**__ has left **{beforeVch.Name}** voice channel.";
                }
                if (str != null)
                {
                    UserPresenceUpdates.AddOrUpdate(logChannel, new List <string>()
                    {
                        str
                    }, (id, list) => { list.Add(str); return(list); });
                }

                return(Task.CompletedTask);
            }
Ejemplo n.º 6
0
            private Task UserUpdatedEventHandler(IUser iuser, IVoiceState before, IVoiceState after)
            {
                var user  = (iuser as IGuildUser);
                var guild = user?.Guild;

                if (guild == null)
                {
                    return(Task.CompletedTask);
                }
                var task = Task.Run(async() =>
                {
                    var botUserPerms = guild.GetCurrentUser().GuildPermissions;
                    try
                    {
                        if (before.VoiceChannel == after.VoiceChannel)
                        {
                            return;
                        }

                        if (!voicePlusTextCache.Contains(guild.Id))
                        {
                            return;
                        }

                        if (!botUserPerms.ManageChannels || !botUserPerms.ManageRoles)
                        {
                            try
                            {
                                await(await guild.GetOwnerAsync()).SendMessageAsync(
                                    "I don't have manage server and/or Manage Channels permission," +
                                    $" so I cannot run voice+text on **{guild.Name}** server.").ConfigureAwait(false);
                            }
                            catch { }
                            using (var uow = DbHandler.UnitOfWork())
                            {
                                uow.GuildConfigs.For(guild.Id).VoicePlusTextEnabled = false;
                                voicePlusTextCache.TryRemove(guild.Id);
                                await uow.CompleteAsync().ConfigureAwait(false);
                            }
                            return;
                        }


                        var beforeVch = before.VoiceChannel;
                        if (beforeVch != null)
                        {
                            var textChannel = guild.GetTextChannels().Where(t => t.Name == GetChannelName(beforeVch.Name)).FirstOrDefault();
                            if (textChannel != null)
                            {
                                await textChannel.AddPermissionOverwriteAsync(user,
                                                                              new OverwritePermissions(readMessages: PermValue.Deny,
                                                                                                       sendMessages: PermValue.Deny)).ConfigureAwait(false);
                            }
                        }
                        var afterVch = after.VoiceChannel;
                        if (afterVch != null && guild.AFKChannelId != afterVch.Id)
                        {
                            var textChannel = guild.GetTextChannels()
                                              .Where(t => t.Name == GetChannelName(afterVch.Name))
                                              .FirstOrDefault();
                            if (textChannel == null)
                            {
                                textChannel = (await guild.CreateTextChannelAsync(GetChannelName(afterVch.Name)).ConfigureAwait(false));
                                await textChannel.AddPermissionOverwriteAsync(guild.EveryoneRole,
                                                                              new OverwritePermissions(readMessages: PermValue.Deny,
                                                                                                       sendMessages: PermValue.Deny)).ConfigureAwait(false);
                            }
                            await textChannel.AddPermissionOverwriteAsync(user,
                                                                          new OverwritePermissions(readMessages: PermValue.Allow,
                                                                                                   sendMessages: PermValue.Allow)).ConfigureAwait(false);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                });

                return(Task.CompletedTask);
            }
Ejemplo n.º 7
0
        private async Task PlayNext(ulong id, IVoiceState state)
        {
            var guild = Program.GetGuild(id);
            var songs = guild.Songs;

            if (guild.IsPlaying || songs.Count == 0)
            {
                return;
            }
            //guild.Save();
            guild.IsPlaying = true;
            var video = songs.Dequeue();

            Program.GetGuild(id).UsersVoteSkipped.Clear();

            await guild.JoinAudio(Program.Client.GetGuild(id), state.VoiceChannel);

            _cancelToken = new CancellationTokenSource();
            _cancelToken.Token.ThrowIfCancellationRequested();

            guild.CurrentPlaying = video;
            Program.SetGame(video.Video.Title);

            var youtube   = new YoutubeClient();
            var streamObj = await youtube.GetVideoMediaStreamInfosAsync(video.Video.Id);

            var            streamurl  = streamObj.Audio.First().Url;
            AudioOutStream lastStream = null;

            if (guild.AudioChannel != null)
            {
                try
                {
                    var embed = Embeds.GetNowPlaying(video, guild, true);
                    await guild.MessageChannel.SendMessageAsync(string.Empty, embed : embed);

                    using (var ffmpeg = CreateStream(streamurl))
                        using (var stream = guild.AudioChannel.CreatePCMStream(AudioApplication.Music, 48000))
                        {
                            try
                            {
                                lastStream          = stream;
                                guild.SongStartedAt = DateTime.Now;
                                Program.Log($"Now Playing: {video.Video.Title} - {video.Video.Duration.ToString()} - [{video.AuthorUsername}]");
                                await ffmpeg.StandardOutput.BaseStream.CopyToAsync(stream, 81920, _cancelToken.Token);
                            }
                            catch (AggregateException e)
                            {
                            }
                            catch (OperationCanceledException e)
                            {
                            }
                            catch (Exception e)
                            {
                                throw e;
                            }
                            finally
                            {
                                CleanUpBeforeNext(stream, id, state);
                            }
                        }
                }
                catch (YoutubeExplode.Exceptions.VideoUnavailableException e)
                {
                    Program.GetGuild(id).IsPlaying = false;
                    CleanUpBeforeNext(lastStream, id, state);
                    return;
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }
Ejemplo n.º 8
0
        public async Task PlayAsync([Remainder] string searchQuery)
        {
            Language lang = Commands.GetLanguage(Context.Guild.Id);

            if (!_lavaNode.HasPlayer(Context.Guild))
            {
                IVoiceState voiceState = Context.User as IVoiceState;
                if (voiceState?.VoiceChannel == null)
                {
                    EmbedBuilder b = new EmbedBuilder();
                    b.WithTitle(lang.Not_connected);
                    b.WithFooter(lang.Requested_by + Context.User.Username, Commands.GetUserAvatarUrl(Context.User));
                    await ReplyAsync(embed : b.Build());

                    return;
                }

                try
                {
                    await _lavaNode.JoinAsync(voiceState.VoiceChannel, Context.Channel as ITextChannel);

                    EmbedBuilder b = new EmbedBuilder();
                    b.WithTitle(lang.Joined_before + voiceState.VoiceChannel.Name + lang.Joined_after);
                    b.WithFooter(lang.Requested_by + Context.User.Username, Commands.GetUserAvatarUrl(Context.User));
                    await ReplyAsync(embed : b.Build());
                }
                catch (Exception exception)
                {
                    await Exeptionhandle(exception, "join in play").ConfigureAwait(false);

                    throw;
                }
            }
            LavaPlayer player = _lavaNode.GetPlayer(Context.Guild);

            if (player.PlayerState == PlayerState.Paused && string.IsNullOrEmpty(searchQuery))
            {
                try
                {
                    await player.ResumeAsync();
                    await ReplyAsync(lang.Resumed_front + player.Track.Title);

                    return;
                }
                catch (Exception exception)
                {
                    await Exeptionhandle(exception, "resume in play").ConfigureAwait(false);

                    throw;
                }
            }
            else
            {
                if (string.IsNullOrWhiteSpace(searchQuery))
                {
                    await ReplyAsync(lang.No_search_term);

                    return;
                }
            }
            int searchtype = 0;

            Victoria.Responses.Rest.SearchResponse searchResponse = await _lavaNode.SearchAsync(searchQuery);

            if (searchResponse.LoadStatus == LoadStatus.LoadFailed ||
                searchResponse.LoadStatus == LoadStatus.NoMatches)
            {
                searchResponse = await _lavaNode.SearchYouTubeAsync(searchQuery); searchtype = 1;
                if (searchResponse.LoadStatus == LoadStatus.LoadFailed ||
                    searchResponse.LoadStatus == LoadStatus.NoMatches)
                {
                    searchResponse = await _lavaNode.SearchSoundCloudAsync(searchQuery); searchtype = 2;
                    if (searchResponse.LoadStatus == LoadStatus.LoadFailed ||
                        searchResponse.LoadStatus == LoadStatus.NoMatches)
                    {
                        EmbedBuilder eb = new EmbedBuilder();
                        eb.WithTitle(lang.No_results_front + searchQuery + lang.No_results_back);
                        eb.WithFooter(lang.Requested_by + Context.User.Username, Commands.GetUserAvatarUrl(Context.User));
                        await ReplyAsync($"", false, eb.Build());

                        return;
                    }
                }
            }

            if (player.PlayerState == PlayerState.Playing || player.PlayerState == PlayerState.Paused)
            {
                if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name))
                {
                    foreach (LavaTrack track in searchResponse.Tracks)
                    {
                        player.Queue.Enqueue(track);
                    }

                    await ReplyAsync($"Enqueued {searchResponse.Tracks.Count} tracks.");
                }
                else
                {
                    LavaTrack track = searchResponse.Tracks[0];
                    player.Queue.Enqueue(track);
                    await ReplyAsync($"Enqueued: {track.Title}");
                }
            }
            else
            {
                LavaTrack track = searchResponse.Tracks[0];

                if (!string.IsNullOrWhiteSpace(searchResponse.Playlist.Name))
                {
                    for (int i = 0; i < searchResponse.Tracks.Count; i++)
                    {
                        if (i == 0)
                        {
                            await player.PlayAsync(track);

                            EmbedBuilder b = new EmbedBuilder();
                            b.WithTitle($"Now playing: {track.Title}");
                            if (searchtype == 1)
                            {
                                b.AddField("source", "<:youtube:793403957871247360> search");
                            }
                            if (searchtype == 2)
                            {
                                b.AddField("source", "<:soundcloud:793405493204090911> search");
                            }
                            string art = await track.FetchArtworkAsync();

                            b.WithThumbnailUrl(art);
                            b.WithFooter(lang.Requested_by + Context.User.Username, Commands.GetUserAvatarUrl(Context.User));
                            await ReplyAsync(embed : b.Build());
                        }
                        else
                        {
                            if (searchResponse.Tracks[i] == null)
                            {
                                await ReplyAsync(i + " was null");
                            }
                            player.Queue.Enqueue(searchResponse.Tracks[i]);
                        }
                    }

                    await ReplyAsync($"Enqueued {searchResponse.Tracks.Count} tracks.");
                }
                else
                {
                    await player.PlayAsync(track);

                    EmbedBuilder b = new EmbedBuilder();
                    b.WithTitle($"Now playing: {track.Title}");
                    if (searchtype == 1)
                    {
                        b.AddField("source", "<:youtube:793403957871247360> search");
                    }
                    if (searchtype == 2)
                    {
                        b.AddField("source", "<:soundcloud:793405493204090911> search");
                    }
                    string art = await track.FetchArtworkAsync();

                    b.WithThumbnailUrl(art);
                    b.WithFooter(new Language().Requested_by + Context.User.Username, Commands.GetUserAvatarUrl(Context.User));
                    await ReplyAsync(embed : b.Build());
                }
            }
        }
Ejemplo n.º 9
0
        private static async Task EnsureConnectedToUsersChannel(JukeboxConnection connection, IVoiceState voiceState)
        {
            if (connection.CurrentChannelId != voiceState.VoiceChannel.Id)
            {
                await DisconnectFromCurrentChannel(connection);
            }

            if (connection.AudioClient == null)
            {
                connection.AudioClient = await voiceState.VoiceChannel.ConnectAsync();

                connection.CurrentChannelId = voiceState.VoiceChannel.Id;
            }
        }
Ejemplo n.º 10
0
            private Task _client_UserVoiceStateUpdated(IUser iusr, IVoiceState before, IVoiceState after)
            {
                var usr = iusr as IGuildUser;
                if (usr == null)
                    return Task.CompletedTask;

                var beforeVch = before.VoiceChannel;
                var afterVch = after.VoiceChannel;

                if (beforeVch == afterVch)
                    return Task.CompletedTask;

                LogSetting logSetting;
                if (!GuildLogSettings.TryGetValue(usr.Guild.Id, out logSetting)
                    || !logSetting.LogVoicePresence)
                    return Task.CompletedTask;

                ITextChannel logChannel;
                if ((logChannel = TryGetLogChannel(usr.Guild, logSetting, LogChannelType.Voice)) == null)
                    return Task.CompletedTask;

                    string str = null;
                    if (beforeVch?.Guild == afterVch?.Guild)
                    {
                        str = $"🎙`{prettyCurrentTime}`👤__**{usr.Username}#{usr.Discriminator}**__ moved from **{beforeVch.Name}** to **{afterVch.Name}** voice channel.";
                    }
                    else if (beforeVch == null)
                    {
                        str = $"🎙`{prettyCurrentTime}`👤__**{usr.Username}#{usr.Discriminator}**__ has joined **{afterVch.Name}** voice channel.";
                    }
                    else if (afterVch == null)
                    {
                        str = $"🎙`{prettyCurrentTime}`👤__**{usr.Username}#{usr.Discriminator}**__ has left **{beforeVch.Name}** voice channel.";
                    }
                    if(str != null)
                        UserPresenceUpdates.AddOrUpdate(logChannel, new List<string>() { str }, (id, list) => { list.Add(str); return list; });

                return Task.CompletedTask;
            }
Ejemplo n.º 11
0
            private Task UserUpdatedEventHandler(IUser iuser, IVoiceState before, IVoiceState after)
            {
                var user = (iuser as IGuildUser);
                var guild = user?.Guild;

                if (guild == null)
                    return Task.CompletedTask;
                var task = Task.Run(async () =>
                {
                    try
                    {
                        var botUserPerms = guild.GetCurrentUser().GuildPermissions;
                    
                        if (before.VoiceChannel == after.VoiceChannel) return;
                        
                        if (!voicePlusTextCache.Contains(guild.Id))
                            return;

                        if (!botUserPerms.ManageChannels || !botUserPerms.ManageRoles)
                        {
                            try
                            {
                                await (await guild.GetOwnerAsync()).SendMessageAsync(
                                    "⚠️ I don't have **manage server** and/or **manage channels** permission," +
                                    $" so I cannot run `voice+text` on **{guild.Name}** server.").ConfigureAwait(false);
                            }
                            catch { }
                            using (var uow = DbHandler.UnitOfWork())
                            {
                                uow.GuildConfigs.For(guild.Id).VoicePlusTextEnabled = false;
                                voicePlusTextCache.TryRemove(guild.Id);
                                await uow.CompleteAsync().ConfigureAwait(false);
                            }
                            return;
                        }


                        var beforeVch = before.VoiceChannel;
                        if (beforeVch != null)
                        {
                            var textChannel = guild.GetTextChannels().Where(t => t.Name == GetChannelName(beforeVch.Name).ToLowerInvariant()).FirstOrDefault();
                            if (textChannel != null)
                                await textChannel.AddPermissionOverwriteAsync(user,
                                    new OverwritePermissions(readMessages: PermValue.Deny,
                                                       sendMessages: PermValue.Deny)).ConfigureAwait(false);
                        }
                        var afterVch = after.VoiceChannel;
                        if (afterVch != null && guild.AFKChannelId != afterVch.Id)
                        {
                            var textChannel = guild.GetTextChannels()
                                                        .Where(t => t.Name ==  GetChannelName(afterVch.Name).ToLowerInvariant())
                                                        .FirstOrDefault();
                            if (textChannel == null)
                            {
                                textChannel = (await guild.CreateTextChannelAsync(GetChannelName(afterVch.Name).ToLowerInvariant()).ConfigureAwait(false));
                                await textChannel.AddPermissionOverwriteAsync(guild.EveryoneRole,
                                    new OverwritePermissions(readMessages: PermValue.Deny,
                                                       sendMessages: PermValue.Deny)).ConfigureAwait(false);
                            }
                            await textChannel.AddPermissionOverwriteAsync(user,
                                new OverwritePermissions(readMessages: PermValue.Allow,
                                                        sendMessages: PermValue.Allow)).ConfigureAwait(false);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                });
                return Task.CompletedTask;
            }
Ejemplo n.º 12
0
 internal static bool GetMusic(IVoiceState user) => Music.Get(user.VoiceChannel);