Merge pull request #18 from GreenLeaf-Gaming/bot_presence

Add bot playing status with online player count
This commit is contained in:
Dennis Heinrich 2025-07-10 17:04:51 +02:00 committed by GitHub
commit 4a18bd53e0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 151 additions and 139 deletions

1
.gitignore vendored
View file

@ -6,3 +6,4 @@ config.json
config.prod.json config.prod.json
config.test.json config.test.json
config.dev.json config.dev.json
.DS_Store

View file

@ -1,7 +1,7 @@
import {Client, EmbedBuilder, Snowflake, TextChannel} from "discord.js"; import { ActivityType, Client, EmbedBuilder, PresenceUpdateStatus, Snowflake, TextChannel } from "discord.js";
import Configuration from "./Configuration"; import Configuration from "./Configuration";
import ServerStatusFeed from "./ServerStatusFeed"; import ServerStatusFeed from "./ServerStatusFeed";
import {Logger} from "winston"; import { Logger } from "winston";
import Logging from "./Logging"; import Logging from "./Logging";
export default class DiscordEmbed { export default class DiscordEmbed {
@ -33,14 +33,19 @@ export default class DiscordEmbed {
private async updateDiscordEmbed(): Promise<void> { private async updateDiscordEmbed(): Promise<void> {
try { try {
await this.serverStatsFeed.updateServerFeed(); await this.serverStatsFeed.updateServerFeed();
if(this.serverStatsFeed.isFetching()) { if (this.serverStatsFeed.isFetching()) {
this.appLogger.info('Server status feed is still fetching, try again...'); this.appLogger.info("Server status feed is still fetching, try again...");
setTimeout(() => { setTimeout(() => {
this.updateDiscordEmbed(); this.updateDiscordEmbed();
}, 1000); }, 1000);
return; return;
} }
this.discordAppClient.channels.fetch(this.appConfiguration.discord.channelId as Snowflake).then(async channel => { this.discordAppClient.user?.setActivity({
name: `with ${this.serverStatsFeed.getPlayerCount() ?? 0} players`,
type: ActivityType.Playing,
});
this.discordAppClient.channels.fetch(this.appConfiguration.discord.channelId as Snowflake).then(async (channel) => {
/** /**
* Send the initial message to the channel (if the first message id is not set) or * Send the initial message to the channel (if the first message id is not set) or
* the message is meanwhile deleted * the message is meanwhile deleted
@ -48,18 +53,21 @@ export default class DiscordEmbed {
*/ */
let sendInitialMessage = (embedMessage: EmbedBuilder) => { let sendInitialMessage = (embedMessage: EmbedBuilder) => {
// noinspection JSAnnotator // noinspection JSAnnotator
(channel as TextChannel).send({embeds: [embedMessage]}).then(message => { (channel as TextChannel).send({ embeds: [embedMessage] }).then((message) => {
this.firstMessageId = message.id; this.firstMessageId = message.id;
}); });
}; };
this.generateEmbedFromStatusFeed(this.serverStatsFeed).then(embedMessage => { this.generateEmbedFromStatusFeed(this.serverStatsFeed).then((embedMessage) => {
if (this.firstMessageId !== null) { if (this.firstMessageId !== null) {
(channel as TextChannel).messages.fetch(this.firstMessageId).then(message => { (channel as TextChannel).messages
.fetch(this.firstMessageId)
.then((message) => {
this.appLogger.info(`Message found, editing message with new embed`); this.appLogger.info(`Message found, editing message with new embed`);
message.edit({embeds: [embedMessage]}); message.edit({ embeds: [embedMessage] });
}).catch(() => { })
this.appLogger.warn('Message not found, sending new message'); .catch(() => {
this.appLogger.warn("Message not found, sending new message");
sendInitialMessage(embedMessage); sendInitialMessage(embedMessage);
}); });
} else { } else {
@ -84,8 +92,8 @@ export default class DiscordEmbed {
private async deleteAllMessages(): Promise<boolean> { private async deleteAllMessages(): Promise<boolean> {
let textChannel = this.discordAppClient.channels.cache.get(this.appConfiguration.discord.channelId as Snowflake) as TextChannel; let textChannel = this.discordAppClient.channels.cache.get(this.appConfiguration.discord.channelId as Snowflake) as TextChannel;
this.appLogger.info(`Deleting all messages in discord text channel ${textChannel.id}`); this.appLogger.info(`Deleting all messages in discord text channel ${textChannel.id}`);
textChannel.messages.fetch().then(messages => { textChannel.messages.fetch().then((messages) => {
messages.forEach(message => { messages.forEach((message) => {
message.delete(); message.delete();
}); });
}); });
@ -99,7 +107,7 @@ export default class DiscordEmbed {
* @returns The truncated string * @returns The truncated string
*/ */
private async truncateText(text: string, maxLength = 1024): Promise<string> { private async truncateText(text: string, maxLength = 1024): Promise<string> {
return text.length > maxLength ? text.slice(0, maxLength - 3) + '...' : text; return text.length > maxLength ? text.slice(0, maxLength - 3) + "..." : text;
} }
/** /**
@ -112,47 +120,50 @@ export default class DiscordEmbed {
embed.setTitle(config.translation.discordEmbed.title); embed.setTitle(config.translation.discordEmbed.title);
if (!serverStats.isOnline()) { if (!serverStats.isOnline()) {
embed.setColor(0xCA0000); embed.setColor(0xca0000);
embed.setDescription(config.translation.discordEmbed.descriptionOffline); embed.setDescription(config.translation.discordEmbed.descriptionOffline);
} else if (serverStats.isFetching()) { } else if (serverStats.isFetching()) {
embed.setDescription(config.translation.discordEmbed.descriptionUnknown); embed.setDescription(config.translation.discordEmbed.descriptionUnknown);
} else { } else {
embed.setColor(0x00CA00); embed.setColor(0x00ca00);
embed.setDescription(config.translation.discordEmbed.descriptionOnline); embed.setDescription(config.translation.discordEmbed.descriptionOnline);
embed.setTimestamp(new Date()); embed.setTimestamp(new Date());
embed.setThumbnail(config.application.serverMapUrl); embed.setThumbnail(config.application.serverMapUrl);
let playerListString: string; let playerListString: string;
let playerListTitleString = `${config.translation.discordEmbed.titlePlayerCount} (${serverStats.getPlayerCount()??0}/${serverStats.getMaxPlayerCount()??0}):`; let playerListTitleString = `${config.translation.discordEmbed.titlePlayerCount} (${serverStats.getPlayerCount() ?? 0}/${serverStats.getMaxPlayerCount() ?? 0}):`;
if(serverStats.getPlayerList().length === 0) { if (serverStats.getPlayerList().length === 0) {
playerListString = config.translation.discordEmbed.noPlayersOnline; playerListString = config.translation.discordEmbed.noPlayersOnline;
} else { } else {
playerListString = serverStats.getPlayerList().map(p => p.username).join(', '); playerListString = serverStats
.getPlayerList()
.map((p) => p.username)
.join(", ");
} }
let serverPassword = config.application.serverPassword; let serverPassword = config.application.serverPassword;
if(config.application.serverPassword == "") { if (config.application.serverPassword == "") {
serverPassword = "-/-"; serverPassword = "-/-";
} }
let serverMods = serverStats.getServerMods(); let serverMods = serverStats.getServerMods();
let serverModsText = "-/-"; let serverModsText = "-/-";
if(serverMods.length > 0) { if (serverMods.length > 0) {
serverModsText = await this.truncateText(serverMods.map(mod => `${mod.name}`).join(', ')); serverModsText = await this.truncateText(serverMods.map((mod) => `${mod.name}`).join(", "));
} }
// @ts-ignore // @ts-ignore
embed.addFields( embed.addFields(
{name: config.translation.discordEmbed.titleServerName, value: serverStats.getServerName()}, { name: config.translation.discordEmbed.titleServerName, value: serverStats.getServerName() },
{name: config.translation.discordEmbed.titleServerPassword, value: serverPassword}, { name: config.translation.discordEmbed.titleServerPassword, value: serverPassword },
{name: config.translation.discordEmbed.titleServerTime, value: serverStats.getServerTime()}, { name: config.translation.discordEmbed.titleServerTime, value: serverStats.getServerTime() },
{name: config.translation.discordEmbed.titleServerMap, value: serverStats.getServerMap()}, { name: config.translation.discordEmbed.titleServerMap, value: serverStats.getServerMap() },
{name: config.translation.discordEmbed.titleServerMods, value: serverModsText}, { name: config.translation.discordEmbed.titleServerMods, value: serverModsText },
{ {
name: playerListTitleString, name: playerListTitleString,
value: playerListString value: playerListString,
}, }
); );
} }
return embed; return embed;