diff --git a/src/main/java/com/github/kaktushose/nplaybot/events/collect/CollectEventService.java b/src/main/java/com/github/kaktushose/nplaybot/events/collect/CollectEventService.java index 49e0fb4..ac3715b 100644 --- a/src/main/java/com/github/kaktushose/nplaybot/events/collect/CollectEventService.java +++ b/src/main/java/com/github/kaktushose/nplaybot/events/collect/CollectEventService.java @@ -30,7 +30,7 @@ public CollectEventService(DataSource dataSource, Bot bot) { } public boolean isCollectEventActive() { - log.debug("Querying collect event active flag for guild {}", guild); + log.debug("Querying collect event active setting"); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" SELECT collect_event_active @@ -49,7 +49,7 @@ public boolean isCollectEventActive() { } public void startCollectEvent(String eventName, String currencyName, String emoji) { - log.debug("Starting new collect event [{}, {}, {}] for guild {}", eventName, currencyName, emoji, guild); + log.info("Starting new collect event [{}, {}, {}]", eventName, currencyName, emoji); try (Connection connection = dataSource.getConnection()) { connection.prepareStatement("UPDATE users SET collect_points = 0").execute(); @@ -75,7 +75,7 @@ public void startCollectEvent(String eventName, String currencyName, String emoj } public void stopCollectEvent() { - log.debug("Stopping collect event for guild {}", guild); + log.info("Stopping current collect event"); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" UPDATE event_settings @@ -91,7 +91,7 @@ public void stopCollectEvent() { } public void createCollectReward(String name, int threshold, int xp, @Nullable Role role, @Nullable ItemService.Item item, String embed) { - log.debug("Creating new collect reward"); + log.info("Creating new collect reward [name={}, threshold={}, xp={}, role={}, item={}]", name, threshold, xp, role, item); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement("INSERT INTO collect_rewards(name, threshold, xp, role_id, item_id, embed) VALUES (?, ?, ?, ?, ?, CAST (? AS jsonb))"); statement.setString(1, name); @@ -108,7 +108,7 @@ public void createCollectReward(String name, int threshold, int xp, @Nullable Ro } public void updateCollectLootChance(double chance) { - log.debug("Updating collect loot chance for guild: {}", guild); + log.info("Updating collect loot chance, new value: {}", chance); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" UPDATE event_settings @@ -185,7 +185,7 @@ public List getCollectRewards() { } public void deleteCollectReward(int rewardId) { - log.debug("Deleting collect reward with id {}", rewardId); + log.info("Deleting collect reward with id {}", rewardId); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement("DELETE FROM collect_rewards WHERE reward_id = ?"); statement.setInt(1, rewardId); @@ -196,7 +196,7 @@ public void deleteCollectReward(int rewardId) { } public int addCollectPoint(UserSnowflake user) { - log.debug("Adding one collect point to user: {}", user); + log.info("Adding one collect point to user: {}", user); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement("UPDATE users SET collect_points = collect_points + 1 where user_id = ?"); statement.setLong(1, user.getIdLong()); @@ -221,6 +221,7 @@ public int getCollectPoints(UserSnowflake user) { } public String getEventName() { + log.debug("Querying collect event name"); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" SELECT collect_event_name @@ -241,5 +242,17 @@ public record CollectCurrency(String name, String emoji) { public record CollectReward(int rewardId, String name, int threshold, int xp, long roleId, int itemId, String embed) { + + @Override + public String toString() { + return "CollectReward{" + + "rewardId=" + rewardId + + ", name='" + name + '\'' + + ", threshold=" + threshold + + ", xp=" + xp + + ", roleId=" + roleId + + ", itemId=" + itemId + + '}'; + } } } diff --git a/src/main/java/com/github/kaktushose/nplaybot/events/contest/ContestEventService.java b/src/main/java/com/github/kaktushose/nplaybot/events/contest/ContestEventService.java index 52c2c06..f987b6d 100644 --- a/src/main/java/com/github/kaktushose/nplaybot/events/contest/ContestEventService.java +++ b/src/main/java/com/github/kaktushose/nplaybot/events/contest/ContestEventService.java @@ -63,7 +63,7 @@ public String getVoteEmoji() { } public void startContestEvent(TextChannel channel, String emoji) { - log.debug("Starting new contest event in {} with vote emoji {}", channel, emoji); + log.info("Starting new contest event in {} with vote emoji {}", channel, emoji); try (Connection connection = dataSource.getConnection()) { log.debug("Truncating old votes"); connection.prepareStatement("TRUNCATE TABLE contest_entries;").execute(); @@ -85,7 +85,7 @@ public void startContestEvent(TextChannel channel, String emoji) { } public List stopContestEvent() { - log.debug("Stopping current contest event"); + log.info("Stopping current contest event"); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" UPDATE event_settings @@ -116,7 +116,7 @@ public List stopContestEvent() { } public boolean createContestEntry(Message message) { - log.debug("Inserting contest entry: {}", message); + log.info("Inserting contest entry: {}", message); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement("INSERT INTO contest_entries VALUES(?, 0, ?) ON CONFLICT DO NOTHING"); statement.setLong(1, message.getAuthor().getIdLong()); @@ -128,7 +128,7 @@ public boolean createContestEntry(Message message) { } public void deleteContestEntry(long messageId) { - log.debug("Deleting contest entry: {}", messageId); + log.info("Deleting contest entry: {}", messageId); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement("DELETE FROM contest_entries WHERE message_id = ?"); statement.setLong(1, messageId); @@ -145,7 +145,7 @@ public void deleteContestEntry(long messageId) { * @param userId the id of the user that voted for the entry */ public void increaseVoteCount(long messageId, long userId) { - log.debug("Increasing total votes for {} by one", messageId); + log.info("User {} added one vote for entry {}", userId, messageId); try (Connection connection = dataSource.getConnection()) { // this AND clause prevents a self vote of the message author var statement = connection.prepareStatement("UPDATE contest_entries SET votes = votes + 1 where message_id = ? AND user_id != ?"); @@ -164,7 +164,7 @@ public void increaseVoteCount(long messageId, long userId) { * @param userId the id of the user that removed his vote for the entry */ public void decreaseVoteCount(long messageId, long userId) { - log.debug("Decreasing total votes for {} by one", messageId); + log.info("User {} removed one vote for entry {}", userId, messageId); try (Connection connection = dataSource.getConnection()) { // this AND clause prevents a self vote of the message author var statement = connection.prepareStatement("UPDATE contest_entries SET votes = votes - 1 where message_id = ? AND user_id != ?"); diff --git a/src/main/java/com/github/kaktushose/nplaybot/events/contest/ContestListener.java b/src/main/java/com/github/kaktushose/nplaybot/events/contest/ContestListener.java index c04ccb3..325e1fe 100644 --- a/src/main/java/com/github/kaktushose/nplaybot/events/contest/ContestListener.java +++ b/src/main/java/com/github/kaktushose/nplaybot/events/contest/ContestListener.java @@ -43,10 +43,9 @@ public void onMessageReceived(@NotNull MessageReceivedEvent event) { } if (eventService.createContestEntry(event.getMessage())) { - log.debug("Created new contest entry: {}", event.getMessage()); event.getMessage().addReaction(Emoji.fromFormatted(eventService.getVoteEmoji())).queue(); } else { - log.debug("User already has a contest entry, deleting message"); + log.info("User {} already has a contest entry, deleting new message", event.getAuthor()); event.getMessage().delete().queue(); } } @@ -54,6 +53,7 @@ public void onMessageReceived(@NotNull MessageReceivedEvent event) { @Override public void onMessageDelete(@NotNull MessageDeleteEvent event) { eventService.setVoteCount(event.getMessageIdLong(), 0); + log.info("Contest entry {} got deleted, setting vote count to 0", event.getMessageId()); } @Override @@ -107,7 +107,7 @@ public void onMessageReactionRemoveEmoji(@NotNull MessageReactionRemoveEmojiEven if (!event.getEmoji().equals(Emoji.fromFormatted(eventService.getVoteEmoji()))) { return; } - log.debug("Detected removal of all vote emojis. Adding initial emoji again"); + log.warn("Detected removal of all vote emojis. Adding initial emoji again"); event.getChannel().retrieveMessageById(event.getMessageId()).flatMap(message -> message.addReaction(Emoji.fromFormatted(eventService.getVoteEmoji())) ).queue(); @@ -119,7 +119,7 @@ public void onMessageReactionRemoveAll(@NotNull MessageReactionRemoveAllEvent ev if (event.getChannel().getIdLong() != eventService.getContestEventChannel()) { return; } - log.debug("Detected removal of all vote emojis. Adding initial emoji again"); + log.warn("Detected removal of all vote emojis. Adding initial emoji again"); event.getChannel().retrieveMessageById(event.getMessageId()).flatMap(message -> message.addReaction(Emoji.fromFormatted(eventService.getVoteEmoji())) ).queue(); diff --git a/src/main/java/com/github/kaktushose/nplaybot/events/contest/MemberExcludeCommand.java b/src/main/java/com/github/kaktushose/nplaybot/events/contest/MemberExcludeCommand.java index 7fd29ac..cb8be04 100644 --- a/src/main/java/com/github/kaktushose/nplaybot/events/contest/MemberExcludeCommand.java +++ b/src/main/java/com/github/kaktushose/nplaybot/events/contest/MemberExcludeCommand.java @@ -11,11 +11,15 @@ import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.interactions.commands.Command; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @Interaction @Permissions(BotPermissions.MODIFY_USER_BALANCE) public class MemberExcludeCommand { + private static final Logger log = LoggerFactory.getLogger(MemberExcludeCommand.class); + @Inject private Database database; @Inject @@ -23,6 +27,7 @@ public class MemberExcludeCommand { @ContextCommand(value = "Vom Contest ausschließen", type = Command.Type.MESSAGE, isGuildOnly = true, ephemeral = true, enabledFor = Permission.BAN_MEMBERS) public void onRemoveContestPost(CommandEvent event, Message message) { + log.info("Excluding member {} from contest event", message.getAuthor()); database.getContestEventService().setVoteCount(message.getIdLong(), 0); message.delete().queue(); event.getGuild().addRoleToMember(message.getAuthor(), message.getGuild().getRoleById(885530505192284210L)).queue(); diff --git a/src/main/java/com/github/kaktushose/nplaybot/internal/MaintenanceCommands.java b/src/main/java/com/github/kaktushose/nplaybot/internal/MaintenanceCommands.java index bcaa9c9..b78f6f2 100644 --- a/src/main/java/com/github/kaktushose/nplaybot/internal/MaintenanceCommands.java +++ b/src/main/java/com/github/kaktushose/nplaybot/internal/MaintenanceCommands.java @@ -8,16 +8,21 @@ import com.github.kaktushose.jda.commands.dispatching.interactions.commands.CommandEvent; import com.github.kaktushose.nplaybot.permissions.BotPermissions; import net.dv8tion.jda.api.Permission; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @Interaction @Permissions(BotPermissions.BOT_ADMINISTRATOR) public class MaintenanceCommands { + private static final Logger log = LoggerFactory.getLogger(MaintenanceCommands.class); + @Inject private EmbedCache embedCache; @SlashCommand(value = "maintenance reload embeds", desc = "Aktualisiert den EmbedCache", enabledFor = Permission.BAN_MEMBERS) public void onReload(CommandEvent event) { + log.warn("Reloading embed cache"); embedCache.loadEmbeds(); event.reply(embedCache.getEmbed("embedCacheReload")); } diff --git a/src/main/java/com/github/kaktushose/nplaybot/items/AddItemCommand.java b/src/main/java/com/github/kaktushose/nplaybot/items/AddItemCommand.java index 0806f82..6a038c7 100644 --- a/src/main/java/com/github/kaktushose/nplaybot/items/AddItemCommand.java +++ b/src/main/java/com/github/kaktushose/nplaybot/items/AddItemCommand.java @@ -9,6 +9,8 @@ import com.github.kaktushose.nplaybot.permissions.BotPermissions; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Member; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.List; @@ -19,6 +21,7 @@ @Permissions(BotPermissions.MODIFY_USER_BALANCE) public class AddItemCommand { + private static final Logger log = LoggerFactory.getLogger(AddItemCommand.class); @Inject private Database database; @Inject @@ -65,9 +68,10 @@ public void onItemAdd(CommandEvent event, Member target) { @StringSelectMenu("Wähle ein Item aus") @SelectOption(label = "dummy option", value = "dummy option") public void onItemAddSelect(ComponentEvent event, List selection) { - selection.forEach(id -> database.getItemService().createTransaction(target, Integer.parseInt(id)).ifPresent(role -> - event.getGuild().addRoleToMember(target, role).queue() - )); + selection.forEach(id -> database.getItemService().createTransaction(target, Integer.parseInt(id)).ifPresent(role -> { + log.info("Adding role {} to member {}", target, role); + event.getGuild().addRoleToMember(target, role).queue(); + })); event.reply(embedCache.getEmbed("itemAdd")); event.removeComponents(); } diff --git a/src/main/java/com/github/kaktushose/nplaybot/items/ItemExpirationTask.java b/src/main/java/com/github/kaktushose/nplaybot/items/ItemExpirationTask.java index c13d9fc..9e2ed1a 100644 --- a/src/main/java/com/github/kaktushose/nplaybot/items/ItemExpirationTask.java +++ b/src/main/java/com/github/kaktushose/nplaybot/items/ItemExpirationTask.java @@ -7,6 +7,8 @@ import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import net.dv8tion.jda.api.exceptions.ErrorHandler; import net.dv8tion.jda.api.requests.ErrorResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; @@ -14,6 +16,7 @@ public class ItemExpirationTask { + private static final Logger log = LoggerFactory.getLogger(ItemExpirationTask.class); public static final int PLAY_ACTIVITY_KARMA_THRESHOLD = 30; private final ScheduledExecutorService executor; @@ -27,21 +30,26 @@ public void onCheckItems(Bot bot) { for (var expiring : itemService.getExpiringTransactions()) { executor.schedule(() -> { var transaction = itemService.getTransactionById(expiring.transactionId()); + log.info("Starting removal for transaction {}", transaction); if (transaction.expiresAt() > System.currentTimeMillis() + TimeUnit.HOURS.toMillis(24)) { + log.info("Removal got invalidated. Transaction probably got prolonged"); return; } itemService.deleteTransaction(UserSnowflake.fromId(transaction.userId()), transaction.transactionId()); if (transaction.isPlayActivity()) { + log.info("Transaction was play activity. Checking if user is still eligible"); var rankInfo = bot.getDatabase().getRankService().getUserInfo(UserSnowflake.fromId(transaction.userId())); if (rankInfo.karma() - rankInfo.lastKarma() >= PLAY_ACTIVITY_KARMA_THRESHOLD) { + log.info("Adding new play activity to user"); itemService.addPlayActivity(UserSnowflake.fromId(transaction.userId())); itemService.updateLastKarma(UserSnowflake.fromId(transaction.userId())); messageUser(transaction, bot.getEmbedCache().getEmbed("playActivityRenew").toEmbedBuilder(), bot); return; } + log.info("User didn't reach play activity threshold"); } var item = itemService.getItem(transaction.itemId()); @@ -51,8 +59,9 @@ public void onCheckItems(Bot bot) { .toEmbedBuilder(); messageUser(transaction, embed, bot); - + log.info("Item removal finished"); }, expiring.expiresAt() - System.currentTimeMillis(), TimeUnit.MILLISECONDS); + log.info("Scheduling transaction {} for removal in {} ms", expiring, expiring.expiresAt() - System.currentTimeMillis()); } } diff --git a/src/main/java/com/github/kaktushose/nplaybot/items/ItemService.java b/src/main/java/com/github/kaktushose/nplaybot/items/ItemService.java index 4af0445..6e2980c 100644 --- a/src/main/java/com/github/kaktushose/nplaybot/items/ItemService.java +++ b/src/main/java/com/github/kaktushose/nplaybot/items/ItemService.java @@ -5,6 +5,8 @@ import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.entities.UserSnowflake; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.sql.DataSource; import java.sql.Connection; @@ -16,6 +18,7 @@ public class ItemService { + private static final Logger log = LoggerFactory.getLogger(ItemService.class); public static final int PREMIUM_BASE_TYPE_ID = 2; public static final int PREMIUM_UNLIMITED_ITEM_ID = 9; private static final int PLAY_ACTIVITY_ITEM_ID = 7; @@ -28,6 +31,7 @@ public ItemService(DataSource dataSource, Bot bot) { } public List getAllItems() { + log.debug("Querying all items"); try (Connection connection = dataSource.getConnection()) { var items = new ArrayList(); @@ -55,6 +59,7 @@ public List getAllItems() { } public Item getItem(int itemId) { + log.debug("Querying item with id {}", itemId); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" SELECT * @@ -79,6 +84,7 @@ public Item getItem(int itemId) { } public List getTransactions(UserSnowflake user) { + log.debug("Querying all transactions for user {}", user); try (Connection connection = dataSource.getConnection()) { var transactions = new ArrayList(); @@ -117,20 +123,25 @@ public Optional createTransaction(UserSnowflake user, int itemId) { } public void addPlayActivity(UserSnowflake user) { - createTransaction(user, PLAY_ACTIVITY_ITEM_ID, true).ifPresent(it -> - guild.addRoleToMember(user, it).queue() - ); + createTransaction(user, PLAY_ACTIVITY_ITEM_ID, true).ifPresent(it -> { + log.info("Adding role {} to user {}", it, user); + guild.addRoleToMember(user, it).queue(); + }); } private Optional createTransaction(UserSnowflake user, int itemId, boolean isPlayActivity) { + log.info("Starting item transaction: ItemId={}, user={}, isPlayActivity={}", itemId, user, isPlayActivity); try (Connection connection = dataSource.getConnection()) { var item = getItem(itemId); - if (getTransactions(user).stream().map(Transaction::itemId).toList().contains(PREMIUM_UNLIMITED_ITEM_ID) && (item.typeId == PREMIUM_BASE_TYPE_ID || itemId == PREMIUM_UNLIMITED_ITEM_ID)) { + if (getTransactions(user).stream().map(Transaction::itemId).toList().contains(PREMIUM_UNLIMITED_ITEM_ID) && + (item.typeId == PREMIUM_BASE_TYPE_ID || itemId == PREMIUM_UNLIMITED_ITEM_ID)) { + log.info("Stopping transaction. User already has Premium Unlimited"); return Optional.empty(); } if (itemId == PREMIUM_UNLIMITED_ITEM_ID) { + log.info("Adding Premium Unlimited"); var statement = connection.prepareStatement(""" SELECT transaction_id FROM transactions JOIN items ON items.item_id = transactions.item_id @@ -142,6 +153,7 @@ private Optional createTransaction(UserSnowflake user, int itemId, boolean var result = statement.executeQuery(); if (result.next()) { + log.info("Removing temporary Premium Item from User"); statement = connection.prepareStatement("DELETE FROM transactions WHERE transaction_id = ?"); statement.setInt(1, result.getInt("transaction_id")); statement.execute(); @@ -152,7 +164,7 @@ private Optional createTransaction(UserSnowflake user, int itemId, boolean statement.setInt(2, itemId); statement.execute(); - + log.info("Item transaction finished"); return Optional.ofNullable(guild.getRoleById(item.roleId)); } @@ -168,11 +180,14 @@ private Optional createTransaction(UserSnowflake user, int itemId, boolean var result = statement.executeQuery(); // if so just increase the duration of the first item if (result.next()) { + var transactionId = result.getInt("transaction_id"); + log.info("User already has an item of type {}. Adding duration {} to existing transaction {}", item.typeId, item.duration, transactionId); statement = connection.prepareStatement("UPDATE transactions SET expires_at = ?, is_play_activity = ? WHERE transaction_id = ?"); statement.setLong(1, result.getLong("expires_at") + item.duration); statement.setBoolean(2, isPlayActivity); - statement.setLong(3, result.getInt("transaction_id")); + statement.setLong(3, transactionId); statement.execute(); + log.info("Item transaction finished"); return Optional.empty(); } @@ -184,6 +199,7 @@ private Optional createTransaction(UserSnowflake user, int itemId, boolean statement.execute(); + log.info("Item transaction finished"); if (item.roleId > 0) { return Optional.ofNullable(guild.getRoleById(item.roleId)); } @@ -194,6 +210,7 @@ private Optional createTransaction(UserSnowflake user, int itemId, boolean } public void deleteTransaction(UserSnowflake user, int transactionId) { + log.info("Deleting transaction {} for user {}", transactionId, user); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement("SELECT item_id FROM transactions WHERE transaction_id = ?"); statement.setInt(1, transactionId); @@ -213,6 +230,7 @@ public void deleteTransaction(UserSnowflake user, int transactionId) { } public String getTypeEmoji(int typeId) { + log.debug("Querying emoji for item type {}", typeId); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement("SELECT emoji FROM item_types where base_type_id = ?"); statement.setInt(1, typeId); @@ -225,6 +243,7 @@ public String getTypeEmoji(int typeId) { } public void updateLastKarma(UserSnowflake user) { + log.info("Updating last karma for user {}", user); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement("UPDATE users SET last_karma = karma_points WHERE user_id = ?"); statement.setLong(1, user.getIdLong()); @@ -235,6 +254,7 @@ public void updateLastKarma(UserSnowflake user) { } public List getExpiringTransactions() { + log.debug("Querying expiring transactions"); try (Connection connection = dataSource.getConnection()) { var transactions = new ArrayList(); @@ -270,6 +290,7 @@ public List getExpiringTransactions() { } private List getAllItemRoles() { + log.debug("Querying all item roles"); try (Connection connection = dataSource.getConnection()) { var result = connection.prepareStatement("SELECT role_id FROM item_types").executeQuery(); var roles = new ArrayList(); @@ -287,18 +308,22 @@ public void updateItemRoles(Member member) { member.getRoles().stream().filter(getAllItemRoles()::contains).forEach(role -> { if (!transactions.stream().map(Transaction::roleId).toList().contains(role.getIdLong())) { + log.info("Removing invalid item role {} from member {}", role, member); guild.removeRoleFromMember(member, role).queue(); } }); transactions.forEach(transaction -> { if (transaction.roleId > 0) { - guild.addRoleToMember(member, guild.getRoleById(transaction.roleId)).queue(); + var role = guild.getRoleById(transaction.roleId); + log.info("Adding missing item role {} to member {}", role, member); + guild.addRoleToMember(member, role).queue(); } }); } public Transaction getTransactionById(long transactionId) { + log.debug("Querying transaction {}", transactionId); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" SELECT * @@ -328,11 +353,36 @@ public Transaction getTransactionById(long transactionId) { } public record Item(int itemId, int typeId, String name, long duration, long roleId) { + @Override + public String toString() { + return "Item{" + + "itemId=" + itemId + + ", typeId=" + typeId + + ", name='" + name + '\'' + + ", duration=" + duration + + ", roleId=" + roleId + + '}'; + } } public record Transaction(int transactionId, long userId, int itemId, int typeId, String name, long duration, long expiresAt, long roleId, boolean isPlayActivity) { + + @Override + public String toString() { + return "Transaction{" + + "transactionId=" + transactionId + + ", userId=" + userId + + ", itemId=" + itemId + + ", typeId=" + typeId + + ", name='" + name + '\'' + + ", duration=" + duration + + ", expiresAt=" + expiresAt + + ", roleId=" + roleId + + ", isPlayActivity=" + isPlayActivity + + '}'; + } } } diff --git a/src/main/java/com/github/kaktushose/nplaybot/karma/KarmaService.java b/src/main/java/com/github/kaktushose/nplaybot/karma/KarmaService.java index 001989d..46222c0 100644 --- a/src/main/java/com/github/kaktushose/nplaybot/karma/KarmaService.java +++ b/src/main/java/com/github/kaktushose/nplaybot/karma/KarmaService.java @@ -43,7 +43,7 @@ public KarmaService(DataSource dataSource, RankService rankService, ItemService } public void setKarma(UserSnowflake user, int karma) { - log.debug("Setting karma of {} to {}", user, karma); + log.info("Setting karma of {} to {}", user, karma); try (var connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" UPDATE users @@ -60,7 +60,7 @@ public void setKarma(UserSnowflake user, int karma) { } public void addKarma(UserSnowflake user, int karma) { - log.debug("Increasing karma points of {} by {}", user, karma); + log.info("Increasing karma points of {} by {}", user, karma); try (var connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" UPDATE users @@ -84,6 +84,7 @@ public void onKarmaIncrease(int oldKarma, int newKarma, Member member, EmbedCach return; } + log.info("User {} has enough karma for Play Activity", member); itemService.addPlayActivity(member); itemService.updateLastKarma(member); @@ -118,6 +119,7 @@ public void onKarmaIncrease(int oldKarma, int newKarma, Member member, EmbedCach .addEmbeds(EmbedBuilder.fromData(DataObject.fromJson(reward.embed())).build()) .build(); bot.getDatabase().getSettingsService().getBotChannel().sendMessage(builder).queue(); + log.info("Member {} received a karma reward {}", member, reward); } public void onKarmaDecrease(int oldKarma, int newKarma, Member member, EmbedCache embedCache) { @@ -149,6 +151,7 @@ public void onKarmaDecrease(int oldKarma, int newKarma, Member member, EmbedCach .build() ).build(); bot.getDatabase().getSettingsService().getBotChannel().sendMessage(builder).queue(); + log.info("Removed karma reward {} from user {}", reward, member); } public void resetTokens() { @@ -163,7 +166,7 @@ public void resetTokens() { } public void decreaseTokens(UserSnowflake user, int decrease) { - log.debug("Decreasing karma tokens of {} by {}", user, decrease); + log.info("Decreasing karma tokens of {} by {}", user, decrease); try (var connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" UPDATE users @@ -180,7 +183,7 @@ public void decreaseTokens(UserSnowflake user, int decrease) { } public int onKarmaVoteAdd(UserSnowflake author, UserSnowflake target, boolean decreaseTokens) { - log.debug("Performing karma vote of {} for {}", author, target); + log.info("Performing karma vote of {} for {}", author, target); try (var connection = dataSource.getConnection()) { if (getUserTokens(author) > 0) { addKarma(target, 1); @@ -202,7 +205,7 @@ public int onKarmaVoteAdd(UserSnowflake author, UserSnowflake target, boolean de } public int onKarmaVoteRemove(UserSnowflake author, UserSnowflake target, boolean decreaseTokens) { - log.debug("Removing karma vote of {} for {}", author, target); + log.info("Removing karma vote of {} for {}", author, target); try (var connection = dataSource.getConnection()) { if (getUserTokens(author) > 0) { addKarma(target, -1); @@ -243,7 +246,7 @@ public int getUserTokens(UserSnowflake user) { } public int getDefaultTokens() { - log.debug("Querying default karma tokens for guild {}", guild); + log.debug("Querying default karma tokens"); try (var connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" SELECT default_tokens @@ -262,7 +265,7 @@ public int getDefaultTokens() { } public void setDefaultTokens(int value) { - log.debug("Setting default karma tokens for guild {}", guild); + log.info("Setting default karma tokens, new value {}", value); try (var connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" UPDATE karma_settings @@ -280,7 +283,7 @@ public void setDefaultTokens(int value) { } public List getValidUpvoteEmojis() { - log.debug("Querying valid karma emojis for guild {}", guild); + log.debug("Querying valid karma emojis"); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" SELECT valid_emojis_upvote @@ -300,7 +303,7 @@ public List getValidUpvoteEmojis() { } public List getValidDownvoteEmojis() { - log.debug("Querying valid karma emojis for guild {}", guild); + log.debug("Querying valid karma emojis"); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" SELECT valid_emojis_downvote @@ -320,7 +323,7 @@ public List getValidDownvoteEmojis() { } public void createKarmaReward(String name, int threshold, int xp, Role role, String embed) { - log.debug("Creating new karma reward"); + log.info("Creating new karma reward"); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement("INSERT INTO karma_rewards(name, threshold, xp, role_id, embed) VALUES (?, ?, ?, ?, CAST (? AS jsonb))"); statement.setString(1, name); @@ -359,7 +362,7 @@ public List getKarmaRewards() { } public void deleteKarmaReward(int rewardId) { - log.debug("Deleting karma reward with id {}", rewardId); + log.info("Deleting karma reward with id {}", rewardId); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement("DELETE FROM karma_rewards WHERE reward_id = ?"); statement.setInt(1, rewardId); @@ -370,5 +373,16 @@ public void deleteKarmaReward(int rewardId) { } public record KarmaReward(int rewardId, String name, int threshold, int xp, long roleId, String embed) { + @Override + public String toString() { + return "KarmaReward{" + + "rewardId=" + rewardId + + ", name='" + name + '\'' + + ", threshold=" + threshold + + ", xp=" + xp + + ", roleId=" + roleId + + ", embed='" + embed + '\'' + + '}'; + } } } diff --git a/src/main/java/com/github/kaktushose/nplaybot/permissions/PermissionsService.java b/src/main/java/com/github/kaktushose/nplaybot/permissions/PermissionsService.java index 1f7fbbd..7cc313e 100644 --- a/src/main/java/com/github/kaktushose/nplaybot/permissions/PermissionsService.java +++ b/src/main/java/com/github/kaktushose/nplaybot/permissions/PermissionsService.java @@ -116,18 +116,26 @@ public boolean hasUserPermissions(Member member) { } public boolean hasPermissions(Member member, String... permissions) { - log.debug("Checking permissions for member {}", member); + log.debug("Checking permissions {} for member {}", permissions, member); return hasPermissions(member, Set.of(permissions)); } public boolean hasPermissions(Member member, Set permissions) { - log.debug("Checking permissions for member {}", member); - return BotPermissions.hasPermissions(permissions, getMemberPermissions(member)); + log.debug("Checking permissions {} for member {}", permissions, member); + var hasPerms = BotPermissions.hasPermissions(permissions, getMemberPermissions(member)); + if (!hasPerms) { + log.info("Denying access for user {} due to missing permissions", member); + } + return hasPerms; } public boolean hasPermissions(User user, Set permissions) { - log.debug("Checking permissions for user {}", user); - return BotPermissions.hasPermissions(permissions, getUserPermissions(user)); + log.debug("Checking permissions {} for user {}", permissions, user); + var hasPerms = BotPermissions.hasPermissions(permissions, getUserPermissions(user)); + if (!hasPerms) { + log.info("Denying access for user {} due to missing permissions", user); + } + return hasPerms; } } diff --git a/src/main/java/com/github/kaktushose/nplaybot/rank/LootboxListener.java b/src/main/java/com/github/kaktushose/nplaybot/rank/LootboxListener.java index 97f937a..a1a7302 100644 --- a/src/main/java/com/github/kaktushose/nplaybot/rank/LootboxListener.java +++ b/src/main/java/com/github/kaktushose/nplaybot/rank/LootboxListener.java @@ -8,6 +8,8 @@ import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder; import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; @@ -15,6 +17,7 @@ public class LootboxListener extends ListenerAdapter { + private static final Logger log = LoggerFactory.getLogger(LootboxListener.class); private static final String LOOTBOX_EMOJI = "\uD83C\uDF81"; private static final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); private final Bot bot; @@ -30,6 +33,7 @@ private LootboxListener(Bot bot, RankService.Lootbox lootbox, UserSnowflake user this.messageId = message.getIdLong(); this.isPrivate = isPrivate; bot.getJda().addEventListener(this); + log.debug("Creating new lootbox listener: Lootbox={}, user={}, message = {}, isPrivate={}", lootbox, user, message, isPrivate); message.addReaction(Emoji.fromFormatted(LOOTBOX_EMOJI)).queue(); executor.schedule(() -> terminate(message), 30, TimeUnit.MINUTES); } @@ -68,6 +72,8 @@ public void onMessageReactionAdd(@NotNull MessageReactionAddEvent event) { event.getReaction().clearReactions().queue(); + log.info("Lootbox {} got claimed by {}", event.getMessageId(), event.getMember()); + if (lootbox.xpReward() > 0) { var result = bot.getDatabase().getRankService().addXp(target, lootbox.xpReward()); bot.getDatabase().getRankService().onXpChange(result, event.getMember(), bot.getEmbedCache()); @@ -109,6 +115,7 @@ public void onMessageReactionAdd(@NotNull MessageReactionAddEvent event) { } private void terminate(Message message) { + log.info("Removing unclaimed lootbox listener for message: {}", message); message.clearReactions().queue(); bot.getJda().removeEventListener(this); } diff --git a/src/main/java/com/github/kaktushose/nplaybot/rank/RankDecayTask.java b/src/main/java/com/github/kaktushose/nplaybot/rank/RankDecayTask.java index 8c19ad2..0970115 100644 --- a/src/main/java/com/github/kaktushose/nplaybot/rank/RankDecayTask.java +++ b/src/main/java/com/github/kaktushose/nplaybot/rank/RankDecayTask.java @@ -29,7 +29,9 @@ public void accept(Bot bot) { log.info("Checking for rank decay"); rankService.getUsersForRankDecay().forEach(user -> { + log.info("Checking user {}", user); if ((System.currentTimeMillis() - user.lastValidMessage()) < TimeUnit.DAYS.toMillis(rankDecayInterval)) { + log.info("User was active. Check done"); return; } @@ -53,8 +55,10 @@ public void accept(Bot bot) { var minimumRank = bot.getDatabase().getRankService().getRankInfo(startDecayRankId); result = bot.getDatabase().getRankService().setXp(userSnowflake, minimumRank.orElseThrow().xpBound()); } + log.info("Decaying user {}, new rank: {}, current xp: {}", user, result.currentRank(), result.currentXp()); bot.getGuild().retrieveMemberById(user.id()).queue(member -> bot.getDatabase().getRankService().onXpChange(result, member, bot.getEmbedCache())); + log.info("Check done"); }); } } diff --git a/src/main/java/com/github/kaktushose/nplaybot/rank/RankListener.java b/src/main/java/com/github/kaktushose/nplaybot/rank/RankListener.java index 8b7830b..f475545 100644 --- a/src/main/java/com/github/kaktushose/nplaybot/rank/RankListener.java +++ b/src/main/java/com/github/kaktushose/nplaybot/rank/RankListener.java @@ -196,6 +196,8 @@ private void onCollectPointChange(int oldPoints, int newPoints, Member member, G .addEmbeds(EmbedBuilder.fromData(DataObject.fromJson(reward.embed())).build()) .build(); settingsService.getBotChannel().sendMessage(builder).queue(); + + log.info("Member {} received a collect reward {}", member, reward); } private void onCollectLootDrop(MessageReceivedEvent event) { @@ -205,7 +207,7 @@ private void onCollectLootDrop(MessageReceivedEvent event) { log.debug("No collect loot drop for this message"); return; } - + log.info("Creating collect loot drop for message {}, points: {}", event.getMessageId(), points); collectLootDrops.add(event.getMessageIdLong()); event.getMessage().addReaction(Emoji.fromUnicode(eventService.getCollectCurrency().emoji())).queue(); } @@ -232,7 +234,7 @@ private void onCollectEventDropReactionAdd(MessageReactionAddEvent event) { return; } - log.debug("Collect loot drop got claimed by {}", event.getMember()); + log.info("Collect loot drop {} got claimed by {}", event.getMessageId(), event.getMember()); var oldPoints = eventService.getCollectPoints(event.getMember()); var newPoints = eventService.addCollectPoint(event.getMember()); diff --git a/src/main/java/com/github/kaktushose/nplaybot/rank/RankService.java b/src/main/java/com/github/kaktushose/nplaybot/rank/RankService.java index 3ff6ea6..e6da131 100644 --- a/src/main/java/com/github/kaktushose/nplaybot/rank/RankService.java +++ b/src/main/java/com/github/kaktushose/nplaybot/rank/RankService.java @@ -35,7 +35,7 @@ public RankService(DataSource dataSource, ItemService itemService, Bot bot) { } public boolean createUser(UserSnowflake user) { - log.debug("Inserting user: {}", user); + log.info("Inserting new user: {}", user); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement("INSERT INTO users VALUES(?) ON CONFLICT DO NOTHING RETURNING user_id"); statement.setLong(1, user.getIdLong()); @@ -47,7 +47,7 @@ public boolean createUser(UserSnowflake user) { } public void removeUser(UserSnowflake user) { - log.debug("Deleting user: {}", user); + log.info("Deleting user: {}", user); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement("DELETE FROM users WHERE user_id = ?"); statement.setLong(1, user.getIdLong()); @@ -111,7 +111,7 @@ public UserInfo getUserInfo(UserSnowflake user) { } public RankConfig getRankConfig() { - log.debug("Querying rank config for guild: {}", guild); + log.debug("Querying rank config"); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" SELECT message_cooldown, min_message_length, xp_loot_chance @@ -135,7 +135,7 @@ public RankConfig getRankConfig() { } public void updateCooldown(int cooldown) { - log.debug("Updating cooldown for guild: {}", guild); + log.info("Updating cooldown, new value {}", cooldown); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" UPDATE rank_settings @@ -153,7 +153,7 @@ public void updateCooldown(int cooldown) { } public void updateMinMessageLength(int length) { - log.debug("Updating minimum message length for guild: {}", guild); + log.info("Updating minimum message length, new value {}", length); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" UPDATE rank_settings @@ -171,7 +171,7 @@ public void updateMinMessageLength(int length) { } public void updateXpLootChance(double chance) { - log.debug("Updating xp loot chance for guild: {}", guild); + log.info("Updating xp loot chance for guild, new value {}", chance); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" UPDATE rank_settings @@ -189,7 +189,7 @@ public void updateXpLootChance(double chance) { } public Set getValidChannels() { - log.debug("Querying valid channels for guild {}", guild); + log.debug("Querying valid channels"); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" SELECT valid_channels @@ -208,7 +208,7 @@ public Set getValidChannels() { } public void updateValidChannels(Set validChannels) { - log.debug("Querying valid channels for guild {}", guild); + log.debug("Querying valid channels"); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" UPDATE rank_settings @@ -301,7 +301,7 @@ public XpChangeResult addRandomXp(UserSnowflake user) { } public XpChangeResult addXp(UserSnowflake user, int amount) { - log.debug("Adding {} xp to {}", amount, user); + log.info("Adding {} xp to {}", amount, user); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement("SELECT * FROM add_xp(?, ?)"); statement.setLong(1, user.getIdLong()); @@ -322,7 +322,7 @@ public XpChangeResult addXp(UserSnowflake user, int amount) { } public XpChangeResult setXp(UserSnowflake user, int value) { - log.debug("Setting xp of user {} to {}", user, value); + log.info("Setting xp of user {} to {}", user, value); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement("SELECT * FROM set_xp(?, ?)"); statement.setLong(1, user.getIdLong()); @@ -343,13 +343,13 @@ public XpChangeResult setXp(UserSnowflake user, int value) { } public void onXpChange(XpChangeResult result, Member member, EmbedCache embedCache) { - log.debug("Checking for rank up: {}", member); + log.info("Checking for rank change: {}", member); if (!result.rankChanged()) { - log.debug("Rank hasn't changed"); + log.info("Rank hasn't changed"); return; } - log.debug("Applying changes. New rank: {}", result.currentRank()); + log.info("Applying changes. Previous rank: {}, New rank: {}", result.previousRank(), result.currentRank()); if (result.previousRank().isPresent()) { if (result.currentRank().rankId() < result.previousRank().get().rankId()) { @@ -358,6 +358,7 @@ public void onXpChange(XpChangeResult result, Member member, EmbedCache embedCac .addEmbeds(embedCache.getEmbed(embed).injectValues(result.getEmbedValues(member)).toMessageEmbed()) .build(); bot.getDatabase().getSettingsService().getBotChannel().sendMessage(message).queue(); + log.info("Rank change done"); return; } } @@ -366,6 +367,7 @@ public void onXpChange(XpChangeResult result, Member member, EmbedCache embedCac String reward = "keine Belohnung"; if (result.currentRank().lootboxReward()) { lootbox = Optional.of(getRandomLootbox()); + log.info("Rank up reward: {}", lootbox.get()); reward = "\uD83C\uDF81 eine Lootbox"; } else { lootbox = Optional.empty(); @@ -377,6 +379,7 @@ public void onXpChange(XpChangeResult result, Member member, EmbedCache embedCac var item = itemService.getItem(result.currentRank().itemRewardId()); var emoji = bot.getDatabase().getItemService().getTypeEmoji(item.typeId()); reward = String.format("%s %s", emoji, item.name()); + log.info("Rank up reward: {}", item); } updateRankRoles(member, result.currentRank(), itemRole); @@ -389,9 +392,11 @@ public void onXpChange(XpChangeResult result, Member member, EmbedCache embedCac bot.getDatabase().getSettingsService().getBotChannel().sendMessage(message).queue(msg -> lootbox.ifPresent(it -> LootboxListener.newListener(bot, it, member, msg, true)) ); + log.info("Rank change done"); } public Lootbox getRandomLootbox() { + log.debug("Querying random lootbox"); try (Connection connection = dataSource.getConnection()) { var result = connection.prepareStatement("SELECT * FROM get_random_lootbox()").executeQuery(); result.next(); @@ -412,6 +417,7 @@ public Lootbox getRandomLootbox() { } public Optional getRankByXp(int xp) { + log.debug("Querying rank for xp {}", xp); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement("SELECT * FROM ranks WHERE ? >= bound ORDER BY bound DESC LIMIT 1"); statement.setInt(1, xp); @@ -435,7 +441,7 @@ public void updateRankRoles(Member member, RankInfo currentRank, Optional .map(guild::getRoleById) .filter(it -> it != validRole) .toList(); - log.debug("Updating roles for {}. Valid role: {}, invalid Roles {}", member, validRole, invalidRoles); + log.info("Updating roles for {}. Valid role: {}, invalid Roles {}", member, validRole, invalidRoles); guild.modifyMemberRoles(member, List.of(validRole, itemRole.get()), invalidRoles).queue(); } @@ -445,7 +451,7 @@ public void updateRankRoles(Member member, RankInfo currentRank) { .map(guild::getRoleById) .filter(it -> it != validRole) .toList(); - log.debug("Updating roles for {}. Valid role: {}, invalid Roles {}", member, validRole, invalidRoles); + log.info("Updating roles for {}. Valid role: {}, invalid Roles {}", member, validRole, invalidRoles); guild.modifyMemberRoles(member, List.of(validRole), invalidRoles).queue(); } @@ -499,7 +505,7 @@ public List getLeaderboard() { } public void resetDailyStatistics() { - log.debug("Resetting start_xp for all users"); + log.info("Resetting start_xp for all users"); try (Connection connection = dataSource.getConnection()) { connection.prepareStatement("UPDATE users SET start_xp = xp").execute(); } catch (SQLException e) { @@ -508,7 +514,7 @@ public void resetDailyStatistics() { } public void updateStatistics() { - log.debug("Resetting start_xp for all users"); + log.info("Updating rank statistics"); try (Connection connection = dataSource.getConnection()) { connection.prepareStatement("SELECT * FROM update_rank_statistics()").execute(); } catch (SQLException e) { @@ -526,7 +532,7 @@ public void increaseTotalMessageCount() { } public void switchDaily(UserSnowflake user, boolean enabled) { - log.debug("Setting daily message for user {} to {}", user, enabled); + log.info("Setting daily message for user {} to {}", user, enabled); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement("UPDATE users SET daily_message = ? where user_id = ?"); statement.setBoolean(1, enabled); @@ -610,6 +616,7 @@ public boolean isValidChannel(MessageChannelUnion channel) { } public int getStartDecayRankId() { + log.debug("Querying start decay rank id"); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" SELECT rank_decay_start @@ -628,6 +635,7 @@ public int getStartDecayRankId() { } public int getDecayXp() { + log.debug("Querying decay xp"); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" SELECT rank_decay_xp_loss @@ -646,6 +654,7 @@ public int getDecayXp() { } public int getLootboxChance() { + log.debug("Querying lootbox chance"); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" SELECT lootbox_chance @@ -664,6 +673,7 @@ public int getLootboxChance() { } public int getLootboxQueryLimit() { + log.debug("Querying lootbox_query_limit"); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" SELECT lootbox_query_limit @@ -682,6 +692,7 @@ public int getLootboxQueryLimit() { } public long getLastDecay() { + log.debug("Querying last rank decay date"); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" SELECT last_rank_decay @@ -700,6 +711,7 @@ public long getLastDecay() { } public void updateLastDecay() { + log.debug("Updating last rank decay date"); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" UPDATE rank_settings @@ -717,6 +729,7 @@ public void updateLastDecay() { } public List getUsersForRankDecay() { + log.debug("Querying users eligible for rank decay"); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" SELECT users.* FROM users @@ -739,6 +752,7 @@ public List getUsersForRankDecay() { } public int getRankDecayInterval() { + log.debug("Querying rank decay interval"); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" SELECT rank_decay_interval @@ -757,6 +771,15 @@ public int getRankDecayInterval() { } public record Lootbox(int id, int xpReward, int karmaReward, int itemId) { + @Override + public String toString() { + return "Lootbox{" + + "id=" + id + + ", xpReward=" + xpReward + + ", karmaReward=" + karmaReward + + ", itemId=" + itemId + + '}'; + } } } diff --git a/src/main/java/com/github/kaktushose/nplaybot/rank/daily/DailyMessageTask.java b/src/main/java/com/github/kaktushose/nplaybot/rank/daily/DailyMessageTask.java index 8b09fdc..0ccdc61 100644 --- a/src/main/java/com/github/kaktushose/nplaybot/rank/daily/DailyMessageTask.java +++ b/src/main/java/com/github/kaktushose/nplaybot/rank/daily/DailyMessageTask.java @@ -5,20 +5,26 @@ import net.dv8tion.jda.api.entities.UserSnowflake; import net.dv8tion.jda.api.exceptions.ErrorHandler; import net.dv8tion.jda.api.requests.ErrorResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.concurrent.TimeUnit; public class DailyMessageTask { + private static final Logger log = LoggerFactory.getLogger(DailyMessageTask.class); + @ScheduledTask(period = 24, unit = TimeUnit.HOURS, startAtMidnight = true) public void onSendDailyMessages(Bot bot) { - bot.getDatabase().getRankService().getDailyRankInfos().forEach(user -> - bot.getGuild().retrieveMember(UserSnowflake.fromId(user.id())).queue(member -> - member.getUser().openPrivateChannel().flatMap(channel -> channel.sendMessage( - bot.getEmbedCache().getEmbed(user.nextRank().isPresent() ? "rankInfo" : "rankInfoMax") - .injectValues(user.getEmbedValues(member.getUser(), true)).toMessageCreateData() - )).queue(), new ErrorHandler().ignore(ErrorResponse.UNKNOWN_MEMBER)) + bot.getDatabase().getRankService().getDailyRankInfos().forEach(user -> { + log.info("Sending daily info message to user {}", user); + bot.getGuild().retrieveMember(UserSnowflake.fromId(user.id())).queue(member -> + member.getUser().openPrivateChannel().flatMap(channel -> channel.sendMessage( + bot.getEmbedCache().getEmbed(user.nextRank().isPresent() ? "rankInfo" : "rankInfoMax") + .injectValues(user.getEmbedValues(member.getUser(), true)).toMessageCreateData()) + ).queue(), new ErrorHandler().ignore(ErrorResponse.UNKNOWN_MEMBER) + ); + } ); } - } diff --git a/src/main/java/com/github/kaktushose/nplaybot/starboard/StarboardListener.java b/src/main/java/com/github/kaktushose/nplaybot/starboard/StarboardListener.java index a356fe8..23c7292 100644 --- a/src/main/java/com/github/kaktushose/nplaybot/starboard/StarboardListener.java +++ b/src/main/java/com/github/kaktushose/nplaybot/starboard/StarboardListener.java @@ -21,6 +21,8 @@ import net.dv8tion.jda.api.utils.messages.MessageCreateData; import net.dv8tion.jda.api.utils.messages.MessageEditData; import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Optional; import java.util.Set; @@ -30,6 +32,7 @@ public class StarboardListener extends ListenerAdapter { + private static final Logger log = LoggerFactory.getLogger(StarboardListener.class); private final StarboardService starboardService; private final KarmaService karmaService; private final RankService rankService; @@ -221,6 +224,7 @@ private MessageCreateData buildMessage(Message message, int count) { } private void removeEntry(GenericMessageEvent event) { + log.info("Deleting starboard post {}", event.getMessageIdLong()); event.getGuild().getTextChannelById(starboardService.getStarboardChannelId()) .retrieveMessageById(starboardService.getPostId(event.getMessageIdLong())) .flatMap(Message::delete) diff --git a/src/main/java/com/github/kaktushose/nplaybot/starboard/StarboardService.java b/src/main/java/com/github/kaktushose/nplaybot/starboard/StarboardService.java index 5cab131..ee958e6 100644 --- a/src/main/java/com/github/kaktushose/nplaybot/starboard/StarboardService.java +++ b/src/main/java/com/github/kaktushose/nplaybot/starboard/StarboardService.java @@ -21,7 +21,7 @@ public StarboardService(DataSource dataSource, Bot bot) { } public boolean entryExists(long messageId) { - log.debug("Checking if starboard entry exists"); + log.debug("Checking if starboard entry {} exists", messageId); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement("SELECT EXISTS(SELECT 1 FROM starboard_entries WHERE message_id = ?)"); statement.setLong(1, messageId); @@ -34,7 +34,7 @@ public boolean entryExists(long messageId) { } public void createEntry(long messageId) { - log.debug("Creating starboard entry"); + log.info("Creating starboard entry for message {}", messageId); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement("INSERT INTO starboard_entries VALUES(?)"); statement.setLong(1, messageId); @@ -45,7 +45,7 @@ public void createEntry(long messageId) { } public boolean isRewarded(long messageId) { - log.debug("Querying starboard votes"); + log.debug("Checking if entry {} already got rewarded", messageId); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" SELECT is_rewarded @@ -63,7 +63,7 @@ public boolean isRewarded(long messageId) { } public void setRewarded(long messageId) { - log.debug("Querying starboard votes"); + log.info("Marking entry {} as rewarded", messageId); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" UPDATE starboard_entries @@ -79,7 +79,7 @@ public void setRewarded(long messageId) { } public long getPostId(long messageId) { - log.debug("Querying starboard post id"); + log.debug("Querying starboard post {}", messageId); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" SELECT post_id @@ -97,7 +97,7 @@ public long getPostId(long messageId) { } public void setPostId(long messageId, long postId) { - log.debug("Setting starboard post id"); + log.info("Setting starboard post id to {} for entry {}", postId, messageId); try (Connection connection = dataSource.getConnection()) { var statement = connection.prepareStatement(""" UPDATE starboard_entries