use of net.dv8tion.jda.api.entities.Message.Attachment in project nc-reactor-generator by ThizThizzyDizzy.
the class Bot method onMessageReceived.
@Override
public void onMessageReceived(MessageReceivedEvent mre) {
if (mre.getAuthor().isBot())
return;
if (!botChannels.isEmpty()) {
// not a bot channel! DO NOTHING
if (!botChannels.contains(mre.getChannel().getIdLong()))
return;
}
Message message = mre.getMessage();
storeReactors(message);
String content = message.getContentStripped();
for (String prefix : prefixes) {
if (!content.startsWith(prefix))
continue;
content = content.substring(prefix.length());
content = content.toLowerCase().replace("_", "").replace("-", "").replace(":", "").replace("=", "");
while (content.contains(" ")) content = content.replace(" ", " ");
content = content.replace(" x ", "x");
// <editor-fold defaultstate="collapsed" desc="Secret">
if (content.startsWith("cookie")) {
cookies++;
config.set("cookies", cookies);
System.out.println("saving " + cookies + " cookies");
config.save();
jda.getPresence().setActivity(Activity.watching("cookies accumulate (" + cookies + ")"));
return;
}
// <editor-fold defaultstate="collapsed" desc="Help">
if (content.startsWith("help")) {
try {
message.getChannel().sendMessage(getHelpEmbed()).queue();
} catch (InsufficientPermissionException ex) {
message.getChannel().sendMessage(getHelp()).queue();
}
return;
}
// <editor-fold defaultstate="collapsed" desc="Abort">
if (content.startsWith("abort") || content.startsWith("halt") || content.startsWith("finish") || content.startsWith("stop")) {
if (content.contains("overhaul") && !content.contains("preoverhaul") && !content.contains("underhaul")) {
if (overhaul.Main.running) {
overhaul.Main.instance.stop();
message.getChannel().sendMessage("Overhaul generation halted").queue();
} else {
message.getChannel().sendMessage("Overhaul generator is not running!").queue();
}
} else {
if (underhaul.Main.running) {
underhaul.Main.instance.stop();
message.getChannel().sendMessage("Underhaul generation halted").queue();
} else {
message.getChannel().sendMessage("Underhaul generator is not running!").queue();
}
}
}
// <editor-fold defaultstate="collapsed" desc="Info">
if (content.startsWith("info")) {
for (Attachment at : message.getAttachments()) {
try {
if (at.getFileExtension().equals("json")) {
String text = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(at.retrieveInputStream().get()));
String line;
while ((line = reader.readLine()) != null) {
text += line + "\n";
}
reader.close();
JSONObject json = JSON.parse(text);
underhaul.Configuration.load(Configuration.DEFAULT);
try {
underhaul.Reactor r = underhaul.Reactor.parseJSON(json, underhaul.Fuel.get(json.getJSONObject("UsedFuel").getString("Name")));
if (r.isValid()) {
message.getChannel().sendMessage(new EmbedBuilder().setTitle("Underhaul Reactor Info").addField("Details", r.getDetails(), false).setColor(r.heat <= 0 ? Color.orange : Color.red).build()).queue();
}
} catch (Exception ex) {
}
underhaul.Configuration.load(Configuration.E2E);
try {
underhaul.Reactor r = underhaul.Reactor.parseJSON(json, underhaul.Fuel.get(json.getJSONObject("UsedFuel").getString("Name")));
if (r.isValid()) {
message.getChannel().sendMessage(new EmbedBuilder().setTitle("E2E Reactor Info").addField("Details", r.getDetails(), false).setColor(r.heat <= 0 ? Color.orange : Color.red).build()).queue();
}
} catch (Exception ex) {
}
underhaul.Configuration.load(Configuration.PO3);
try {
underhaul.Reactor r = underhaul.Reactor.parseJSON(json, underhaul.Fuel.get(json.getJSONObject("UsedFuel").getString("Name")));
if (r.isValid()) {
message.getChannel().sendMessage(new EmbedBuilder().setTitle("PO3 Reactor Info").addField("Details", r.getDetails(), false).setColor(r.heat <= 0 ? Color.orange : Color.red).build()).queue();
}
} catch (Exception ex) {
}
underhaul.Reactor r = underhaul.Reactor.parseJSON(json, new underhaul.Fuel("none", 1, 0, 1));
if (r.isValid()) {
File image = new File("info.png");
ImageIO.write(r.getImage(), "png", image);
message.getChannel().sendFile(image, "reactor.png").queue();
}
} else {
System.err.println("Unknown extention: " + at.getFileExtension());
}
} catch (Exception ex) {
}
try {
if (at.getFileExtension().equals("json")) {
String text = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(at.retrieveInputStream().get()));
String line;
while ((line = reader.readLine()) != null) {
text += line + "\n";
}
reader.close();
overhaul.Reactor r = overhaul.Reactor.parseJSON(JSON.parse(text));
if (r.isValid()) {
message.getChannel().sendMessage(new EmbedBuilder().setTitle("Overhaul Reactor Info").addField("Details", r.getDetails(), false).build()).queue();
File image = new File("info.png");
ImageIO.write(r.getImage(), "png", image);
message.getChannel().sendFile(image, "reactor.png").queue();
}
} else {
System.err.println("Unknown extention: " + at.getFileExtension());
}
} catch (Exception ex) {
}
}
}
// <editor-fold defaultstate="collapsed" desc="generate / search">
if (content.startsWith("generate") || content.startsWith("search") || content.startsWith("find")) {
boolean isGenerating = content.startsWith("generate");
if (content.contains("overhaul") && !content.contains("preoverhaul") && !content.contains("underhaul")) {
if (overhaul.Main.running) {
message.getChannel().sendMessage("Overhaul generator is already running! Use `-abort overhaul` to stop generation").queue();
return;
}
int X = 5, Y = 5, Z = 5;
for (int x = 0; x <= MAX_SIZE; x++) {
for (int y = 0; y <= MAX_SIZE; y++) {
for (int z = 0; z <= MAX_SIZE; z++) {
if (content.contains(x + "x" + y + "x" + z)) {
X = x;
Y = y;
Z = z;
}
}
}
}
overhaul.Fuel fuel = overhaul.Fuel.fuels.get(3);
boolean fuelSet = false;
for (overhaul.Fuel f : overhaul.Fuel.fuels) {
if (content.contains(f.toString().toLowerCase().replace("-", ""))) {
content = content.replace(f.toString().toLowerCase().replace("-", ""), "");
if (fuelSet) {
message.getChannel().sendMessage("Reactors with multiple fuels are not supported!").queue();
return;
}
fuel = f;
fuelSet = true;
}
}
overhaul.Fuel.Type type = overhaul.Fuel.Type.OX;
boolean typeSet = false;
for (overhaul.Fuel.Type f : overhaul.Fuel.Type.values()) {
if (content.contains(f.name().toLowerCase().replace(" ", "").replace("-", ""))) {
content = content.replace(f.name().toLowerCase().replace(" ", "").replace("-", ""), "");
if (typeSet) {
message.getChannel().sendMessage("Reactors with multiple fuels are not supported!").queue();
return;
}
type = f;
typeSet = true;
}
if (content.contains(f.toString().toLowerCase().replace("-", ""))) {
content = content.replace(f.toString().toLowerCase().replace("-", ""), "");
if (typeSet) {
message.getChannel().sendMessage("Reactors with multiple fuels are not supported!").queue();
return;
}
type = f;
typeSet = true;
}
}
overhaul.Priority.Preset pre = overhaul.Priority.presets.get(0);
for (overhaul.Priority.Preset p : overhaul.Priority.presets) {
for (String s : p.alternatives) {
if (content.contains(s.toLowerCase())) {
pre = p;
}
}
}
pre.set();
overhaulPriority = pre.name;
if (overhaul.Main.instance != null)
overhaul.Main.instance.dispose();
overhaul.Main.genModel = overhaul.GenerationModel.DEFAULT;
overhaul.Main.instance = new overhaul.Main();
ArrayList<overhaul.ReactorPart> allowedBlocks = new ArrayList<>(overhaul.ReactorPart.parts);
allowedBlocks.remove(overhaul.ReactorPart.FUEL_CELL_PO_BE);
allowedBlocks.remove(overhaul.ReactorPart.FUEL_CELL_RA_BE);
for (overhaul.ReactorPart part : overhaul.ReactorPart.parts) {
String nam = part.jsonName;
if (nam == null)
continue;
if (content.contains("no" + nam.toLowerCase()) || content.contains("no " + nam.toLowerCase())) {
allowedBlocks.remove(part);
}
}
overhaul.Main.instance.setAllowedBlocks(allowedBlocks);
overhaul.Main.instance.checkBoxSymmetryX.setSelected(content.contains("symmetr"));
overhaul.Main.instance.checkBoxSymmetryY.setSelected(content.contains("symmetr"));
overhaul.Main.instance.checkBoxSymmetryZ.setSelected(content.contains("symmetr"));
overhaul.Main.instance.spinnerX.setValue(X);
overhaul.Main.instance.spinnerY.setValue(Y);
overhaul.Main.instance.spinnerZ.setValue(Z);
overhaul.Main.instance.checkBoxFillConductors.setSelected(false);
;
overhaul.Main.instance.allowedFuels.clear();
overhaul.Main.instance.allowFuel(fuel, type);
if (!isGenerating) {
overhaul.Main.genModel = overhaul.GenerationModel.get("None");
}
overhaul.Main.instance.start();
try {
overhaulMessage = message.getChannel().sendMessage(new EmbedBuilder().setTitle((isGenerating ? "Generating " : "Searching ") + "Overhaul Reactors...").build()).complete();
} catch (InsufficientPermissionException ex) {
overhaulMessage = message.getChannel().sendMessage((isGenerating ? "Generating " : "Searching ") + "Overhaul Reactors...").complete();
}
overhaulTime = System.nanoTime();
int sx = X, sy = Y, sz = Z;
overhaul.Fuel sf = fuel;
overhaul.Fuel.Type sft = type;
Thread t = new Thread(() -> {
while (overhaul.Main.running && System.nanoTime() < overhaulTime + TIME_LIMIT) {
try {
Thread.sleep(1000);
updateOverhaul((isGenerating ? "Generating " : "Searching ") + "Overhaul Reactors...\n", true);
} catch (InterruptedException ex) {
Logger.getLogger(Bot.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (overhaul.Main.running)
overhaul.Main.instance.stop();
updateOverhaul((isGenerating ? "Generated " : "Found ") + "Overhaul Reactor", false);
File image = new File("overhaul.png");
File json = new File("overhaul.json");
overhaul.Reactor r = overhaul.Main.genPlan.getReactors().get(0);
try {
ImageIO.write(r.getImage(), "png", image);
message.getChannel().sendFile(image, "Overhaul " + sx + "x" + sy + "x" + sz + " " + sf.toString() + ".png").queue();
r.exportJSON().write(json);
message.getChannel().sendFile(json, "Overhaul " + sx + "x" + sy + "x" + sz + " " + sf.toString() + " " + sft.toString() + ".json").queue();
} catch (Exception ex) {
message.getChannel().sendMessage(ex.getClass().getName() + ": " + ex.getMessage()).queue();
ex.printStackTrace();
}
});
t.setDaemon(true);
t.start();
boolean shouldImport = true;
if (isGenerating) {
for (Attachment at : message.getAttachments()) {
shouldImport = false;
try {
if (at.getFileExtension().equals("json")) {
String text = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(at.retrieveInputStream().get()));
String line;
while ((line = reader.readLine()) != null) {
text += line + "\n";
}
reader.close();
overhaul.Reactor r = overhaul.Reactor.parse(text, X, Y, Z);
if (r == null)
throw new NullPointerException("Invalid Reactor");
final overhaul.Reactor react = r;
final Fuel feul = fuel;
final Fuel.Type typ = type;
r = new overhaul.Reactor(X, Y, Z) {
@Override
protected overhaul.ReactorPart build(int X, int Y, int Z) {
return overhaul.ReactorPart.getSelectedParts().contains(react.parts[X][Y][Z]) ? react.parts[X][Y][Z] : overhaul.ReactorPart.AIR;
}
@Override
protected Fuel.Group buildFuel(int X, int Y, int Z) {
return new Fuel.Group(feul, typ);
}
};
overhaul.Main.genPlan.importReactor(r, true);
message.getChannel().sendMessage("Imported reactor: " + at.getFileName()).queue();
} else {
System.err.println("Unknown extention: " + at.getFileExtension());
}
} catch (Exception ex) {
message.getChannel().sendMessage("Failed to parse attachment: " + at.getFileName() + "\n" + ex.getClass().getName() + ": " + ex.getMessage()).queue();
ex.printStackTrace();
}
}
}
if (shouldImport) {
System.out.println("Importing " + storedReactors.get(X).get(Y).get(Z).size() + " Reactors...");
JSONObject best = null;
int imported = 0;
for (JSONObject json : storedReactors.get(X).get(Y).get(Z)) {
imported++;
System.out.println("Importing... " + imported + "/ " + storedReactors.get(X).get(Y).get(Z).size());
try {
overhaul.Reactor r = overhaul.Reactor.parseJSON(json, X, Y, Z);
if (r == null) {
continue;
}
final overhaul.Reactor react = r;
final Fuel feul = fuel;
final Fuel.Type typ = type;
r = new overhaul.Reactor(X, Y, Z) {
@Override
protected overhaul.ReactorPart build(int X, int Y, int Z) {
return overhaul.ReactorPart.getSelectedParts().contains(react.parts[X][Y][Z]) ? react.parts[X][Y][Z] : overhaul.ReactorPart.AIR;
}
@Override
protected Fuel.Group buildFuel(int X, int Y, int Z) {
return new Fuel.Group(feul, typ);
}
};
boolean isBest = true;
for (overhaul.Reactor re : overhaul.Main.genPlan.getReactors()) {
if (overhaul.Reactor.isbetter(re, r))
isBest = false;
}
if (isBest && overhaul.Main.genPlan.importReactor(r, true))
best = json;
System.out.println("Imported Player-made Reactor!");
} catch (Exception ex) {
}
}
System.out.println("Done importing reactors");
if (best != null) {
message.getChannel().sendMessage("Found basis reactor: " + reactorLinks.get(best)).queue();
}
}
if (!isGenerating) {
overhaul.Main.instance.stop();
}
} else {
if (underhaul.Main.running) {
message.getChannel().sendMessage("Underhaul generator is already running! Use `-abort` to stop generation").queue();
return;
}
if (content.contains("e2e")) {
override = "E2E ";
underhaul.Configuration.load(underhaul.Configuration.E2E);
} else if (content.contains("po3")) {
override = "PO3 ";
underhaul.Configuration.load(underhaul.Configuration.PO3);
} else {
override = "";
underhaul.Configuration.load(underhaul.Configuration.DEFAULT);
}
int X = 3, Y = 3, Z = 3;
for (int x = 0; x <= MAX_SIZE; x++) {
for (int y = 0; y <= MAX_SIZE; y++) {
for (int z = 0; z <= MAX_SIZE; z++) {
if (content.contains(x + "x" + y + "x" + z)) {
X = x;
Y = y;
Z = z;
}
}
}
}
underhaul.Fuel fuel = underhaul.Fuel.fuels.get(7);
boolean fuelSet = false;
for (underhaul.Fuel f : underhaul.Fuel.fuels) {
if (!f.toString().contains("Oxide"))
continue;
if (content.contains(f.toString().toLowerCase().replace("-", ""))) {
content = content.replace(f.toString().toLowerCase().replace("-", ""), "");
if (fuelSet) {
message.getChannel().sendMessage("Reactors with multiple fuels are not supported!").queue();
return;
}
fuel = f;
fuelSet = true;
}
}
for (underhaul.Fuel f : underhaul.Fuel.fuels) {
if (f.toString().contains("Oxide"))
continue;
if (content.contains(f.toString().toLowerCase().replace("-", ""))) {
content = content.replace(f.toString().toLowerCase().replace("-", ""), "");
if (fuelSet) {
message.getChannel().sendMessage("Reactors with multiple fuels are not supported!").queue();
return;
}
fuel = f;
fuelSet = true;
}
}
underhaul.Priority.Preset pre = underhaul.Priority.presets.get(0);
for (underhaul.Priority.Preset p : underhaul.Priority.presets) {
for (String s : p.alternatives) {
if (content.contains(s.toLowerCase())) {
pre = p;
}
}
}
pre.set();
underhaulPriority = pre.name;
if (underhaul.Main.instance != null)
underhaul.Main.instance.dispose();
underhaul.Main.genModel = underhaul.GenerationModel.DEFAULT;
underhaul.Main.instance = new underhaul.Main();
ArrayList<underhaul.ReactorPart> allowedBlocks = new ArrayList<>(underhaul.ReactorPart.parts);
allowedBlocks.remove(underhaul.ReactorPart.BERYLLIUM);
allowedBlocks.remove(underhaul.ReactorPart.AIR);
for (underhaul.ReactorPart part : underhaul.ReactorPart.parts) {
String nam = part.jsonName;
if (nam == null)
continue;
if (content.contains("no" + nam.toLowerCase()) || content.contains("no " + nam.toLowerCase())) {
allowedBlocks.remove(part);
}
}
underhaul.Main.instance.setAllowedBlocks(allowedBlocks);
underhaul.Main.instance.checkBoxSymmetryX.setSelected(content.contains("symmetr"));
underhaul.Main.instance.checkBoxSymmetryY.setSelected(content.contains("symmetr"));
underhaul.Main.instance.checkBoxSymmetryZ.setSelected(content.contains("symmetr"));
underhaul.Main.instance.spinnerX.setValue(X);
underhaul.Main.instance.spinnerY.setValue(Y);
underhaul.Main.instance.spinnerZ.setValue(Z);
underhaul.Main.instance.boxFuel.setSelectedIndex(underhaul.Fuel.fuels.indexOf(fuel));
if (!isGenerating) {
underhaul.Main.genModel = underhaul.GenerationModel.get("None");
}
underhaul.Main.instance.start();
try {
underhaulMessage = message.getChannel().sendMessage(new EmbedBuilder().setTitle((isGenerating ? "Generating " : "Searching ") + override + "Reactors...").build()).complete();
} catch (InsufficientPermissionException ex) {
underhaulMessage = message.getChannel().sendMessage((isGenerating ? "Generating " : "Searching ") + override + "Reactors...").complete();
}
underhaulTime = System.nanoTime();
int sx = X, sy = Y, sz = Z;
underhaul.Fuel sf = fuel;
Thread t = new Thread(() -> {
while (underhaul.Main.running && System.nanoTime() < underhaulTime + TIME_LIMIT) {
try {
Thread.sleep(1000);
updateUnderhaul((isGenerating ? "Generating " : "Searching ") + override + "Reactors...\n", true);
} catch (InterruptedException ex) {
Logger.getLogger(Bot.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (underhaul.Main.running)
underhaul.Main.instance.stop();
updateUnderhaul((isGenerating ? "Generated " : "Found ") + override + "Reactor", false);
File image = new File("underhaul.png");
File json = new File("underhaul.json");
underhaul.Reactor r = underhaul.Main.genPlan.getReactors().get(0);
try {
ImageIO.write(r.getImage(), "png", image);
message.getChannel().sendFile(image, (override == null ? "Underhaul " : override) + sx + "x" + sy + "x" + sz + " " + sf.toString() + ".png").queue();
r.exportJSON().write(json);
message.getChannel().sendFile(json, (override == null ? "Underhaul " : override) + sx + "x" + sy + "x" + sz + " " + sf.toString() + ".json").queue();
} catch (Exception ex) {
message.getChannel().sendMessage(ex.getClass().getName() + ": " + ex.getMessage()).queue();
ex.printStackTrace();
}
});
t.setDaemon(true);
t.start();
boolean shouldImport = true;
if (isGenerating) {
for (Attachment at : message.getAttachments()) {
shouldImport = false;
try {
if (at.getFileExtension().equals("json")) {
String text = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(at.retrieveInputStream().get()));
String line;
while ((line = reader.readLine()) != null) {
text += line + "\n";
}
reader.close();
underhaul.Reactor r = underhaul.Reactor.parse(text, fuel, X, Y, Z);
if (r == null)
throw new NullPointerException("Invalid Reactor");
underhaul.Main.genPlan.importReactor(r, true);
message.getChannel().sendMessage("Imported reactor: " + at.getFileName()).queue();
} else {
System.err.println("Unknown extention: " + at.getFileExtension());
}
} catch (Exception ex) {
message.getChannel().sendMessage("Failed to parse attachment: " + at.getFileName() + "\n" + ex.getClass().getName() + ": " + ex.getMessage()).queue();
ex.printStackTrace();
}
}
}
if (shouldImport) {
System.out.println("Importing " + storedReactors.get(X).get(Y).get(Z).size() + " Reactors...");
JSONObject best = null;
int imported = 0;
for (JSONObject json : storedReactors.get(X).get(Y).get(Z)) {
imported++;
System.out.println("Importing... " + imported + "/ " + storedReactors.get(X).get(Y).get(Z).size());
try {
underhaul.Reactor react = underhaul.Reactor.parseJSON(json, fuel, X, Y, Z);
if (react == null) {
continue;
}
underhaul.Reactor r = new underhaul.Reactor(fuel, X, Y, Z) {
@Override
protected underhaul.ReactorPart build(int X, int Y, int Z) {
return underhaul.ReactorPart.getAvailableParts().contains(react.parts[X][Y][Z]) ? react.parts[X][Y][Z] : underhaul.ReactorPart.AIR;
}
};
boolean isBest = true;
for (underhaul.Reactor re : underhaul.Main.genPlan.getReactors()) {
if (underhaul.Reactor.isbetter(re, r))
isBest = false;
}
if (isBest && underhaul.Main.genPlan.importReactor(r, true))
best = json;
System.out.println("Imported Player-made Reactor!");
} catch (Exception ex) {
}
}
System.out.println("Done importing reactors");
if (best != null) {
message.getChannel().sendMessage("Found basis reactor: " + reactorLinks.get(best)).queue();
}
}
if (!isGenerating) {
underhaul.Main.instance.stop();
}
}
}
// </editor-fold>
break;
}
}
use of net.dv8tion.jda.api.entities.Message.Attachment in project nc-reactor-generator by ThizThizzyDizzy.
the class Bot method onReady.
@Override
public void onReady(ReadyEvent re) {
Thread channelRead = new Thread(() -> {
int bytes = 0;
int totalCount = 0;
for (Long id : dataChannels) {
TextChannel channel = jda.getTextChannelById(id);
if (channel == null) {
System.err.println("Invalid channel: " + id);
continue;
}
System.out.println("Reading channel: " + channel.getName());
MessageHistory history = channel.getHistoryFromBeginning(batchSize).complete();
int count = 0;
while (true) {
Message last = null;
ArrayList<Message> messages = new ArrayList<>(history.getRetrievedHistory());
Stack<Message> stak = new Stack<>();
for (Message m : messages) {
stak.push(m);
}
messages.clear();
while (!stak.isEmpty()) messages.add(stak.pop());
for (Message message : messages) {
last = message;
storeReactors(message);
for (Attachment att : message.getAttachments()) {
if (att.getFileExtension().equalsIgnoreCase("json")) {
count++;
System.out.println("Found " + att.getFileName() + " (" + count + ")");
bytes += att.getSize();
}
}
}
if (last == null)
break;
if (history.size() < batchSize) {
break;
} else {
history = channel.getHistoryAfter(last, batchSize).complete();
}
}
System.out.println("Finished Reading channel: " + channel.getName() + ". Reactors: " + count);
totalCount += count;
}
System.out.println("Total Reactors: " + totalCount);
System.out.println("Total Size: " + bytes);
});
channelRead.setDaemon(true);
channelRead.start();
}
use of net.dv8tion.jda.api.entities.Message.Attachment in project Sx4 by sx4-discord-bot.
the class StarboardHandler method onGuildMessageReactionAdd.
public void onGuildMessageReactionAdd(GuildMessageReactionAddEvent event) {
if (event.getUser().isBot()) {
return;
}
List<Bson> starboardPipeline = List.of(Aggregates.match(Filters.or(Filters.eq("originalMessageId", event.getMessageIdLong()), Filters.eq("messageId", event.getMessageIdLong()))), Aggregates.project(Projections.include("originalMessageId", "channelId")));
List<Bson> pipeline = List.of(Aggregates.match(Filters.eq("_id", event.getGuild().getIdLong())), Aggregates.project(Projections.fields(Projections.include("starboard"), Projections.computed("premium", Operators.lt(Operators.nowEpochSecond(), Operators.ifNull("$premium.endAt", 0L))))), Aggregates.unionWith("starboards", starboardPipeline), Aggregates.group(null, Accumulators.max("messageId", "$originalMessageId"), Accumulators.max("channelId", "$channelId"), Accumulators.max("starboard", "$starboard"), Accumulators.max("premium", "$premium")));
this.bot.getMongo().aggregateGuilds(pipeline).whenComplete((documents, aggregateException) -> {
if (ExceptionUtility.sendErrorMessage(aggregateException)) {
return;
}
if (documents.isEmpty()) {
return;
}
Document data = documents.get(0);
Document starboard = data.get("starboard", MongoDatabase.EMPTY_DOCUMENT);
if (!starboard.get("enabled", false)) {
return;
}
long channelId = starboard.get("channelId", 0L), messageChannelId = data.get("channelId", 0L);
TextChannel messageChannel = messageChannelId == 0L ? event.getChannel() : event.getGuild().getTextChannelById(messageChannelId);
TextChannel channel = channelId == 0L ? null : event.getGuild().getTextChannelById(channelId);
if (channel == null || messageChannel == null) {
return;
}
ReactionEmote emote = event.getReactionEmote();
boolean emoji = emote.isEmoji();
Document emoteData = starboard.get("emote", new Document("name", "⭐"));
if ((emoji && !emote.getEmoji().equals(emoteData.getString("name"))) || (!emoji && (!emoteData.containsKey("id") || emoteData.getLong("id") != emote.getIdLong()))) {
return;
}
Long originalMessageId = data.getLong("messageId");
long messageId = originalMessageId == null ? event.getMessageIdLong() : originalMessageId;
messageChannel.retrieveMessageById(messageId).queue(message -> {
String image = message.getAttachments().stream().filter(Attachment::isImage).map(Attachment::getUrl).findFirst().orElse(null);
Document star = new Document("userId", event.getUser().getIdLong()).append("messageId", messageId).append("guildId", event.getGuild().getIdLong());
this.bot.getMongo().insertStar(star).thenCompose(result -> {
Bson update = Updates.combine(Updates.inc("count", 1), Updates.setOnInsert("originalMessageId", messageId), Updates.setOnInsert("guildId", event.getGuild().getIdLong()), Updates.setOnInsert("channelId", event.getChannel().getIdLong()), Updates.set("content", message.getContentRaw()), Updates.set("authorId", message.getAuthor().getIdLong()));
if (image != null) {
update = Updates.combine(update, Updates.set("image", image));
}
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER).upsert(true);
return this.bot.getMongo().findAndUpdateStarboard(Filters.eq("originalMessageId", messageId), update, options);
}).thenCompose(updatedData -> {
WebhookMessage webhookMessage = this.getStarboardMessage(starboard, updatedData, event.getGuild(), event.getMember(), emote, data.getBoolean("premium"));
if (webhookMessage == null) {
return CompletableFuture.completedFuture(null);
}
if (updatedData.containsKey("messageId")) {
this.bot.getStarboardManager().editStarboard(updatedData.getLong("messageId"), channel.getIdLong(), starboard.get("webhook", MongoDatabase.EMPTY_DOCUMENT), webhookMessage);
// return null so no update is made in the next stage
return CompletableFuture.completedFuture(null);
} else {
return this.bot.getStarboardManager().sendStarboard(channel, starboard.get("webhook", MongoDatabase.EMPTY_DOCUMENT), webhookMessage);
}
}).whenComplete((createdMessage, exception) -> {
if (exception instanceof CompletionException) {
Throwable cause = exception.getCause();
if (cause instanceof MongoWriteException && ((MongoWriteException) cause).getError().getCategory() == ErrorCategory.DUPLICATE_KEY) {
// duplicate star just ignore
return;
}
}
if (ExceptionUtility.sendErrorMessage(exception)) {
return;
}
if (createdMessage != null) {
Route.CompiledRoute route = Route.Messages.ADD_REACTION.compile(Long.toString(createdMessage.getChannelId()), Long.toString(createdMessage.getId()), EncodingUtil.encodeReaction(emote.getAsReactionCode()), "@me");
new RestActionImpl<>(event.getJDA(), route).queue(null, ErrorResponseException.ignore(ErrorResponse.UNKNOWN_EMOJI, ErrorResponse.MISSING_PERMISSIONS, ErrorResponse.MISSING_ACCESS));
this.bot.getMongo().updateStarboard(Filters.eq("originalMessageId", messageId), Updates.set("messageId", createdMessage.getId())).whenComplete(MongoDatabase.exceptionally());
}
});
});
});
}
use of net.dv8tion.jda.api.entities.Message.Attachment in project Sx4 by sx4-discord-bot.
the class MediaModeHandler method handle.
public void handle(Message message) {
if (message.getAuthor().isBot() || message.getMember().hasPermission(Permission.ADMINISTRATOR)) {
return;
}
TextChannel channel = message.getTextChannel();
this.bot.getExecutor().submit(() -> {
Document media = this.bot.getMongo().getMediaChannel(Filters.eq("channelId", channel.getIdLong()), Projections.include("types"));
if (media == null) {
return;
}
EnumSet<MediaType> types = MediaType.getMediaTypes(media.get("types", MediaType.ALL));
Attachment attachment = message.getAttachments().stream().filter(file -> types.stream().anyMatch(type -> type.getExtension().equalsIgnoreCase(this.getMimeType(file.getContentType())))).findFirst().orElse(null);
if (attachment == null && message.getGuild().getSelfMember().hasPermission(channel, Permission.MESSAGE_MANAGE)) {
message.delete().queue();
}
});
}
use of net.dv8tion.jda.api.entities.Message.Attachment in project SkyBot by DuncteBot.
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();
}
Aggregations