discord4j.core.object.entity.Guild Java Examples

The following examples show how to use discord4j.core.object.entity.Guild. 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: LeaveGuildCmd.java    From Shadbot with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Mono<Void> execute(Context context) {
    final String arg = context.requireArg();

    final Long guildId = NumberUtils.toPositiveLongOrNull(arg);
    if (guildId == null) {
        return Mono.error(new CommandException(String.format("`%s` is not a valid guild ID.", arg)));
    }

    return context.getClient().getGuildById(Snowflake.of(guildId))
            .onErrorMap(ClientException.isStatusCode(HttpResponseStatus.FORBIDDEN.code()),
                    err -> new CommandException("Guild not found."))
            .flatMap(Guild::leave)
            .then(context.getChannel())
            .flatMap(channel -> DiscordUtils.sendMessage(
                    String.format(Emoji.CHECK_MARK + " Guild with ID **%d** left.", guildId), channel))
            .then();
}
 
Example #2
Source File: CalendarMessageFormatter.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static Consumer<EmbedCreateSpec> getCalendarLinkEmbed(Calendar cal, GuildSettings settings) {
	return spec -> {
		Guild guild = DisCalClient.getClient().getGuildById(settings.getGuildID()).block();

		if (settings.isBranded() && guild != null)
			spec.setAuthor(guild.getName(), GlobalConst.discalSite, guild.getIconUrl(Image.Format.PNG).orElse(GlobalConst.iconUrl));
		else
			spec.setAuthor("DisCal", GlobalConst.discalSite, GlobalConst.iconUrl);

		spec.setTitle(MessageManager.getMessage("Embed.Calendar.Link.Title", settings));

		if (cal.getSummary() != null)
			spec.addField(MessageManager.getMessage("Embed.Calendar.Link.Summary", settings), cal.getSummary(), true);

		if (cal.getDescription() != null)
			spec.addField(MessageManager.getMessage("Embed.Calendar.Link.Description", settings), cal.getDescription(), true);

		spec.addField(MessageManager.getMessage("Embed.Calendar.Link.TimeZone", settings), cal.getTimeZone(), false);
		spec.setUrl(CalendarMessageFormatter.getCalendarLink(settings.getGuildID()));
		spec.setFooter(MessageManager.getMessage("Embed.Calendar.Link.CalendarId", "%id%", cal.getId(), settings), null);
		spec.setColor(GlobalConst.discalColor);
	};
}
 
Example #3
Source File: RoleUtils.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #4
Source File: ComHandler.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 6 votes vote down vote up
@PostMapping(value = "/website/embed/calendar", produces = "application/json")
public static String getWebsiteEmbedCalendar(HttpServletRequest request, HttpServletResponse response, @RequestBody String requestBody) {
	//Get guild for calendar embed on the website.
	JSONObject jsonRequest = new JSONObject(requestBody);
	JSONObject jsonResponse = new JSONObject();

	Optional<Guild> guild = GuildFinder.findGuild(Snowflake.of(jsonRequest.getLong("guild_id")));

	if (guild.isPresent()) {
		jsonResponse.put("guild", new WebGuild().fromGuild(guild.get()).toJson());

		response.setStatus(200);
		response.setContentType("application/json");
		return jsonResponse.toString();
	} else {
		jsonResponse.put("message", "Guild not Found");
		response.setStatus(404);
		response.setContentType("application/json");
		return jsonResponse.toString();
	}
}
 
Example #5
Source File: UserUtils.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Grabs a user from a string
 *
 * @param toLookFor The String to look with
 * @param guild     The guild
 * @return The user if found, null otherwise
 */
public static Snowflake getUser(String toLookFor, Guild guild) {
	toLookFor = GeneralUtils.trim(toLookFor);
	final String lower = toLookFor.toLowerCase();
	if (lower.matches("@!?[0-9]+") || lower.matches("[0-9]+")) {
		Member exists = guild.getMemberById(Snowflake.of(Long.parseLong(toLookFor.replaceAll("[<@!>]", "")))).onErrorResume(e -> Mono.empty()).block();
		if (exists != null)
			return exists.getId();
	}


	List<Member> users = new ArrayList<>();

	users.addAll(guild.getMembers().filter(m -> m.getUsername().equalsIgnoreCase(lower)).collectList().block());
	users.addAll(guild.getMembers().filter(m -> m.getUsername().toLowerCase().contains(lower)).collectList().block());
	users.addAll(guild.getMembers().filter(m -> (m.getUsername() + "#" + m.getDiscriminator()).equalsIgnoreCase(lower)).collectList().block());
	users.addAll(guild.getMembers().filter(m -> m.getDiscriminator().equalsIgnoreCase(lower)).collectList().block());
	users.addAll(guild.getMembers().filter(m -> m.getDisplayName().equalsIgnoreCase(lower)).collectList().block());
	users.addAll(guild.getMembers().filter(m -> m.getDisplayName().toLowerCase().contains(lower)).collectList().block());


	if (!users.isEmpty())
		return users.get(0).getId();

	return null;
}
 
Example #6
Source File: CalendarMessageFormatter.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static Consumer<EmbedCreateSpec> getCalendarLinkEmbed(Calendar cal, GuildSettings settings) {
	return spec -> {
		Guild guild = DisCalClient.getClient().getGuildById(settings.getGuildID()).block();

		if (settings.isBranded() && guild != null)
			spec.setAuthor(guild.getName(), GlobalConst.discalSite, guild.getIconUrl(Image.Format.PNG).orElse(GlobalConst.iconUrl));
		else
			spec.setAuthor("DisCal", GlobalConst.discalSite, GlobalConst.iconUrl);

		spec.setTitle(MessageManager.getMessage("Embed.Calendar.Link.Title", settings));

		if (cal.getSummary() != null)
			spec.addField(MessageManager.getMessage("Embed.Calendar.Link.Summary", settings), cal.getSummary(), true);

		if (cal.getDescription() != null)
			spec.addField(MessageManager.getMessage("Embed.Calendar.Link.Description", settings), cal.getDescription(), true);

		spec.addField(MessageManager.getMessage("Embed.Calendar.Link.TimeZone", settings), cal.getTimeZone(), false);
		spec.setUrl(CalendarMessageFormatter.getCalendarLink(settings.getGuildID()));
		spec.setFooter(MessageManager.getMessage("Embed.Calendar.Link.CalendarId", "%id%", cal.getId(), settings), null);
		spec.setColor(GlobalConst.discalColor);
	};
}
 
Example #7
Source File: ServerInfoCmd.java    From Shadbot with GNU General Public License v3.0 6 votes vote down vote up
private Consumer<EmbedCreateSpec> getEmbed(Guild guild, List<GuildChannel> channels, Member owner, Region region, String avatarUrl) {
    final LocalDateTime creationTime = TimeUtils.toLocalDateTime(guild.getId().getTimestamp());
    final String creationDate = String.format("%s%n(%s)",
            creationTime.format(this.dateFormatter), FormatUtils.formatLongDuration(creationTime));
    final long voiceChannels = channels.stream().filter(VoiceChannel.class::isInstance).count();
    final long textChannels = channels.stream().filter(TextChannel.class::isInstance).count();

    return ShadbotUtils.getDefaultEmbed()
            .andThen(embed -> embed.setAuthor(String.format("Server Info: %s", guild.getName()), null, avatarUrl)
                    .setThumbnail(guild.getIconUrl(Format.JPEG).orElse(""))
                    .addField("Owner", owner.getUsername(), false)
                    .addField("Server ID", guild.getId().asString(), false)
                    .addField("Creation date", creationDate, false)
                    .addField("Region", region.getName(), false)
                    .addField("Channels", String.format("**Voice:** %d%n**Text:** %d", voiceChannels, textChannels), false)
                    .addField("Members", Integer.toString(guild.getMemberCount()), false));
}
 
Example #8
Source File: ComHandler.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 6 votes vote down vote up
@PostMapping(value = "/website/embed/calendar", produces = "application/json")
public static String getWebsiteEmbedCalendar(HttpServletRequest request, HttpServletResponse response, @RequestBody String requestBody) {
	//Get guild for calendar embed on the website.
	JSONObject jsonRequest = new JSONObject(requestBody);
	JSONObject jsonResponse = new JSONObject();

	Optional<Guild> guild = GuildFinder.findGuild(Snowflake.of(jsonRequest.getLong("guild_id")));

	if (guild.isPresent()) {
		jsonResponse.put("guild", new WebGuild().fromGuild(guild.get()).toJson());

		response.setStatus(200);
		response.setContentType("application/json");
		return jsonResponse.toString();
	} else {
		jsonResponse.put("message", "Guild not Found");
		response.setStatus(404);
		response.setContentType("application/json");
		return jsonResponse.toString();
	}
}
 
Example #9
Source File: DisCalCommand.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void moduleDisCalInfo(MessageCreateEvent event, GuildSettings settings) {
	Consumer<EmbedCreateSpec> embed = spec -> {
		Guild guild = event.getGuild().block();

		if (settings.isBranded() && guild != null)
			spec.setAuthor(guild.getName(), GlobalConst.discalSite, guild.getIconUrl(Image.Format.PNG).orElse(GlobalConst.iconUrl));
		else
			spec.setAuthor("DisCal", GlobalConst.discalSite, GlobalConst.iconUrl);

		spec.setTitle(MessageManager.getMessage("Embed.DisCal.Info.Title", settings));
		spec.addField(MessageManager.getMessage("Embed.DisCal.Info.Developer", settings), "DreamExposure", true);
		spec.addField(MessageManager.getMessage("Embed.Discal.Info.Version", settings), GlobalConst.version, true);
		spec.addField(MessageManager.getMessage("Embed.DisCal.Info.Library", settings), "Discord4J, version 3.0.6", false);
		spec.addField("Shard Index", BotSettings.SHARD_INDEX.get() + "/" + BotSettings.SHARD_COUNT.get(), true);
		spec.addField(MessageManager.getMessage("Embed.DisCal.Info.TotalGuilds", settings), DisCalClient.getClient().getGuilds().count().block() + "", true);
		spec.addField(MessageManager.getMessage("Embed.DisCal.Info.TotalCalendars", settings), DatabaseManager.getManager().getCalendarCount() + "", true);
		spec.addField(MessageManager.getMessage("Embed.DisCal.Info.TotalAnnouncements", settings), DatabaseManager.getManager().getAnnouncementCount() + "", true);
		spec.setFooter(MessageManager.getMessage("Embed.DisCal.Info.Patron", settings) + ": https://www.patreon.com/Novafox", null);
		spec.setUrl("https://www.discalbot.com");
		spec.setColor(GlobalConst.discalColor);
	};
	MessageManager.sendMessageAsync(embed, event);
}
 
Example #10
Source File: RoleUtils.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #11
Source File: MessageProcessor.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
private static Mono<Void> processCommand(MessageCreateEvent event, DBGuild dbGuild) {
    return Mono.justOrEmpty(event.getMember())
            // The role is allowed or the author is the guild's owner
            .filterWhen(member -> BooleanUtils.or(
                    member.getRoles().collectList().map(dbGuild.getSettings()::hasAllowedRole),
                    event.getGuild().map(Guild::getOwnerId).map(member.getId()::equals)))
            // The channel is allowed
            .flatMap(ignored -> event.getMessage().getChannel())
            .filter(channel -> dbGuild.getSettings().isTextChannelAllowed(channel.getId()))
            // The message starts with the correct prefix
            .flatMap(ignored -> MessageProcessor.getPrefix(dbGuild, event.getMessage().getContent()))
            // Execute the command
            .flatMap(prefix -> MessageProcessor.executeCommand(dbGuild, new Context(event, prefix)));
}
 
Example #12
Source File: AlmanaxAutoCommand.java    From KaellyBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void request(Message message, Matcher m, Language lg) {
    if (isUserHasEnoughRights(message)) {
        String guildId = message.getGuild().blockOptional()
                .map(Guild::getId).map(Snowflake::asString).orElse("");
        String channelId = message.getChannel().blockOptional()
                .map(MessageChannel::getId).map(Snowflake::asString).orElse("");
        
        if (m.group(1).matches("\\s+true") || m.group(1).matches("\\s+0") || m.group(1).matches("\\s+on"))
            if (!AlmanaxCalendar.getAlmanaxCalendars().containsKey(channelId)) {
                new AlmanaxCalendar(guildId, channelId).addToDatabase();
                message.getChannel().flatMap(chan -> chan
                        .createMessage(Translator.getLabel(lg, "almanax-auto.request.1")))
                        .subscribe();
            } else
                message.getChannel().flatMap(chan -> chan
                        .createMessage(Translator.getLabel(lg, "almanax-auto.request.2")))
                        .subscribe();
        else if (m.group(1).matches("\\s+false") || m.group(1).matches("\\s+1") || m.group(1).matches("\\s+off"))
            if (AlmanaxCalendar.getAlmanaxCalendars().containsKey(channelId)) {
                AlmanaxCalendar.getAlmanaxCalendars().get(channelId).removeToDatabase();
                message.getChannel().flatMap(chan -> chan
                        .createMessage(Translator.getLabel(lg, "almanax-auto.request.3")))
                        .subscribe();
            } else
                message.getChannel().flatMap(chan -> chan
                        .createMessage(Translator.getLabel(lg, "almanax-auto.request.4")))
                        .subscribe();
    } else
        BasicDiscordException.NO_ENOUGH_RIGHTS.throwException(message, this, lg);
}
 
Example #13
Source File: ChannelUtils.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static boolean channelExists(String nameOrId, Guild guild) {
	if (nameOrId.contains("#"))
		nameOrId = nameOrId.replace("#", "");

	for (TextChannel c : guild.getChannels().ofType(TextChannel.class).toIterable()) {
		if (c.getName().equalsIgnoreCase(nameOrId) || c.getId().asString().equals(nameOrId))
			return true;
	}
	return false;
}
 
Example #14
Source File: ChannelUtils.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Gets the IChannel from its name.
 *
 * @param nameOrId The channel name or ID.
 * @return the IChannel if successful, else <code>null</code>.
 */
public static String getChannelNameFromNameOrId(String nameOrId, Guild guild) {
	if (nameOrId.contains("#"))
		nameOrId = nameOrId.replace("#", "");

	for (TextChannel c : guild.getChannels().ofType(TextChannel.class).toIterable()) {
		if (c.getName().equalsIgnoreCase(nameOrId) || c.getId().asString().equals(nameOrId))
			return c.getName();
	}
	return "ERROR";
}
 
Example #15
Source File: UserUtils.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static Member getUserFromID(String id, Guild guild) {
	try {
		return guild.getMemberById(Snowflake.of(Long.parseUnsignedLong(id))).block();
	} catch (Exception e) {
		//Ignore. Probably invalid ID.
		return null;
	}
}
 
Example #16
Source File: ChannelUtils.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Gets the IChannel from its name.
 *
 * @param nameOrId The channel name or ID.
 * @return the IChannel if successful, else <code>null</code>.
 */
public static String getChannelNameFromNameOrId(String nameOrId, Guild guild) {
	if (nameOrId.contains("#"))
		nameOrId = nameOrId.replace("#", "");

	for (TextChannel c : guild.getChannels().ofType(TextChannel.class).toIterable()) {
		if (c.getName().equalsIgnoreCase(nameOrId) || c.getId().asString().equals(nameOrId))
			return c.getName();
	}
	return "ERROR";
}
 
Example #17
Source File: UserUtils.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static ArrayList<Member> getUsers(ArrayList<String> userIds, Guild guild) {
	ArrayList<Member> users = new ArrayList<>();
	for (String u : userIds) {
		Member user = getUserFromID(u, guild);
		if (user != null)
			users.add(user);
	}
	return users;
}
 
Example #18
Source File: CalendarMessageFormatter.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates an EmbedObject for the PreCalendar.
 *
 * @param calendar The PreCalendar to create an EmbedObject for.
 * @return The EmbedObject for the PreCalendar.
 */
public static Consumer<EmbedCreateSpec> getPreCalendarEmbed(PreCalendar calendar, GuildSettings settings) {
	return spec -> {
		Guild guild = DisCalClient.getClient().getGuildById(settings.getGuildID()).block();

		if (settings.isBranded() && guild != null)
			spec.setAuthor(guild.getName(), GlobalConst.discalSite, guild.getIconUrl(Image.Format.PNG).orElse(GlobalConst.iconUrl));
		else
			spec.setAuthor("DisCal", GlobalConst.discalSite, GlobalConst.iconUrl);

		spec.setTitle(MessageManager.getMessage("Embed.Calendar.Pre.Title", settings));
		if (calendar.getSummary() != null)
			spec.addField(MessageManager.getMessage("Embed.Calendar.Pre.Summary", settings), calendar.getSummary(), true);
		else
			spec.addField(MessageManager.getMessage("Embed.Calendar.Pre.Summary", settings), "***UNSET***", true);

		if (calendar.getDescription() != null)
			spec.addField(MessageManager.getMessage("Embed.Calendar.Pre.Description", settings), calendar.getDescription(), false);
		else
			spec.addField(MessageManager.getMessage("Embed.Calendar.Pre.Description", settings), "***UNSET***", false);

		if (calendar.getTimezone() != null)
			spec.addField(MessageManager.getMessage("Embed.Calendar.Pre.TimeZone", settings), calendar.getTimezone(), true);
		else
			spec.addField(MessageManager.getMessage("Embed.Calendar.Pre.TimeZone", settings), "***UNSET***", true);

		if (calendar.isEditing())
			spec.addField(MessageManager.getMessage("Embed.Calendar.Pre.CalendarId", settings), calendar.getCalendarId(), false);


		spec.setFooter(MessageManager.getMessage("Embed.Calendar.Pre.Key", settings), null);
		spec.setColor(GlobalConst.discalColor);

	};
}
 
Example #19
Source File: ServerInfoCmd.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Mono<Void> execute(Context context) {
    final Mono<Guild> getGuild = context.getGuild().cache();
    return Mono.zip(getGuild,
            getGuild.flatMapMany(Guild::getChannels).collectList(),
            getGuild.flatMap(Guild::getOwner),
            getGuild.flatMap(Guild::getRegion),
            Mono.just(context.getAvatarUrl()))
            .map(TupleUtils.function(this::getEmbed))
            .flatMap(embed -> context.getChannel()
                    .flatMap(channel -> DiscordUtils.sendMessage(embed, channel)))
            .then();
}
 
Example #20
Source File: TwitterCommand.java    From KaellyBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void request(Message message, Matcher m, Language lg) {
    //On check si la personne a bien les droits pour exécuter cette commande
    if (isUserHasEnoughRights(message)) {
        String value = m.group(1);

        Long guildId = message.getGuild().blockOptional()
                .map(Guild::getId).map(Snowflake::asLong).orElse(0L);
        Long channelId = message.getChannel().blockOptional()
                .map(MessageChannel::getId).map(Snowflake::asLong).orElse(0L);

        if (value.matches("\\s+true") || value.matches("\\s+0") || value.matches("\\s+on")){
            if (! TwitterFinder.getTwitterChannels().containsKey(channelId)) {
                new TwitterFinder(guildId, channelId).addToDatabase();
                message.getChannel().flatMap(chan -> chan
                        .createMessage(Translator.getLabel(lg, "twitter.request.1")
                        .replace("{twitter.name}", Translator.getLabel(lg, "twitter.name"))))
                        .subscribe();
            }
            else
                twitterFound.throwException(message, this, lg);
        }
        else if (value.matches("\\s+false") || value.matches("\\s+1") || value.matches("\\s+off")){
            if (TwitterFinder.getTwitterChannels().containsKey(channelId)) {
                TwitterFinder.getTwitterChannels().get(channelId).removeToDatabase();
                message.getChannel().flatMap(chan -> chan
                        .createMessage(Translator.getLabel(lg, "twitter.request.2")
                                .replace("{twitter.name}", Translator.getLabel(lg, "twitter.name"))))
                        .subscribe();
            }
            else
                twitterNotFound.throwException(message, this, lg);
        }
        else
            badUse.throwException(message, this, lg);
    }
    else
        BasicDiscordException.NO_ENOUGH_RIGHTS.throwException(message, this, lg);
}
 
Example #21
Source File: Main.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private synchronized GuildMusicManager getGuildAudioPlayer(Guild guild) {
  long guildId = guild.getId().asLong();
  GuildMusicManager musicManager = musicManagers.get(guildId);

  if (musicManager == null) {
    musicManager = new GuildMusicManager(playerManager);
    musicManagers.put(guildId, musicManager);
  }

  return musicManager;
}
 
Example #22
Source File: MemberJoinListener.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Mono<Void> execute(MemberJoinEvent event) {
    // Send an automatic join message if one was configured
    final Mono<Message> sendWelcomeMessage = DatabaseManager.getGuilds()
            .getDBGuild(event.getGuildId())
            .map(DBGuild::getSettings)
            .flatMap(settings -> Mono.zip(
                    Mono.justOrEmpty(settings.getMessageChannelId()),
                    Mono.justOrEmpty(settings.getJoinMessage())))
            .flatMap(TupleUtils.function((messageChannelId, joinMessage) ->
                    MemberJoinListener.sendAutoMessage(event.getClient(), event.getMember(), messageChannelId, joinMessage)));

    // Add auto-roles when a user joins if they are configured
    final Flux<Void> addAutoRoles = event.getGuild()
            .flatMap(Guild::getSelfMember)
            .flatMapMany(self -> self.getBasePermissions()
                    .filter(permissions -> permissions.contains(Permission.MANAGE_ROLES))
                    .flatMap(ignored -> DatabaseManager.getGuilds()
                            .getDBGuild(event.getGuildId())
                            .map(DBGuild::getSettings))
                    .flatMapMany(settings -> Flux.fromIterable(settings.getAutoRoleIds())
                            .flatMap(roleId -> event.getClient().getRoleById(event.getGuildId(), roleId))
                            .filterWhen(role -> self.hasHigherRoles(Set.of(role.getId())))
                            .flatMap(role -> event.getMember().addRole(role.getId()))));

    return sendWelcomeMessage.and(addAutoRoles);
}
 
Example #23
Source File: Main.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private static void attachToFirstVoiceChannel(Guild guild, D4jAudioProvider provider) {
  VoiceChannel voiceChannel = guild.getChannels().ofType(VoiceChannel.class).blockFirst();
  boolean inVoiceChannel = guild.getVoiceStates() // Check if any VoiceState for this guild relates to bot
      .any(voiceState -> guild.getClient().getSelfId().map(voiceState.getUserId()::equals).orElse(false))
      .block();

  if (!inVoiceChannel) {
    voiceChannel.join(spec -> spec.setProvider(provider)).block();
  }
}
 
Example #24
Source File: BotSupport.java    From Discord4J with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Mono<Void> onMessageCreate(MessageCreateEvent event) {
    Message message = event.getMessage();
    String content = message.getContent();
    if (content.startsWith("!getMembers ")) {
        String guildId = content.substring("!getMembers ".length());
        return event.getClient().getGuildById(Snowflake.of(guildId))
          .flatMapMany(Guild::getMembers)
                .doOnNext(member -> log.info("{}", member.getTag()))
                .then();
    }
    return Mono.empty();
}
 
Example #25
Source File: EventMessageFormatter.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Gets an EmbedObject for the specified CreatorResponse.
 *
 * @param ecr The CreatorResponse involved.
 * @return The EmbedObject for the CreatorResponse.
 */
public static Consumer<EmbedCreateSpec> getEventConfirmationEmbed(EventCreatorResponse ecr, GuildSettings settings) {
	return spec -> {
		EventData ed = DatabaseManager.getManager().getEventData(settings.getGuildID(), ecr.getEvent().getId());
		Guild guild = DisCalClient.getClient().getGuildById(settings.getGuildID()).block();

		if (settings.isBranded() && guild != null)
			spec.setAuthor(guild.getName(), GlobalConst.discalSite, guild.getIconUrl(Image.Format.PNG).orElse(GlobalConst.iconUrl));
		else
			spec.setAuthor("DisCal", GlobalConst.discalSite, GlobalConst.iconUrl);

		spec.setTitle(MessageManager.getMessage("Embed.Event.Confirm.Title", settings));
		if (ed.getImageLink() != null && ImageUtils.validate(ed.getImageLink(), settings.isPatronGuild())) {
			spec.setImage(ed.getImageLink());
		}
		spec.addField(MessageManager.getMessage("Embed.Event.Confirm.ID", settings), ecr.getEvent().getId(), false);
		spec.addField(MessageManager.getMessage("Embed.Event.Confirm.Date", settings), getHumanReadableDate(ecr.getEvent().getStart(), settings, false), false);
		if (ecr.getEvent().getLocation() != null && !ecr.getEvent().getLocation().equalsIgnoreCase("")) {
			if (ecr.getEvent().getLocation().length() > 300) {
				String location = ecr.getEvent().getLocation().substring(0, 300).trim() + "... (cont. on Google Cal)";
				spec.addField(MessageManager.getMessage("Embed.Event.Confirm.Location", settings), location, true);
			} else {
				spec.addField(MessageManager.getMessage("Embed.Event.Confirm.Location", settings), ecr.getEvent().getLocation(), true);
			}
		}
		spec.setFooter(MessageManager.getMessage("Embed.Event.Confirm.Footer", settings), null);
		spec.setUrl(ecr.getEvent().getHtmlLink());
		try {
			EventColor ec = EventColor.fromId(Integer.valueOf(ecr.getEvent().getColorId()));
			spec.setColor(ec.asColor());
		} catch (Exception e) {
			//Color is null, ignore and add our default.
			spec.setColor(GlobalConst.discalColor);
		}
	};
}
 
Example #26
Source File: CalendarMessageFormatter.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates an EmbedObject for the PreCalendar.
 *
 * @param calendar The PreCalendar to create an EmbedObject for.
 * @return The EmbedObject for the PreCalendar.
 */
public static Consumer<EmbedCreateSpec> getPreCalendarEmbed(PreCalendar calendar, GuildSettings settings) {
	return spec -> {
		Guild guild = DisCalClient.getClient().getGuildById(settings.getGuildID()).block();

		if (settings.isBranded() && guild != null)
			spec.setAuthor(guild.getName(), GlobalConst.discalSite, guild.getIconUrl(Image.Format.PNG).orElse(GlobalConst.iconUrl));
		else
			spec.setAuthor("DisCal", GlobalConst.discalSite, GlobalConst.iconUrl);

		spec.setTitle(MessageManager.getMessage("Embed.Calendar.Pre.Title", settings));
		if (calendar.getSummary() != null)
			spec.addField(MessageManager.getMessage("Embed.Calendar.Pre.Summary", settings), calendar.getSummary(), true);
		else
			spec.addField(MessageManager.getMessage("Embed.Calendar.Pre.Summary", settings), "***UNSET***", true);

		if (calendar.getDescription() != null)
			spec.addField(MessageManager.getMessage("Embed.Calendar.Pre.Description", settings), calendar.getDescription(), false);
		else
			spec.addField(MessageManager.getMessage("Embed.Calendar.Pre.Description", settings), "***UNSET***", false);

		if (calendar.getTimezone() != null)
			spec.addField(MessageManager.getMessage("Embed.Calendar.Pre.TimeZone", settings), calendar.getTimezone(), true);
		else
			spec.addField(MessageManager.getMessage("Embed.Calendar.Pre.TimeZone", settings), "***UNSET***", true);

		if (calendar.isEditing())
			spec.addField(MessageManager.getMessage("Embed.Calendar.Pre.CalendarId", settings), calendar.getCalendarId(), false);


		spec.setFooter(MessageManager.getMessage("Embed.Calendar.Pre.Key", settings), null);
		spec.setColor(GlobalConst.discalColor);

	};
}
 
Example #27
Source File: ComHandler.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
@PostMapping(value = "/website/dashboard/guild", produces = "application/json")
public static String getWebsiteDashboardGuild(HttpServletRequest request, HttpServletResponse response, @RequestBody String requestBody) {
	//Requires us to grab data for guild and return a response containing the WebGuild with needed info
	JSONObject jsonRequest = new JSONObject(requestBody);
	JSONObject jsonResponse = new JSONObject();

	Optional<Guild> guild = GuildFinder.findGuild(Snowflake.of(jsonRequest.getLong("guild_id")));

	if (guild.isPresent()) {
		Member member = guild.get().getMemberById(Snowflake.of(jsonRequest.getLong("member_id"))).block();
		if (member != null) {
			WebGuild wg = new WebGuild().fromGuild(guild.get());
			wg.setDiscalRole(PermissionChecker.hasSufficientRole(guild.get(), member));
			wg.setManageServer(PermissionChecker.hasManageServerRole(member));

			jsonResponse.put("guild", new WebGuild().fromGuild(guild.get()).toJson());

			response.setStatus(200);
			response.setContentType("application/json");
			return jsonResponse.toString();
		} else {
			jsonResponse.put("message", "Member not Found");
			response.setStatus(404);
			response.setContentType("application/json");
			return jsonResponse.toString();
		}
	} else {
		jsonResponse.put("message", "Guild not Found");
		response.setStatus(404);
		response.setContentType("application/json");
		return jsonResponse.toString();
	}
}
 
Example #28
Source File: DisCalCommand.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void moduleSettings(MessageCreateEvent event, GuildSettings settings) {
	Consumer<EmbedCreateSpec> embed = spec -> {
		Guild guild = event.getGuild().block();

		if (settings.isBranded() && guild != null)
			spec.setAuthor(guild.getName(), GlobalConst.discalSite, guild.getIconUrl(Image.Format.PNG).orElse(GlobalConst.iconUrl));
		else
			spec.setAuthor("DisCal", GlobalConst.discalSite, GlobalConst.iconUrl);

		spec.setTitle(MessageManager.getMessage("Embed.DisCal.Settings.Title", settings));
		spec.addField(MessageManager.getMessage("Embed.DisCal.Settings.ExternalCal", settings), String.valueOf(settings.useExternalCalendar()), true);
		if (RoleUtils.roleExists(settings.getControlRole(), event)) {
			spec.addField(MessageManager.getMessage("Embed.Discal.Settings.Role", settings), RoleUtils.getRoleNameFromID(settings.getControlRole(), event), true);
		} else {
			spec.addField(MessageManager.getMessage("Embed.Discal.Settings.Role", settings), "everyone", true);
		}
		if (ChannelUtils.channelExists(settings.getDiscalChannel(), event)) {
			spec.addField(MessageManager.getMessage("Embed.DisCal.Settings.Channel", settings), ChannelUtils.getChannelNameFromNameOrId(settings.getDiscalChannel(), guild), false);
		} else {
			spec.addField(MessageManager.getMessage("Embed.DisCal.Settings.Channel", settings), "All Channels", true);
		}
		spec.addField(MessageManager.getMessage("Embed.DisCal.Settings.SimpleAnn", settings), String.valueOf(settings.usingSimpleAnnouncements()), true);
		spec.addField(MessageManager.getMessage("Embed.DisCal.Settings.Patron", settings), String.valueOf(settings.isPatronGuild()), true);
		spec.addField(MessageManager.getMessage("Embed.DisCal.Settings.Dev", settings), String.valueOf(settings.isDevGuild()), true);
		spec.addField(MessageManager.getMessage("Embed.DisCal.Settings.MaxCal", settings), String.valueOf(settings.getMaxCalendars()), true);
		spec.addField(MessageManager.getMessage("Embed.DisCal.Settings.Language", settings), settings.getLang(), true);
		spec.addField(MessageManager.getMessage("Embed.DisCal.Settings.Prefix", settings), settings.getPrefix(), true);
		//TODO: Add translations...
		spec.addField("Using Branding", settings.isBranded() + "", true);
		spec.setFooter(MessageManager.getMessage("Embed.DisCal.Info.Patron", settings) + ": https://www.patreon.com/Novafox", null);
		spec.setUrl("https://www.discalbot.com/");
		spec.setColor(GlobalConst.discalColor);
	};
	MessageManager.sendMessageAsync(embed, event);
}
 
Example #29
Source File: DevCommand.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void moduleLeaveGuild(String[] args, MessageCreateEvent event) {
	if (args.length == 2) {
		try {
			Long.valueOf(args[1]);
		} catch (NumberFormatException ignore) {
			MessageManager.sendMessageAsync("Specified ID is not a valid LONG", event);
			return;
		}

		//Check if its on this shard...
		Guild g = DisCalClient.getClient().getGuildById(Snowflake.of(args[1])).block();
		if (g != null) {
			g.leave().subscribe();

			MessageManager.sendMessageAsync("Guild connected to this shard has been left!", event);
			return;
		}

		//Just send this across the network with Pub/Sub... and let the changes propagate
		JSONObject request = new JSONObject();

		request.put("Reason", PubSubReason.HANDLE.name());
		request.put("Realm", DisCalRealm.GUILD_LEAVE);
		request.put("Guild-Id", args[1]);

		PubSubManager.get().publish(BotSettings.PUBSUB_PREFIX.get() + "/ToClient/All", DisCalClient.clientId(), request);

		MessageManager.sendMessageAsync("DisCal will leave the specified guild (if connected). Please allow some time for this to propagate across the network!", event);
	} else {
		MessageManager.sendMessageAsync("Please specify the ID of the guild to leave with `!dev leave <ID>`", event);
	}
}
 
Example #30
Source File: GuildFinder.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static Optional<Guild> findGuild(Snowflake guildId) {
	if ((guildId.asLong() >> 22) % Integer.valueOf(BotSettings.SHARD_COUNT.get()) == DisCalClient.clientId()) {
		ServiceMediator med = DisCalClient.getClient().getServiceMediator();
		return med.getStateHolder().getGuildStore()
			.find(guildId.asLong())
			.blockOptional()
			.map(bean -> new Guild(med, bean));
	}

	return Optional.empty();
}