use of com.sx4.bot.core.Sx4 in project Sx4 by sx4-discord-bot.
the class LoggerManager method handleQueue.
private void handleQueue() {
this.executor.submit(() -> {
try {
Request request = this.queue.poll();
if (request == null) {
return;
}
if (request.getAttempts() == LoggerManager.MAX_RETRIES) {
this.handleQueue();
return;
}
Guild guild = request.getGuild();
if (guild == null) {
this.handleQueue();
return;
}
long channelId = request.getChannelId();
BaseGuildMessageChannel channel = request.getChannel(guild);
if (channel == null) {
this.bot.getMongo().deleteLogger(Filters.eq("channelId", channelId)).whenComplete((result, exception) -> {
ExceptionUtility.sendErrorMessage(exception);
this.queue.clear();
});
return;
}
List<WebhookEmbed> embeds = new ArrayList<>(request.getEmbeds());
int length = MessageUtility.getWebhookEmbedLength(embeds);
List<Request> skippedRequests = new ArrayList<>(), requests = new ArrayList<>();
requests.add(request);
Request nextRequest;
while ((nextRequest = this.queue.poll()) != null) {
List<WebhookEmbed> nextEmbeds = nextRequest.getEmbeds();
int nextLength = MessageUtility.getWebhookEmbedLength(nextEmbeds);
if (embeds.size() + nextEmbeds.size() > WebhookMessage.MAX_EMBEDS || length + nextLength > MessageEmbed.EMBED_MAX_LENGTH_BOT) {
skippedRequests.add(nextRequest);
break;
}
embeds.addAll(nextEmbeds);
requests.add(nextRequest);
length += nextLength;
}
// Keep order of logs
skippedRequests.forEach(this.queue::addFirst);
Document logger = request.getLogger();
Document webhookData = logger.get("webhook", MongoDatabase.EMPTY_DOCUMENT);
boolean premium = logger.getBoolean("premium");
WebhookMessage message = new WebhookMessageBuilder().addEmbeds(embeds).setUsername(premium ? webhookData.get("name", "Sx4 - Logger") : "Sx4 - Logger").setAvatarUrl(premium ? webhookData.get("avatar", request.getJDA().getSelfUser().getEffectiveAvatarUrl()) : request.getJDA().getSelfUser().getEffectiveAvatarUrl()).build();
if (this.webhook == null) {
if (!webhookData.containsKey("id")) {
if (guild.getSelfMember().hasPermission(channel, Permission.MANAGE_WEBHOOKS)) {
this.createWebhook(channel, requests);
return;
}
this.handleQueue();
return;
} else {
this.webhook = new WebhookClient(webhookData.getLong("id"), webhookData.getString("token"), this.webhookExecutor, this.webhookClient);
}
}
this.webhook.send(message).whenComplete((result, exception) -> {
Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
if (cause instanceof HttpException && ((HttpException) cause).getCode() == 404) {
if (guild.getSelfMember().hasPermission(channel, Permission.MANAGE_WEBHOOKS)) {
this.createWebhook(channel, requests);
return;
}
this.disableLogger(channel.getIdLong());
return;
}
if (ExceptionUtility.sendErrorMessage(exception)) {
requests.forEach(failedRequest -> this.queue.addFirst(failedRequest.incrementAttempts()));
}
this.handleQueue();
});
} catch (Throwable exception) {
// Continue queue even if an exception occurs to avoid the queue getting stuck
ExceptionUtility.sendErrorMessage(exception);
this.handleQueue();
}
});
}
use of com.sx4.bot.core.Sx4 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();
}
});
}
}
use of com.sx4.bot.core.Sx4 in project Sx4 by sx4-discord-bot.
the class SuggestionManager method sendSuggestion.
public CompletableFuture<ReadonlyMessage> sendSuggestion(TextChannel channel, Document webhookData, boolean premium, WebhookEmbed embed) {
User selfUser = channel.getJDA().getSelfUser();
WebhookMessage message = new WebhookMessageBuilder().setAvatarUrl(webhookData.get("avatar", selfUser.getEffectiveAvatarUrl())).setUsername(webhookData.get("name", "Sx4 - Suggestions")).addEmbeds(embed).build();
WebhookClient webhook;
if (this.webhooks.containsKey(channel.getIdLong())) {
webhook = this.webhooks.get(channel.getIdLong());
} else if (!webhookData.containsKey("id")) {
return this.createWebhook(channel, message);
} else {
webhook = new WebhookClient(webhookData.getLong("id"), webhookData.getString("token"), this.executor, this.client);
this.webhooks.put(channel.getIdLong(), webhook);
}
return webhook.send(message).thenApply(webhookMessage -> new ReadonlyMessage(webhookMessage, webhook.getId(), webhook.getToken())).exceptionallyCompose(exception -> {
Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
if (cause instanceof HttpException && ((HttpException) cause).getCode() == 404) {
this.webhooks.remove(channel.getIdLong());
return this.createWebhook(channel, message);
}
return CompletableFuture.failedFuture(exception);
});
}
use of com.sx4.bot.core.Sx4 in project Sx4 by sx4-discord-bot.
the class LoggerCommand method avatar.
@Command(value = "avatar", description = "Set the avatar of the webhook that sends logs")
@CommandId(424)
@Examples({ "logger avatar #logs Shea#6653", "logger avatar https://i.imgur.com/i87lyNO.png" })
@Premium
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void avatar(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true) TextChannel channel, @Argument(value = "avatar", endless = true, acceptEmpty = true) @ImageUrl String url) {
TextChannel effectiveChannel = channel == null ? event.getTextChannel() : channel;
event.getMongo().updateLogger(Filters.eq("channelId", effectiveChannel.getIdLong()), Updates.set("webhook.avatar", url)).whenComplete((result, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
if (result.getModifiedCount() == 0) {
event.replyFailure("Your webhook avatar for that logger was already set to that").queue();
return;
}
event.replySuccess("Your webhook avatar has been updated for that logger, this only works with premium <https://patreon.com/Sx4>").queue();
});
}
use of com.sx4.bot.core.Sx4 in project Sx4 by sx4-discord-bot.
the class LoggerCommand method name.
@Command(value = "name", description = "Set the name of the webhook that sends logs")
@CommandId(423)
@Examples({ "logger name #logs Logs", "logger name Logger" })
@Premium
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void name(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true) TextChannel channel, @Argument(value = "name", endless = true) String name) {
TextChannel effectiveChannel = channel == null ? event.getTextChannel() : channel;
event.getMongo().updateLogger(Filters.eq("channelId", effectiveChannel.getIdLong()), Updates.set("webhook.name", name)).whenComplete((result, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
if (result.getModifiedCount() == 0) {
event.replyFailure("Your webhook name for that logger was already set to that").queue();
return;
}
event.replySuccess("Your webhook name has been updated for that logger, this only works with premium <https://patreon.com/Sx4>").queue();
});
}
Aggregations