예제 #1
0
파일: Music.cs 프로젝트: Aryan10/Bot
        public async Task QueueSong(IGuildUser queuer, ITextChannel textCh, IVoiceChannel voiceCh, string query, bool silent = false, MusicType musicType = MusicType.Normal)
        {
            if (voiceCh == null || voiceCh.Guild != textCh.Guild)
            {
                if (!silent)
                {
                    await textCh.SendErrorAsync(GetText("must_be_in_voice")).ConfigureAwait(false);
                }
                throw new ArgumentNullException(nameof(voiceCh));
            }
            if (string.IsNullOrWhiteSpace(query) || query.Length < 3)
            {
                throw new ArgumentException("Invalid song query.", nameof(query));
            }

            var musicPlayer = MusicPlayers.GetOrAdd(textCh.Guild.Id, server =>
            {
                float vol;// SpecificConfigurations.Default.Of(server.Id).DefaultMusicVolume;
                using (var uow = DbHandler.UnitOfWork())
                {
                    vol = uow.GuildConfigs.For(textCh.Guild.Id, set => set).DefaultMusicVolume;
                }
                var mp = new MusicPlayer(voiceCh, textCh, vol);
                IUserMessage playingMessage      = null;
                IUserMessage lastFinishedMessage = null;
                mp.OnCompleted += async(s, song) =>
                {
                    try
                    {
                        lastFinishedMessage?.DeleteAfter(0);

                        try
                        {
                            lastFinishedMessage = await mp.OutputTextChannel.EmbedAsync(new EmbedBuilder().WithOkColor()
                                                                                        .WithAuthor(eab => eab.WithName(GetText("finished_song")).WithMusicIcon())
                                                                                        .WithDescription(song.PrettyName)
                                                                                        .WithFooter(ef => ef.WithText(song.PrettyInfo)))
                                                  .ConfigureAwait(false);
                        }
                        catch
                        {
                            // ignored
                        }

                        if (mp.Autoplay && mp.Playlist.Count == 0 && song.SongInfo.ProviderType == MusicType.Normal)
                        {
                            var relatedVideos = (await NadekoBot.Google.GetRelatedVideosAsync(song.SongInfo.Query, 4)).ToList();
                            if (relatedVideos.Count > 0)
                            {
                                await QueueSong(await queuer.Guild.GetCurrentUserAsync(),
                                                textCh,
                                                voiceCh,
                                                relatedVideos[new NadekoRandom().Next(0, relatedVideos.Count)],
                                                true).ConfigureAwait(false);
                            }
                        }
                    }
                    catch
                    {
                        // ignored
                    }
                };

                mp.OnStarted += async(player, song) =>
                {
                    try { await mp.UpdateSongDurationsAsync().ConfigureAwait(false); }
                    catch
                    {
                        // ignored
                    }
                    var sender = player;
                    if (sender == null)
                    {
                        return;
                    }
                    try
                    {
                        playingMessage?.DeleteAfter(0);

                        playingMessage = await mp.OutputTextChannel.EmbedAsync(new EmbedBuilder().WithOkColor()
                                                                               .WithAuthor(eab => eab.WithName(GetText("playing_song")).WithMusicIcon())
                                                                               .WithDescription(song.PrettyName)
                                                                               .WithFooter(ef => ef.WithText(song.PrettyInfo)))
                                         .ConfigureAwait(false);
                    }
                    catch
                    {
                        // ignored
                    }
                };
                mp.OnPauseChanged += async(paused) =>
                {
                    try
                    {
                        IUserMessage msg;
                        if (paused)
                        {
                            msg = await mp.OutputTextChannel.SendConfirmAsync(GetText("paused")).ConfigureAwait(false);
                        }
                        else
                        {
                            msg = await mp.OutputTextChannel.SendConfirmAsync(GetText("resumed")).ConfigureAwait(false);
                        }

                        msg?.DeleteAfter(10);
                    }
                    catch
                    {
                        // ignored
                    }
                };

                mp.SongRemoved += async(song, index) =>
                {
                    try
                    {
                        var embed = new EmbedBuilder()
                                    .WithAuthor(eab => eab.WithName(GetText("removed_song") + " #" + (index + 1)).WithMusicIcon())
                                    .WithDescription(song.PrettyName)
                                    .WithFooter(ef => ef.WithText(song.PrettyInfo))
                                    .WithErrorColor();

                        await mp.OutputTextChannel.EmbedAsync(embed).ConfigureAwait(false);
                    }
                    catch
                    {
                        // ignored
                    }
                };
                return(mp);
            });
            Song resolvedSong;

            try
            {
                musicPlayer.ThrowIfQueueFull();
                resolvedSong = await SongHandler.ResolveSong(query, musicType).ConfigureAwait(false);

                if (resolvedSong == null)
                {
                    throw new SongNotFoundException();
                }

                musicPlayer.AddSong(resolvedSong, queuer.Username);
            }
            catch (PlaylistFullException)
            {
                try
                {
                    await textCh.SendConfirmAsync(GetText("queue_full", musicPlayer.MaxQueueSize));
                }
                catch
                {
                    // ignored
                }
                throw;
            }
            if (!silent)
            {
                try
                {
                    //var queuedMessage = await textCh.SendConfirmAsync($"🎵 Queued **{resolvedSong.SongInfo.Title}** at `#{musicPlayer.Playlist.Count + 1}`").ConfigureAwait(false);
                    var queuedMessage = await textCh.EmbedAsync(new EmbedBuilder().WithOkColor()
                                                                .WithAuthor(eab => eab.WithName(GetText("queued_song") + " #" + (musicPlayer.Playlist.Count + 1)).WithMusicIcon())
                                                                .WithDescription($"{resolvedSong.PrettyName}\n{GetText("queue")} ")
                                                                .WithThumbnailUrl(resolvedSong.Thumbnail)
                                                                .WithFooter(ef => ef.WithText(resolvedSong.PrettyProvider)))
                                        .ConfigureAwait(false);

                    queuedMessage?.DeleteAfter(10);
                }
                catch
                {
                    // ignored
                } // if queued message sending fails, don't attempt to delete it
            }
        }
예제 #2
0
            private async Task PotentialAcro(SocketMessage arg)
            {
                try
                {
                    var msg = arg as SocketUserMessage;
                    if (msg == null || msg.Author.IsBot || msg.Channel.Id != _channel.Id)
                    {
                        return;
                    }

                    ++_spamCount;

                    var guildUser = (IGuildUser)msg.Author;

                    var input = msg.Content.ToUpperInvariant().Trim();

                    if (phase == AcroPhase.Submitting)
                    {
                        if (_spamCount > 10)
                        {
                            _spamCount = 0;
                            try { await _channel.EmbedAsync(GetEmbed()).ConfigureAwait(false); }
                            catch { }
                        }
                        var inputWords = input.Split(' ');                //get all words

                        if (inputWords.Length != _startingLetters.Length) // number of words must be the same as the number of the starting letters
                        {
                            return;
                        }

                        for (int i = 0; i < _startingLetters.Length; i++)
                        {
                            var letter = _startingLetters[i];

                            if (!inputWords[i].StartsWith(letter.ToString())) // all first letters must match
                            {
                                return;
                            }
                        }


                        if (!_usersWhoSubmitted.Add(guildUser.Id))
                        {
                            return;
                        }
                        //try adding it to the list of answers
                        if (!_submissions.TryAdd(input, guildUser))
                        {
                            _usersWhoSubmitted.TryRemove(guildUser.Id);
                            return;
                        }

                        // all good. valid input. answer recorded
                        await _channel.SendConfirmAsync(GetText("acrophobia"),
                                                        GetText("acro_submit", guildUser.Mention,
                                                                _submissions.Count));

                        try
                        {
                            await msg.DeleteAsync();
                        }
                        catch
                        {
                            await msg.DeleteAsync(); //try twice
                        }
                    }
                    else if (phase == AcroPhase.Voting)
                    {
                        if (_spamCount > 10)
                        {
                            _spamCount = 0;
                            try { await _channel.EmbedAsync(GetEmbed()).ConfigureAwait(false); }
                            catch { }
                        }

                        //if (submissions.TryGetValue(input, out usr) && usr.Id != guildUser.Id)
                        //{
                        //    if (!usersWhoVoted.Add(guildUser.Id))
                        //        return;
                        //    votes.AddOrUpdate(input, 1, (key, old) => ++old);
                        //    await channel.SendConfirmAsync("Acrophobia", $"{guildUser.Mention} cast their vote!").ConfigureAwait(false);
                        //    await msg.DeleteAsync().ConfigureAwait(false);
                        //    return;
                        //}

                        int num;
                        if (int.TryParse(input, out num) && num > 0 && num <= _submissions.Count)
                        {
                            var kvp = _submissions.Skip(num - 1).First();
                            var usr = kvp.Value;
                            //can't vote for yourself, can't vote multiple times
                            if (usr.Id == guildUser.Id || !_usersWhoVoted.Add(guildUser.Id))
                            {
                                return;
                            }
                            _votes.AddOrUpdate(kvp.Key, 1, (key, old) => ++ old);
                            await _channel.SendConfirmAsync(GetText("acrophobia"),
                                                            GetText("acro_vote_cast", Format.Bold(guildUser.ToString()))).ConfigureAwait(false);

                            await msg.DeleteAsync().ConfigureAwait(false);
                        }
                    }
                }
                catch (Exception ex)
                {
                    _log.Warn(ex);
                }
            }
예제 #3
0
        public static async Task QueueSong(IGuildUser queuer, ITextChannel textCh, IVoiceChannel voiceCh, string query, bool silent = false, MusicType musicType = MusicType.Normal)
        {
            if (voiceCh == null || voiceCh.Guild != textCh.Guild)
            {
                if (!silent)
                {
                    await textCh.SendErrorAsync("💢 You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining.").ConfigureAwait(false);
                }
                throw new ArgumentNullException(nameof(voiceCh));
            }
            if (string.IsNullOrWhiteSpace(query) || query.Length < 3)
            {
                throw new ArgumentException("💢 Invalid query for queue song.", nameof(query));
            }

            var musicPlayer = MusicPlayers.GetOrAdd(textCh.Guild.Id, server =>
            {
                float vol = 1;// SpecificConfigurations.Default.Of(server.Id).DefaultMusicVolume;
                using (var uow = DbHandler.UnitOfWork())
                {
                    vol = uow.GuildConfigs.For(textCh.Guild.Id, set => set).DefaultMusicVolume;
                }
                var mp = new MusicPlayer(voiceCh, vol);
                IUserMessage playingMessage      = null;
                IUserMessage lastFinishedMessage = null;
                mp.OnCompleted += async(s, song) =>
                {
                    if (song.PrintStatusMessage)
                    {
                        try
                        {
                            if (lastFinishedMessage != null)
                            {
                                await lastFinishedMessage.DeleteAsync().ConfigureAwait(false);
                            }
                            if (playingMessage != null)
                            {
                                await playingMessage.DeleteAsync().ConfigureAwait(false);
                            }
                            try { lastFinishedMessage = await textCh.SendConfirmAsync($"🎵 Finished {song.PrettyName}").ConfigureAwait(false); } catch { }
                            if (mp.Autoplay && mp.Playlist.Count == 0 && song.SongInfo.Provider == "YouTube")
                            {
                                await QueueSong(queuer.Guild.GetCurrentUser(), textCh, voiceCh, (await NadekoBot.Google.GetRelatedVideosAsync(song.SongInfo.Query, 4)).ToList().Shuffle().FirstOrDefault(), silent, musicType).ConfigureAwait(false);
                            }
                        }
                        catch { }
                    }
                };
                mp.OnStarted += async(s, song) =>
                {
                    if (song.PrintStatusMessage)
                    {
                        var sender = s as MusicPlayer;
                        if (sender == null)
                        {
                            return;
                        }

                        var msgTxt = $"🎵 Playing {song.PrettyName}\t `Vol: {(int)(sender.Volume * 100)}%`";
                        try { playingMessage = await textCh.SendConfirmAsync(msgTxt).ConfigureAwait(false); } catch { }
                    }
                };
                mp.OnPauseChanged += async(paused) =>
                {
                    try
                    {
                        if (paused)
                        {
                            await textCh.SendConfirmAsync("🎵 Music playback **paused**.").ConfigureAwait(false);
                        }
                        else
                        {
                            await textCh.SendConfirmAsync("🎵 Music playback **resumed**.").ConfigureAwait(false);
                        }
                    }
                    catch { }
                };
                return(mp);
            });
            Song resolvedSong;

            try
            {
                musicPlayer.ThrowIfQueueFull();
                resolvedSong = await Song.ResolveSong(query, musicType).ConfigureAwait(false);

                if (resolvedSong == null)
                {
                    throw new SongNotFoundException();
                }

                musicPlayer.AddSong(resolvedSong, queuer.Username);
            }
            catch (PlaylistFullException)
            {
                try { await textCh.SendConfirmAsync($"🎵 Queue is full at **{musicPlayer.MaxQueueSize}/{musicPlayer.MaxQueueSize}**. "); } catch { }
                throw;
            }
            if (!silent)
            {
                try
                {
                    var queuedMessage = await textCh.SendConfirmAsync($"🎵 Queued **{resolvedSong.SongInfo.Title.TrimTo(55)}** at `#{musicPlayer.Playlist.Count + 1}`").ConfigureAwait(false);

                    var t = Task.Run(async() =>
                    {
                        try
                        {
                            await Task.Delay(10000).ConfigureAwait(false);

                            await queuedMessage.DeleteAsync().ConfigureAwait(false);
                        }
                        catch { }
                    }).ConfigureAwait(false);
                }
                catch { } // if queued message sending fails, don't attempt to delete it
            }
        }