public RoleUserController(IRoleUser repoRoleUser , IRole repoRole, IPermission repoPer) { dalRoleUser = repoRoleUser; dalRole = repoRole; dalPermission = repoPer; }
/// <summary> /// Adds the role. /// </summary> /// <param name="role">The role.</param> public void AddRole(IRole role) { using (Logger.Assembly.Scope()) { RoleIds.Add(role.Id); } }
private void RemoveExclusions(IRole role, Dictionary<string, IRole> roles, HashSet<IRole> parsedMemberships, HashSet<IRole> parsedExclusions) { foreach (var exclusion in role.RoleExclusions.Values) { if (parsedExclusions.Contains(exclusion)) { continue; } if (roles.ContainsKey(exclusion.Name)) { roles.Remove(exclusion.Name); parsedExclusions.Add(exclusion); } RemoveExclusions(exclusion, roles, parsedMemberships, parsedExclusions); } foreach (var membership in role.RoleMemberships.Values) { if (parsedMemberships.Contains(membership)) { continue; } parsedMemberships.Add(membership); RemoveExclusions(membership, roles, parsedMemberships, parsedExclusions); } }
/// <summary> /// Assign a set of abilities to a role. /// </summary> /// <param name="role">The role that is to be inspected and if nescessary configured</param> /// <param name="abilities">The abilities to assign the role if nescessary</param> public static void RegisterAbilities(IRole role, IEnumerable<IAbility> abilities) { // This method is intended to be used from the Global.asax.cs or // similar. It should only be done from there to encourage a centralized // place to assign abilities. // // You could additionally add the roles and abilities into this file // but it was designed to be general enough to support most use cases // // The method is designed with dependency injection in mind which should allow // any method of configuring roles and abilities (i.e. pulling roles from the database, // or abilities through refection) if (role == null) throw new ArgumentNullException("role"); if (abilities == null) throw new ArgumentNullException("abilities"); if (role.Abilities == null) role.Abilities = new List<IAbility>(); foreach (IAbility ability in abilities) role.Abilities.Add(ability); AuthorizationService.AddRole(role); }
public AccountController(IUser userRepository, ISettings settingsRepository, IRole roleRepository) : base(settingsRepository) { _userRepository = userRepository; _roleRepository = roleRepository; ExpectedMasterName = string.Empty; }
public ModifyIncidentHandler() { APF = Australian_Parachute_Federation.Instance; _reporter = APF.Searcher.Find_User("13E98653-675F-44E6-A0A2-E2E40261F8FE"); _role = APF.Searcher.Find_Role("70CAAFBC-B595-4D98-85CF-FCDC913FDB9D"); _userInRole = (IUserInRole)APF.Searcher.Find_User_In_Role(_reporter.User_ID, _role.Role_ID); }
/// <summary> /// Constructor /// </summary> /// <param name="roleAccessor">Role Property Accessor this instance will be returned by</param> /// <param name="memberships">Other roles to participate in</param> /// <param name="exclusions">Roles of which this role is excluded</param> public RoleExpression(Expression<Func<IRole>> roleAccessor, IRole[] memberships, IRole[] exclusions) { Name = BindingHelper.Name(roleAccessor); RoleMemberships = memberships.ToDictionary(r => r.Name); RoleExclusions = exclusions.ToDictionary(r => r.Name); }
public Task<int> UpdateAsync(IRole role) { if (String.IsNullOrEmpty(role.Id)) { throw new ArgumentNullException("Id"); } return roleRepository.UpdateAsync(role); }
public IRole AddRole(IRole role) { foreach (IAbility ability in role.Abilities) AddAbility(ability); _roleRepository.Create(role); return GetRole(role.Name); }
/// <summary> /// 根据流程和角色创建SOARoleContext /// </summary> /// <param name="role"></param> /// <param name="process"></param> /// <returns></returns> public static SOARoleContext CreateContext(IRole role, IWfProcess process) { role.NullCheck("role"); SOARole soaRole = (SOARole)SOARole.CreateWrapperObject(role); return CreateContext(soaRole.PropertyDefinitions, process); }
public TaskContext(IRole role) { Role = role; Settings = new ExpandoObject(); StepIndex = 0; TaskSteps = new List<TaskStep>(); }
public void remove_role(IRole role) { roles.RemoveAll(r => r.GetType() == role.GetType()); Contract.Ensures( roles.Count > 0, "Personnel must have at least one role" ); }
public new static IRole CreateWrapperObject(IRole role) { IRole result = role; if (role is SOARole == false) result = new SOARole(role); return result; }
public Character(string name, char gender, int age, IRole role, string race) { this.name = name; this.gender = gender; this.age = age; this.role = role; this.race = race; // give random hair type , eye colour , hair colour }
public void Initial() { if(PlayerGO != null) Player = PlayerGO.GetComponent<IRole>(); if(EnemyGO != null) Enemy = EnemyGO.GetComponent<IRole> (); if(PlayerCameraGO != null) PlayerCam = PlayerCameraGO.GetComponent<ICamera> (); if(EnemyCameraGO != null) EnemyCam = EnemyCameraGO.GetComponent<ICamera> (); if(BulletCameraGO != null) BulletCam = BulletCameraGO.GetComponent<ICamera> (); if(MainCameraGO != null) MainCam = MainCameraGO.GetComponent<ICamera> (); }
public Boolean HasRole(IRole role) { foreach (IRole personnel_role in this.roles) { if (role.GetType() == personnel_role.GetType()){ return true; } } return false; }
public TaskContext(IRole role) { if (role == null) throw new Exception("角色不能为null"); Role = role; Settings = new ExpandoObject(); StepIndex = 0; TaskSteps = new List<TaskStep>(); }
public IRole RenameRole(IRole role, String newRoleName) { if (role == null) throw new ArgumentNullException("role"); if (String.IsNullOrEmpty(newRoleName)) throw new ArgumentNullException("newRoleName"); role.Name = newRoleName; this.RoleRepository.Update(role); return role; }
private static void bindCheckBoxList( SecurityTool tool, IBlock sblock, IRole role ) { IBlock cbBlock = sblock.GetBlock( "checkboxs" ); IList checkValues = tool.GetCheckBoxList( role ); foreach (ActionVo av in checkValues) { cbBlock.Set( "a.Name", av.Name ); cbBlock.Set( "a.Value", av.Value ); cbBlock.Set( "a.Checked", av.Checked ); cbBlock.Next(); } }
public static void Add(IContext context, IRole role) { Context ctx = context as Context; if (ctx == null) throw new Exception(typeof(Context).FullName + " expected."); SqlCommand command = new SqlCommand("insert into Role (title) values (@Title)"); command.Parameters.Add(new SqlParameter("Title", role.Title)); command.ExecuteNonQuery(); }
public Task<int> DeleteAsync(IRole entity) { try { return Repository.DeleteAsync(entity); } catch (Exception e) { throw new Exception(e.ToString()); } }
public Task<int> InsertAsync(IRole entity) { try { return Repository.InsertAsync(entity); } catch (Exception e) { throw e; } }
public virtual Task<int> DeleteAsync(IRole entity) { try { return Repository.DeleteAsync<Role>(Mapper.Map<Role>(entity)); } catch (Exception e) { throw new Exception(e.ToString()); } }
public virtual Task<int> UpdateAsync(IRole entity) { try { return Repository.UpdateAsync<Role>(Mapper.Map<Role>(entity)); } catch (Exception e) { throw e; } }
public bool Authorize(IRole role, IAbility ability) { if (role.Abilities.Contains(ability)) return true; foreach (IAbility root in role.Abilities) if (_Authorize(root, ability)) return true; return false; }
public Permission SetPermission(IRole role, IAction action, bool isAllowed) { Permission permission = PermissionRepository.GetPermissionByRole(role, action); if (permission == null) permission = new Permission(role, action, isAllowed); else permission.IsAllowed = isAllowed; PermissionRepository.SavePermission(permission); return permission; }
internal static VRole C2V(IRole contract) { if (!System.Runtime.Remoting.RemotingServices.IsObjectOutOfAppDomain(contract) && (contract.GetType().Equals(typeof(RoleV2C)))) { return ((RoleV2C)(contract)).GetSourceView(); } else { return new RoleC2V(contract); } }
public void GrantRole(IRole role, IAccount account) { if (role == null) throw new ArgumentNullException("role"); if (account == null) throw new ArgumentNullException("account"); if (account.Roles.Any(x => x.Id == role.Id)) throw new FineWorkException(String.Format( "The role [{0} ({1})] has been granted to account [{2} {3}] already.", role.Id, role.Name, account.Id, account.Name)); role.Accounts.Add(account); this.RoleRepository.Update(role); }
public RoleRightsController(IRole role, IUserRole userRole, IModule module, IAction action, IActionModule actionModule, IRoleRight roleRight, ICacheManager cache) { _role = role; _module = module; _actionModule = actionModule; _roleRight = roleRight; _action = action; _cache = cache; _userRole = userRole; }
public void add_role(IRole role) { Contract.Requires<ArgumentOutOfRangeException>( role != null, "role cannot be null" ); // ensure that "roles" doesn't have duplicates Contract.Ensures(Contract.ForAll(roles, r1 => !Contract.Exists(roles, r2 => r1 != r2 && r1.GetType() == r2.GetType()))); roles.Add(role); }
/// <summary> /// Add the specified used to the specified streaming role. /// </summary> /// <param name="guildUser">User to add to role.</param> /// <param name="streamingRole">Role to add the user to.</param> private async Task AddUserToStreamingRole(IGuildUser guildUser, IRole streamingRole) { await guildUser.AddRoleAsync(streamingRole); logger.LogDebug($"StreamingRole Module: Adding {guildUser.Username}"); }
Task <bool> IPermissionConfig.SetGuildModRole(IGuild guild, IRole role) { Guilds.Single(g => g.GuildId == guild.Id).ModRole = role.Id; return(Task.FromResult(true)); }
/// <summary> /// Remove the specified used to the specified streaming role. /// </summary> /// <param name="guildUser">User to add to role.</param> /// <param name="streamingRole">Role to add the user to.</param> private async Task RemoveUserFromStreamingRole(IGuildUser guildUser, IRole streamingRole) { await guildUser.RemoveRoleAsync(streamingRole); logger.LogDebug($"StreamingRole Module: Removing {guildUser.Username}"); }
public void Init(IRole uvo) { this.UVO = uvo; }
public static ImmutableArray <ITag> ParseTags(string text, IMessageChannel channel, IGuild guild, IReadOnlyCollection <IUser> userMentions) { var tags = ImmutableArray.CreateBuilder <ITag>(); int index = 0; while (true) { index = text.IndexOf('<', index); if (index == -1) { break; } int endIndex = text.IndexOf('>', index + 1); if (endIndex == -1) { break; } string content = text.Substring(index, endIndex - index + 1); if (MentionUtils.TryParseUser(content, out ulong id)) { IUser mentionedUser = null; foreach (var mention in userMentions) { if (mention.Id == id) { mentionedUser = channel?.GetUserAsync(id, CacheMode.CacheOnly).GetAwaiter().GetResult(); if (mentionedUser == null) { mentionedUser = mention; } break; } } tags.Add(new Tag <IUser>(TagType.UserMention, index, content.Length, id, mentionedUser)); } else if (MentionUtils.TryParseChannel(content, out id)) { IChannel mentionedChannel = null; if (guild != null) { mentionedChannel = guild.GetChannelAsync(id, CacheMode.CacheOnly).GetAwaiter().GetResult(); } tags.Add(new Tag <IChannel>(TagType.ChannelMention, index, content.Length, id, mentionedChannel)); } else if (MentionUtils.TryParseRole(content, out id)) { IRole mentionedRole = null; if (guild != null) { mentionedRole = guild.GetRole(id); } tags.Add(new Tag <IRole>(TagType.RoleMention, index, content.Length, id, mentionedRole)); } else if (Emote.TryParse(content, out var emoji)) { tags.Add(new Tag <Emote>(TagType.Emoji, index, content.Length, emoji.Id, emoji)); } else //Bad Tag { index = index + 1; continue; } index = endIndex + 1; } index = 0; while (true) { index = text.IndexOf("@everyone", index); if (index == -1) { break; } var tagIndex = FindIndex(tags, index); if (tagIndex.HasValue) { tags.Insert(tagIndex.Value, new Tag <object>(TagType.EveryoneMention, index, "@everyone".Length, 0, null)); } index++; } index = 0; while (true) { index = text.IndexOf("@here", index); if (index == -1) { break; } var tagIndex = FindIndex(tags, index); if (tagIndex.HasValue) { tags.Insert(tagIndex.Value, new Tag <object>(TagType.HereMention, index, "@here".Length, 0, null)); } index++; } return(tags.ToImmutable()); }
public async Task RoleInfoAsync(IRole role) { var srole = ((SocketRole)role).Permissions; var l = new List <string>(); if (srole.AddReactions) { l.Add("Can Add Reactions"); } if (srole.Administrator) { l.Add("Is Administrator"); } if (srole.AttachFiles) { l.Add("Can Attach Files"); } if (srole.BanMembers) { l.Add("Can Ban Members"); } if (srole.ChangeNickname) { l.Add("Can Change Nickname"); } if (srole.Connect) { l.Add("Can Connect"); } if (srole.CreateInstantInvite) { l.Add("Can Create Invite"); } if (srole.DeafenMembers) { l.Add("Can Deafen Members"); } if (srole.EmbedLinks) { l.Add("Can Embed Links"); } if (srole.KickMembers) { l.Add("Can Kick Members"); } if (srole.ManageChannels) { l.Add("Can Manage Channels"); } if (srole.ManageEmojis) { l.Add("Can Manage Emojis"); } if (srole.ManageGuild) { l.Add("Can Manage Guild"); } if (srole.ManageMessages) { l.Add("Can Manage Messages"); } if (srole.ManageNicknames) { l.Add("Can Manage Nicknames"); } if (srole.ManageRoles) { l.Add("Can Manage Roles"); } if (srole.ManageWebhooks) { l.Add("Can Manage Webhooks"); } if (srole.MentionEveryone) { l.Add("Can Mention Everyone"); } if (srole.MoveMembers) { l.Add("Can Move Members"); } if (srole.MuteMembers) { l.Add("Can Mute Members"); } if (srole.ReadMessageHistory) { l.Add("Can Read Message History"); } if (srole.ReadMessages) { l.Add("Can Read Messages"); } if (srole.SendMessages) { l.Add("Can Send Messages"); } if (srole.SendTTSMessages) { l.Add("Can Send TTS Messages"); } if (srole.Speak) { l.Add("Can Speak"); } if (srole.UseExternalEmojis) { l.Add("Can Use Externam Emojis"); } if (srole.UseVAD) { l.Add("Can Use VAD"); } var list = string.Join("\n", l.ToArray()); if (list == "") { list = "None :("; } var embed = new EmbedBuilder() .WithTitle($"RoleInfo for {role.Name}") .AddField("Colour", $"{role.Color}") .AddField("ID", $"{role.Id}") .AddField("Creation Date", $"{role.CreatedAt}") .AddField("Displayed Separately?", $"{role.IsHoisted}") .AddField("Mentionable?", $"{role.IsMentionable}") .AddField("Discord Generated?", $"{role.IsManaged}") .AddField("Permissions", list) .WithFooter(x => { x.WithText("PassiveBOT"); x.WithIconUrl(Context.Client.CurrentUser.GetAvatarUrl()); }); await ReplyAsync("", false, embed.Build()); }
public bool IsSubjectInRole(ISubject account, IRole role) { return(CoreContext.UserManager.IsUserInGroup(account.ID, role.ID)); }
public bool IsSubjectInRole(ISubject account, IRole role) { List <IRole> roles = GetRoles(account); return(roles.Contains(role)); }
public async Task AddEmoteRoles(IRole role, string emoteString = "", string name = "") { if (!_reactRoleService.IsPreparingMessage) { await ReplyAsync("No message is being prepared, use NewMessage first!"); return; } // If empty we check the message for the role passed in, if it exists we remove that role from the message. if (emoteString == string.Empty) { var reactionRemove = _reactRoleService.NewMessage.Reactions?.Find(reactRole => reactRole.RoleId == role.Id); if (reactionRemove == null) { await ReplyAsync($"Role {role.Name} was not attached to this message."); return; } _reactRoleService.NewMessage.Reactions.Remove(reactionRemove); await ReplyAsync($"Removed Role {role.Name} from message."); return; } // Try pull the Emote ID from the emote used. Emote tempEmote; if (!Emote.TryParse(emoteString, out tempEmote)) { await ReplyAsync($"Emote ({emoteString}) does not exist in this server."); return; } // We make sure we have access to it on this server var emote = await Context.Guild.GetEmoteAsync(tempEmote.Id); if (emote == null) { await ReplyAsync($"Failed to use ({emoteString}), unknown error."); return; } if (name == string.Empty) { name = emote.Name; } // Add our Reaction Role _reactRoleService.NewMessage.Reactions ??= new List <ReactRole>(); var newRole = new ReactRole(name, role.Id, emote.Id); _reactRoleService.NewMessage.Reactions.Add(newRole); await Context.Message.AddReactionAsync(emote); await Context.Message.AddReactionAsync(_thumbUpEmote); }
public static IEnumerable <IUser> Members(this IRole role) => role.Guild.GetUsersAsync().GetAwaiter().GetResult().Where(u => u.RoleIds.Contains(role.Id)) ?? Enumerable.Empty <IUser>();
public static async Task <IEnumerable <IGuildUser> > GetMembersAsync(this IRole role) => (await role.Guild.GetUsersAsync(CacheMode.CacheOnly)).Where(u => u.RoleIds.Contains(role.Id)) ?? Enumerable.Empty <IGuildUser>();
private Embed BuildEmbed(IReadOnlyCollection <TagSummary> tags, IUser ownerUser = null, IGuild ownerGuild = null, IRole ownerRole = null) { var orderedTags = tags .OrderByDescending(x => x.Uses) .ThenBy(x => x.Name); var ownerName = ownerUser?.Username ?? ownerGuild?.Name ?? ownerRole?.Name; var ownerImage = ownerUser?.GetDefiniteAvatarUrl() ?? ownerGuild?.IconUrl; var builder = new EmbedBuilder(); builder .WithAuthor(ownerName, ownerImage) .WithColor(Color.DarkPurple) .WithDescription(tags.Count > 0 ? null : "No tags.") .WithFooter(EmbedFooterText) .WithTitle("Tags"); const int tagsToDisplay = 6; foreach (var tag in orderedTags.Take(tagsToDisplay)) { builder.AddField(tag.Name, $"{tag.Uses} uses", true); } if (tags.Count > tagsToDisplay) { var fieldName = $"and {tags.Count - tagsToDisplay} more"; // https://modix.gg/tags var url = new UriBuilder(Config.WebsiteBaseUrl) { Path = "/tags" }.RemoveDefaultPort().ToString(); builder.AddField(x => x.WithName(fieldName) .WithValue($"View at {url}")); } return(builder.Build()); }
public AndroidController(IOverTimeRequest _ioverTimeReques, IWorkflowDetail _iworkflowDetail, IWorkflowTracker _iworkflowTracker, IDepartment _idepartment, IDocuments _idocuments, IRole _irole, IUser _iuser, IHold _ihold, IMenu _imenu, IInsight _iinsight) { ioverTimeRequest = _ioverTimeReques; iworkflowDetail = _iworkflowDetail; iworkflowTracker = _iworkflowTracker; idepartment = _idepartment; idocuments = _idocuments; irole = _irole; iuser = _iuser; ihold = _ihold; imenu = _imenu; iinsight = _iinsight; }
public KaraokeSetting(IVoiceChannel karaokeVc, ITextChannel karaokeChannel, IRole singingRole) { KaraokeVc = karaokeVc.Id; KaraokeChannel = karaokeChannel.Id; SingingRole = singingRole.Id; }
public static List <IRole> Balance(IRole roleflags, int playerCount, bool chaos, bool burningOverkill, out List <IRole> possibleRoles, bool validationMode = false) { List <IRole> rolesToAssign; List <IRole> disabledRoles = roleflags.HasFlag(IRole.VALID) || validationMode ? roleflags.GetUniqueRoles().ToList() : new List <IRole>(); var balanced = false; var attempts = 0; var nonVgRoles = new[] { IRole.Cultist, IRole.SerialKiller, IRole.Tanner, IRole.Wolf, IRole.AlphaWolf, IRole.Sorcerer, IRole.WolfCub, IRole.Lycan, IRole.Thief, IRole.SnowWolf, IRole.Arsonist }; do { attempts++; if (attempts >= 500) { throw new IndexOutOfRangeException("Unable to create a balanced game. Please try again.\nPlayer count: " + playerCount); } //determine which roles should be assigned rolesToAssign = GetRoleList(playerCount, disabledRoles); while (rolesToAssign.Count < playerCount) { rolesToAssign.Add(IRole.Villager); } possibleRoles = new List <IRole>(rolesToAssign); Shuffle(rolesToAssign); rolesToAssign = rolesToAssign.Take(playerCount).ToList(); //let's fix some roles that should or shouldn't be there... //sorcerer or traitor or snowwolf, without wolves, are pointless. change one of them to wolf if ((rolesToAssign.Contains(IRole.Sorcerer) || rolesToAssign.Contains(IRole.Traitor) || rolesToAssign.Contains(IRole.SnowWolf)) && !rolesToAssign.Any(x => WolfRoles.Contains(x))) { var towolf = rolesToAssign.FindIndex(x => x == IRole.Sorcerer || x == IRole.Traitor || x == IRole.SnowWolf); //if there are multiple, the random order of rolesToAssign will choose for us which one to substitute var possibleWolves = WolfRoles.Where(x => !disabledRoles.Contains(x)).ToList(); rolesToAssign[towolf] = possibleWolves[R.Next(possibleWolves.Count)]; //choose randomly from WolfRoles } //cult without CH -> add CH (unless the group REALLY doesn't want it...) if (rolesToAssign.Contains(IRole.Cultist) && !rolesToAssign.Contains(IRole.CultistHunter) && !disabledRoles.Contains(IRole.CultistHunter)) { //just pick a vg, and turn them to CH var vg = rolesToAssign.FindIndex(x => !nonVgRoles.Contains(x)); rolesToAssign[vg] = IRole.CultistHunter; } //appseer without seer -> seer if (rolesToAssign.Contains(IRole.ApprenticeSeer) && !rolesToAssign.Contains(IRole.Seer)) { //substitute with seer var apps = rolesToAssign.IndexOf(IRole.ApprenticeSeer); rolesToAssign[apps] = IRole.Seer; } //make sure that we have at least two teams if ( rolesToAssign.Any(x => !nonVgRoles.Contains(x)) && //make sure we have VGs rolesToAssign.Any(x => nonVgRoles.Contains(x) && x != IRole.Sorcerer && x != IRole.Tanner && x != IRole.Thief) //make sure we have at least one enemy ) { balanced = true; } //else, redo role assignment. better to rely on randomness, than trying to fix it //also make sure that baddie count is lower than village count if (rolesToAssign.Count(x => nonVgRoles.Contains(x)) >= rolesToAssign.Count(x => !nonVgRoles.Contains(x))) { balanced = false; } if (rolesToAssign.Contains(IRole.SerialKiller) && rolesToAssign.Contains(IRole.Arsonist)) { balanced = balanced && burningOverkill; } //the roles to assign are good, now if it's not a chaos game we need to check if they're balanced if (!chaos) { var villageStrength = rolesToAssign.Where(x => !nonVgRoles.Contains(x)).Sum(x => x.GetStrength(rolesToAssign)); var enemyStrength = rolesToAssign.Where(x => nonVgRoles.Contains(x)).Sum(x => x.GetStrength(rolesToAssign)); //check balance var varianceAllowed = (playerCount / 4) + 1; balanced = balanced && (Math.Abs(villageStrength - enemyStrength) <= varianceAllowed); } } while (!balanced); return(rolesToAssign); }
/// <inheritdoc /> Task IGuildUser.RemoveRoleAsync(IRole role, RequestOptions options) => throw new NotSupportedException("Roles are not supported on webhook users.");
public static int GetStrength(this IRole role, List <IRole> allRoles) { IRole[] WolfRoles = { IRole.Wolf, IRole.WolfCub, IRole.AlphaWolf, IRole.Lycan }; IRole[] nonConvertibleRoles = { IRole.Seer, IRole.GuardianAngel, IRole.Detective, IRole.Cursed, IRole.Harlot, IRole.Hunter, IRole.Doppelgänger, IRole.Wolf, IRole.AlphaWolf, IRole.WolfCub, IRole.SerialKiller, IRole.Lycan, IRole.Thief, IRole.SnowWolf }; switch (role) { case IRole.Villager: return(1); case IRole.Drunk: return(3); case IRole.Harlot: return(6); case IRole.Seer: return(7 - allRoles.Count(x => x == IRole.Lycan) - (allRoles.Count(x => x == IRole.WolfMan) * 2)); case IRole.Traitor: return(0); case IRole.GuardianAngel: return(7 + (allRoles.Contains(IRole.Arsonist) ? 1 : 0)); case IRole.Detective: return(6); case IRole.Wolf: return(10); case IRole.Cursed: return(1 - allRoles.Count(x => WolfRoles.Contains(x) || x == IRole.SnowWolf) / 2); //vg, or worse case IRole.Gunner: return(6); case IRole.Tanner: return(allRoles.Count / 2); case IRole.Fool: return(3); case IRole.WildChild: return(1); case IRole.Beholder: return(1 + (allRoles.Any(x => x == IRole.Seer) ? 4 : 0) + (allRoles.Any(x => x == IRole.Fool) ? 1 : 0)); //only good if seer is present! case IRole.ApprenticeSeer: return(6); case IRole.Cultist: return(10 + allRoles.Count(x => !nonConvertibleRoles.Contains(x))); case IRole.CultistHunter: return(allRoles.Count(x => x == IRole.Cultist) == 0 ? 1 : 7); case IRole.Mason: return(allRoles.Count(x => x == IRole.Mason) <= 1 ? 1 : allRoles.Count(x => x == IRole.Mason) + 3); //strength in numbers case IRole.Doppelgänger: return(2); case IRole.Cupid: return(2); case IRole.Hunter: return(6); case IRole.SerialKiller: return(15); case IRole.Sorcerer: return(2); case IRole.AlphaWolf: return(12); case IRole.WolfCub: return(new[] { IRole.AlphaWolf, IRole.Wolf, IRole.Lycan, IRole.SnowWolf, IRole.WildChild, IRole.Doppelgänger, IRole.Cursed, IRole.Traitor } .Any(x => allRoles.Contains(x)) ? 12 : 10); // only count as 12 if there can be another wolf case IRole.Blacksmith: return(5); case IRole.ClumsyGuy: return(-1); case IRole.Mayor: return(4); case IRole.Prince: return(3); case IRole.WolfMan: return(1); case IRole.Augur: return(5); case IRole.Pacifist: return(3); case IRole.WiseElder: return(3); case IRole.Oracle: return(4); case IRole.Sandman: return(3); case IRole.Lycan: return(10); case IRole.Thief: return(4); case IRole.Troublemaker: return(5); case IRole.Chemist: return(0); case IRole.SnowWolf: return(15); case IRole.GraveDigger: return(8); case IRole.Arsonist: return(8); case IRole.Spumpkin: return(2); default: throw new ArgumentOutOfRangeException(nameof(role), role, null); } }
public static string Role(IRole role) { Guard.IsNotNull(role); return(Role(role.Id)); }
public RolesController(IRole roleData) { _roleData = roleData; }
public async Task StreamOnline(List <TwitchUser> userList, StreamStatus streamStatus) { foreach (TwitchUser t in userList) { //Really iterating over servers here. Task <Server> getServerTask = _context.ServerList.AsQueryable().FirstAsync(s => s.ServerId == t.ServerId); RestGuild guild = (RestGuild)await _client.GetGuildAsync(ulong.Parse(t.ServerId)); Task <RestGuildUser> getUserTask = null; if (!string.IsNullOrEmpty(t.DiscordUserId)) { //We don't need this yet so we'll do this later. getUserTask = guild.GetUserAsync(ulong.Parse(t.DiscordUserId)); } Server server = await getServerTask; string twitchChannelId = server.TwitchChannel; RestGuildUser user = null; if (getUserTask != null) { user = await getUserTask; } if (user != null && !string.IsNullOrEmpty(server?.TwitchLiveRoleId)) { //We need to update the role IRole twitchLiveRole = guild.GetRole(ulong.Parse(server.TwitchLiveRoleId)); await user.AddRoleAsync(twitchLiveRole); } if (!string.IsNullOrEmpty(twitchChannelId)) { //We post updates to the channel, so now we need to see if we've already posted. string streamUrl = "https://twitch.tv/" + t.ChannelName; DateTimeOffset streamStartedUTC = streamStatus.started_at; RestTextChannel channel = await guild.GetTextChannelAsync(ulong.Parse(twitchChannelId)); //Find whether or not we've selected a message ulong lastMessageId = 0; bool sendMessage = true; while (true) { IAsyncEnumerable <IReadOnlyCollection <RestMessage> > messagesUnflattened = lastMessageId == 0 ? channel.GetMessagesAsync(100) : channel.GetMessagesAsync(lastMessageId, Direction.Before, 100); List <RestMessage> messages = (await messagesUnflattened.FlattenAsync()).ToList(); var myMessages = messages.Where(m => m.Author.Id == _client.CurrentUser.Id && m.Timestamp > streamStartedUTC && m.Content.Contains(streamUrl)).ToList(); if (myMessages.Any()) { //Already sent message. We don't need to send it again sendMessage = false; break; } else { if (messages.Last().Timestamp < streamStartedUTC) { //We're past when the stream started break; } } lastMessageId = messages.Last().Id; } if (sendMessage) { //We still need to send the message string stringToSend = ""; if (user != null && String.IsNullOrEmpty(user?.Nickname)) { stringToSend += !String.IsNullOrEmpty(user.Nickname) ? user.Nickname : user.Username; } else { stringToSend += t.ChannelName; } stringToSend += " is now live at " + streamUrl; await channel.SendMessageAsync(stringToSend); } } } }
public async Task SetMuteRoleAsync(IRole role) { _moderation.CreateOrSetMutedRole(Context.Guild, role); await ReplyAsync($"Successfully set the muterole to {role.Mention}."); }
public static string ToIDString(this IRole role) => role != null ? $"{role.Name} ({role.Id})" : "N/A";
/// <inheritdoc /> public Task RemoveRoleAsync(IRole role, RequestOptions options = null) => RemoveRoleAsync(role.Id, options);
public PickWPName(IRole UVO_) { InitializeComponent(); this.UVO = UVO_; }
/// <inheritdoc /> public Task AddRoleAsync(IRole role, RequestOptions options = null) => AddRoleAsync(role.Id, options);
public static int GetStrength(this IRole role, List <IRole> allRoles) { IRole[] WolfRoles = { IRole.WolfCub, IRole.WolfCub, IRole.AlphaWolf }; IRole[] nonConvertibleRoles = { IRole.Seer, IRole.GuardianAngel, IRole.Detective, IRole.Cursed, IRole.Harlot, IRole.Hunter, IRole.Doppelgänger, IRole.Wolf, IRole.AlphaWolf, IRole.WolfCub, IRole.SerialKiller }; switch (role) { case IRole.Villager: return(1); case IRole.Drunk: return(3); case IRole.Harlot: return(6); case IRole.Seer: return(7); case IRole.Traitor: return(0); case IRole.GuardianAngel: return(7); case IRole.Detective: return(6); case IRole.Wolf: return(10); case IRole.Cursed: return(1 - allRoles.Count(x => WolfRoles.Contains(x)) / 2); //vg, or worse case IRole.Gunner: return(6); case IRole.Tanner: return(allRoles.Count / 2); case IRole.Fool: return(3); case IRole.WildChild: return(1); case IRole.Beholder: return(2 + (allRoles.Any(x => x == IRole.Seer) ? 4 : 0)); //only good if seer is present! case IRole.ApprenticeSeer: return(6); case IRole.Cultist: return(10 + allRoles.Count(x => !nonConvertibleRoles.Contains(x))); case IRole.CultistHunter: return(allRoles.Count(x => x == IRole.Cultist) == 0 ? 1 : 7); case IRole.Mason: return(allRoles.Count(x => x == IRole.Mason) <= 1 ? 1 : allRoles.Count(x => x == IRole.Mason) + 3); //strength in numbers case IRole.Doppelgänger: return(2); case IRole.Cupid: return(2); case IRole.Hunter: return(6); case IRole.SerialKiller: return(15); case IRole.Sorcerer: return(2); case IRole.AlphaWolf: return(12); case IRole.WolfCub: return(12); case IRole.Blacksmith: return(5); case IRole.ClumsyGuy: return(-1); case IRole.Mayor: return(4); case IRole.Prince: return(3); default: throw new ArgumentOutOfRangeException(nameof(role), role, null); } }
public SOARolePropertyRowCollection(IRole role) { this._Role = role; }
public static IPlayer GetPlayerForRole(this IEnumerable <IPlayer> players, IRole role, bool aliveOnly = true, IPlayer exceptPlayer = null) { return(players?.FirstOrDefault(x => x.PlayerRole == role && (!aliveOnly || !x.IsDead) && x.Id != exceptPlayer?.Id)); }
private async Task ConfigureChannelMuteRolePermissionsAsync(IGuildChannel channel, IRole muteRole) { var permissionOverwrite = channel.GetPermissionOverwrite(muteRole); if (permissionOverwrite != null) { if ((permissionOverwrite.Value.AllowValue == _mutePermissions.AllowValue) && (permissionOverwrite.Value.DenyValue == _mutePermissions.DenyValue)) { Log.Debug("Skipping setting mute permissions for channel #{Channel} as they're already set.", channel.Name); return; } Log.Debug("Removing permission overwrite for channel #{Channel}.", channel.Name); await channel.RemovePermissionOverwriteAsync(muteRole); } await channel.AddPermissionOverwriteAsync(muteRole, _mutePermissions); Log.Debug("Set mute permissions for role {Role} in channel #{Channel}.", muteRole.Name, channel.Name); }
public static ImmutableArray <ITag> ParseTags(string text, IMessageChannel channel, IGuild guild, IReadOnlyCollection <IUser> userMentions) { var tags = ImmutableArray.CreateBuilder <ITag>(); int index = 0; var codeIndex = 0; // checks if the tag being parsed is wrapped in code blocks bool CheckWrappedCode() { // util to check if the index of a tag is within the bounds of the codeblock bool EnclosedInBlock(Match m) => m.Groups[1].Index < index && index < m.Groups[2].Index; // loop through all code blocks that are before the start of the tag while (codeIndex < index) { var blockMatch = BlockCodeRegex.Match(text, codeIndex); if (blockMatch.Success) { if (EnclosedInBlock(blockMatch)) { return(true); } // continue if the end of the current code was before the start of the tag codeIndex += blockMatch.Groups[2].Index + blockMatch.Groups[2].Length; if (codeIndex < index) { continue; } return(false); } var inlineMatch = InlineCodeRegex.Match(text, codeIndex); if (inlineMatch.Success) { if (EnclosedInBlock(inlineMatch)) { return(true); } // continue if the end of the current code was before the start of the tag codeIndex += inlineMatch.Groups[2].Index + inlineMatch.Groups[2].Length; if (codeIndex < index) { continue; } return(false); } return(false); } return(false); } while (true) { index = text.IndexOf('<', index); if (index == -1) { break; } int endIndex = text.IndexOf('>', index + 1); if (endIndex == -1) { break; } if (CheckWrappedCode()) { break; } string content = text.Substring(index, endIndex - index + 1); if (MentionUtils.TryParseUser(content, out ulong id)) { IUser mentionedUser = null; foreach (var mention in userMentions) { if (mention.Id == id) { mentionedUser = channel?.GetUserAsync(id, CacheMode.CacheOnly).GetAwaiter().GetResult(); if (mentionedUser == null) { mentionedUser = mention; } break; } } tags.Add(new Tag <IUser>(TagType.UserMention, index, content.Length, id, mentionedUser)); } else if (MentionUtils.TryParseChannel(content, out id)) { IChannel mentionedChannel = null; if (guild != null) { mentionedChannel = guild.GetChannelAsync(id, CacheMode.CacheOnly).GetAwaiter().GetResult(); } tags.Add(new Tag <IChannel>(TagType.ChannelMention, index, content.Length, id, mentionedChannel)); } else if (MentionUtils.TryParseRole(content, out id)) { IRole mentionedRole = null; if (guild != null) { mentionedRole = guild.GetRole(id); } tags.Add(new Tag <IRole>(TagType.RoleMention, index, content.Length, id, mentionedRole)); } else if (Emote.TryParse(content, out var emoji)) { tags.Add(new Tag <Emote>(TagType.Emoji, index, content.Length, emoji.Id, emoji)); } else //Bad Tag { index = index + 1; continue; } index = endIndex + 1; } index = 0; codeIndex = 0; while (true) { index = text.IndexOf("@everyone", index); if (index == -1) { break; } if (CheckWrappedCode()) { break; } var tagIndex = FindIndex(tags, index); if (tagIndex.HasValue) { tags.Insert(tagIndex.Value, new Tag <IRole>(TagType.EveryoneMention, index, "@everyone".Length, 0, guild?.EveryoneRole)); } index++; } index = 0; codeIndex = 0; while (true) { index = text.IndexOf("@here", index); if (index == -1) { break; } if (CheckWrappedCode()) { break; } var tagIndex = FindIndex(tags, index); if (tagIndex.HasValue) { tags.Insert(tagIndex.Value, new Tag <IRole>(TagType.HereMention, index, "@here".Length, 0, guild?.EveryoneRole)); } index++; } return(tags.ToImmutable()); }