use of net.dv8tion.jda.api.entities.MessageEmbed.Field in project nc-reactor-generator by ThizThizzyDizzy.
the class Bot method getHelp.
private String getHelp() {
MessageEmbed embed = getHelpEmbed();
String text = "__**" + embed.getTitle() + "**__";
for (Field f : embed.getFields()) {
text += "\n> **" + f.getName() + "**\n" + f.getValue();
}
text += "\n> *" + embed.getFooter() + "*";
return text;
}
use of net.dv8tion.jda.api.entities.MessageEmbed.Field 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;
}
use of net.dv8tion.jda.api.entities.MessageEmbed.Field in project Factorio-FBSR by demodude4u.
the class BlueprintBotDiscordService method processBlueprints.
private List<EmbedBuilder> processBlueprints(List<BlueprintStringData> blueprintStrings, CommandReporting reporting, JSONObject options) throws IOException {
List<EmbedBuilder> embedBuilders = new ArrayList<>();
List<Entry<Optional<String>, BufferedImage>> images = new ArrayList<>();
for (BlueprintStringData blueprintString : blueprintStrings) {
System.out.println("Parsing blueprints: " + blueprintString.getBlueprints().size());
for (Blueprint blueprint : blueprintString.getBlueprints()) {
try {
BufferedImage image = FBSR.renderBlueprint(blueprint, reporting, options);
images.add(new SimpleEntry<>(blueprint.getLabel(), image));
} catch (Exception e) {
reporting.addException(e);
}
}
}
List<Long> renderTimes = blueprintStrings.stream().flatMap(d -> d.getBlueprints().stream()).flatMap(b -> (b.getRenderTime().isPresent() ? Arrays.asList(b.getRenderTime().getAsLong()) : ImmutableList.<Long>of()).stream()).collect(Collectors.toList());
if (!renderTimes.isEmpty()) {
reporting.addField(new Field("Render Time", renderTimes.stream().mapToLong(l -> l).sum() + " ms" + (renderTimes.size() > 1 ? (" [" + renderTimes.stream().map(Object::toString).collect(Collectors.joining(", ")) + "]") : ""), true));
}
if (images.size() == 0) {
embedBuilders.add(new EmbedBuilder().setDescription("Blueprint not found!"));
} else if (images.size() == 1) {
Entry<Optional<String>, BufferedImage> entry = images.get(0);
BufferedImage image = entry.getValue();
String url = WebUtils.uploadToHostingService("blueprint.png", image);
EmbedBuilder builder = new EmbedBuilder();
builder.setImage(url);
embedBuilders.add(builder);
} else {
List<Entry<String, String>> links = new ArrayList<>();
for (Entry<Optional<String>, BufferedImage> entry : images) {
BufferedImage image = entry.getValue();
links.add(new SimpleEntry<>(WebUtils.uploadToHostingService("blueprint.png", image), entry.getKey().orElse("")));
}
ArrayDeque<String> lines = new ArrayDeque<>();
for (int i = 0; i < links.size(); i++) {
Entry<String, String> entry = links.get(i);
if (entry.getValue() != null && !entry.getValue().trim().isEmpty()) {
lines.add("[" + entry.getValue().trim() + "](" + entry.getKey() + ")");
} else {
lines.add("[Blueprint Image " + (i + 1) + "](" + entry.getKey() + ")");
}
}
while (!lines.isEmpty()) {
EmbedBuilder builder = new EmbedBuilder();
for (int i = 0; i < 3 && !lines.isEmpty(); i++) {
StringBuilder description = new StringBuilder();
while (!lines.isEmpty()) {
if (description.length() + lines.peek().length() + 1 < MessageEmbed.VALUE_MAX_LENGTH) {
description.append(lines.pop()).append('\n');
} else {
break;
}
}
builder.addField("", description.toString(), true);
}
embedBuilders.add(builder);
}
}
if (!blueprintStrings.isEmpty() && !embedBuilders.isEmpty()) {
List<String> links = new ArrayList<>();
for (int i = 0; i < blueprintStrings.size(); i++) {
BlueprintStringData blueprintString = blueprintStrings.get(i);
String label = blueprintString.getLabel().orElse((blueprintString.getBlueprints().size() > 1 ? "Blueprint Book " : "Blueprint ") + (i + 1));
String link = WebUtils.uploadToHostingService("blueprint.txt", blueprintString.toString().getBytes());
links.add("[" + label + "](" + link + ")");
}
embedBuilders.get(0).getFields().add(0, new Field("Blueprint String" + (blueprintStrings.size() > 1 ? "s" : ""), links.stream().collect(Collectors.joining("\n")), false));
}
return embedBuilders;
}
use of net.dv8tion.jda.api.entities.MessageEmbed.Field in project Factorio-FBSR by demodude4u.
the class WebAPIService method startUp.
@Override
protected void startUp() {
ServiceFinder.addService(this);
configJson = Config.get().getJSONObject("webapi");
String address = configJson.optString("bind", "0.0.0.0");
int port = configJson.optInt("port", 80);
On.address(address).port(port);
On.post("/blueprint").serve((req, resp) -> {
System.out.println("Web API POST!");
CommandReporting reporting = new CommandReporting("Web API / " + req.clientIpAddress() + " / " + Optional.ofNullable(req.header("User-Agent", null)).orElse("<Unknown>"), null, Instant.now());
try {
JSONObject body = null;
BufferedImage returnSingleImage = null;
List<String> infos = new ArrayList<>();
List<Entry<Optional<String>, String>> imageLinks = new ArrayList<>();
boolean useLocalStorage = configJson.optBoolean("use-local-storage", false);
try {
if (req.body() == null) {
resp.code(400);
resp.plain("Body is empty!");
reporting.addException(new IllegalArgumentException("Body is empty!"));
return resp;
}
try {
body = new JSONObject(new String(req.body()));
} catch (Exception e) {
reporting.addException(e);
resp.code(400);
resp.plain("Malformed JSON: " + e.getMessage());
return resp;
}
reporting.setCommand(body.toString(2));
/*
* { "blueprint": "0e...", (required) "max-width": 1234, "max-height": 1234,
* "show-info-panels": false } | v { "info": [ "message 1!", "message 2!", ...
* ], "images": [ { "label": "Blueprint Label", "link":
* "https://cdn.discordapp.com/..." (or) "1563569893008.png" } ] }
*/
String content = body.getString("blueprint");
List<BlueprintStringData> blueprintStrings = BlueprintFinder.search(content, reporting);
List<Blueprint> blueprints = blueprintStrings.stream().flatMap(s -> s.getBlueprints().stream()).collect(Collectors.toList());
for (Blueprint blueprint : blueprints) {
try {
BufferedImage image = FBSR.renderBlueprint(blueprint, reporting, body);
if (body.optBoolean("return-single-image")) {
returnSingleImage = image;
break;
}
if (useLocalStorage) {
File localStorageFolder = new File(configJson.getString("local-storage"));
String imageLink = saveToLocalStorage(localStorageFolder, image);
imageLinks.add(new SimpleEntry<>(blueprint.getLabel(), imageLink));
} else {
imageLinks.add(new SimpleEntry<>(blueprint.getLabel(), WebUtils.uploadToHostingService("blueprint.png", image).toString()));
}
} catch (Exception e) {
reporting.addException(e);
}
}
List<Long> renderTimes = blueprintStrings.stream().flatMap(d -> d.getBlueprints().stream()).flatMap(b -> (b.getRenderTime().isPresent() ? Arrays.asList(b.getRenderTime().getAsLong()) : ImmutableList.<Long>of()).stream()).collect(Collectors.toList());
if (!renderTimes.isEmpty()) {
reporting.addField(new Field("Render Time", renderTimes.stream().mapToLong(l -> l).sum() + " ms" + (renderTimes.size() > 1 ? (" [" + renderTimes.stream().map(Object::toString).collect(Collectors.joining(", ")) + "]") : ""), true));
}
if (blueprintStrings.stream().anyMatch(d -> d.getBlueprints().stream().anyMatch(b -> b.isModsDetected()))) {
infos.add("(Modded features are shown as question marks)");
}
} catch (Exception e) {
reporting.addException(e);
}
if (returnSingleImage != null) {
resp.contentType(MediaType.IMAGE_PNG);
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
ImageIO.write(returnSingleImage, "PNG", baos);
baos.flush();
resp.body(baos.toByteArray());
}
return resp;
} else {
JSONObject result = new JSONObject();
Utils.terribleHackToHaveOrderedJSONObject(result);
if (!reporting.getExceptions().isEmpty()) {
resp.code(400);
infos.add("There was a problem completing your request.");
reporting.getExceptions().forEach(Exception::printStackTrace);
}
if (!infos.isEmpty()) {
result.put("info", new JSONArray(infos));
}
if (imageLinks.size() == 1 && !useLocalStorage) {
reporting.setImageURL(imageLinks.get(0).getValue());
}
if (!imageLinks.isEmpty()) {
JSONArray images = new JSONArray();
for (Entry<Optional<String>, String> pair : imageLinks) {
JSONObject image = new JSONObject();
Utils.terribleHackToHaveOrderedJSONObject(image);
pair.getKey().ifPresent(l -> image.put("label", l));
image.put("link", pair.getValue());
images.put(image);
}
result.put("images", images);
}
resp.contentType(MediaType.JSON);
String responseBody = result.toString(2);
resp.body(responseBody.getBytes());
reporting.addField(new Field("Response", responseBody, false));
return resp;
}
} finally {
ServiceFinder.findService(BlueprintBotDiscordService.class).ifPresent(s -> s.getBot().submitReport(reporting));
}
});
System.out.println("Web API Initialized at " + address + ":" + port);
}
use of net.dv8tion.jda.api.entities.MessageEmbed.Field in project Factorio-FBSR by demodude4u.
the class BlueprintBotRedditService method processContent.
private List<String> processContent(String content, String link, String category, String author, Optional<WatchdogService> watchdog) {
String contentLowerCase = content.toLowerCase();
if (!contentLowerCase.contains(summonKeyword) && !contentLowerCase.contains(myUserNameMention)) {
return ImmutableList.of();
}
CommandReporting reporting = new CommandReporting("Reddit / " + category + " / " + author, REDDIT_AUTHOR_URL, Instant.now());
reporting.setCommand(content);
List<String> infos = new ArrayList<>();
List<Entry<Optional<String>, String>> imageLinks = new ArrayList<>();
try {
List<BlueprintStringData> blueprintStrings = BlueprintFinder.search(content, reporting);
List<Blueprint> blueprints = blueprintStrings.stream().flatMap(s -> s.getBlueprints().stream()).collect(Collectors.toList());
for (Blueprint blueprint : blueprints) {
watchdog.ifPresent(w -> w.notifyActive(WATCHDOG_LABEL));
try {
BufferedImage image = FBSR.renderBlueprint(blueprint, reporting);
imageLinks.add(new SimpleEntry<>(blueprint.getLabel(), WebUtils.uploadToHostingService("blueprint.png", image).toString()));
} catch (Exception e) {
reporting.addException(e);
}
}
List<Long> renderTimes = blueprintStrings.stream().flatMap(d -> d.getBlueprints().stream()).flatMap(b -> (b.getRenderTime().isPresent() ? Arrays.asList(b.getRenderTime().getAsLong()) : ImmutableList.<Long>of()).stream()).collect(Collectors.toList());
if (!renderTimes.isEmpty()) {
reporting.addField(new Field("Render Time", renderTimes.stream().mapToLong(l -> l).sum() + " ms" + (renderTimes.size() > 1 ? (" [" + renderTimes.stream().map(Object::toString).collect(Collectors.joining(", ")) + "]") : ""), true));
}
if (blueprintStrings.stream().anyMatch(d -> d.getBlueprints().stream().anyMatch(b -> b.isModsDetected()))) {
infos.add("(Modded features are shown as question marks)");
}
} catch (Exception e) {
reporting.addException(e);
}
List<String> lines = new ArrayList<>();
if (imageLinks.size() > 1) {
int id = 1;
List<Entry<URL, String>> links = new ArrayList<>();
for (Entry<Optional<String>, String> pair : imageLinks) {
Optional<String> label = pair.getKey();
String url = pair.getValue();
try {
links.add(new SimpleEntry<>(new URL(url), label.orElse(null)));
} catch (MalformedURLException e) {
reporting.addException(e);
}
}
lines.add("Blueprint Images:");
for (Entry<Optional<String>, String> pair : imageLinks) {
Optional<String> label = pair.getKey();
String url = pair.getValue();
lines.add("[" + (id++) + ": " + label.orElse("Blueprint") + "](" + url + ")");
}
} else if (!imageLinks.isEmpty()) {
Entry<Optional<String>, String> pair = imageLinks.get(0);
Optional<String> label = pair.getKey();
String url = pair.getValue();
lines.add("[Blueprint Image" + label.map(s -> " (" + s + ")").orElse("") + "](" + url + ")");
reporting.setImageURL(url);
}
for (String info : infos) {
lines.add(" " + info);
}
if (!reporting.getExceptions().isEmpty()) {
lines.add(" Sorry, There was a problem completing your request.");
}
ServiceFinder.findService(BlueprintBotDiscordService.class).ifPresent(s -> s.getBot().submitReport(reporting));
if (!lines.isEmpty()) {
List<String> res = new ArrayList<>();
String message = "";
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i) + "\n\n";
if (message.length() + line.length() < 10000) {
message += line;
} else {
res.add(message);
message = "Blueprint Images (Continued):\n\n";
}
}
res.add(message);
return res;
} else {
return ImmutableList.of();
}
}
Aggregations