Search in sources :

Example 1 with Attachment

use of net.dv8tion.jda.api.entities.Message.Attachment in project ExciteBot by TheGameCommunity.

the class ArchiveCommand method archive.

private static int archive(MessageContext source, String argument) {
    if (source.isAdmin()) {
        if (source.isGuildMessage()) {
            if (argument.isEmpty()) {
                source.sendMessage("Usage: archive <TextChannels>");
                return 1;
            }
            DiscordServer server = source.getServer();
            Guild guild = server.getGuild();
            Member member = DiscordUser.getMember(source.getDiscordAuthor(), server);
            HashSet<TextChannel> channelsToArchive = getChannels(source, guild, Arrays.asList(argument.split(" ")));
            for (TextChannel channel : channelsToArchive) {
                if (!member.hasPermission(channel, Permission.MANAGE_CHANNEL, Permission.MESSAGE_MANAGE)) {
                    source.sendMessage("You must have the `MANAGE_CHANNEL` and `MESSAGE_MANAGE` permission in " + channel.getAsMention() + " in order to archive it.");
                    return 1;
                }
            }
            Thread workerThread = ThreadService.run("Archiver thread", new Thread() {

                private final Thread workerThread = this;

                private final int newlineSize = System.lineSeparator().length();

                public volatile WorkerStatus status = NOT_STARTED;

                public volatile byte updates = 0;

                public volatile int messagesArchived = 0;

                public volatile int wiiMessagesArchived = 0;

                public volatile int attachmentsArchived = 0;

                public volatile long estimatedSize = 0;

                private volatile Throwable error;

                @Override
                public void run() {
                    Thread monitorThread = ThreadService.run("Archive monitor", new Thread() {

                        public void run() {
                            Instant start = Instant.now();
                            EmbedBuilder embed = new EmbedBuilder();
                            embed.setTitle("Archive in progress...");
                            Field archivedDiscordMessagesField = new Field("Discord Messages archived:", "0", true, true);
                            Field archivedDiscordAttachmentsField = new Field("Discord Attachments archived:", "0", true, true);
                            Field emailsArchivedField = new Field("Wii Mails archived:", "0", true, true);
                            Field estimatedSizeField = new Field("Estimated size:", FileUtils.humanReadableByteCount(0), true, true);
                            Field timeElapsedField = new Field("Time elapsed:", "0 seconds", true, true);
                            embed.setTimestamp(start);
                            WorkerStatus currentStatus = status;
                            embed.addField(archivedDiscordMessagesField);
                            embed.addField(archivedDiscordAttachmentsField);
                            embed.addField(emailsArchivedField);
                            embed.addField(estimatedSizeField);
                            embed.addField(timeElapsedField);
                            Message message = source.sendMessage(embed.build());
                            while (!currentStatus.finished()) {
                                try {
                                    Thread.sleep(2500);
                                    currentStatus = status;
                                    Instant now = Instant.now();
                                    embed = new EmbedBuilder();
                                    if (currentStatus == NOT_STARTED) {
                                        embed.setColor(Color.DARK_GRAY);
                                    }
                                    if (currentStatus == WORKING) {
                                        if (updates++ % 2 == 0) {
                                            embed.setColor(Color.YELLOW);
                                        } else {
                                            // dark yellow
                                            embed.setColor(new Color(204, 204, 0));
                                        }
                                        embed.setTitle("Archive in progress...");
                                        embed.addField(archivedDiscordMessagesField = new Field("Discord Messages archived:", messagesArchived + "", true, true));
                                        embed.addField(archivedDiscordAttachmentsField = new Field("Discord Attachments archived:", attachmentsArchived + "", true, true));
                                        embed.addField(emailsArchivedField = new Field("Wii Messages archived:", wiiMessagesArchived + "", true, true));
                                        embed.addField(estimatedSizeField = new Field("Estimated size:", FileUtils.humanReadableByteCount(estimatedSize), true, true));
                                        embed.addField(timeElapsedField = new Field("Time elapsed:", TimeUtils.readableDuration(Duration.between(start, now)), true, true));
                                        embed.setTimestamp(now);
                                        message.editMessage(embed.build()).complete();
                                    }
                                    Thread.sleep(2500);
                                } catch (InterruptedException e) {
                                    currentStatus = ERRORED;
                                    embed.setTitle("Archive failed");
                                    embed.setColor(Color.RED);
                                    message.editMessage(embed.build()).complete();
                                    System.out.println("Monitor thread interrupted... stopping!");
                                    return;
                                }
                            }
                            Instant now = Instant.now();
                            embed.addField(archivedDiscordMessagesField = new Field("Discord Messages archived:", messagesArchived + "", true, true));
                            embed.addField(archivedDiscordAttachmentsField = new Field("Discord Attachments archived:", attachmentsArchived + "", true, true));
                            embed.addField(emailsArchivedField = new Field("Wii Messages archived:", wiiMessagesArchived + "", true, true));
                            embed.addField(estimatedSizeField = new Field("Estimated size:", FileUtils.humanReadableByteCount(estimatedSize), true, true));
                            embed.addField(timeElapsedField = new Field("Time elapsed:", TimeUtils.readableDuration(Duration.between(start, now)), true, true));
                            embed.setTimestamp(now);
                            message.editMessage(embed.build()).complete();
                            if (currentStatus == COMPLETE) {
                                embed.setColor(Color.GREEN);
                                embed.setTitle("Archive complete");
                                source.sendMessage(source.getDiscordAuthor().getJDAUser().getAsMention() + " Archive complete.");
                            } else {
                                embed.setColor(Color.RED);
                                embed.setTitle("Archive failed");
                                source.sendMessage(source.getDiscordAuthor().getJDAUser().getAsMention() + " Archive FAILED.");
                            }
                            message.editMessage(embed.build()).complete();
                        }
                    });
                    String date = TimeUtils.getDBDate(Instant.now());
                    try {
                        status = WORKING;
                        for (File f : org.apache.commons.io.FileUtils.listFiles(Mailbox.MAILBOX, null, true)) {
                            File archive = new File(".archive/" + date + "/" + f.getPath().replace("/run", ""));
                            if (!archive.getParentFile().mkdirs() && !archive.getParentFile().exists()) {
                                throw new IOException("Could not create " + archive.getAbsolutePath());
                            }
                            org.apache.commons.io.FileUtils.copyFile(f, archive);
                            wiiMessagesArchived++;
                            estimatedSize += archive.length();
                        }
                        for (TextChannel channel : channelsToArchive) {
                            try {
                                File file = new File(".archive/" + date + "/" + channel.getName() + "/" + channel.getName() + ".arc");
                                if (!file.getParentFile().mkdirs()) {
                                    throw new IOException("Could not create " + file.getAbsolutePath());
                                }
                                System.out.println(file.getAbsolutePath());
                                file.createNewFile();
                                MessagePaginationAction action = channel.getIterableHistory();
                                BufferedWriter fileWriter = new BufferedWriter(new FileWriter(file));
                                action.forEach((message) -> {
                                    try {
                                        List<Attachment> attachments = message.getAttachments();
                                        write(fileWriter, "==========START " + message.getIdLong() + " USER:" + message.getAuthor().getAsTag());
                                        write(fileWriter, message.getContentRaw());
                                        if (!attachments.isEmpty()) {
                                            write(fileWriter, "==========ATTACHMENTS " + message.getIdLong());
                                            for (Attachment attachment : attachments) {
                                                File attachmentFile = new File(file.getParentFile().getPath() + "/attach" + attachment.getIdLong() + attachment.getFileName());
                                                CompletableFuture<File> future = attachment.downloadToFile(attachmentFile);
                                                future.exceptionally(error -> {
                                                    int i = 0;
                                                    source.sendMessage("Encountered " + error.getClass().getSimpleName() + " while downloading " + attachmentFile + " retrying... (" + i++ + "/4)");
                                                    while (i < 4) {
                                                        try {
                                                            future.get();
                                                            i++;
                                                        } catch (Throwable t) {
                                                            if (t instanceof InterruptedException) {
                                                                throw new ThreadDeath();
                                                            }
                                                            if (i < 4) {
                                                                source.sendMessage("Encountered " + t.getClass().getSimpleName() + " while downloading " + attachmentFile + " retrying... (" + i + "/4)");
                                                            }
                                                        }
                                                    }
                                                    return null;
                                                }).get();
                                                write(fileWriter, attachment.getId() + attachmentFile.getName());
                                                estimatedSize += attachment.getSize();
                                                attachmentsArchived++;
                                            }
                                        }
                                        write(fileWriter, "==========END " + message.getIdLong());
                                        messagesArchived++;
                                    } catch (IOException | InterruptedException | ExecutionException e) {
                                        throw new RuntimeException(e);
                                    }
                                });
                                fileWriter.close();
                            } catch (Throwable t) {
                                source.sendMessage("Could not back up channel " + channel.getAsMention());
                                throw t;
                            }
                        }
                        status = COMPLETE;
                    } catch (Throwable t) {
                        source.sendMessage(StacktraceUtil.getStackTrace(t));
                        status = ERRORED;
                    }
                }

                private void write(BufferedWriter writer, String text) throws IOException {
                    estimatedSize += text.length() + newlineSize;
                    writer.write(text);
                    writer.newLine();
                }
            });
        } else {
            source.sendMessage("You must execute this command in a server");
        }
    } else {
        source.sendMessage("You must be an administator to execute this command");
    }
    return 1;
}
Also used : Color(java.awt.Color) ThreadService(com.gamebuster19901.excite.util.ThreadService) Arrays(java.util.Arrays) CommandDispatcher(com.mojang.brigadier.CommandDispatcher) Permission(net.dv8tion.jda.api.Permission) CompletableFuture(java.util.concurrent.CompletableFuture) Member(net.dv8tion.jda.api.entities.Member) Field(net.dv8tion.jda.api.entities.MessageEmbed.Field) TextChannel(net.dv8tion.jda.api.entities.TextChannel) MessagePaginationAction(net.dv8tion.jda.api.requests.restaction.pagination.MessagePaginationAction) HashSet(java.util.HashSet) StringArgumentType(com.mojang.brigadier.arguments.StringArgumentType) WorkerStatus(com.gamebuster19901.excite.bot.command.ArchiveCommand.WorkerStatus) Guild(net.dv8tion.jda.api.entities.Guild) Duration(java.time.Duration) Mailbox(com.gamebuster19901.excite.bot.mail.Mailbox) StacktraceUtil(com.gamebuster19901.excite.util.StacktraceUtil) Message(net.dv8tion.jda.api.entities.Message) Attachment(net.dv8tion.jda.api.entities.Message.Attachment) BufferedWriter(java.io.BufferedWriter) FileUtils(com.gamebuster19901.excite.util.file.FileUtils) FileWriter(java.io.FileWriter) DiscordUser(com.gamebuster19901.excite.bot.user.DiscordUser) IOException(java.io.IOException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Instant(java.time.Instant) File(java.io.File) ExecutionException(java.util.concurrent.ExecutionException) DiscordServer(com.gamebuster19901.excite.bot.server.DiscordServer) List(java.util.List) TimeUtils(com.gamebuster19901.excite.util.TimeUtils) Message(net.dv8tion.jda.api.entities.Message) FileWriter(java.io.FileWriter) Attachment(net.dv8tion.jda.api.entities.Message.Attachment) Guild(net.dv8tion.jda.api.entities.Guild) BufferedWriter(java.io.BufferedWriter) Field(net.dv8tion.jda.api.entities.MessageEmbed.Field) TextChannel(net.dv8tion.jda.api.entities.TextChannel) CompletableFuture(java.util.concurrent.CompletableFuture) WorkerStatus(com.gamebuster19901.excite.bot.command.ArchiveCommand.WorkerStatus) List(java.util.List) Member(net.dv8tion.jda.api.entities.Member) Instant(java.time.Instant) Color(java.awt.Color) IOException(java.io.IOException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) DiscordServer(com.gamebuster19901.excite.bot.server.DiscordServer) File(java.io.File) MessagePaginationAction(net.dv8tion.jda.api.requests.restaction.pagination.MessagePaginationAction)

Example 2 with Attachment

use of net.dv8tion.jda.api.entities.Message.Attachment in project Factorio-FBSR by demodude4u.

the class BlueprintBotDiscordService method handleBlueprintUpgradeBeltsCommand.

private void handleBlueprintUpgradeBeltsCommand(SlashCommandEvent event) {
    String content = event.getCommandString();
    Optional<Attachment> attachment = event.optParamAttachment("file");
    if (attachment.isPresent()) {
        content += " " + attachment.get().getUrl();
    }
    List<BlueprintStringData> blueprintStringDatas = BlueprintFinder.search(content, event.getReporting());
    int upgradedCount = 0;
    for (BlueprintStringData blueprintStringData : blueprintStringDatas) {
        for (Blueprint blueprint : blueprintStringData.getBlueprints()) {
            for (BlueprintEntity blueprintEntity : blueprint.getEntities()) {
                String upgradeName = upgradeBeltsEntityMapping.get(blueprintEntity.getName());
                if (upgradeName != null) {
                    blueprintEntity.json().put("name", upgradeName);
                    upgradedCount++;
                }
            }
        }
    }
    if (upgradedCount > 0) {
        for (BlueprintStringData blueprintStringData : blueprintStringDatas) {
            try {
                event.replyFile(BlueprintStringData.encode(blueprintStringData.json()).getBytes(), "blueprint.txt");
            } catch (IOException e) {
                event.getReporting().addException(e);
            }
        }
        event.reply("Upgraded " + upgradedCount + " entities.");
    } else if (blueprintStringDatas.stream().anyMatch(d -> !d.getBlueprints().isEmpty())) {
        event.replyIfNoException("I couldn't find anything to upgrade!");
    } else {
        event.replyIfNoException("No blueprint found!");
    }
}
Also used : OptionType(net.dv8tion.jda.api.interactions.commands.OptionType) Arrays(java.util.Arrays) EventReply(com.demod.dcba.EventReply) URL(java.net.URL) FBSR(com.demod.fbsr.FBSR) Permission(net.dv8tion.jda.api.Permission) SlashCommandHandler(com.demod.dcba.SlashCommandHandler) Field(net.dv8tion.jda.api.entities.MessageEmbed.Field) TextChannel(net.dv8tion.jda.api.entities.TextChannel) DataTable(com.demod.factorio.DataTable) RenderUtils(com.demod.fbsr.RenderUtils) JSONException(org.json.JSONException) Matcher(java.util.regex.Matcher) JSONObject(org.json.JSONObject) Map(java.util.Map) ZipEntry(java.util.zip.ZipEntry) WebUtils(com.demod.fbsr.WebUtils) Message(net.dv8tion.jda.api.entities.Message) BufferedImage(java.awt.image.BufferedImage) DataPrototype(com.demod.factorio.prototype.DataPrototype) LevenshteinDistance(org.apache.commons.text.similarity.LevenshteinDistance) Collectors(java.util.stream.Collectors) Config(com.demod.factorio.Config) BlueprintEntity(com.demod.fbsr.BlueprintEntity) List(java.util.List) FactorioData(com.demod.factorio.FactorioData) MessageCommandEvent(com.demod.dcba.MessageCommandEvent) Entry(java.util.Map.Entry) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) BlueprintStringData(com.demod.fbsr.BlueprintStringData) ZipOutputStream(java.util.zip.ZipOutputStream) Blueprint(com.demod.fbsr.Blueprint) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HashMap(java.util.HashMap) Function(java.util.function.Function) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) WatchdogReporter(com.demod.fbsr.app.WatchdogService.WatchdogReporter) ImmutableList(com.google.common.collect.ImmutableList) AbstractIdleService(com.google.common.util.concurrent.AbstractIdleService) SlashCommandEvent(com.demod.dcba.SlashCommandEvent) SimpleEntry(java.util.AbstractMap.SimpleEntry) Attachment(net.dv8tion.jda.api.entities.Message.Attachment) MapVersion(com.demod.fbsr.MapVersion) OptionData(net.dv8tion.jda.api.interactions.commands.build.OptionData) CommandReporting(com.demod.dcba.CommandReporting) DCBA(com.demod.dcba.DCBA) IOException(java.io.IOException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Utils(com.demod.factorio.Utils) DiscordBot(com.demod.dcba.DiscordBot) LuaValue(org.luaj.vm2.LuaValue) AutoCompleteHandler(com.demod.dcba.AutoCompleteHandler) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) ArrayDeque(java.util.ArrayDeque) BlueprintFinder(com.demod.fbsr.BlueprintFinder) ChunkingFilter(net.dv8tion.jda.api.utils.ChunkingFilter) JSONArray(org.json.JSONArray) BlueprintEntity(com.demod.fbsr.BlueprintEntity) Blueprint(com.demod.fbsr.Blueprint) Attachment(net.dv8tion.jda.api.entities.Message.Attachment) BlueprintStringData(com.demod.fbsr.BlueprintStringData) IOException(java.io.IOException) Blueprint(com.demod.fbsr.Blueprint)

Example 3 with Attachment

use of net.dv8tion.jda.api.entities.Message.Attachment in project Factorio-FBSR by demodude4u.

the class BlueprintBotDiscordService method handleBlueprintTotalsCommand.

private void handleBlueprintTotalsCommand(SlashCommandEvent event) {
    DataTable table;
    try {
        table = FactorioData.getTable();
    } catch (JSONException | IOException e1) {
        throw new InternalError(e1);
    }
    String content = event.getCommandString();
    Optional<Attachment> attachment = event.optParamAttachment("file");
    if (attachment.isPresent()) {
        content += " " + attachment.get().getUrl();
    }
    List<BlueprintStringData> blueprintStringDatas = BlueprintFinder.search(content, event.getReporting());
    Map<String, Double> totalItems = new LinkedHashMap<>();
    for (BlueprintStringData blueprintStringData : blueprintStringDatas) {
        for (Blueprint blueprint : blueprintStringData.getBlueprints()) {
            Map<String, Double> items = FBSR.generateSummedTotalItems(table, blueprint);
            items.forEach((k, v) -> {
                totalItems.compute(k, ($, old) -> old == null ? v : old + v);
            });
        }
    }
    if (!totalItems.isEmpty()) {
        String responseContent = totalItems.entrySet().stream().sorted((e1, e2) -> e1.getKey().compareTo(e2.getKey())).map(e -> e.getKey() + ": " + RenderUtils.fmtDouble2(e.getValue())).collect(Collectors.joining("\n"));
        String response = "```ldif\n" + responseContent + "```";
        if (response.length() < 2000) {
            event.reply(response);
        } else {
            event.replyFile(responseContent.getBytes(), "totals.txt");
        }
    } else if (blueprintStringDatas.stream().anyMatch(d -> !d.getBlueprints().isEmpty())) {
        event.replyIfNoException("I couldn't find any items!");
    } else {
        event.replyIfNoException("No blueprint found!");
    }
}
Also used : OptionType(net.dv8tion.jda.api.interactions.commands.OptionType) Arrays(java.util.Arrays) EventReply(com.demod.dcba.EventReply) URL(java.net.URL) FBSR(com.demod.fbsr.FBSR) Permission(net.dv8tion.jda.api.Permission) SlashCommandHandler(com.demod.dcba.SlashCommandHandler) Field(net.dv8tion.jda.api.entities.MessageEmbed.Field) TextChannel(net.dv8tion.jda.api.entities.TextChannel) DataTable(com.demod.factorio.DataTable) RenderUtils(com.demod.fbsr.RenderUtils) JSONException(org.json.JSONException) Matcher(java.util.regex.Matcher) JSONObject(org.json.JSONObject) Map(java.util.Map) ZipEntry(java.util.zip.ZipEntry) WebUtils(com.demod.fbsr.WebUtils) Message(net.dv8tion.jda.api.entities.Message) BufferedImage(java.awt.image.BufferedImage) DataPrototype(com.demod.factorio.prototype.DataPrototype) LevenshteinDistance(org.apache.commons.text.similarity.LevenshteinDistance) Collectors(java.util.stream.Collectors) Config(com.demod.factorio.Config) BlueprintEntity(com.demod.fbsr.BlueprintEntity) List(java.util.List) FactorioData(com.demod.factorio.FactorioData) MessageCommandEvent(com.demod.dcba.MessageCommandEvent) Entry(java.util.Map.Entry) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) BlueprintStringData(com.demod.fbsr.BlueprintStringData) ZipOutputStream(java.util.zip.ZipOutputStream) Blueprint(com.demod.fbsr.Blueprint) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HashMap(java.util.HashMap) Function(java.util.function.Function) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) WatchdogReporter(com.demod.fbsr.app.WatchdogService.WatchdogReporter) ImmutableList(com.google.common.collect.ImmutableList) AbstractIdleService(com.google.common.util.concurrent.AbstractIdleService) SlashCommandEvent(com.demod.dcba.SlashCommandEvent) SimpleEntry(java.util.AbstractMap.SimpleEntry) Attachment(net.dv8tion.jda.api.entities.Message.Attachment) MapVersion(com.demod.fbsr.MapVersion) OptionData(net.dv8tion.jda.api.interactions.commands.build.OptionData) CommandReporting(com.demod.dcba.CommandReporting) DCBA(com.demod.dcba.DCBA) IOException(java.io.IOException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Utils(com.demod.factorio.Utils) DiscordBot(com.demod.dcba.DiscordBot) LuaValue(org.luaj.vm2.LuaValue) AutoCompleteHandler(com.demod.dcba.AutoCompleteHandler) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) ArrayDeque(java.util.ArrayDeque) BlueprintFinder(com.demod.fbsr.BlueprintFinder) ChunkingFilter(net.dv8tion.jda.api.utils.ChunkingFilter) JSONArray(org.json.JSONArray) DataTable(com.demod.factorio.DataTable) Blueprint(com.demod.fbsr.Blueprint) JSONException(org.json.JSONException) Attachment(net.dv8tion.jda.api.entities.Message.Attachment) BlueprintStringData(com.demod.fbsr.BlueprintStringData) IOException(java.io.IOException) LinkedHashMap(java.util.LinkedHashMap)

Example 4 with Attachment

use of net.dv8tion.jda.api.entities.Message.Attachment in project Factorio-FBSR by demodude4u.

the class BlueprintBotDiscordService method handleBlueprintBookExtractCommand.

private void handleBlueprintBookExtractCommand(SlashCommandEvent event) {
    String content = event.getCommandString();
    Optional<Attachment> attachment = event.optParamAttachment("file");
    if (attachment.isPresent()) {
        content += " " + attachment.get().getUrl();
    }
    List<BlueprintStringData> blueprintStringDatas = BlueprintFinder.search(content, event.getReporting());
    List<Blueprint> blueprints = blueprintStringDatas.stream().flatMap(bs -> bs.getBlueprints().stream()).collect(Collectors.toList());
    List<Entry<String, String>> links = new ArrayList<>();
    for (Blueprint blueprint : blueprints) {
        try {
            blueprint.json().remove("index");
            String url = WebUtils.uploadToHostingService("blueprint.txt", BlueprintStringData.encode(blueprint.json()).getBytes());
            links.add(new SimpleEntry<>(url, blueprint.getLabel().orElse(null)));
        } catch (Exception e) {
            event.getReporting().addException(e);
        }
    }
    List<EmbedBuilder> embedBuilders = new ArrayList<>();
    if (!links.isEmpty()) {
        ArrayDeque<String> lines = links.stream().map(p -> (p.getValue() != null && !p.getValue().isEmpty()) ? ("[" + p.getValue() + "](" + p.getKey() + ")") : p.getKey()).collect(Collectors.toCollection(ArrayDeque::new));
        while (!lines.isEmpty()) {
            EmbedBuilder builder = new EmbedBuilder();
            StringBuilder description = new StringBuilder();
            while (!lines.isEmpty()) {
                if (description.length() + lines.peek().length() + 1 < MessageEmbed.DESCRIPTION_MAX_LENGTH) {
                    description.append(lines.pop()).append('\n');
                } else {
                    break;
                }
            }
            builder.setDescription(description);
            embedBuilders.add(builder);
        }
    } else {
        embedBuilders.add(new EmbedBuilder().setDescription("Blueprint not found!"));
    }
    List<MessageEmbed> embeds = embedBuilders.stream().map(EmbedBuilder::build).collect(Collectors.toList());
    for (MessageEmbed embed : embeds) {
        event.replyEmbed(embed);
    }
}
Also used : OptionType(net.dv8tion.jda.api.interactions.commands.OptionType) Arrays(java.util.Arrays) EventReply(com.demod.dcba.EventReply) URL(java.net.URL) FBSR(com.demod.fbsr.FBSR) Permission(net.dv8tion.jda.api.Permission) SlashCommandHandler(com.demod.dcba.SlashCommandHandler) Field(net.dv8tion.jda.api.entities.MessageEmbed.Field) TextChannel(net.dv8tion.jda.api.entities.TextChannel) DataTable(com.demod.factorio.DataTable) RenderUtils(com.demod.fbsr.RenderUtils) JSONException(org.json.JSONException) Matcher(java.util.regex.Matcher) JSONObject(org.json.JSONObject) Map(java.util.Map) ZipEntry(java.util.zip.ZipEntry) WebUtils(com.demod.fbsr.WebUtils) Message(net.dv8tion.jda.api.entities.Message) BufferedImage(java.awt.image.BufferedImage) DataPrototype(com.demod.factorio.prototype.DataPrototype) LevenshteinDistance(org.apache.commons.text.similarity.LevenshteinDistance) Collectors(java.util.stream.Collectors) Config(com.demod.factorio.Config) BlueprintEntity(com.demod.fbsr.BlueprintEntity) List(java.util.List) FactorioData(com.demod.factorio.FactorioData) MessageCommandEvent(com.demod.dcba.MessageCommandEvent) Entry(java.util.Map.Entry) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) BlueprintStringData(com.demod.fbsr.BlueprintStringData) ZipOutputStream(java.util.zip.ZipOutputStream) Blueprint(com.demod.fbsr.Blueprint) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HashMap(java.util.HashMap) Function(java.util.function.Function) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) WatchdogReporter(com.demod.fbsr.app.WatchdogService.WatchdogReporter) ImmutableList(com.google.common.collect.ImmutableList) AbstractIdleService(com.google.common.util.concurrent.AbstractIdleService) SlashCommandEvent(com.demod.dcba.SlashCommandEvent) SimpleEntry(java.util.AbstractMap.SimpleEntry) Attachment(net.dv8tion.jda.api.entities.Message.Attachment) MapVersion(com.demod.fbsr.MapVersion) OptionData(net.dv8tion.jda.api.interactions.commands.build.OptionData) CommandReporting(com.demod.dcba.CommandReporting) DCBA(com.demod.dcba.DCBA) IOException(java.io.IOException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Utils(com.demod.factorio.Utils) DiscordBot(com.demod.dcba.DiscordBot) LuaValue(org.luaj.vm2.LuaValue) AutoCompleteHandler(com.demod.dcba.AutoCompleteHandler) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) ArrayDeque(java.util.ArrayDeque) BlueprintFinder(com.demod.fbsr.BlueprintFinder) ChunkingFilter(net.dv8tion.jda.api.utils.ChunkingFilter) JSONArray(org.json.JSONArray) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) Blueprint(com.demod.fbsr.Blueprint) ArrayList(java.util.ArrayList) Attachment(net.dv8tion.jda.api.entities.Message.Attachment) BlueprintStringData(com.demod.fbsr.BlueprintStringData) JSONException(org.json.JSONException) IOException(java.io.IOException) ZipEntry(java.util.zip.ZipEntry) Entry(java.util.Map.Entry) SimpleEntry(java.util.AbstractMap.SimpleEntry) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder)

Example 5 with Attachment

use of net.dv8tion.jda.api.entities.Message.Attachment in project SkyBot by duncte123.

the class ImageCommandBase method tryGetAttachment.

@Nullable
private String tryGetAttachment(CommandContext ctx) {
    final Attachment attachment = ctx.getMessage().getAttachments().get(0);
    final File file = new File(attachment.getFileName());
    String mimetype = null;
    try {
        mimetype = Files.probeContentType(file.toPath());
    } catch (IOException e) {
        e.printStackTrace();
    }
    // if (mimetype == null || !mimetype.split("/")[0].equals("image")) {
    if (mimetype == null || !mimetype.startsWith("image/")) {
        sendMsg(ctx, "That file does not look like an image");
        return null;
    }
    return attachment.getUrl();
}
Also used : Attachment(net.dv8tion.jda.api.entities.Message.Attachment) IOException(java.io.IOException) File(java.io.File) Nullable(javax.annotation.Nullable)

Aggregations

Attachment (net.dv8tion.jda.api.entities.Message.Attachment)17 IOException (java.io.IOException)14 Message (net.dv8tion.jda.api.entities.Message)13 TextChannel (net.dv8tion.jda.api.entities.TextChannel)12 ArrayList (java.util.ArrayList)11 List (java.util.List)11 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)11 Permission (net.dv8tion.jda.api.Permission)11 Blueprint (com.demod.fbsr.Blueprint)10 ByteArrayOutputStream (java.io.ByteArrayOutputStream)10 AutoCompleteHandler (com.demod.dcba.AutoCompleteHandler)9 CommandReporting (com.demod.dcba.CommandReporting)9 DCBA (com.demod.dcba.DCBA)9 DiscordBot (com.demod.dcba.DiscordBot)9 EventReply (com.demod.dcba.EventReply)9 MessageCommandEvent (com.demod.dcba.MessageCommandEvent)9 SlashCommandEvent (com.demod.dcba.SlashCommandEvent)9 SlashCommandHandler (com.demod.dcba.SlashCommandHandler)9 Config (com.demod.factorio.Config)9 DataTable (com.demod.factorio.DataTable)9