Search in sources :

Example 46 with UserId

use of com.sx4.bot.annotations.argument.UserId in project Sx4 by sx4-discord-bot.

the class AntiRegexCommand method set.

@Command(value = "set", description = "Sets the amount of attempts a user has for an anti regex")
@CommandId(460)
@Examples({ "anti regex set 5f023782ef9eba03390a740c @Shea#6653 0", "anti regex set 5f023782ef9eba03390a740c Shea 3", "anti regex set 5f023782ef9eba03390a740c 402557516728369153 2" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void set(Sx4CommandEvent event, @Argument(value = "id") ObjectId id, @Argument(value = "user") Member member, @Argument(value = "attempts") int attempts) {
    Bson filter = Filters.and(Filters.eq("regexId", id), Filters.eq("userId", member.getIdLong()), Filters.eq("guildId", event.getGuild().getIdLong()));
    CompletableFuture<Document> future;
    if (attempts == 0) {
        future = event.getMongo().findAndDeleteRegexAttempt(filter);
    } else {
        FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().projection(Projections.include("attempts")).returnDocument(ReturnDocument.BEFORE).upsert(true);
        future = event.getMongo().findAndUpdateRegexAttempt(filter, Updates.set("attempts", attempts), options);
    }
    future.whenComplete((data, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (data == null) {
            event.replyFailure("I could not find that anti regex").queue();
            return;
        }
        if (data.getInteger("attempts") == attempts) {
            event.replyFailure("That users attempts were already set to that").queue();
            return;
        }
        event.replySuccess("**" + member.getUser().getAsTag() + "** has had their attempts set to **" + attempts + "**").queue();
    });
}
Also used : Document(org.bson.Document) Bson(org.bson.conversions.Bson) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) 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 47 with UserId

use of com.sx4.bot.annotations.argument.UserId in project Sx4 by sx4-discord-bot.

the class ReminderCommand method remove.

@Command(value = "remove", aliases = { "delete" }, description = "Remove a reminder from being notified about")
@CommandId(154)
@Examples({ "reminder remove 5ec67a3b414d8776950f0eee" })
public void remove(Sx4CommandEvent event, @Argument(value = "id", nullDefault = true) ObjectId id) {
    if (id == null) {
        if (!event.getBot().getConnectionHandler().isReady()) {
            event.replyFailure("You cannot view reminders while the bot is starting up").queue();
            return;
        }
        List<Document> reminders = event.getMongo().getReminders(Filters.eq("userId", event.getAuthor().getIdLong()), Projections.include("reminder", "remindAt")).into(new ArrayList<>());
        if (reminders.isEmpty()) {
            event.replyFailure("You do not have any active reminders").queue();
            return;
        }
        long now = Clock.systemUTC().instant().getEpochSecond();
        PagedResult<Document> paged = new PagedResult<>(event.getBot(), reminders).setAuthor("Reminders", null, event.getAuthor().getEffectiveAvatarUrl()).setPerPage(10).setIndexed(true).setDisplayFunction(data -> StringUtility.limit(data.getString("reminder"), 150) + " in `" + TimeUtility.LONG_TIME_FORMATTER.parse(data.getLong("remindAt") - now) + "`");
        paged.onSelect(select -> {
            ObjectId selected = select.getSelected().getObjectId("_id");
            event.getMongo().deleteReminder(Filters.eq("_id", selected)).whenComplete((result, exception) -> {
                if (ExceptionUtility.sendExceptionally(event, exception)) {
                    return;
                }
                if (result.getDeletedCount() == 0) {
                    event.replyFailure("You do not have a reminder with that id").queue();
                    return;
                }
                event.getBot().getReminderManager().deleteExecutor(selected);
                event.replySuccess("You will no longer be reminded about that reminder").queue();
            });
        });
        paged.execute(event);
    } else {
        event.getMongo().deleteReminder(Filters.and(Filters.eq("_id", id), Filters.eq("userId", event.getAuthor().getIdLong()))).whenComplete((result, exception) -> {
            if (ExceptionUtility.sendExceptionally(event, exception)) {
                return;
            }
            if (result.getDeletedCount() == 0) {
                event.replyFailure("You do not have a reminder with that id").queue();
                return;
            }
            event.getBot().getReminderManager().deleteExecutor(id);
            event.replySuccess("You will no longer be reminded about that reminder").queue();
        });
    }
}
Also used : ObjectId(org.bson.types.ObjectId) Document(org.bson.Document) 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 48 with UserId

use of com.sx4.bot.annotations.argument.UserId in project Sx4 by sx4-discord-bot.

the class ReminderCommand method add.

@Command(value = "add", description = "Create a reminder so the bot will message you when the time is up", argumentInfo = "reminder add <reminder>* in <time>*\nreminder add <reminder>* at <date time>*")
@CommandId(153)
@Examples({ "reminder add Football game in 4 hours", "reminder add Party at 21/07/20 15:00 UTC+1", "reminder add Finish coursework at 12:00", "reminder add fish in 5 minutes --repeat", "reminder add weekly task at 23/05 --repeat=7d" })
public void add(Sx4CommandEvent event, @Argument(value = "reminder", endless = true) ReminderArgument reminder, @Option(value = "repeat", description = "Continuously repeats the reminder after the initial duration is up") Duration repeat) {
    long initialDuration = reminder.getDuration();
    boolean repeatOption = event.isOptionPresent("repeat");
    long duration = repeat == null ? initialDuration : repeat.toSeconds();
    if (duration < 30 && repeatOption) {
        event.replyFailure("Repeated reminders have to be at least 30 seconds long").queue();
        return;
    }
    if (reminder.getReminder().length() > 1500) {
        event.replyFailure("Your reminder cannot be longer than 1500 characters").queue();
        return;
    }
    Document data = new Document("userId", event.getAuthor().getIdLong()).append("repeat", repeatOption).append("duration", duration).append("reminder", reminder.getReminder()).append("remindAt", Clock.systemUTC().instant().getEpochSecond() + initialDuration);
    event.getMongo().insertReminder(data).whenComplete((result, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        ObjectId id = result.getInsertedId().asObjectId().getValue();
        data.append("_id", id);
        event.getBot().getReminderManager().putReminder(initialDuration, data);
        event.replyFormat("I will remind you about that in **%s**, your reminder id is `%s` %s", TimeUtility.LONG_TIME_FORMATTER.parse(initialDuration), id.toHexString(), event.getConfig().getSuccessEmote()).queue();
    });
}
Also used : ObjectId(org.bson.types.ObjectId) 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 49 with UserId

use of com.sx4.bot.annotations.argument.UserId in project Sx4 by sx4-discord-bot.

the class UserInfoCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "user", nullDefault = true) @UserId long userId) {
    RestAction<User> action = userId == 0L ? new CompletedRestAction<>(event.getJDA(), event.getAuthor()) : event.getJDA().retrieveUserById(userId);
    action.flatMap(user -> {
        EmbedBuilder embed = new EmbedBuilder().setDescription(event.getConfig().getUserFlagEmotes(user.getFlags())).setAuthor(user.getAsTag(), user.getEffectiveAvatarUrl(), user.getEffectiveAvatarUrl()).setThumbnail(user.getEffectiveAvatarUrl()).addField("Joined Discord", user.getTimeCreated().format(TimeUtility.DEFAULT_FORMATTER), true).addField("User ID", user.getId(), true).addField("Bot", user.isBot() ? "Yes" : "No", false);
        return event.reply(embed.build());
    }).onErrorFlatMap(exception -> {
        if (exception instanceof ErrorResponseException && ((ErrorResponseException) exception).getErrorResponse() == ErrorResponse.UNKNOWN_USER) {
            return event.replyFailure("I could not find that user");
        }
        return null;
    }).queue();
}
Also used : UserId(com.sx4.bot.annotations.argument.UserId) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) CompletedRestAction(net.dv8tion.jda.internal.requests.CompletedRestAction) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) User(net.dv8tion.jda.api.entities.User) ModuleCategory(com.sx4.bot.category.ModuleCategory) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) TimeUtility(com.sx4.bot.utility.TimeUtility) RestAction(net.dv8tion.jda.api.requests.RestAction) Argument(com.jockie.bot.core.argument.Argument) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) User(net.dv8tion.jda.api.entities.User) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException)

Example 50 with UserId

use of com.sx4.bot.annotations.argument.UserId in project Sx4 by sx4-discord-bot.

the class ReminderManager method executeReminderBulk.

public CompletableFuture<WriteModel<Document>> executeReminderBulk(Document data) {
    User user = this.bot.getShardManager().getUserById(data.getLong("userId"));
    if (user != null) {
        return user.openPrivateChannel().submit().thenCompose(channel -> channel.sendMessageFormat("You wanted me to remind you about **%s**", data.getString("reminder")).submit()).handle((message, exception) -> {
            ObjectId id = data.getObjectId("_id");
            int attempts;
            Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
            if (cause instanceof ErrorResponseException) {
                int code = ((ErrorResponseException) cause).getResponse().code;
                // Check whether it's on discords end, in that case don't increase the attempts
                if (code > 499 && code < 600) {
                    attempts = this.attempts.getOrDefault(id, 0);
                } else {
                    attempts = this.attempts.compute(id, (key, value) -> value == null ? 1 : value + 1);
                }
            } else {
                this.attempts.remove(id);
                attempts = 0;
            }
            return this.handleReminder(data, attempts);
        });
    } else {
        return CompletableFuture.completedFuture(this.handleReminder(data, this.attempts.compute(data.getObjectId("_id"), (key, value) -> value == null ? 1 : value + 1)));
    }
}
Also used : Document(org.bson.Document) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) java.util.concurrent(java.util.concurrent) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) HashMap(java.util.HashMap) User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) List(java.util.List) Sx4(com.sx4.bot.core.Sx4) Map(java.util.Map) ObjectId(org.bson.types.ObjectId) Clock(java.time.Clock) com.mongodb.client.model(com.mongodb.client.model) FutureUtility(com.sx4.bot.utility.FutureUtility) User(net.dv8tion.jda.api.entities.User) ObjectId(org.bson.types.ObjectId) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException)

Aggregations

Document (org.bson.Document)46 Bson (org.bson.conversions.Bson)44 Sx4Command (com.sx4.bot.core.Sx4Command)36 Command (com.jockie.bot.core.command.Command)28 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)26 User (net.dv8tion.jda.api.entities.User)26 CommandId (com.sx4.bot.annotations.command.CommandId)25 Examples (com.sx4.bot.annotations.command.Examples)23 Operators (com.sx4.bot.database.mongo.model.Operators)23 List (java.util.List)21 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)20 Permission (net.dv8tion.jda.api.Permission)20 Member (net.dv8tion.jda.api.entities.Member)20 ModuleCategory (com.sx4.bot.category.ModuleCategory)18 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)18 PagedResult (com.sx4.bot.paged.PagedResult)14 Argument (com.jockie.bot.core.argument.Argument)13 com.mongodb.client.model (com.mongodb.client.model)13 ArrayList (java.util.ArrayList)13 BotPermissions (com.sx4.bot.annotations.command.BotPermissions)12