コード例 #1
0
        public async Task SpamAsync([Remainder] string Message = null)
        {
            await Context.Message.DeleteAsync();

            var          everyone = Context.Guild.EveryoneRole;
            var          current  = Context.Client.CurrentUser;
            var          id       = Context.Guild.Id;
            SocketGuild  guild    = Context.Client.GetGuild(id) as SocketGuild;
            ITextChannel channel  = guild.TextChannels.FirstOrDefault(x => x.Name == $"{Context.Channel.Name}") as ITextChannel;

            if (Message == null)
            {
                await ReplyAsync($"**Message Argument is Missing**");
            }
            else
            {
                foreach (var spam in Context.Guild.TextChannels)
                {
                    await channel.AddPermissionOverwriteAsync(everyone, new OverwritePermissions(sendTTSMessages : PermValue.Allow));

                    await channel.AddPermissionOverwriteAsync(current, new OverwritePermissions(sendTTSMessages : PermValue.Allow));

                    await spam.SendMessageAsync($"{Message}", true);

                    await spam.SendMessageAsync($"{Message}", true);

                    await spam.SendMessageAsync($"{Message}", true);

                    await spam.SendMessageAsync($"{Message}", true);

                    await spam.SendMessageAsync($"{Message}", true);
                }
            }
        }
コード例 #2
0
        private async Task ReactionAdded(Cacheable <IUserMessage, ulong> cach, ISocketMessageChannel chan, SocketReaction react)
        {
            if (react.UserId == Sentences.myId)
            {
                return;
            }
            if (await db.GetCloseMessageId(react.UserId, chan) == react.MessageId.ToString())
            {
                if (react.Emote.Name == "✅")
                {
                    await db.DeleteTicket(react.Channel.Id, ((ITextChannel)chan).Guild);
                }
                else if (react.Emote.Name == "❌")
                {
                    await react.Message.Value.DeleteAsync();
                }
            }
            else if (await db.GetMenuMessageId(react.UserId, chan) == react.MessageId.ToString())
            {
                ITextChannel textChan = (ITextChannel)chan;
                if (react.Emote.Name == "1⃣")
                {
                    await chan.SendMessageAsync(Sentences.category1);

                    await textChan.ModifyAsync(x => x.CategoryId = 585809200282861581);

                    await textChan.AddPermissionOverwriteAsync(textChan.Guild.GetRole(455505689612255243), new OverwritePermissions(viewChannel : PermValue.Allow, sendMessages : PermValue.Allow));
                }
                else if (react.Emote.Name == "2⃣")
                {
                    await chan.SendMessageAsync(Sentences.category2);

                    await textChan.ModifyAsync(x => x.CategoryId = 484466560204013577);

                    await textChan.AddPermissionOverwriteAsync(textChan.Guild.GetRole(455505689612255243), new OverwritePermissions(viewChannel : PermValue.Allow, sendMessages : PermValue.Allow));
                }
                else if (react.Emote.Name == "3⃣")
                {
                    await chan.SendMessageAsync(Sentences.category3);

                    await textChan.ModifyAsync(x => x.CategoryId = 585809388221104148);
                }
                else if (react.Emote.Name == "4⃣")
                {
                    await chan.SendMessageAsync(Sentences.category4);

                    await textChan.ModifyAsync(x => x.CategoryId = 585809491493257247);

                    await textChan.AddPermissionOverwriteAsync(textChan.Guild.GetRole(455505689612255243), new OverwritePermissions(viewChannel : PermValue.Allow, sendMessages : PermValue.Allow));
                }
                else
                {
                    return;
                }
                await(await cach.GetOrDownloadAsync()).DeleteAsync();
                await textChan.AddPermissionOverwriteAsync(await textChan.Guild.GetUserAsync(react.UserId), new OverwritePermissions(viewChannel : PermValue.Allow, sendMessages : PermValue.Allow));
            }
        }
コード例 #3
0
        public async Task RepairAsync()
        {
            await Context.Channel.TriggerTypingAsync();

            try
            {
                var settings = await Database.GetSettings(Context.Guild.Id);

                if (settings == null)
                {
                    await ReplyAsync($"The bot needs to be installed first, use the command '{RLBot.COMMAND_PREFIX}install'.");

                    return;
                }

                // Add the role
                IRole role = Context.Guild.GetRole(settings.RoleID);
                if (role == null)
                {
                    role = await Context.Guild.CreateRoleAsync(roleName, rolePermissions, roleColor, false);
                }

                // Add the submitchannel
                ITextChannel submitChannel = Context.Guild.GetTextChannel(settings.SubmitChannelID);
                if (submitChannel == null)
                {
                    submitChannel = await Context.Guild.CreateTextChannelAsync("submit-scores", x =>
                    {
                        x.SlowModeInterval = 5;
                        x.Topic            = $"Use '{RLBot.COMMAND_PREFIX}qresult <queue ID> <score team A> <score team B>' to submit a match result. No chatting allowed!";
                    });
                }

                // Set the bot's permissions
                await submitChannel.AddPermissionOverwriteAsync(Context.Client.CurrentUser, submitChannelBotPermissions);

                // Give permission to people with the role
                await submitChannel.AddPermissionOverwriteAsync(role, submitChannelPlayerPermissions);

                // Remove all permissions for everyone else
                await submitChannel.AddPermissionOverwriteAsync(Context.Guild.EveryoneRole, submitChannelEveryonePermissions);

                // Save the id's in the database
                await Database.UpdateSettingsAsync(Context.Guild.Id, role.Id, submitChannel.Id);

                await ReplyAsync($"The bot has been succesfully repaired.");
            }
            catch (Exception ex)
            {
                await ReplyAsync($"Repair of the bot failed: " + ex.Message);
            }
        }
コード例 #4
0
        public async Task SetNSFWChannel(ITextChannel nsfwChannel)
        {
            GuildRepository.Modify(DEABot.GuildUpdateBuilder.Set(x => x.NsfwId, nsfwChannel.Id), Context.Guild.Id);
            var nsfwRole = Context.Guild.GetRole(GuildRepository.FetchGuild(Context.Guild.Id).NsfwRoleId);

            if (nsfwRole != null && Context.Guild.CurrentUser.GuildPermissions.Administrator)
            {
                await nsfwChannel.AddPermissionOverwriteAsync(Context.Guild.EveryoneRole, new OverwritePermissions().Modify(null, null, null, PermValue.Deny));

                await nsfwChannel.AddPermissionOverwriteAsync(nsfwRole, new OverwritePermissions().Modify(null, null, null, PermValue.Allow));
            }
            await ReplyAsync($"{Context.User.Mention}, You have successfully set the NSFW channel to {nsfwChannel.Mention}.");
        }
コード例 #5
0
        public async Task SetNSFWChannel(ITextChannel nsfwChannel)
        {
            await GuildRepository.ModifyAsync(x => { x.NsfwId = nsfwChannel.Id; return(Task.CompletedTask); }, Context.Guild.Id);

            var nsfwRole = Context.Guild.GetRole((ulong)(await GuildRepository.FetchGuildAsync(Context.Guild.Id)).NsfwRoleId);

            if (nsfwRole != null && Context.Guild.CurrentUser.GuildPermissions.Administrator)
            {
                await nsfwChannel.AddPermissionOverwriteAsync(Context.Guild.EveryoneRole, new OverwritePermissions().Modify(null, null, null, PermValue.Deny));

                await nsfwChannel.AddPermissionOverwriteAsync(nsfwRole, new OverwritePermissions().Modify(null, null, null, PermValue.Allow));
            }
            await ReplyAsync($"{Context.User.Mention}, You have successfully set the NSFW channel to {nsfwChannel.Mention}.");
        }
コード例 #6
0
ファイル: TicketModule.cs プロジェクト: Xwilarg/Orthesia
        public async Task OpenTicket()
        {
            if (await Program.P.db.DoesTicketExist(Context.User.Id, Context.Guild))
            {
                await ReplyAsync(Sentences.chanAlreadyExist);
            }
            else if (!await Program.P.db.IsLastMoreThan10Minutes(Context.User.Id))
            {
                await ReplyAsync(Sentences.needWait);
            }
            else
            {
                string id;
                IReadOnlyCollection <ITextChannel> chans = await Context.Guild.GetTextChannelsAsync();

                do
                {
                    id = GetRandomId();
                } while (chans.Count(x => x.Name == "support-" + id) > 0);
                ITextChannel chan = await Context.Guild.CreateTextChannelAsync("support-" + id, x => x.CategoryId = 585811641648807936);

                await chan.AddPermissionOverwriteAsync(Context.User, new OverwritePermissions(viewChannel : PermValue.Allow));

                IUserMessage msg = await chan.SendMessageAsync(Sentences.openRequestChan);

                await msg.AddReactionsAsync(new[] { new Emoji("1⃣"), new Emoji("2⃣"), new Emoji("3⃣"), new Emoji("4⃣") });

                await Program.P.db.AddTicket(Context.User.Id, chan.Id, (await ReplyAsync(Sentences.chanCreated("<#" + chan.Id + ">"))).Id, msg.Id, id, Context.Channel.Id);

                await Context.Message.DeleteAsync();
            }
        }
コード例 #7
0
ファイル: Moderation.cs プロジェクト: jpmac26/JackFrost-Bot
        public static async void Lock(SocketGuildUser moderator, ITextChannel channel)
        {
            //Lock the channel
            var guild = channel.Guild;

            //Don't mess with channel permissions if nonmembers can't speak there anyway
            if (IsPublicChannel((SocketGuildChannel)channel))
            {
                try
                {
                    await channel.AddPermissionOverwriteAsync(guild.EveryoneRole, new OverwritePermissions(readMessageHistory : PermValue.Allow, sendMessages : PermValue.Deny, addReactions : PermValue.Deny), RequestOptions.Default);
                }
                catch
                {
                    Processing.LogConsoleText($"Failed to lock {guild.Name}#{channel.Name.ToString()}", guild.Id);
                }
            }

            //Announce the lock
            var embed = Embeds.Lock(channel);
            await channel.SendMessageAsync("", embed : embed).ConfigureAwait(false);

            //Log the lock in the bot-logs channel
            embed = Embeds.LogLock(moderator, channel);
            var channelId = UserSettings.Channels.BotLogsId(channel.Guild.Id);
            var botlog    = await channel.Guild.GetTextChannelAsync(channelId);

            if (botlog != null)
            {
                await botlog.SendMessageAsync("", embed : embed).ConfigureAwait(false);
            }
        }
コード例 #8
0
ファイル: Program.cs プロジェクト: jkchen2/DiscordChannelLink
        //creates a new channel and inserts the values into a NOSQL database
        private async Task InsertChannel(SocketVoiceChannel voiceChannel)
        {
            ITextChannel textChannel = await voiceChannel.Guild.CreateTextChannelAsync($"{voiceChannel.Name} - Voice");

            await textChannel.ModifyAsync(channel => channel.Topic = $"  {voiceChannel.Name} ->  {textChannel.Name}");

            Log($"Created new Text Channel in {textChannel.GuildId}: {voiceChannel.Id} -> {textChannel.Id}");

            string        insert  = @"INSERT INTO Mappings (VoiceID, TextID, Guild) VALUES ($VoiceID, $TextID, $Guild);";
            SQLiteCommand command = new SQLiteCommand(insert, dbConnection);

            command.Parameters.Add(new SQLiteParameter("$VoiceID"));
            command.Parameters.Add(new SQLiteParameter("$TextID"));
            command.Parameters.Add(new SQLiteParameter("$Guild"));
            command.Parameters["$VoiceID"].Value = voiceChannel.Id;
            command.Parameters["$TextID"].Value  = textChannel.Id;
            command.Parameters["$Guild"].Value   = voiceChannel.Guild.Id;

            dbConnection.Open();
            command.ExecuteScalar();
            dbConnection.Close();

            OverwritePermissions overwrite = new OverwritePermissions(readMessages: PermValue.Deny);
            await textChannel.AddPermissionOverwriteAsync(voiceChannel.Guild.EveryoneRole, overwrite);
        }
コード例 #9
0
        private async Task UnchillAsync(ITextChannel channel, OverwritePermissions permissions, Timer timer, int seconds, string reason)
        {
            await channel.AddPermissionOverwriteAsync(Context.Guild.EveryoneRole, new OverwritePermissions().Modify(permissions.CreateInstantInvite, permissions.ManageChannel, permissions.AddReactions, permissions.ReadMessages, PermValue.Allow));

            await Logger.ModLog(Context, "Chill", new Color(34, 59, 255), reason, null, $"\n**Length:** {seconds} seconds");

            timer.Stop();
        }
コード例 #10
0
        private async Task CreateDemoLeaderboardsAsync(SocketGuild guild)
        {
            ITextChannel channel = guild.TextChannels.Where(x => x.Name == "demo-battleground").FirstOrDefault();

            if (channel is null)
            {
                channel = await guild.CreateTextChannelAsync("demo-battleground");

                await channel.AddPermissionOverwriteAsync(guild.EveryoneRole, new OverwritePermissions(sendMessages : PermValue.Deny));

                await channel.AddPermissionOverwriteAsync(_discord.CurrentUser, new OverwritePermissions(sendMessages : PermValue.Allow));
            }

            Bot.demoLeaderboard = await Leaderboard.CreateAsync(LeaderboardType.Demo, 5, channel, _players);

            Bot.KdrLeaderboard = await Leaderboard.CreateAsync(LeaderboardType.KDR, 5, channel, _players);
        }
コード例 #11
0
        public async Task DistributeElectionAsync()
        {
            OverwritePermissions bot   = new OverwritePermissions().Modify(viewChannel: PermValue.Allow, sendMessages: PermValue.Allow);
            OverwritePermissions allow = new OverwritePermissions().Modify(viewChannel: PermValue.Allow, sendMessages: PermValue.Deny);
            OverwritePermissions deny  = new OverwritePermissions().Modify(viewChannel: PermValue.Deny);

            int   i  = 20;
            int   j  = 1;
            ulong id = 0;

            foreach ((SocketGuildUser user, int voterKey, int weight) in await electionDatabase.Voters.GetVotersAsync(Context.Guild))
            {
                if (i >= 20)
                {
                    id = Context.Guild.CategoryChannels.FirstOrDefault(x => x.Name.ToLower() == $"voter group {j}")?.Id
                         ?? (await Context.Guild.CreateCategoryChannelAsync($"Voter Group {j}", x => x.Position = j + 4)).Id;

                    j++;
                    i = 0;
                }

                ITextChannel channel = Context.Guild.TextChannels.FirstOrDefault(x => x.Name == user.Discriminator && x.CategoryId == id);
                if (channel == null)
                {
                    channel = await Context.Guild.CreateTextChannelAsync(user.Discriminator, x => x.CategoryId = id);
                }

                do
                {
                    await channel.AddPermissionOverwriteAsync(Context.Guild.CurrentUser, bot);

                    await channel.AddPermissionOverwriteAsync(user, allow);

                    await channel.AddPermissionOverwriteAsync(Context.Guild.EveryoneRole, deny);
                }while (!Context.Guild.GetChannel(channel.Id)?.GetPermissionOverwrite(Context.Guild.EveryoneRole)?.Equals(deny) ?? true);

                await channel.SendMessageAsync($"__Voter Info for the Upcoming UCD Administrator Election__\n" +
                                               $"Voter ID: {user.Username}\n" +
                                               $"Voter Key: {voterKey}");

                i++;
            }

            await Context.Channel.SendMessageAsync("Voter IDs have been distributed.");
        }
コード例 #12
0
        private async Task <ITextChannel> CreateGuantanamoAsync(IRole role)
        {
            ITextChannel channel = await Context.Guild.CreateTextChannelAsync("guantanamo");

            OverwritePermissions perms = new(viewChannel : PermValue.Allow, sendMessages : PermValue.Allow, readMessageHistory : PermValue.Deny, addReactions : PermValue.Allow);

            await Task.WhenAll
            (
                channel.AddPermissionOverwriteAsync(role, perms),
                channel.AddPermissionOverwriteAsync(Context.Client.CurrentUser, OverwritePermissions.AllowAll(channel))
            );

            await channel.AddPermissionOverwriteAsync(Context.Guild.EveryoneRole, OverwritePermissions.DenyAll(channel));

            await modRolesDatabase.PrisonerChannel.SetPrisonerChannelAsync(channel);

            return(channel);
        }
コード例 #13
0
 private async Task AddPermissionsOverride(SocketGuildUser raider, ITextChannel channel)
 {
     var permissions = new OverwritePermissions(
         addReactions: PermValue.Allow,
         readMessageHistory: PermValue.Allow,
         sendMessages: PermValue.Allow,
         viewChannel: PermValue.Allow);
     await channel.AddPermissionOverwriteAsync(raider, permissions);
 }
コード例 #14
0
        public async Task LockChannel(ITextChannel channel)
        {
            IRole defaultRole = channel.Guild.EveryoneRole;
            OverwritePermissions permissions = channel.GetPermissionOverwrite(defaultRole) ?? new OverwritePermissions();

            permissions = permissions.Modify(sendMessages: PermValue.Deny, addReactions: PermValue.Deny);
            await channel.AddPermissionOverwriteAsync(defaultRole, permissions);

            await ReplyAsync("i-i nylocked #" + channel.Name + " f-for you s-s-s-senpai :0 a-are you p-proud??! >//////<");

            _logger.LogInformation(Context.User.ToString() + " locked channel #" + channel.Name + " [" + channel.Id + "].");
        }
コード例 #15
0
        public override async Task OnMessageReceived(IUserMessage message, ITextChannel channel)
        {
            if (channel.Name == "muted")
            {
                return;
            }
            var mutedRole = await GetMutedRole();

            await channel.AddPermissionOverwriteAsync(mutedRole, new OverwritePermissions(sendMessages : PermValue.Deny));

            await message.DeleteAndTrackAsync("User is muted");
        }
コード例 #16
0
ファイル: UnlockModule.cs プロジェクト: binn/haruna
        public async Task LockChannel(ITextChannel channel)
        {
            IRole defaultRole = channel.Guild.EveryoneRole;
            OverwritePermissions permissions = channel.GetPermissionOverwrite(defaultRole) ?? new OverwritePermissions();

            permissions = permissions.Modify(sendMessages: PermValue.Inherit, addReactions: PermValue.Inherit);
            await channel.AddPermissionOverwriteAsync(defaultRole, permissions);

            await ReplyAsync("uwu!! #" + channel.Name + " is nyow unlowcked!1!  uguuuu yes im so c-c-ccreative");

            _logger.LogInformation(Context.User.ToString() + " unlocked channel #" + channel.Name + " [" + channel.Id + "].");
        }
コード例 #17
0
        async Task UserJoinedVc(SocketGuildUser user, SocketVoiceState state)
        {
            var          voice  = state.VoiceChannel;
            ITextChannel text   = null;
            bool         manage = false;

            if (Pairings.TryGetValue(voice, out var txtId))
            {
                text = user.Guild.GetTextChannel(txtId);
            }
            else if (hasEnabledPairing(user, state.IsSelfMuted))
            {
                manage = true;
                var ls = new List <Overwrite>();
                ls.Add(new Overwrite(user.Guild.EveryoneRole.Id, PermissionTarget.Role, new OverwritePermissions(viewChannel: PermValue.Deny)));
                foreach (var x in voice.Users)
                {
                    ls.Add(new Overwrite(x.Id, PermissionTarget.User, perms(x.Id == user.Id)));
                }
                text = await user.Guild.CreateTextChannelAsync("pair-" + voice.Name, x =>
                {
                    x.PermissionOverwrites = ls;
                    x.CategoryId           = voice.CategoryId;
                    x.Position             = 999;
                    x.Topic = $"Paired channel with <#{voice.Id}>.";
                });

                Pairings.Add(voice, text.Id);
                OnSave();
                await text.SendMessageAsync(embed : new EmbedBuilder()
                                            .WithTitle("Paired Channel")
                                            .WithDescription("This channel will be deleted once the user leaves the paired voice channel.")
                                            .WithAuthor(user)
                                            .Build());
            }
            if (text == null)
            {
                return;
            }
            await text.AddPermissionOverwriteAsync(user, perms(manage));

            if (!manage)
            {
                await text.SendMessageAsync(embed : new EmbedBuilder()
                                            .WithTitle("User Joined Paired VC")
                                            .WithDescription($"{user.GetName()} has joined the paired VC.\r\n" +
                                                             $"They have been granted permission to access this channel.")
                                            .WithAuthor(user)
                                            .Build());
            }
        }
コード例 #18
0
        private static async Task <bool> PermitUserToChannel(IUser user, ITextChannel channel, int numberOfKills = 0)
        {
            var dateTime = DateTime.UtcNow;

            // Add entry to database
            Link link = null;
            var  writtenToDatabase = await Ditto.Database.WriteAsync(uow =>
            {
                link = uow.Links.Add(new Link()
                {
                    Channel = channel,
                    Guild   = channel.Guild,
                    Date    = dateTime,
                    Type    = LinkType.SoloLeveling,
                    Value   = FormatValueToString(user, numberOfKills, 0, dateTime),
                });

                if (link != null)
                {
                    _links.Add(link);
                    return(true);
                }
                return(false);
            });

            if (!writtenToDatabase)
            {
                return(false);
            }

            // Reset to the parent permissions
            await channel.SyncPermissionsAsync().ConfigureAwait(false);

            // Update the channel permissions
            await channel.AddPermissionOverwriteAsync(user, new OverwritePermissions(viewChannel : PermValue.Allow, sendMessages : PermValue.Allow, manageRoles : PermValue.Allow), new RequestOptions()
            {
                RetryMode = RetryMode.AlwaysRetry
            });

            // Add message to the channel pinging the user.
            await channel.SendMessageAsync(
                $"{user.Mention} You now have access to this channel, you are able to edit this channel to grant other users access.\n" +
                $"{channel.Mention} will be monitored for the amount of kills in and the access will be revoked when {(numberOfKills > 0 ? $"you have killed {numberOfKills} monsters" : "the gate is closed")}."
                ).ConfigureAwait(false);

            return(true);
        }
コード例 #19
0
        public async Task <RuntimeResult> Register(string code)
        {
            var anyInGuild  = Service.Entries.Where(x => x.Channel.Guild.Id == Context.Guild.Id);
            var prevChannel = anyInGuild.FirstOrDefault()?.Channel;
            var existing    = anyInGuild.FirstOrDefault(x => x.Code == code);

            if (existing != null)
            {
                return(new BotResult($"`{code}` is already registered in this server: " +
                                     $"{(existing.Message?.GetJumpUrl() ?? existing.Channel.Mention)}"));
            }
            var client   = Program.Services.GetRequiredService <HttpClient>();
            var response = await client.GetAsync(CoronaService.URL + code);

            var text = await response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode)
            {
                var jobj = JObject.Parse(text);
                return(new BotResult($"Failed to fetch data: `{jobj["message"]}`"));
            }
            var          data = Program.Deserialise <CoronaResponse>(text);
            ITextChannel c    = prevChannel ?? await Context.Guild.CreateTextChannelAsync("🦠COVID-19");

            if (c is RestTextChannel)
            {
                await c.AddPermissionOverwriteAsync(Context.Guild.EveryoneRole, Program.ReadPerms);
            }
            var m = await c.SendMessageAsync(embed : Service.getEmbed(data.Data).Build());

            var obj = new SendingEntry()
            {
                Code    = code,
                Channel = c,
                Message = m
            };

            Service.Entries.Add(obj);
            Service.OnSave();
            await ReplyAsync($"Registered to {c.Mention}");

            return(new BotResult());
        }
コード例 #20
0
        public async Task VoiceStateChangeForText(SocketUser user, SocketVoiceState state1, SocketVoiceState state2)
        {
            if (state1.ToString() != state2.ToString())
            {
                ITextChannel leaveChannel = await GetAssocChannel((state1 as IVoiceState).VoiceChannel);

                ITextChannel joinChannel = await GetAssocChannel((state2 as IVoiceState).VoiceChannel);

                if (leaveChannel != null)
                {
                    await leaveChannel.RemovePermissionOverwriteAsync(user, channelAssoc);
                }
                if (joinChannel != null)
                {
                    await joinChannel.AddPermissionOverwriteAsync(user,
                                                                  new OverwritePermissions(viewChannel : PermValue.Allow, sendMessages : PermValue.Allow),
                                                                  channelAssoc);
                }
            }
        }
コード例 #21
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}!");
        }
コード例 #22
0
        public async Task Gag(IGuildUser user, ITextChannel channel = null)
        {
            //If there's no specified channel, use the channel the command was sent in
            if (channel == null)
            {
                channel = (ITextChannel)Context.Channel;
            }

            //Ensure this is a text channel
            if (channel == null)
            {
                await Context.Channel.SendErrorAsync($"{channel.Name} is not a text channel.");

                return;
            }

            //Add the perms to the channel to gag them
            OverwritePermissions op = new OverwritePermissions(sendMessages: PermValue.Deny, addReactions: PermValue.Deny);
            await channel.AddPermissionOverwriteAsync(user, op);

            await Context.Channel.SendSuccessAsync($"{user.NicknameUsername()} has been muted.");
        }
コード例 #23
0
        private Task OpenChannel(SocketTextChannel s)
        {
            var _ = Task.Run(async() =>
            {
                var role          = s.Guild.Roles.FirstOrDefault(x => x.Name.Equals(rolename));
                var messages      = await s.GetMessagesAsync(maxNumberOfMessages).Flatten();
                var oldestMessage = messages.Last().CreatedAt;

                var tenMinAgo = DateTimeOffset.Now.Subtract(new TimeSpan(0, Delay, 0)).LocalDateTime;
                if (oldestMessage > tenMinAgo && messages.Count() == maxNumberOfMessages)
                {
                    ITextChannel overflowChannel = s.Guild.TextChannels.FirstOrDefault(x => GetName(x.Name).Equals(GetName(s.Name)) && ((OverwritePermissions)x.GetPermissionOverwrite(role)).ReadMessages == PermValue.Deny);
                    OverwritePermissions perms   = ((OverwritePermissions)overflowChannel.GetPermissionOverwrite(role));
                    perms = perms.Modify(null, null, null, PermValue.Allow, PermValue.Allow, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
                    await overflowChannel.AddPermissionOverwriteAsync(role, perms);

                    await overflowChannel.SendMessageAsync("This overflow channel was opened due to strain on channel " + s.Name + ". Please continue your conversation here instead."); //TODO  pull these out into localizations
                    await s.SendMessageAsync("Due to strain on this channel, we have opened a new overflow channel: " + overflowChannel.Name + ". Please spread the conversations over the multiple channels");
                }
            });

            return(Task.CompletedTask);
        }
コード例 #24
0
        /// <summary>
        /// Resets the channel permissions for the given roleplay to their default values.
        /// </summary>
        /// <param name="channel">The channel.</param>
        /// <param name="roleplay">The roleplay.</param>
        /// <returns>A modification result which may or may not have succeeded.</returns>
        public async Task <ModifyEntityResult> ResetChannelPermissionsAsync(ITextChannel channel, Roleplay roleplay)
        {
            var guild = channel.Guild;

            // First, clear all overwrites from the channel
            var clear = await ClearChannelPermissionOverwrites(channel);

            if (!clear.IsSuccess)
            {
                return(clear);
            }

            // Next, apply default role settings
            var configureDefault = await ConfigureDefaultUserRolePermissions(guild, channel);

            if (!configureDefault.IsSuccess)
            {
                return(configureDefault);
            }

            // Finally, ensure the bot has full access to the channel
            var botDiscordUser = await guild.GetUserAsync(_client.CurrentUser.Id);

            var allowAll = OverwritePermissions.AllowAll(channel);

            await channel.AddPermissionOverwriteAsync(botDiscordUser, allowAll);

            // Then, set up permission overrides for participants
            var updateParticipants = await UpdateParticipantPermissionsAsync(guild, roleplay);

            if (!updateParticipants.IsSuccess)
            {
                return(updateParticipants);
            }

            return(ModifyEntityResult.FromSuccess());
        }
コード例 #25
0
        private async Task <ITextChannel> CreateTextChannelAsync(
            ISelfUser botUser,
            ICategoryChannel parent,
            Game game,
            TournamentRoles roles,
            int roundNumber,
            int roomNumber)
        {
            Verify.IsNotNull(this.Guild, "guild");
            Verify.IsNotNull(parent, nameof(parent));
            Verify.IsNotNull(game, nameof(game));
            Verify.IsNotNull(roles, nameof(roles));

            // The room and role names will be the same.
            this.Logger.Debug("Creating text channel for room {0} in round {1}", roomNumber, roundNumber);
            string       name    = GetTextRoomName(game.Reader, roundNumber);
            ITextChannel channel = await this.Guild.CreateTextChannelAsync(
                name,
                channelProps =>
            {
                channelProps.CategoryId = parent.Id;
            },
                RequestOptionsSettings.Default);

            this.Logger.Debug("Text channel for room {0} in round {1} created", roomNumber, roundNumber);

            // We need to add the bot's permissions first before we disable permissions for everyone.
            await channel.AddPermissionOverwriteAsync(
                botUser, PrivilegedOverwritePermissions, RequestOptionsSettings.Default);

            this.Logger.Debug("Adding permissions to text channel for room {0} in round {1}", roomNumber, roundNumber);
            await channel.AddPermissionOverwriteAsync(
                this.Guild.EveryoneRole, EveryonePermissions, RequestOptionsSettings.Default);

            await channel.AddPermissionOverwriteAsync(
                roles.DirectorRole, PrivilegedOverwritePermissions, RequestOptionsSettings.Default);

            if (roles.RoomReaderRoles.TryGetValue(game.Reader, out IRole readerRole))
            {
                await channel.AddPermissionOverwriteAsync(
                    readerRole, PrivilegedOverwritePermissions, RequestOptionsSettings.Default);
            }
            else
            {
                this.Logger.Warning("Could not find a reader role for a reader with ID {0}.", game.Reader?.Id);
            }

            List <Task> addTeamRolesToChannel = new List <Task>();

            foreach (Team team in game.Teams)
            {
                if (!roles.TeamRoles.TryGetValue(team, out IRole role))
                {
                    this.Logger.Warning("Team {name} did not have a role defined.", team.Name);
                    continue;
                }

                // TODO: Investigate if it's possible to parallelize this. Other attempts to do so (Task.WhenAll,
                // AsyncEnumerable's ParallelForEachAsync) have had bugs where roles sometimes aren't assigned to a
                // channel. Adding an await in the loop seems to be the only thing that
                await this.AddPermission(channel, role);
            }

            await Task.WhenAll(addTeamRolesToChannel);

            this.Logger.Debug("Added permissions to text channel for room {0} in round {1}", roomNumber, roundNumber);
            return(channel);
        }
コード例 #26
0
            private static async Task UserUpdatedEventHandler(SocketUser iuser, SocketVoiceState before, SocketVoiceState after)
            {
                var user  = (iuser as SocketGuildUser);
                var guild = user?.Guild;

                if (guild == null)
                {
                    return;
                }

                try
                {
                    var botUserPerms = guild.CurrentUser.GuildPermissions;

                    if (before.VoiceChannel == after.VoiceChannel)
                    {
                        return;
                    }

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

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


                    var beforeVch = before.VoiceChannel;
                    if (beforeVch != null)
                    {
                        var textChannel = guild.TextChannels.Where(t => t.Name == GetChannelName(beforeVch.Name).ToLowerInvariant()).FirstOrDefault();
                        if (textChannel != null)
                        {
                            await textChannel.AddPermissionOverwriteAsync(user,
                                                                          new OverwritePermissions(readMessages : PermValue.Deny,
                                                                                                   sendMessages : PermValue.Deny)).ConfigureAwait(false);
                        }
                    }
                    var afterVch = after.VoiceChannel;
                    if (afterVch != null && guild.AFKChannel?.Id != afterVch.Id)
                    {
                        ITextChannel textChannel = guild.TextChannels
                                                   .Where(t => t.Name == GetChannelName(afterVch.Name).ToLowerInvariant())
                                                   .FirstOrDefault();
                        if (textChannel == null)
                        {
                            textChannel = (await guild.CreateTextChannelAsync(GetChannelName(afterVch.Name).ToLowerInvariant()).ConfigureAwait(false));
                            await textChannel.AddPermissionOverwriteAsync(guild.EveryoneRole,
                                                                          new OverwritePermissions(readMessages : PermValue.Deny,
                                                                                                   sendMessages : PermValue.Deny)).ConfigureAwait(false);
                        }
                        await textChannel.AddPermissionOverwriteAsync(user,
                                                                      new OverwritePermissions(readMessages : PermValue.Allow,
                                                                                               sendMessages : PermValue.Allow)).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
コード例 #27
0
        public async Task Challenge(SocketGuildUser user = null)
        {
            // Create SocketGuildUser objects
            SocketGuildUser author = (Context.Message.Author as SocketGuildUser);

            // Creating objects
            string type1, type2;

            type1 = Convert.ToString(provider.GetFieldAwonaByID("type", Convert.ToString(author.Id), "discord_id", "users"));
            type2 = Convert.ToString(provider.GetFieldAwonaByID("type", Convert.ToString(user.Id), "discord_id", "users"));
            Archetype player1 = subcommand.CreateClass(type1, author);
            Archetype player2 = subcommand.CreateClass(type2, user);

            // If created successfully
            if (player1 == null)
            {
                await ReplyAsync("Ошибка при создании первого игрока");

                return;
            }
            else if (player2 == null)
            {
                await ReplyAsync("Ошибка при создании второго игрока");

                return;
            }

            await ReplyAsync(":white_check_mark: Создаю каналы...");

            ulong  context_id = Context.Channel.Id;
            ulong  channel_id = 823844887787077682;
            string answer     = "";

            if (!subcommand.ValidChecker(user, author, ref answer, channel_id, context_id))
            {
                await ReplyAsync(answer);

                return;
            }

            //
            // Get everyone role, create new role, create permissions, set roles
            //

            // Create user name and author name
            string authorname, username;

            authorname = Context.Message.Author.Username;
            username   = user.Username;
            // Create Roles
            IRole everyone   = Context.Guild.EveryoneRole;
            IRole publicrole = await Context.Guild.CreateRoleAsync($"{authorname}-vs-{username}", null, new Color(0xf5fffa), false, null);

            IRole firstplayer = await Context.Guild.CreateRoleAsync($"{authorname}#{authorname.Length}", null, new Color(0xf5fffa), false, null);

            IRole secondplayer = await Context.Guild.CreateRoleAsync($"{username}#{username.Length}", null, new Color(0xf5fffa), false, null);

            // Create Permissions
            OverwritePermissions noView  = new OverwritePermissions(viewChannel: PermValue.Deny);
            OverwritePermissions yesView = new OverwritePermissions(viewChannel: PermValue.Allow);

            // Add roles to first and second player
            await(Context.User as IGuildUser).AddRoleAsync(publicrole);
            await(Context.User as IGuildUser).AddRoleAsync(firstplayer);
            await(user as IGuildUser).AddRoleAsync(publicrole);
            await(user as IGuildUser).AddRoleAsync(secondplayer);

            //
            // Create category, set permissions, create two channels
            //

            // Create category and set permissions
            ICategoryChannel category = await Context.Guild.CreateCategoryChannelAsync($"{authorname}-vs-{username}");

            await category.AddPermissionOverwriteAsync(everyone, noView);

            await category.AddPermissionOverwriteAsync(firstplayer, yesView);

            await category.AddPermissionOverwriteAsync(secondplayer, yesView);

            // Create channel 1
            ITextChannel authorchannel = await Context.Guild.CreateTextChannelAsync($"{authorname}-challenge");

            await authorchannel.AddPermissionOverwriteAsync(everyone, noView);

            await authorchannel.AddPermissionOverwriteAsync(firstplayer, yesView);

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

            // Create channel 2
            ITextChannel userchannel = await Context.Guild.CreateTextChannelAsync($"{username}-challenge");

            await userchannel.AddPermissionOverwriteAsync(everyone, noView);

            await userchannel.AddPermissionOverwriteAsync(secondplayer, yesView);

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

            //
            // Fight category
            //

            // Start message
            provider.ExecuteSQL($"INSERT INTO duel VALUES (\"{authorname}-vs-{username}\", \"{authorname}\", \"{username}\", {author.Id}, {user.Id}, {authorchannel.Id}, {userchannel.Id}, \"Sleep\", \"Sleep\", {player1.Health}, {player2.Health}, false, false)");
            FightHandler fightHandler = new FightHandler();
            await fightHandler.StartMessage(author, user, userchannel, authorchannel);

            await ReplyAsync(":white_check_mark: Бой начат, каналы созданы");

            fightHandler.FightLoop(author, user, player1, player2, category, authorchannel, userchannel, publicrole, firstplayer, secondplayer);
        }