Skip to content

Commit

Permalink
Added Sharding
Browse files Browse the repository at this point in the history
  • Loading branch information
beanbeanjuice committed Aug 5, 2024
1 parent dd99d65 commit 843d0ef
Show file tree
Hide file tree
Showing 15 changed files with 75 additions and 97 deletions.
2 changes: 1 addition & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ tasks.clean {
dependencies {
implementation(project(":wrappers:cafe-api-wrapper"))

implementation("net.dv8tion", "JDA", "5.0.0-beta.24") { exclude(module = "opus-java") }
implementation("net.dv8tion", "JDA", "5.0.1") { exclude(module = "opus-java") }

implementation("org.apache.logging.log4j", "log4j-api", "2.23.1")
implementation("org.apache.logging.log4j", "log4j-core", "2.23.1")
Expand Down
95 changes: 52 additions & 43 deletions src/main/java/com/beanbeanjuice/cafebot/CafeBot.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,18 +50,15 @@
import lombok.Getter;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.OnlineStatus;
import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.requests.GatewayIntent;
import net.dv8tion.jda.api.requests.restaction.CacheRestAction;
import net.dv8tion.jda.api.requests.RestAction;
import net.dv8tion.jda.api.sharding.DefaultShardManagerBuilder;
import net.dv8tion.jda.api.sharding.ShardManager;
import net.dv8tion.jda.api.utils.ChunkingFilter;
import net.dv8tion.jda.api.utils.MemberCachePolicy;
import org.jetbrains.annotations.NotNull;

import java.awt.*;
import java.io.IOException;
Expand All @@ -82,7 +79,7 @@ public class CafeBot {
// Bot Items
@Getter private final String botVersion = getVersion();
@Getter private final String botUserAgent = "java:com.beanbeanjuice.cafeBot:" + botVersion;
@Getter private final JDA JDA;
@Getter private final ShardManager shardManager;

// API
@Getter private final CafeAPI cafeAPI;
Expand Down Expand Up @@ -125,7 +122,7 @@ public CafeBot() throws InterruptedException {
this.logger.addWebhookURL(EnvironmentVariable.CAFEBOT_GUILD_WEBHOOK_URL.getSystemVariable());
this.logger.log(CafeBot.class, LogLevel.OKAY, "Starting bot!", true, false);

this.JDA = JDABuilder
this.shardManager = DefaultShardManagerBuilder
.createDefault(EnvironmentVariable.CAFEBOT_TOKEN.getSystemVariable())
.setActivity(Activity.playing("The barista is starting..."))
.setStatus(OnlineStatus.IDLE)
Expand All @@ -135,21 +132,17 @@ public CafeBot() throws InterruptedException {
GatewayIntent.DIRECT_MESSAGES,
GatewayIntent.MESSAGE_CONTENT
)
// .enableCache(
// CacheFlag.EMOJI
// )
.setMemberCachePolicy(MemberCachePolicy.ALL) // ! - Needed for mutual guilds
.setChunkingFilter(ChunkingFilter.ALL) // ! - Needed for mutual guilds
.build()
.awaitReady();
.build();

logger.log(CafeBot.class, LogLevel.INFO, "Checking servers...");
this.checkGuilds();

this.logger.enableDiscordLogging();
logger.log(CafeBot.class, LogLevel.INFO, "Enabled Discord Logging...", true, true);

JDA.getPresence().setStatus(OnlineStatus.ONLINE);
this.shardManager.setStatus(OnlineStatus.ONLINE);
logger.log(CafeBot.class, LogLevel.OKAY, "The bot is online!");

logger.log(CafeBot.class, LogLevel.INFO, "Adding commands...");
Expand All @@ -158,16 +151,15 @@ public CafeBot() throws InterruptedException {

setupListeners();

this.JDA.getGuilds();

this.startUpdateTimer();
this.startBioUpdateTimer();
}

// TODO: Does this only get it from cache?
private void checkGuilds() {
GuildsEndpoint guildsEndpoint = this.cafeAPI.getGuildsEndpoint();
guildsEndpoint.getAllGuildInformation().thenAcceptAsync((information) -> {
this.JDA.getGuilds().forEach((guild) -> {
this.shardManager.getGuilds().forEach((guild) -> {
if (information.containsKey(guild.getId())) return;

guildsEndpoint.createGuildInformation(guild.getId());
Expand Down Expand Up @@ -278,7 +270,7 @@ private void setupCommands() {
new CustomChannelsCommand(this)
);

this.JDA.addEventListener(commandHandler);
this.shardManager.addEventListener(commandHandler);
this.helpHandler = new HelpHandler(commandHandler);
this.twitchHandler = new TwitchHandler(EnvironmentVariable.CAFEBOT_TWITCH_ACCESS_TOKEN.getSystemVariable(), this);

Expand All @@ -293,12 +285,12 @@ private void setupCommands() {
}

public void addEventListener(final ListenerAdapter listener) {
this.JDA.addEventListener(listener);
this.shardManager.addEventListener(listener);
}

private void setupListeners() {
this.aiResponseListener = new AIResponseListener(this);
this.JDA.addEventListener(
this.shardManager.addEventListener(
new BotAddListener(this),
new BotRemoveListener(this),
new CountingListener(this),
Expand Down Expand Up @@ -333,9 +325,7 @@ public void run() {
bot.getLogger().log(CafeBot.class, LogLevel.DEBUG, "Sending bot status message...", true, false);

bot.getUser("690927484199370753").queue((owner) -> {
bot.getJDA().getRestPing().queue((ping) -> {
bot.pmUser(owner, getUpdateEmbed(ping, bot.getJDA().getGatewayPing()));
});
bot.pmUser(owner, getUpdateEmbed(bot.getShardManager().getAverageGatewayPing()));
});
}
};
Expand All @@ -360,58 +350,73 @@ public void run() {
case 3 -> finalString = "Serving " + getTotalUsers() + " customers!";
}

bot.getJDA().getPresence().setActivity(Activity.playing(initialString + finalString));
bot.getShardManager().setActivity(Activity.customStatus(initialString + finalString));
}
};
timer.scheduleAtFixedRate(timerTask, 0, TimeUnit.MINUTES.toMillis(1));
}

private MessageEmbed getUpdateEmbed(@NotNull Long botPing, @NotNull Long gatewayPing) {
public MessageEmbed getUpdateEmbed(final double gatewayPing) {
EmbedBuilder embedBuilder = new EmbedBuilder();
StringBuilder descriptionBuilder = new StringBuilder();
double cpuLoad = (double) Math.round((ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class).getCpuLoad()*100) * 100) / 100;
long systemMemoryTotal = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class).getTotalMemorySize()/1048576;
long systemMemoryUsage = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class).getCommittedVirtualMemorySize()/1048576;
long dedicatedMemoryTotal = Runtime.getRuntime().maxMemory()/1048576;
long dedicatedMemoryUsage = Runtime.getRuntime().totalMemory()/1048576;

embedBuilder.setTitle("Daily CafeBot Update");
descriptionBuilder.append("**__System Status__**: Online\n\n");
descriptionBuilder.append("**__Rest Ping__** - `").append(botPing).append("`\n")
.append("**__Gateway Ping__** - `").append(gatewayPing).append("`\n")
.append("**__Current Version__** - `").append(this.botVersion).append("`\n")
.append("**__CPU Usage__** - `").append(cpuLoad).append("%`\n")
.append("**__OS Memory Usage__** - `").append(systemMemoryUsage).append("` mb / `").append(systemMemoryTotal).append("` mb\n")
.append("**__Bot Memory Usage__** - `").append(dedicatedMemoryUsage).append("` mb / `").append(dedicatedMemoryTotal).append("` mb\n")
.append("**__Bot Uptime__** - `").append(Helper.formatTimeDays(ManagementFactory.getRuntimeMXBean().getUptime())).append("`\n")
.append("**__Commands Run (After Restart)__** - `").append(this.commandsRun).append("`\n");

embedBuilder.setDescription(descriptionBuilder.toString());

String description = String.format(
"""
**__System Status__**: Online
**__Current Version__** - `%s`
**__Shards__** - `%d`
**__Average Gateway Ping__** - `%.2f` ms
**__CPU Usage__** - `%.2f%%`
**__OS Memory Usage__** - `%d` mb / `%d` mb
**__ Bot Memory Usage__** - `%d` mb / `%d` mb
**__Bot Uptime__** - `%s`
**__Commands Run (Since Restart)__** - `%d`
""",
this.botVersion,
this.shardManager.getShardsTotal(),
gatewayPing,
cpuLoad,
systemMemoryUsage,
systemMemoryTotal,
dedicatedMemoryUsage,
dedicatedMemoryTotal,
Helper.formatTimeDays(ManagementFactory.getRuntimeMXBean().getUptime()),
this.commandsRun);

embedBuilder.setDescription(description);
embedBuilder.setThumbnail(this.discordAvatarUrl);
embedBuilder.setColor(Color.green);
return embedBuilder.build();
}

public int getTotalChannels() {
return this.JDA.getTextChannels().size();
return this.shardManager.getTextChannels().size();
}

public int getTotalServers() {
return this.JDA.getGuilds().size();
return this.shardManager.getGuilds().size();
}

public int getTotalUsers() {
int count = 0;
for (Guild guild : this.JDA.getGuilds()) count += guild.getMemberCount();
for (Guild guild : this.shardManager.getGuilds()) count += guild.getMemberCount();
return count;
}

private CacheRestAction<User> getUser(String userID) {
private RestAction<User> getUser(String userID) {
userID = userID.replace("<@!", "");
userID = userID.replace("<@", ""); // Edge Case for Mobile
userID = userID.replace(">", "");

try {
return this.JDA.retrieveUserById(userID);
return this.shardManager.retrieveUserById(userID);
} catch (NullPointerException | NumberFormatException e) {
this.logger.log(CafeBot.class, LogLevel.ERROR, "Error getting user from cache: " + e.getMessage());
throw e;
Expand All @@ -426,6 +431,10 @@ public void increaseCommandsRun() {
this.commandsRun++;
}

public SelfUser getSelfUser() {
return this.shardManager.getShards().getFirst().getSelfUser();
}

public static void main(String[] args) throws InterruptedException {
new CafeBot();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ private MessageEmbed countingStatisticsEmbed(final CountingInformation countingI
"""
Your current place in the global server leaderboard is \
**%d/%d**.
""", leaderboardPlace, cafeBot.getJDA().getGuilds().size()))
""", leaderboardPlace, cafeBot.getShardManager().getGuilds().size()))
.setColor(Helper.getRandomColor())
.setFooter("These statistics are for the current server only.")
.build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public void handle(SlashCommandInteractionEvent event) {
}

private Button getInviteButton() {
return Button.link(URL.replace("{BOT_ID}", cafeBot.getJDA().getSelfUser().getId()), "Invite")
return Button.link(URL.replace("{BOT_ID}", cafeBot.getSelfUser().getId()), "Invite")
.withEmoji(Emoji.fromFormatted("<a:cafeBot:1119635469727191190>"));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public void handle(SlashCommandInteractionEvent event) {
private MessageEmbed infoEmbed() {
return new EmbedBuilder()
.setColor(Helper.getRandomColor())
.setAuthor("Bot Information", null, cafeBot.getJDA().getSelfUser().getAvatarUrl())
.setAuthor("Bot Information", null, cafeBot.getSelfUser().getAvatarUrl())
.addField("⚙ Commands Run", "```" + cafeBot.getCommandsRun() + "```", true)
.addField("<a:wowowow:886217210010431508> Creator", "```@beanbeanjuice```", true)
.addField("<:html:1000241652444692530> Frameworks", "Built With: [Discord JDA](https://github.com/DV8FromTheWorld/JDA), " +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import com.beanbeanjuice.cafebot.utility.commands.CommandCategory;
import com.beanbeanjuice.cafebot.utility.commands.ICommand;
import com.beanbeanjuice.cafebot.utility.helper.Helper;
import com.sun.management.OperatingSystemMXBean;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.MessageEmbed;
Expand All @@ -14,7 +13,6 @@
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.OptionData;

import java.lang.management.ManagementFactory;
import java.util.Optional;

public class PingCommand extends Command implements ICommand {
Expand All @@ -25,10 +23,8 @@ public PingCommand(final CafeBot cafeBot) {

@Override
public void handle(SlashCommandInteractionEvent event) {
this.cafeBot.getJDA().getRestPing().queue((botPing) -> {
long gatewayPing = this.cafeBot.getJDA().getGatewayPing();
event.getHook().sendMessageEmbeds(messageEmbed(botPing, gatewayPing)).queue();
});
double gatewayPing = this.cafeBot.getShardManager().getAverageGatewayPing();
event.getHook().sendMessageEmbeds(messageEmbed(gatewayPing)).queue();

Optional<OptionMapping> wordOptionMapping = Optional.ofNullable(event.getOption("word"));
Optional<OptionMapping> numberOptionMapping = Optional.ofNullable(event.getOption("number"));
Expand All @@ -52,28 +48,12 @@ public void handle(SlashCommandInteractionEvent event) {
numberOptionMapping.map(OptionMapping::getAsInt).ifPresent((number) -> event.getHook().sendMessage(String.valueOf(number)).queue());
}

private MessageEmbed messageEmbed(final long botPing, final long gatewayPing) {
EmbedBuilder embedBuilder = new EmbedBuilder();
embedBuilder.setTitle("ping!", "https://www.beanbeanjuice.com/cafeBot.html");
StringBuilder descriptionBuilder = new StringBuilder();
double cpuLoad = (double) Math.round((ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class).getCpuLoad()*100) * 100) / 100;
long systemMemoryTotal = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class).getTotalMemorySize()/1048576;
long systemMemoryUsage = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class).getCommittedVirtualMemorySize()/1048576;
long dedicatedMemoryTotal = Runtime.getRuntime().maxMemory()/1048576;
long dedicatedMemoryUsage = Runtime.getRuntime().totalMemory()/1048576;
descriptionBuilder
.append("**Rest Ping** - `").append(botPing).append("`\n")
.append("**Gateway Ping** - `").append(gatewayPing).append("`\n")
.append("**Current Version** - `").append(this.cafeBot.getBotVersion()).append("`\n")
.append("**CPU Usage** - `").append(cpuLoad).append("%`\n")
.append("**OS Memory Usage** - `").append(systemMemoryUsage).append("` mb / `").append(systemMemoryTotal).append("` mb\n")
.append("**Bot Memory Usage** - `").append(dedicatedMemoryUsage).append("` mb / `").append(dedicatedMemoryTotal).append("` mb\n")
.append("**Bot Uptime** - `").append(Helper.millisToDays(ManagementFactory.getRuntimeMXBean().getUptime())).append("`\n")
.append("**Commands Run (After Restart)** - `").append(this.cafeBot.getCommandsRun()).append("`\n")
.append("Hello there! How are you? Would you like to order some coffee?");
private MessageEmbed messageEmbed(final double gatewayPing) {
EmbedBuilder embedBuilder = new EmbedBuilder(this.cafeBot.getUpdateEmbed(gatewayPing));

embedBuilder.setTitle("ping!", "https://www.beanbeanjuice.com/cafeBot.html");
embedBuilder.appendDescription("\n\nHello!~ Would you like to order some coffee?");
embedBuilder
.setDescription(descriptionBuilder.toString())
.setFooter("Author: beanbeanjuice - " + "https://github.com/beanbeanjuice/cafeBot")
.setThumbnail(this.cafeBot.getDiscordAvatarUrl())
.setColor(Helper.getRandomColor());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public void handle(SlashCommandInteractionEvent event) {
private MessageEmbed statsEmbed() {
return new EmbedBuilder()
.setColor(Helper.getRandomColor())
.setAuthor("Bot Statistics", null, cafeBot.getJDA().getSelfUser().getAvatarUrl())
.setAuthor("Bot Statistics", null, cafeBot.getSelfUser().getAvatarUrl())
.addField("<a:cafeBot:1119635469727191190> Total Text Channels", "```" + cafeBot.getTotalChannels() + "```", true)
.addField("<:smartPeepo:1000248538376196280> Total Servers", "```" + cafeBot.getTotalServers() + "```", true)
.addField("⚙ Commands Run (After Restart)", "```" + cafeBot.getCommandsRun() + "```", true)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@ public void addCommands(final ICommand... commands) {
cafeBot.getLogger().log(CommandHandler.class, LogLevel.INFO, "Adding command: /" + newCommand.getName(), false, false);
});

cafeBot.getJDA()
cafeBot.getShardManager()
.getShards()
.getFirst()
.updateCommands()
.addCommands(slashCommands)
.queue((e) -> cafeBot.getLogger().log(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ private void handleDailyResets() {
guildsMap.forEach((guildId, guildInfo) -> {
String dailyChannelID = guildInfo.getSetting(GuildInformationType.DAILY_CHANNEL_ID);

Guild guild = this.cafeBot.getJDA().getGuildById(guildId);
Guild guild = this.cafeBot.getShardManager().getGuildById(guildId);
if (guild == null) return;

TextChannel channel = guild.getTextChannelById(dailyChannelID);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public void checkUpdate() {
this.cafeBot.getCafeAPI().getVersionsEndpoint().updateCurrentCafeBotVersion(gitHubVersion);

this.githubVersionWrapper.getVersion(gitHubVersion).thenAcceptAsync((embed) -> {
this.guildsToNotify.addAll(this.cafeBot.getJDA().getGuilds());
this.guildsToNotify.addAll(this.cafeBot.getShardManager().getGuilds());
handleUpdateNotifications();
});
});
Expand Down
Loading

0 comments on commit 843d0ef

Please sign in to comment.