discord4j.core.object.entity.Role Java Examples
The following examples show how to use
discord4j.core.object.entity.Role.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RoleUtils.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 6 votes |
public static Snowflake getRole(String toLookFor, Guild guild) { toLookFor = GeneralUtils.trim(toLookFor); final String lower = toLookFor.toLowerCase(); if (lower.matches("@&[0-9]+") || lower.matches("[0-9]+")) { Role exists = guild.getRoleById(Snowflake.of(Long.parseLong(toLookFor.replaceAll("[<@&>]", "")))).onErrorResume(e -> Mono.empty()).block(); if (exists != null) return exists.getId(); } List<Role> roles = new ArrayList<>(); roles.addAll(guild.getRoles().filter(r -> r.getName().equalsIgnoreCase(lower)).collectList().block()); roles.addAll(guild.getRoles().filter(r -> r.getName().toLowerCase().contains(lower)).collectList().block()); if (!roles.isEmpty()) return roles.get(0).getId(); return null; }
Example #2
Source File: RoleUtils.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 6 votes |
public static Snowflake getRole(String toLookFor, Guild guild) { toLookFor = GeneralUtils.trim(toLookFor); final String lower = toLookFor.toLowerCase(); if (lower.matches("@&[0-9]+") || lower.matches("[0-9]+")) { Role exists = guild.getRoleById(Snowflake.of(Long.parseLong(toLookFor.replaceAll("[<@&>]", "")))).onErrorResume(e -> Mono.empty()).block(); if (exists != null) return exists.getId(); } List<Role> roles = new ArrayList<>(); roles.addAll(guild.getRoles().filter(r -> r.getName().equalsIgnoreCase(lower)).collectList().block()); roles.addAll(guild.getRoles().filter(r -> r.getName().toLowerCase().contains(lower)).collectList().block()); if (!roles.isEmpty()) return roles.get(0).getId(); return null; }
Example #3
Source File: Settings.java From Shadbot with GNU General Public License v3.0 | 5 votes |
public boolean hasAllowedRole(List<Role> roles) { final Set<Snowflake> allowedRoleIds = this.getAllowedRoleIds(); // If no permission has been set if (allowedRoleIds.isEmpty()) { return true; } //If the user is an administrator OR the role is allowed return roles.stream() .anyMatch(role -> role.getPermissions().contains(Permission.ADMINISTRATOR) || allowedRoleIds.contains(role.getId())); }
Example #4
Source File: RoleUtils.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 5 votes |
public static String getRoleNameFromID(String id, MessageCreateEvent event) { Role role = getRoleFromID(id, event); if (role != null) return role.getName(); else return "ERROR"; }
Example #5
Source File: RoleUtils.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 5 votes |
public static boolean roleExists(String id, MessageCreateEvent event) { for (Role r : event.getMessage().getGuild().block().getRoles().toIterable()) { if (id.equals(r.getId().asString())) return true; } return false; }
Example #6
Source File: RoleUtils.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 5 votes |
public static Role getRoleFromID(String id, MessageCreateEvent event) { for (Role r : event.getMessage().getGuild().block().getRoles().toIterable()) { if (id.equals(r.getId().asString()) || id.equals(r.getName())) return r; } return null; }
Example #7
Source File: DisCalCommand.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 5 votes |
/** * Sets the control role for the guild. * * @param args The args of the command. * @param event The event received. */ private void moduleControlRole(String[] args, MessageCreateEvent event, GuildSettings settings) { if (PermissionChecker.hasSufficientRole(event)) { if (args.length > 1) { String roleName = GeneralUtils.getContent(args, 1); Role controlRole; if (!"everyone".equalsIgnoreCase(roleName)) { controlRole = RoleUtils.getRoleFromID(roleName, event); if (controlRole != null) { settings.setControlRole(controlRole.getId().asString()); DatabaseManager.getManager().updateSettings(settings); //Send message. MessageManager.sendMessageAsync(MessageManager.getMessage("DisCal.ControlRole.Set", "%role%", controlRole.getName(), settings), event); } else { //Invalid role. MessageManager.sendMessageAsync(MessageManager.getMessage("DisCal.ControlRole.Invalid", settings), event); } } else { //Role is @everyone, set this so that anyone can control the bot. settings.setControlRole("everyone"); DatabaseManager.getManager().updateSettings(settings); //Send message MessageManager.sendMessageAsync(MessageManager.getMessage("DisCal.ControlRole.Reset", settings), event); } } else { MessageManager.sendMessageAsync(MessageManager.getMessage("DisCal.ControlRole.Specify", settings), event); } } else { MessageManager.sendMessageAsync(MessageManager.getMessage("Notification.Perm.CONTROL_ROLE", settings), event); } }
Example #8
Source File: RoleUtils.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 5 votes |
public static String getRoleNameFromID(String id, MessageCreateEvent event) { Role role = getRoleFromID(id, event); if (role != null) return role.getName(); else return "ERROR"; }
Example #9
Source File: RoleUtils.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 5 votes |
public static boolean roleExists(String id, MessageCreateEvent event) { for (Role r : event.getMessage().getGuild().block().getRoles().toIterable()) { if (id.equals(r.getId().asString())) return true; } return false; }
Example #10
Source File: RoleUtils.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 5 votes |
public static Role getRoleFromID(String id, MessageCreateEvent event) { for (Role r : event.getMessage().getGuild().block().getRoles().toIterable()) { if (id.equals(r.getId().asString()) || id.equals(r.getName())) return r; } return null; }
Example #11
Source File: DisCalCommand.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 5 votes |
/** * Sets the control role for the guild. * * @param args The args of the command. * @param event The event received. */ private void moduleControlRole(String[] args, MessageCreateEvent event, GuildSettings settings) { if (PermissionChecker.hasSufficientRole(event)) { if (args.length > 1) { String roleName = GeneralUtils.getContent(args, 1); Role controlRole; if (!"everyone".equalsIgnoreCase(roleName)) { controlRole = RoleUtils.getRoleFromID(roleName, event); if (controlRole != null) { settings.setControlRole(controlRole.getId().asString()); DatabaseManager.getManager().updateSettings(settings); //Send message. MessageManager.sendMessageAsync(MessageManager.getMessage("DisCal.ControlRole.Set", "%role%", controlRole.getName(), settings), event); } else { //Invalid role. MessageManager.sendMessageAsync(MessageManager.getMessage("DisCal.ControlRole.Invalid", settings), event); } } else { //Role is @everyone, set this so that anyone can control the bot. settings.setControlRole("everyone"); DatabaseManager.getManager().updateSettings(settings); //Send message MessageManager.sendMessageAsync(MessageManager.getMessage("DisCal.ControlRole.Reset", settings), event); } } else { MessageManager.sendMessageAsync(MessageManager.getMessage("DisCal.ControlRole.Specify", settings), event); } } else { MessageManager.sendMessageAsync(MessageManager.getMessage("Notification.Perm.CONTROL_ROLE", settings), event); } }
Example #12
Source File: AutoRolesSetting.java From Shadbot with GNU General Public License v3.0 | 5 votes |
private Mono<List<Role>> checkPermissions(Context context, List<Role> roles, Action action) { if (action == Action.ADD) { return context.getChannel() .flatMap(channel -> DiscordUtils.requirePermissions(channel, Permission.MANAGE_ROLES) .thenReturn(roles.stream().map(Role::getId).collect(Collectors.toSet())) .flatMap(roleIds -> context.getSelfAsMember() .filterWhen(self -> self.hasHigherRoles(roleIds)) .switchIfEmpty(DiscordUtils.sendMessage(Emoji.WARNING + " I can't automatically add this role because I'm lower or " + "at the same level in the role hierarchy.", channel) .then(Mono.empty())) .map(ignored -> roles))); } return Mono.just(roles); }
Example #13
Source File: AutoRolesSetting.java From Shadbot with GNU General Public License v3.0 | 5 votes |
@Override public Mono<ImmutableEmbedFieldData> show(Context context, Settings settings) { return Flux.fromIterable(settings.getAutoRoleIds()) .flatMap(roleId -> context.getClient().getRoleById(context.getGuildId(), roleId)) .map(Role::getMention) .collectList() .filter(roles -> !roles.isEmpty()) .map(roles -> String.join(", ", roles)) .map(value -> ImmutableEmbedFieldData.builder() .name("Auto-roles") .value(value) .build()); }
Example #14
Source File: AllowedRolesSetting.java From Shadbot with GNU General Public License v3.0 | 5 votes |
@Override public Mono<ImmutableEmbedFieldData> show(Context context, Settings settings) { return Flux.fromIterable(settings.getAllowedRoleIds()) .flatMap(roleId -> context.getClient().getRoleById(context.getGuildId(), roleId)) .map(Role::getMention) .collectList() .filter(roles -> !roles.isEmpty()) .map(roles -> String.join(", ", roles)) .map(value -> ImmutableEmbedFieldData.builder() .name("Allowed roles") .value(value) .build()); }
Example #15
Source File: RestrictedRolesSetting.java From Shadbot with GNU General Public License v3.0 | 5 votes |
@Override public Mono<ImmutableEmbedFieldData> show(Context context, Settings settings) { return Flux.fromIterable(settings.getRestrictedRoles().entrySet()) .flatMap(entry -> Mono.zip( context.getClient().getRoleById(context.getGuildId(), entry.getKey()).map(Role::getMention), Mono.just(FormatUtils.format(entry.getValue(), BaseCmd::getName, ", ")))) .map(TupleUtils.function((roleMention, cmds) -> String.format("%s: %s", roleMention, cmds))) .reduce("", (value, text) -> value + "\n" + text) .filter(value -> !value.isBlank()) .map(value -> ImmutableEmbedFieldData.builder() .name("Restricted roles") .value(value) .build()); }
Example #16
Source File: UserInfoCmd.java From Shadbot with GNU General Public License v3.0 | 5 votes |
private Consumer<EmbedCreateSpec> getEmbed(Member member, List<Role> roles, String avatarUrl) { final LocalDateTime createTime = TimeUtils.toLocalDateTime(member.getId().getTimestamp()); final String creationDate = String.format("%s%n(%s)", createTime.format(this.dateFormatter), FormatUtils.formatLongDuration(createTime)); final LocalDateTime joinTime = TimeUtils.toLocalDateTime(member.getJoinTime()); final String joinDate = String.format("%s%n(%s)", joinTime.format(this.dateFormatter), FormatUtils.formatLongDuration(joinTime)); final StringBuilder usernameBuilder = new StringBuilder(member.getUsername()); if (member.isBot()) { usernameBuilder.append(" (Bot)"); } if (member.getPremiumTime().isPresent()) { usernameBuilder.append(" (Booster)"); } return ShadbotUtils.getDefaultEmbed() .andThen(embed -> { embed.setAuthor(String.format("User Info: %s", usernameBuilder), null, avatarUrl) .setThumbnail(member.getAvatarUrl()) .addField("Display name", member.getDisplayName(), false) .addField("User ID", member.getId().asString(), false) .addField("Creation date", creationDate, false) .addField("Join date", joinDate, false); if (!roles.isEmpty()) { embed.addField("Roles", FormatUtils.format(roles, Role::getMention, "\n"), true); } }); }
Example #17
Source File: DiscordUtils.java From Shadbot with GNU General Public License v3.0 | 5 votes |
/** * @param guild The {@link Guild} containing the roles to extract. * @param str The string containing role mentions and / or names. * @return A {@link Role} {@link Flux} containing the extracted roles. */ public static Flux<Role> extractRoles(Guild guild, String str) { final List<String> words = StringUtils.split(str); return guild.getRoles() .filter(role -> words.contains(role.getName()) || words.contains(String.format("@%s", role.getName())) || words.contains(role.getMention())); }
Example #18
Source File: FallbackEntityRetriever.java From Discord4J with GNU Lesser General Public License v3.0 | 4 votes |
@Override public Flux<Role> getGuildRoles(Snowflake guildId) { return first.getGuildRoles(guildId).switchIfEmpty(fallback.getGuildRoles(guildId)); }
Example #19
Source File: IamCmd.java From Shadbot with GNU General Public License v3.0 | 4 votes |
@Override public Mono<Void> execute(Context context) { final String arg = context.requireArg(); final List<String> quotedElements = StringUtils.getQuotedElements(arg); if (quotedElements.isEmpty() && arg.contains("\"")) { return Mono.error(new CommandException("One quotation mark is missing.")); } if (quotedElements.size() > 1) { return Mono.error(new CommandException("You should specify only one text in quotation marks.")); } final Flux<Role> getRoles = context.getGuild() .flatMapMany(guild -> DiscordUtils.extractRoles(guild, StringUtils.remove(arg, quotedElements))); return context.getChannel() .flatMap(channel -> DiscordUtils.requirePermissions(channel, Permission.MANAGE_ROLES, Permission.ADD_REACTIONS) .then(getRoles.collectList()) .flatMap(roles -> { if (roles.isEmpty()) { return Mono.error(new MissingArgumentException()); } final StringBuilder description = new StringBuilder(); if (quotedElements.isEmpty()) { description.append(String.format("Click on %s to get role(s): %s", REACTION.getRaw(), FormatUtils.format(roles, role -> String.format("`@%s`", role.getName()), "\n"))); } else { description.append(quotedElements.get(0)); } final Consumer<EmbedCreateSpec> embedConsumer = ShadbotUtils.getDefaultEmbed() .andThen(embed -> embed.setAuthor(String.format("Iam: %s", FormatUtils.format(roles, role -> String.format("@%s", role.getName()), ", ")), null, context.getAvatarUrl()) .setDescription(description.toString())); return new ReactionMessage(context.getClient(), context.getChannelId(), List.of(REACTION)) .send(embedConsumer) .zipWith(DatabaseManager.getGuilds().getDBGuild(context.getGuildId())) .flatMap(TupleUtils.function((message, dbGuild) -> { // Converts the new message to an IamBean final List<IamBean> iamList = roles.stream() .map(Role::getId) .map(roleId -> new Iam(message.getId(), roleId)) .map(Iam::getBean) .collect(Collectors.toList()); // Add previous Iam to the new one iamList.addAll(dbGuild.getSettings() .getIam() .stream() .map(Iam::getBean) .collect(Collectors.toList())); return dbGuild.updateSetting(Setting.IAM_MESSAGES, iamList); })); })) .then(); }
Example #20
Source File: FallbackEntityRetriever.java From Discord4J with GNU Lesser General Public License v3.0 | 4 votes |
@Override public Mono<Role> getRoleById(Snowflake guildId, Snowflake roleId) { return first.getRoleById(guildId, roleId).switchIfEmpty(fallback.getRoleById(guildId, roleId)); }
Example #21
Source File: RoleDeleteEvent.java From Discord4J with GNU Lesser General Public License v3.0 | 4 votes |
public RoleDeleteEvent(GatewayDiscordClient gateway, ShardInfo shardInfo, long guildId, long roleId, @Nullable Role role) { super(gateway, shardInfo); this.guildId = guildId; this.roleId = roleId; this.role = role; }
Example #22
Source File: RoleUpdateEvent.java From Discord4J with GNU Lesser General Public License v3.0 | 4 votes |
public RoleUpdateEvent(GatewayDiscordClient gateway, ShardInfo shardInfo, Role current, @Nullable Role old) { super(gateway, shardInfo); this.current = current; this.old = old; }
Example #23
Source File: RoleCreateEvent.java From Discord4J with GNU Lesser General Public License v3.0 | 4 votes |
public RoleCreateEvent(GatewayDiscordClient gateway, ShardInfo shardInfo, long guildId, Role role) { super(gateway, shardInfo); this.guildId = guildId; this.role = role; }
Example #24
Source File: WebRole.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 4 votes |
public WebRole fromRole(Role r, GuildSettings settings) { id = r.getId().asLong(); name = r.getName(); managed = r.isManaged(); everyone = r.isEveryone(); if (r.isEveryone() && settings.getControlRole().equalsIgnoreCase("everyone")) controlRole = true; else controlRole = settings.getControlRole().equalsIgnoreCase(String.valueOf(id)); return this; }
Example #25
Source File: RolelistCmd.java From Shadbot with GNU General Public License v3.0 | 4 votes |
@Override public Mono<Void> execute(Context context) { final String arg = context.requireArg(); return context.getGuild() .flatMapMany(guild -> DiscordUtils.extractRoles(guild, arg)) .collectList() .flatMap(mentionedRoles -> { if (mentionedRoles.isEmpty()) { return Mono.error(new CommandException(String.format("Role `%s` not found.", arg))); } final List<Snowflake> mentionedRoleIds = mentionedRoles .stream() .map(Role::getId) .collect(Collectors.toList()); final Mono<List<String>> usernames = context.getGuild() .flatMapMany(Guild::getMembers) .filter(member -> !Collections.disjoint(member.getRoleIds(), mentionedRoleIds)) .map(Member::getUsername) .distinct() .collectList(); return Mono.zip(Mono.just(mentionedRoles), usernames); }) .map(TupleUtils.function((mentionedRoles, usernames) -> ShadbotUtils.getDefaultEmbed() .andThen(embed -> { embed.setAuthor( String.format("Rolelist: %s", FormatUtils.format(mentionedRoles, Role::getName, ", ")), null, context.getAvatarUrl()); if (usernames.isEmpty()) { embed.setDescription( String.format("There is nobody with %s.", mentionedRoles.size() == 1 ? "this role" : "these " + "roles")); return; } FormatUtils.createColumns(usernames, 25) .forEach(field -> embed.addField(field.name(), field.value(), true)); }))) .flatMap(embedConsumer -> context.getChannel() .flatMap(channel -> DiscordUtils.sendMessage(embedConsumer, channel))) .then(); }
Example #26
Source File: WebRole.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 4 votes |
public WebRole fromRole(Role r, GuildSettings settings) { id = r.getId().asLong(); name = r.getName(); managed = r.isManaged(); everyone = r.isEveryone(); if (r.isEveryone() && settings.getControlRole().equalsIgnoreCase("everyone")) controlRole = true; else controlRole = settings.getControlRole().equalsIgnoreCase(String.valueOf(id)); return this; }
Example #27
Source File: AllowedRolesSetting.java From Shadbot with GNU General Public License v3.0 | 4 votes |
@Override public Mono<Void> execute(Context context) { final List<String> args = context.requireArgs(3); final Action action = EnumUtils.parseEnum(Action.class, args.get(1), new CommandException(String.format("`%s` is not a valid action. %s", args.get(1), FormatUtils.options(Action.class)))); return context.getGuild() .flatMapMany(guild -> DiscordUtils.extractRoles(guild, args.get(2))) .collectList() .flatMap(mentionedRoles -> { if (mentionedRoles.isEmpty()) { return Mono.error(new CommandException(String.format("Role `%s` not found.", args.get(2)))); } return Mono.zip(Mono.just(mentionedRoles), DatabaseManager.getGuilds().getDBGuild(context.getGuildId())); }) .flatMap(TupleUtils.function((mentionedRoles, dbGuild) -> { final Set<Snowflake> allowedRoles = dbGuild.getSettings().getAllowedRoleIds(); final Set<Snowflake> mentionedRoleIds = mentionedRoles.stream() .map(Role::getId) .collect(Collectors.toUnmodifiableSet()); final StringBuilder strBuilder = new StringBuilder(); if (action == Action.ADD) { allowedRoles.addAll(mentionedRoleIds); strBuilder.append(String.format(Emoji.CHECK_MARK + " %s will now be able to interact with me.", FormatUtils.format(mentionedRoles, role -> String.format("`@%s`", role.getName()), ", "))); } else { allowedRoles.removeAll(mentionedRoleIds); strBuilder.append(String.format(Emoji.CHECK_MARK + " %s will not be able to interact with me anymore.", FormatUtils.format(mentionedRoles, role -> String.format("`@%s`", role.getName()), ", "))); if (allowedRoles.isEmpty()) { strBuilder.append("\n" + Emoji.INFO + " There are no more allowed roles set, everyone " + "can now interact with me."); } } return dbGuild.updateSetting(this.getSetting(), allowedRoles) .thenReturn(strBuilder); })) .map(StringBuilder::toString) .flatMap(text -> context.getChannel() .flatMap(channel -> DiscordUtils.sendMessage(text, channel))) .then(); }
Example #28
Source File: AutoRolesSetting.java From Shadbot with GNU General Public License v3.0 | 4 votes |
@Override public Mono<Void> execute(Context context) { final List<String> args = context.requireArgs(3); final Action action = EnumUtils.parseEnum(Action.class, args.get(1), new CommandException(String.format("`%s` is not a valid action. %s", args.get(1), FormatUtils.options(Action.class)))); return context.getGuild() .flatMapMany(guild -> DiscordUtils.extractRoles(guild, args.get(2))) .collectList() .map(mentionedRoles -> { if (mentionedRoles.isEmpty()) { throw new CommandException(String.format("Role `%s` not found.", args.get(2))); } return mentionedRoles; }) .flatMap(mentionedRoles -> this.checkPermissions(context, mentionedRoles, action)) .zipWith(DatabaseManager.getGuilds() .getDBGuild(context.getGuildId())) .flatMap(TupleUtils.function((mentionedRoles, dbGuild) -> { final List<Snowflake> mentionedRoleIds = mentionedRoles.stream() .map(Role::getId) .collect(Collectors.toList()); final Set<Snowflake> autoRoleIds = dbGuild.getSettings().getAutoRoleIds(); final StringBuilder strBuilder = new StringBuilder(); if (action == Action.ADD) { autoRoleIds.addAll(mentionedRoleIds); strBuilder.append(String.format(Emoji.CHECK_MARK + " %s added to auto-assigned roles.", FormatUtils.format(mentionedRoles, role -> String.format("`@%s`", role.getName()), ", "))); } else { autoRoleIds.removeAll(mentionedRoleIds); strBuilder.append(String.format(Emoji.CHECK_MARK + " %s removed from auto-assigned roles.", FormatUtils.format(mentionedRoles, role -> String.format("`@%s`", role.getName()), ", "))); } return dbGuild.updateSetting(this.getSetting(), autoRoleIds) .thenReturn(strBuilder.toString()); })) .flatMap(text -> context.getChannel() .flatMap(channel -> DiscordUtils.sendMessage(text, channel))) .then(); }
Example #29
Source File: RoleCreateEvent.java From Discord4J with GNU Lesser General Public License v3.0 | 2 votes |
/** * Gets the {@link Role} that was created in this event. * * @return The {@link Role} that was created. */ public Role getRole() { return role; }
Example #30
Source File: RoleUpdateEvent.java From Discord4J with GNU Lesser General Public License v3.0 | 2 votes |
/** * Gets the current, new version of the {@link Role} that was updated in the event. * * @return The current version of the updated {@link Role}. */ public Role getCurrent() { return current; }