private async Task <(RestRole role, RestCategoryChannel category, RestTextChannel text, RestVoiceChannel voice)> CreateGroup(int groupNumber)
        {
            string   name = string.Format(_groupConfig.GroupChannelNameTemplate, groupNumber);
            RestRole role = await Context.Guild.CreateRoleAsync(name,
                                                                GuildPermissions.None,
                                                                _roleColors[(groupNumber - 1) % _roleColors.Count], // groupNumber is 1-indexed
                                                                isMentionable : false,
                                                                isHoisted : true);

            // Create group-category which only 'role' can see and join
            RestCategoryChannel category = await Context.Guild.CreateCategoryChannelAsync(name);

            OverwritePermissions groupPermission = new OverwritePermissions(viewChannel: PermValue.Allow, connect: PermValue.Allow);
            await category.AddPermissionOverwriteAsync(role, groupPermission);

            // The bot needs those permissions as well otherwise it can't delete the channel later on. Alternatively you could add 'role' to the bot.
            await category.AddPermissionOverwriteAsync(Context.Client.CurrentUser, groupPermission);

            OverwritePermissions everyonePermission = new OverwritePermissions(viewChannel: PermValue.Deny, connect: PermValue.Deny);
            await category.AddPermissionOverwriteAsync(Context.Guild.EveryoneRole, everyonePermission);

            // Add one text and one voice channel
            Action <GuildChannelProperties> assignCategoryId = c => c.CategoryId = category.Id;
            RestTextChannel text = await Context.Guild.CreateTextChannelAsync(name, assignCategoryId);

            RestVoiceChannel voice = await Context.Guild.CreateVoiceChannelAsync(name, assignCategoryId);

            return(role, category, text, voice);
        }
Beispiel #2
0
        public async Task CreateVoiceChannelForRole(string channelName)
        {
            RestRole newRole = await Context.Guild.CreateRoleAsync(channelName);

            RestTextChannel textChannel = await Context.Guild.CreateTextChannelAsync(channelName);

            RestVoiceChannel voiceChannel = await Context.Guild.CreateVoiceChannelAsync(channelName);

            Discord.OverwritePermissions newRolePermission = new Discord.OverwritePermissions(
                readMessages: Discord.PermValue.Allow
                );

            Discord.OverwritePermissions everyonePermission = new Discord.OverwritePermissions(
                readMessages: Discord.PermValue.Deny
                );

            await textChannel.AddPermissionOverwriteAsync(Context.Guild.EveryoneRole, everyonePermission);

            await textChannel.AddPermissionOverwriteAsync(newRole, newRolePermission);

            DiscordServer server = DiscordServer.GetServerFromID(Context.Guild.Id);

            server.voiceChannelRoles.Add(new VoiceChannelRole()
            {
                voiceChannelID = voiceChannel.Id,
                textChannelID  = textChannel.Id,
                roleID         = newRole.Id
            });
            server.SaveData();
        }
Beispiel #3
0
        private async Task CreateJDRChannels()
        {
            await Context.Channel.SendMessageAsync("Tentative de création");

            await DeleteOldChannels("lobby", "en attente");

            maintTextChannel = await Context.Guild.CreateTextChannelAsync("Lobby");

            mainVoiceChannel = await Context.Guild.CreateVoiceChannelAsync("Joueurs en attente");
        }
        public static async Task <VoiceChannel> CreateTemporaryChannel(string channelName, TimeSpan lifeTime)
        {
            RestVoiceChannel channel = await Utility.GetServer().CreateVoiceChannelAsync(channelName);

            VoiceChannel newVoice = new VoiceChannel(channel.Id, channelName, allVoiceChannels.Count);

            newVoice.lifeTime = lifeTime;
            AddTemporaryChannel(channel.Id, newVoice);
            return(allVoiceChannels [channel.Id]);
        }
        public static async Task <RestVoiceChannel> CreateAutoVCChannel(SocketGuild guild, string baseName)
        {
            RestVoiceChannel vcChannel =
                await guild.CreateVoiceChannelAsync($"➕ New {baseName} VC");

            ServerAudioVoiceChannel audioVoiceChannel = new ServerAudioVoiceChannel(vcChannel.Id, baseName);

            ServerListsManager.GetServer(guild).AutoVoiceChannels.Add(audioVoiceChannel);
            ServerListsManager.SaveServerList();

            return(vcChannel);
        }
        public async Task MoveToNewRoomAsync(params SocketGuildUser[] users)
        {
            RestVoiceChannel voiceChannel = await Context.Guild.CreateVoiceChannelAsync("Breakout room",
                                                                                        x => x.CategoryId = _session.DatingCategory.Id);

            foreach (var user in users)
            {
                await voiceChannel.AddPermissionOverwriteAsync(user, Overwrites.ConnectVoice);

                await user.ModifyAsync(u => u.Channel = voiceChannel);
            }
        }
Beispiel #7
0
        internal async Task createguild(GiveAway currGiveaway)
        {
            try
            {
                var newguild = await _client.CreateGuildAsync($"{currGiveaway.GiveAwayItem} Giveaway", _client.VoiceRegions.FirstOrDefault(n => n.Name == "US East"));

                GiveawayGuildObj g = new GiveawayGuildObj();
                g.create(newguild);
                currgiveaway = currGiveaway;
                currgiveaway.giveawayguild = g;
                GuildPermissions adminguildperms = new GuildPermissions(true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true);
                GuildPermissions Contestantperms = new GuildPermissions(false, false, false, false, false, false, true, false, true, true, false, false, true, true, true, false, true, true, true, false, false, false, true, false, true, false, false, false, false);

                await newguild.CreateRoleAsync("Admins", adminguildperms, Color.Red, true);

                await newguild.CreateRoleAsync("Contestants", Contestantperms, Color.Blue, false);

                var chanContestants = await newguild.CreateTextChannelAsync("Contestants", x => x.Topic = "talk in here till bans are unleashed >:)");

                var chanInfo = await newguild.CreateTextChannelAsync("Info", x => x.Topic = "Rules and info");

                var chanCount = await newguild.CreateVoiceChannelAsync("Time: xxx");

                chantimer = chanCount;

                EmbedBuilder eb = new EmbedBuilder();
                eb.Title       = "***INFO***";
                eb.Color       = Color.Gold;
                eb.Description = $"Welcome to the giveaway guild! the prize for this giveaway is {currGiveaway.GiveAwayItem}!\n\n **How to play** once the timer reaches 0 everyone with the `Contesters` role will be givin access to the \"ban command, its a FFA to the death! the last player(s) remaining will get the prize! this is a fun interactive competative giveaway where users can decide who wins!";
                eb.Footer      = new EmbedFooterBuilder();

                var username = CommandHandler._client.GetGuild(SwissGuildId).Users.FirstOrDefault(x => x.Id == currgiveaway.GiveAwayUser);
                eb.Footer.Text    = $"Giveaway by {username.ToString()}";
                eb.Footer.IconUrl = _client.GetGuild(Global.SwissGuildId).GetUser(currGiveaway.GiveAwayUser).GetAvatarUrl();
                await chanInfo.SendMessageAsync("", false, eb.Build());

                OverwritePermissions adminperms = new OverwritePermissions(PermValue.Allow, PermValue.Allow, PermValue.Allow, PermValue.Allow, PermValue.Allow, PermValue.Allow, PermValue.Allow, PermValue.Allow, PermValue.Allow, PermValue.Allow, PermValue.Allow, PermValue.Allow, PermValue.Allow, PermValue.Allow, PermValue.Allow, PermValue.Allow, PermValue.Allow, PermValue.Allow, PermValue.Allow, PermValue.Allow);
                await chanInfo.AddPermissionOverwriteAsync(newguild.Roles.FirstOrDefault(r => r.Name == "Admins"), adminperms);

                OverwritePermissions contesterperms = new OverwritePermissions(PermValue.Deny, PermValue.Deny, PermValue.Allow, PermValue.Allow, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Allow, PermValue.Allow, PermValue.Allow, PermValue.Deny, PermValue.Deny, PermValue.Allow, PermValue.Allow, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Allow, PermValue.Deny, PermValue.Deny);
                await chanInfo.AddPermissionOverwriteAsync(newguild.Roles.FirstOrDefault(r => r.Name == "Contestants"), contesterperms);

                var url = chanInfo.CreateInviteAsync(null, null, false, false);
                _client.UserJoined += userjoinGiveaway;
                inviteURL           = url.Result.Url;
            }
            catch (Exception ex)
            {
            }
        }
        private async Task VoiceKickUserAsync(SocketGuildUser user)
        {
            SocketVoiceChannel currentVc = user.VoiceChannel;
            RestVoiceChannel   vcChannel = await ServerData.Server.CreateVoiceChannelAsync("Temporary");

            await user.ModifyAsync(x => x.Channel = vcChannel);

            await vcChannel.DeleteAsync();

            if (user.Nickname != null)
            {
                await ReplyAsync(BotUtils.KamtroText($"{user.Nickname} has been removed from {currentVc.Name}."));
            }
            else
            {
                await ReplyAsync(BotUtils.KamtroText($"{user.Username} has been removed from {currentVc.Name}."));
            }
        }
Beispiel #9
0
        private async Task UserVoiceUpdated(SocketUser arg1, SocketVoiceState arg2, SocketVoiceState arg3)
        {
            if (arg1 is SocketGuildUser user)
            {
                var chnl = user.VoiceChannel;
                if (chnl != null && chnl.Id == config.SetupChannelId)
                {
                    if (chnl.Category is SocketCategoryChannel cat)
                    {
                        if (cat.Channels.Count - 1 >= config.MaxRentedVCs)
                        {
                            await user.ModifyAsync(prop =>
                            {
                                prop.Channel = null;
                            });
                        }
                        else
                        {
                            RestVoiceChannel vc = await chnl.Guild.CreateVoiceChannelAsync(user.Username, prop =>
                            {
                                prop.CategoryId = config.CategoryId;
                            });

                            OverwritePermissions creatorperms = OverwritePermissions.DenyAll(vc);
                            creatorperms = creatorperms.Modify(viewChannel: PermValue.Allow, manageChannel: PermValue.Allow, manageRoles: PermValue.Allow, useVoiceActivation: PermValue.Allow, prioritySpeaker: PermValue.Allow, connect: PermValue.Allow, stream: PermValue.Allow, speak: PermValue.Allow);
                            await vc.AddPermissionOverwriteAsync(user, creatorperms);

                            await user.ModifyAsync(prop =>
                            {
                                prop.Channel = vc;
                            });
                        }
                    }
                }
                if (arg2.VoiceChannel != null && arg2.VoiceChannel.CategoryId == config.CategoryId && arg2.VoiceChannel.Id != config.SetupChannelId && arg2.VoiceChannel.Users.Count == 0)
                {
                    await arg2.VoiceChannel.DeleteAsync();
                }
                if (arg3.VoiceChannel != null && arg3.VoiceChannel.CategoryId == config.CategoryId && arg3.VoiceChannel.Id != config.SetupChannelId && arg3.VoiceChannel.Users.Count == 0)
                {
                    await arg3.VoiceChannel.DeleteAsync();
                }
            }
        }
Beispiel #10
0
        private static async Task AddCategoryWithChannels(SocketGuild guild, IRole memberRole, string categoryName, int position)
        {
            RestCategoryChannel category = await guild.CreateCategoryChannelAsync(categoryName, properties => properties.Position = position);

            await category.AddPermissionOverwriteAsync(guild.EveryoneRole, OverwritePermissions.InheritAll);

            await category.AddPermissionOverwriteAsync(memberRole, OverwritePermissions.InheritAll);

            //Text chat
            RestTextChannel chat = await guild.CreateTextChannelAsync(categoryName.ToLower(), properties => properties.CategoryId = category.Id);

            await chat.SyncPermissionsAsync();

            //Auto VC chat
            RestVoiceChannel autoVcChat = await AutoVCChannelCreator.CreateAutoVCChannel(guild, categoryName);

            await autoVcChat.ModifyAsync(properties => properties.CategoryId = category.Id);

            await autoVcChat.SyncPermissionsAsync();
        }
Beispiel #11
0
        public async Task CreateStatChannels(SocketGuild guild)
        {
            if (GetVChannel(guild.VoiceChannels, "Bot Count") == null)
            {
                int botcount = 0;
                IReadOnlyCollection <SocketGuildUser> users = guild.Users;
                foreach (SocketGuildUser user in users)
                {
                    if (user.IsBot)
                    {
                        botcount++;
                    }
                }
                RestVoiceChannel x = await guild.CreateVoiceChannelAsync("Bot Count: " + botcount);

                await x.ModifyAsync(m => { m.Position = 1; m.UserLimit = 0; });
            }
            if (GetVChannel(guild.VoiceChannels, "User Count") == null)
            {
                int botcount = 0;
                IReadOnlyCollection <SocketGuildUser> users = guild.Users;
                foreach (SocketGuildUser user in users)
                {
                    if (user.IsBot)
                    {
                        botcount++;
                    }
                }
                RestVoiceChannel z = await guild.CreateVoiceChannelAsync("User Count: " + (users.Count - botcount));

                await z.ModifyAsync(m => { m.Position = 2; m.UserLimit = 0; });
            }
            if (GetVChannel(guild.VoiceChannels, "Member Count") == null)
            {
                IReadOnlyCollection <SocketGuildUser> users = guild.Users;
                RestVoiceChannel z = await guild.CreateVoiceChannelAsync("Member Count: " + users.Count);

                await z.ModifyAsync(m => { m.Position = 0; m.UserLimit = 0; });
            }
        }
        public async Task <string> Load(CustomVC vc)
        {
            if (await IsActive(vc))
            {
                return(":x: Custom VC is already loaded.");
            }
            using MySqlConnection connection = MySQL.MySQL.getConnection();
            string query     = $"SELECT ChannelID FROM CustomVCs WHERE UserID={vc.UserID}";
            ulong  channelid = await connection.ExecuteScalarAsync <ulong>(query);

            SocketGuildUser  user  = Constants.IGuilds.Jordan(_client).GetUser(vc.UserID);
            RestVoiceChannel voice = await Constants.IGuilds.Jordan(_client).CreateVoiceChannelAsync($"{user.Username}'s VC",
                                                                                                     x =>
            {
                x.CategoryId = Data.GetChnlId("Voice Booth", MySQL.ChannelType.CategoryChannel);
                if (vc.Slots != 0)
                {
                    x.UserLimit = vc.Slots;
                }
                else
                {
                    x.UserLimit = null;
                }
                x.Bitrate = vc.Bitrate;
            });

            query = $"UPDATE CustomVCs SET ChannelID={voice.Id} WHERE UserID={vc.UserID}";
            await connection.ExecuteAsync(query);

            OverwritePermissions perms = new OverwritePermissions(
                muteMembers: PermValue.Allow,
                deafenMembers: PermValue.Allow,
                moveMembers: PermValue.Allow
                );
            await voice.AddPermissionOverwriteAsync(user, perms);

            return(":white_check_mark: Loaded Custom VC.");
        }
Beispiel #13
0
 public void setChannel(RestVoiceChannel channel)
 {
     _channel = channel;
 }
Beispiel #14
0
        public async Task clear()
        {
            Console.WriteLine(Context.Message.Author.Username);
            if (Context.Message.Author.Username == "hex")
            {
                await Context.Channel.SendMessageAsync(Context.Message.Author.Mention + " Clearing all objects...");

                //iterate through groups and delete everything
                ArrayList groups = (ArrayList)SaveGroup.get();
                int       count  = groups.Count;
                if (count != 0)
                {
                    for (int i = 0; i < count; i++)
                    {
                        Group group = (Group)groups[i];

                        //delete group role
                        IRole role = group.getRole();
                        Console.WriteLine("Role: " + role);
                        //group role can not exist
                        try
                        {
                            await role.DeleteAsync();
                        }
                        catch (Exception e)
                        {
                        }

                        //delete creator role
                        IRole creatorRole = group.getCreatorRole();
                        Console.WriteLine("Creator Role: " + creatorRole);
                        await creatorRole.DeleteAsync();

                        //delete group channel
                        RestVoiceChannel channel = group.getChannel();
                        Console.WriteLine("Channel: " + channel);
                        //channel can not exist
                        try
                        {
                            await channel.DeleteAsync();
                        }
                        catch (Exception e)
                        {
                        }

                        //Store empty group object
                        SaveGroup.store(new ArrayList());
                    }
                    await Context.Channel.SendMessageAsync(Context.Message.Author.Mention + " Cleared succesfully!");
                }
                else
                {
                    await Context.Channel.SendMessageAsync(Context.Message.Author.Mention + " Nothing to clear.");
                }
            }
            else
            {
                //INVALID USER
                await Context.Channel.SendMessageAsync(Context.Message.Author.Mention + " Error: You are not my creator...");
            }
        }
Beispiel #15
0
        private async Task OnReactionAdded(Cacheable <IUserMessage, ulong> cache, ISocketMessageChannel channel, SocketReaction reaction)
        {
            IGuildChannel   guildChannel = channel as IGuildChannel;
            SocketGuild     guild        = guildChannel.Guild as SocketGuild; //GlobalUtils.client.Guilds.FirstOrDefault();
            SocketUser      user         = GlobalUtils.client.GetUser(reaction.UserId);
            SocketGuildUser guser        = guild.GetUser(user.Id);


            if (user.IsBot)
            {
                return;            // Task.CompletedTask;
            }
            // add vote
            Console.WriteLine($"Emoji added: {reaction.Emote.Name}");
            if (pendingGames.ContainsKey(reaction.MessageId) && reaction.Emote.Name == "\u2705")
            {
                pendingGames[reaction.MessageId].votes++;
                if (pendingGames[reaction.MessageId].votes >= voteThreshold || user.Id == 346219993437831182)
                {
                    Console.WriteLine("Adding game: " + pendingGames[reaction.MessageId].game);
                    // add the game now!
                    RestRole gRole = await guild.CreateRoleAsync(pendingGames[reaction.MessageId].game);

                    Console.WriteLine("Game Role: " + gRole.Name);

                    RestTextChannel txtChan = await guild.CreateTextChannelAsync(pendingGames[reaction.MessageId].game, x =>
                    {
                        x.CategoryId = gamesText.Id;
                    });

                    Console.WriteLine("Text Channel: " + txtChan.Name);


                    await txtChan.AddPermissionOverwriteAsync(gRole, permissions);

                    RestVoiceChannel voiceChan = await guild.CreateVoiceChannelAsync(pendingGames[reaction.MessageId].game, x =>
                    {
                        x.CategoryId = gamesVoice.Id;
                    });

                    Console.WriteLine("Voice Channel: " + voiceChan.Name);
                    await voiceChan.AddPermissionOverwriteAsync(gRole, permissions);

                    games.Add(new GameInfo(pendingGames[reaction.MessageId].game, txtChan.Id, voiceChan.Id));

                    // remove poll message, add new game announcement and remove pending game
                    ISocketMessageChannel chan = gameChannel as ISocketMessageChannel;
                    await chan.DeleteMessageAsync(reaction.MessageId);

                    EmbedBuilder embed = new EmbedBuilder();
                    embed.WithTitle("New Game Added");
                    embed.WithDescription($"`{pendingGames[reaction.MessageId].game}`\n");
                    embed.WithColor(GlobalUtils.color);
                    await chan.SendMessageAsync("", false, embed.Build());

                    pendingGames.Remove(reaction.MessageId);

                    UpdateOrAddRoleMessage();
                }
            }
            Console.WriteLine($"Emoji added: {reaction.MessageId} == {roleMessageId} : {reaction.MessageId == roleMessageId}");
            Console.WriteLine("Add Game Role: " + guser.Nickname);
            if (reaction.MessageId == roleMessageId)
            {
                // they reacted to the correct role message
                Console.WriteLine("Add Game Role: " + guser.Nickname);
                for (int i = 0; i < games.Count && i < GlobalUtils.menu_emoji.Count <string>(); i++)
                {
                    if (GlobalUtils.menu_emoji[i] == reaction.Emote.Name)
                    {
                        Console.WriteLine("Emoji Found");
                        var result = from a in guild.Roles
                                     where a.Name == games[i].game
                                     select a;
                        SocketRole role = result.FirstOrDefault();
                        Console.WriteLine("Role: " + role.Name);
                        await guser.AddRoleAsync(role);
                    }
                }
            }
            Console.WriteLine("what?!");
            Save();
        }
Beispiel #16
0
        public async Task UserVoiceStateUpdated(SocketUser user, SocketVoiceState before,
                                                SocketVoiceState after)
        {
            try
            {
                ServerList server = ServerListsManager.GetServer(((SocketGuildUser)user).Guild);

                //If we are adding an auto voice channel
                if (after.VoiceChannel != null)
                {
                    ServerAudioVoiceChannel audioVoiceChannel = server.GetAutoVoiceChannel(after.VoiceChannel.Id);
                    if (audioVoiceChannel.Name != null)
                    {
                        RestVoiceChannel createdChannel =
                            await after.VoiceChannel.Guild.CreateVoiceChannelAsync(
                                $"{audioVoiceChannel.Name} #" + (server.ActiveAutoVoiceChannels.Count + 1), x =>
                        {
                            x.CategoryId = after.VoiceChannel.CategoryId;
                            x.Bitrate    = after.VoiceChannel.Bitrate;
                            x.Position   = after.VoiceChannel.Position + 1;
                        });

                        if (createdChannel.CategoryId != null)
                        {
                            await createdChannel.SyncPermissionsAsync();
                        }

                        //Move the user who created the channel to the new channel
                        await((SocketGuildUser)user).ModifyAsync(x => { x.ChannelId = createdChannel.Id; });

                        server.ActiveAutoVoiceChannels.Add(createdChannel.Id);
                        ServerListsManager.SaveServerList();
                    }
                }

                //If we are removing an auto voice channel
                if (before.VoiceChannel != null)
                {
                    ulong activeChannel = server.GetActiveVoiceChannel(before.VoiceChannel.Id);
                    if (activeChannel != 0)
                    {
                        //There are no user on the active auto voice channel
                        if (before.VoiceChannel.Users.Count == 0)
                        {
                            await before.VoiceChannel.DeleteAsync();

                            server.ActiveAutoVoiceChannels.Remove(before.VoiceChannel.Id);
                            ServerListsManager.SaveServerList();
                        }
                    }
                }

                //Only check channel user count if the audio services are enabled.
                if (Config.bot.AudioSettings.AudioServicesEnabled)
                {
                    //There is an active song playing on this guild
                    ServerMusicItem musicItem = MusicService.GetMusicList(((SocketGuildUser)user).Guild.Id);
                    if (musicItem != null && musicItem.AudioChannel.Id == before.VoiceChannel?.Id)
                    {
                        //It is literally just us in the voice channel
                        if (before.VoiceChannel.Users.Count == 1)
                        {
                            await MusicService.StopPlayingAudioOnServer(musicItem);

                            //Leave this voice channel
                            await musicItem.AudioClient.StopAsync();

                            await musicItem.StartChannel.SendMessageAsync(
                                ":musical_note: Left the audio channel due to there being no one there :(");

                            MusicService.currentChannels.Remove(musicItem);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("An error occured while managing a user voice updated event! {@Exception}", ex);
            }
        }
Beispiel #17
0
        private async Task MessageReceived(SocketMessage arg)
        {
            if (!sentMessages.Contains(arg) && arg.Author.Id != _c.CurrentUser.Id)
            {
                sentMessages.Add(arg);

                if (arg.Channel.Id == 759102103200989254)
                {
                    string content = arg.Content;
                    await arg.DeleteAsync();

                    int section;
                    if (int.TryParse(content, out section))
                    {
                        if (section <= 72 && section >= 2 && section % 10 != 0)
                        {
                            bool found = false;
                            foreach (SocketRole role in _c.GetGuild(759101634948890645).Roles)
                            {
                                if (role.Name == "Lab " + section)
                                {
                                    found = true;
                                }
                            }

                            if (!found)
                            {
                                Log("Role doesn't exist for section " + section + ", creating...");
                                RestRole role = await _c.GetGuild(759101634948890645).CreateRoleAsync("Lab " + section, null, null, false, null);

                                Log("Created role with id " + role.Id);
                                await(arg.Author as IGuildUser).AddRoleAsync(role);
                                Log("Adding " + role.Name + " to " + arg.Author.Username);

                                // Check for already-existing channel. If there isn't one, create one.
                                found = false;
                                foreach (ITextChannel channel in _c.GetGuild(759101634948890645).TextChannels)
                                {
                                    if (channel.Name == "lab-" + section)
                                    {
                                        found = true;
                                    }
                                }

                                if (!found)
                                {
                                    RestTextChannel tc = await _c.GetGuild(759101634948890645).CreateTextChannelAsync("lab-" + section, (a) => { a.CategoryId = 759102041309708370; });

                                    RestVoiceChannel vc = await _c.GetGuild(759101634948890645).CreateVoiceChannelAsync("- Lab " + section + " -", (a) => { a.CategoryId = 759102041309708370; });

                                    OverwritePermissions allow_perms = new OverwritePermissions(connect: PermValue.Allow, viewChannel: PermValue.Allow, sendMessages: PermValue.Allow, readMessageHistory: PermValue.Allow, speak: PermValue.Allow);
                                    OverwritePermissions deny_perms  = new OverwritePermissions(connect: PermValue.Deny, viewChannel: PermValue.Deny, sendMessages: PermValue.Deny, readMessageHistory: PermValue.Deny, speak: PermValue.Deny);
                                    await vc.AddPermissionOverwriteAsync(role, allow_perms);

                                    await vc.AddPermissionOverwriteAsync(_c.GetGuild(759101634948890645).EveryoneRole, deny_perms);

                                    await tc.AddPermissionOverwriteAsync(role, allow_perms);

                                    await tc.AddPermissionOverwriteAsync(_c.GetGuild(759101634948890645).EveryoneRole, deny_perms);
                                }
                            }

                            foreach (SocketRole role in _c.GetGuild(759101634948890645).Roles)
                            {
                                if (role.Name.ToLower().Contains("lab ") && role.Name != "Lab " + section)
                                {
                                    await(arg.Author as IGuildUser).RemoveRoleAsync(role);
                                }
                                else if (role.Name.ToLower() == "student")
                                {
                                    await(arg.Author as IGuildUser).AddRoleAsync(role);
                                    Log("Adding " + role.Name + " to " + arg.Author.Username);
                                }
                                else if (role.Name == "Lab " + section)
                                {
                                    await(arg.Author as IGuildUser).AddRoleAsync(role);
                                    Log("Adding " + role.Name + " to " + arg.Author.Username);

                                    // Check for already-existing channel. If there isn't one, create one.
                                    found = false;
                                    foreach (ITextChannel channel in _c.GetGuild(759101634948890645).TextChannels)
                                    {
                                        if (channel.Name == "lab-" + section)
                                        {
                                            found = true;
                                        }
                                    }

                                    if (!found)
                                    {
                                        RestTextChannel tc = await _c.GetGuild(759101634948890645).CreateTextChannelAsync("lab-" + section, (a) => { a.CategoryId = 759102041309708370; });

                                        RestVoiceChannel vc = await _c.GetGuild(759101634948890645).CreateVoiceChannelAsync("- Lab " + section + " -", (a) => { a.CategoryId = 759102041309708370; });

                                        OverwritePermissions allow_perms = new OverwritePermissions(connect: PermValue.Allow, viewChannel: PermValue.Allow, sendMessages: PermValue.Allow, readMessageHistory: PermValue.Allow, speak: PermValue.Allow);
                                        OverwritePermissions deny_perms  = new OverwritePermissions(connect: PermValue.Deny, viewChannel: PermValue.Deny, sendMessages: PermValue.Deny, readMessageHistory: PermValue.Deny, speak: PermValue.Deny);
                                        await vc.AddPermissionOverwriteAsync(role, allow_perms);

                                        await vc.AddPermissionOverwriteAsync(_c.GetGuild(759101634948890645).EveryoneRole, deny_perms);

                                        await tc.AddPermissionOverwriteAsync(role, allow_perms);

                                        await tc.AddPermissionOverwriteAsync(_c.GetGuild(759101634948890645).EveryoneRole, deny_perms);
                                    }
                                }
                            }
                        }
                    }
                }
                else if (arg.Channel.Id == 762877768315830273)
                {
                    string content = arg.Content;
                    await arg.DeleteAsync();

                    int section;
                    if (int.TryParse(content, out section))
                    {
                        if (section >= 1 && section <= 70 && (section % 10 == 0 || section == 1))
                        {
                            bool found = false;
                            foreach (SocketRole role in _c.GetGuild(759101634948890645).Roles)
                            {
                                if (role.Name == "Lecture " + section)
                                {
                                    found = true;
                                }
                            }

                            if (!found)
                            {
                                Log("Role doesn't exist for section " + section + ", creating...");
                                RestRole role = await _c.GetGuild(759101634948890645).CreateRoleAsync("Lecture " + section, null, null, false, null);

                                Log("Created role with id " + role.Id);
                                await(arg.Author as IGuildUser).AddRoleAsync(role);
                                Log("Adding " + role.Name + " to " + arg.Author.Username);

                                // Check for already-existing channel. If there isn't one, create one.
                                found = false;
                                foreach (ITextChannel channel in _c.GetGuild(759101634948890645).TextChannels)
                                {
                                    if (channel.Topic == "Section " + (section == 1 ? "001" : "0" + section))
                                    {
                                        found = true;
                                    }
                                }

                                if (!found)
                                {
                                    RestTextChannel tc = await _c.GetGuild(759101634948890645).CreateTextChannelAsync("lecture-chat", (a) => { a.CategoryId = 759103059695239240; a.Topic = "Section " + (section == 1 ? "001" : "0" + section); });

                                    RestVoiceChannel vc = await _c.GetGuild(759101634948890645).CreateVoiceChannelAsync("- Lecture Chat (0" + (section == 1 ? "01" : section + "") + ")" + " -", (a) => { a.CategoryId = 759103059695239240; });

                                    OverwritePermissions allow_perms = new OverwritePermissions(connect: PermValue.Allow, viewChannel: PermValue.Allow, sendMessages: PermValue.Allow, readMessageHistory: PermValue.Allow, speak: PermValue.Allow);
                                    OverwritePermissions deny_perms  = new OverwritePermissions(connect: PermValue.Deny, viewChannel: PermValue.Deny, sendMessages: PermValue.Deny, readMessageHistory: PermValue.Deny, speak: PermValue.Deny);
                                    await vc.AddPermissionOverwriteAsync(role, allow_perms);

                                    await vc.AddPermissionOverwriteAsync(_c.GetGuild(759101634948890645).EveryoneRole, deny_perms);

                                    await tc.AddPermissionOverwriteAsync(role, allow_perms);

                                    await tc.AddPermissionOverwriteAsync(_c.GetGuild(759101634948890645).EveryoneRole, deny_perms);
                                }
                            }

                            foreach (SocketRole role in _c.GetGuild(759101634948890645).Roles)
                            {
                                if (role.Name.ToLower().Contains("lecture ") && role.Name != "Lecture " + section)
                                {
                                    await(arg.Author as IGuildUser).RemoveRoleAsync(role);
                                }
                                else if (role.Name.ToLower() == "student")
                                {
                                    await(arg.Author as IGuildUser).AddRoleAsync(role);
                                    Log("Adding " + role.Name + " to " + arg.Author.Username);
                                }
                                else if (role.Name == "Lecture " + section)
                                {
                                    await(arg.Author as IGuildUser).AddRoleAsync(role);
                                    Log("Adding " + role.Name + " to " + arg.Author.Username);

                                    // Check for already-existing channel. If there isn't one, create one.
                                    found = false;
                                    foreach (ITextChannel channel in _c.GetGuild(759101634948890645).TextChannels)
                                    {
                                        if (channel.Topic == "Section " + (section == 1 ? "001" : "0" + section))
                                        {
                                            found = true;
                                        }
                                    }

                                    if (!found)
                                    {
                                        RestTextChannel tc = await _c.GetGuild(759101634948890645).CreateTextChannelAsync("lecture-chat", (a) => { a.CategoryId = 759103059695239240; a.Topic = "Section " + (section == 1 ? "001" : "0" + section); });

                                        RestVoiceChannel vc = await _c.GetGuild(759101634948890645).CreateVoiceChannelAsync("- Lecture Chat (0" + (section == 1 ? "01" : section + "") + ")" + " -", (a) => { a.CategoryId = 759103059695239240; });

                                        OverwritePermissions allow_perms = new OverwritePermissions(connect: PermValue.Allow, viewChannel: PermValue.Allow, sendMessages: PermValue.Allow, readMessageHistory: PermValue.Allow, speak: PermValue.Allow);
                                        OverwritePermissions deny_perms  = new OverwritePermissions(connect: PermValue.Deny, viewChannel: PermValue.Deny, sendMessages: PermValue.Deny, readMessageHistory: PermValue.Deny, speak: PermValue.Deny);
                                        await vc.AddPermissionOverwriteAsync(role, allow_perms);

                                        await vc.AddPermissionOverwriteAsync(_c.GetGuild(759101634948890645).EveryoneRole, deny_perms);

                                        await tc.AddPermissionOverwriteAsync(role, allow_perms);

                                        await tc.AddPermissionOverwriteAsync(_c.GetGuild(759101634948890645).EveryoneRole, deny_perms);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Beispiel #18
0
        public List <Command> Init(IValkyrjaClient iClient)
        {
            this.Client = iClient as ValkyrjaClient;
            List <Command> commands = new List <Command>();

            this.Client.Events.MessageReceived += OnMessageReceived;

// !tempChannel
            Command newCommand = new Command("tempChannel");

            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Creates a temporary voice channel. This channel will be destroyed when it becomes empty, with grace period of three minutes since it's creation.";
            newCommand.ManPage             = new ManPage("[userLimit] <channelName>", "`[userLimit]` - Optional user limit.\n\n`<channelName>` - Name of the new temporary voice channel.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin | PermissionType.Moderator | PermissionType.SubModerator;
            newCommand.OnExecute          += async e => {
                if (e.Server.Config.TempChannelCategoryId == 0)
                {
                    await e.SendReplySafe("This command has to be configured on the config page (\"other\" section) <https://valkyrja.app/config>");

                    return;
                }

                if (string.IsNullOrWhiteSpace(e.TrimmedMessage))
                {
                    await e.SendReplySafe($"Usage: `{e.Server.Config.CommandPrefix}tempChannel <name>` or `{e.Server.Config.CommandPrefix}tempChannel [userLimit] <name>`");

                    return;
                }

                int           limit   = 0;
                bool          limited = int.TryParse(e.MessageArgs[0], out limit);
                StringBuilder name    = new StringBuilder();
                for (int i = limited ? 1 : 0; i < e.MessageArgs.Length; i++)
                {
                    name.Append(e.MessageArgs[i]);
                    name.Append(" ");
                }
                string responseString = string.Format(TempChannelConfirmString, name.ToString());

                try
                {
                    RestVoiceChannel tempChannel = null;
                    if (limited)
                    {
                        tempChannel = await e.Server.Guild.CreateVoiceChannelAsync(name.ToString(), c => {
                            c.CategoryId = e.Server.Config.TempChannelCategoryId;
                            c.UserLimit  = limit;
                        });
                    }
                    else
                    {
                        tempChannel = await e.Server.Guild.CreateVoiceChannelAsync(name.ToString(), c => c.CategoryId = e.Server.Config.TempChannelCategoryId);
                    }

                    if (e.Server.Config.TempChannelGiveAdmin)
                    {
                        await tempChannel.AddPermissionOverwriteAsync(e.Message.Author, new OverwritePermissions(manageChannel : PermValue.Allow, manageRoles : PermValue.Allow, moveMembers : PermValue.Allow, muteMembers : PermValue.Allow, deafenMembers : PermValue.Allow));
                    }

                    ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                    ChannelConfig channel   = dbContext.Channels.AsQueryable().FirstOrDefault(c => c.ServerId == e.Server.Id && c.ChannelId == tempChannel.Id);
                    if (channel == null)
                    {
                        channel = new ChannelConfig {
                            ServerId  = e.Server.Id,
                            ChannelId = tempChannel.Id
                        };

                        dbContext.Channels.Add(channel);
                    }

                    channel.Temporary = true;
                    dbContext.SaveChanges();
                    dbContext.Dispose();
                }
                catch (HttpException exception)
                {
                    await e.Server.HandleHttpException(exception, $"This happened in <#{e.Channel.Id}> when trying to create a temporary channel.");
                }
                catch (Exception exception)
                {
                    await this.Client.LogException(exception, e);

                    responseString = string.Format(ErrorUnknownString, this.Client.GlobalConfig.AdminUserId);
                }

                await e.SendReplySafe(responseString);
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("tmp"));
            commands.Add(newCommand.CreateAlias("tc"));

// !mentionRole
            newCommand                     = new Command("mentionRole");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Mention a role with a message. Use with the name of the role as the first parameter and the message will be the rest.";
            newCommand.ManPage             = new ManPage("<roleName> <message text>", "`<roleName>` - Name of the role to be mentioned with a ping.\n\n`<message text>` - Text that will be said with the role mention.");
            newCommand.DeleteRequest       = true;
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.SendReplySafe(ErrorPermissionsString);

                    return;
                }

                if (e.MessageArgs == null || e.MessageArgs.Length < 2)
                {
                    await e.SendReplySafe($"Usage: `{e.Server.Config.CommandPrefix}{e.CommandId} <roleName> <message text>`");

                    return;
                }

                IEnumerable <SocketRole> foundRoles = null;
                if (!(foundRoles = e.Server.Guild.Roles.Where(r => r.Name == e.MessageArgs[0])).Any() &&
                    !(foundRoles = e.Server.Guild.Roles.Where(r => r.Name.ToLower() == e.MessageArgs[0].ToLower())).Any() &&
                    !(foundRoles = e.Server.Guild.Roles.Where(r => r.Name.ToLower().Contains(e.MessageArgs[0].ToLower()))).Any())
                {
                    await e.SendReplySafe(ErrorRoleNotFound);

                    return;
                }

                if (foundRoles.Count() > 1)
                {
                    await e.SendReplySafe(ErrorTooManyFound);

                    return;
                }

                SocketRole role    = foundRoles.First();
                string     message = e.TrimmedMessage.Substring(e.TrimmedMessage.IndexOf(e.MessageArgs[1]));

                await role.ModifyAsync(r => r.Mentionable = true);

                await Task.Delay(100);

                await e.SendReplySafe($"{role.Mention} {message}", allowedMentions : new AllowedMentions(AllowedMentionTypes.Users | AllowedMentionTypes.Everyone | AllowedMentionTypes.Roles));

                await Task.Delay(100);

                await role.ModifyAsync(r => r.Mentionable = false);
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("announce"));

// !cheatsheet
            newCommand                     = new Command("cheatsheet");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Send an embed cheatsheet with various moderation commands.";
            newCommand.ManPage             = new ManPage("", "");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                EmbedBuilder embedBuilder = new EmbedBuilder();
                embedBuilder.WithTitle("Moderation commands").WithColor(16711816).WithFields(
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}op`").WithValue("Distinguish yourself as a moderator when addressing people, and allow the use of `!mute`, `!kick` & `!ban` commands."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}mute @user(s) duration`").WithValue("Mute mentioned user(s) for `duration` (use `m`, `h` and `d`, e.g. 1h15m. This will effectively move them to the `#chill-zone` channel."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}kick @user(s) reason`").WithValue("Kick mentioned `@users` (or IDs) with specific `reason`."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}ban @user(s) duration reason`").WithValue("Ban mentioned `@users` (or IDs) for `duration` (use `h` and `d`, e.g. 1d12h, or zero `0d` for permanent) with specific `reason`."),
                    new EmbedFieldBuilder().WithName("`reason`").WithValue("Reason parameter of the above `kick` and `ban` commands is stored in the database as a _warning_ and also PMed to the user. Please provide proper descriptions."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}issueWarning @user(s) message`").WithValue("The same as `addWarning`, but also PM this message to the user(s)"),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}addWarning @user(s) message`").WithValue("Add a `message` to the database, taking notes of peoples naughty actions."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}removeWarning @user`").WithValue("Remove the last added warning from the `@user` (or ID)"),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}whois @user`").WithValue("Search for a `@user` (or ID, or name) who is present on the server."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}find expression`").WithValue("Search for a user using more complex search through all the past nicknames, etc... This will also go through people who are not on the server anymore."),
                    new EmbedFieldBuilder().WithName($"`whois/find`").WithValue("Both whois and find commands will return information about the user, when was their account created, when did they join, their past names and nicknames, and all the previous warnings and bans.")
                    );

                RestUserMessage msg = await e.Channel.SendMessageAsync(embed : embedBuilder.Build());

                await msg.PinAsync();

                embedBuilder = new EmbedBuilder();
                embedBuilder.WithTitle("Moderation guidelines").WithColor(16711816).WithDescription("for implementing the [theory](http://rhea-ayase.eu/articles/2017-04/Moderation-guidelines) in real situations.\n")
                .WithFields(
                    new EmbedFieldBuilder().WithName("__Talking to people__").WithValue("~"),
                    new EmbedFieldBuilder().WithName("Don't use threats.").WithValue("a) **Imposed consequences** - what you can do with your power (kick, ban,...) These are direct threats, avoid them.\nb) **Natural consequences** - implied effects of members actions. These can include \"the community is growing to dislike you,\" or \"see you as racist,\" etc..."),
                    new EmbedFieldBuilder().WithName("Identify what is the underlying problem.").WithValue("a) **Motivation problem** - the member is not motivated to behave in acceptable manner - is a troll or otherwise enjoys being mean to people.\nb) **Ability problem** - the member may be direct without \"filters\" and their conversation often comes off as offensive while they just state things the way they see them: http://www.mit.edu/~jcb/tact.html"),
                    new EmbedFieldBuilder().WithName("Conversation should follow:").WithValue("1) **Explain** the current situation / problem.\n2) **Establish safety** - you're not trying to ban them or discourage them from participating.\n3) **Call to action** - make sure to end the conversation with an agreement about what steps will be taken towards improvement.\n"),
                    new EmbedFieldBuilder().WithName("__Taking action__").WithValue("~"),
                    new EmbedFieldBuilder().WithName("Always log every action").WithValue("with `warnings`, and always check every member and their history."),
                    new EmbedFieldBuilder().WithName("Contents of our channels should not be disrespectful towards anyone, think about minorities.").WithValue("a) Discussion topic going wild, the use of racial/homophobic or other improper language should be pointed out with an explanation that it is not cool towards minorities within our community.\nb) A member being plain disrespectful on purpose... Mute them, see their reaction to moderation talk and act on it."),
                    new EmbedFieldBuilder().WithName("Posting or even spamming inappropriate content").WithValue("should result in immediate mute and only then followed by explaining correct behavior based on all of the above points."),
                    new EmbedFieldBuilder().WithName("Repeated offense").WithValue("a) 1d ban, 3d ban, 7d ban - are your options depending on how severe it is.\nb) Permanent ban should be brought up for discussion with the rest of the team."),
                    new EmbedFieldBuilder().WithName("Member is disrespectful to the authority.").WithValue("If you get into conflict yourself, someone is disrespectful to you as a moderator, trolling and challenging your authority - step back and ask for help, mention `@Staff` in the mod channel, and let 3rd party deal with it.")
                    );

                msg = await e.Channel.SendMessageAsync(embed : embedBuilder.Build());

                await msg.PinAsync();
            };
            commands.Add(newCommand);

// !embed
            newCommand             = new Command("embed");
            newCommand.Type        = CommandType.Standard;
            newCommand.Description = "Build an embed. Use without arguments for help.";
            newCommand.ManPage     = new ManPage("<options>", "Use any combination of:\n" +
                                                 "`--channel     ` - Channel where to send the embed.\n" +
                                                 "`--edit <msgId>` - Replace a MessageId with a new embed (use after --channel)\n" +
                                                 "`--title       ` - Title\n" +
                                                 "`--description ` - Description\n" +
                                                 "`--footer      ` - Footer\n" +
                                                 "`--color       ` - #rrggbb hex color used for the embed stripe.\n" +
                                                 "`--image       ` - URL of a Hjuge image in the bottom.\n" +
                                                 "`--thumbnail   ` - URL of a smol image on the side.\n" +
                                                 "`--fieldName   ` - Create a new field with specified name.\n" +
                                                 "`--fieldValue  ` - Text value of a field - has to follow a name.\n" +
                                                 "`--fieldInline ` - Use to set the field as inline.\n" +
                                                 "Where you can repeat the field* options multiple times.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                await this.Client.SendEmbedFromCli(e);
            };
            commands.Add(newCommand);

// !addEmoji
            newCommand                     = new Command("addEmoji");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Add an emoji reaction to a message.";
            newCommand.ManPage             = new ManPage("<messageId> <emojis>", "`<messageId>` - ID of the message (in the current channel)\n\n`<emojis>` - Emojis that will be added as a reaction.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (e.MessageArgs == null || e.MessageArgs.Length < 2 || !guid.TryParse(e.MessageArgs[0], out guid messageId))
                {
                    await e.SendReplySafe("Invalid parameters:\n" + e.Command.ManPage.ToString(e.Server.Config.CommandPrefix + e.CommandId));

                    return;
                }

                List <IEmote> emotes = new List <IEmote>();
                for (int i = 1; i < e.MessageArgs.Length; i++)
                {
                    if (Emote.TryParse(e.MessageArgs[i], out Emote emote))
                    {
                        emotes.Add(emote);
                    }
                    else
                    {
                        emotes.Add(new Emoji(e.MessageArgs[i]));
                    }
                }

                if (!emotes.Any())
                {
                    await e.SendReplySafe("No emotes found:\n" + e.Command.ManPage.ToString(e.Server.Config.CommandPrefix + e.CommandId));

                    return;
                }

                string response = "K.";
                try
                {
                    IMessage msg = await e.Channel.GetMessageAsync(messageId);

                    switch (msg)
                    {
                    case RestUserMessage message:
                        await message.AddReactionsAsync(emotes.ToArray());

                        break;

                    case SocketUserMessage message:
                        await message.AddReactionsAsync(emotes.ToArray());

                        break;

                    default:
                        response = "Failed to fetch a message with that ID. Did you use this command in a correct channel?";
                        break;
                    }
                }
                catch (Exception)
                {
                    response = "You've dun goof'd, eh?";
                }

                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);

            return(commands);
        }
Beispiel #19
0
        public async Task IsolerAsync(IGuildUser iuser)
        {
            if (Context.Guild.GetCategoriesAsync().Result.Where(x => x.Id == Config._INSTANCE.GuildConfigs[Context.Guild.Id].IsolementCategoryVoiceChannelId).Count() == 0)
            {
                var _settings = new Settings();

                await ReplyAsync("La catégorie du salon d'isolement n'est pas définie. Remédiez-y avec la commande **x!settings IsolementCategoryVoiceChannelId**.");
                await ReplyAsync("N'oubliez pas d'ajouter des salons interdits aux utilisateurs en période d'isolement ! (**x!settings AddForbiddenIsolementChannelId**)");

                return;
            }



            SocketGuildUser user = (SocketGuildUser)iuser;

            if (user.IsBot || user.IsWebhook)
            {
                await ReplyAsync("Vous ne pouvez isoler que des joueurs. Tu ne comptais tout de même pas m'isoler j'éspère ?!");

                return;
            }

            if (user == null)
            {
                await ReplyAsync("Le joueur ciblé n'existe pas.");

                return;
            }

            if (user.VoiceChannel == null)
            {
                await ReplyAsync(user.Mention + " n'est pas connecté à un serveur vocal.");

                return;
            }

            SocketGuild   guild            = user.Guild;
            SocketChannel isolementChannel = Program._client.GetChannel(Config._INSTANCE.GuildConfigs[Context.Guild.Id].IsolementVoiceChannelId);

            if (isolementChannel == null)
            {
                await ReplyAsync("Création d'une nouvelle cellule d'isolement.");


                ICategoryChannel category = Program._client.GetGuild(guild.Id).CategoryChannels
                                            .FirstOrDefault(x => x.Id == Config._INSTANCE.GuildConfigs[Context.Guild.Id].IsolementCategoryVoiceChannelId);

                RestVoiceChannel rest = await guild.CreateVoiceChannelAsync("isolement");

                await rest.ModifyAsync(x => x.CategoryId = category.Id);

                Config._INSTANCE.GuildConfigs[Context.Guild.Id].IsolementVoiceChannelId = rest.Id;
                XmlManager.SaveXmlConfig();
            }

            try
            {
                foreach (ulong forbiddenId in Config._INSTANCE.GuildConfigs[Context.Guild.Id].ForbiddenIsolementChannelsId)
                {
                    await guild.GetChannel(forbiddenId).AddPermissionOverwriteAsync(user, new OverwritePermissions(0, 13631488));
                }
            }
            catch { }

            await user.ModifyAsync(x => x.ChannelId = Config._INSTANCE.GuildConfigs[Context.Guild.Id].IsolementVoiceChannelId);

            await ReplyAsync(user.Mention + " est désormais seul, au bord du suicide.");

            joueursIsolés.Add(user.Id, user.VoiceChannel.Id);

            System.Threading.Timer timer = null;
            timer = new System.Threading.Timer(async(obj) =>
            {
                await Task.Run(() => LibreAsync(user, true, true));
                timer.Dispose();
            },
                                               null, (int)(Config._INSTANCE.GuildConfigs[Context.Guild.Id].IsolementTime * 1000), System.Threading.Timeout.Infinite);
        }
Beispiel #20
0
        private async Task JoinChannel(SocketVoiceChannel channel, SocketGuildUser user)
        {
            if (channel == null)
            {
                return;
            }

            var failed = false;
            RestVoiceChannel newChannel = null;

            try
            {
                var auto = await _channel.Load(channel.Guild.Id, AutomationType.Temporary);

                if (channel.Name.StartsWith(auto.Prefix, StringComparison.OrdinalIgnoreCase))
                {
                    newChannel = await DuplicateChannel(channel, user, auto.Name);

                    await _channel.AddGeneratedChannel(channel.Guild.Id, newChannel.Id);

                    _channels.Remove(newChannel.Id);
                    return;
                }

                var perma = await _channel.Load(channel.Guild.Id, AutomationType.Permanent);

                if (channel.Name.StartsWith(perma.Prefix, StringComparison.OrdinalIgnoreCase))
                {
                    newChannel = await DuplicateChannel(channel, user, perma.Name);

                    _channels.Remove(newChannel.Id);
                }
            }
            catch (HttpException httpException)
            {
                if (!httpException.Message.Contains("error 50013: Missing Permissions"))
                {
                    await Logs.Write("Crashes",
                                     $"JoinChannel crashed. ({channel.Guild.Id}) {channel.Id}, {channel.Name}.", httpException);
                }
                else
                {
                    var pmChannel = await channel.Guild.Owner.GetOrCreateDMChannelAsync();
                    await LoadLanguage(channel.Guild.Id);

                    await pmChannel.SendMessageAsync(_localization.GetMessage("Channel no permission",
                                                                              channel.Guild.Name, channel.Name));
                }

                failed = true;
            }
            catch (Exception e)
            {
                await Logs.Write("Crashes",
                                 $"JoinChannel crashed. ({channel.Guild.Id}) {channel.Id}, {channel.Name}.", e);

                failed = true;
            }

            if (failed)
            {
                if (newChannel != null)
                {
                    await newChannel.DeleteAsync();

                    try
                    {
                        await _channel.RemoveGeneratedChannel(newChannel.GuildId, newChannel.Id);
                    }
                    catch (Exception)
                    {
                        //ignore
                    }

                    _channels.Remove(newChannel.Id);
                }
            }
        }
Beispiel #21
0
        public List <Command> Init(IBotwinderClient iClient)
        {
            this.Client = iClient as BotwinderClient;
            List <Command> commands = new List <Command>();

// !tempChannel
            Command newCommand = new Command("tempChannel");

            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Creates a temporary voice channel. This channel will be destroyed when it becomes empty, with grace period of three minutes since it's creation.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin | PermissionType.Moderator | PermissionType.SubModerator;
            newCommand.OnExecute          += async e => {
                if (e.Server.Config.TempChannelCategoryId == 0)
                {
                    await e.SendReplySafe("This command has to be configured on the config page (social) <https://valkyrja.app/config>");

                    return;
                }

                if (string.IsNullOrWhiteSpace(e.TrimmedMessage))
                {
                    await e.SendReplySafe($"Usage: `{e.Server.Config.CommandPrefix}tempChannel <name>` or `{e.Server.Config.CommandPrefix}tempChannel [userLimit] <name>`");

                    return;
                }

                int           limit   = 0;
                bool          limited = int.TryParse(e.MessageArgs[0], out limit);
                StringBuilder name    = new StringBuilder();
                for (int i = limited ? 1 : 0; i < e.MessageArgs.Length; i++)
                {
                    name.Append(e.MessageArgs[i]);
                    name.Append(" ");
                }
                string responseString = string.Format(TempChannelConfirmString, name.ToString());

                try
                {
                    RestVoiceChannel tempChannel = null;
                    if (limited)
                    {
                        tempChannel = await e.Server.Guild.CreateVoiceChannelAsync(name.ToString(), c => {
                            c.CategoryId = e.Server.Config.TempChannelCategoryId;
                            c.UserLimit  = limit;
                        });
                    }
                    else
                    {
                        tempChannel = await e.Server.Guild.CreateVoiceChannelAsync(name.ToString(), c => c.CategoryId = e.Server.Config.TempChannelCategoryId);
                    }

                    ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                    ChannelConfig channel   = dbContext.Channels.FirstOrDefault(c => c.ServerId == e.Server.Id && c.ChannelId == tempChannel.Id);
                    if (channel == null)
                    {
                        channel = new ChannelConfig {
                            ServerId  = e.Server.Id,
                            ChannelId = tempChannel.Id
                        };

                        dbContext.Channels.Add(channel);
                    }

                    channel.Temporary = true;
                    dbContext.SaveChanges();
                    dbContext.Dispose();
                }
                catch (Exception exception)
                {
                    await this.Client.LogException(exception, e);

                    responseString = string.Format(ErrorUnknownString, this.Client.GlobalConfig.AdminUserId);
                }
                await e.SendReplySafe(responseString);
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("tmp"));
            commands.Add(newCommand.CreateAlias("tc"));

// !mentionRole
            newCommand                     = new Command("mentionRole");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Mention a role with a message. Use with the name of the role as the first parameter and the message will be the rest.";
            newCommand.DeleteRequest       = true;
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.SendReplySafe(ErrorPermissionsString);

                    return;
                }

                if (e.MessageArgs == null || e.MessageArgs.Length < 2)
                {
                    await e.SendReplyUnsafe($"Usage: `{e.Server.Config.CommandPrefix}{e.CommandId} <roleName> <message text>`");

                    return;
                }

                IEnumerable <SocketRole> foundRoles = null;
                if (!(foundRoles = e.Server.Guild.Roles.Where(r => r.Name == e.MessageArgs[0])).Any() &&
                    !(foundRoles = e.Server.Guild.Roles.Where(r => r.Name.ToLower() == e.MessageArgs[0].ToLower())).Any() &&
                    !(foundRoles = e.Server.Guild.Roles.Where(r => r.Name.ToLower().Contains(e.MessageArgs[0].ToLower()))).Any())
                {
                    await e.SendReplyUnsafe(ErrorRoleNotFound);

                    return;
                }

                if (foundRoles.Count() > 1)
                {
                    await e.SendReplyUnsafe(ErrorTooManyFound);

                    return;
                }

                SocketRole role    = foundRoles.First();
                string     message = e.TrimmedMessage.Substring(e.TrimmedMessage.IndexOf(e.MessageArgs[1]));

                await role.ModifyAsync(r => r.Mentionable = true);

                await Task.Delay(100);

                await e.SendReplySafe($"{role.Mention} {message}");

                await Task.Delay(100);

                await role.ModifyAsync(r => r.Mentionable = false);
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("announce"));

// !cheatsheet
            newCommand                     = new Command("cheatsheet");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Send an embed cheatsheet with various moderation commands.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                EmbedBuilder embedBuilder = new EmbedBuilder();
                embedBuilder.WithTitle("Moderation commands").WithColor(16711816).WithFields(
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}op`").WithValue("Distinguish yourself as a moderator when addressing people, and allow the use of `!mute`, `!kick` & `!ban` commands."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}mute @user(s) duration`").WithValue("Mute mentioned user(s) for `duration` (use `m`, `h` and `d`, e.g. 1h15m. This will effectively move them to the `#chill-zone` channel."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}kick @user(s) reason`").WithValue("Kick mentioned `@users` (or IDs) with specific `reason`."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}ban @user(s) duration reason`").WithValue("Ban mentioned `@users` (or IDs) for `duration` (use `h` and `d`, e.g. 1d12h, or zero `0d` for permanent) with specific `reason`."),
                    new EmbedFieldBuilder().WithName("`reason`").WithValue("Reason parameter of the above `kick` and `ban` commands is stored in the database as a _warning_ and also PMed to the user. Please provide proper descriptions."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}issueWarning @user(s) message`").WithValue("The same as `addWarning`, but also PM this message to the user(s)"),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}addWarning @user(s) message`").WithValue("Add a `message` to the database, taking notes of peoples naughty actions."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}removeWarning @user`").WithValue("Remove the last added warning from the `@user` (or ID)"),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}whois @user`").WithValue("Search for a `@user` (or ID, or name) who is present on the server."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}find expression`").WithValue("Search for a user using more complex search through all the past nicknames, etc... This will also go through people who are not on the server anymore."),
                    new EmbedFieldBuilder().WithName($"`whois/find`").WithValue("Both whois and find commands will return information about the user, when was their account created, when did they join, their past names and nicknames, and all the previous warnings and bans.")
                    );

                RestUserMessage msg = await e.Channel.SendMessageAsync(embed : embedBuilder.Build());

                await msg.PinAsync();

                embedBuilder = new EmbedBuilder();
                embedBuilder.WithTitle("Moderation guidelines").WithColor(16711816).WithDescription("for implementing the [theory](http://rhea-ayase.eu/articles/2017-04/Moderation-guidelines) in real situations.\n")
                .WithFields(
                    new EmbedFieldBuilder().WithName("__Talking to people__").WithValue("~"),
                    new EmbedFieldBuilder().WithName("Don't use threats.").WithValue("a) **Imposed consequences** - what you can do with your power (kick, ban,...) These are direct threats, avoid them.\nb) **Natural consequences** - implied effects of members actions. These can include \"the community is growing to dislike you,\" or \"see you as racist,\" etc..."),
                    new EmbedFieldBuilder().WithName("Identify what is the underlying problem.").WithValue("a) **Motivation problem** - the member is not motivated to behave in acceptable manner - is a troll or otherwise enjoys being mean to people.\nb) **Ability problem** - the member may be direct without \"filters\" and their conversation often comes off as offensive while they just state things the way they see them: http://www.mit.edu/~jcb/tact.html"),
                    new EmbedFieldBuilder().WithName("Conversation should follow:").WithValue("1) **Explain** the current situation / problem.\n2) **Establish safety** - you're not trying to ban them or discourage them from participating.\n3) **Call to action** - make sure to end the conversation with an agreement about what steps will be taken towards improvement.\n"),
                    new EmbedFieldBuilder().WithName("__Taking action__").WithValue("~"),
                    new EmbedFieldBuilder().WithName("Always log every action").WithValue("with `warnings`, and always check every member and their history."),
                    new EmbedFieldBuilder().WithName("Contents of our channels should not be disrespectful towards anyone, think about minorities.").WithValue("a) Discussion topic going wild, the use of racial/homophobic or other improper language should be pointed out with an explanation that it is not cool towards minorities within our community.\nb) A member being plain disrespectful on purpose... Mute them, see their reaction to moderation talk and act on it."),
                    new EmbedFieldBuilder().WithName("Posting or even spamming inappropriate content").WithValue("should result in immediate mute and only then followed by explaining correct behavior based on all of the above points."),
                    new EmbedFieldBuilder().WithName("Repeated offense").WithValue("a) 1d ban, 3d ban, 7d ban - are your options depending on how severe it is.\nb) Permanent ban should be brought up for discussion with the rest of the team."),
                    new EmbedFieldBuilder().WithName("Member is disrespectful to the authority.").WithValue("If you get into conflict yourself, someone is disrespectful to you as a moderator, trolling and challenging your authority - step back and ask for help, mention `@Staff` in the mod channel, and let 3rd party deal with it.")
                    );

                msg = await e.Channel.SendMessageAsync(embed : embedBuilder.Build());

                await msg.PinAsync();
            };
            commands.Add(newCommand);

// !embed
            newCommand                     = new Command("embed");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Build an embed. Use without arguments for help.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (string.IsNullOrEmpty(e.TrimmedMessage) || e.TrimmedMessage == "-h" || e.TrimmedMessage == "--help")
                {
                    await e.SendReplySafe("```md\nCreate an embed using the following parameters:\n" +
                                          "[ --channel     ] Channel where to send the embed.\n" +
                                          "[ --title       ] Short title\n" +
                                          "[ --description ] Short description\n" +
                                          "[ --color       ] #rrggbb hex color used for the embed stripe.\n" +
                                          "[ --image       ] URL of a Hjuge image in the bottom.\n" +
                                          "[ --thumbnail   ] URL of a smol image on the side.\n" +
                                          "[ --fieldName   ] Create a new field with specified name.\n" +
                                          "[ --fieldValue  ] Text value of a field - has to follow a name.\n" +
                                          "[ --fieldInline ] Use to set the field as inline.\n" +
                                          "Where you can repeat the field* options multiple times.\n```"
                                          );

                    return;
                }

                bool debug = false;
                SocketTextChannel channel      = e.Channel;
                EmbedFieldBuilder currentField = null;
                EmbedBuilder      embedBuilder = new EmbedBuilder();

                foreach (Match match in this.EmbedParamRegex.Matches(e.TrimmedMessage))
                {
                    string optionString = this.EmbedOptionRegex.Match(match.Value).Value;

                    if (optionString == "--debug")
                    {
                        if (this.Client.IsGlobalAdmin(e.Message.Author.Id) || this.Client.IsSupportTeam(e.Message.Author.Id))
                        {
                            debug = true;
                        }
                        continue;
                    }

                    if (optionString == "--fieldInline")
                    {
                        if (currentField == null)
                        {
                            await e.SendReplySafe($"`fieldInline` can not precede `fieldName`.");

                            return;
                        }

                        currentField.WithIsInline(true);
                        if (debug)
                        {
                            await e.SendReplySafe($"Setting inline for field `{currentField.Name}`");
                        }
                        continue;
                    }

                    string value;
                    if (match.Value.Length <= optionString.Length || string.IsNullOrWhiteSpace(value = match.Value.Substring(optionString.Length + 1).Trim()))
                    {
                        await e.SendReplySafe($"Invalid value for `{optionString}`");

                        return;
                    }

                    if (value.Length >= UserProfileOption.ValueCharacterLimit)
                    {
                        await e.SendReplySafe($"`{optionString}` is too long! (It's {value.Length} characters while the limit is {UserProfileOption.ValueCharacterLimit})");

                        return;
                    }

                    switch (optionString)
                    {
                    case "--channel":
                        if (!guid.TryParse(value.Trim('<', '>', '#'), out guid id) || (channel = e.Server.Guild.GetTextChannel(id)) == null)
                        {
                            await e.SendReplySafe($"Channel {value} not found.");

                            return;
                        }
                        if (debug)
                        {
                            await e.SendReplySafe($"Channel set: `{channel.Name}`");
                        }

                        break;

                    case "--title":
                        embedBuilder.WithTitle(value);
                        if (debug)
                        {
                            await e.SendReplySafe($"Title set: `{value}`");
                        }

                        break;

                    case "--description":
                        embedBuilder.WithDescription(value);
                        if (debug)
                        {
                            await e.SendReplySafe($"Description set: `{value}`");
                        }

                        break;

                    case "--image":
                        embedBuilder.WithImageUrl(value);
                        if (debug)
                        {
                            await e.SendReplySafe($"Image URL set: `{value}`");
                        }

                        break;

                    case "--thumbnail":
                        embedBuilder.WithThumbnailUrl(value);
                        if (debug)
                        {
                            await e.SendReplySafe($"Thumbnail URL set: `{value}`");
                        }

                        break;

                    case "--color":
                        uint color = uint.Parse(value.TrimStart('#'), System.Globalization.NumberStyles.AllowHexSpecifier);
                        embedBuilder.WithColor(color);
                        if (debug)
                        {
                            await e.SendReplySafe($"Color `{value}` set.");
                        }

                        break;

                    case "--fieldName":
                        if (currentField != null && currentField.Value == null)
                        {
                            await e.SendReplySafe($"Field `{currentField.Name}` is missing a value!");

                            return;
                        }

                        embedBuilder.AddField(currentField = new EmbedFieldBuilder().WithName(value));
                        if (debug)
                        {
                            await e.SendReplySafe($"Creating new field `{currentField.Name}`");
                        }

                        break;

                    case "--fieldValue":
                        if (currentField == null)
                        {
                            await e.SendReplySafe($"`fieldValue` can not precede `fieldName`.");

                            return;
                        }

                        currentField.WithValue(value);
                        if (debug)
                        {
                            await e.SendReplySafe($"Setting value:\n```\n{value}\n```\n...for field:`{currentField.Name}`");
                        }

                        break;

                    default:
                        await e.SendReplySafe($"Unknown option: `{optionString}`");

                        return;
                    }
                }

                if (currentField != null && currentField.Value == null)
                {
                    await e.SendReplySafe($"Field `{currentField.Name}` is missing a value!");

                    return;
                }

                await channel.SendMessageAsync(embed : embedBuilder.Build());
            };
            commands.Add(newCommand);

            return(commands);
        }