Search in sources :

Example 31 with Sx4

use of com.sx4.bot.core.Sx4 in project Sx4 by sx4-discord-bot.

the class PremiumCommand method credit.

@Command(value = "credit", description = "Checks your current credit")
@CommandId(179)
@Examples({ "premium credit" })
public void credit(Sx4CommandEvent event) {
    Document premium = event.getMongoMain().getUserById(event.getAuthor().getIdLong(), Projections.include("premium.credit", "premium.endAt")).get("premium", MongoDatabase.EMPTY_DOCUMENT);
    int credit = premium.getInteger("credit", 0);
    long endAt = premium.get("endAt", -1L);
    OffsetDateTime expire = OffsetDateTime.ofInstant(Instant.ofEpochSecond(endAt), ZoneOffset.UTC);
    String format = String.format(expire.format(this.formatter), NumberUtility.getSuffix(expire.getDayOfMonth()));
    event.replyFormat("Your current credit is **$%,.2f**%s", credit / 100D, endAt == -1 ? "" : "\n\nYour personal premium " + (expire.isBefore(OffsetDateTime.now(ZoneOffset.UTC)) ? "expired on the **" + format + "**, you can renew it here <https://patreon.com/Sx4>" : "will expire on the **" + format + "**")).queue();
}
Also used : OffsetDateTime(java.time.OffsetDateTime) Document(org.bson.Document) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Example 32 with Sx4

use of com.sx4.bot.core.Sx4 in project Sx4 by sx4-discord-bot.

the class PremiumCommand method add.

@Command(value = "add", description = "Make a server premium")
@CommandId(177)
@Examples({ "premium add", "premium add 31", "premium add 20 Sx4 | Support Server" })
@Premium
public void add(Sx4CommandEvent event, @Argument(value = "days") @DefaultNumber(31) @Limit(min = 1, max = 365) int days, @Argument(value = "server", endless = true, nullDefault = true) Guild guild) {
    if (guild == null) {
        guild = event.getGuild();
    }
    int monthPrice = event.getConfig().getPremiumPrice();
    int price = (int) Math.round((monthPrice / (double) event.getConfig().getPremiumDays()) * days);
    long endAtPrior = event.getMongo().getGuildById(guild.getIdLong(), Projections.include("premium.endAt")).getEmbedded(List.of("premium", "endAt"), 0L);
    boolean hasPremium = endAtPrior != 0;
    MessageEmbed embed = new EmbedBuilder().setColor(event.getConfig().getOrange()).setAuthor("Premium", null, event.getAuthor().getEffectiveAvatarUrl()).setDescription(String.format("Buying %d day%s of premium will:\n\n• Make you unable to use this credit on the other version of the bot\n• Use **$%.2f** of your credit\n• %s %1$s day%2$s of premium to the server\n\n:warning: **This action cannot be reversed** :warning:", days, days == 1 ? "" : "s", price / 100D, hasPremium ? "Add an extra" : "Give")).build();
    String acceptId = new CustomButtonId.Builder().setType(ButtonType.PREMIUM_CONFIRM).setTimeout(60).setOwners(event.getAuthor().getIdLong()).setArguments(guild.getIdLong(), days).getId();
    String rejectId = new CustomButtonId.Builder().setType(ButtonType.GENERIC_REJECT).setTimeout(60).setOwners(event.getAuthor().getIdLong()).getId();
    List<Button> buttons = List.of(Button.success(acceptId, "Confirm"), Button.danger(rejectId, "Cancel"));
    event.reply(embed).setActionRow(buttons).queue();
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) Button(net.dv8tion.jda.api.interactions.components.buttons.Button) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) CustomButtonId(com.sx4.bot.entities.interaction.CustomButtonId) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command) Premium(com.sx4.bot.annotations.command.Premium) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Example 33 with Sx4

use of com.sx4.bot.core.Sx4 in project Sx4 by sx4-discord-bot.

the class ServerLogHandler method onGuildJoin.

public void onGuildJoin(GuildJoinEvent event) {
    ShardManager manager = event.getJDA().getShardManager();
    Member owner = event.getGuild().getOwner();
    WebhookEmbedBuilder embed = new WebhookEmbedBuilder().setColor(this.bot.getConfig().getGreen()).setThumbnailUrl(event.getGuild().getIconUrl()).setTimestamp(Instant.now()).setDescription(String.format("I am now in %,d servers and connected to %,d users", manager.getGuildCache().size(), manager.getUserCache().size())).setAuthor(new WebhookEmbed.EmbedAuthor("Joined Server!", event.getJDA().getSelfUser().getEffectiveAvatarUrl(), null)).addField(new WebhookEmbed.EmbedField(true, "Server Name", event.getGuild().getName())).addField(new WebhookEmbed.EmbedField(true, "Server ID", event.getGuild().getId())).addField(new WebhookEmbed.EmbedField(true, "Server Owner", (owner == null ? "Anonymous#0000" : owner.getUser().getAsTag()) + "\n" + event.getGuild().getOwnerId())).addField(new WebhookEmbed.EmbedField(true, "Server Members", String.format("%,d member%s", event.getGuild().getMemberCount(), event.getGuild().getMemberCount() == 1 ? "" : "s")));
    this.webhook.send(embed.build());
    if (event.getGuild().getSelfMember().hasPermission(Permission.VIEW_AUDIT_LOGS)) {
        event.getGuild().retrieveAuditLogs().type(ActionType.BOT_ADD).queueAfter(500, TimeUnit.MILLISECONDS, audits -> {
            AuditLogEntry audit = audits.stream().filter(auditLog -> auditLog.getTargetIdLong() == event.getJDA().getSelfUser().getIdLong()).filter(auditLog -> Duration.between(auditLog.getTimeCreated(), ZonedDateTime.now(ZoneOffset.UTC)).toSeconds() <= 5).findFirst().orElse(null);
            if (audit != null) {
                audit.getUser().openPrivateChannel().flatMap(channel -> channel.sendMessage("Thanks for adding me to your server!\nThe default prefix is `s?` however if that doesn't work use `@Sx4#1617 prefix` to check your current prefixes\nAll my info and commands can be found in `s?help`\nIf you need any help feel free to join the support server: https://discord.gg/PqJNcfB")).queue();
            }
        });
    }
}
Also used : ActionType(net.dv8tion.jda.api.audit.ActionType) Document(org.bson.Document) WebhookClient(club.minnced.discord.webhook.WebhookClient) GuildJoinEvent(net.dv8tion.jda.api.events.guild.GuildJoinEvent) Permission(net.dv8tion.jda.api.Permission) ZonedDateTime(java.time.ZonedDateTime) Member(net.dv8tion.jda.api.entities.Member) AuditLogEntry(net.dv8tion.jda.api.audit.AuditLogEntry) RequestBody(okhttp3.RequestBody) WebhookEmbedBuilder(club.minnced.discord.webhook.send.WebhookEmbedBuilder) Sx4(com.sx4.bot.core.Sx4) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) TimeUtility(com.sx4.bot.utility.TimeUtility) Duration(java.time.Duration) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) ZoneOffset(java.time.ZoneOffset) MediaType(okhttp3.MediaType) Request(okhttp3.Request) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) HttpCallback(com.sx4.bot.http.HttpCallback) Instant(java.time.Instant) GuildLeaveEvent(net.dv8tion.jda.api.events.guild.GuildLeaveEvent) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) EventListener(net.dv8tion.jda.api.hooks.EventListener) NotNull(org.jetbrains.annotations.NotNull) WebhookClientBuilder(club.minnced.discord.webhook.WebhookClientBuilder) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) AuditLogEntry(net.dv8tion.jda.api.audit.AuditLogEntry) WebhookEmbedBuilder(club.minnced.discord.webhook.send.WebhookEmbedBuilder) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) Member(net.dv8tion.jda.api.entities.Member)

Example 34 with Sx4

use of com.sx4.bot.core.Sx4 in project Sx4 by sx4-discord-bot.

the class StarboardHandler method getStarboardMessage.

private WebhookMessage getStarboardMessage(Document guildData, Document starboard, Guild guild, Member member, ReactionEmote emote, boolean premium) {
    List<Document> messages = guildData.getList("messages", Document.class, StarboardManager.DEFAULT_CONFIGURATION);
    int stars = starboard.getInteger("count");
    Document messageData = messages.stream().filter(d -> starboard.getInteger("count") >= d.getInteger("stars")).max(Comparator.comparingInt(d -> d.getInteger("stars"))).orElse(null);
    if (messageData == null) {
        return null;
    }
    int nextStars = messages.stream().filter(d -> starboard.getInteger("count") < d.getInteger("stars")).mapToInt(d -> d.getInteger("stars")).min().orElse(0);
    User author = this.bot.getShardManager().getUserById(starboard.getLong("authorId"));
    long channelId = starboard.getLong("channelId");
    BaseGuildMessageChannel channel = guild.getChannelById(BaseGuildMessageChannel.class, channelId);
    if (channel == null) {
        return null;
    }
    String messageLink = "https://discord.com/channels/" + guild.getId() + "/" + channelId + "/" + starboard.getLong("originalMessageId");
    // temporary while embed support isn't a thing
    WebhookEmbedBuilder builder = new WebhookEmbedBuilder().setAuthor(new WebhookEmbed.EmbedAuthor(author == null ? "Anonymous#0000" : author.getAsTag(), author == null ? null : author.getEffectiveAvatarUrl(), null)).setColor(-21453).addField(new WebhookEmbed.EmbedField(false, "Message Link", "[Jump!](" + messageLink + ")")).setImageUrl(starboard.getString("image"));
    String content = starboard.getString("content");
    if (content != null && !content.isBlank()) {
        builder.addField(new WebhookEmbed.EmbedField(false, "Message", StringUtility.limit(content, MessageEmbed.VALUE_MAX_LENGTH, "[...](" + messageLink + ")")));
    }
    Document webhookData = guildData.get("webhook", MongoDatabase.EMPTY_DOCUMENT);
    try {
        return this.format(messageData.get("message", Document.class), member, channel, emote, stars, nextStars, starboard.getObjectId("_id")).setUsername(premium ? webhookData.get("name", "Sx4 - Starboard") : "Sx4 - Starboard").setAvatarUrl(premium ? webhookData.get("avatar", this.bot.getShardManager().getShardById(0).getSelfUser().getEffectiveAvatarUrl()) : this.bot.getShardManager().getShardById(0).getSelfUser().getEffectiveAvatarUrl()).addEmbeds(builder.build()).build();
    } catch (IllegalArgumentException e) {
        // TODO: can't currently happen but when embed support is added handle this
        return null;
    }
}
Also used : Document(org.bson.Document) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) ReactionEmote(net.dv8tion.jda.api.entities.MessageReaction.ReactionEmote) MessageReactionRemoveEvent(net.dv8tion.jda.api.events.message.react.MessageReactionRemoveEvent) JsonFormatter(com.sx4.bot.formatter.JsonFormatter) MongoWriteException(com.mongodb.MongoWriteException) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) CompletableFuture(java.util.concurrent.CompletableFuture) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) Bson(org.bson.conversions.Bson) Formatter(com.sx4.bot.formatter.Formatter) WebhookEmbedBuilder(club.minnced.discord.webhook.send.WebhookEmbedBuilder) Sx4(com.sx4.bot.core.Sx4) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) com.mongodb.client.model(com.mongodb.client.model) EncodingUtil(net.dv8tion.jda.internal.utils.EncodingUtil) WebhookMessageBuilder(club.minnced.discord.webhook.send.WebhookMessageBuilder) Operators(com.sx4.bot.database.mongo.model.Operators) Attachment(net.dv8tion.jda.api.entities.Message.Attachment) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) MessageUtility(com.sx4.bot.utility.MessageUtility) StarboardManager(com.sx4.bot.managers.StarboardManager) CompletionException(java.util.concurrent.CompletionException) Route(net.dv8tion.jda.internal.requests.Route) MessageReactionAddEvent(net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent) RestActionImpl(net.dv8tion.jda.internal.requests.RestActionImpl) List(java.util.List) EventListener(net.dv8tion.jda.api.hooks.EventListener) WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) ObjectId(org.bson.types.ObjectId) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) NotNull(org.jetbrains.annotations.NotNull) Comparator(java.util.Comparator) StringUtility(com.sx4.bot.utility.StringUtility) ErrorCategory(com.mongodb.ErrorCategory) Document(org.bson.Document) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) WebhookEmbedBuilder(club.minnced.discord.webhook.send.WebhookEmbedBuilder)

Example 35 with Sx4

use of com.sx4.bot.core.Sx4 in project Sx4 by sx4-discord-bot.

the class WelcomerHandler method sendWelcomer.

public void sendWelcomer(Guild guild, Member member) {
    JDA jda = guild.getJDA();
    Document data = this.bot.getMongo().getGuildById(guild.getIdLong(), Projections.include("welcomer", "premium.endAt"));
    Document welcomer = data.get("welcomer", MongoDatabase.EMPTY_DOCUMENT);
    Document image = welcomer.get("image", MongoDatabase.EMPTY_DOCUMENT);
    if (member.isPending() == welcomer.get("screening", true)) {
        return;
    }
    boolean messageEnabled = welcomer.getBoolean("enabled", false), imageEnabled = image.getBoolean("enabled", false);
    if (!messageEnabled && !imageEnabled) {
        return;
    }
    long channelId = welcomer.get("channelId", 0L);
    BaseGuildMessageChannel channel = channelId == 0L ? null : guild.getChannelById(BaseGuildMessageChannel.class, channelId);
    boolean dm = welcomer.getBoolean("dm", false);
    if (channel == null && !dm) {
        return;
    }
    Document webhookData = welcomer.get("webhook", MongoDatabase.EMPTY_DOCUMENT);
    boolean premium = Clock.systemUTC().instant().getEpochSecond() < data.getEmbedded(List.of("premium", "endAt"), 0L);
    WelcomerUtility.getWelcomerMessage(this.bot.getHttpClient(), messageEnabled ? welcomer.get("message", WelcomerManager.DEFAULT_MESSAGE) : null, image.getString("bannerId"), member, this.bot.getConfig().isCanary(), imageEnabled, premium, (builder, exception) -> {
        if (exception instanceof IllegalArgumentException) {
            this.bot.getMongo().updateGuildById(guild.getIdLong(), Updates.unset("welcomer.message")).whenComplete(MongoDatabase.exceptionally());
            return;
        }
        if (ExceptionUtility.sendErrorMessage(exception)) {
            return;
        }
        if (dm) {
            member.getUser().openPrivateChannel().flatMap(privateChannel -> MessageUtility.fromWebhookMessage(privateChannel, builder.build())).queue(null, ErrorResponseException.ignore(ErrorResponse.CANNOT_SEND_TO_USER));
        } else {
            WebhookMessage message = builder.setUsername(premium ? webhookData.get("name", "Sx4 - Welcomer") : "Sx4 - Welcomer").setAvatarUrl(premium ? webhookData.get("avatar", jda.getSelfUser().getEffectiveAvatarUrl()) : jda.getSelfUser().getEffectiveAvatarUrl()).build();
            this.bot.getWelcomerManager().sendWelcomer(channel, webhookData, message);
        }
    });
}
Also used : Document(org.bson.Document) GuildMemberUpdatePendingEvent(net.dv8tion.jda.api.events.guild.member.update.GuildMemberUpdatePendingEvent) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) JDA(net.dv8tion.jda.api.JDA) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) MessageUtility(com.sx4.bot.utility.MessageUtility) Projections(com.mongodb.client.model.Projections) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) Updates(com.mongodb.client.model.Updates) Member(net.dv8tion.jda.api.entities.Member) TextChannel(net.dv8tion.jda.api.entities.TextChannel) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) List(java.util.List) Guild(net.dv8tion.jda.api.entities.Guild) EventListener(net.dv8tion.jda.api.hooks.EventListener) Sx4(com.sx4.bot.core.Sx4) WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) Clock(java.time.Clock) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) NotNull(org.jetbrains.annotations.NotNull) WelcomerManager(com.sx4.bot.managers.WelcomerManager) WelcomerUtility(com.sx4.bot.utility.WelcomerUtility) GuildMemberJoinEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent) WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) JDA(net.dv8tion.jda.api.JDA) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) Document(org.bson.Document)

Aggregations

Document (org.bson.Document)28 Sx4Command (com.sx4.bot.core.Sx4Command)24 Command (com.jockie.bot.core.command.Command)23 Bson (org.bson.conversions.Bson)21 Permission (net.dv8tion.jda.api.Permission)19 CompletableFuture (java.util.concurrent.CompletableFuture)16 com.mongodb.client.model (com.mongodb.client.model)14 MongoDatabase (com.sx4.bot.database.mongo.MongoDatabase)14 Operators (com.sx4.bot.database.mongo.model.Operators)14 CompletionException (java.util.concurrent.CompletionException)13 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)13 Argument (com.jockie.bot.core.argument.Argument)12 ModuleCategory (com.sx4.bot.category.ModuleCategory)12 Sx4 (com.sx4.bot.core.Sx4)12 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)12 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)12 BaseGuildMessageChannel (net.dv8tion.jda.api.entities.BaseGuildMessageChannel)12 CommandId (com.sx4.bot.annotations.command.CommandId)11 Examples (com.sx4.bot.annotations.command.Examples)10 User (net.dv8tion.jda.api.entities.User)10