Example #1
0
        public async Task SortCategory(ICategoryChannel channelCategory)
        {
            var category = channelCategory as SocketCategoryChannel;

            if (category == null)
            {
                await ReplyAsync("invalid channel cat");

                return;
            }

            int order = 1;

            var ackMsg = await ReplyAsync("k.");

            foreach (var channel in category.Channels.Where(x => x is INestedChannel).OrderBy(x => x.Name))
            {
                var c = channel as SocketGuildChannel;
                await c.ModifyAsync(x => x.Position = order);

                order++;

                // delay a bit to avoid pre-emptive rate limit
                await Task.Delay(100);
            }

            await ackMsg.ModifyAsync(x => x.Content = "k done.");
        }
Example #2
0
        public async Task CreateNewVoiceChannel(IGuild guild, ICategoryChannel category, IGuildUser creator, IVoiceChannel initial)
        {
            PublicVoiceChannel newChannel = new PublicVoiceChannel
            {
                moderators = new List <IGuildUser>()
                {
                    creator
                }
            };

            _log.Info($"Creating new Voice Channel for user {creator.Id}");
            var voiceChannel = await guild.CreateVoiceChannelAsync($"{creator.Username}#{creator.Discriminator}",
                                                                   func =>
            {
                func.CategoryId = category.Id;
            });

            newChannel.voiceChannel = voiceChannel;
            newChannel.CreatorId    = creator.Id;

            _log.Info($"Moved user to Voice Channel {voiceChannel.Id}");
            await creator.ModifyAsync(x =>
            {
                x.ChannelId = voiceChannel.Id;
            });

            _customVoiceChannels.Add(newChannel);
        }
Example #3
0
        private async Task <IGuildChannel> CreateOrUpdateChannel(SocketGuild guild, ICategoryChannel category, string name, string topic, int position)
        {
            var channel = guild.Channels.OfType <SocketTextChannel>().SingleOrDefault(a => a.Name == name && a.CategoryId == category.Id) as IGuildChannel;

            if (channel == null)
            {
                _logger.LogDebug($"'#{name}' channel not found, creating.");
                _waitingForChannel = name;
                channel            = await guild.CreateTextChannelAsync(name, a =>
                {
                    a.CategoryId = category.Id;
                    a.Position   = position;
                    a.Topic      = topic;
                });

                _channelCreatedWaiter.WaitOne();
            }

            _logger.LogDebug($"Enforcing deny to send messages, or reactions to @everyone in the '#{name}' channel");
            await channel.AddPermissionOverwriteAsync(guild.EveryoneRole, new OverwritePermissions(sendMessages : PermValue.Deny, addReactions : PermValue.Deny));

            var botRole = guild.Roles.SingleOrDefault(a => a.Name == _bot.DiscordClient.CurrentUser.Username);

            if (botRole != null)
            {
                await channel.AddPermissionOverwriteAsync(botRole, new OverwritePermissions(sendMessages : PermValue.Allow, addReactions : PermValue.Allow));
            }
            else
            {
                await channel.AddPermissionOverwriteAsync(_bot.DiscordClient.CurrentUser, new OverwritePermissions(sendMessages : PermValue.Allow, addReactions : PermValue.Allow));
            }
            return(channel);
        }
        /********************************************************
         * Creates Public Anon Channel
         * ********************************************************/
        public async Task CreatePublicAnonChannel(SocketGuild guild)
        {
            var everyoneRole = guild.Roles.FirstOrDefault(x => x.IsEveryone);

            Console.WriteLine($"Creating PublicChannel for Guild {guild.Name}");
            var text = await guild.CreateTextChannelAsync("Anon");

            ICategoryChannel category = guild.CategoryChannels.FirstOrDefault(x => x.Id == CatagoryID);

            //if catagory exits make a new one
            if (category == null)
            {
                category = await guild.CreateCategoryChannelAsync("Anonyomus Channels");

                await category.AddPermissionOverwriteAsync(everyoneRole, PermissionsDenyAll);
            }

            await text.AddPermissionOverwriteAsync(everyoneRole, PermissionsReadOnly);

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

            var message = await text.SendMessageAsync($"**Welcome to {guild.Name}'s Anonamus Channel!**\n\n" +
                                                      "This channel allows all the users on the server to see the anonamous chat without being in it." +
                                                      "The bot grabs all messages sent by users and sends them to everyone elses channel. " +
                                                      "Becouse the bot posts the message you don't know who sent the message.\n\n" +
                                                      "You can view the source code at https://github.com/doc543/AnonBot \n");

            await message.PinAsync();

            Console.WriteLine("Created Text Channel: " + CatagoryID.ToString());
        }
        public async Task PropertySummary()
        {
            var guild = Context.Guild;
            var props = SpService.GetProperties(Context.Guild.Id);
            var eb    = new EmbedBuilder()
                        .WithTitle("Server properties for " + Context.Guild.Name)
                        .WithColor(0, 255, 0);
            var logChannel = await guild.GetTextChannelAsync(props.LogChannelId).ConfigureAwait(false);

            var spamRole                  = guild.GetRole(props.SpamRoleId);
            var nsfwRole                  = guild.GetRole(props.NsfwRoleId);
            var possibleTempCategory      = (await guild.GetCategoriesAsync().ConfigureAwait(false)).Where(cat => cat.Id == props.TempVoiceCategoryId);
            ICategoryChannel tempCategory = null;

            if (possibleTempCategory.Any())
            {
                tempCategory = possibleTempCategory.First();
            }
            var tempChannel = await guild.GetVoiceChannelAsync(props.TempVoiceCreateChannelId).ConfigureAwait(false);

            eb.AddField("Log Channel", logChannel?.Mention ?? "None");
            eb.AddField("Spam Role", spamRole?.Name ?? "None");
            eb.AddField("NSFW Role", nsfwRole?.Name ?? "None");
            eb.AddField("Temporary Voice Channel Category", tempCategory?.Name ?? "None");
            eb.AddField("Temporary Voice Creation Channel", tempChannel?.Name ?? "None");
            eb.AddField("Simple Temp VCs", props.SimpleTempVc ? "Enabled" : "Disabled");
            eb.AddField("Prefix", !string.IsNullOrEmpty(props.Prefix) ? $"`{props.Prefix}`" : "(Default global prefix - see `sp prefix`)");
            await ReplyAsync("", false, eb.Build()).ConfigureAwait(false);
        }
Example #6
0
        public async Task RoleProject([Remainder] string projectName)
        {
            string       TrueName       = projectName.Replace(' ', '-');
            ITextChannel ProjectChannel = (ITextChannel)Context.Guild.Channels.First(x => x.Name == TrueName);

            ICategoryChannel ProjectsCategory = CommandHelper.FindCategory(Context.Guild.CategoryChannels, Strings.ProjectCategoryName);

            if (ProjectChannel.CategoryId != ProjectsCategory.Id)
            {
                await ReplyAsync("The named project was not found!");

                return;
            }

            IRole      role      = Context.Guild.Roles.First(x => x.Name.ToLower() == TrueName.ToLower());
            IGuildUser GuildUser = (IGuildUser)Context.User;

            if (GuildUser.RoleIds.Contains(role.Id))
            {
                await GuildUser.RemoveRoleAsync(role);
                await ReplyAsync($"Removed the {role.Name} role from {GuildUser.Mention}!");
            }
            else
            {
                await GuildUser.AddRoleAsync(role);
                await ReplyAsync($"Added the {role.Name} role to {GuildUser.Mention}!");
            }
        }
Example #7
0
        protected async Task <ITextChannel> FindTextChannel(string channelname, ICategoryChannel cat, UUID sender, string sendername, string TopicType)
        {
            await WaitForUnlock();

            channelname = channelname.ToLowerInvariant();
            channelname = String.Concat(channelname.Where(char.IsLetterOrDigit));
            DiscordLock = true;
            IReadOnlyCollection <ITextChannel> found_chans = await DiscordServer.GetTextChannelsAsync(CacheMode.AllowDownload);

            ITextChannel result = null;

            foreach (ITextChannel ITC in found_chans)
            {
                if (ITC.CategoryId == cat.Id)
                {
                    if (ITC.Name == channelname)
                    {
                        result = ITC;
                        break;
                    }
                }
            }
            if (result == null)
            {
                result = await CreateChannel(channelname, TopicType, sender.ToString());
            }
            else
            {
                await CleanDiscordChannel(result, myconfig.DiscordServerImHistoryHours).ConfigureAwait(false);
            }
            DiscordLock = false;
            return(result);
        }
Example #8
0
        public async Task <ITextChannel> CreateChannelsForFinals(
            ISelfUser botUser, ITournamentState state, Game finalsGame, int finalsRoundNumber, int roomIndex)
        {
            Verify.IsNotNull(this.Guild, "guild");
            Verify.IsNotNull(state, nameof(state));
            Verify.IsNotNull(finalsGame, nameof(finalsGame));

            TournamentRoles roles = this.GetTournamentRoles(state);

            ICategoryChannel finalsCategoryChannel = await this.Guild.CreateCategoryAsync("Finals");

            ITextChannel channel = await this.CreateTextChannelAsync(
                botUser,
                finalsCategoryChannel,
                finalsGame,
                roles,
                finalsRoundNumber,
                roomIndex);

            state.ChannelIds = state.ChannelIds
                               .Concat(new ulong[] { channel.Id })
                               .Concat(new ulong[] { finalsCategoryChannel.Id });

            return(channel);
        }
                public async Task SetDedicatedRoleplayChannelCategory(ICategoryChannel category)
                {
                    var getServerResult = await _servers.GetOrRegisterServerAsync(this.Context.Guild);

                    if (!getServerResult.IsSuccess)
                    {
                        await _feedback.SendErrorAsync(this.Context, getServerResult.ErrorReason);

                        return;
                    }

                    var server = getServerResult.Entity;

                    var result = await _roleplaying.SetDedicatedRoleplayChannelCategoryAsync
                                 (
                        server,
                        category
                                 );

                    if (!result.IsSuccess)
                    {
                        await _feedback.SendErrorAsync(this.Context, result.ErrorReason);

                        return;
                    }

                    await _feedback.SendConfirmationAsync(this.Context, "Dedicated channel category set.");
                }
Example #10
0
        public async Task UpdateAsync()
        {
            await Context.Message.DeleteAsync();

            var cats             = Context.Guild.GetCategoriesAsync().Result;
            ICategoryChannel cat = null;

            foreach (var category in cats)
            {
                if (category.Name.ToLower().Equals("globals"))
                {
                    cat = category;
                }
            }

            if (cat != null)
            {
                var dbCon = DBConnection.Instance();
                dbCon.DatabaseName = BotConfig.Load().DatabaseName;

                if (dbCon.IsConnect())
                {
                    for (int i = 0; i < ChannelData.Channels.Count; i++)
                    {
                        var chanId = ServerConfig.GetChannelId(Context.Guild.Id, ChannelData.Channels[i].IndexId, dbCon);
                        if (ServerConfig.GetChannelState(Context.Guild.Id, ChannelData.Channels[i].IndexToggle, dbCon) == false && chanId != 0)
                        {
                            var chan = await Context.Guild.GetChannelAsync(chanId);

                            if (chan != null)
                            {
                                await chan.DeleteAsync();

                                await ServerConfig.SetupChannel(Context.Guild.Id, 0, ChannelData.Channels[i].Id, dbCon);
                            }
                        }
                        else if (ServerConfig.GetChannelState(Context.Guild.Id, ChannelData.Channels[i].IndexToggle, dbCon) == true && chanId == 0)
                        {
                            var chan = await Context.Guild.CreateTextChannelAsync(ChannelData.Channels[i].Name);

                            await chan.ModifyAsync(x => x.CategoryId = cat.Id);

                            await ServerConfig.SetupChannel(Context.Guild.Id, chan.Id, ChannelData.Channels[i].Id, dbCon);
                        }
                    }

                    dbCon.Close();
                }

                var message = await Context.Channel.SendMessageAsync("Your global channels should now be updated. Please use the `!request` command in a global channel, if you have any issues.");

                await Delete.DeleteMessage(message);
            }
            else
            {
                var message = await Context.Channel.SendMessageAsync("We couldn't find the globals category in your server, I suggest deleting all the global channels and category. Then run the `!create` command.");

                await Delete.DeleteMessage(message, 25000);
            }
        }
        public static Task <ICategoryChannel> ModifyAsync(this ICategoryChannel channel,
                                                          Action <ModifyCategoryChannelActionProperties> action,
                                                          IRestRequestOptions options = null, CancellationToken cancellationToken = default)
        {
            var client = channel.GetRestClient();

            return(client.ModifyCategoryChannelAsync(channel.Id, action, options, cancellationToken));
        }
Example #12
0
        public async Task CreateChannelsAndRole(ICategoryChannel channelCategory, string courseName)
        {
            var category = channelCategory as SocketCategoryChannel;

            if (category == null)
            {
                await ReplyAsync("Invalid channel type. Must be a category channel.");

                return;
            }

            courseName = courseName.ToLower();
            var roleName = $"member_{channelCategory.Name}_{courseName}".ToLower();

            // ack
            var ackMessage = await ReplyAsync($"Ok, creating channel and role {courseName} under {category}");

            // check that a channel with the same name does not already exist
            if (category.Channels.Any(x => x.Name.ToLower() == courseName.ToLower()))
            {
                await ReplyAsync("Duplicate text channel under this category already exists. Quitting.");

                return;
            }

            var channel = await Context.Guild.CreateTextChannelAsync(courseName, x =>
            {
                x.CategoryId = channelCategory.Id;
                x.Topic      = $"Course channel for {courseName}";
            });

            // set the everyone role for channel to disable view channel perm by default
            await channel.AddPermissionOverwriteAsync(Context.Guild.EveryoneRole, new OverwritePermissions(viewChannel : PermValue.Deny));

            await ackMessage.ModifyAsync(x => x.Content = ackMessage.Content + $"\nCreated {channel}.");

            // check duplicate role
            if (Context.Guild.Roles.Any(x => x.Name.ToLower() == roleName))
            {
                await ReplyAsync("Duplicate role name found. Quitting.");

                return;
            }

            // create role
            var role = await Context.Guild.CreateRoleAsync(roleName, permissions : GuildPermissions.None);

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

            await ackMessage.ModifyAsync(x => x.Content = ackMessage.Content + $"\nCreated role {role}.");

            var perms = new OverwritePermissions(viewChannel: PermValue.Allow);

            // assign role perms
            await channel.AddPermissionOverwriteAsync(role, perms);

            await ackMessage.ModifyAsync(x => x.Content = ackMessage.Content + $"\nAssigned perms to {role}.\nDone.");
        }
Example #13
0
        protected async Task DiscordRebuildChannels()
        {
            List <string> required_cats = new List <string>()
            {
                "bot", "group", "im"
            };
            IReadOnlyCollection <ICategoryChannel> found_cats = await DiscordServer.GetCategoriesAsync(CacheMode.AllowDownload);

            foreach (ICategoryChannel fcat in found_cats)
            {
                if (required_cats.Contains(fcat.Name) == true)
                {
                    required_cats.Remove(fcat.Name);
                    catmap.Add(fcat.Name, fcat);
                }
            }
            foreach (string A in required_cats)
            {
                ICategoryChannel newcat = await DiscordServer.CreateCategoryAsync(A).ConfigureAwait(true);

                catmap.Add(A, newcat);
            }
            List <string> required_channels = new List <string>()
            {
                "status", "interface"
            };
            IReadOnlyCollection <ITextChannel> found_chans = await DiscordServer.GetTextChannelsAsync(CacheMode.AllowDownload);

            List <string> GroupChannels = new List <string>();

            foreach (ITextChannel chan in found_chans)
            {
                if (chan.CategoryId == catmap["bot"].Id)
                {
                    required_channels.Remove(chan.Name);
                }
                else
                {
                    if (chan.CategoryId == catmap["group"].Id)
                    {
                        GroupChannels.Add(chan.Name);
                    }
                }
            }
            foreach (string A in required_channels)
            {
                _ = await FindTextChannel(A, catmap["bot"], UUID.Zero, A, "bot").ConfigureAwait(false);
            }
            foreach (Group G in mygroups.Values)
            {
                string groupname = G.Name.ToLowerInvariant();
                groupname = String.Concat(groupname.Where(char.IsLetterOrDigit));
                if (GroupChannels.Contains(groupname) == false)
                {
                    _ = await FindTextChannel(groupname, catmap["group"], G.ID, groupname, "Group").ConfigureAwait(false);
                }
            }
        }
Example #14
0
 public void AddChannel(ChannelType type, ICategoryChannel defaultChannel = null)
 {
     if (defaultChannel != null)
     {
         /*
          * If the channel object/id is given, add a new channel to this object.
          */
     }
 }
Example #15
0
        public static ChannelPermissions Mask(ulong rawValue, IGuildChannel channel)
        {
            var mask = channel switch
            {
                ITextChannel _ => TEXT_PERMISSIONS_VALUE,
                IVoiceChannel _ => VOICE_PERMISSIONS_VALUE,
                ICategoryChannel _ => CATEGORY_PERMISSIONS_VALUE,
                _ => ALL_PERMISSIONS_VALUE,
            };

            return(new ChannelPermissions(rawValue & mask));
        }
Example #16
0
        public static ChannelPermissions Mask(Permission permissions, IGuildChannel channel)
        {
            var mask = channel switch
            {
                IMessageGuildChannel _ => TextPermissionsValue,
                IVocalGuildChannel _ => VoicePermissionsValue,
                ICategoryChannel _ => CategoryPermissionsValue,
                _ => AllPermissionsValue,
            };

            return(new ChannelPermissions(permissions & (Permission)mask));
        }
Example #17
0
 private Investigation(string topic, bool ismoginvest, int id, List <InvestMember> investigators, ulong categoryID, ulong mainchannelID, ulong investigatorschannelID, ulong investigationroleID, List <InterviewRoom> interviewRooms, string auditdate, bool _ismoginvest)
 {
     _IsMOGInvest         = ismoginvest;
     AuditDate            = auditdate;
     Topic                = topic;
     ID                   = id;
     Investigators        = investigators;
     Category             = DiscordBot.Program.CasinoGuild.GetChannel(categoryID) as ICategoryChannel;
     MainChannel          = DiscordBot.Program.CasinoGuild.GetChannel(mainchannelID) as ITextChannel;
     InvestigatorsChannel = DiscordBot.Program.CasinoGuild.GetChannel(investigatorschannelID) as ITextChannel;
     InvestigationRole    = DiscordBot.Program.CasinoGuild.GetRole(investigationroleID) as IRole;
     InterviewRooms       = interviewRooms;
 }
Example #18
0
 public Investigation(SocketGuildUser lead, ITextChannel main, ITextChannel investigators, ICategoryChannel cate, IRole role, int id)
 {
     ID            = id;
     Investigators = new List <InvestMember>
     {
         new InvestMember(lead, InvestPermissions.Admin)
     };
     Category             = cate;
     MainChannel          = main;
     InvestigatorsChannel = investigators;
     InvestigationRole    = role;
     InterviewRooms       = new List <InterviewRoom>();
 }
Example #19
0
        public async Task RoleProject()
        {
            ICategoryChannel ProjectsCategory = CommandHelper.FindCategory(Context.Guild.CategoryChannels, Strings.ProjectCategoryName);

            if (((ITextChannel)Context.Channel).CategoryId != ProjectsCategory.Id)
            {
                await ReplyAsync("This channel is not a project channel - please enter a project name or run this command in a project channel!");

                return;
            }

            await RoleProject(Context.Channel.Name);
        }
Example #20
0
        public async Task RequestChannel(string channelName, [Remainder] ICategoryChannel category = null)
        {
            if (channelName.IsNullOrWhitespace() || !IsValidChannelName(channelName))
            {
                await ReplyAsync("Channel name cannot be empty. Channel names can only contain alphanumeric, dash, and underscore characters.");

                return;
            }

            if (Context.Guild.Channels.Any(x => x.Name == channelName))
            {
                await ReplyAsync($"A channel with the specified name already exists.");
            }

            if (_pendingChannels.ContainsKey(channelName))
            {
                await ReplyAsync($"A pending channel request is already requesting the specified name.");

                return;
            }

            var channelRequest = new PendingChannelModel()
            {
                CategoryId    = category?.Id,
                ChannelName   = channelName,
                RequestUserId = Context.User.Id
            };

            _pendingChannels.AddOrUpdate(channelName, channelRequest, (key, value) => channelRequest);

            if (!_pendingChannels.ContainsKey(channelName))
            {
                await ReplyAsync($"An unexpected error occurred when attempting to create the channel request.");

                return;
            }

            var adminMsg = $"{Context.User.Username} requested a text channel with the name {channelName}";

            if (category != null)
            {
                adminMsg += $" in the {category.Name} category";
            }
            await Context.Guild.MessageAdmins(adminMsg);

            await ReplyAsync("Channel request has been created successfully.");
        }
Example #21
0
        private async Task UpdateCategoryCount()
        {
            if (ClientUpAndRunning() && CategoryConfigurationAvailable())
            {
                int memberCount               = _discord.GetGuild(_config.GuildID).MemberCount;
                ICategoryChannel channel      = _discord.GetChannel(_config.InfoCategoryId) as ICategoryChannel;
                string           categoryName = _config.InfoCategoryDisplay.Replace("%s%", $"{memberCount}");

                if (CategoryShouldUpdate(channel, categoryName))
                {
                    await channel.ModifyAsync(x => x.Name = categoryName);
                }
            }
            else
            {
                await _loggingService.LogMessageAsync(new LogMessage(LogSeverity.Verbose, "ServerInfoService", $"Discord is {_discord}, Guild is {_discord.GetGuild(_config.GuildID)}, InfoCategory is {_config.InfoCategoryDisplay}, InfoCategoryId is {_config.InfoCategoryId}"));
            }
        }
Example #22
0
        private async Task <IVoiceChannel> CreateVoiceChannelAsync(ICategoryChannel parent, Reader reader)
        {
            Verify.IsNotNull(this.Guild, "guild");
            Verify.IsNotNull(parent, nameof(parent));
            Verify.IsNotNull(reader, nameof(reader));

            this.Logger.Debug("Creating voice channel for reader {id}", reader.Id);
            string        name    = GetVoiceRoomName(reader);
            IVoiceChannel channel = await this.Guild.CreateVoiceChannelAsync(
                name,
                channelProps =>
            {
                channelProps.CategoryId = parent.Id;
            },
                RequestOptionsSettings.Default);

            this.Logger.Debug("Voice channel for reader {id} created", reader.Id);
            return(channel);
        }
Example #23
0
        public async Task ArchiveChannel([Remainder] IGuildChannel channel)
        {
            //First we need to move channel
            var cat = await Context.Guild.GetCategoriesAsync();

            ICategoryChannel category = cat.Where(x => x.Id == 548238743476240405).FirstOrDefault();

            if (category == null)
            {
                return;
            }

            //Move it now
            await channel.ModifyAsync(x => x.CategoryId = category.Id);

            //Get role overwrites
            var everyoneOverwrite = category.GetPermissionOverwrite(Context.Guild.EveryoneRole);
            var adminOverwrite    = category.GetPermissionOverwrite(Context.Guild.GetRole(217696310168518657));

            //First remove all perms
            var curPerms = channel.PermissionOverwrites;

            foreach (Overwrite ow in curPerms)
            {
                if (ow.TargetType == PermissionTarget.Role)
                {
                    await channel.RemovePermissionOverwriteAsync(Context.Guild.GetRole(ow.TargetId));
                }
                else
                {
                    await channel.RemovePermissionOverwriteAsync(await Context.Guild.GetUserAsync(ow.TargetId));
                }
            }

            //Okay now we set perms
            await channel.AddPermissionOverwriteAsync(Context.Guild.EveryoneRole, everyoneOverwrite.Value);

            await channel.AddPermissionOverwriteAsync(Context.Guild.GetRole(217696310168518657), adminOverwrite.Value);

            //Will add an output
            await Context.Channel.SendSuccessAsync($"The channel {channel.Name} has been archived.");
        }
Example #24
0
        public async Task <ModifyEntityResult> SetDedicatedRoleplayChannelCategoryAsync
        (
            [NotNull] Server server,
            [CanBeNull] ICategoryChannel category
        )
        {
            var getSettingsResult = await GetOrCreateServerRoleplaySettingsAsync(server);

            if (!getSettingsResult.IsSuccess)
            {
                return(ModifyEntityResult.FromError(getSettingsResult));
            }

            var settings = getSettingsResult.Entity;

            settings.DedicatedRoleplayChannelsCategory = (long?)category?.Id;
            await _database.SaveChangesAsync();

            return(ModifyEntityResult.FromSuccess());
        }
Example #25
0
        public async Task <RuntimeResult> Setup(int count = 3)
        {
            IRole role = Context.Guild.Roles.FirstOrDefault(x => x.Name == TTTService.RoleName);

            if (role == null)
            {
                role = await Context.Guild.CreateRoleAsync(TTTService.RoleName, isMentionable : false);
            }
            var existing = Context.Guild.VoiceChannels.Count(x => x.Name.StartsWith("ttt-"));
            ICategoryChannel category = Context.Guild.CategoryChannels.FirstOrDefault(x => x.Name == "TTT");

            if (category == null)
            {
                category = await Context.Guild.CreateCategoryChannelAsync("TTT");

                await category.AddPermissionOverwriteAsync(Context.Guild.EveryoneRole, Program.NoPerms);

                await category.AddPermissionOverwriteAsync(role, Program.ReadPerms);
            }
            for (int i = 0; i < (count * count); i++)
            {
                IVoiceChannel vc = Context.Guild.VoiceChannels.FirstOrDefault(x => x.Name.StartsWith($"ttt-{i}"));
                if (vc == null)
                {
                    vc = await Context.Guild.CreateVoiceChannelAsync($"ttt-{i}", x =>
                    {
                        x.CategoryId = category.Id;
                    });
                }
                var invites = await vc.GetInvitesAsync();

                IInvite invite = invites.FirstOrDefault();
                if (invite == null)
                {
                    invite = await vc.CreateInviteAsync(maxAge : null, maxUses : 1, isTemporary : true);
                }
                await vc.ModifyAsync(x => x.Name = $"ttt-{i}-{invite.Code}");
            }
            return(Success("Server has been setup for tic tac toe."));
        }
Example #26
0
        public async Task AddProject([Remainder] string projectName)
        {
            ICategoryChannel ProjectsCategory = CommandHelper.FindCategory(Context.Guild.CategoryChannels, Strings.ProjectCategoryName);
            string           TrueName         = projectName.Replace(' ', '-');

            if (ProjectsCategory is null)
            {
                //Create the category
                ProjectsCategory = await Context.Guild.CreateCategoryChannelAsync(Strings.ProjectCategoryName);
            }

            ITextChannel ProjectChannel = await Context.Guild.CreateTextChannelAsync(TrueName);

            await ProjectChannel.ModifyAsync(delegate(TextChannelProperties ac) { ac.CategoryId = ProjectsCategory.Id; });

            //fully order channels in category
            List <ITextChannel> channels = new List <ITextChannel>(Context.Guild.TextChannels);

            channels.RemoveAll(x => x.CategoryId != ProjectsCategory.Id);
            channels.Add(ProjectChannel);

            await CommandHelper.OrderChannels(channels, ProjectsCategory.Id);

            //create a role
            IRole ProjectManagerRole = await Context.Guild.CreateRoleAsync($"{TrueName}-Manager");

            await ProjectManagerRole.ModifyAsync(delegate(RoleProperties rp) { rp.Mentionable = true; });

            IRole ProjectRole = await Context.Guild.CreateRoleAsync(TrueName);

            await ProjectRole.ModifyAsync(delegate(RoleProperties rp) { rp.Mentionable = true; });

            await((IGuildUser)Context.User).AddRolesAsync(new List <IRole> {
                ProjectManagerRole, ProjectRole
            });

            await ProjectChannel.AddPermissionOverwriteAsync(ProjectManagerRole, new OverwritePermissions(manageMessages : PermValue.Allow));

            await ReplyAsync($"Created {ProjectChannel.Mention} with role {ProjectRole.Mention}!");
        }
Example #27
0
        /// <exception cref="InvalidOperationException">This channel does not have a parent channel.</exception>
        public static async Task SyncPermissionsAsync(INestedChannel channel, BaseDiscordClient client, RequestOptions options)
        {
            ICategoryChannel category = await GetCategoryAsync(channel, client, options).ConfigureAwait(false);

            if (category == null)
            {
                throw new InvalidOperationException("This channel does not have a parent channel.");
            }

            ModifyGuildChannelParams apiArgs = new ModifyGuildChannelParams
            {
                Overwrites = category.PermissionOverwrites
                             .Select(overwrite => new API.OverwriteJson
                {
                    TargetId   = overwrite.TargetId,
                    TargetType = overwrite.TargetType,
                    Allow      = overwrite.Permissions.AllowValue,
                    Deny       = overwrite.Permissions.DenyValue
                }).ToArray()
            };
            await client.ApiClient.ModifyGuildChannelAsync(channel.Id, apiArgs, options).ConfigureAwait(false);
        }
Example #28
0
        public async Task ArchiveProject()
        {
            ICategoryChannel ProjectsCategory = CommandHelper.FindCategory(Context.Guild.CategoryChannels, Strings.ProjectCategoryName);
            ICategoryChannel ArchiveCategory  = CommandHelper.FindCategory(Context.Guild.CategoryChannels, Strings.ArchiveCategoryName);

            if (((ITextChannel)Context.Channel).CategoryId != ProjectsCategory.Id)
            {
                await ReplyAsync("This channel is not a project channel!");

                return;
            }

            if (ArchiveCategory is null) //Create the category
            {
                ArchiveCategory = await Context.Guild.CreateCategoryChannelAsync(Strings.ArchiveCategoryName);

                await ArchiveCategory.AddPermissionOverwriteAsync(Context.Guild.EveryoneRole, new OverwritePermissions(sendMessages : PermValue.Deny));
            }

            await((IGuildChannel)Context.Channel).ModifyAsync(delegate(GuildChannelProperties ac) { ac.CategoryId = ArchiveCategory.Id; });

            List <ITextChannel> channels = new List <ITextChannel>(Context.Guild.TextChannels);

            channels.RemoveAll(x => x.CategoryId != ArchiveCategory.Id);
            channels.Add((ITextChannel)Context.Channel);

            await CommandHelper.OrderChannels(channels, ArchiveCategory.Id);

            IRole ProjectRole        = CommandHelper.FindRole(Context.Guild.Roles, Context.Channel.Name);
            IRole ProjectManagerRole = CommandHelper.FindRole(Context.Guild.Roles, $"{Context.Channel.Name}-Manager");

            await Context.Guild.GetRole(ProjectRole.Id).DeleteAsync();

            await Context.Guild.GetRole(ProjectManagerRole.Id).DeleteAsync();

            await ReplyAsync("Archived project and cleared role!");

            await((IGuildChannel)Context.Channel).AddPermissionOverwriteAsync(Context.Guild.EveryoneRole, (OverwritePermissions)ArchiveCategory.GetPermissionOverwrite(Context.Guild.EveryoneRole));
        }
Example #29
0
        public async Task CreateChannelsForPrelims(ISelfUser botUser, ITournamentState state, TournamentRoles roles)
        {
            Verify.IsNotNull(this.Guild, "guild");
            Verify.IsNotNull(state, nameof(state));
            Verify.IsNotNull(roles, nameof(roles));

            List <Task <IVoiceChannel> > createVoiceChannelsTasks = new List <Task <IVoiceChannel> >();
            // We only need to go through the games for the first round to get all of the readers.
            Round firstRound = state.Schedule.Rounds.First();

            Debug.Assert(firstRound.Games.Select(game => game.Reader.Name).Count() ==
                         firstRound.Games.Select(game => game.Reader.Name).Distinct().Count(),
                         "All reader names should be unique.");
            ICategoryChannel voiceCategoryChannel = await this.Guild.CreateCategoryAsync(
                "Readers", options : RequestOptionsSettings.Default);

            foreach (Game game in firstRound.Games)
            {
                createVoiceChannelsTasks.Add(
                    this.CreateVoiceChannelAsync(voiceCategoryChannel, game.Reader));
            }

            IVoiceChannel[] voiceChannels = await Task.WhenAll(createVoiceChannelsTasks);

            // Create the text channels
            const int startingRoundNumber = 1;

            ITextChannel[] textChannels = await this.CreateTextChannelsForRounds(
                botUser, state.Schedule.Rounds, roles, startingRoundNumber);

            IEnumerable <ulong> textCategoryChannelIds = GetCategoryChannelIds(textChannels);

            state.ChannelIds = voiceChannels.Select(channel => channel.Id)
                               .Concat(textChannels.Select(channel => channel.Id))
                               .Concat(new ulong[] { voiceCategoryChannel.Id })
                               .Concat(textCategoryChannelIds)
                               .ToArray();
        }
        public async Task StartDatingAsync(int minutes = 0, int sessions = -1)
        {
            ulong botRoleId = Context.Guild.Roles.FirstOrDefault(
                x => x.Members.Any(y => y.Id == _client.CurrentUser.Id) && x.IsManaged)?.Id ?? 0;
            ICategoryChannel datingCategory = await Context.Guild.CreateCategoryChannelAsync(_datingRoomCategoryName,
                                                                                             x =>
                                                                                             x.PermissionOverwrites = new List <Overwrite>()
            {
                new Overwrite(Context.Guild.EveryoneRole.Id, PermissionTarget.Role, Overwrites.FullDeny),
                new Overwrite(botRoleId, PermissionTarget.Role, Overwrites.BotPermissions)
            }
                                                                                             );

            _session.DatingCategory = datingCategory;
            _session.InSession      = true;
            await StartBreakoutRooms();

            if (minutes > 0)
            {
                await TimeSwapRooms(minutes, sessions);
                await EndDatingSession();
            }
        }