Search in sources :

Example 21 with ShardManager

use of net.dv8tion.jda.api.sharding.ShardManager in project Sx4 by sx4-discord-bot.

the class TemporaryBanManager method removeBanAndGet.

public DeleteOneModel<Document> removeBanAndGet(long guildId, long userId, boolean automatic) {
    ShardManager shardManager = this.bot.getShardManager();
    Guild guild = shardManager.getGuildById(guildId);
    if (guild == null) {
        return null;
    }
    User user = shardManager.getUserById(userId);
    Member member = user == null ? null : guild.getMember(user);
    if (automatic && member == null) {
        guild.unban(User.fromId(userId)).reason("Ban length served").queue();
    }
    if (automatic) {
        Reason reason = new Reason("Ban length served");
        UnbanEvent event = new UnbanEvent(guild.getSelfMember(), user == null ? UserReference.fromId(userId) : user, reason);
        this.bot.getModActionManager().onModAction(event);
    }
    this.deleteExecutor(guildId, userId);
    return new DeleteOneModel<>(Filters.and(Filters.eq("guildId", guildId), Filters.eq("userId", userId)));
}
Also used : User(net.dv8tion.jda.api.entities.User) UnbanEvent(com.sx4.bot.events.mod.UnbanEvent) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) Guild(net.dv8tion.jda.api.entities.Guild) Member(net.dv8tion.jda.api.entities.Member) Reason(com.sx4.bot.entities.mod.Reason)

Example 22 with ShardManager

use of net.dv8tion.jda.api.sharding.ShardManager in project SkyBot by duncte123.

the class AirUtils method handleExpiredReminders.

public static void handleExpiredReminders(List<Reminder> reminders, DatabaseAdapter adapter) {
    // Get the shardManager and a list of ints to purge the ids for
    final ShardManager shardManager = SkyBot.getInstance().getShardManager();
    final List<Integer> toPurge = new ArrayList<>();
    for (final Reminder reminder : reminders) {
        // The reminder message template
        final String message = String.format("%s you asked me to remind you about \"%s\"", TimeFormat.RELATIVE.format(reminder.getCreate_date()), reminder.getReminder().trim());
        // If we have a channel send the message to that
        if (reminder.getIn_channel()) {
            final long channelId = reminder.getChannel_id();
            final TextChannel channel = shardManager.getTextChannelById(channelId);
            // skipping the continue statement makes sure that we roll into the dm part of this
            if (channel != null) {
                // Add the reminder to the list of the reminders to purge
                toPurge.add(reminder.getId());
                sendMsg(new MessageConfig.Builder().setChannel(channel).setMessage(String.format("<@%s>, %s", reminder.getUser_id(), message)).replyTo(reminder.getMessage_id()).build());
                // go to the next one and don't run the user code if a channel was found
                continue;
            }
        }
        try {
            Objects.requireNonNull(shardManager.getShardById(0)).openPrivateChannelById(reminder.getUser_id()).flatMap((c) -> c.sendMessage(message + "\n" + reminder.getJumpUrl())).complete();
            toPurge.add(reminder.getId());
        } catch (ErrorResponseException errorResponseEx) {
            final ErrorResponse errorResponse = errorResponseEx.getErrorResponse();
            if (// The account probably got deleted or something
            errorResponse == ErrorResponse.UNKNOWN_USER || // we cannot dm this user (has dms blocked?)
            errorResponse == ErrorResponse.CANNOT_SEND_TO_USER) {
                toPurge.add(reminder.getId());
            }
        } catch (Exception e) {
            Sentry.captureException(e);
        }
    }
    // get a date that is 2 days in the future
    final OffsetDateTime plusTwoDays = OffsetDateTime.now(ZoneOffset.UTC).plus(2L, ChronoUnit.DAYS);
    // Remove any reminders that have not been removed after 2 days
    final List<Integer> extraRemoval = reminders.stream().filter((reminder) -> reminder.getReminder_date().isAfter(plusTwoDays)).map(Reminder::getId).collect(Collectors.toList());
    toPurge.addAll(extraRemoval);
    if (!toPurge.isEmpty()) {
        adapter.purgeRemindersSync(toPurge);
    }
}
Also used : Arrays(java.util.Arrays) JDA(net.dv8tion.jda.api.JDA) StringUtils(me.duncte123.botcommons.StringUtils) ParsedDuration(me.duncte123.durationparser.ParsedDuration) Permission(net.dv8tion.jda.api.Permission) JSONRequestBody(me.duncte123.botcommons.web.requests.JSONRequestBody) Member(net.dv8tion.jda.api.entities.Member) TextChannel(net.dv8tion.jda.api.entities.TextChannel) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) FinderUtil(com.jagrosh.jdautilities.commons.utils.FinderUtil) User(net.dv8tion.jda.api.entities.User) TemporalAccessor(java.time.temporal.TemporalAccessor) ArrayList(java.util.ArrayList) WebParserUtils.toJSONObject(me.duncte123.botcommons.web.WebParserUtils.toJSONObject) Guild(net.dv8tion.jda.api.entities.Guild) JDAImpl(net.dv8tion.jda.internal.JDAImpl) LavalinkManager(fredboat.audio.player.LavalinkManager) ZoneOffset(java.time.ZoneOffset) Sentry(io.sentry.Sentry) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) MessageUtils.sendMsg(me.duncte123.botcommons.messaging.MessageUtils.sendMsg) CommandContext(ml.duncte123.skybot.objects.command.CommandContext) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) TimeFormat(net.dv8tion.jda.api.utils.TimeFormat) WebParserUtils(me.duncte123.botcommons.web.WebParserUtils) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) TLongObjectHashMap(gnu.trove.map.hash.TLongObjectHashMap) DateTimeParseException(java.time.format.DateTimeParseException) List(java.util.List) OffsetDateTime(java.time.OffsetDateTime) ChronoUnit(java.time.temporal.ChronoUnit) MessageConfig(me.duncte123.botcommons.messaging.MessageConfig) SkyBot(ml.duncte123.skybot.SkyBot) DatabaseAdapter(ml.duncte123.skybot.adapters.DatabaseAdapter) TLongObjectMap(gnu.trove.map.TLongObjectMap) FakeMember(ml.duncte123.skybot.entities.jda.FakeMember) RateLimiter(com.github.natanbc.reliqua.limiter.RateLimiter) WebUtils(me.duncte123.botcommons.web.WebUtils) PendingRequest(com.github.natanbc.reliqua.request.PendingRequest) GuildMusicManager(ml.duncte123.skybot.audio.GuildMusicManager) Reminder(ml.duncte123.skybot.objects.api.Reminder) FakePendingRequest(ml.duncte123.skybot.objects.FakePendingRequest) Reminder(ml.duncte123.skybot.objects.api.Reminder) ArrayList(java.util.ArrayList) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) DateTimeParseException(java.time.format.DateTimeParseException) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) TextChannel(net.dv8tion.jda.api.entities.TextChannel) MessageConfig(me.duncte123.botcommons.messaging.MessageConfig) OffsetDateTime(java.time.OffsetDateTime) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException)

Example 23 with ShardManager

use of net.dv8tion.jda.api.sharding.ShardManager in project SkyBot by duncte123.

the class CommandUtils method getPatronGuildIds.

public static List<Long> getPatronGuildIds(long userId, ShardManager shardManager) {
    if (ONEGUILD_PATRONS.containsKey(userId)) {
        return List.of(ONEGUILD_PATRONS.get(userId));
    }
    final List<Long> guildIds = new ArrayList<>();
    shardManager.getGuildCache().acceptStream((stream) -> stream.filter((guild) -> {
        final Member member = guild.getMemberById(userId);
        return member != null && member.hasPermission(Permission.ADMINISTRATOR);
    }).forEach((guild) -> guildIds.add(guild.getIdLong())));
    return guildIds;
}
Also used : EmbedUtils(me.duncte123.botcommons.messaging.EmbedUtils) Arrays(java.util.Arrays) Parser(com.jagrosh.jagtag.Parser) Permission(net.dv8tion.jda.api.Permission) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AllPatronsData(ml.duncte123.skybot.objects.api.AllPatronsData) Member(net.dv8tion.jda.api.entities.Member) TextChannel(net.dv8tion.jda.api.entities.TextChannel) Supplier(java.util.function.Supplier) User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) MessageUtils.sendEmbed(me.duncte123.botcommons.messaging.MessageUtils.sendEmbed) JagTag(com.jagrosh.jagtag.JagTag) Guild(net.dv8tion.jda.api.entities.Guild) PATREON(ml.duncte123.skybot.Settings.PATREON) Map(java.util.Map) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) Checks(net.dv8tion.jda.internal.utils.Checks) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) TLongSet(gnu.trove.set.TLongSet) CommandContext(ml.duncte123.skybot.objects.command.CommandContext) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Collectors(java.util.stream.Collectors) Settings(ml.duncte123.skybot.Settings) List(java.util.List) DiscordMethods(ml.duncte123.skybot.objects.jagtag.DiscordMethods) Flag(ml.duncte123.skybot.objects.command.Flag) TLongLongMap(gnu.trove.map.TLongLongMap) ArrayList(java.util.ArrayList) Member(net.dv8tion.jda.api.entities.Member)

Example 24 with ShardManager

use of net.dv8tion.jda.api.sharding.ShardManager in project Sx4 by sx4-discord-bot.

the class GiveawayCommand method list.

@Command(value = "list", description = "Lists all the giveaways which have happened in the server")
@CommandId(52)
@Examples({ "giveaway list" })
public void list(Sx4CommandEvent event) {
    List<Document> giveaways = event.getMongo().getGiveaways(Filters.eq("guildId", event.getGuild().getIdLong())).into(new ArrayList<>());
    if (giveaways.isEmpty()) {
        event.replyFailure("No giveaways have been setup in this server").queue();
        return;
    }
    PagedResult<Document> paged = new PagedResult<>(event.getBot(), giveaways).setAuthor("Giveaways", null, event.getGuild().getIconUrl()).setDisplayFunction(data -> {
        long endAt = data.getLong("endAt"), timeNow = Clock.systemUTC().instant().getEpochSecond();
        return data.getLong("messageId") + " - " + (endAt - timeNow < 0 ? "Ended" : TimeUtility.LONG_TIME_FORMATTER.parse(endAt - timeNow));
    });
    paged.onSelect(select -> {
        ShardManager shardManager = event.getShardManager();
        Document data = select.getSelected();
        List<Long> winners = data.getList("winners", Long.class, Collections.emptyList());
        String winnersString = winners.isEmpty() ? "None" : winners.stream().map(shardManager::getUserById).filter(Objects::nonNull).map(User::getAsMention).collect(Collectors.joining(", "));
        event.replyFormat("**Giveaway %d**\nItem: %s\nWinner%s: %s\nDuration: %s", data.getLong("messageId"), data.getString("item"), winners.size() == 1 ? "" : "s", winnersString, TimeUtility.LONG_TIME_FORMATTER.parse(data.getLong("duration"))).queue();
    });
    paged.execute(event);
}
Also used : User(net.dv8tion.jda.api.entities.User) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) Document(org.bson.Document) ReturnDocument(com.mongodb.client.model.ReturnDocument) PagedResult(com.sx4.bot.paged.PagedResult) 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 25 with ShardManager

use of net.dv8tion.jda.api.sharding.ShardManager in project Sx4 by sx4-discord-bot.

the class GuessTheNumberGame method endGame.

public void endGame(InteractionHook hook) {
    this.bot.getGuessTheNumberManager().removeGame(this);
    ShardManager manager = this.bot.getShardManager();
    ObjectId gameId = ObjectId.get();
    int randomNumber = this.random.nextInt(this.max) + 1;
    Document authorData = new Document("userId", this.userId).append("gameId", gameId).append("type", GameType.GUESS_THE_NUMBER.getId()).append("choice", this.userGuess).append("answer", randomNumber);
    Document opponentData = new Document("userId", this.opponentId).append("gameId", gameId).append("type", GameType.GUESS_THE_NUMBER.getId()).append("choice", this.opponentGuess).append("answer", randomNumber);
    int authorDifference = Math.abs(this.userGuess - randomNumber), opponentDifference = Math.abs(this.opponentGuess - randomNumber);
    User user = manager.getUserById(this.userId), opponent = manager.getUserById(this.opponentId);
    StringBuilder content = new StringBuilder("The random number was **" + randomNumber + "**\n" + (opponent == null ? this.opponentId : opponent.getName()) + "'s number was **" + this.opponentGuess + "**\n" + (user == null ? this.userId : user.getName()) + "'s number was **" + this.userGuess + "**\n\n");
    if (authorDifference == opponentDifference) {
        content.append("You both guessed the same number, It was a draw!");
        authorData.append("state", GameState.DRAW.getId());
        opponentData.append("state", GameState.DRAW.getId());
    } else if (authorDifference > opponentDifference) {
        content.append(opponent == null ? this.opponentId : opponent.getName()).append(" won! They were the closest to ").append(randomNumber);
        authorData.append("state", GameState.LOSS.getId());
        opponentData.append("state", GameState.WIN.getId());
    } else {
        content.append(user == null ? this.userId : user.getName()).append(" won! They were the closest to ").append(randomNumber);
        authorData.append("state", GameState.WIN.getId());
        opponentData.append("state", GameState.LOSS.getId());
    }
    hook.sendMessage(content.toString()).queue();
    hook.editMessageComponentsById(this.messageId, ActionRow.of(Button.primary("a", "Guess the number").asDisabled())).queue();
    this.bot.getMongo().insertManyGames(List.of(authorData, opponentData)).whenComplete(MongoDatabase.exceptionally());
}
Also used : User(net.dv8tion.jda.api.entities.User) ObjectId(org.bson.types.ObjectId) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) Document(org.bson.Document)

Aggregations

ShardManager (net.dv8tion.jda.api.sharding.ShardManager)41 JDA (net.dv8tion.jda.api.JDA)19 Member (net.dv8tion.jda.api.entities.Member)15 Guild (net.dv8tion.jda.api.entities.Guild)14 User (net.dv8tion.jda.api.entities.User)14 ArrayList (java.util.ArrayList)12 List (java.util.List)9 Collectors (java.util.stream.Collectors)9 Permission (net.dv8tion.jda.api.Permission)8 TextChannel (net.dv8tion.jda.api.entities.TextChannel)8 Arrays (java.util.Arrays)5 Executors (java.util.concurrent.Executors)5 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)5 Nonnull (javax.annotation.Nonnull)5 DefaultShardManagerBuilder (net.dv8tion.jda.api.sharding.DefaultShardManagerBuilder)5 Document (org.bson.Document)5 WebhookEmbed (club.minnced.discord.webhook.send.WebhookEmbed)4 WebhookEmbedBuilder (club.minnced.discord.webhook.send.WebhookEmbedBuilder)4 DecimalFormat (java.text.DecimalFormat)4 IOException (java.io.IOException)3