Java Code Examples for net.dv8tion.jda.api.EmbedBuilder#addField()

The following examples show how to use net.dv8tion.jda.api.EmbedBuilder#addField() . 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: MemberMuteAuditForwardProvider.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void build(AuditAction action, MessageBuilder messageBuilder, EmbedBuilder embedBuilder) {
    if (action.getTargetUser() == null) {
        return;
    }
    Boolean global = action.getAttribute(GLOBAL_ATTR, Boolean.class);
    embedBuilder.setDescription(messageService.getMessage(Boolean.TRUE.equals(global)
                    ? "audit.member.mute.message.global" : "audit.member.mute.message",
            getReferenceContent(action.getTargetUser(), false)));

    addModeratorField(action, embedBuilder);
    addChannelField(action, embedBuilder);
    addReasonField(action, embedBuilder);
    addExpirationField(action, embedBuilder);

    Integer duration = action.getAttribute(DURATION_ATTR, Integer.class);
    if (duration != null) {
        embedBuilder.addField(messageService.getMessage("audit.member.mute.duration.title"),
                String.valueOf(duration), true);
    }

    embedBuilder.setFooter(messageService.getMessage("audit.member.id", action.getTargetUser().getId()), null);
}
 
Example 2
Source File: MessageDeleteAuditForwardProvider.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void build(AuditAction action, MessageBuilder messageBuilder, EmbedBuilder embedBuilder) {
    String messageId = action.getAttribute(MESSAGE_ID, String.class);
    if (action.getChannel() == null || action.getUser() == null || messageId == null) {
        return;
    }

    embedBuilder.setDescription(messageService.getMessage("audit.message.delete.message",
            String.valueOf(action.getGuildId()),
            action.getChannel().getId(),
            messageId));

    embedBuilder.addField(messageService.getMessage("audit.message.deletedContent.title"),
            getMessageValue(action, OLD_CONTENT), false);
    addAuthorField(action, embedBuilder);
    addChannelField(action, embedBuilder);

    embedBuilder.setFooter(messageService.getMessage("audit.message.id", messageId), null);
}
 
Example 3
Source File: AudioMessageManager.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
private void addQueue(EmbedBuilder builder, PlaybackInstance instance, List<TrackRequest> requests, int offset, boolean nextHint) {
    if (requests.isEmpty()) {
        return;
    }

    for (int i = 0; i < requests.size(); i++) {
        TrackRequest request = requests.get(i);
        AudioTrack track = request.getTrack();
        AudioTrackInfo info = track.getInfo();

        int rowNum = i + offset;
        String name = EmbedBuilder.ZERO_WIDTH_SPACE;
        if (nextHint && i == 0) {
            name = messageService.getMessage("discord.command.audio.queue.next");
        }

        String duration = info.isStream ? "" : String.format("`[%s]`", CommonUtils.formatDuration(track.getDuration()));
        String icon = info.isStream ? ":red_circle: " : ":musical_note: ";
        String title = messageService.getMessage("discord.command.audio.queue.list.entry", rowNum,
                duration, !nextHint && rowNum - instance.getCursor() == 1 ? icon : "",
                getTitle(info), getUrl(info), getMemberName(request, false));
        builder.addField(name, title, false);
    }
}
 
Example 4
Source File: ServerInfoCommand.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean doCommand(GuildMessageReceivedEvent message, BotContext context, String query) {
    Guild guild = message.getGuild();

    EmbedBuilder builder = messageService.getBaseEmbed();
    builder.setTitle(messageService.getMessage("discord.command.server.title", guild.getName()));
    builder.setThumbnail(guild.getIconUrl());
    builder.setFooter(messageService.getMessage("discord.command.info.identifier", guild.getId()), null);

    builder.addField(getMemberListField(guild));
    builder.addField(getChannelListField(guild));
    builder.addField(getShard(guild));
    builder.addField(getVerificationLevel(guild.getVerificationLevel()));
    builder.addField(getRegion(guild));
    builder.addField(getOwner(guild));
    builder.addField(getCreatedAt(guild, context));

    messageService.sendMessageSilent(message.getChannel()::sendMessage, builder.build());
    return true;
}
 
Example 5
Source File: MemberWarnAuditForwardProvider.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void build(AuditAction action, MessageBuilder messageBuilder, EmbedBuilder embedBuilder) {
    if (action.getTargetUser() == null) {
        return;
    }
    String message = messageService.getMessage("audit.member.warn.message",
            getReferenceContent(action.getTargetUser(), false));
    embedBuilder.setDescription(message);

    addModeratorField(action, embedBuilder);

    Number count = action.getAttribute(COUNT_ATTR, Number.class);
    if (count != null) {
        embedBuilder.addField(messageService.getMessage("audit.member.warn.count.title"),
                messageService.getMessage("audit.member.warn.count.content", count), true);
    }

    addReasonField(action, embedBuilder);
    addExpirationField(action, embedBuilder);

    embedBuilder.setFooter(messageService.getMessage("audit.member.id", action.getTargetUser().getId()), null);
}
 
Example 6
Source File: MessageEditAuditForwardProvider.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void build(AuditAction action, MessageBuilder messageBuilder, EmbedBuilder embedBuilder) {
    String messageId = action.getAttribute(MESSAGE_ID, String.class);
    if (action.getChannel() == null || action.getUser() == null || messageId == null) {
        return;
    }

    embedBuilder.setDescription(messageService.getMessage("audit.message.edit.message",
            String.valueOf(action.getGuildId()),
            action.getChannel().getId(),
            messageId));

    addOldContentField(action, embedBuilder);
    embedBuilder.addField(messageService.getMessage("audit.message.newContent.title"),
            getMessageValue(action, NEW_CONTENT), false);

    addAuthorField(action, embedBuilder);
    addChannelField(action, embedBuilder);

    embedBuilder.setFooter(messageService.getMessage("audit.message.id", messageId), null);
}
 
Example 7
Source File: DogCommand.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
private void sendImage(GuildMessageReceivedEvent event, DogImage image) {
    EmbedBuilder builder = messageService.getBaseEmbed();
    builder.setImage(image.getUrl());
    if (CollectionUtils.isNotEmpty(image.getBreeds())) {
        DogBreed breed = image.getBreeds().get(0);
        if (StringUtils.isNotEmpty(breed.getName())) {
            builder.addField(messageService.getMessage("discord.command.dog.breed.title"), breed.getName(), true);
        }
        if (StringUtils.isNotEmpty(breed.getBreedGroup())) {
            builder.addField(messageService.getMessage("discord.command.dog.breedGroup.title"), breed.getBreedGroup(), true);
        }
        if (StringUtils.isNotEmpty(breed.getBredFor())) {
            builder.addField(messageService.getMessage("discord.command.dog.bredFor.title"), breed.getBredFor(), true);
        }
        if (StringUtils.isNotEmpty(breed.getTemperament())) {
            builder.addField(messageService.getMessage("discord.command.dog.temperament.title"), breed.getTemperament(), true);
        }
        String weight = getMeasure(breed.getWeight());
        if (StringUtils.isNotEmpty(weight)) {
            builder.addField(messageService.getMessage("discord.command.dog.weight.title"), weight, true);
        }
        String height = getMeasure(breed.getHeight());
        if (StringUtils.isNotEmpty(height)) {
            builder.addField(messageService.getMessage("discord.command.dog.height.title"), height, true);
        }
    }
    messageService.sendMessageSilent(event.getChannel()::sendMessage, builder.build());
}
 
Example 8
Source File: GuildListener.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
private MessageEmbed createWelcomeMessage(Guild guild) {
    Function<String, String> m = messageService::getMessage;
    String webPage = m.apply("about.support.page");
    String discordServer = m.apply("about.support.server");
    String githubPage = m.apply("about.support.github");
    EmbedBuilder builder = messageService.getBaseEmbed(true);
    builder.setDescription(messageService.getMessage("welcome.guild.message") + NEW_LINE);

    User self = guild.getJDA().getSelfUser();
    builder.setAuthor(self.getName(), webPage, self.getAvatarUrl());

    builder.addField(m.apply("welcome.fields.common.title"),
            m.apply("welcome.fields.common.content") + NEW_LINE, false);
    builder.addField(m.apply("welcome.fields.music.title"),
            m.apply("welcome.fields.music.content") + NEW_LINE, false);
    builder.addField(m.apply("welcome.fields.audit.title"),
            m.apply("welcome.fields.audit.content") + NEW_LINE, false);
    builder.addField(m.apply("welcome.fields.subscriptions.title"),
            m.apply("welcome.fields.subscriptions.content") + NEW_LINE, false);
    builder.addField(m.apply("welcome.fields.ranking.title"),
            m.apply("welcome.fields.ranking.content") + NEW_LINE, false);
    builder.addField(m.apply("welcome.fields.welcome.title"),
            m.apply("welcome.fields.welcome.content") + NEW_LINE, false);
    builder.addField(m.apply("welcome.fields.commands.title"),
            m.apply("welcome.fields.commands.content") + NEW_LINE, false);
    builder.addField(m.apply("welcome.fields.custom.title"),
            m.apply("welcome.fields.custom.content") + NEW_LINE, false);
    builder.addField(m.apply("welcome.fields.fun.title"),
            m.apply("welcome.fields.fun.content") + NEW_LINE, false);

    builder.addField(m.apply("welcome.fields.support.title"),
            messageService.getMessage("welcome.fields.support.content", webPage, discordServer, githubPage),
            false);

    return builder.build();
}
 
Example 9
Source File: StatsCommand.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean doCommand(GuildMessageReceivedEvent message, BotContext context, String content) {
    EmbedBuilder builder = messageService.getBaseEmbed(true);
    builder.setTitle(messageService.getMessage("discord.command.stats.title"));
    builder.setThumbnail(commonProperties.getBranding().getAvatarSmallUrl());

    Map<String, Metric> metricMap = metricRegistry.getMetrics();
    builder.addField(getCommonStats(metricMap));
    builder.addField(getCommandStats(metricMap));
    builder.addField(getPlatformStats(metricMap));

    messageService.sendMessageSilent(message.getChannel()::sendMessage, builder.build());
    return true;
}
 
Example 10
Source File: InfoCommand.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean doCommand(GuildMessageReceivedEvent message, BotContext context, String query) {
    String prefix = context.getConfig() != null ? context.getConfig().getPrefix() : commonProperties.getDiscord().getDefaultPrefix();

    EmbedBuilder builder = messageService.getBaseEmbed(true);
    builder.setAuthor(message.getJDA().getSelfUser().getName(), messageService.getMessage("about.support.page"));
    builder.setThumbnail(commonProperties.getBranding().getAvatarSmallUrl());

    String helpCommand = messageService.getMessageByLocale("discord.command.help.key",
            context.getCommandLocale());

    builder.setDescription(messageService.getMessage("discord.command.info.description", prefix, helpCommand));

    builder.addField(
            messageService.getMessage("discord.command.info.author.title"),
            messageService.getMessage("about.support.owner"), true);

    DateTimeFormatter formatter = DateTimeFormat
            .mediumDateTime()
            .withLocale(contextService.getLocale())
            .withZone(context.getTimeZone());
    builder.addField(
            messageService.getMessage("discord.command.info.version.title"),
            String.format("%s (%s)", appVersion, formatter.print(buildTimestamp)), true);

    builder.addField(
            messageService.getMessage("discord.command.info.links.title"),
            messageService.getMessage("discord.command.info.links.content"), true);

    builder.addField(
            messageService.getMessage("discord.command.info.framework.title"),
            messageService.getMessage("discord.command.info.framework.content",
                    jdaVersion, lavaPlayerVersion, springVersion),
            true);

    messageService.sendMessageSilent(message.getChannel()::sendMessage, builder.build());
    return true;
}
 
Example 11
Source File: ModerationAuditForwardProvider.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
protected void addExpirationField(AuditAction action, EmbedBuilder embedBuilder) {
    Long durationMs = action.getAttribute(DURATION_MS_ATTR, Long.class);
    if (durationMs != null) {
        String result = PrettyTimeUtils.print(durationMs, contextService.getLocale());
        embedBuilder.addField(messageService.getMessage("audit.member.mute.durationms.title"), result, true);
    }
}
 
Example 12
Source File: DiscordUtils.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
private static EmbedBuilder addAllFields(EmbedBuilder builder, List<MessageEmbed.Field> fields) {
    builder.clearFields();
    for (MessageEmbed.Field f : fields) {
        builder.addField(f);
    }

    return builder;
}
 
Example 13
Source File: LoggingAuditForwardProvider.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
protected void addChannelField(AuditAction action, EmbedBuilder embedBuilder) {
    if (action.getChannel() != null) {
        embedBuilder.addField(messageService.getMessage("audit.channel.title"),
                getReferenceContent(action.getChannel(), true), true);
    }
}
 
Example 14
Source File: ModerationAuditForwardProvider.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
protected void addModeratorField(AuditAction action, EmbedBuilder embedBuilder) {
    if (action.getUser() != null) {
        embedBuilder.addField(messageService.getMessage("audit.moderator.title"),
                getReferenceContent(action.getUser(), false), true);
    }
}
 
Example 15
Source File: AudioMessageManager.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
private EmbedBuilder getPlayMessage(TrackRequest request) {
    EmbedBuilder builder = getBasicMessage(request);
    builder.setDescription(null);

    AudioTrackInfo info = request.getTrack().getInfo();
    PlaybackInstance instance = TrackData.get(request.getTrack()).getInstance();
    boolean refreshable = isRefreshable(instance.getGuildId());

    String durationText;
    if (request.getEndReason() != null) {
        StringBuilder reasonBuilder = new StringBuilder();

        boolean hasDuration = !info.isStream && info.length > 0;
        if (hasDuration) {
            reasonBuilder.append(CommonUtils.formatDuration(request.getTrack().getDuration())).append(" (");
        }
        reasonBuilder.append(messageService.getEnumTitle(request.getEndReason()));

        String endMember = getMemberName(request, true);
        if (StringUtils.isNotBlank(endMember)) {
            reasonBuilder
                    .append(" - **")
                    .append(endMember)
                    .append("**");
        }
        if (hasDuration) {
            reasonBuilder.append(")");
        }
        reasonBuilder.append(CommonUtils.EMPTY_SYMBOL);
        durationText = reasonBuilder.toString();
    } else {
        durationText = getTextProgress(instance, request.getTrack(), refreshable);
    }

    if (instance.getPlaylistUuid() != null) {
        builder.setDescription(messageService.getMessage("discord.command.audio.panel.playlist",
                commonProperties.getBranding().getWebsiteUrl(), instance.getPlaylistUuid()));
    }

    int size = instance.getQueue().size();
    if (request.getEndReason() == null && size > 1) {
        MusicConfig config = musicConfigService.getByGuildId(instance.getGuildId());
        if (config != null && config.isShowQueue()) {
            List<TrackRequest> next = instance.getQueue().subList(1, Math.min(size, MAX_SHORT_QUEUE + 1));
            addQueue(builder, instance, next, 2 + instance.getCursor(), true);
        }
    }

    if (request.getTrack().getInfo().isStream || !refreshable) {
        builder.addField(messageService.getMessage("discord.command.audio.panel.duration"),
                durationText, true);
        builder.addField(messageService.getMessage("discord.command.audio.panel.requestedBy"),
                getMemberName(request, false), true);
    } else {
        String requestedBy = String.format("%s: %s",
                messageService.getMessage("discord.command.audio.panel.requestedBy"),
                getMemberName(request, false));
        builder.addField(requestedBy, durationText, true);
    }

    if (request.getEndReason() == null) {
        IPlayer player = instance.getPlayer();
        if (player.getVolume() != 100) {
            int volume = player.getVolume();
            builder.addField(messageService.getMessage("discord.command.audio.panel.volume"),
                    String.format("%d%% %s", volume, CommonUtils.getVolumeIcon(volume)), true);
        }
        if (!RepeatMode.NONE.equals(instance.getMode())) {
            builder.addField(messageService.getMessage("discord.command.audio.panel.repeatMode"),
                    instance.getMode().getEmoji(), true);
        }
        if (player.isPaused()) {
            builder.addField(messageService.getMessage("discord.command.audio.panel.paused"),
                    "\u23F8", true);
        }

        if (player instanceof LavalinkPlayer) {
            LavalinkPlayer lavalinkPlayer = (LavalinkPlayer) player;
            Link link = lavalinkPlayer.getLink();
            if (link != null) {
                LavalinkSocket socket = link.getNode(false);
                if (socket != null) {
                    StringBuilder statsBuilder = new StringBuilder(messageService
                            .getMessage("discord.command.audio.panel.poweredBy", socket.getName()));
                    if (refreshable && socket.getStats() != null) {
                        long load = Math.round(socket.getStats().getSystemLoad() * 100);
                        if (load < 0) load = 0;
                        if (load > 100) load = 100;
                        statsBuilder
                                .append(" ")
                                .append(messageService.getMessage("discord.command.audio.panel.load", load));
                    }
                    builder.setFooter(statsBuilder.toString(), null);
                }
            }
        }
    }
    return builder;
}
 
Example 16
Source File: DiscordUtils.java    From MantaroBot with GNU General Public License v3.0 4 votes vote down vote up
public static Future<Void> list(GuildMessageReceivedEvent event, int timeoutSeconds, boolean canEveryoneUse, EmbedBuilder base, List<List<MessageEmbed.Field>> parts) {
    if (parts.size() == 0)
        return null;

    for (MessageEmbed.Field f : parts.get(0)) {
        base.addField(f);
    }

    if (parts.size() == 1) {
        event.getChannel().sendMessage(base.build()).queue();
        return null;
    }

    AtomicInteger index = new AtomicInteger();
    Message m = event.getChannel().sendMessage(base.build()).complete();
    return ReactionOperations.create(m, timeoutSeconds, (e) -> {
        if (!canEveryoneUse && e.getUser().getIdLong() != event.getAuthor().getIdLong())
            return Operation.IGNORED;

        switch (e.getReactionEmote().getName()) {
            //left arrow
            case "\u2b05" -> {
                if (index.get() == 0)
                    break;
                EmbedBuilder toSend = addAllFields(base, parts.get(index.decrementAndGet()));
                toSend.setFooter("Current page: " + (index.get() + 1), event.getAuthor().getEffectiveAvatarUrl());
                m.editMessage(toSend.build()).queue();
            }
            //right arrow
            case "\u27a1" -> {
                if (index.get() + 1 >= parts.size())
                    break;
                EmbedBuilder toSend1 = addAllFields(base, parts.get(index.incrementAndGet()));
                toSend1.setFooter("Current page: " + (index.get() + 1), event.getAuthor().getEffectiveAvatarUrl());
                m.editMessage(toSend1.build()).queue();
            }
        }

        if (event.getGuild().getSelfMember().hasPermission(e.getTextChannel(), Permission.MESSAGE_MANAGE)) {
            e.getReaction().removeReaction(e.getUser()).queue();
        }

        return Operation.IGNORED;
    }, "\u2b05", "\u27a1");
}
 
Example 17
Source File: RemindCommand.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean doCommand(GuildMessageReceivedEvent message, BotContext context, String content) {
    try {
        DateTime date = null;
        String reminder = null;
        Matcher m = PATTERN.matcher(content);
        if (m.find()) {
            date = getFormatter(context).parseDateTime(String.format("%s %s", m.group(1), m.group(2)));
            reminder = m.group(3);
            if (DateTime.now().isAfter(date)) {
                messageService.onError(message.getChannel(), "discord.command.remind.error.future");
                return fail(message);
            }
        }

        String keyWord = messageService.getMessage("discord.command.remind.keyWord");
        m = Pattern.compile(String.format(RELATIVE_PATTERN_FORMAT, keyWord)).matcher(content);
        if (m.find()) {
            Long millis = TimeSequenceParser.parseFull(m.group(1));
            reminder = m.group(2);
            if (millis != null && StringUtils.isNotEmpty(reminder)) {
                date = DateTime.now().plus(millis);
            }
        }

        if (date != null && reminder != null) {
            createReminder(message.getChannel(), message.getMember(), reminder, date.toDate());
            return ok(message, "discord.command.remind.done");
        }
    } catch (IllegalArgumentException e) {
        // fall down
    }

    String prefix = context.getConfig() != null ? context.getConfig().getPrefix() : commonProperties.getDiscord().getDefaultPrefix();

    String remindCommand = messageService.getMessageByLocale("discord.command.remind.key",
            context.getCommandLocale());

    DateTime current = DateTime.now();
    current = current.plusMinutes(1);
    EmbedBuilder builder = messageService.getBaseEmbed();
    builder.setTitle(messageService.getMessage("discord.command.remind.help.title"));
    builder.addField(
            messageService.getMessage("discord.command.remind.help.field1.title",
                    CommonUtils.getUTCOffset(context.getTimeZone())),
            messageService.getMessage("discord.command.remind.help.field1.value", prefix, remindCommand,
                    getFormatter(context).print(current)), false);
    builder.addField(
            messageService.getMessage("discord.command.remind.help.field2.title"),
            messageService.getMessage("discord.command.remind.help.field2.value", prefix, remindCommand),
            false);
    messageService.sendMessageSilent(message.getChannel()::sendMessage, builder.build());
    return false;
}
 
Example 18
Source File: SteamCommand.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean doCommand(GuildMessageReceivedEvent message, BotContext context, String query) {
    if (StringUtils.isEmpty(query)) {
        messageService.onMessage(message.getChannel(), "discord.command.steam.enter");
        return true;
    }
    message.getChannel().sendTyping().queue();
    SteamApp app = null;
    if (StringUtils.isNumeric(query)) {
        app = steamService.findByAppId(Long.parseLong(query));
    }
    if (app == null) {
        app = steamService.findOne(query);
    }
    SteamAppDetails details = steamService.getDetails(app, contextService.getLocale());
    if (details == null) {
        messageService.onMessage(message.getChannel(), "discord.command.steam.noResults");
        return false;
    }

    String storeUrl = APP_PAGE + app.getAppId();

    EmbedBuilder builder = messageService.getBaseEmbed(true);
    if (StringUtils.isNotEmpty(details.getHeaderImage())) {
        builder.setThumbnail(details.getHeaderImage());
    }
    builder.setAuthor(details.getName(), storeUrl);
    builder.setDescription(details.getShortDescription());

    if (details.getReleaseDate() != null && details.getReleaseDate().isCorrect()) {
        builder.addField(getReleaseDate(details.getReleaseDate()));
    }
    if (details.getPrice() != null && details.getPrice().isCorrect()) {
        builder.addField(getPrice(details.getPrice()));
    }
    if (CollectionUtils.isNotEmpty(details.getDevelopers())) {
        builder.addField(getParts(details.getDevelopers(), "discord.command.steam.developers"));
    }
    if (CollectionUtils.isNotEmpty(details.getPublishers())) {
        builder.addField(getParts(details.getPublishers(), "discord.command.steam.publishers"));
    }
    if (details.getPlatforms() != null && details.getPlatforms().isCorrect()) {
        builder.addField(getPlatforms(details.getPlatforms()));
    }
    if (StringUtils.isNotEmpty(details.getWebSite())) {
        builder.addField(messageService.getMessage("discord.command.steam.website"), details.getWebSite(), true);
    }

    if (CollectionUtils.isNotEmpty(details.getScreenshots())) {
        for (SteamAppScreenshot screenshot : details.getScreenshots()) {
            if (StringUtils.isNotEmpty(screenshot.getFull())) {
                builder.setImage(screenshot.getFull());
                break;
            }
        }
    }
    messageService.sendMessageSilent(message.getChannel()::sendMessage, builder.build());
    return true;
}
 
Example 19
Source File: WarnsCommand.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean doCommand(MemberReference reference, GuildMessageReceivedEvent event, BotContext context, String query) {
    LocalMember member = reference.getLocalMember();

    List<MemberWarning> warningList = moderationService.getWarnings(member);
    if (warningList.isEmpty()) {
        messageService.onEmbedMessage(event.getChannel(), "discord.command.mod.warns.empty");
        return false;
    }
    if (warningList.size() > 20) {
        warningList = warningList.subList(0, 20);
    }

    EmbedBuilder builder = messageService.getBaseEmbed();
    builder.setTitle(messageService.getMessage("discord.command.mod.warns.message.title", member.getEffectiveName()));

    DateTimeFormatter formatter = DateTimeFormat
            .shortDateTime()
            .withZone(context.getTimeZone())
            .withLocale(contextService.getLocale());

    int i = 1;
    int length = builder.length();
    for (MemberWarning warning : warningList) {
        String title = String.format("%2s. %s %s (%s)", i++,
                formatter.print(new DateTime(warning.getDate())),
                CommonUtils.getUTCOffset(context.getTimeZone()),
                warning.getModerator().getEffectiveName());
        StringBuilder detailsBuilder = new StringBuilder();
        if (StringUtils.isNotEmpty(warning.getReason())) {
            detailsBuilder.append(messageService.getMessage("discord.command.mod.warns.reason",
                    warning.getReason()));
        }
        if (warning.getEndDate() != null) {
            if (detailsBuilder.length() > 0) {
                detailsBuilder.append("\n");
            }
            detailsBuilder.append(messageService.getMessage("discord.command.mod.warns.until",
                    formatter.print(new DateTime(warning.getEndDate())),
                    CommonUtils.getUTCOffset(context.getTimeZone())));
        }
        if ((length += title.length() + detailsBuilder.length()) > MessageEmbed.EMBED_MAX_LENGTH_BOT) {
            break;
        }
        builder.addField(title, detailsBuilder.toString(), false);
    }
    messageService.sendMessageSilent(event.getChannel()::sendMessage, builder.build());
    return true;
}
 
Example 20
Source File: MessageTemplateServiceImpl.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
public Message compile(@NonNull MessageTemplateCompiler compiler) {
    try {

        MessageTemplatePlaceholderResolver resolver = getPropertyResolver(compiler);
        String content = processContent(getContent(compiler), resolver, compiler, Message.MAX_CONTENT_LENGTH, false);
        MessageBuilder messageBuilder = new MessageBuilder();
        messageBuilder.setContent(content);
        if (compiler.getTemplate() != null) {
            messageBuilder.setTTS(compiler.getTemplate().isTts());
        }

        if (compiler.getTemplate() == null || compiler.getTemplate().getType() == MessageTemplateType.TEXT) {
            if (StringUtils.isBlank(content)) {
                return null;
            }
            return messageBuilder.build();
        }

        MessageTemplate template = compiler.getTemplate();

        EmbedBuilder embedBuilder = new EmbedBuilder();
        embedBuilder.setDescription(processContent(getEmbedContent(compiler), resolver, compiler, MessageEmbed.TEXT_MAX_LENGTH, false));
        embedBuilder.setThumbnail(processUrl(template.getThumbnailUrl(), resolver, compiler));
        embedBuilder.setImage(processUrl(template.getImageUrl(), resolver, compiler));
        if (StringUtils.isNotEmpty(template.getColor())) {
            embedBuilder.setColor(Color.decode(template.getColor()));
        } else {
            embedBuilder.setColor(contextService.getDefaultColor());
        }
        if (template.getTimestamp() != null) {
            embedBuilder.setTimestamp(template.getTimestamp().toInstant());
        }

        embedBuilder.setAuthor(
                processContent(template.getAuthor(), resolver, compiler, MessageEmbed.TITLE_MAX_LENGTH, false),
                processUrl(template.getAuthorUrl(), resolver, compiler),
                processUrl(template.getAuthorIconUrl(), resolver, compiler));

        embedBuilder.setTitle(
                processContent(template.getTitle(), resolver, compiler, MessageEmbed.TITLE_MAX_LENGTH, false),
                processUrl(template.getTitleUrl(), resolver, compiler));

        embedBuilder.setFooter(
                processContent(template.getFooter(), resolver, compiler, MessageEmbed.TEXT_MAX_LENGTH, false),
                processUrl(template.getFooterIconUrl(), resolver, compiler));

        int length = embedBuilder.length();

        if (CollectionUtils.isNotEmpty(template.getFields())) {
            for (MessageTemplateField templateField : template.getFields()) {
                String name = processContent(templateField.getName(), resolver, compiler,
                        MessageEmbed.TITLE_MAX_LENGTH, false);
                if (StringUtils.isEmpty(name)) {
                    name = "";
                }
                String value = processContent(templateField.getValue(), resolver, compiler,
                        MessageEmbed.VALUE_MAX_LENGTH, false);
                if (StringUtils.isEmpty(value)) {
                    value = "";
                }

                if ((length += name.length() + value.length()) > MessageEmbed.EMBED_MAX_LENGTH_BOT) {
                    break;
                }
                embedBuilder.addField(name, value, templateField.isInline());
            }
        }

        if (messageBuilder.isEmpty() && embedBuilder.isEmpty()) {
            return null;
        }
        messageBuilder.setEmbed(embedBuilder.build());
        return messageBuilder.build();
    } catch (IllegalArgumentException e) {
        log.error("Cannot compile message", e);
    }
    return null;
}