use of com.sx4.bot.formatter.Formatter in project Sx4 by sx4-discord-bot.
the class FormatterCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "arguments", nullDefault = true) String content) {
FormatterManager manager = FormatterManager.getDefaultManager();
String[] arguments = content == null ? new String[0] : content.split("\\.");
Set<Class<?>> functionClasses = manager.getFunctions().keySet();
Set<Class<?>> variableClasses = manager.getVariables().keySet();
Set<Class<?>> classes = new HashSet<>();
classes.addAll(functionClasses);
classes.addAll(variableClasses);
List<Class<?>> filteredClasses = classes.stream().filter(clazz -> arguments.length == 0 || arguments[0].equalsIgnoreCase(clazz.getSimpleName())).collect(Collectors.toList());
if (filteredClasses.isEmpty()) {
event.replyFailure("I could not find that formatter type").queue();
return;
}
PagedResult<Class<?>> paged = new PagedResult<>(event.getBot(), filteredClasses).setPerPage(15).setAutoSelect(true).setDisplayFunction(Class::getSimpleName);
paged.onSelect(select -> {
Class<?> clazz = select.getSelected();
for (int i = 1; i < arguments.length; i++) {
String name = arguments[i];
FormatterFunction<?> function = manager.getFunctions(clazz).stream().filter(f -> f.getName().equalsIgnoreCase(name)).findFirst().orElse(null);
FormatterVariable<?> variable = manager.getVariables(clazz).stream().filter(v -> v.getName().equalsIgnoreCase(name)).findFirst().orElse(null);
boolean last = i == arguments.length - 1;
MessageEmbed embed;
if (function != null) {
Method method = function.getMethod();
if (!last) {
clazz = method.getReturnType();
continue;
}
embed = new EmbedBuilder().setDescription(function.getDescription()).setTitle(this.getFunctionString(function)).addField("Return Type", method.getReturnType().getSimpleName(), true).build();
} else if (variable != null) {
Class<?> returnType = variable.getReturnType();
if (!last) {
clazz = returnType;
continue;
}
embed = new EmbedBuilder().setDescription(variable.getDescription()).setTitle(variable.getName()).addField("Return Type", returnType.getSimpleName(), true).build();
} else {
event.replyFailure("I could not find a variable or function named `" + name + "` on the type `" + clazz.getSimpleName() + "`").queue();
return;
}
event.reply(embed).queue();
return;
}
String variables = manager.getVariables(clazz).stream().map(FormatterVariable::getName).collect(Collectors.joining("\n"));
String functions = manager.getFunctions(clazz).stream().map(this::getFunctionString).collect(Collectors.joining("\n"));
EmbedBuilder embed = new EmbedBuilder().setTitle(clazz.getSimpleName()).addField("Functions", functions.isEmpty() ? "None" : functions, true).addField("Variables", variables.isEmpty() ? "None" : variables, true);
event.reply(embed.build()).queue();
});
paged.execute(event);
}
use of com.sx4.bot.formatter.Formatter in project Sx4 by sx4-discord-bot.
the class FreeGameManager method sendFreeGameNotifications.
public CompletableFuture<List<ReadonlyMessage>> sendFreeGameNotifications(List<? extends FreeGame<?>> games) {
games.forEach(this::addAnnouncedGame);
List<Document> gameData = games.stream().map(FreeGame::toData).collect(Collectors.toList());
if (!gameData.isEmpty()) {
this.bot.getMongo().insertManyAnnouncedGames(gameData).whenComplete(MongoDatabase.exceptionally());
}
List<Bson> guildPipeline = List.of(Aggregates.match(Operators.expr(Operators.eq("$_id", "$$guildId"))), Aggregates.project(Projections.computed("premium", Operators.lt(Operators.nowEpochSecond(), Operators.ifNull("$premium.endAt", 0L)))));
List<Bson> pipeline = List.of(Aggregates.lookup("guilds", List.of(new Variable<>("guildId", "$guildId")), guildPipeline, "premium"), Aggregates.addFields(new Field<>("premium", Operators.cond(Operators.isEmpty("$premium"), false, Operators.get(Operators.arrayElemAt("$premium", 0), "premium")))));
return this.bot.getMongo().aggregateFreeGameChannels(pipeline).thenComposeAsync(documents -> {
List<WriteModel<Document>> bulkData = new ArrayList<>();
List<CompletableFuture<List<ReadonlyMessage>>> futures = new ArrayList<>();
for (Document data : documents) {
if (!data.getBoolean("enabled", true)) {
continue;
}
TextChannel channel = this.bot.getShardManager().getTextChannelById(data.getLong("channelId"));
if (channel == null) {
continue;
}
String avatar = channel.getJDA().getSelfUser().getEffectiveAvatarUrl();
boolean premium = data.getBoolean("premium");
Document webhookData = data.get("webhook", MongoDatabase.EMPTY_DOCUMENT);
long platforms = data.get("platforms", FreeGameType.ALL);
List<WebhookMessage> messages = new ArrayList<>();
for (FreeGame<?> game : games) {
long raw = game.getType().getRaw();
if ((platforms & raw) != raw) {
continue;
}
Formatter<Document> formatter = new JsonFormatter(data.get("message", FreeGameManager.DEFAULT_MESSAGE)).addVariable("game", game);
WebhookMessage message;
try {
message = MessageUtility.fromJson(formatter.parse()).setAvatarUrl(premium ? webhookData.get("avatar", avatar) : avatar).setUsername(premium ? webhookData.get("name", "Sx4 - Free Games") : "Sx4 - Free Games").build();
} catch (IllegalArgumentException e) {
bulkData.add(new UpdateOneModel<>(Filters.eq("_id", data.getObjectId("_id")), Updates.unset("message")));
continue;
}
messages.add(message);
}
if (!messages.isEmpty()) {
futures.add(this.sendFreeGameNotificationMessages(channel, webhookData, messages));
}
}
if (!bulkData.isEmpty()) {
this.bot.getMongo().bulkWriteFreeGameChannels(bulkData).whenComplete(MongoDatabase.exceptionally());
}
return FutureUtility.allOf(futures).thenApply(list -> list.stream().flatMap(List::stream).collect(Collectors.toList()));
});
}
use of com.sx4.bot.formatter.Formatter in project Sx4 by sx4-discord-bot.
the class LeaverUtility method getLeaverMessage.
public static WebhookMessageBuilder getLeaverMessage(Document messageData, Member member) {
Guild guild = member.getGuild();
User user = member.getUser();
OffsetDateTime now = OffsetDateTime.now();
Formatter<Document> formatter = new JsonFormatter(messageData).member(member).user(user).guild(guild).addVariable(Member.class, "age", LeaverUtility.FORMATTER.parse(Duration.between(member.getTimeJoined(), now).toSeconds())).addVariable(User.class, "age", LeaverUtility.FORMATTER.parse(Duration.between(user.getTimeCreated(), now).toSeconds())).addVariable("now", now);
return MessageUtility.fromJson(formatter.parse());
}
use of com.sx4.bot.formatter.Formatter in project Sx4 by sx4-discord-bot.
the class FreeGamesCommand method preview.
@Command(value = "preview", description = "Preview your free game notification message")
@CommandId(481)
@Examples({ "free games preview" })
public void preview(Sx4CommandEvent event) {
Document data = event.getMongo().getFreeGameChannel(Filters.eq("guildId", event.getGuild().getIdLong()), Projections.include("message"));
if (data == null) {
event.replyFailure("You don't have a free game channel setup").queue();
return;
}
FreeGameUtility.retrieveFreeGames(event.getHttpClient(), freeGames -> {
Formatter<Document> formatter = new JsonFormatter(data.get("message", FreeGameManager.DEFAULT_MESSAGE)).addVariable("game", freeGames.get(0));
MessageUtility.fromWebhookMessage(event.getChannel(), MessageUtility.fromJson(formatter.parse()).build()).queue();
});
}
use of com.sx4.bot.formatter.Formatter in project Sx4 by sx4-discord-bot.
the class WelcomerUtility method getWelcomerMessage.
public static void getWelcomerMessage(OkHttpClient httpClient, Document messageData, String bannerId, Member member, boolean canary, boolean image, boolean gif, BiConsumer<WebhookMessageBuilder, Throwable> consumer) {
Guild guild = member.getGuild();
User user = member.getUser();
OffsetDateTime now = OffsetDateTime.now();
Formatter<Document> formatter = new JsonFormatter(messageData).member(member).user(user).guild(guild).addVariable(User.class, "age", TimeUtility.LONG_TIME_FORMATTER.parse(Duration.between(user.getTimeCreated(), now).toSeconds())).addVariable("now", now);
if (!image) {
WebhookMessageBuilder builder;
if (messageData != null) {
try {
builder = MessageUtility.fromJson(formatter.parse());
} catch (IllegalArgumentException e) {
consumer.accept(null, e);
return;
}
} else {
builder = new WebhookMessageBuilder();
}
consumer.accept(builder, null);
} else {
ImageRequest request = new ImageRequest(Config.get().getImageWebserverUrl("welcomer")).addQuery("avatar", user.getEffectiveAvatarUrl()).addQuery("name", user.getAsTag()).addQuery("gif", gif).addQuery("directory", canary ? "sx4-canary" : "sx4-main");
if (bannerId != null) {
request.addQuery("banner_id", bannerId);
}
httpClient.newCall(request.build(Config.get().getImageWebserver())).enqueue((HttpCallback) response -> {
if (response.isSuccessful()) {
String fileName = "welcomer." + response.header("Content-Type").split("/")[1];
formatter.addVariable("file.name", fileName).addVariable("file.url", "attachment://" + fileName);
WebhookMessageBuilder builder;
if (messageData == null) {
builder = new WebhookMessageBuilder();
} else {
try {
builder = MessageUtility.fromJson(formatter.parse());
} catch (IllegalArgumentException e) {
consumer.accept(null, e);
return;
}
}
builder.addFile(fileName, response.body().bytes());
consumer.accept(builder, null);
} else {
response.close();
}
});
}
}
Aggregations