public static Task StwStoreWebhook(ulong guid, string fileName, string title, GuildConfig gConfig)
        {
            return(Task.Run(() =>
            {
                try
                {
                    fileName = Path.GetFileName(fileName);
                    if (gConfig == null || gConfig.Admin.StwStoreStates.Active == false)
                    {
                        return;
                    }

                    var discordApi = DIManager.Services.GetRequiredService <IDiscordRestApi>();;
                    var guild = discordApi.GetApi.GetGuildAsync(guid).Result;
                    if (guild == null)
                    {
                        return;
                    }

                    var channel = guild.GetTextChannelAsync(ulong.Parse(gConfig.Admin.StwStoreStates.ChannelId)).Result;
                    if (channel != null)
                    {
                        var embedImage = new EmbedBuilder()
                        {
                            ImageUrl = $"attachment://{fileName}"
                        }.Build();
                        string mentionTag = string.Empty;
                        RestRole r0 = null;
                        if (!string.IsNullOrWhiteSpace(gConfig.Admin.StwStoreStates.RoleIdToMention))
                        {
                            mentionTag = $"<@&{gConfig.Admin.StwStoreStates.RoleIdToMention}>";
                            r0 = guild.GetRole(ulong.Parse(gConfig.Admin.StwStoreStates.RoleIdToMention));
                            r0.ModifyAsync((o) =>
                            {
                                o.Mentionable = true;
                            }).Wait();
                        }
                        channel.SendFileAsync(fileName, $"{mentionTag} {title}", embed: embedImage, options: Utils.RequestOption).Wait();
                        r0?.ModifyAsync((o) =>
                        {
                            o.Mentionable = false;
                        }).Wait();
                    }
                }
                catch (Exception exception1)
                {
                    Log.Exception(exception1, Serilog.Events.LogEventLevel.Error);
                }
            }));
        }
Пример #2
0
        public async Task Init()
        {
            if (States.state == States.StatesList[0])
            {
                GameChannel = await Context.Guild.CreateTextChannelAsync("NAVIGATION", null, null);

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

                Navigator = await Context.Guild.CreateRoleAsync("Navigator", null, Color.Blue, false, null);

                await Context.Channel.SendMessageAsync("ALL PARTICIPATING AGENTS ENTER COMMAND !Join AND FIND 'NAVIGATION' CHANNEL", false, null);

                await GameChannel.AddPermissionOverwriteAsync((IRole)Navigator, OverwritePermissions.AllowAll(GameChannel));

                EmbedBuilder Embed = new EmbedBuilder();
                Embed.WithAuthor("DDA SYSTEMS");
                Embed.AddField(">>> START TRANSMISSION", "> TO ALL DDA INVESTIGATORS");
                Embed.AddField("> MISSION DETAILS:", "WE COLLABORATED WITH THE POLICE USING THE TECHNOLOGY HERE AT THE DIGITAL DATASCAPE AGENCY TO CREATE A DIGITAL COPY OF THE SUBJECT’S MEMORY. YOUR MISSION AS DDA INVESTIGATORS WILL HAVE YOU NAVIGATING THROUGH THE DIGITAL MINDSCAPE TO RESTORE THE SUBJECT’S MIND AND FIND THE RIGHT MEMORIES TO HELP SOLVE THE CASE. ");
                Embed.AddField("> SUBJECT '00003126'", "FLORENCE CARTER, ADDRESS: 2027 MEADOWLARK DR, CASTRO VALLEY, CA 94546, COUNTRY: USA, DOB: 7 / 14 / 1987, SEX: F, HEIGHT: 5’08");
                Embed.AddField("> DIAGNOSIS:", "SUBJECT IS SUFFERING BOTH RETROGRADE AND DISSOCIATIVE AMNESIA ONSET BY STRESS AND/OR TRAUMA. SUBJECT WAS FOUND IN THE PARKING LOT OF HER WORKPLACE, WANDERING AROUND IN A DISSOCIATIVE FUGUE. WHEN CONFRONTED BY A WORKER, SHE WAS UNABLE TO CONFIRM HER OWN IDENTITY. AFTER BEING ADMITTED TO THE HOSPITAL, HER IDENTITY WAS CONFIRMED. WHILE IN THE HOSPITAL, THE SUBJECT WAS ATTACKED BY AN UNKNOWN ASSAILANT. SHE SUFFERED MINIMAL INJURY. AFTERWARDS, THE POLICE WERE CALLED TO HER LOCATION. THE POLICE DETERMINED ______ BETWEEN THE SUBJECT AND AN ONGOING CASE REGARDING THE SERIAL KILLER _________ “THE ORPHANER”. THE SUBJECT WAS FOUND TO BE _____  ________ ______ OF A CLOSE FRIEND. HER ____________ AND _____ FRIEND’S ________ ________ FOUND MURDERED THE NEXT DAY, LEAVING BEHIND _____________ AGED ______. THERE IS A ______ POSSIBILITY THAT THE SUBJECT ____ ______ EVENTS ___________ WHICH CREATED _______ _______ ENOUGH _________________ ________");
                Embed.AddField("END TRANSMISSION <<<", "WE HIGHLY RECOMENDED ALL INVESTIGATORS REMAIN IN COMMUNICATION THROUGHOUT NAVIGATION");
                Embed.AddField("GOOD LUCK INVESTIGATORS", "TO BEGIN NAVIGATION, TYPE COMMAND !Ready");

                await GameChannel.SendMessageAsync("", false, Embed.Build(), null);

                States.isDead     = false;
                States.canPlace   = false;
                States.isPlaced   = false;
                States.bladesOn   = true;
                Room4.player1Free = false;
                Room4.player2Free = false;
                foreach (var item in States.Inventory)
                {
                    States.Inventory.Remove(item);
                }
                States.state = States.StatesList[1];
            }
        }
Пример #3
0
        public async Task ConsumeMessageAsync(IGatewayMessage message, CancellationToken ct)
        {
            if (message is not DiscordMessage discordMessage)
            {
                return;
            }
            if (discordMessage.SocketMessage.Channel is not SocketGuildChannel)
            {
                return;
            }
            var         parts = message.Content.ToLower().Split();
            SocketGuild guild = (discordMessage.SocketMessage.Channel as SocketGuildChannel).Guild;

            if (parts.Length >= 1 && parts[0] == "!role")
            {
                if (parts.Length == 1)
                {
                    await message.RespondToSenderAsync("Allows users to create and add themselves to custom roles.\n*Usage: `!role <create, add, remove, list>`*", ct);

                    return;
                }
                if (parts.Length == 2)
                {
                    if (parts[1] == "list")
                    {
                        string            roleBuffer  = "Roles: ";
                        List <SocketRole> sortedRoles = guild.Roles.Where(r => r.Name.StartsWith("@")).OrderByDescending(r => r.Members.Count()).ToList();
                        foreach (SocketRole r in sortedRoles)
                        {
                            if (r.Name == "@everyone")
                            {
                                continue;
                            }
                            string pendingRole = $"`{r.Name} [{r.Members.Count()}]` ";
                            if (roleBuffer.Length + pendingRole.Length >= 2000)
                            {
                                await message.RespondInChatAsync(roleBuffer, ct);

                                roleBuffer = pendingRole;
                            }
                            else
                            {
                                roleBuffer += pendingRole;
                            }
                        }
                        await message.RespondInChatAsync(roleBuffer, ct);

                        return;
                    }
                    var helpMessage = parts[1] switch
                    {
                        "create" => "Creates a new role and adds you to it.\n*Usage: `!role create <name of new role>`*",
                        "add" => "Adds you to an existing role. \n*Usage: `!role add <name of desired role>`*",
                        "remove" => "Removes you from a role you have.\n*Usage: `!role remove <name of unwanted role>`*",
                        _ => _invalid
                    };
                    await message.RespondToSenderAsync(helpMessage, ct);

                    return;
                }
                string     target = "@" + message.Content.ToLower().Substring(parts[0].Length + parts[1].Length + 2);
                SocketRole role   = guild.Roles.FirstOrDefault(r => r.Name == target);
                IGuildUser user   = discordMessage.SocketMessage.Author as IGuildUser;
                if (parts[1] == "create")
                {
                    if (role != null)
                    {
                        await message.RespondToSenderAsync($"`{target}` already exists. If you want to add yourself to it, use `!role add`.", ct);
                    }
                    else
                    {
                        RestRole newrole = await guild.CreateRoleAsync(target, null, null, false, true, null);

                        await user.AddRoleAsync(newrole);

                        await message.RespondToSenderAsync($"OK! Created `{target}` and added you to it.", ct);
                    }
                    return;
                }
                if (parts[1] == "add")
                {
                    if (role != null)
                    {
                        await user.AddRoleAsync(role);

                        await message.RespondToSenderAsync($"OK! Added you to `{target}`.", ct);
                    }
                    else
                    {
                        await message.RespondToSenderAsync($"That role doesn't exist. If you want to create it, use `!role create`.", ct);
                    }
                    return;
                }
                if (parts[1] == "remove")
                {
                    await guild.DownloadUsersAsync();

                    if (role != null)
                    {
                        if (role.Members.Contains(user))
                        {
                            if (role.Members.Count() == 1)
                            {
                                await role.DeleteAsync();

                                await message.RespondToSenderAsync($"OK! You were the last person in `{target}`, so it's been deleted.", ct);
                            }
                            else
                            {
                                await user.RemoveRoleAsync(role);

                                await message.RespondToSenderAsync($"OK! You no longer have `{target}`.", ct);
                            }
                        }
                        else
                        {
                            await message.RespondToSenderAsync($"You aren't in `{target}`.", ct);
                        }
                    }
                    else
                    {
                        await message.RespondToSenderAsync($"`{target}` doesn't exist.", ct);
                    }
                    return;
                }
                if (parts[1] == "list")
                {
                    if (target == "@everyone")
                    {
                        await message.RespondToSenderAsync("Nice Try!", ct);

                        return;
                    }
                    await guild.DownloadUsersAsync();

                    if (role != null)
                    {
                        await message.RespondToSenderAsync($"Users in `{target}`: {String.Join(", ", role.Members.Select(m => m.Username))}", ct);
                    }
                    else
                    {
                        await message.RespondToSenderAsync($"`{target}` doesn't exist.", ct);
                    }
                    return;
                }
                await message.RespondToSenderAsync(_invalid, ct);
            }
        }
    }
Пример #4
0
        private async Task <RoleConfig> CreateTempRole(CommandArguments e, ServerContext dbContext)
        {
            if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
            {
                await e.Message.Channel.SendMessageSafe(ErrorPermissionsString);

                return(null);
            }
            if (string.IsNullOrEmpty(e.TrimmedMessage))
            {
                await e.SendReplySafe("What role? Name? Do you want me to come up with something silly or what? And when do you want to nuke it?");

                return(null);
            }

            if (e.MessageArgs.Length != 2)
            {
                await e.SendReplySafe(e.Command.Description);

                return(null);
            }

            int durationHours = 0;

            try
            {
                Match dayMatch  = Regex.Match(e.MessageArgs[1], "\\d+d", RegexOptions.IgnoreCase);
                Match hourMatch = Regex.Match(e.MessageArgs[1], "\\d+h", RegexOptions.IgnoreCase);

                if (!hourMatch.Success && !dayMatch.Success)
                {
                    await e.SendReplySafe(e.Command.Description);

                    dbContext.Dispose();
                    return(null);
                }

                if (hourMatch.Success)
                {
                    durationHours = int.Parse(hourMatch.Value.Trim('h').Trim('H'));
                }
                if (dayMatch.Success)
                {
                    durationHours += 24 * int.Parse(dayMatch.Value.Trim('d').Trim('D'));
                }
            }
            catch (Exception)
            {
                await e.SendReplySafe(e.Command.Description);

                dbContext.Dispose();
                return(null);
            }

            RoleConfig roleConfig = null;
            string     response   = Localisation.SystemStrings.DiscordShitEmoji;

            try
            {
                RestRole role = await e.Server.Guild.CreateRoleAsync(e.MessageArgs[0], GuildPermissions.None);

                roleConfig = dbContext.GetOrAddRole(e.Server.Id, role.Id);
                roleConfig.DeleteAtTime = DateTime.UtcNow + TimeSpan.FromHours(durationHours);
                response = $"Role created: `{role.Name}`\n  Id: `{role.Id}`\n  Delete at `{Utils.GetTimestamp(roleConfig.DeleteAtTime)}`";
            }
            catch (Exception exception)
            {
                await this.HandleException(exception, "CreateTempRole failed.", e.Server.Id);
            }

            await e.SendReplySafe(response);

            return(roleConfig);
        }
Пример #5
0
        public List <Command> Init(IBotwinderClient iClient)
        {
            this.Client = iClient as BotwinderClient;
            List <Command> commands = new List <Command>();

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

            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Get a name, id and color of `roleID` or `roleName` parameter.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                guid              id         = 0;
                SocketRole        roleFromId = null;
                List <SocketRole> roles      = null;
                if (string.IsNullOrEmpty(e.TrimmedMessage) ||
                    (!(guid.TryParse(e.TrimmedMessage, out id) && (roleFromId = e.Server.Guild.GetRole(id)) != null) &&
                     !(roles = e.Server.Guild.Roles.Where(r => r.Name.ToLower().Contains(e.TrimmedMessage.ToLower())).ToList()).Any()))
                {
                    await e.SendReplySafe("Role not found.");

                    return;
                }

                if (roleFromId != null)
                {
                    roles = new List <SocketRole>();
                    roles.Add(roleFromId);
                }

                StringBuilder response = new StringBuilder();
                foreach (SocketRole role in roles)
                {
                    string hex = BitConverter.ToString(new byte[] { role.Color.R, role.Color.G, role.Color.B }).Replace("-", "");
                    response.AppendLine($"Role: `{role.Name}`\n  Id: `{role.Id}`\n  Position: `{role.Position}`\n  Color: `rgb({role.Color.R},{role.Color.G},{role.Color.B})` | `hex(#{hex})`");
                }

                await e.SendReplySafe(response.ToString());
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("getrole"));

// !addEmojiRole
            newCommand                     = new Command("addEmojiRole");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Add an emoji reaction assigned role to a message.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (e.MessageArgs == null || e.MessageArgs.Length < 3 || e.TrimmedMessage == "-h" || e.TrimmedMessage == "--help" || !guid.TryParse(e.MessageArgs[0], out guid messageId))
                {
                    await e.SendReplySafe($"Usage: `{e.Server.Config.CommandPrefix}{e.CommandId} <messageId> <emoji> <roleId or name expression>`");

                    return;
                }

                Match emoji = this.EmojiNameRegex.Match(e.MessageArgs[1]);
                if (!emoji.Success)
                {
                    await e.SendReplySafe("What emoji again?");

                    return;
                }

                SocketRole role = e.Server.GetRole(e.MessageArgs[2], out string response);
                if (role == null)
                {
                    await e.SendReplySafe(response);

                    return;
                }

                ServerContext        dbContext    = ServerContext.Create(this.Client.DbConnectionString);
                ReactionAssignedRole reactionRole = dbContext.ReactionAssignedRoles.FirstOrDefault(r => r.ServerId == e.Server.Id && r.MessageId == messageId && r.Emoji == emoji.Value);
                if (reactionRole == null)
                {
                    dbContext.ReactionAssignedRoles.Add(reactionRole = new ReactionAssignedRole()
                    {
                        ServerId  = e.Server.Id,
                        MessageId = messageId,
                        Emoji     = emoji.Value
                    });
                }
                else if (reactionRole.RoleId == role.Id)
                {
                    await e.SendReplySafe("Already exists.");

                    dbContext.Dispose();
                    return;
                }

                reactionRole.RoleId = role.Id;
                dbContext.SaveChanges();
                dbContext.Dispose();
                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);

// !membersOf
            newCommand                     = new Command("membersOf");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Display a list of members of a role.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                SocketRole role = e.Server.GetRole(e.TrimmedMessage, out string response);
                if (role == null)
                {
                    await e.SendReplySafe(response);

                    return;
                }

                await e.Server.Guild.DownloadUsersAsync();

                List <string> names = role.Members.Select(u => u.GetUsername()).ToList();
                names.Sort();

                response = names.Count == 0 ? "Nobody has this role." : $"Members of `{role.Name}` are:\n" + names.ToNamesList();
                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("listMembers"));

// !createRole
            newCommand                     = new Command("createRole");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Create a role with specified name.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.Message.Channel.SendMessageSafe(ErrorPermissionsString);

                    return;
                }
                if (string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    await e.SendReplySafe("What role? Name? Do you want me to come up with something silly or what?");

                    return;
                }

                RestRole role = await e.Server.Guild.CreateRoleAsync(e.TrimmedMessage, GuildPermissions.None);

                string response = $"Role created: `{role.Name}`\n  Id: `{role.Id}`";
                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);

// !createRoles
            newCommand                     = new Command("createRoles");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Create roles with specified names. List of whitespace delimited arguments, use quotes to use spaces.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.Message.Channel.SendMessageSafe(ErrorPermissionsString);

                    return;
                }
                if (string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    await e.SendReplySafe(e.Command.Description);

                    return;
                }

                StringBuilder response = new StringBuilder("Roles created:\n");

                for (int i = 0; i < e.MessageArgs.Length; i++)
                {
                    RestRole role = await e.Server.Guild.CreateRoleAsync(e.MessageArgs[i], GuildPermissions.None);

                    response.AppendLine($"`{role.Id}` | `{role.Name}`");
                }

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

// !createPublicRoles
            newCommand                     = new Command("createPublicRoles");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Create public roles with specified names. The first argument will be used as a name for the new role group, followed by a list of whitespace delimited arguments, use quotes to use spaces.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.Message.Channel.SendMessageSafe(ErrorPermissionsString);

                    return;
                }
                if (e.MessageArgs.Length < 2)
                {
                    await e.SendReplySafe(e.Command.Description);

                    return;
                }

                StringBuilder response = new StringBuilder("Roles created:\n");

                Int64         groupId   = 1;
                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                IEnumerable <RoleGroupConfig> roleGroups = dbContext.PublicRoleGroups.Where(g => g.ServerId == e.Server.Id);
                foreach (RoleGroupConfig group in roleGroups)
                {
                    if (groupId < group.GroupId)
                    {
                        groupId = group.GroupId;
                    }
                }

                RoleGroupConfig roleGroup = new RoleGroupConfig()
                {
                    ServerId  = e.Server.Id,
                    GroupId   = groupId,
                    Name      = e.MessageArgs[0],
                    RoleLimit = 1
                };
                dbContext.PublicRoleGroups.Add(roleGroup);

                bool save = true;
                for (int i = 1; i < e.MessageArgs.Length; i++)
                {
                    try
                    {
                        RestRole role = await e.Server.Guild.CreateRoleAsync(e.MessageArgs[i], GuildPermissions.None);

                        RoleConfig roleConfig = new RoleConfig()
                        {
                            ServerId          = e.Server.Id,
                            RoleId            = role.Id,
                            PermissionLevel   = RolePermissionLevel.Public,
                            PublicRoleGroupId = groupId
                        };
                        dbContext.Roles.Add(roleConfig);

                        response.AppendLine($"`{role.Id}` | `{role.Name}`");
                    }
                    catch (Exception)
                    {
                        save = false;
                        response.AppendLine($"__Something went wrong__ :/");
                        break;
                    }
                }

                if (save)
                {
                    dbContext.SaveChanges();
                }
                dbContext.Dispose();

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

// !createTempRole
            newCommand                     = new Command("createTempRole");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "`createTempRole name time` Create a role with specified name, which will be destroyed after specified time (e.g. `7d` or `12h` or `1d12h`)";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                ServerContext dbContext  = ServerContext.Create(this.Client.DbConnectionString);
                RoleConfig    roleConfig = await CreateTempRole(e, dbContext);

                if (roleConfig != null)
                {
                    dbContext.SaveChanges();
                }
                dbContext.Dispose();
            };
            commands.Add(newCommand);

// !createTempPublicRole
            newCommand                     = new Command("createTempPublicRole");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "`createTempRole name time` Create a role with specified name, which will be destroyed after specified time (e.g. `7d` or `12h` or `1d12h`) This role will also become a public - use the `join` command to get it.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                ServerContext dbContext  = ServerContext.Create(this.Client.DbConnectionString);
                RoleConfig    roleConfig = await CreateTempRole(e, dbContext);

                if (roleConfig != null)
                {
                    roleConfig.PermissionLevel = RolePermissionLevel.Public;
                    dbContext.SaveChanges();
                }
                dbContext.Dispose();
            };
            commands.Add(newCommand);

// !createColourRoles
            newCommand                     = new Command("createColourRoles");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Create 9 roles with various colours, you can find emoji representations of these colours in Valhalla - the Valkyrja support server.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.SendReplySafe(ErrorPermissionsString);

                    return;
                }

                await e.Server.Guild.CreateRoleAsync("purple", GuildPermissions.None, new Color(180, 136, 209));

                await e.Server.Guild.CreateRoleAsync("pink", GuildPermissions.None, new Color(255, 183, 255));

                await e.Server.Guild.CreateRoleAsync("orange", GuildPermissions.None, new Color(255, 165, 105));

                await e.Server.Guild.CreateRoleAsync("lightOrange", GuildPermissions.None, new Color(255, 186, 158));

                await e.Server.Guild.CreateRoleAsync("lightYellow", GuildPermissions.None, new Color(223, 223, 133));

                await e.Server.Guild.CreateRoleAsync("yellow", GuildPermissions.None, new Color(201, 192, 67));

                await e.Server.Guild.CreateRoleAsync("blue", GuildPermissions.None, new Color(92, 221, 255));

                await e.Server.Guild.CreateRoleAsync("cyan", GuildPermissions.None, new Color(150, 232, 221));

                await e.Server.Guild.CreateRoleAsync("green", GuildPermissions.None, new Color(46, 204, 113));

                await e.SendReplySafe("I've created them roles, but you're gonna have to set them up yourself at <https://valkyrja.app/config> because I don't know the details!\n" +
                                      "_You can use my colour emojis to set them up as reaction assigned roles. Get them in Valhalla: https://discord.gg/XgVvkXx_");
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("createColorRoles"));

// !removeStreamPermission
            newCommand                     = new Command("removeStreamPermission");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Removes Stream permission from all the roles.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.SendReplySafe("I ain't got the permissions.");

                    return;
                }

                int highestRolePosition = 0;
                foreach (SocketRole role in e.Server.Guild.Roles)
                {
                    if (role.Position > highestRolePosition)
                    {
                        highestRolePosition = role.Position;
                    }
                }

                if (e.Server.Guild.CurrentUser.Hierarchy < highestRolePosition)
                {
                    await e.SendReplySafe("I am not the top role in hierarchy. I really have to be on top to disable that thing on all the roles!");

                    return;
                }

                int    exceptions = 0;
                string response   = "Done with exceptions:\n";
                foreach (SocketRole role in e.Server.Guild.Roles.Where(r => r.Position < e.Server.Guild.CurrentUser.Hierarchy))
                {
                    try
                    {
                        await role.ModifyAsync(r => r.Permissions = new Optional <GuildPermissions>(role.Permissions.Modify(stream: false)));
                    }
                    catch (Exception)
                    {
                        response += $"`{role.Name}`\n";
                        if (++exceptions > 5)
                        {
                            response += "...and probably more...";
                            break;
                        }
                    }
                }

                if (exceptions == 0)
                {
                    response = "Done.";
                }

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

            return(commands);
        }
Пример #6
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);
            }
        }
Пример #7
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();
        }
        public List <Command> Init(IBotwinderClient iClient)
        {
            this.Client = iClient as BotwinderClient;
            List <Command> commands = new List <Command>();

            this.Client.Events.UserJoined += OnUserJoined;

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

            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Get a name, id and color of `roleID` or `roleName` parameter.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                guid              id         = 0;
                SocketRole        roleFromId = null;
                List <SocketRole> roles      = null;
                if (string.IsNullOrEmpty(e.TrimmedMessage) ||
                    (!(guid.TryParse(e.TrimmedMessage, out id) && (roleFromId = e.Server.Guild.GetRole(id)) != null) &&
                     !(roles = e.Server.Guild.Roles.Where(r => r.Name.ToLower().Contains(e.TrimmedMessage.ToLower())).ToList()).Any()))
                {
                    await iClient.SendMessageToChannel(e.Channel, "Role not found.");

                    return;
                }

                if (roleFromId != null)
                {
                    roles = new List <SocketRole>();
                    roles.Add(roleFromId);
                }

                StringBuilder response = new StringBuilder();
                foreach (SocketRole role in roles)
                {
                    string hex = BitConverter.ToString(new byte[] { role.Color.R, role.Color.G, role.Color.B }).Replace("-", "");
                    response.AppendLine($"Role: `{role.Name}`\n  Id: `{role.Id}`\n  Position: `{role.Position}`\n  Color: `rgb({role.Color.R},{role.Color.G},{role.Color.B})` | `hex(#{hex})`");
                }

                await iClient.SendMessageToChannel(e.Channel, response.ToString());
            };
            commands.Add(newCommand);

// !createRole
            newCommand                     = new Command("createRole");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Create a role with specified name.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    await iClient.SendMessageToChannel(e.Channel, "What role? Name? Do you want me to come up with something silly or what?");

                    return;
                }

                RestRole role = await e.Server.Guild.CreateRoleAsync(e.TrimmedMessage);

                string response = $"Role created: `{role.Name}`\n  Id: `{role.Id}`";
                await iClient.SendMessageToChannel(e.Channel, response);
            };
            commands.Add(newCommand);

// !publicRoles
            newCommand                     = new Command("publicRoles");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "See what Public Roles can you join on this server.";
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                List <RoleConfig> publicRoles = e.Server.Roles.Values.Where(r => r.PermissionLevel == RolePermissionLevel.Public).ToList();
                if (publicRoles == null || publicRoles.Count == 0)
                {
                    await iClient.SendMessageToChannel(e.Channel, ErrorNoPublicRoles);

                    return;
                }

                StringBuilder responseBuilder = new StringBuilder(string.Format("You can use `{0}join` and `{0}leave` commands with these Public Roles: ", e.Server.Config.CommandPrefix));
                Dictionary <Int64, List <RoleConfig> > groups = new Dictionary <Int64, List <RoleConfig> >();

                foreach (RoleConfig roleConfig in publicRoles)
                {
                    SocketRole role = e.Server.Guild.GetRole(roleConfig.RoleId);
                    if (role == null)
                    {
                        continue;
                    }

                    if (!groups.ContainsKey(roleConfig.PublicRoleGroupId))
                    {
                        List <RoleConfig> tempGroup = publicRoles.Where(r => r.PublicRoleGroupId == roleConfig.PublicRoleGroupId).ToList();
                        groups.Add(roleConfig.PublicRoleGroupId, tempGroup);
                    }
                }

                string GetRoleNames(List <RoleConfig> roleConfigs)
                {
                    return(e.Server.Guild.Roles.Where(r => roleConfigs.Any(rc => rc.RoleId == r.Id))
                           .Select(r => r.Name).ToNames());
                }

                if (groups.ContainsKey(0))
                {
                    responseBuilder.Append(GetRoleNames(groups[0]));
                }

                bool hadGroup = false;
                foreach (KeyValuePair <Int64, List <RoleConfig> > group in groups)
                {
                    if (group.Key == 0)
                    {
                        continue;
                    }

                    hadGroup = true;
                    responseBuilder.Append($"\n\n**Group #{group.Key}:** ");

                    responseBuilder.Append(GetRoleNames(group.Value));
                }

                if (hadGroup)
                {
                    responseBuilder.AppendLine("\n\n_(Where the `Group` roles are mutually exclusive - joining a `Group` role will remove any other role out of that group, that you already have.)_");
                }

                await iClient.SendMessageToChannel(e.Channel, responseBuilder.ToString());
            };
            commands.Add(newCommand);

// !join
            newCommand                     = new Command("join");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Use with parameter, name of a Role that you wish to join.";
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await iClient.SendMessageToChannel(e.Channel, ErrorPermissionsString);

                    return;
                }

                if (string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    await iClient.SendMessageToChannel(e.Channel, e.Command.Description);

                    return;
                }

                List <RoleConfig> publicRoles = e.Server.Roles.Values.Where(r => r.PermissionLevel == RolePermissionLevel.Public).ToList();
                if (publicRoles == null || publicRoles.Count == 0)
                {
                    await iClient.SendMessageToChannel(e.Channel, ErrorNoPublicRoles);

                    return;
                }

                IEnumerable <SocketRole> roles      = e.Server.Guild.Roles.Where(r => publicRoles.Any(rc => rc.RoleId == r.Id));
                IEnumerable <SocketRole> foundRoles = null;
                if (!(foundRoles = roles.Where(r => r.Name == e.TrimmedMessage)).Any() &&
                    !(foundRoles = roles.Where(r => r.Name.ToLower() == e.TrimmedMessage.ToLower())).Any() &&
                    !(foundRoles = roles.Where(r => r.Name.ToLower().Contains(e.TrimmedMessage.ToLower()))).Any())
                {
                    await iClient.SendMessageToChannel(e.Channel, ErrorRoleNotFound);

                    return;
                }

                if (foundRoles.Count() > 1)
                {
                    await iClient.SendMessageToChannel(e.Channel, ErrorTooManyFound);

                    return;
                }

                IEnumerable <guid> idsToLeave   = null;
                SocketRole         roleToAssign = foundRoles.First();
                Int64 groupId = publicRoles.First(r => r.RoleId == roleToAssign.Id).PublicRoleGroupId;

                if (groupId != 0)
                {
                    idsToLeave = publicRoles.Where(r => r.PublicRoleGroupId == groupId).Select(r => r.RoleId);
                }

                bool   removed  = false;
                string response = "Done!";
                try
                {
                    SocketGuildUser user = (e.Message.Author as SocketGuildUser);

                    if (idsToLeave != null)
                    {
                        foreach (guid id in idsToLeave)
                        {
                            if (user.Roles.All(r => r.Id != id))
                            {
                                continue;
                            }

                            SocketRole roleToLeave = e.Server.Guild.GetRole(id);
                            if (roleToLeave == null)
                            {
                                continue;
                            }

                            await user.RemoveRoleAsync(roleToLeave);

                            removed = true;
                        }
                    }

                    await user.AddRoleAsync(roleToAssign);
                } catch (Exception exception)
                {
                    if (exception is Discord.Net.HttpException ex && ex.HttpCode == System.Net.HttpStatusCode.Forbidden)
                    {
                        response = "Something went wrong, I may not have server permissions to do that.\n(Hint: <http://i.imgur.com/T8MPvME.png>)";
                    }
Пример #9
0
        public List <Command> Init(IBotwinderClient iClient)
        {
            this.Client = iClient as BotwinderClient;
            List <Command> commands = new List <Command>();

            this.Client.Events.UserJoined += OnUserJoined;

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

            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Get a name, id and color of `roleID` or `roleName` parameter.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                guid              id         = 0;
                SocketRole        roleFromId = null;
                List <SocketRole> roles      = null;
                if (string.IsNullOrEmpty(e.TrimmedMessage) ||
                    (!(guid.TryParse(e.TrimmedMessage, out id) && (roleFromId = e.Server.Guild.GetRole(id)) != null) &&
                     !(roles = e.Server.Guild.Roles.Where(r => r.Name.ToLower().Contains(e.TrimmedMessage.ToLower())).ToList()).Any()))
                {
                    await e.SendReplySafe("Role not found.");

                    return;
                }

                if (roleFromId != null)
                {
                    roles = new List <SocketRole>();
                    roles.Add(roleFromId);
                }

                StringBuilder response = new StringBuilder();
                foreach (SocketRole role in roles)
                {
                    string hex = BitConverter.ToString(new byte[] { role.Color.R, role.Color.G, role.Color.B }).Replace("-", "");
                    response.AppendLine($"Role: `{role.Name}`\n  Id: `{role.Id}`\n  Position: `{role.Position}`\n  Color: `rgb({role.Color.R},{role.Color.G},{role.Color.B})` | `hex(#{hex})`");
                }

                await e.SendReplySafe(response.ToString());
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("getrole"));

// !membersOf
            newCommand                     = new Command("membersOf");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Display a list of members of a role.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                string expression = e.TrimmedMessage;

                guid id = 0;
                IEnumerable <SocketRole> roles      = e.Server.Guild.Roles;
                IEnumerable <SocketRole> foundRoles = null;
                SocketRole role = null;

                if (!(guid.TryParse(expression, out id) && (role = e.Server.Guild.GetRole(id)) != null) &&
                    !(foundRoles = roles.Where(r => r.Name == expression)).Any() &&
                    !(foundRoles = roles.Where(r => r.Name.ToLower() == expression.ToLower())).Any() &&
                    !(foundRoles = roles.Where(r => r.Name.ToLower().Contains(expression.ToLower()))).Any())
                {
                    await e.SendReplySafe(ErrorRoleNotFound);

                    return;
                }

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

                    return;
                }

                if (role == null)
                {
                    role = foundRoles.First();
                }

                await e.Server.Guild.DownloadUsersAsync();

                List <string> names = role.Members.Select(u => u.GetUsername()).ToList();
                names.Sort();

                string response = names.Count == 0 ? "Nobody has this role." : $"Members of `{role.Name}` are:\n" + names.ToNamesList();
                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("listMembers"));

// !createRole
            newCommand                     = new Command("createRole");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Create a role with specified name.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.Message.Channel.SendMessageSafe(ErrorPermissionsString);

                    return;
                }
                if (string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    await e.SendReplySafe("What role? Name? Do you want me to come up with something silly or what?");

                    return;
                }

                RestRole role = await e.Server.Guild.CreateRoleAsync(e.TrimmedMessage, GuildPermissions.None);

                string response = $"Role created: `{role.Name}`\n  Id: `{role.Id}`";
                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);

// !createTempRole
            newCommand                     = new Command("createTempRole");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "`createTempRole name time` Create a role with specified name, which will be destroyed after specified time (e.g. `7d` or `12h` or `1d12h`)";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                ServerContext dbContext  = ServerContext.Create(this.Client.DbConnectionString);
                RoleConfig    roleConfig = await CreateTempRole(e, dbContext);

                if (roleConfig != null)
                {
                    dbContext.SaveChanges();
                }
                dbContext.Dispose();
            };
            commands.Add(newCommand);

// !createTempPublicRole
            newCommand                     = new Command("createTempPublicRole");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "`createTempRole name time` Create a role with specified name, which will be destroyed after specified time (e.g. `7d` or `12h` or `1d12h`) This role will also become a public - use the `join` command to get it.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                ServerContext dbContext  = ServerContext.Create(this.Client.DbConnectionString);
                RoleConfig    roleConfig = await CreateTempRole(e, dbContext);

                if (roleConfig != null)
                {
                    roleConfig.PermissionLevel = RolePermissionLevel.Public;
                    dbContext.SaveChanges();
                }
                dbContext.Dispose();
            };
            commands.Add(newCommand);

// !publicRoles
            newCommand                     = new Command("publicRoles");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "See what Public Roles can you join on this server.";
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                List <RoleConfig> publicRoles = e.Server.Roles.Values.Where(r => r.PermissionLevel == RolePermissionLevel.Public).ToList();
                if (publicRoles == null || publicRoles.Count == 0)
                {
                    await e.SendReplySafe(ErrorNoPublicRoles);

                    return;
                }

                ServerContext dbContext       = ServerContext.Create(this.Client.DbConnectionString);
                StringBuilder responseBuilder = new StringBuilder(string.Format("You can use `{0}join` and `{0}leave` commands with these Public Roles: ", e.Server.Config.CommandPrefix));
                Dictionary <Int64, List <RoleConfig> > groupRoles   = new Dictionary <Int64, List <RoleConfig> >();
                Dictionary <Int64, RoleGroupConfig>    groupConfigs = dbContext.PublicRoleGroups.Where(g => g.ServerId == e.Server.Id).ToDictionary(g => g.GroupId);
                dbContext.Dispose();

                foreach (RoleConfig roleConfig in publicRoles)
                {
                    SocketRole role = e.Server.Guild.GetRole(roleConfig.RoleId);
                    if (role == null)
                    {
                        continue;
                    }

                    if (!groupRoles.ContainsKey(roleConfig.PublicRoleGroupId))
                    {
                        List <RoleConfig> tempGroup = publicRoles.Where(r => r.PublicRoleGroupId == roleConfig.PublicRoleGroupId).ToList();
                        groupRoles.Add(roleConfig.PublicRoleGroupId, tempGroup);
                    }
                }

                string GetRoleNames(List <RoleConfig> roleConfigs)
                {
                    return(e.Server.Guild.Roles.Where(r => roleConfigs.Any(rc => rc.RoleId == r.Id))
                           .Select(r => r.Name).ToNames());
                }

                if (groupRoles.ContainsKey(0))
                {
                    responseBuilder.Append(GetRoleNames(groupRoles[0]));
                }

                foreach (KeyValuePair <Int64, List <RoleConfig> > groupRole in groupRoles)
                {
                    if (groupRole.Key == 0)
                    {
                        continue;
                    }

                    RoleGroupConfig groupConfig = groupConfigs.ContainsKey(groupRole.Key) ? groupConfigs[groupRole.Key] : new RoleGroupConfig();
                    string          name        = string.IsNullOrEmpty(groupConfig.Name) ? ("Group #" + groupRole.Key.ToString()) : groupConfig.Name;
                    responseBuilder.Append($"\n\n**{name}** - you can join {groupConfig.RoleLimit} of these:\n");

                    responseBuilder.Append(GetRoleNames(groupRole.Value));
                }

                await e.SendReplySafe(responseBuilder.ToString());
            };
            commands.Add(newCommand);

// !roleCounts
            newCommand                     = new Command("roleCounts");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Get some numbers about public roles for specific group.";
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                string expression = e.TrimmedMessage;

                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                IEnumerable <RoleGroupConfig> roleGroups  = dbContext.PublicRoleGroups.Where(g => g.ServerId == e.Server.Id);
                IEnumerable <RoleGroupConfig> foundGroups = null;

                if (string.IsNullOrEmpty(expression) || (
                        !(foundGroups = roleGroups.Where(g => g.Name == expression)).Any() &&
                        !(foundGroups = roleGroups.Where(g => (g.Name?.ToLower() ?? "") == expression.ToLower())).Any() &&
                        !(foundGroups = roleGroups.Where(g => g.Name?.ToLower().Contains(expression.ToLower()) ?? false)).Any()))
                {
                    await e.SendReplySafe(ErrorGroupNotFound);

                    dbContext.Dispose();
                    return;
                }

                if (foundGroups.Count() > 1)
                {
                    await e.SendReplySafe(ErrorTooManyGroupsFound);

                    dbContext.Dispose();
                    return;
                }

                await e.Server.Guild.DownloadUsersAsync();

                Int64 groupId = foundGroups.First().GroupId;
                dbContext.Dispose();

                IEnumerable <guid>       roleIds  = e.Server.Roles.Values.Where(r => r.PublicRoleGroupId == groupId).Select(r => r.RoleId);
                IEnumerable <SocketRole> roles    = e.Server.Guild.Roles.Where(r => roleIds.Contains(r.Id));
                StringBuilder            response = new StringBuilder();
                foreach (SocketRole role in roles)
                {
                    response.AppendLine($"**{role.Name}**: `{role.Members.Count()}`");
                }

                await e.SendReplySafe(response.ToString());
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("countGroup"));
            commands.Add(newCommand.CreateAlias("countRoles"));

// !join
            newCommand                     = new Command("join");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Use with parameter, name of a Role that you wish to join.";
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.SendReplySafe(ErrorPermissionsString);

                    return;
                }

                if (string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    await e.SendReplyUnsafe(e.Command.Description);

                    return;
                }

                List <RoleConfig> publicRoles = e.Server.Roles.Values.Where(r => r.PermissionLevel == RolePermissionLevel.Public).ToList();
                if (publicRoles == null || publicRoles.Count == 0)
                {
                    await e.SendReplySafe(ErrorNoPublicRoles);

                    return;
                }

                IEnumerable <SocketRole> roles      = e.Server.Guild.Roles.Where(r => publicRoles.Any(rc => rc.RoleId == r.Id));
                IEnumerable <SocketRole> foundRoles = null;
                if (!(foundRoles = roles.Where(r => r.Name == e.TrimmedMessage)).Any() &&
                    !(foundRoles = roles.Where(r => r.Name.ToLower() == e.TrimmedMessage.ToLower())).Any() &&
                    !(foundRoles = roles.Where(r => r.Name.ToLower().Contains(e.TrimmedMessage.ToLower()))).Any())
                {
                    await e.SendReplyUnsafe(ErrorRoleNotFound);

                    return;
                }

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

                    return;
                }

                RoleGroupConfig    groupConfig  = null;
                IEnumerable <guid> groupRoleIds = null;
                SocketRole         roleToAssign = foundRoles.First();
                Int64 groupId = publicRoles.First(r => r.RoleId == roleToAssign.Id).PublicRoleGroupId;

                if (groupId != 0)
                {
                    groupRoleIds = publicRoles.Where(r => r.PublicRoleGroupId == groupId).Select(r => r.RoleId);
                    int userHasCount = (e.Message.Author as SocketGuildUser).Roles.Count(r => groupRoleIds.Any(id => id == r.Id));

                    if (userHasCount > 0)
                    {
                        ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                        groupConfig = dbContext.PublicRoleGroups.FirstOrDefault(g => g.ServerId == e.Server.Id && g.GroupId == groupId);
                        dbContext.Dispose();

                        if (groupConfig != null && groupConfig.RoleLimit > 1 && userHasCount >= groupConfig.RoleLimit)
                        {
                            await e.SendReplyUnsafe($"You can only have {groupConfig.RoleLimit} roles from the `{groupConfig.Name}` group.");

                            return;
                        }
                    }
                }

                bool   removed  = false;
                string response = "Done!";
                try
                {
                    SocketGuildUser user = (e.Message.Author as SocketGuildUser);

                    if (groupRoleIds != null && (groupConfig == null || groupConfig.RoleLimit == 1))
                    {
                        foreach (guid id in groupRoleIds)
                        {
                            if (user.Roles.All(r => r.Id != id))
                            {
                                continue;
                            }

                            SocketRole roleToLeave = e.Server.Guild.GetRole(id);
                            if (roleToLeave == null)
                            {
                                continue;
                            }

                            await user.RemoveRoleAsync(roleToLeave);

                            removed = true;
                        }
                    }

                    await user.AddRoleAsync(roleToAssign);
                } catch (Exception exception)
                {
                    if (exception is Discord.Net.HttpException ex && ex.HttpCode == System.Net.HttpStatusCode.Forbidden ||
                        exception.Message.Contains("Missing Access"))
                    {
                        response = "Something went wrong, I may not have server permissions to do that.\n(Hint: <http://i.imgur.com/T8MPvME.png>)";
                    }
Пример #10
0
        private async Task MessageReceived(SocketMessage arg)
        {
            if (!sentMessages.Contains(arg) && arg.Author.Id != _c.CurrentUser.Id)
            {
                sentMessages.Add(arg);

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

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

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

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

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

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

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

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

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

                                    await tc.AddPermissionOverwriteAsync(role, allow_perms);

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

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

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

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

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

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

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

                                        await tc.AddPermissionOverwriteAsync(role, allow_perms);

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

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

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

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

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

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

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

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

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

                                    await tc.AddPermissionOverwriteAsync(role, allow_perms);

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

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

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

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

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

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

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

                                        await tc.AddPermissionOverwriteAsync(role, allow_perms);

                                        await tc.AddPermissionOverwriteAsync(_c.GetGuild(759101634948890645).EveryoneRole, deny_perms);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #11
0
        public UserRole Create(RestRole restRole)
        {
            var permissions = restRole.Permissions.ToList().Select(x => (Permission)x).ToList();

            return(new UserRole(restRole.Id, restRole.Name, permissions));
        }
        public static Task MissionWebhook(ulong guid, GuildConfig gConfig, IEnumerable <IMissionX> missions)
        {
            return(Task.Run(() =>
            {
                try
                {
                    if (gConfig == null || gConfig.Admin.MissionStates.Active == false || missions.Count() == 0)
                    {
                        return;
                    }

                    var discordApi = DIManager.Services.GetRequiredService <IDiscordRestApi>();;
                    var guild = discordApi.GetApi.GetGuildAsync(guid).Result;
                    if (guild == null)
                    {
                        return;
                    }

                    if (gConfig.Admin.MissionStates.Contains(MissionType.All_TheSame_Channel))
                    {
                        var channelId = gConfig.Admin.MissionStates.Get(MissionType.All_TheSame_Channel).ChannelId;
                        if (string.IsNullOrWhiteSpace(channelId))
                        {
                            return;
                        }
                        var channel = guild.GetTextChannelAsync(ulong.Parse(channelId)).Result;
                        if (channel == null)
                        {
                            return;
                        }
                        var sndList1 = missions.Take(11);
                        foreach (var mission in sndList1)
                        {
                            var embedMsg = mission.ToWebhookEmbed(gConfig.Owner.DefaultLanguage);
                            if (embedMsg == null)
                            {
                                continue;
                            }

                            string mentionTag = "";
                            string vl = gConfig.Admin.MissionStates.Get(MissionType.All_TheSame_Channel).RoleId;
                            RestRole r0 = null;
                            if (vl.Length != 0 && (mission.HasVBuck() || mission.AnyMythic()))
                            {
                                mentionTag = $"<@&{vl}>";
                                r0 = guild.GetRole(ulong.Parse(vl));
                                r0.ModifyAsync((o) =>
                                {
                                    o.Mentionable = true;
                                }).Wait();
                            }
                            channel.SendMessageAsync(mentionTag, false, embedMsg, Utils.RequestOption).Wait();
                            r0?.ModifyAsync((o) =>
                            {
                                o.Mentionable = false;
                            }).Wait();
                        }
                    }
                    else
                    {
                        var grpChannels = gConfig.Admin.MissionStates.Channels.GroupBy(f => f.ChannelId);

                        foreach (var chnl in grpChannels)
                        {
                            var channelId = chnl.Key;
                            if (string.IsNullOrWhiteSpace(channelId))
                            {
                                continue;
                            }

                            var channel = guild.GetTextChannelAsync(ulong.Parse(channelId)).Result;
                            if (channel == null)
                            {
                                continue;
                            }
                            Dictionary <int, List <string> > crossCheck = new Dictionary <int, List <string> >();
                            foreach (var missionType in chnl)
                            {
                                bool hasRoleId = !string.IsNullOrWhiteSpace(missionType.RoleId);
                                if (missionType.MissionType == MissionType.VBuck)
                                {
                                    var mentionRoleId = $"<@&{missionType.RoleId}>";
                                    var hashl = missions.Where(f => f.HasVBuck()).Select(f => f.GetHashCode());
                                    crossCheck = GenCrossCheckTable(crossCheck, hashl, mentionRoleId, hasRoleId);
                                }
                                else if (missionType.MissionType == MissionType.Mythic_Leader_Survivor)
                                {
                                    var mentionRoleId = $"<@&{missionType.RoleId}>";
                                    var hashl = missions.Where(f => f.AnyMythic()).Select(f => f.GetHashCode());
                                    crossCheck = GenCrossCheckTable(crossCheck, hashl, mentionRoleId, hasRoleId);
                                }
                                else if (missionType.MissionType == MissionType.Any_Legendary)
                                {
                                    var mentionRoleId = $"<@&{missionType.RoleId}>";
                                    var hashl = missions.Where(f => f.AnyLegendary()).OrderBy(f => f.OrderNumber).Take(5).Select(f => f.GetHashCode());
                                    crossCheck = GenCrossCheckTable(crossCheck, hashl, mentionRoleId, hasRoleId);
                                }
                                else if (missionType.MissionType == MissionType.Legendary_Survivor)
                                {
                                    var mentionRoleId = $"<@&{missionType.RoleId}>";
                                    var hashl = missions.Where(f => f.HasLegendarySurvivor()).Select(f => f.GetHashCode());
                                    crossCheck = GenCrossCheckTable(crossCheck, hashl, mentionRoleId, hasRoleId);
                                }
                                else if (missionType.MissionType == MissionType.Legendary_PerkUp)
                                {
                                    var mentionRoleId = $"<@&{missionType.RoleId}>";
                                    var hashl = missions.Where(f => f.HasLegendaryPerkUp(WorldName.Twine_Peaks)).OrderBy(f => f.OrderNumber).Take(4).Select(f => f.GetHashCode());
                                    crossCheck = GenCrossCheckTable(crossCheck, hashl, mentionRoleId, hasRoleId);
                                }
                                else if (missionType.MissionType == MissionType.Legendary_Hero)
                                {
                                    var mentionRoleId = $"<@&{missionType.RoleId}>";
                                    var hashl = missions.Where(f => f.HasLegendaryHero()).Select(f => f.GetHashCode());
                                    crossCheck = GenCrossCheckTable(crossCheck, hashl, mentionRoleId, hasRoleId);
                                }
                                else if (missionType.MissionType == MissionType.Legendary_Defender)
                                {
                                    var mentionRoleId = $"<@&{missionType.RoleId}>";
                                    var hashl = missions.Where(f => f.HasLegendaryDefender()).Select(f => f.GetHashCode());
                                    crossCheck = GenCrossCheckTable(crossCheck, hashl, mentionRoleId, hasRoleId);
                                }
                                else if (missionType.MissionType == MissionType.Legendary_Transform)
                                {
                                    var mentionRoleId = $"<@&{missionType.RoleId}>";
                                    var hashl = missions.Where(f => f.HasLegendaryAnyTransform()).Select(f => f.GetHashCode());
                                    crossCheck = GenCrossCheckTable(crossCheck, hashl, mentionRoleId, hasRoleId);
                                }
                                else if (missionType.MissionType == MissionType.Epic_PerkUp)
                                {
                                    var mentionRoleId = $"<@&{missionType.RoleId}>";
                                    var hashl = missions.Where(f => f.HasEpicPerkUp(WorldName.Twine_Peaks)).OrderBy(f => f.OrderNumber).Take(4).Select(f => f.GetHashCode());
                                    crossCheck = GenCrossCheckTable(crossCheck, hashl, mentionRoleId, hasRoleId);
                                }
                                else if (missionType.MissionType == MissionType.Epic_Hero)
                                {
                                    var mentionRoleId = $"<@&{missionType.RoleId}>";
                                    var hashl = missions.Where(f => f.HasEpicHero()).Select(f => f.GetHashCode());
                                    crossCheck = GenCrossCheckTable(crossCheck, hashl, mentionRoleId, hasRoleId);
                                }
                                else if (missionType.MissionType == MissionType.Pure_Drop_Of_Rain)
                                {
                                    var mentionRoleId = $"<@&{missionType.RoleId}>";
                                    var hashl = missions.Where(f => f.Has4xPureDropOfRain()).OrderByDescending(f => f.MissionLevel).Take(4).Select(f => f.GetHashCode());
                                    crossCheck = GenCrossCheckTable(crossCheck, hashl, mentionRoleId, hasRoleId);
                                }
                                else if (missionType.MissionType == MissionType.Eye_Of_Storm)
                                {
                                    var mentionRoleId = $"<@&{missionType.RoleId}>";
                                    var hashl = missions.Where(f => f.Has4xEyeOfStorm()).OrderByDescending(f => f.MissionLevel).Take(4).Select(f => f.GetHashCode());
                                    crossCheck = GenCrossCheckTable(crossCheck, hashl, mentionRoleId, hasRoleId);
                                }
                                else if (missionType.MissionType == MissionType.Lightning_In_Bottle)
                                {
                                    var mentionRoleId = $"<@&{missionType.RoleId}>";
                                    var hashl = missions.Where(f => f.Has4xLightningInABottle()).OrderByDescending(f => f.MissionLevel).Take(4).Select(f => f.GetHashCode());
                                    crossCheck = GenCrossCheckTable(crossCheck, hashl, mentionRoleId, hasRoleId);
                                }
                                else if (missionType.MissionType == MissionType.Storm_Shard)
                                {
                                    var mentionRoleId = $"<@&{missionType.RoleId}>";
                                    var hashl = missions.Where(f => f.Has4xStormShard()).OrderByDescending(f => f.MissionLevel).Take(4).Select(f => f.GetHashCode());
                                    crossCheck = GenCrossCheckTable(crossCheck, hashl, mentionRoleId, hasRoleId);
                                }
                                else if (missionType.MissionType == MissionType.Epic_Survivor)
                                {
                                    var mentionRoleId = $"<@&{missionType.RoleId}>";
                                    var hashl = missions.Where(f => f.HasEpicSurvivor()).OrderByDescending(f => f.MissionLevel).Take(6).Select(f => f.GetHashCode());
                                    crossCheck = GenCrossCheckTable(crossCheck, hashl, mentionRoleId, hasRoleId);
                                }
                            }
                            foreach (var key in crossCheck.Keys)
                            {
                                var mssn = missions.FirstOrDefault(f => f.GetHashCode() == key);
                                if (mssn == null)
                                {
                                    continue;
                                }
                                var embd = mssn.ToWebhookEmbed(gConfig.Owner.DefaultLanguage);
                                if (embd == null)
                                {
                                    continue;
                                }
                                string mentionTag = string.Empty;
                                List <Task> rls = new List <Task>();
                                if (crossCheck[key].Count > 0)
                                {
                                    mentionTag = string.Join(' ', crossCheck[key].ToArray());
                                    foreach (var item in crossCheck[key])
                                    {
                                        try
                                        {
                                            RestRole r1 = guild.GetRole(ulong.Parse(item.Substring(3, item.Length - 4)));
                                            rls.Add(r1.ModifyAsync((o) =>
                                            {
                                                o.Mentionable = true;
                                            }));
                                        }
                                        catch (Exception)
                                        {
                                        }
                                    }
                                    Task.WaitAll(rls.ToArray());
                                    rls.Clear();
                                }
                                channel.SendMessageAsync(mentionTag, false, embd, Utils.RequestOption).Wait();
                                foreach (var item in crossCheck[key])
                                {
                                    try
                                    {
                                        RestRole r1 = guild.GetRole(ulong.Parse(item.Substring(3, item.Length - 4)));
                                        rls.Add(r1.ModifyAsync((o) =>
                                        {
                                            o.Mentionable = false;
                                        }));
                                    }
                                    catch (Exception)
                                    {
                                    }
                                }
                                Task.WaitAll(rls.ToArray());
                            }
                        }
                    }
                }
                catch (Exception exception1)
                {
                    Log.Exception(exception1, Serilog.Events.LogEventLevel.Error);
                }
            }));
        }
Пример #13
0
        public List <Command> Init(IValkyrjaClient iClient)
        {
            this.Client = iClient as ValkyrjaClient;
            List <Command> commands = new List <Command>();

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

            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Restrict alert logging to search only one channel. Use with `set #channel` or `reset` argument.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.ManPage             = new ManPage("<set #channel | reset>", "`<set #channel>` - Restrict the alert-logging to keep an eye only on this specific #channel.\n\n`<reset>` - Reset the restriction, alert-logging will keep an eye on all the channels.");
            newCommand.OnExecute          += async e => {
                string        response  = "";
                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                ServerConfig  config    = dbContext.ServerConfigurations.AsQueryable().FirstOrDefault(c => c.ServerId == e.Server.Id);
                if (string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    response = "Invalid arguments.\n" + e.Command.ManPage.ToString(e.Server.Config.CommandPrefix + e.CommandId);
                }
                else if (config == null)
                {
                    response = "Server config was not found in the database. Please try again in a few minutes or contact support.";
                }
                else if (e.MessageArgs[0].ToLower() == "reset")
                {
                    config.AlertWhitelistId = 0;
                    response = "Done.";
                    dbContext.SaveChanges();
                }
                else if (e.MessageArgs.Length != 2 || e.MessageArgs[0].ToLower() != "set")
                {
                    response = "Invalid arguments.\n" + e.Command.ManPage.ToString(e.Server.Config.CommandPrefix + e.CommandId);
                }
                else if (e.MessageArgs.Length == 2 && guid.TryParse(e.MessageArgs[1].Trim('<', '#', '>'), out ulong channelid) && e.Server.Guild.GetChannel(channelid) != null)
                {
                    config.AlertWhitelistId = channelid;
                    response = "Done.";
                    dbContext.SaveChanges();
                }
                else
                {
                    response = "Channel not found.";
                }

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

// !getRole
            newCommand                     = new Command("getRole");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Get a name, id and color of `roleID` or `roleName` parameter.";
            newCommand.ManPage             = new ManPage("<RoleId | roleName>", "`<RoleId | roleName>` - Role to be displayed.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                guid              id         = 0;
                SocketRole        roleFromId = null;
                List <SocketRole> roles      = null;
                if (string.IsNullOrEmpty(e.TrimmedMessage) ||
                    (!(guid.TryParse(e.TrimmedMessage, out id) && (roleFromId = e.Server.Guild.GetRole(id)) != null) &&
                     !(roles = e.Server.Guild.Roles.Where(r => r.Name.ToLower().Contains(e.TrimmedMessage.ToLower())).ToList()).Any()))
                {
                    await e.SendReplySafe("Role not found.");

                    return;
                }

                if (roleFromId != null)
                {
                    roles = new List <SocketRole>();
                    roles.Add(roleFromId);
                }

                StringBuilder response = new StringBuilder();
                foreach (SocketRole role in roles)
                {
                    string hex = BitConverter.ToString(new byte[] { role.Color.R, role.Color.G, role.Color.B }).Replace("-", "");
                    response.AppendLine($"Role: `{role.Name}`\n  Id: `{role.Id}`\n  Position: `{role.Position}`\n  Color: `rgb({role.Color.R},{role.Color.G},{role.Color.B})` | `hex(#{hex})`");
                }

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

// !membersOf
            newCommand                     = new Command("membersOf");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Display a list of members of a role.";
            newCommand.ManPage             = new ManPage("<RoleId | roleName>", "`<RoleId | roleName>` - Members of this role will be printed.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                SocketRole role = e.Server.GetRole(e.TrimmedMessage, out string response);
                if (role == null)
                {
                    await e.SendReplySafe(response);

                    return;
                }

                await e.Server.Guild.DownloadUsersAsync();

                List <string> names = role.Members.Select(u => u.GetUsername()).ToList();
                names.Sort();

                response = names.Count == 0 ? "Nobody has this role." : $"Members of `{role.Name}` are:\n" + names.ToNamesList();
                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("listMembers"));

// !createRole
            newCommand                     = new Command("createRole");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Create a role with specified name.";
            newCommand.ManPage             = new ManPage("<roleName>", "`<roleName>` - Name of the new role.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.Message.Channel.SendMessageSafe(ErrorPermissionsString);

                    return;
                }
                if (string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    await e.SendReplySafe("What role? Name? Do you want me to come up with something silly or what?");

                    return;
                }

                RestRole role = await e.Server.Guild.CreateRoleAsync(e.TrimmedMessage, GuildPermissions.None);

                string response = $"Role created: `{role.Name}`\n  Id: `{role.Id}`";
                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);

// !createRoles
            newCommand                     = new Command("createRoles");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Create roles with specified names.";
            newCommand.ManPage             = new ManPage("<roleName1, roleName2, ...>", "`<roleName>` - Name of the new role. Use quotes if you want a name with multiple words/spaces.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.Message.Channel.SendMessageSafe(ErrorPermissionsString);

                    return;
                }
                if (string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    await e.SendReplySafe("Invalid arguments.\n" + e.Command.ManPage.ToString(e.Server.Config.CommandPrefix + e.CommandId));

                    return;
                }

                StringBuilder response = new StringBuilder("Roles created:\n");

                for (int i = 0; i < e.MessageArgs.Length; i++)
                {
                    RestRole role = await e.Server.Guild.CreateRoleAsync(e.MessageArgs[i], GuildPermissions.None);

                    response.AppendLine($"`{role.Id}` | `{role.Name}`");
                }

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

// !createPublicRoles
            newCommand                     = new Command("createPublicRoles");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Create public roles with specified names.";
            newCommand.ManPage             = new ManPage("<groupName> <roleName1, roleName2, ...>", "`<groupName>` - Name of the Role Group under which these roles will be created.\n\n`<roleName>` - Name of the new role. Use quotes if you want a name with multiple words/spaces.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.Message.Channel.SendMessageSafe(ErrorPermissionsString);

                    return;
                }
                if (e.MessageArgs == null || e.MessageArgs.Length < 2)
                {
                    await e.SendReplySafe("Invalid arguments.\n" + e.Command.ManPage.ToString(e.Server.Config.CommandPrefix + e.CommandId));

                    return;
                }

                StringBuilder response = new StringBuilder("Roles created:\n");

                Int64         groupId   = 1;
                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                IEnumerable <RoleGroupConfig> roleGroups = dbContext.PublicRoleGroups.AsQueryable().Where(g => g.ServerId == e.Server.Id);
                foreach (RoleGroupConfig group in roleGroups)
                {
                    if (groupId < group.GroupId)
                    {
                        groupId = group.GroupId;
                    }
                }

                RoleGroupConfig roleGroup = new RoleGroupConfig()
                {
                    ServerId  = e.Server.Id,
                    GroupId   = groupId,
                    Name      = e.MessageArgs[0],
                    RoleLimit = 1
                };
                dbContext.PublicRoleGroups.Add(roleGroup);

                bool save = true;
                for (int i = 1; i < e.MessageArgs.Length; i++)
                {
                    try
                    {
                        RestRole role = await e.Server.Guild.CreateRoleAsync(e.MessageArgs[i], GuildPermissions.None);

                        RoleConfig roleConfig = new RoleConfig()
                        {
                            ServerId          = e.Server.Id,
                            RoleId            = role.Id,
                            PermissionLevel   = RolePermissionLevel.Public,
                            PublicRoleGroupId = groupId
                        };
                        dbContext.Roles.Add(roleConfig);

                        response.AppendLine($"`{role.Id}` | `{role.Name}`");
                    }
                    catch (Exception)
                    {
                        save = false;
                        response.AppendLine($"__Something went wrong__ :/");
                        break;
                    }
                }

                if (save)
                {
                    dbContext.SaveChanges();
                }
                dbContext.Dispose();

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

// !prune
            newCommand                     = new Command("prune");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Kicks out all the inactive members.";
            newCommand.ManPage             = new ManPage("<n> [roleIDs] [yes]", "`<n>` - Number of days of user inactivity.\n\n`[roleIDs]` - An optional, whitespace delimited list of role IDs to include in the prune.\n\n`[yes]` - If specified \"yes\" will actually prune, only returns the counts otherwise.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner;
            newCommand.OnExecute          += async e => {
                int n = 0;
                if (e.MessageArgs == null || e.MessageArgs.Length < 1 || !int.TryParse(e.MessageArgs[0], out n))
                {
                    await e.SendReplySafe("Invalid Arguments.\n" + e.Command.ManPage.ToString(e.Server.Config.CommandPrefix + e.CommandId));

                    return;
                }
                bool   prune    = e.MessageArgs.Length > 1 && e.MessageArgs[e.MessageArgs.Length - 1].ToLower() == "yes";
                guid[] roleIDs  = e.MessageArgs.Length > 2 || (!prune && e.MessageArgs.Length > 1) ? e.MessageArgs.Skip(1).TakeWhile(r => guid.TryParse(r, out guid _)).Select(guid.Parse).ToArray() : null;
                string response = "";
                try
                {
                    int count = await e.Server.Guild.PruneUsersAsync(n, !prune, roleIDs);

                    response = prune ? $"I've kicked out `{count}` humans.\n_\\*waves*_" : $"I can kick out `{count}` humans. Should you wish to proceed, append `yes` to the command arguments (you can edit your message) as follows:\n `{e.Server.Config.CommandPrefix + e.CommandId} {e.TrimmedMessage} yes`";
                }
                catch (HttpException exception)
                {
                    await e.Server.HandleHttpException(exception, $"Command failed to prune users in <#{e.Channel.Id}>");

                    response = Utils.HandleHttpException(exception);
                }
                catch (Exception exception)
                {
                    await this.HandleException(exception, "Command prune", e.Server.Id);

                    response = "Unknown error.";
                }

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

/*
 * // !createTempRole
 *                      newCommand = new Command("createTempRole");
 *                      newCommand.Type = CommandType.Standard;
 *                      newCommand.Description = "`createTempRole name time` Create a role with specified name, which will be destroyed after specified time (e.g. `7d` or `12h` or `1d12h`)";
 *                      newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
 *                      newCommand.OnExecute += async e => {
 *                              ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
 *                              RoleConfig roleConfig = await CreateTempRole(e, dbContext);
 *                              if( roleConfig != null )
 *                                      dbContext.SaveChanges();
 *                              dbContext.Dispose();
 *                      };
 *                      commands.Add(newCommand);
 *
 * // !createTempPublicRole
 *                      newCommand = new Command("createTempPublicRole");
 *                      newCommand.Type = CommandType.Standard;
 *                      newCommand.Description = "`createTempRole name time` Create a role with specified name, which will be destroyed after specified time (e.g. `7d` or `12h` or `1d12h`) This role will also become a public - use the `join` command to get it.";
 *                      newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
 *                      newCommand.OnExecute += async e => {
 *                              ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
 *                              RoleConfig roleConfig = await CreateTempRole(e, dbContext);
 *                              if( roleConfig != null )
 *                              {
 *                                      roleConfig.PermissionLevel = RolePermissionLevel.Public;
 *                                      dbContext.SaveChanges();
 *                              }
 *                              dbContext.Dispose();
 *                      };
 *                      commands.Add(newCommand);*/

// !createColourRoles
            newCommand                     = new Command("createColourRoles");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Create 9 roles with various colours, you can find emoji representations of these colours in Valhalla - the Valkyrja support server.";
            newCommand.ManPage             = new ManPage("", "");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.SendReplySafe(ErrorPermissionsString);

                    return;
                }

                await e.Server.Guild.CreateRoleAsync("purple", GuildPermissions.None, new Color(180, 136, 209));

                await e.Server.Guild.CreateRoleAsync("pink", GuildPermissions.None, new Color(255, 183, 255));

                await e.Server.Guild.CreateRoleAsync("orange", GuildPermissions.None, new Color(255, 165, 105));

                await e.Server.Guild.CreateRoleAsync("lightOrange", GuildPermissions.None, new Color(255, 186, 158));

                await e.Server.Guild.CreateRoleAsync("lightYellow", GuildPermissions.None, new Color(223, 223, 133));

                await e.Server.Guild.CreateRoleAsync("yellow", GuildPermissions.None, new Color(201, 192, 67));

                await e.Server.Guild.CreateRoleAsync("blue", GuildPermissions.None, new Color(92, 221, 255));

                await e.Server.Guild.CreateRoleAsync("cyan", GuildPermissions.None, new Color(150, 232, 221));

                await e.Server.Guild.CreateRoleAsync("green", GuildPermissions.None, new Color(46, 204, 113));

                await e.SendReplySafe("I've created them roles, but you're gonna have to set them up yourself at <https://valkyrja.app/config> because I don't know the details!\n" +
                                      $"_You can use my colour emojis to set them up as reaction assigned roles. Get them in Valhalla: {GlobalConfig.DiscordInvite}_");
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("createColorRoles"));

// !removeStreamPermission
            newCommand                     = new Command("removeStreamPermission");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Removes Stream permission from all the roles.";
            newCommand.ManPage             = new ManPage("", "");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.SendReplySafe("I ain't got the permissions.");

                    return;
                }

                int highestRolePosition = 0;
                foreach (SocketRole role in e.Server.Guild.Roles)
                {
                    if (role.Position > highestRolePosition)
                    {
                        highestRolePosition = role.Position;
                    }
                }

                if (e.Server.Guild.CurrentUser.Hierarchy < highestRolePosition)
                {
                    await e.SendReplySafe("I am not the top role in hierarchy. I really have to be on top to disable that thing on all the roles!");

                    return;
                }

                int    exceptions = 0;
                string response   = "Done with exceptions:\n";
                foreach (SocketRole role in e.Server.Guild.Roles.Where(r => r.Position < e.Server.Guild.CurrentUser.Hierarchy))
                {
                    try
                    {
                        await role.ModifyAsync(r => r.Permissions = new Optional <GuildPermissions>(role.Permissions.Modify(stream: false)));
                    }
                    catch (Exception)
                    {
                        response += $"`{role.Name}`\n";
                        if (++exceptions > 5)
                        {
                            response += "...and probably more...";
                            break;
                        }
                    }
                }

                if (exceptions == 0)
                {
                    response = "Done.";
                }

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

            return(commands);
        }
Пример #14
0
        private async Task MessageReceived(SocketMessage arg)
        {
            SocketRole infectedRole = null;

            if (arg is SocketUserMessage message && !message.Author.IsBot && !message.Author.IsWebhook && message.Author is SocketGuildUser user1 && message.Channel is SocketGuildChannel channel)
            {
                if (!configs.Guilds.ContainsKey(user1.Guild.Id.ToString()))
                {
                    return;
                }
                if (!databases.Guilds.ContainsKey(user1.Guild.Id.ToString()))
                {
                    databases.Guilds.Add(user1.Guild.Id.ToString(), new GuildDatabase());
                }
                GuildConfig config = (configs.Guilds[user1.Guild.Id.ToString()]);
                if (infectedRole == null)
                {
                    infectedRole = user1.Guild.GetRole(config.InfectedRoleId);
                }
                SocketGuild guild = user1.Guild;
                if (infectedRole != null && !config.SafeChannelIds.Contains(message.Channel.Id) && !config.SuperSafeChannelIds.Contains(message.Channel.Id) && message.Content.ToLower().Contains("*cough*") && user1.Roles.Contains(infectedRole))
                {
                    bool found = false;
                    foreach (var item in config.SafeChannelIds)
                    {
                        var cat = guild.GetCategoryChannel(item);
                        if (cat == null || !cat.Channels.Contains(channel))
                        {
                            continue;
                        }
                        found = true;
                        break;
                    }
                    if (!found)
                    {
                        foreach (var item in config.SuperSafeChannelIds)
                        {
                            var cat = guild.GetCategoryChannel(item);
                            if (cat == null || !cat.Channels.Contains(channel))
                            {
                                continue;
                            }
                            found = true;
                            break;
                        }
                    }
                    if (!found)
                    {
                        var msgsa = message.Channel.GetMessagesAsync(config.InfectMessageLimit);
                        var msgs  = await msgsa.FlattenAsync();

                        // if (msgs.Where(p => p.Content.Contains("*cough*") && p.Author.Id == user1.Id).Count() == 0)
                        {
                            IMessage[] array = msgs.Where(p => !p.Author.IsBot && !p.Author.IsWebhook && p.Author.Id != user1.Id && p.Timestamp.UtcDateTime.Add(TimeSpan.FromSeconds(config.SafeTimeSeconds)) >= DateTime.UtcNow && p.Author is SocketGuildUser user && !user.Roles.Contains(infectedRole)).ToArray();
                            if (array.Length != 0)
                            {
                                IMessage msg2 = array[rng.Next(array.Length)];
                                if (msg2 is RestUserMessage message2 && message2.Author is SocketGuildUser user2)
                                {
                                    await InfectUser(user2, infectedRole, user1);
                                    await SaveData();

                                    string name = string.IsNullOrWhiteSpace(user1.Nickname) ? user1.Username : user1.Nickname;
                                    await message2.ReplyAsync($"{name} infected you with {config.VirusName}!");
                                }
                            }
                        }
                    }
                }
                if (infectedRole != null && !user1.Roles.Contains(infectedRole) && !config.SuperSafeChannelIds.Contains(message.Channel.Id) && rng.Next(100) < config.AutoInfectPercent)
                {
                    bool found = false;
                    foreach (var item in config.SuperSafeChannelIds)
                    {
                        var cat = guild.GetCategoryChannel(item);
                        if (cat == null || !cat.Channels.Contains(channel))
                        {
                            continue;
                        }
                        found = true;
                        break;
                    }
                    if (!found)
                    {
                        await InfectUser(user1, infectedRole);
                        await SaveData();

                        await message.ReplyAsync($"Somehow, you were infected with {config.VirusName}!");
                    }
                }
                if (infectedRole != null && message.Content.ToLower().StartsWith(config.StatsCommand.ToLower()))
                {
                    string[] infected = infectedRole.Members.OrderByDescending(p =>
                    {
                        if (databases.Guilds[user1.Guild.Id.ToString()].InfectedTimestamps.ContainsKey(p.Id.ToString()))
                        {
                            return(databases.Guilds[user1.Guild.Id.ToString()].InfectedTimestamps[p.Id.ToString()]);
                        }
                        return(long.MinValue);
                    }).Select(p =>
                    {
                        string time = "N/A";
                        if (databases.Guilds[user1.Guild.Id.ToString()].InfectedTimestamps.ContainsKey(p.Id.ToString()))
                        {
                            time = DateTime.MinValue.AddTicks(databases.Guilds[user1.Guild.Id.ToString()].InfectedTimestamps[p.Id.ToString()]).ToString();
                        }
                        return($"{p.Username}#{p.Discriminator} was infected at {time}");
                    }).ToArray();
                    string output = "";
                    for (int i = 0; i < infected.Length && i < config.StatsMaxInfectedListings; i++)
                    {
                        if (i != 0)
                        {
                            output += "\n";
                        }
                        output += infected[i];
                    }
                    EmbedBuilder emb = new EmbedBuilder();
                    emb.WithColor(config.InfectedRoleColorRed, config.InfectedRoleColorGreen, config.InfectedRoleColorBlue);
                    emb.WithTitle(config.VirusName);
                    emb.WithDescription(output);
                    await message.ReplyAsync(embed : emb.Build());

                    // string path = Path.GetTempFileName();
                    string path = Path.GetRandomFileName() + ".png";
                    StatsDraw.Draw(path, user1.Guild, databases.Guilds[user1.Guild.Id.ToString()].InfectedWho, config.StatsMaxInfectedListings);
                    await message.Channel.SendFileAsync(path);

                    File.Delete(path);
                }
                if (user1.GuildPermissions.ManageRoles && message.Content.ToLower().StartsWith(config.ResetCommand.ToLower()))
                {
                    if (infectedRole != null)
                    {
                        await infectedRole.DeleteAsync();
                    }
                    RestRole role = await user1.Guild.CreateRoleAsync(config.InfectedRoleName, GuildPermissions.None, new Discord.Color(config.InfectedRoleColorRed, config.InfectedRoleColorGreen, config.InfectedRoleColorBlue), false, false);

                    configs.Guilds[user1.Guild.Id.ToString()].InfectedRoleId = role.Id;
                    databases.Guilds[user1.Guild.Id.ToString()].InfectedTimestamps.Clear();
                    databases.Guilds[user1.Guild.Id.ToString()].InfectedWho.Clear();
                    await SaveData();

                    await message.ReplyAsync($"{config.VirusName} has been contained.");
                }
            }
        }