Search in sources :

Example 16 with ErrorHandler

use of net.dv8tion.jda.api.exceptions.ErrorHandler in project Levelbot by Kaktushose.

the class ShopListener method onGuildMessageReactionAdd.

@Override
public void onGuildMessageReactionAdd(@NotNull GuildMessageReactionAddEvent event) {
    // bots should just be ignored
    if (event.getUser().isBot()) {
        return;
    }
    // must be in channel #levelsystem
    if (event.getChannel().getIdLong() != LEVEL_SYSTEM_CHANNEL_ID) {
        return;
    }
    if (levelbot.getUserService().getMutedUsers().contains(event.getUser().getIdLong())) {
        event.getReaction().removeReaction(event.getUser()).queue(null, new ErrorHandler().ignore(UNKNOWN_MESSAGE));
        return;
    }
    // indicates active purchase
    if (activeUsers.contains(event.getUser().getIdLong())) {
        event.getReaction().removeReaction(event.getUser()).queue(null, new ErrorHandler().ignore(UNKNOWN_MESSAGE));
        return;
    }
    Member member = event.getMember();
    ItemCategory itemCategory;
    switch(event.getMessageId()) {
        case PREMIUM_MESSAGE_ID:
            itemCategory = ItemCategory.PREMIUM;
            break;
        case DJ_MESSAGE_ID:
            itemCategory = ItemCategory.DJ;
            break;
        case NICKNAME_MESSAGE_ID:
            itemCategory = ItemCategory.NICKNAME;
            break;
        case COINS_BOOSTER_MESSAGE_ID:
            itemCategory = ItemCategory.COINS_BOOSTER;
            break;
        case XP_BOOSTER_MESSAGE_ID:
            itemCategory = ItemCategory.XP_BOOSTER;
            break;
        default:
            event.getReaction().removeReaction(member.getUser()).queue(null, new ErrorHandler().ignore(UNKNOWN_MESSAGE));
            return;
    }
    int variant;
    switch(event.getReactionEmote().getName()) {
        case NumberEmojis.ONE:
            variant = 0;
            break;
        case NumberEmojis.TWO:
            variant = 1;
            break;
        case NumberEmojis.THREE:
            variant = 2;
            break;
        default:
            event.getReaction().removeReaction(member.getUser()).queue();
            return;
    }
    if ((itemCategory == ItemCategory.COINS_BOOSTER || itemCategory == ItemCategory.XP_BOOSTER) && variant == 2) {
        event.getReaction().removeReaction(member.getUser()).queue();
        return;
    }
    Item item = levelService.getItemsByCategoryId(itemCategory.id).get(variant);
    BotUser botUser = userService.getUserById(member.getIdLong());
    String fail = null;
    if (shopService.hasItemOfCategory(member.getIdLong(), item.getCategoryId())) {
        fail = "Du besitzt dieses Item bereits!";
    }
    if (botUser.getCoins() < item.getPrice()) {
        fail = "Du hast nicht genug Münzen!";
    }
    TextChannel channel = event.getChannel();
    Consumer<Message> delete = success -> success.delete().queueAfter(30, TimeUnit.SECONDS, null, new ErrorHandler().ignore(UNKNOWN_MESSAGE));
    MessageBuilder builder = new MessageBuilder().append(member.getAsMention());
    if (fail != null) {
        // transaction failed
        channel.sendMessage(builder.setEmbeds(embedCache.getEmbed("shopError").injectValue("message", fail).toMessageEmbed()).build()).queue(delete);
    } else {
        activeUsers.add(member.getIdLong());
        // confirm transaction
        channel.sendMessage(builder.setEmbeds(embedCache.getEmbed("shopConfirm").injectValue("item", item.getName()).injectValue("price", item.getPrice()).toMessageEmbed()).build()).queue(confirmMessage -> {
            // wait for reactions
            // delete confirm message after 30 secs if nothing happens
            confirmMessage.delete().queueAfter(30, TimeUnit.SECONDS, success -> activeUsers.remove(member.getIdLong()), new ErrorHandler().ignore(UNKNOWN_MESSAGE));
            confirmMessage.addReaction(CONFIRM).and(confirmMessage.addReaction(CANCEL)).queue();
            ReactionWaiter waiter = new ReactionWaiter(confirmMessage, event.getMember(), CONFIRM, CANCEL);
            waiter.onEvent(reactionEvent -> {
                // on reaction confirm or cancel emoji
                confirmMessage.delete().queue();
                if (reactionEvent.getEmote().equals(CONFIRM)) {
                    shopService.buyItem(botUser.getUserId(), item.getItemId());
                    // successful transaction
                    channel.sendMessageEmbeds(embedCache.getEmbed("shopSuccess").injectValue("item", item.getName()).injectValue("days", TimeUnit.MILLISECONDS.toDays(item.getDuration())).toMessageEmbed()).queue(delete);
                    levelbot.getLogChannel().sendMessageEmbeds(embedCache.getEmbed("buyLog").injectValue("user", member.getAsMention()).injectValue("item", item.getName()).toMessageEmbed()).queue();
                }
                activeUsers.remove(member.getIdLong());
                waiter.stopWaiting(false);
            });
        });
    }
    event.getReaction().removeReaction(member.getUser()).queue();
}
Also used : Message(net.dv8tion.jda.api.entities.Message) BotUser(de.kaktushose.levelbot.database.model.BotUser) LevelService(de.kaktushose.levelbot.database.services.LevelService) ListenerAdapter(net.dv8tion.jda.api.hooks.ListenerAdapter) Set(java.util.Set) UNKNOWN_MESSAGE(net.dv8tion.jda.api.requests.ErrorResponse.UNKNOWN_MESSAGE) Levelbot(de.kaktushose.levelbot.bot.Levelbot) Member(net.dv8tion.jda.api.entities.Member) TextChannel(net.dv8tion.jda.api.entities.TextChannel) UserService(de.kaktushose.levelbot.database.services.UserService) HashSet(java.util.HashSet) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ShopService(de.kaktushose.levelbot.shop.data.ShopService) EmbedCache(com.github.kaktushose.jda.commands.embeds.EmbedCache) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) ReactionWaiter(de.kaktushose.discord.reactionwaiter.ReactionWaiter) GuildMessageReactionAddEvent(net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionAddEvent) Item(de.kaktushose.levelbot.shop.data.items.Item) NotNull(org.jetbrains.annotations.NotNull) NumberEmojis(de.kaktushose.levelbot.util.NumberEmojis) ErrorHandler(net.dv8tion.jda.api.exceptions.ErrorHandler) ErrorHandler(net.dv8tion.jda.api.exceptions.ErrorHandler) BotUser(de.kaktushose.levelbot.database.model.BotUser) Message(net.dv8tion.jda.api.entities.Message) ReactionWaiter(de.kaktushose.discord.reactionwaiter.ReactionWaiter) Item(de.kaktushose.levelbot.shop.data.items.Item) TextChannel(net.dv8tion.jda.api.entities.TextChannel) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Member(net.dv8tion.jda.api.entities.Member)

Example 17 with ErrorHandler

use of net.dv8tion.jda.api.exceptions.ErrorHandler in project Levelbot by Kaktushose.

the class Levelbot method sendItemExpiredInformation.

public void sendItemExpiredInformation(long userId, int itemId, long buyTime) {
    User user = jda.getUserById(userId);
    Item item = levelService.getItem(itemId);
    EmbedBuilder embed = embedCache.getEmbed("itemExpired").injectValue("item", item.getName()).injectValue("date", new SimpleDateFormat("dd.MM.yyyy HH:mm").format(new Date(buyTime))).toEmbedBuilder();
    user.openPrivateChannel().flatMap(privateChannel -> privateChannel.sendMessageEmbeds(embed.build())).queue(null, new ErrorHandler().handle(ErrorResponse.CANNOT_SEND_TO_USER, exception -> {
        TextChannel channel = getBotChannel();
        channel.sendMessage(user.getAsMention()).and(channel.sendMessageEmbeds(embed.build())).queue();
    }));
}
Also used : LoginException(javax.security.auth.login.LoginException) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) BotUser(de.kaktushose.levelbot.database.model.BotUser) JDA(net.dv8tion.jda.api.JDA) Date(java.util.Date) ReactionListener(de.kaktushose.discord.reactionwaiter.ReactionListener) LoggerFactory(org.slf4j.LoggerFactory) Statistics(de.kaktushose.levelbot.util.Statistics) SimpleDateFormat(java.text.SimpleDateFormat) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) de.kaktushose.levelbot.listener(de.kaktushose.levelbot.listener) GatewayIntent(net.dv8tion.jda.api.requests.GatewayIntent) ShopService(de.kaktushose.levelbot.shop.data.ShopService) Calendar(java.util.Calendar) CollectEvent(de.kaktushose.levelbot.database.model.CollectEvent) JDABuilder(net.dv8tion.jda.api.JDABuilder) Bootstrapper(de.kaktushose.levelbot.Bootstrapper) CacheFlag(net.dv8tion.jda.api.utils.cache.CacheFlag) ErrorHandler(net.dv8tion.jda.api.exceptions.ErrorHandler) OnlineStatus(net.dv8tion.jda.api.OnlineStatus) MemberCachePolicy(net.dv8tion.jda.api.utils.MemberCachePolicy) ShopListener(de.kaktushose.levelbot.shop.ShopListener) Logger(org.slf4j.Logger) JsonErrorMessageFactory(com.github.kaktushose.jda.commands.embeds.error.JsonErrorMessageFactory) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) de.kaktushose.levelbot.database.services(de.kaktushose.levelbot.database.services) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) EmbedDTO(com.github.kaktushose.jda.commands.embeds.EmbedDTO) List(java.util.List) EmbedCache(com.github.kaktushose.jda.commands.embeds.EmbedCache) Rank(de.kaktushose.levelbot.database.model.Rank) JDACommands(com.github.kaktushose.jda.commands.JDACommands) JsonHelpMessageFactory(com.github.kaktushose.jda.commands.embeds.help.JsonHelpMessageFactory) WelcomeEmbedsCommand(de.kaktushose.levelbot.commands.moderation.WelcomeEmbedsCommand) Item(de.kaktushose.levelbot.shop.data.items.Item) ChunkingFilter(net.dv8tion.jda.api.utils.ChunkingFilter) Item(de.kaktushose.levelbot.shop.data.items.Item) ErrorHandler(net.dv8tion.jda.api.exceptions.ErrorHandler) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) BotUser(de.kaktushose.levelbot.database.model.BotUser) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date)

Example 18 with ErrorHandler

use of net.dv8tion.jda.api.exceptions.ErrorHandler in project cds by iamysko.

the class MessageListener method validateBanRequest.

/**
 * Validate a ban request by checking if the:
 * Correct format is used
 * User ID exists
 * User ID doesn't belong to a staff member
 *
 * @param message       the message
 */
private void validateBanRequest(final Message message) {
    if (!message.getContentRaw().matches("(?si)^;(?:force)?ban\\s\\d{17,19}\\s.+$")) {
        message.reply("Incorrect ban request format. Please use `;ban <user id> <reason>`").mentionRepliedUser(true).setActionRow(Button.primary("DeleteMessage", "Hide Alert")).queue();
    } else {
        Pattern regexPattern = Pattern.compile("(?si)^;(?:force)?ban\\s(\\d{17,19})\\s.+$");
        Matcher matchedResults = regexPattern.matcher(message.getContentRaw());
        matchedResults.find();
        message.getJDA().getGuildById(Properties.GUILD_ROBLOX_DISCORD_ID).retrieveMemberById(matchedResults.group(1)).queue(targetedMember -> {
            if (RoleUtils.isAnyRole(targetedMember, RoleUtils.ROLE_LEAD, RoleUtils.ROLE_SERVER_MANAGER, RoleUtils.ROLE_MODERATOR, RoleUtils.ROLE_SENIOR_MODERATOR, RoleUtils.ROLE_BOT, RoleUtils.ROLE_TRIAL_MODERATOR)) {
                message.reply("The provided ID belongs to a staff member.").mentionRepliedUser(true).setActionRow(Button.primary("DeleteMessage", "Hide Alert")).queue();
            }
        }, new ErrorHandler().ignore(ErrorResponse.UNKNOWN_MEMBER).handle(ErrorResponse.UNKNOWN_USER, (error) -> message.reply("The provided ID is not a valid user ID").mentionRepliedUser(true).setActionRow(Button.primary("DeleteMessage", "Hide Alert")).queue()));
    }
}
Also used : Arrays(java.util.Arrays) RoleUtils(com.misterveiga.cds.utils.RoleUtils) Properties(com.misterveiga.cds.utils.Properties) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) Member(net.dv8tion.jda.api.entities.Member) TextChannel(net.dv8tion.jda.api.entities.TextChannel) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) MessageFilter(com.misterveiga.cds.utils.MessageFilter) Matcher(java.util.regex.Matcher) RegexConstants(com.misterveiga.cds.utils.RegexConstants) Map(java.util.Map) Button(net.dv8tion.jda.api.interactions.components.Button) StringBuilds(com.misterveiga.cds.utils.StringBuilds) ErrorHandler(net.dv8tion.jda.api.exceptions.ErrorHandler) Message(net.dv8tion.jda.api.entities.Message) Logger(org.slf4j.Logger) ListenerAdapter(net.dv8tion.jda.api.hooks.ListenerAdapter) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) List(java.util.List) Component(org.springframework.stereotype.Component) CollectionUtils(org.springframework.util.CollectionUtils) DurationUtils(com.misterveiga.cds.utils.DurationUtils) Pattern(java.util.regex.Pattern) MessageReceivedEvent(net.dv8tion.jda.api.events.message.MessageReceivedEvent) CommandImpl(com.misterveiga.cds.command.CommandImpl) Pattern(java.util.regex.Pattern) ErrorHandler(net.dv8tion.jda.api.exceptions.ErrorHandler) Matcher(java.util.regex.Matcher)

Example 19 with ErrorHandler

use of net.dv8tion.jda.api.exceptions.ErrorHandler in project Robertify-Bot by bombies.

the class ReminderScheduler method dmReminder.

private void dmReminder(Guild guild, long user, String reminder) {
    User u = Robertify.shardManager.retrieveUserById(user).complete();
    u.openPrivateChannel().queue(channel -> channel.sendMessageEmbeds(RobertifyEmbedUtils.embedMessageWithTitle(guild, "Reminder", reminder).setFooter("Reminder from: " + guild.getName()).setTimestamp(Instant.now()).build()).queue(null, new ErrorHandler().handle(ErrorResponse.CANNOT_SEND_TO_USER, ignored -> {
    })));
}
Also used : ErrorHandler(net.dv8tion.jda.api.exceptions.ErrorHandler) ReminderUser(main.utils.json.reminders.ReminderUser) User(net.dv8tion.jda.api.entities.User)

Example 20 with ErrorHandler

use of net.dv8tion.jda.api.exceptions.ErrorHandler in project Robertify-Bot by bombies.

the class UnbanCommand method handleUnban.

private EmbedBuilder handleUnban(Guild guild, User user) {
    if (!new GuildConfig().isBannedUser(guild.getIdLong(), user.getIdLong()))
        return RobertifyEmbedUtils.embedMessage(guild, "This user is not banned.");
    new GuildConfig().unbanUser(guild.getIdLong(), user.getIdLong());
    user.openPrivateChannel().queue(channel -> channel.sendMessageEmbeds(RobertifyEmbedUtils.embedMessage(guild, "You have been unbanned from **" + guild.getName() + "**").build()).queue(success -> {
    }, new ErrorHandler().handle(ErrorResponse.CANNOT_SEND_TO_USER, e -> Listener.logger.warn("Was not able to send an unban message to " + user.getAsTag() + "(" + user.getIdLong() + ")"))));
    return RobertifyEmbedUtils.embedMessage(guild, "You have unbanned " + user.getAsMention());
}
Also used : Message(net.dv8tion.jda.api.entities.Message) OptionType(net.dv8tion.jda.api.interactions.commands.OptionType) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) Permission(main.constants.Permission) GuildConfig(main.utils.json.guildconfig.GuildConfig) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Member(net.dv8tion.jda.api.entities.Member) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) User(net.dv8tion.jda.api.entities.User) SlashCommandEvent(net.dv8tion.jda.api.events.interaction.SlashCommandEvent) ICommand(main.commands.prefixcommands.ICommand) List(java.util.List) Guild(net.dv8tion.jda.api.entities.Guild) CommandContext(main.commands.prefixcommands.CommandContext) RobertifyEmbedUtils(main.utils.RobertifyEmbedUtils) AbstractSlashCommand(main.utils.component.interactions.AbstractSlashCommand) BotConstants(main.constants.BotConstants) Listener(main.main.Listener) NotNull(org.jetbrains.annotations.NotNull) GeneralUtils(main.utils.GeneralUtils) ErrorHandler(net.dv8tion.jda.api.exceptions.ErrorHandler) ScriptException(javax.script.ScriptException) ErrorHandler(net.dv8tion.jda.api.exceptions.ErrorHandler) GuildConfig(main.utils.json.guildconfig.GuildConfig)

Aggregations

ErrorHandler (net.dv8tion.jda.api.exceptions.ErrorHandler)20 ErrorResponse (net.dv8tion.jda.api.requests.ErrorResponse)8 Instant (java.time.Instant)6 MessageConfig (me.duncte123.botcommons.messaging.MessageConfig)6 net.dv8tion.jda.api.entities (net.dv8tion.jda.api.entities)6 List (java.util.List)5 TimeUnit (java.util.concurrent.TimeUnit)5 Collectors (java.util.stream.Collectors)5 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)5 JDA (net.dv8tion.jda.api.JDA)5 Message (net.dv8tion.jda.api.entities.Message)5 TextChannel (net.dv8tion.jda.api.entities.TextChannel)5 NotNull (org.jetbrains.annotations.NotNull)5 GuildSetting (com.dunctebot.models.settings.GuildSetting)4 Matcher (java.util.regex.Matcher)4 Pattern (java.util.regex.Pattern)4 User (net.dv8tion.jda.api.entities.User)4 ListenerAdapter (net.dv8tion.jda.api.hooks.ListenerAdapter)4 Logger (org.slf4j.Logger)4 LoggerFactory (org.slf4j.LoggerFactory)4