Ejemplo n.º 1
0
        public List <Command> Init(IBotwinderClient iClient)
        {
            this.Client = iClient as BotwinderClient;
            List <Command> commands = new List <Command>();

            this.Client.Events.MessageReceived += OnMessageReceived;

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

            newCommand.Type        = CommandType.Standard;
            newCommand.Description = "Find out what's your level!";
            newCommand.IsPremiumServerwideCommand = true;
            newCommand.RequiredPermissions        = PermissionType.Everyone;
            newCommand.OnExecute += async e => {
                if (!e.Server.Config.ExpEnabled)
                {
                    await e.SendReplySafe(ExpDisabledString);

                    return;
                }

                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                UserData      userData  = dbContext.GetOrAddUser(e.Server.Id, e.Message.Author.Id);

                string response = string.Format(LevelNullString, userData.Level);

                SocketRole role = null;
                if (userData.Level > 0 &&
                    (role = e.Server.Roles.Values.Where(r => r.ExpLevel == userData.Level)
                            .Select(r => e.Server.Guild.GetRole(r.RoleId)).FirstOrDefault()) != null)
                {
                    response = string.Format(LevelString, role.Name, userData.Level);
                }

                Int64 expAtLevel = GetTotalExpAtLevel(e.Server.Config.BaseExpToLevelup, userData.Level + 1);
                Int64 expToLevel = expAtLevel - userData.Exp;

                if (e.Server.Config.ExpPerMessage != 0 && e.Server.Config.ExpPerAttachment != 0)
                {
                    response += string.Format(ThingsToLevel, expToLevel / e.Server.Config.ExpPerMessage, expToLevel / e.Server.Config.ExpPerAttachment);
                }
                else if (e.Server.Config.ExpPerMessage != 0)
                {
                    response += string.Format(MessagesToLevel, expToLevel / e.Server.Config.ExpPerMessage);
                }
                else if (e.Server.Config.ExpPerAttachment != 0)
                {
                    response += string.Format(ImagesToLevel, expToLevel / e.Server.Config.ExpPerAttachment);
                }

                await e.SendReplySafe(response);

                dbContext.Dispose();
            };
            commands.Add(newCommand);


            return(commands);
        }
Ejemplo n.º 2
0
        public List <Command> Init(IBotwinderClient iClient)
        {
            this.Client = iClient as BotwinderClient;

            this.Client.Events.UserJoined            += OnUserJoined;
            this.Client.Events.UserLeft              += OnUserLeft;
            this.Client.Events.UserVoiceStateUpdated += OnUserVoice;
            this.Client.Events.MessageDeleted        += OnMessageDeleted;
            this.Client.Events.MessageUpdated        += OnMessageUpdated;
            this.Client.Events.MessageReceived       += OnMessageReceived;
            this.Client.Events.UserBanned            += OnUserBanned;
            this.Client.Events.UserUnbanned          += OnUserUnbanned;
            this.Client.Events.LogWarning            += LogWarning;
            this.Client.Events.LogBan            += LogBan;
            this.Client.Events.LogUnban          += LogUnban;
            this.Client.Events.LogKick           += LogKick;
            this.Client.Events.LogMute           += LogMute;
            this.Client.Events.LogUnmute         += LogUnmute;
            this.Client.Events.LogMutedChannel   += LogMutedChannel;
            this.Client.Events.LogUnmutedChannel += LogUnmutedChannel;

            this.Client.Events.LogPublicRoleJoin  += LogPublicRoleJoin;
            this.Client.Events.LogPublicRoleLeave += LogPublicRoleLeave;
            this.Client.Events.LogPromote         += LogPromote;
            this.Client.Events.LogDemote          += LogDemote;

            return(new List <Command>());
        }
Ejemplo n.º 3
0
        public async Task Update(IBotwinderClient iClient)
        {
            BotwinderClient client    = iClient as BotwinderClient;
            ServerContext   dbContext = ServerContext.Create(client.DbConnectionString);
            bool            save      = false;
            DateTime        minTime   = DateTime.MinValue + TimeSpan.FromMinutes(1);

            //Channels
            List <ChannelConfig> channelsToRemove = new List <ChannelConfig>();

            foreach (ChannelConfig channelConfig in dbContext.Channels.Where(c => c.Temporary))
            {
                Server server;
                if (!client.Servers.ContainsKey(channelConfig.ServerId) ||
                    (server = client.Servers[channelConfig.ServerId]) == null)
                {
                    continue;
                }

                //Temporary voice channels
                SocketGuildChannel channel = server.Guild.GetChannel(channelConfig.ChannelId);
                if (channel != null &&
                    channel.CreatedAt < DateTimeOffset.UtcNow - this.TempChannelDelay &&
                    !channel.Users.Any())
                {
                    try
                    {
                        await channel.DeleteAsync();

                        channelConfig.Temporary = false;
                        channelsToRemove.Add(channelConfig);
                        save = true;
                    }
                    catch (Exception) { }
                }
                else if (channel == null)
                {
                    channelConfig.Temporary = false;
                    channelsToRemove.Add(channelConfig);
                    save = true;
                }
            }

            if (channelsToRemove.Any())
            {
                dbContext.Channels.RemoveRange(channelsToRemove);
            }

            if (save)
            {
                dbContext.SaveChanges();
            }
            dbContext.Dispose();
        }
Ejemplo n.º 4
0
        public List <Command> Init(IBotwinderClient iClient)
        {
            this.Client = iClient as BotwinderClient;

            this.Client.Events.UserJoined            += OnUserJoined;
            this.Client.Events.UserLeft              += OnUserLeft;
            this.Client.Events.UserVoiceStateUpdated += OnUserVoice;
            this.Client.Events.MessageDeleted        += OnMessageDeleted;
            this.Client.Events.MessageUpdated        += OnMessageUpdated;
            this.Client.Events.UserBanned            += async(user, guild) => {
                Server server;
                if (!this.Client.Servers.ContainsKey(guild.Id) || (server = this.Client.Servers[guild.Id]) == null ||
                    this.RecentlyBannedUserIDs.Contains(user.Id))
                {
                    return;
                }

                await LogBan(server, user.GetUsername(), user.Id, "unknown", "permanently", null);
            };
            this.Client.Events.UserUnbanned += async(user, guild) => {
                Server server;
                if (!this.Client.Servers.ContainsKey(guild.Id) || (server = this.Client.Servers[guild.Id]) == null ||
                    this.RecentlyUnbannedUserIDs.Contains(user.Id))
                {
                    return;
                }

                await LogUnban(server, user.GetUsername(), user.Id, null);
            };

            this.Client.Events.LogBan    += LogBan;
            this.Client.Events.LogUnban  += LogUnban;
            this.Client.Events.LogKick   += LogKick;
            this.Client.Events.LogMute   += LogMute;
            this.Client.Events.LogUnmute += LogUnmute;

            this.Client.Events.LogPublicRoleJoin  += LogPublicRoleJoin;
            this.Client.Events.LogPublicRoleLeave += LogPublicRoleLeave;
            this.Client.Events.LogPromote         += LogPromote;
            this.Client.Events.LogDemote          += LogDemote;

            return(new List <Command>());
        }
Ejemplo n.º 5
0
        public async Task RunAndWait(int shardIdOverride = -1)
        {
            while (true)
            {
                this.Bot = new BotwinderClient(shardIdOverride);
                InitModules();

                try
                {
                    await this.Bot.Connect();

                    this.Bot.Events.Initialize += InitCommands;
                    await Task.Delay(-1);
                }
                catch (Exception e)
                {
                    await this.Bot.LogException(e, "--BotwinderClient crashed.");

                    this.Bot.Dispose();
                }
            }
        }
Ejemplo n.º 6
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);
        }
Ejemplo n.º 7
0
        public List <Command> Init(IBotwinderClient iClient)
        {
            this.Client = iClient as BotwinderClient;
            List <Command> commands = new List <Command>();

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

            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Display your memo. If used with a username or @mention, it will display someone else' memo.";
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Config.MemoEnabled)
                {
                    await e.SendReplySafe("Memo is disabled on this server.");

                    return;
                }

                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                string        response  = "";

                if (!string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    string     expression = e.TrimmedMessage.ToLower();
                    SocketUser user       = e.Message.MentionedUsers.FirstOrDefault();
                    if (user == null)
                    {
                        user = e.Server.Guild.Users.FirstOrDefault(u => (u?.Username != null && u.Username.ToLower() == expression) || (u?.Nickname != null && u.Nickname.ToLower() == expression));
                    }

                    if (user == null)
                    {
                        response = NotFoundString;
                    }
                    else
                    {
                        UserData userData = dbContext.GetOrAddUser(e.Server.Id, user.Id);
                        if (string.IsNullOrEmpty(userData.Memo))
                        {
                            response = string.Format(NoMemoOtherString, user.GetNickname(), e.CommandId);
                        }
                        else
                        {
                            response = string.Format(MemoOtherString, user.GetNickname(), e.CommandId, userData.Memo);
                        }
                    }
                }
                else
                {
                    UserData userData = dbContext.GetOrAddUser(e.Server.Id, e.Message.Author.Id);
                    if (string.IsNullOrEmpty(userData.Memo))
                    {
                        response = string.Format(NoMemoString, e.CommandId);
                    }
                    else
                    {
                        response = string.Format(MemoString, e.CommandId, userData.Memo);
                    }
                }

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

// !setMemo
            newCommand                     = new Command("setMemo");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Set your memo.";
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Config.MemoEnabled)
                {
                    await e.SendReplySafe("Memo is disabled on this server.");

                    return;
                }

                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                string        response  = "";

                UserData userData = dbContext.GetOrAddUser(e.Server.Id, e.Message.Author.Id);
                if (string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    userData.Memo = "";
                    response      = ClearedString;
                }
                else
                {
                    userData.Memo = e.TrimmedMessage;
                    response      = string.Format(SetString, userData.Memo);
                }

                dbContext.SaveChanges();
                dbContext.Dispose();
                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("setmemo"));

// !profile
            newCommand                     = new Command("profile");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Display your profile. If used with a username or @mention, it will display someone else' profile. Get Help: setProfile --help";
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                if (!this.Client.IsPremium(e.Server) && !this.Client.IsTrialServer(e.Server.Id))
                {
                    await e.SendReplySafe("User profiles are a subscriber-only feature.");

                    return;
                }

                if (!e.Server.Config.ProfileEnabled)
                {
                    await e.SendReplySafe("User profiles are disabled on this server.");

                    return;
                }

                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);

                if (!string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    string     expression = e.TrimmedMessage.ToLower();
                    SocketUser user       = e.Message.MentionedUsers.FirstOrDefault();
                    if (user == null)
                    {
                        user = e.Server.Guild.Users.FirstOrDefault(u => (u?.Username != null && u.Username == e.TrimmedMessage) || (u?.Nickname != null && u.Nickname == e.TrimmedMessage));
                    }
                    if (user == null)
                    {
                        user = e.Server.Guild.Users.FirstOrDefault(u => (u?.Username != null && u.Username.ToLower() == expression) || (u?.Nickname != null && u.Nickname.ToLower() == expression));
                    }
                    if (user == null)
                    {
                        user = e.Server.Guild.Users.FirstOrDefault(u => (u?.Username != null && u.Username.ToLower().Contains(expression)) || (u?.Nickname != null && u.Nickname.ToLower().Contains(expression)));
                    }

                    if (user == null)
                    {
                        await e.SendReplySafe(NotFoundString);
                    }
                    else if (user.Id == this.Client.DiscordClient.CurrentUser.Id)
                    {
                        await e.Channel.SendMessageAsync("", embed : GetBotwinderEmbed(user as SocketGuildUser));
                    }
                    else
                    {
                        await e.Channel.SendMessageAsync("", embed : GetProfileEmbed(dbContext, e.Server, user as SocketGuildUser));
                    }
                }
                else
                {
                    await e.Channel.SendMessageAsync("", embed : GetProfileEmbed(dbContext, e.Server, e.Message.Author as SocketGuildUser));
                }

                dbContext.Dispose();
            };
            commands.Add(newCommand);

// !sendProfile
            newCommand                     = new Command("sendProfile");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Send your profile to preconfigured introduction channel. Get Help: setProfile --help";
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                if (!this.Client.IsPremium(e.Server) && !this.Client.IsTrialServer(e.Server.Id))
                {
                    await e.SendReplySafe("User profiles are a subscriber-only feature.");

                    return;
                }

                IMessageChannel channel = null;
                if (!e.Server.Config.ProfileEnabled || e.Server.Config.ProfileChannelId == 0 || (channel = e.Server.Guild.GetTextChannel(e.Server.Config.ProfileChannelId)) == null)
                {
                    await e.SendReplySafe("User profiles do not have a channel configured.");

                    return;
                }

                List <IMessage> messages        = new List <IMessage>();
                guid            lastMessage     = 0;
                int             downloadedCount = 0;
                do
                {
                    IMessage[] downloaded = await channel.GetMessagesAsync(lastMessage, Direction.After, 100, CacheMode.AllowDownload).Flatten().ToArray();

                    lastMessage     = messages.FirstOrDefault()?.Id ?? 0;
                    downloadedCount = downloaded.Length;
                    if (downloaded.Any())
                    {
                        messages.AddRange(downloaded);
                    }
                } while(downloadedCount >= 100 && lastMessage > 0);

                IMessage message = messages.FirstOrDefault(m => guid.TryParse(this.UserIdRegex.Match(m.Content).Value, out guid id) && id == e.Message.Author.Id);
                if (message != null)
                {
                    await message.DeleteAsync();
                }

                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);

                await channel.SendMessageAsync($"<@{e.Message.Author.Id}>'s introduction:", embed : GetProfileEmbed(dbContext, e.Server, e.Message.Author as SocketGuildUser));

                await e.SendReplySafe("It haz been done.");

                dbContext.Dispose();
            };
            commands.Add(newCommand);

// !getProfile
            newCommand                     = new Command("getProfile");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Get the source used to set your profile.";
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                if (!this.Client.IsPremium(e.Server) && !this.Client.IsTrialServer(e.Server.Id))
                {
                    await e.SendReplySafe("User profiles are a subscriber-only feature.");

                    return;
                }

                if (!e.Server.Config.ProfileEnabled)
                {
                    await e.SendReplySafe("User profiles are disabled on this server.");

                    return;
                }

                StringBuilder response              = new StringBuilder();
                ServerContext dbContext             = ServerContext.Create(this.Client.DbConnectionString);
                IEnumerable <ProfileOption> options = dbContext.ProfileOptions.Where(o => o.ServerId == e.Server.Id).OrderBy(o => o.Order);
                foreach (ProfileOption option in options)
                {
                    UserProfileOption userOption = dbContext.UserProfileOptions.FirstOrDefault(o => o.ServerId == e.Server.Id && o.UserId == e.Message.Author.Id && o.Option == option.Option);
                    if (userOption == null || string.IsNullOrWhiteSpace(userOption.Value))
                    {
                        continue;
                    }

                    response.Append($"{userOption.Option} {userOption.Value} ");
                }
                response.Append("\n```");

                string responseString = "There ain't no profile to get! >_<";
                if (response.Length > 0)
                {
                    responseString = $"```\n{e.Server.Config.CommandPrefix}setProfile {response.ToString()}";
                }
                await e.SendReplySafe(responseString);

                dbContext.Dispose();
            };
            commands.Add(newCommand);

// !setProfile
            newCommand                     = new Command("setProfile");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Set your profile. Get Help: setProfile --help";
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                if (!this.Client.IsPremium(e.Server) && !this.Client.IsTrialServer(e.Server.Id))
                {
                    await e.SendReplySafe("User profiles are a subscriber-only feature.");

                    return;
                }

                if (!e.Server.Config.ProfileEnabled)
                {
                    await e.SendReplySafe("User profiles are disabled on this server.");

                    return;
                }

                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                StringBuilder response  = new StringBuilder();

                IEnumerable <ProfileOption> options = dbContext.ProfileOptions.Where(o => o.ServerId == e.Server.Id).OrderBy(o => o.Order);
                int maxOptionLength = 0;
                foreach (ProfileOption option in options)
                {
                    if (maxOptionLength < option.OptionAlt.Length)
                    {
                        maxOptionLength = option.OptionAlt.Length;
                    }
                }

                MatchCollection emptyOptions = this.ProfileEmptyOptionRegex.Matches(e.TrimmedMessage);

                if (string.IsNullOrEmpty(e.TrimmedMessage) || (emptyOptions.Count > 0 && emptyOptions.Cast <Match>().Any(o => o.Value == "-h" || o.Value == "--help")))
                {
                    response.AppendLine("```md\nSet your profile fields with the following parameters:");
                    foreach (ProfileOption o in options)
                    {
                        response.Append($"  [ {o.Option} ][ {o.OptionAlt}");
                        response.Append(' ', maxOptionLength - o.OptionAlt.Length);
                        response.AppendLine($" ] | {o.Label}");
                    }

                    response.AppendLine($"\nExample:\n  {e.Server.Config.CommandPrefix}{e.CommandId} --twitter @RheaAyase -y youtube.com/RheaAyase");
                    response.AppendLine($"\nTo null one of the options you have already set, leave it empty:\n  {e.Server.Config.CommandPrefix}{e.CommandId} --twitter -y\n```");
                    dbContext.Dispose();
                    await e.SendReplySafe(response.ToString());

                    return;
                }

                foreach (Match match in emptyOptions)
                {
                    ProfileOption option = options.FirstOrDefault(o => o.Option == match.Value || o.OptionAlt == match.Value);
                    if (option == null)
                    {
                        continue;
                    }
                    UserProfileOption userOption = dbContext.UserProfileOptions.FirstOrDefault(o => o.ServerId == e.Server.Id && o.UserId == e.Message.Author.Id && o.Option == option.Option);
                    if (userOption == null)
                    {
                        continue;
                    }

                    dbContext.UserProfileOptions.Remove(userOption);
                }

                MatchCollection matches = this.ProfileParamRegex.Matches(e.TrimmedMessage);
                foreach (Match match in matches)
                {
                    string optionString = this.ProfileOptionRegex.Match(match.Value).Value;
                    string value        = match.Value.Substring(optionString.Length + 1).Replace('`', '\'');
                    if (value.Length >= UserProfileOption.ValueCharacterLimit)
                    {
                        await e.SendReplySafe($"`{optionString}` is too long! (It's {value.Length} characters while the limit is {UserProfileOption.ValueCharacterLimit})");

                        dbContext.Dispose();
                        return;
                    }

                    ProfileOption option = options.FirstOrDefault(o => o.Option == optionString || o.OptionAlt == optionString);
                    if (option == null)
                    {
                        continue;
                    }

                    UserProfileOption userOption = dbContext.UserProfileOptions.FirstOrDefault(o => o.ServerId == e.Server.Id && o.UserId == e.Message.Author.Id && o.Option == option.Option);
                    if (userOption == null)
                    {
                        userOption = new UserProfileOption()
                        {
                            ServerId = e.Server.Id,
                            UserId   = e.Message.Author.Id,
                            Option   = option.Option
                        };
                        dbContext.UserProfileOptions.Add(userOption);
                    }

                    userOption.Value = value;
                }

                dbContext.SaveChanges();

                await e.Channel.SendMessageAsync("", embed : GetProfileEmbed(dbContext, e.Server, e.Message.Author as SocketGuildUser));

                dbContext.Dispose();
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("setprofile"));

            return(commands);
        }
Ejemplo n.º 8
0
        public List <Command> Init(IBotwinderClient iClient)
        {
            this.Client = iClient as BotwinderClient;
            List <Command> commands = new List <Command>();

            this.Client.Events.UserJoined += OnUserJoined;

            // Replaced by cluster solution in the Update.

            /* this.Client.Events.MessageReceived += async message => {
             *      if( message.Channel is IDMChannel )
             *              await VerifyUserHash(message.Author.Id, message.Content);
             * }; */

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

            newCommand.Type        = CommandType.Standard;
            newCommand.Description = "This will send you some info about verification. You can use this with a parameter to send the info to your friend - you have to @mention them.";
            newCommand.OnExecute  += async e => {
                if (!e.Server.Config.VerificationEnabled)
                {
                    await this.Client.SendMessageToChannel(e.Channel, "Verification is disabled on this server.");

                    return;
                }

                ServerContext   dbContext      = ServerContext.Create(this.Client.DbConnectionString);
                List <UserData> mentionedUsers = this.Client.GetMentionedUsersData(dbContext, e);
                string          response       = InvalidParametersString;

                // Admin verified someone.
                if (e.MessageArgs != null && e.MessageArgs.Length > 1 &&
                    e.Server.IsAdmin(e.Message.Author as SocketGuildUser) &&
                    e.MessageArgs[e.MessageArgs.Length - 1] == "force")
                {
                    if (!mentionedUsers.Any())
                    {
                        await this.Client.SendMessageToChannel(e.Channel, UserNotFoundString);

                        dbContext.Dispose();
                        return;
                    }

                    await VerifyUsers(e.Server, mentionedUsers);                     // actually verify people

                    response = string.Format(VerifiedString, mentionedUsers.Select(u => u.UserId).ToMentions());
                    dbContext.SaveChanges();
                }
                else if (string.IsNullOrEmpty(e.TrimmedMessage))                  // Verify the author.
                {
                    UserData userData = dbContext.GetOrAddUser(e.Server.Id, e.Message.Author.Id);
                    await VerifyUsersPm(e.Server, new List <UserData> {
                        userData
                    });

                    response = SentString;
                }
                else if (mentionedUsers.Any())                  // Verify mentioned users.
                {
                    await VerifyUsersPm(e.Server, mentionedUsers);

                    response = MentionedString;
                }

                await this.Client.SendMessageToChannel(e.Channel, response);

                dbContext.Dispose();
            };
            commands.Add(newCommand);


            return(commands);
        }
        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>)";
                    }
Ejemplo n.º 10
0
        public List <Command> Init(IBotwinderClient iClient)
        {
            this.Client = iClient as BotwinderClient;
            List <Command> commands = new List <Command>();

            this.Client.Events.MessageReceived += OnMessageReceived;

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

            newCommand.Type        = CommandType.Standard;
            newCommand.Description = "Check how many cookies you've got.";
            newCommand.IsPremiumServerwideCommand = true;
            newCommand.RequiredPermissions        = PermissionType.Everyone;
            newCommand.OnExecute += async e => {
                if (!e.Server.Config.KarmaEnabled)
                {
                    await e.SendReplySafe(KarmaDisabledString);

                    return;
                }

                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                UserData      userData  = dbContext.GetOrAddUser(e.Server.Id, e.Message.Author.Id);

                await e.SendReplySafe(string.Format("Hai **{0}**, you have {1} {2}!\nYou can {4} one with the `{3}{4}` command, or you can give a {5} to your friend using `{3}give @friend`",
                                                    e.Message.Author.GetNickname(), userData.KarmaCount,
                                                    (userData.KarmaCount == 1 ? e.Server.Config.KarmaCurrencySingular : e.Server.Config.KarmaCurrency),
                                                    e.Server.Config.CommandPrefix, e.Server.Config.KarmaConsumeCommand,
                                                    e.Server.Config.KarmaCurrencySingular));

                dbContext.Dispose();
            };
            commands.Add(newCommand);

// !nom
            newCommand             = new Command("nom");
            newCommand.Type        = CommandType.Standard;
            newCommand.Description = "Eat one of your cookies!";
            newCommand.IsPremiumServerwideCommand = true;
            newCommand.RequiredPermissions        = PermissionType.Everyone;
            newCommand.OnExecute += async e => {
                if (!e.Server.Config.KarmaEnabled)
                {
                    await e.SendReplySafe(KarmaDisabledString);

                    return;
                }

                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                UserData      userData  = dbContext.GetOrAddUser(e.Server.Id, e.Message.Author.Id);

                if (userData.KarmaCount <= 0)
                {
                    await e.SendReplySafe(string.Format("Umm... I'm sorry **{0}** you don't have any {1} left =(",
                                                        e.Message.Author.GetNickname(), e.Server.Config.KarmaCurrency));

                    dbContext.Dispose();
                    return;
                }

                userData.KarmaCount -= 1;
                dbContext.SaveChanges();

                await e.SendReplySafe(string.Format("**{0}** just {1} one of {2} {3}! {4} {5} left.",
                                                    e.Message.Author.GetNickname(), e.Server.Config.KarmaConsumeVerb,
                                                    (this.Client.IsGlobalAdmin(e.Message.Author.Id) ? "her" : "their"), e.Server.Config.KarmaCurrency,
                                                    (this.Client.IsGlobalAdmin(e.Message.Author.Id) ? "She has" : "They have"), userData.KarmaCount));// Because i can :P

                dbContext.Dispose();
            };
            commands.Add(newCommand);

// !give
            newCommand             = new Command("give");
            newCommand.Type        = CommandType.Standard;
            newCommand.Description = "Give one of your cookies to a friend =] (use with their @mention as a parameter)";
            newCommand.IsPremiumServerwideCommand = true;
            newCommand.RequiredPermissions        = PermissionType.Everyone;
            newCommand.OnExecute += async e => {
                if (!e.Server.Config.KarmaEnabled)
                {
                    await e.SendReplySafe(KarmaDisabledString);

                    return;
                }

                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                UserData      userData  = dbContext.GetOrAddUser(e.Server.Id, e.Message.Author.Id);
                if (userData.KarmaCount == 0)
                {
                    await e.SendReplySafe(string.Format("Umm... I'm sorry **{0}**, you don't have any {1} left =(",
                                                        e.Message.Author.GetNickname(), e.Server.Config.KarmaCurrency));

                    dbContext.Dispose();
                    return;
                }

                if (e.Message.MentionedUsers == null || !e.Message.MentionedUsers.Any() || e.Message.MentionedUsers.Count() > e.Server.Config.KarmaLimitMentions)
                {
                    await e.SendReplySafe(string.Format("You have to @mention your friend who will receive the {0}. You can mention up to {1} people at the same time.",
                                                        e.Server.Config.KarmaCurrencySingular, e.Server.Config.KarmaLimitMentions));

                    dbContext.Dispose();
                    return;
                }

                int             count     = 0;
                StringBuilder   userNames = new StringBuilder();
                List <UserData> users     = this.Client.GetMentionedUsersData(dbContext, e);
                foreach (UserData mentionedUser in users)
                {
                    if (userData.KarmaCount == 0)
                    {
                        break;
                    }

                    userData.KarmaCount--;
                    mentionedUser.KarmaCount++;

                    userNames.Append((count++ == 0 ? "" : count == users.Count ? ", and " : ", ") + e.Server.Guild.GetUser(mentionedUser.UserId).GetNickname());
                }

                if (count > 0)
                {
                    dbContext.SaveChanges();
                }

                string response = string.Format("**{0}** received a {1} of friendship from **{2}** =]",
                                                userNames, e.Server.Config.KarmaCurrencySingular, e.Message.Author.GetNickname());
                if (count < users.Count)
                {
                    response += "\nBut I couldn't give out more, as you don't have any left =(";
                }

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


            return(commands);
        }
Ejemplo n.º 11
0
        public List <Command> Init(IBotwinderClient iClient)
        {
            this.Client = iClient as BotwinderClient;
            List <Command> commands = new List <Command>();

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

            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Get a random quote, or a quote with specific id, oooor search for a quote by a specific user!";
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                string        response  = "";

                IEnumerable <Quote> quotes = dbContext.Quotes.Where(q => q.ServerId == e.Server.Id);

                if (!quotes.Any())
                {
                    response = "There ain't no quotes here! Add some first :]";
                }
                else if (string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    int   count = quotes.Count();
                    Int64 id    = Utils.Random.Next(0, count - 1);
                    response = quotes.FirstOrDefault(q => q.Id == id)?.ToString();
                }
                else
                {
                    Int64  id       = 0;
                    string username = "";
                    string nickname = "";
                    if (Int64.TryParse(e.TrimmedMessage, out id))
                    {
                        response = quotes.FirstOrDefault(q => q.Id == id)?.ToString();
                    }
                    else
                    {
                        if (e.Message.MentionedUsers.Any())
                        {
                            username = e.Message.MentionedUsers.FirstOrDefault()?.Username.ToLower();
                            nickname = (e.Message.MentionedUsers.FirstOrDefault() as IGuildUser)?.Nickname?.ToLower();
                        }
                        else
                        {
                            username = e.MessageArgs[0].ToLower();
                        }
                        quotes = quotes.Where(q => q.Username.ToLower().Contains(username) ||
                                              (!string.IsNullOrEmpty(nickname) && q.Username.ToLower().Contains(nickname)));
                        int count = quotes.Count();
                        id       = Utils.Random.Next(0, count < 1 ? 0 : (count - 1));
                        response = quotes.Skip((int)id).FirstOrDefault()?.ToString();
                    }
                }

                if (string.IsNullOrEmpty(response))
                {
                    response = "I didn't find no such quote.";
                }

                await e.SendReplySafe(response);

                dbContext.Dispose();
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("quote"));

// !addQuote
            newCommand                     = new Command("addQuote");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Add a new quote! Use with a username or mention as the first parameter, and the text as second. (Or you can just use a message ID.)";
            newCommand.RequiredPermissions = PermissionType.SubModerator;
            newCommand.OnExecute          += async e => {
                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                string        response  = "I've no idea what are you trying to tell me.\nUse with a username or mention as the first parameter, and the text as second. (Or you can just use a message ID.)";
                Quote         quote     = null;

                if (string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    response = "Wut?";
                }
                else if (guid.TryParse(e.TrimmedMessage, out guid messageId))
                {
                    if (await e.Channel.GetMessageAsync(messageId) is SocketMessage message)
                    {
                        quote = new Quote()
                        {
                            CreatedTime = new DateTime(message.CreatedAt.Ticks),
                            Username    = message.Author.Username,
                            Value       = message.Content.Replace('`', '\'') +
                                          (message.Attachments.Any() ? (" " + message.Attachments.FirstOrDefault()?.Url + " ") : "")
                        };
                    }
                    else
                    {
                        response = "Message not found _(it may be too old)_";
                    }
                }
                else if (e.MessageArgs.Length > 1)
                {
                    string username = e.Message.MentionedUsers.FirstOrDefault()?.Username ?? e.MessageArgs[0];
                    quote = new Quote()
                    {
                        CreatedTime = DateTime.UtcNow,
                        Username    = username,
                        Value       = e.TrimmedMessage.Substring(e.MessageArgs[0].Length).Replace('`', '\'')
                    };
                }

                if (quote != null)
                {
                    response       = "Unexpected database error :<";
                    quote.ServerId = e.Server.Id;
                    quote.Id       = dbContext.Quotes.Count(q => q.ServerId == e.Server.Id);

                    dbContext.Quotes.Add(quote);
                    dbContext.SaveChanges();

                    response = $"**Quote created with ID** `{quote.Id}`:\n{quote.ToString()}";
                }

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


            return(commands);
        }
Ejemplo n.º 12
0
        public List <Command> Init(IBotwinderClient iClient)
        {
            this.Client = iClient as BotwinderClient;
            List <Command> commands = new List <Command>();

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

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

                    return;
                }

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

                    return;
                }

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

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

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

                        dbContext.Channels.Add(channel);
                    }

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

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

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

                    return;
                }

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

                    return;
                }

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

                    return;
                }

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

                    return;
                }

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

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

                await Task.Delay(100);

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

                await Task.Delay(100);

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

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

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

                await msg.PinAsync();

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

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

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

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

                    return;
                }

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

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

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

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

                            return;
                        }

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

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

                        return;
                    }

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

                        return;
                    }

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

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

                        break;

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

                        break;

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

                        break;

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

                        break;

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

                        break;

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

                        break;

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

                            return;
                        }

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

                        break;

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

                            return;
                        }

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

                        break;

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

                        return;
                    }
                }

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

                    return;
                }

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

            return(commands);
        }
Ejemplo n.º 13
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>)";
                    }
Ejemplo n.º 14
0
        public List <Command> Init(IBotwinderClient iClient)
        {
            this.Client = iClient as BotwinderClient;
            List <Command> commands = new List <Command>();

            this.Client.Events.UserJoined      += OnUserJoined;
            this.Client.Events.ReactionAdded   += OnReactionAdded;
            this.Client.Events.ReactionRemoved += OnReactionRemoved;

// !publicRoles
            Command 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 || (ex.DiscordCode.HasValue && ex.DiscordCode.Value == 50013) || exception.Message.Contains("Missing Access") || exception.Message.Contains("Missing Permissions")))
                    {
                        response = "Something went wrong, I may not have server permissions to do that.\n(Hint: <http://i.imgur.com/T8MPvME.png>)";
                    }