Skip to content

Commit

Permalink
improve logging
Browse files Browse the repository at this point in the history
  • Loading branch information
Kaktushose committed Aug 8, 2024
1 parent 5032839 commit 2ccede1
Show file tree
Hide file tree
Showing 17 changed files with 231 additions and 77 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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();

Expand All @@ -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
Expand All @@ -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);
Expand All @@ -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
Expand Down Expand Up @@ -185,7 +185,7 @@ public List<CollectReward> 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);
Expand All @@ -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());
Expand All @@ -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
Expand All @@ -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 +
'}';
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -85,7 +85,7 @@ public void startContestEvent(TextChannel channel, String emoji) {
}

public List<ContestLeaderboardRow> 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
Expand Down Expand Up @@ -116,7 +116,7 @@ public List<ContestLeaderboardRow> 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());
Expand All @@ -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);
Expand All @@ -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 != ?");
Expand All @@ -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 != ?");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,17 +43,17 @@ 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();
}
}

@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
Expand Down Expand Up @@ -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();
Expand All @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,23 @@
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
private EmbedCache embedCache;

@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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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
Expand Down Expand Up @@ -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<String> 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();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,16 @@
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;
import java.util.concurrent.TimeUnit;

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;

Expand All @@ -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());
Expand All @@ -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());
}
}

Expand Down
Loading

0 comments on commit 2ccede1

Please sign in to comment.