public async Task <ChannelPair?> GetOrCreateChannelPair(SocketGuild guild, string lang)
        {
            string safeLang      = GetSafeLangString(lang);
            string guildLang     = _serverConfig.GetLanguageForGuild(guild.Id);
            string safeGuildLang = GetSafeLangString(guildLang);

            if (_channelPairs.TryGetValue(safeLang, out var pair))
            {
                return(pair);
            }

            var category = guild.CategoryChannels.SingleOrDefault(a => a.Name == TranslationConstants.CategoryName);

            if (category == default)
            {
                throw new InvalidOperationException($"The channel category {TranslationConstants.CategoryName} does not exist");
            }

            var supportedLang = await _translation.IsLangSupported(lang);

            if (!supportedLang)
            {
                throw new LanguageNotSupportedException($"{lang} is not supported at this time.");
            }

            var fromLangName = $"{safeLang}-to-{safeGuildLang}";
            var toLangName   = $"{safeGuildLang}-to-{safeLang}";

            var fromLangChannel = await guild.CreateTextChannelAsync(fromLangName, p => p.CategoryId = category.Id);

            var toLangChannel = await guild.CreateTextChannelAsync(toLangName, p => p.CategoryId = category.Id);

            var localizedTopic = await _translation.GetTranslation(guildLang, lang, $"Responses will be translated to {guildLang} and posted in this channel's pair {toLangChannel.Mention}");

            await fromLangChannel.ModifyAsync(p => p.Topic = localizedTopic.Translated.Text);

            var unlocalizedTopic = $"Responses will be translated to {lang} and posted in this channel's pair {fromLangChannel.Mention}";
            await toLangChannel.ModifyAsync(p => p.Topic = unlocalizedTopic);

            pair = new ChannelPair
            {
                TranslationChannel = fromLangChannel,
                StandardLangChanel = toLangChannel
            };

            if (!_channelPairs.TryAdd(safeLang, pair))
            {
                _logger.LogWarning($"The channel pairs {{{fromLangName}, {toLangName}}} have already been tracked, cleaning up");
                await pair.TranslationChannel.DeleteAsync();

                await pair.StandardLangChanel.DeleteAsync();

                _channelPairs.TryGetValue(safeLang, out pair);
            }

            return(pair);
        }
        // 특정 이름을 가진 채널을 검색, 있을 경우 검색된 채널 반환, 없을 경우 생성한 후 생성한 채널 반환
        public async static Task <SocketTextChannel> CreateChannelIfNotExist(this SocketGuild guild, string name)
        {
            try
            {
                SocketTextChannel osuTrackerChannel = null;
                bool isThereOsuTrackerChannel       = false;

                IReadOnlyCollection <SocketTextChannel> channelList = guild.TextChannels;

                foreach (SocketTextChannel channel in channelList)
                {
                    if (channel.Name.ToLower() == name.ToLower())
                    {
                        isThereOsuTrackerChannel = true;
                        osuTrackerChannel        = channel;
                        break;
                    }
                }

                if (!isThereOsuTrackerChannel)
                {
                    ulong osuTrackerChannelId = (await guild.CreateTextChannelAsync("osu-tracker")).Id;
                    osuTrackerChannel = guild.GetTextChannel(osuTrackerChannelId);
                }

                return(osuTrackerChannel);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Esempio n. 3
0
        private async Task <ITextChannel> CreateApplicationChannel(SocketGuild guild, GuildTB dbentry)
        {
            logger.Log(new LogMessage(LogSeverity.Info, "State", $"Creating an application channel for {guild.Name}."));

            // find the correct category
            SocketCategoryChannel category = null;

            if (dbentry.Public != null)
            {
                foreach (var c in guild.CategoryChannels)
                {
                    if (c.Channels.Any(x => x.Id == dbentry.Public))
                    {
                        category = c;
                        break;
                    }
                }
            }

            try
            {
                // try to create a text channel
                return(await guild.CreateTextChannelAsync("Applications", (x) =>
                {
                    x.Topic = "Are you interested in our community? Write your application here!";
                    x.CategoryId = category?.Id;
                }));
            }
            catch (Exception e)
            {
                // report failure
                logger.Log(new LogMessage(LogSeverity.Error, "State", $"Attempted to create a channel for '{guild.Name}', but failed: {e.Message}\n{e.StackTrace}"));
                return(null);
            }
        }
Esempio n. 4
0
        /********************************************************
         * 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());
        }
Esempio n. 5
0
        /// <summary>
        /// Finds the first channel, which is private to everybody, but, viewable by admins.
        /// </summary>
        /// <param name="Guild"></param>
        ///
        /// <returns></returns>
        public static async Task <ITextChannel> findFirstAdminChannel(SocketGuild Guild)
        {
            var ME = Guild.CurrentUser;

            //Next, Just loop through channels, until we find a writeable channel.
            foreach (SocketTextChannel tch in Guild.Channels.OfType <SocketTextChannel>())
            {
                //Simple stupid way. //ToDo - Add better logic in the future.
                //Summary - Find a channel we can write to, but, everybody cannot.
                if (!PermissionHelper.TestPermission(tch, ChannelPermission.ReadMessages, Guild.EveryoneRole) &&
                    ME.GetPermissions(tch).SendMessages)
                {
                    return(tch);
                }
            }

            //If, there are no writable channels. Lets create one?
            if (ME.GuildPermissions.ManageChannels && ME.GuildPermissions.SendMessages)
            {
                var newCh = await Guild.CreateTextChannelAsync("Admins");

                //Block EVERYONE role from all permissions related to this channel.
                await newCh.AddPermissionOverwriteAsync(Guild.EveryoneRole, OverwritePermissions.DenyAll(newCh));

                //Grant the highest role, all permissions.
                await newCh.AddPermissionOverwriteAsync(Guild.Roles.First(), OverwritePermissions.AllowAll(newCh));

                await newCh.SendMessageAsync(@"I was unable to find a channel to which I could sent leadership/officer messages to... So, I created this channel automatically.
I will leadership-related messages into this channel.");

                return(newCh);
            }

            return(null);
        }
Esempio n. 6
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);
        }
Esempio n. 7
0
        private async Task <SocketChannel> GenerateChannelAsync(SocketGuild guild, string channelName)
        {
            var category = await GetBaseCategoryAsync(guild);

            var adminChannel = await guild.CreateTextChannelAsync(channelName, func : x => { x.CategoryId = category.Id; });

            return(await GetChannelAsync(guild, channelName));
        }
Esempio n. 8
0
        /// <summary>
        /// Creates an opt-in channel in the given guild.
        /// </summary>
        /// <param name="guildConnection">
        /// The connection to the guild this channel is being created in. May not be null.
        /// </param>
        /// <param name="guildData">Information about this guild. May not be null.</param>
        /// <param name="requestAuthor">The author of the channel create request. May not be null.</param>
        /// <param name="channelName">The requested name of the new channel. May not be null.</param>
        /// <param name="description">The requested description of the new channel.</param>
        /// <returns>The result of the request.</returns>
        public static async Task <CreateResult> Create(
            SocketGuild guildConnection,
            Guild guildData,
            SocketGuildUser requestAuthor,
            string channelName,
            string description)
        {
            ValidateArg.IsNotNullOrWhiteSpace(channelName, nameof(channelName));

            if (!guildData.OptinParentCategory.HasValue)
            {
                return(CreateResult.NoOptinCategory);
            }
            var optinsCategory = guildData.OptinParentCategory.GetValueOrDefault();

            // TODO: requestAuthor.Roles gets cached. How do I refresh this value so that it's accurate?

            var hasPermission = PermissionsUtilities.HasPermission(
                userRoles: requestAuthor.Roles.Select(x => new Snowflake(x.Id)),
                allowedRoles: guildData.OptinCreatorsRoles);

            if (!hasPermission)
            {
                return(CreateResult.NoPermissions);
            }

            var optinsCategoryConnection = guildConnection.GetCategoryChannel(optinsCategory.Value);
            var alreadyExists            = optinsCategoryConnection.Channels
                                           .Select(x => x.Name)
                                           .Any(x => string.Compare(x, channelName, ignoreCase: false) == 0);

            if (alreadyExists)
            {
                return(CreateResult.ChannelNameUsed);
            }

            var createdTextChannel = await guildConnection.CreateTextChannelAsync(channelName, settings =>
            {
                settings.CategoryId = optinsCategory.Value;
                settings.Topic      = description ?? string.Empty;
            }).ConfigureAwait(false);

            var createdRole = await guildConnection.CreateRoleAsync(
                name : OptinChannel.GetRoleName(createdTextChannel.Id),
                permissions : null,
                color : null,
                isHoisted : false,
                isMentionable : false)
                              .ConfigureAwait(false);

            var newPermissions = createdTextChannel.AddPermissionOverwriteAsync(
                role: createdRole,
                permissions: new OverwritePermissions(viewChannel: PermValue.Allow));

            await requestAuthor.AddRoleAsync(createdRole).ConfigureAwait(false);

            return(CreateResult.Success);
        }
Esempio n. 9
0
        private async Task <RestTextChannel> CreatePrivateGroupTextChannel(SocketGuild guild, string name, string description)
        {
            var             everyoneRole = guild.Roles.FirstOrDefault(r => r.Name == "@everyone");
            RestTextChannel channel      = await guild.CreateTextChannelAsync(name, (properties) => { properties.Topic = description; });

            await channel.AddPermissionOverwriteAsync(everyoneRole, OverwritePermissions.DenyAll(channel));

            return(channel);
        }
Esempio n. 10
0
 public static async Task <RestTextChannel> AddChannel(string name, SocketGuild guild, string topic = "", ulong catergory = 0, bool isNSFW = false)
 {
     return(await guild.CreateTextChannelAsync(name, x =>
     {
         x.Topic = topic;
         x.CategoryId = catergory;
         x.IsNsfw = isNSFW;
     }));
 }
Esempio n. 11
0
        public static async Task <ITextChannel> GetPickupQueuesChannel(SocketGuild guild)
        {
            var queuesChannel = (ITextChannel)guild.TextChannels.FirstOrDefault(c =>
                                                                                c.Name.Equals(ChannelNames.ActivePickups, StringComparison.OrdinalIgnoreCase)) ??
                                await guild.CreateTextChannelAsync(ChannelNames.ActivePickups,
                                                                   properties => { properties.Topic = "Active pickups, use reactions to signup"; });

            return(queuesChannel);
        }
Esempio n. 12
0
        public static async Task <ITextChannel> GetOrCreateTextChannelAsync(this SocketGuild guild, string channelName, Action <TextChannelProperties> func = null)
        {
            var existingChannel = guild.TextChannels.FirstOrDefault(c => c.Name == channelName.ToLower().Replace(' ', '-'));

            if (existingChannel != null)
            {
                return(existingChannel);
            }
            else
            {
                return(await guild.CreateTextChannelAsync(channelName, func));
            }
        }
Esempio n. 13
0
        public static async Task <RestTextChannel> CreateSuggestionChannel(this SocketGuild guild, ulong categoryId,
                                                                           SuggestionType type, string name)
        {
            var suffix = ChannelSuffixes[type];
            var res    = await guild.CreateTextChannelAsync(suffix + name, c =>
            {
                c.CategoryId = categoryId;
            });

            await ReorderChannels(guild);

            return(res);
        }
Esempio n. 14
0
        private static async Task CreateChannel(SocketGuild guild, string name, string topic, ulong categoryId)
        {
            // create #pickup channel if missing
            var activePickupsChannel = guild.Channels.FirstOrDefault(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase));

            if (activePickupsChannel == null)
            {
                await guild.CreateTextChannelAsync(name, properties =>
                {
                    properties.Topic      = topic;
                    properties.CategoryId = categoryId;
                });
            }
        }
Esempio n. 15
0
        public static GameSession Build(SocketGuild g, Server s, IGame game)
        {
            EmbedBuilder    panel   = game.Embedder.DefaultPanel();
            RestTextChannel channel = g.CreateTextChannelAsync(game.ChannelName, x => { x = GameChannelProperties; }).Result;
            RestUserMessage msg     = channel.SendMessageAsync(embed: panel.Build()).Result;
            GameSession     session = new GameSession(channel.Id, msg, panel);

            if (!s.OpenGameSessions.Exists())
            {
                s.OpenGameSessions = new List <GameSession>();
            }
            s.OpenGameSessions.Add(session);
            return(session);
        }
Esempio n. 16
0
        public DiscordBot(string key)
        {
            _bot.MessageReceived += OnMessageReceived;

            _bot.LoginAsync(TokenType.Bot, key);
            _bot.StartAsync();

            while (_bot.LoginState == LoginState.LoggingIn)
            {
                Thread.Sleep(1);
            }
            SetStatus(UserStatus.DoNotDisturb, "Setting everything up.");

            while ((_guild = _bot.GetGuild(GuildId)) == null)
            {
                Thread.Sleep(1);
            }

            while ((_categoryChannel = _guild.GetCategoryChannel(CategoryId)) == null)
            {
                Thread.Sleep(1);
            }

            IReadOnlyCollection <SocketGuildUser> sockets;

            while ((sockets = _guild.Users).Count <= 1)
            {
                Thread.Sleep(1);
            }

            _players = sockets.Where(user => user.Roles.Any(role => role.Id == RoleId))
                       .Select(user =>
            {
                var channelName = user.Nickname.ToLower() + "s-tattoo";
                if (_categoryChannel.Channels.FirstOrDefault(c => c.Name == channelName) is not ITextChannel channel)
                {
                    channel = _guild.CreateTextChannelAsync(channelName,
                                                            properties => properties.CategoryId = CategoryId).Result;
                    channel.AddPermissionOverwriteAsync(user, new OverwritePermissions(viewChannel: PermValue.Allow, sendMessages: PermValue.Allow));
                }
                var player = new Player(user, channel);
                _channelIdToPlayer.Add(channel.Id, player);
                return(player);
            }).ToArray();
            SetStatus(UserStatus.Online, "Working");
        }
Esempio n. 17
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);
        }
Esempio n. 18
0
        public static async void CheckEvents(SocketGuild server)
        {
            IChannel channel;

            if (!server.TextChannels.Any(a => a.Name == "events"))
            {
                channel = await server.CreateTextChannelAsync("events");
            }
            else
            {
                channel = server.TextChannels.FirstOrDefault(f => f.Name == "events");
            }
            var perms = new OverwritePermissions(sendMessages: PermValue.Deny, attachFiles: PermValue.Deny);

            if (!((SocketTextChannel)channel).GetPermissionOverwrite(server.EveryoneRole).Equals(perms))
            {
                await((SocketTextChannel)channel).AddPermissionOverwriteAsync(server.EveryoneRole, perms);
            }
        }
Esempio n. 19
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();
        }
Esempio n. 20
0
        public static async Task <RestTextChannel> CreatePersonalRoomAsync(SocketGuild guild, SocketGuildUser user)
        {
            SocketRole everyone = guild.Roles.Where(x => x.IsEveryone).First();

            // Creat personal room
            RestTextChannel personalRoom = await guild.CreateTextChannelAsync($"room-{user.Id}");

            // Make room only visible to new user and bots
            await personalRoom.AddPermissionOverwriteAsync(user, Permissions.roomPerm);

            await personalRoom.AddPermissionOverwriteAsync(everyone, Permissions.removeAllPerm);

            // Send intro information
            await personalRoom.SendMessageAsync($"<@{user.Id}>, welcome to your room! \n" +
                                                $"The server might be public but this is your own private sliver of the server.\n" +
                                                $"You can run commands, save images, post stuff, etc.\n" +
                                                $"type `!help` for a list of the commands!");

            return(personalRoom);
        }
Esempio n. 21
0
        private static async Task OnJoinedGuild(SocketGuild guild)
        {
            try
            {
                // create #pickup channel if missing
                var channel = guild.Channels.FirstOrDefault(c => c.Name.Equals("pickup"));
                if (channel == null)
                {
                    await guild.CreateTextChannelAsync("pickup",
                                                       properties => properties.Topic = "powered by pickup-bot | !help for instructions");
                }

                // TODO: create voice channels if missing
                //var voiceChannels = guild.VoiceChannels.Where(vc => vc.Name.StartsWith("pickup")).ToArray();
                //if (!voiceChannels.Any() || voiceChannels.Count() < 6)
                //{
                //    var vctasks = new List<Task>();
                //    for(var i = 1; i <= 6; i++)
                //    {
                //        vctasks.Add(guild.CreateVoiceChannelAsync($"Pickup {i}", properties => properties.UserLimit = 16));
                //    }

                //    await Task.WhenAll(vctasks);
                //}

                // create applicable roles if missing
                if (guild.Roles.All(w => w.Name != "pickup-promote"))
                {
                    await guild.CreateRoleAsync("pickup-promote", GuildPermissions.None, Color.Orange, false);
                }

                // TODO: sync roles with @everyone?
            }
            catch (Exception e)
            {
                await LogAsync(new LogMessage(LogSeverity.Error, nameof(OnJoinedGuild), e.Message, e));
            }
        }
Esempio n. 22
0
        private async Task <ITextChannel> GetReportChannelAsync(SocketGuild guild)
        {
            // Attempts to get text channel from database entry.
            var record = await CoreSettings.GetOrCreateGuildSettingsAsync(guild).ConfigureAwait(false);

            var reportChannel = guild.GetTextChannel(record.ReportChannel);

            if (reportChannel != null)
            {
                return(reportChannel);
            }

            // Attempts to get text channel by name.
            var searchChannel = guild.TextChannels.FirstOrDefault(x => x.Name.ToLower().Contains(ReportChannelName));

            if (searchChannel != null)
            {
                record.ReportChannel = searchChannel.Id;
                await CoreSettings.SaveRepositoryAsync().ConfigureAwait(false);

                return(searchChannel);
            }

            // Attempts to create a new text channel.
            var newChannel = await guild.CreateTextChannelAsync(ReportChannelName).ConfigureAwait(false);

            await newChannel.AddPermissionOverwriteAsync(guild.EveryoneRole,
                                                         new OverwritePermissions(viewChannel : PermValue.Deny)).ConfigureAwait(false);

            var modRoles = await GetModeratorRolesAsync(guild).ConfigureAwait(false);

            foreach (var modRole in modRoles)
            {
                await newChannel.AddPermissionOverwriteAsync(modRole,
                                                             new OverwritePermissions(viewChannel : PermValue.Allow)).ConfigureAwait(false);
            }
            return(newChannel);
        }
Esempio n. 23
0
        /// <summary>
        /// Creates a new mission channel
        /// </summary>
        /// <param name="channel_name_suffix">The suffix added to the channel name</param>
        /// <param name="explorers">All explorers to be part of this new mission channel</param>
        /// <param name="guild">The guild containing the mission channel category</param>
        /// <param name="source">The user that issued the createmission command</param>
        /// <returns>The RestTextChannel created by the command</returns>
        public static async Task <RestTextChannel> CreateMission(string channel_name_suffix, IReadOnlyCollection <SocketUser> explorers, SocketGuild guild, SocketUser source)
        {
            int failcode = 0;

            try
            {
                // [00] retrieving mission number and other variables
                int    missionnumber = MissionSettingsModel.NextMissionNumber;
                string channelname   = string.Format("mission_{0}_{1}", missionnumber, channel_name_suffix);

                SocketGuildChannel missioncategory = guild.GetChannel(MissionSettingsModel.MissionCategoryId);

                failcode++;
                // [01] Creating a temporary ulong list of explorerIds to generate a ping string
                List <ulong> explorerIDs = new List <ulong>();

                foreach (IUser user in explorers)
                {
                    explorerIDs.Add(user.Id);
                }
                string pingstring = ResourcesModel.GetMentionsFromUserIdList(explorerIDs);

                failcode++;

                // [02] Create new channel
                RestTextChannel NewMissionChannel = await guild.CreateTextChannelAsync(channelname);

                failcode++;

                // [03] Sync permissions with mission category
                foreach (Overwrite perm in missioncategory.PermissionOverwrites)
                {
                    if (perm.TargetType == PermissionTarget.Role)
                    {
                        IRole role = guild.GetRole(perm.TargetId);
                        await NewMissionChannel.AddPermissionOverwriteAsync(role, perm.Permissions);
                    }
                    else
                    {
                        IUser user = guild.GetUser(perm.TargetId);
                        await NewMissionChannel.AddPermissionOverwriteAsync(user, perm.Permissions);
                    }
                }

                failcode++;

                // [04] Add explorers  to mission room
                foreach (IUser user in explorers)
                {
                    await NewMissionChannel.AddPermissionOverwriteAsync(user, MissionSettingsModel.ExplorerPerms);
                }

                failcode++;

                // [05] Move to mission category and add channel topic
                string channeltopic;
                if (MissionSettingsModel.DefaultTopic.Contains("{0}"))
                {
                    channeltopic = string.Format(MissionSettingsModel.DefaultTopic, pingstring);
                }
                else
                {
                    channeltopic = MissionSettingsModel.DefaultTopic;
                }
                await NewMissionChannel.ModifyAsync(TextChannelProperties =>
                {
                    TextChannelProperties.CategoryId = MissionSettingsModel.MissionCategoryId;
                    TextChannelProperties.Topic      = channeltopic;
                });

                failcode++;

                // [06] Sending explorer questions
                EmbedBuilder embed = new EmbedBuilder();
                embed.Color = Var.BOTCOLOR;
                if (MissionSettingsModel.ExplorerQuestions.Contains("{0}"))
                {
                    embed.Description = string.Format(MissionSettingsModel.ExplorerQuestions, pingstring);
                }
                else
                {
                    embed.Description = MissionSettingsModel.ExplorerQuestions;
                }
                await NewMissionChannel.SendMessageAsync(pingstring, embed : embed.Build());

                failcode++;

                // [07] Sending debug message, adding to mission list and returning
                await SettingsModel.SendDebugMessage(string.Format("Created new mission room {0} on behalf of {1} for explorer {2}", NewMissionChannel.Mention, source.Mention, pingstring), DebugCategories.missions);

                missionList.Add(NewMissionChannel.Id);
                await SaveMissions();

                await MissionSettingsModel.SaveMissionSettings();

                return(NewMissionChannel);
            }
            catch (Exception e)
            {
                await SettingsModel.SendDebugMessage(string.Format("Creation of new mission channel failed. Failcode: {0}", failcode.ToString("X")), DebugCategories.missions);

                throw e;
            }
        }
Esempio n. 24
0
        /// <summary>
        /// Creates a new guild (includes role, channel, etc)
        /// </summary>
        /// <param name="guild">Discord Server Guild to create channel and role on</param>
        /// <param name="name">Guild Name</param>
        /// <param name="color">Guild Display Color</param>
        /// <param name="captain">Guild Captain</param>
        /// <param name="members">Guild Users</param>
        /// <returns>true, if operation succeeds</returns>
        public static async Task <bool> CreateGuildAsync(SocketGuild guild, string name, GuildColor color, SocketGuildUser captain, List <SocketGuildUser> members)
        {
            string errorhint = "Failed a precheck";

            try
            {
                if (TryGetGuildOfUser(captain.Id, out MinecraftGuild existingCaptainGuild))
                {
                    if (existingCaptainGuild.Active || captain.Id == existingCaptainGuild.CaptainId)
                    {
                        errorhint = "Precheck failed on " + captain.Mention;
                        return(false);
                    }
                    else
                    {
                        existingCaptainGuild.MateIds.Remove(captain.Id);
                        existingCaptainGuild.MemberIds.Remove(captain.Id);
                    }
                }
                foreach (SocketGuildUser member in members)
                {
                    if (TryGetGuildOfUser(member.Id, out MinecraftGuild existingMemberGuild))
                    {
                        if (existingCaptainGuild.Active || member.Id == existingCaptainGuild.CaptainId)
                        {
                            return(false);
                        }
                        else
                        {
                            errorhint = "Precheck failed on " + member.Mention;
                            existingCaptainGuild.MateIds.Remove(member.Id);
                            existingCaptainGuild.MemberIds.Remove(member.Id);
                        }
                    }
                }
                errorhint = "Failed to create Guild Role!";
                RestRole guildRole = await guild.CreateRoleAsync(name, color : MinecraftGuild.ToDiscordColor(color), isHoisted : true);

                errorhint = "Move role into position";
                await guildRole.ModifyAsync(RoleProperties =>
                {
                    RoleProperties.Position = GUILD_ROLE_POSITION;
                });

                errorhint = "Failed to create Guild Channel!";
                SocketCategoryChannel guildCategory = guild.GetChannel(GuildChannelHelper.GuildCategoryId) as SocketCategoryChannel;
                if (guildCategory == null)
                {
                    throw new Exception("Could not find Guild Category Channel!");
                }
                RestTextChannel guildChannel = await guild.CreateTextChannelAsync(name, TextChannelProperties =>
                {
                    TextChannelProperties.CategoryId = GuildChannelHelper.GuildCategoryId;
                    TextChannelProperties.Topic      = "Private Guild Channel for " + name;
                });

                errorhint = "Failed to copy guildcategories permissions";
                foreach (Overwrite overwrite in guildCategory.PermissionOverwrites)
                {
                    IRole role = guild.GetRole(overwrite.TargetId);
                    if (role != null)
                    {
                        await guildChannel.AddPermissionOverwriteAsync(role, overwrite.Permissions);
                    }
                }
                errorhint = "Failed to set Guild Channel Permissions!";
                await guildChannel.AddPermissionOverwriteAsync(guildRole, GuildRoleChannelPerms);

                await guildChannel.AddPermissionOverwriteAsync(captain, CaptainChannelPerms);

                errorhint = "Failed to add Guild Role to Captain!";
                await captain.AddRoleAsync(guildRole);

                errorhint = "Failed to add GuildCaptain Role to Captain!";
                SocketRole captainRole = guild.GetRole(SettingsModel.GuildCaptainRole);
                if (captainRole != null)
                {
                    await captain.AddRoleAsync(captainRole);
                }
                errorhint = "Failed to add Guild Role to a Member!";
                foreach (SocketGuildUser member in members)
                {
                    await member.AddRoleAsync(guildRole);
                }
                errorhint = "Failed to create MinecraftGuild!";

                StringBuilder memberPingString = new StringBuilder();

                MinecraftGuild minecraftGuild = new MinecraftGuild(guildChannel.Id, guildRole.Id, color, name, captain.Id);
                for (int i = 0; i < members.Count; i++)
                {
                    SocketGuildUser member = members[i];
                    minecraftGuild.MemberIds.Add(member.Id);
                    memberPingString.Append(member.Mention);
                    if (i < members.Count - 1)
                    {
                        memberPingString.Append(", ");
                    }
                }
                guilds.Add(minecraftGuild);
                errorhint = "Failed to save MinecraftGuild!";
                await SaveAll();

                errorhint = "Failed to send or pin guild info embed";
                var infomessage = await guildChannel.SendMessageAsync(embed : GuildHelpEmbed.Build());

                await infomessage.PinAsync();

                errorhint = "Notify Admins";
                await AdminTaskInteractiveMessage.CreateAdminTaskMessage($"Create ingame represantation for guild \"{name}\"", $"Name: `{name}`, Color: `{color}` (`0x{((uint)color).ToString("X")}`)\nCaptain: {captain.Mention}\nMembers: {memberPingString}");

                return(true);
            }
            catch (Exception e)
            {
                await GuildChannelHelper.SendExceptionNotification(e, $"Error creating guild {name}. Hint: {errorhint}");

                return(false);
            }
        }
 public virtual Task <RestTextChannel> CreateTextChannelAsync(string name, Action <TextChannelProperties>?func = null, RequestOptions?options = null)
 {
     return(_socketGuild.CreateTextChannelAsync(name, func, options));
 }
Esempio n. 26
0
        private async Task SetupServerQuick(SocketGuild guild, ISocketMessageChannel channel, SocketMessage message, bool addRulesMessage = true, bool setupWelcomeChannel = true,
                                            bool setupRuleReaction = true)
        {
            //Rules message
            string rules = _quickRulesText;

            if (addRulesMessage)
            {
                //Check rules file, or if rules where provided
                if (message.Attachments.Count != 0)
                {
                    Attachment attachment = message.Attachments.ElementAt(0);
                    if (!attachment.Filename.EndsWith(".txt"))
                    {
                        await channel.SendMessageAsync("The provided rules file isn't in a `.txt` file format!");

                        return;
                    }

                    rules = await Global.HttpClient.GetStringAsync(attachment.Url);
                }

                else if (string.IsNullOrWhiteSpace(rules) && message.Attachments.Count == 0)
                {
                    await channel.SendMessageAsync("You MUST provide a rules file!");

                    return;
                }
            }

            Logger.Log($"Running server quick setup on {guild.Name}({guild.Id})");

            ServerList server = ServerListsManager.GetServer(guild);

            //Setup the roles
            IRole memberRole = RoleUtils.GetGuildRole(guild, "Member");

            //There is already a role called "member"
            if (memberRole != null)
            {
                await memberRole.ModifyAsync(properties => properties.Permissions = _memberRoleGuildPermissions);
            }
            else
            {
                //create a new role called member
                memberRole = await guild.CreateRoleAsync("Member", _memberRoleGuildPermissions);

                await guild.EveryoneRole.ModifyAsync(properties => properties.Permissions = _everyoneRoleGuildPermissions);
            }

            //Setup the welcome channel
            if (setupWelcomeChannel)
            {
                ulong welcomeChannelId;

                //First, lets check if they already have a #welcome channel of sorts
                if (guild.SystemChannel == null)
                {
                    //They don't, so set one up
                    RestTextChannel welcomeChannel =
                        await guild.CreateTextChannelAsync("welcome",
                                                           properties => { properties.Topic    = "Were everyone gets a warm welcome!";
                                                                           properties.Position = 0; });

                    await welcomeChannel.AddPermissionOverwriteAsync(guild.EveryoneRole, _everyoneChannelPermissions);

                    welcomeChannelId = welcomeChannel.Id;
                }
                else
                {
                    //They already do, so alter the pre-existing one to have right perms, and to not have Discord random messages put there
                    await guild.SystemChannel.AddPermissionOverwriteAsync(guild.EveryoneRole, _everyoneChannelPermissions);

                    welcomeChannelId = guild.SystemChannel.Id;

                    await guild.ModifyAsync(properties => properties.SystemChannel = null);
                }

                //Setup welcome message
                server.WelcomeChannelId      = welcomeChannelId;
                server.WelcomeMessageEnabled = true;
                server.GoodbyeMessageEnabled = true;

                //Do a delay
                await Task.Delay(1000);
            }

            //Rule reaction
            if (addRulesMessage && setupRuleReaction)
            {
                //Setup rules channel
                RestTextChannel rulesChannel = await guild.CreateTextChannelAsync("rules",
                                                                                  properties => { properties.Position = 1;
                                                                                                  properties.Topic    = "Rules of this Discord server"; });

                await rulesChannel.AddPermissionOverwriteAsync(guild.EveryoneRole, _everyoneChannelPermissions);

                RestUserMessage rulesMessage = await rulesChannel.SendMessageAsync(rules);

                //Setup rules reaction
                await rulesMessage.AddReactionAsync(new Emoji(RulesEmoji));

                server.RuleReactionEmoji    = RulesEmoji;
                server.RuleMessageId        = rulesMessage.Id;
                server.RuleMessageChannelId = rulesChannel.Id;
                server.RuleRoleId           = memberRole.Id;
                server.RuleEnabled          = true;
            }

            //Setup the rest of the channels

            //General category
            await AddCategoryWithChannels(guild, memberRole, "General", 3);

            //Do a delay between categories
            await Task.Delay(500);

            //Gamming category
            await AddCategoryWithChannels(guild, memberRole, "Gamming", 4);

            //DONE!
            ServerListsManager.SaveServerList();
            await Context.Channel.SendMessageAsync("Quick Setup is done!");

            Logger.Log($"server quick setup on {guild.Name}({guild.Id}) is done!");
        }
Esempio n. 27
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();
        }
Esempio n. 28
0
        /// <summary>
        /// Helper method for VoteChecking. Does actual channel creation processing.
        /// </summary>
        private async Task <RestTextChannel> CreateTemporaryChannel(SocketGuild g, GuildInformation info)
        {
            // Yep, we're locking again.
            string     newChannelName;
            EntityList newChannelModlist;

            lock (info)
            {
                newChannelName    = info.Config.TempChannelName;
                newChannelModlist = info.Config.VoteStarters;
            }

            var newChannel = await g.CreateTextChannelAsync(newChannelName); // exceptions here are handled by caller

            foreach (var item in newChannelModlist.Roles)
            {
                // Evaluate role from data
                SocketRole r = null;
                if (item.Id.HasValue)
                {
                    r = g.GetRole(item.Id.Value);
                }
                if (r == null && item.Name != null)
                {
                    r = g.Roles.FirstOrDefault(gr => string.Equals(gr.Name, item.Name, StringComparison.OrdinalIgnoreCase));
                }
                if (r == null)
                {
                    await newChannel.SendMessageAsync($"Unable to find role `{item.ToString()}` to apply permissions.");

                    continue;
                }

                try
                {
                    await newChannel.AddPermissionOverwriteAsync(r, new OverwritePermissions(
                                                                     manageChannel : PermValue.Allow,
                                                                     sendMessages : PermValue.Allow,
                                                                     manageMessages : PermValue.Allow,
                                                                     manageRoles : PermValue.Allow));
                }
                catch (Discord.Net.HttpException ex)
                {
                    // TODO what error code are we looking for here? adjust to pick up only that.
                    // TODO clean up the error message display. users don't want to see the gory details.
                    await newChannel.SendMessageAsync($":x: Unable to set on `{r.Name}`: {ex.Message}");
                }
            }
            foreach (var item in newChannelModlist.Users)
            {
                // Evaluate user from data
                SocketUser u = null;
                if (item.Id.HasValue)
                {
                    u = g.GetUser(item.Id.Value);
                }
                if (u == null && item.Name != null)
                {
                    u = g.Users.FirstOrDefault(gu => string.Equals(gu.Username, item.Name, StringComparison.OrdinalIgnoreCase));
                }
                if (u == null)
                {
                    await newChannel.SendMessageAsync($"Unable to find user `{item.ToString()}` to apply permissions.");

                    continue;
                }

                try
                {
                    await newChannel.AddPermissionOverwriteAsync(u, new OverwritePermissions(
                                                                     manageChannel : PermValue.Allow,
                                                                     sendMessages : PermValue.Allow,
                                                                     manageMessages : PermValue.Allow,
                                                                     manageRoles : PermValue.Allow));
                }
                catch (Discord.Net.HttpException ex)
                {
                    // TODO same as above. which code do we want to catch specifically?
                    await newChannel.SendMessageAsync($":x: Unable to set on `{u.Username}`: {ex.Message}");
                }
            }
            return(newChannel);
        }
Esempio n. 29
0
 public static Task <RestTextChannel> CreateSupportChannel(SocketGuild guild, string channelName, ulong categoryId, bool createdInDiscord)
 => guild.CreateTextChannelAsync(channelName, properties =>
 {
     properties.CategoryId = categoryId;
     properties.Topic      = $"Support request created in {(createdInDiscord ? "Discord" : "RAGE")}.";
 });
Esempio n. 30
0
        public async Task <RestTextChannel> CreateChannelForMission(SocketGuild guild, Mission mission, SignupsData signups)
        {
            // Sort channels by date
            signups.Missions.Sort((x, y) =>
            {
                return(x.Date.CompareTo(y.Date));
            });

            var signupChannel = await guild.CreateTextChannelAsync(mission.Title, x =>
            {
                x.CategoryId = _config.SignupsCategory;
                // Kurwa dlaczego to nie działa
                var index = (int)(mission.Date - new DateTime(2019, 1, 1)).TotalMinutes;
                // really hacky solution to avoid recalculating indexes for each channel integer should have
                // space for around 68 years, and this bot is not going to work this long for sure
                x.Position = index;
            });

            var everyone   = guild.EveryoneRole;
            var armaforces = guild.GetRole(_config.SignupRole);
            var botRole    = guild.GetRole(_config.BotRole);

            var banPermissions = new OverwritePermissions(
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny);

            var botPermissions = new OverwritePermissions(
                PermValue.Deny,
                PermValue.Allow,
                PermValue.Allow,
                PermValue.Allow,
                PermValue.Allow,
                PermValue.Deny,
                PermValue.Allow,
                PermValue.Allow,
                PermValue.Allow,
                PermValue.Allow,
                PermValue.Allow,
                PermValue.Allow,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Allow,
                PermValue.Deny);

            var everyoneStartPermissions = new OverwritePermissions(
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny,
                PermValue.Deny);

            try
            {
                await signupChannel.AddPermissionOverwriteAsync(botRole, botPermissions);

                await signups.BanAccess.WaitAsync(-1);

                try
                {
                    foreach (var ban in signups.SpamBans)
                    {
                        await signupChannel.AddPermissionOverwriteAsync(_client.GetGuild(_config.AFGuild).GetUser(ban.Key), banPermissions);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
                finally
                {
                    signups.BanAccess.Release();
                }

                await signupChannel.AddPermissionOverwriteAsync(everyone, everyoneStartPermissions);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }


            return(signupChannel);
        }