Compare commits

...

5 Commits
main ... alpha

Author SHA1 Message Date
de26cdec44 More debug logging, added dev command to enable debug logging in specific guild (#9)
Reviewed-on: #9
Co-authored-by: Navy.gif <navydotgif@gmail.com>
Co-committed-by: Navy.gif <navydotgif@gmail.com>
2024-07-12 15:28:29 +02:00
a3e6793632 Various fixes
Hopefully prevent danging child processes
Reduce unnecessary db calls in moderation manager
2024-04-01 14:01:30 +03:00
5f07fd3e15 Eval command tweaks 2024-04-01 13:47:28 +03:00
c5c304d5d9 Refactor poll command 2024-04-01 13:47:17 +03:00
bc467e4dd9 Define test workflow 2024-04-01 13:27:47 +03:00
25 changed files with 288 additions and 328 deletions

View File

@ -0,0 +1,26 @@
on:
push:
branches:
- '*'
- '!master'
jobs:
tests:
name: Tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install node
uses: actions/setup-node@v4
with:
node-version: latest
registry-url: https://registry.corgi.wtf
cache: yarn
- name: Install deps
run: yarn install
- name: Lint project
run: yarn run eslint src/
- name: Build project
run: yarn build
env:
CI: false

1
@types/Guild.d.ts vendored
View File

@ -120,6 +120,7 @@ export type GuildData = {
caseId?: number,
settings?: GuildSettings,
premium?: number,
debug?: boolean,
_version?: string,
_imported?: {
[key: string]: boolean | undefined,

View File

@ -69,6 +69,7 @@
"tables": [
"guilds",
"attachments",
"messages",
"permissions",
"webhooks",
"wordwatcher",

View File

@ -210,14 +210,6 @@ class DiscordClient extends Client
this.emit('invalidRequestWarning', ...args);
});
// this.once('ready', () => {
// this._setActivity();
// setInterval(() => {
// this._setActivity();
// }, 1800000); // I think this is 30 minutes. I could be wrong.
// });
this.#loadEevents();
// process.on('uncaughtException', (err) => {
@ -230,7 +222,13 @@ class DiscordClient extends Client
});
process.on('message', this.#handleMessage.bind(this));
process.on('SIGINT', () => this.shutdown());
process.on('SIGINT', () => this.logger.info('Received SIGINT'));
process.on('SIGTERM', () => this.logger.info('Received SIGTERM'));
process.on('disconnect', () =>
{
this.logger.info('Process disconnected from parent for some reason, exiting');
this.shutdown(1);
});
}
async build ()
@ -271,7 +269,7 @@ class DiscordClient extends Client
this.#activityInterval = setInterval(() =>
{
this.setActivity();
}, Util.random(5, 10) * 60 * 60 * 1000);
}, Util.random(5, 10) * 60 * 1000);
}
this.#built = true;
@ -296,6 +294,8 @@ class DiscordClient extends Client
// Handle misc. messages.
if (message._mEvalResult)
this.evalResult(message);
if (message._shutdown)
this.shutdown();
}
// eslint-disable-next-line @typescript-eslint/ban-types
@ -397,6 +397,10 @@ class DiscordClient extends Client
this.user?.setActivity(`${userCount} users`, { type: ActivityType.Listening });
},
async () =>
{
this.user?.setActivity('out for troublemakers', { type: ActivityType.Watching });
},
async () =>
{
this.user?.setActivity('for /help', { type: ActivityType.Listening });
}

View File

@ -0,0 +1,59 @@
import { CommandOptionType, CommandParams } from '../../../../../@types/Client.js';
import DiscordClient from '../../../DiscordClient.js';
import { Command } from '../../../interfaces/index.js';
import InvokerWrapper from '../../wrappers/InvokerWrapper.js';
class DebugCommand extends Command
{
constructor (client: DiscordClient)
{
super(client, {
name: 'debug',
restricted: true,
moduleName: 'developer',
options: [
{ name: 'guild', required: true },
{ name: 'enabled', required: true, type: CommandOptionType.BOOLEAN }
]
});
}
async execute (_invoker: InvokerWrapper, options: CommandParams)
{
const guildId = options.guild!.asString;
return this.enableDebug(guildId, options.enabled?.asBool);
}
async enableDebug (guildId: string, enabled = false)
{
let output = '';
if (this.client.shard)
{
const result = await this.client.shard.broadcastEval(async (client, context) =>
{
const bot = client as DiscordClient;
const wrapper = await bot.getGuildWrapper(context.guildId);
if (!wrapper)
return false;
await wrapper.setDebug(context.enabled);
return `${wrapper.name} (${wrapper.id})`;
}, { context: { guildId, enabled } });
if (!result.some(val => val))
return 'No such guild';
output = result.find(entry => entry) as string;
}
else
{
const wrapper = await this.client.getGuildWrapper(guildId).catch(() => null);
if (!wrapper)
return 'No such guild';
await wrapper.setDebug(enabled);
output = `${wrapper.name} (${wrapper.id})`;
}
return `${enabled ? 'Enabled' : 'Disabled'} debug on **${output}**`;
}
}
export default DebugCommand;

View File

@ -1,7 +1,5 @@
import { userInfo } from 'os';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import { Util, FilterUtil } from '../../../../utilities/index.js';
import { Util as U, FilterUtil as FU } from '../../../../utilities/index.js';
import { inspect } from 'util';
import { CommandOptionType, CommandParams } from '../../../../../@types/Client.js';
import DiscordClient from '../../../DiscordClient.js';
@ -12,6 +10,8 @@ import { ReplyOptions } from '../../../../../@types/Wrappers.js';
const { username } = userInfo();
class EvalCommand extends Command
{
static Util = U;
static FilterUtil = FU;
constructor (client: DiscordClient)
{
super(client, {
@ -32,6 +32,10 @@ class EvalCommand extends Command
if (async?.asBool)
params = `(async () => {${params}})()`;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore // declared for ease of use
const { Util, FilterUtil } = EvalCommand;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore // declared for ease of use
const { guild, author, member, client } = invoker;

View File

@ -8,7 +8,6 @@ import MemberWrapper from '../../wrappers/MemberWrapper.js';
class AddroleCommand extends ModerationCommand
{
constructor (client: DiscordClient)
{
super(client, {
@ -43,12 +42,10 @@ class AddroleCommand extends ModerationCommand
clientPermissions: [ 'ManageRoles' ],
skipOptions: [ 'points', 'expiration', 'force', 'prune' ]
});
}
async execute (invoker: InvokerWrapper<true>, { users, roles, ...args }: CommandParams)
{
if (!users)
throw new CommandError(invoker, { index: 'MODERATION_MISSING_USERS' });
if (!roles)
@ -66,7 +63,6 @@ class AddroleCommand extends ModerationCommand
roles: roles.asString
}
});
}
}

View File

@ -56,12 +56,19 @@ class PollCommand extends SlashCommand
async execute (invoker: InvokerWrapper<true>, { choices, channel, duration, multichoice, message }: CommandParams)
{
const { subcommand, author } = invoker;
const guild = invoker.guild!;
const member = invoker.member!;
const { subcommand } = invoker;
if (subcommand!.name === 'create')
return this.#createPoll(invoker, { choices, channel, duration, multichoice });
else if (subcommand!.name === 'delete')
return this.#deletePoll(invoker, { message });
else if (subcommand!.name === 'end')
return this.#endPoll(invoker, { message });
}
async #createPoll (invoker: InvokerWrapper<true>, { choices, channel, duration, multichoice }: CommandParams)
{
const { guild, member, author } = invoker;
const targetChannel = (channel?.asChannel || invoker.channel) as GuildTextBasedChannel;
if (!targetChannel?.isTextBased())
throw new CommandError(invoker, { index: 'ERR_INVALID_CHANNEL_TYPE' });
@ -118,29 +125,7 @@ class PollCommand extends SlashCommand
await this.client.polls.create(poll, guild.id);
await invoker.editReply({ emoji: 'success', index: 'COMMAND_POLL_START', params: { channel: targetChannel.id } });
}
else if (subcommand!.name === 'delete')
{
const poll = await this.client.polls.delete(message!.asString);
if (!poll)
return { index: 'COMMAND_POLL_404', emoji: 'failure' };
const pollChannel = await guild.resolveChannel<TextChannel>(poll.payload.channel);
if (!pollChannel)
return { index: 'COMMAND_POLL_MISSING_CHANNEL', emoji: 'failure' };
const msg = await pollChannel.messages.fetch(poll.payload.message).catch(() => null);
if (msg)
await msg.delete();
return { index: 'COMMAND_POLL_DELETED', emoji: 'success' };
}
else if (subcommand!.name === 'end')
{
const poll = await this.client.polls.find(message!.asString);
if (!poll)
return { index: 'COMMAND_POLL_404', emoji: 'failure' };
await this.client.polls.end(poll.payload);
// await guild._poll(poll.data as PollData & CallbackData);
return { index: 'COMMAND_POLL_ENDED', emoji: 'success' };
}
}
async #queryQuestions (invoker: InvokerWrapper<true>, choices: number, targetchannel: GuildTextBasedChannel)
{
const { guild, member } = invoker;
@ -166,6 +151,31 @@ class PollCommand extends SlashCommand
}
return questions;
}
async #deletePoll (invoker: InvokerWrapper<true>, { message }: CommandParams)
{
const { guild } = invoker;
const poll = await this.client.polls.delete(message!.asString);
if (!poll)
return { index: 'COMMAND_POLL_404', emoji: 'failure' };
const pollChannel = await guild.resolveChannel<TextChannel>(poll.payload.channel);
if (!pollChannel)
return { index: 'COMMAND_POLL_MISSING_CHANNEL', emoji: 'failure' };
const msg = await pollChannel.messages.fetch(poll.payload.message).catch(() => null);
if (msg)
await msg.delete();
return { index: 'COMMAND_POLL_DELETED', emoji: 'success' };
}
async #endPoll (_invoker: InvokerWrapper<true>, { message }: CommandParams)
{
const poll = await this.client.polls.find(message!.asString);
if (!poll)
return { index: 'COMMAND_POLL_404', emoji: 'failure' };
await this.client.polls.end(poll._id, poll.payload);
// await guild._poll(poll.data as PollData & CallbackData);
return { index: 'COMMAND_POLL_ENDED', emoji: 'success' };
}
}
export default PollCommand;

View File

@ -185,9 +185,9 @@ class CallbackManager implements Initialisable
*
* @async
* @param {string} id
* @returns {*}
* @returns {Promise<void>}
*/
async removeCallback (id: string)
async removeCallback (id: string): Promise<void>
{
await this.storage.deleteOne({ _id: id });
const timeout = this.#timeouts.get(id);

View File

@ -591,9 +591,9 @@ class ModerationManager implements Initialisable, CallbackClient
return responses;
}
async handleCallback (id: string)
async handleCallback (_id: string, infraction: InfractionJSON)
{
const infraction = await this.#client.mongodb.infractions.findOne({ id });
// const infraction = await this.#client.mongodb.infractions.findOne({ id });
if (!infraction)
return;
this.#logger.debug(`Infraction callback: ${infraction.id} (${infraction.type})`);
@ -667,7 +667,7 @@ class ModerationManager implements Initialisable, CallbackClient
if (expiresAt - currentDate <= 0)
{
this.#logger.debug(`Expired infraction:\n${inspect(infraction)}`);
return this.handleCallback(infraction.id);
return this.handleCallback(infraction.id, infraction);
}
this.#logger.debug(`Creating infraction callback for ${infraction.id} (${infraction.type}), expiring in ${Util.humanise(duration / 1000)}`);

View File

@ -47,12 +47,12 @@ class PollManager implements CallbackClient
return poll;
}
async handleCallback (_id: string, payload: PollData): Promise<void>
async handleCallback (id: string, payload: PollData): Promise<void>
{
await this.end(payload);
await this.end(id, payload);
}
async end ({ user, channel, startedIn, message, multiChoice }: PollData)
async end (id: string, { user, channel, startedIn, message, multiChoice }: PollData)
{
const startChannel = await this.#client.resolveChannel(startedIn);
const pollChannel = await this.#client.resolveChannel(channel);
@ -89,6 +89,7 @@ class PollManager implements CallbackClient
if (startChannel && startChannel.isTextBased())
await startChannel.send(guild.format('COMMAND_POLL_NOTIFY_STARTER', { user, channel }));
}
await this.callbacks.removeCallback(id);
}
}

View File

@ -59,89 +59,9 @@ class GuildWrapper
this.#guild = guild;
this.#webhooks = new Collection();
this.#memberWrappers = new Collection();
this.#debugLog('Created wrapper');
this.debug('Created wrapper');
}
// async createPoll ({ user, duration, ...opts }: PollData)
// {
// // Idk polls that don't have a duration should still be stored somewhere so they can be ended at an arbitrary point
// const type = 'poll';
// const now = Date.now();
// const id = `${type}:${user}:${now}`;
// const data = { ...opts, user, id, guild: this.id, type, time: duration * 1000, created: now };
// if (duration)
// await this.createCallback(data satisfies CallbackData);
// }
// async loadCallbacks ()
// {
// const data = await this.#client.mongodb.callbacks.find<CallbackData>({ guild: this.id });
// for (const cb of data)
// await this.createCallback(cb, false);
// }
// async createCallback (data: CallbackData, update = true)
// {
// const handler = this[`_${data.type}`] as CallbackFn;// .bind(this);
// if (!handler)
// throw new Error('Invalid callback type');
// const now = Date.now();
// const time = data.created + data.time;
// const diff = time - now;
// if (diff < 5000)
// return handler.bind(this)(data);
// const cb = { timeout: setTimeout(handler.bind(this), diff, data), data };
// this.#callbacks.set(data.id, cb);
// if (update)
// await this.#client.mongodb.callbacks.updateOne({ id: data.id, guild: this.id }, { $set: data });
// }
// async removeCallback (id: string)
// {
// const cb = this.#callbacks.get(id);
// if (cb)
// clearTimeout(cb.timeout);
// this.#callbacks.delete(id);
// await this.#client.mongodb.callbacks.deleteOne({ guild: this.id, id });
// }
// async _poll ({ user, message, channel, id, questions, startedIn }: PollData & CallbackData)
// { // multichoice,
// const startedInChannel = await this.resolveChannel<TextChannel>(startedIn);
// const pollChannel = await this.resolveChannel<TextChannel>(channel);
// if (pollChannel)
// {
// const msg = await pollChannel.messages.fetch(message).catch(() => null);
// if (msg)
// {
// const { reactions } = msg;
// const reactionEmojis = questions.length ? PollReactions.Multi : PollReactions.Single;
// const result: {[key: string]: number} = {};
// for (const emoji of reactionEmojis)
// {
// let reaction = reactions.resolve(emoji);
// // eslint-disable-next-line max-depth
// if (!reaction)
// continue;
// // eslint-disable-next-line max-depth
// if (reaction.partial)
// reaction = await reaction.fetch();
// result[emoji] = reaction.count - 1;
// }
// const embed = msg.embeds[0].toJSON();
// const results = Object.entries(result).map(([ emoji, count ]) => `${emoji} - ${count}`).join('\n');
// embed.description = this.format('COMMAND_POLL_END', { results });
// await msg.edit({ embeds: [ embed ] });
// }
// }
// await this.removeCallback(id);
// if (startedInChannel)
// await startedInChannel.send(this.format('COMMAND_POLL_NOTIFY_STARTER', { user, channel }));
// }
async filterText (member: GuildMember, text: string)
{
const settings = await this.settings();
@ -289,72 +209,6 @@ class GuildWrapper
return true;
}
// async _attemptDataImport ()
// {
// const migratorOptions = {
// // host: MONGODB_V2_HOST,
// database: 'galacticbot',
// version: '2'
// };
// const settingsMigrator = new SettingsMigrator(this.client, this, migratorOptions);
// const modlogsMigrator = new InfractionMigrator(this.client, this, migratorOptions);
// await settingsMigrator.connect();
// await modlogsMigrator.connect();
// let importedSettings = null;
// let importedModlogs = null;
// try
// {
// importedSettings = await settingsMigrator.import();
// importedModlogs = await modlogsMigrator.import();
// importedModlogs.sort((a, b) => a.case - b.case);
// }
// catch (err)
// {
// await settingsMigrator.end();
// await modlogsMigrator.end();
// // Did not find old settings, marking as imported anyway
// if (err.message.includes('No old'))
// {
// await this.updateData({ _imported: { settings: true, modlogs: true } });
// }
// else
// this.client.logger.error(err.stack);
// return null;
// }
// await settingsMigrator.end();
// await modlogsMigrator.end();
// await this.client.mongodb.infractions.deleteMany({ guild: this.id });
// await this.client.mongodb.infractions.insertMany(importedModlogs);
// this._data.caseId = importedModlogs[importedModlogs.length - 1].case;
// await this.updateData({
// caseId: this._data.caseId,
// premium: importedSettings.premium,
// _imported: { settings: true, modlogs: true }
// });
// const { webhook, permissions, settings } = importedSettings;
// await this.updateSettings(settings);
// if (webhook)
// {
// const hooks = await this.fetchWebhooks().catch(() => null);
// const hook = hooks?.get(webhook);
// if (hook)
// await this.updateWebhook('messages', hook);
// }
// if (permissions)
// await this.#client.mongodb.permissions.updateOne({ guildId: this.id }, permissions);
// return settings;
// }
/**
* Update a webhook entry in the database
*
@ -528,11 +382,18 @@ class GuildWrapper
this.#logger.error(`Database error (guild:${this.id}) :\n${error.stack || error}`);
}
#debugLog (log: string)
debug (log: string)
{
if (!this.#data || this.#data.debug)
this.#logger.debug(`[${this.name}]: ${log}`);
}
async setDebug (enabled: boolean)
{
await this.#client.mongodb.guilds.updateOne({ guildId: this.id }, { $set: { debug: enabled } });
this.#data.debug = enabled;
}
/* Wrapper Functions */
fetchAuditLogs<T extends GuildAuditLogsResolvable> (opts: GuildAuditLogsFetchOptions<T>)

View File

@ -62,10 +62,12 @@ class AddroleInfraction extends Infraction
}
try
{
this.guild.debug(`Adding roles ${this.data.roleIds.join(', ')} to ${this.member.tag} (${this.member.id})`);
await this.member.roles.add(this.data.roleIds, this._reason);
}
catch (error)
{
this.logger.error(`Failed to add roles (${this.data.roleIds.join(', ')}) to ${this.member.tag} (${this.member.id})\n${error}`);
return this._fail('INFRACTION_ERROR');
}

View File

@ -65,6 +65,7 @@ class BanInfraction extends Infraction
}
catch (error)
{
this.logger.error(`Failed to ban ${(this.target as UserWrapper).tag} (${this.target!.id}) from ${this.guild.name} (${this.guild.id})\n${error}`);
return this._fail('INFRACTION_ERROR');
}
await this.handle();

View File

@ -4,6 +4,7 @@ import DiscordClient from '../DiscordClient.js';
import MemberWrapper from '../components/wrappers/MemberWrapper.js';
import Infraction from '../interfaces/Infraction.js';
import { KickData } from '../../../@types/Infractions.js';
import UserWrapper from '../components/wrappers/UserWrapper.js';
class KickInfraction extends Infraction
{
@ -56,6 +57,7 @@ class KickInfraction extends Infraction
}
catch (error)
{
this.logger.error(`Failed to kick ${(this.target as UserWrapper).tag} (${this.target!.id}) from ${this.guild.name} (${this.guild.id})\n${error}`);
return this._fail('INFRACTION_ERROR');
}
await this.handle();

View File

@ -59,6 +59,7 @@ class RemoveroleInfraction extends Infraction
}
catch (error)
{
this.logger.error(`Failed to remove roles (${this.data.roleIds!.join(', ')}) to ${this.member!.tag} (${this.member!.id})\n${error}`);
return this._fail('INFRACTION_ERROR');
}

View File

@ -49,6 +49,7 @@ class UnbanInfraction extends Infraction
}
catch (error)
{
this.logger.error(`Failed to unban ${this.targetId} in ${this.guild.name} (${this.guild.id})\n${error}`);
return this._fail('INFRACTION_ERROR');
}

View File

@ -107,8 +107,9 @@ class UnmuteInfraction extends Infraction
{
this.member!.roles.remove(role, this._reason);
}
catch (e)
catch (error)
{
this.logger.error(`Failed to unmute ${this.member.tag} (${this.member.id})\n${error}`);
return this._fail('C_UNMUTE_1FAIL');
}
}
@ -131,8 +132,9 @@ class UnmuteInfraction extends Infraction
{
this.member.roles.remove(role, this._reason);
}
catch (e)
catch (error)
{
this.logger.error(`Failed to unmute ${this.member.tag} (${this.member.id})\n${error}`);
return this._fail('C_UNMUTE_1FAIL');
}
break;

View File

@ -234,6 +234,10 @@ class Infraction
}).catch(() => null);
this.#dmLogMessageId = logMessage?.id ?? null;
}
else
{
this.logger.debug(`Target not sendable? ${inspect(this.#target)}`);
}
}
if (this.#duration)

View File

@ -1,27 +1,47 @@
import { EventEmitter } from 'node:events';
import { inspect } from 'node:util';
import {
EventEmitter
} from 'node:events';
import {
inspect
} from 'node:util';
import {
existsSync
} from 'node:fs';
import path from 'node:path';
import { CommandsDef, IPCMessage } from '../../@types/Shared.js';
import { BroadcastEvalOptions, ShardMethod, ShardingOptions } from '../../@types/Shard.js';
import { ControllerOptions } from '../../@types/Controller.js';
import {
CommandsDef,
IPCMessage
} from '../../@types/Shared.js';
import { MasterLogger } from '@navy.gif/logger';
import { Collection } from 'discord.js';
import {
BroadcastEvalOptions,
ShardMethod,
ShardingOptions
} from '../../@types/Shard.js';
import {
ControllerOptions
} from '../../@types/Controller.js';
import {
MasterLogger
} from '@navy.gif/logger';
import {
Collection
} from 'discord.js';
// Available for evals
import ClientUtils from './ClientUtils.js';
import Metrics from './Metrics.js';
// import ApiClientUtil from './ApiClientUtil.js';
import SlashCommandManager from './rest/SlashCommandManager.js';
import { Shard } from './shard/index.js';
import { existsSync } from 'node:fs';
import SlashCommandManager from './SlashCommandManager.js';
import Util from '../utilities/Util.js';
// Placeholder
type GalacticAPI = {
init: () => Promise<void>
}
import Shard from './Shard.js';
class Controller extends EventEmitter
{
@ -39,7 +59,6 @@ class Controller extends EventEmitter
#readyAt: number | null;
#built: boolean;
#api?: GalacticAPI;
clientUtils: typeof ClientUtils;
constructor (options: ControllerOptions, version: string)
@ -92,28 +111,7 @@ class Controller extends EventEmitter
async build ()
{
const start = Date.now();
// const API = this._options.api.load ? await import('/Documents/My programs/GBot/api/index.js')
// .catch(() => this.logger.warn(`Error importing API files, continuing without`)) : null;
// let API = null;
// if (this.#options.api.load)
// API = await import('../../api/index.js').catch(() => this.#logger.warn(`Error importing API files, continuing without`));
// if (API) {
// this.#logger.info('Booting up API');
// const { default: APIManager } = API;
// this.#api = new APIManager(this, this.#options.api) as GalacticAPI;
// await this.#api.init();
// const now = Date.now();
// this.#logger.info(`API ready. Took ${now - start} ms`);
// start = now;
// }
this.#logger.status('Starting bot shards');
// await this.shardingManager.spawn().catch((error) => {
// this.#logger.error(`Fatal error during shard spawning:\n${error.stack || inspect(error)}`);
// // eslint-disable-next-line no-process-exit
// process.exit(); // Prevent a boot loop when shards die due to an error in the client
// });
const { totalShards, token } = this.#shardingOptions;
let shardCount = 0;
@ -133,7 +131,6 @@ class Controller extends EventEmitter
throw new TypeError('Amount of shards must be an integer.');
}
// const promises = [];
const retry: Shard[] = [];
for (let i = 0; i < shardCount; i++)
{
@ -148,9 +145,9 @@ class Controller extends EventEmitter
this.logger.info('Retrying shard', i);
retry.push(shard);
}
// promises.push();
}
// Retry failed spawns
for (const shard of retry)
{
try
@ -163,8 +160,6 @@ class Controller extends EventEmitter
}
}
// await Promise.all(promises);
this.#logger.status(`Shards spawned, spawned ${this.#shards.size} shards. Took ${Date.now() - start} ms`);
this.#built = true;
@ -173,12 +168,11 @@ class Controller extends EventEmitter
async shutdown ()
{
this.logger.info('Received SIGINT, shutting down');
this.logger.info('Received SIGINT or SIGTERM, shutting down');
setTimeout(process.exit, 90_000);
const promises = this.shards
.filter(shard => shard.ready)
.map(shard => shard.awaitShutdown()
.then(() => shard.removeAllListeners()));
.map(shard => shard.kill());
if (promises.length)
await Promise.all(promises);
this.logger.status('Shutdown complete, goodbye');
@ -406,11 +400,6 @@ class Controller extends EventEmitter
return this.#logger;
}
get api ()
{
return this.#api;
}
get shards ()
{
return this.#shards.clone();

View File

@ -1,6 +1,6 @@
import BaseClient from './Controller.js';
import os from 'node:os';
import Shard from './shard/Shard.js';
import Shard from './Shard.js';
import { IPCMessage } from '../../@types/Shared.js';
import djs, { GuildMessageManager } from 'discord.js';
import DiscordClient from '../client/DiscordClient.js';

View File

@ -1,13 +1,14 @@
import EventEmitter from 'node:events';
import path from 'node:path';
import { makePlainError, makeError, MakeErrorOptions } from 'discord.js';
import { Util } from '../../utilities/index.js';
import childProcess, { ChildProcess } from 'node:child_process';
import { makePlainError, makeError, MakeErrorOptions } from 'discord.js';
import { EnvObject, IPCMessage } from '../../../@types/Shared.js';
import Controller from '../Controller.js';
import { ShardOptions } from '../../../@types/Shard.js';
import { ClientOptions } from '../../../@types/Client.js';
import Controller from './Controller.js';
import { Util } from '../utilities/index.js';
import { ShardOptions } from '../../@types/Shard.js';
import { ClientOptions } from '../../@types/Client.js';
import { EnvObject, IPCMessage } from '../../@types/Shared.js';
const KillTO = 90 * 1000;
@ -16,8 +17,8 @@ class Shard extends EventEmitter
[key: string]: unknown;
#id: number;
#manager: Controller;
#env: EnvObject; // { [key: string]: string | boolean | number };
#controller: Controller;
#env: EnvObject;
#ready: boolean;
#clientOptions: ClientOptions;
@ -38,10 +39,10 @@ class Shard extends EventEmitter
#crashes: number[];
#fatal: boolean;
constructor (manager: Controller, id: number, options: ShardOptions)
constructor (controller: Controller, id: number, options: ShardOptions)
{
super();
this.#manager = manager;
this.#controller = controller;
this.#id = id;
this.#args = options.args ?? [];
@ -370,7 +371,7 @@ class Shard extends EventEmitter
if (message._sFetchProp)
{
const resp = { _sFetchProp: message._sFetchProp, _sFetchPropShard: message._sFetchPropShard };
this.#manager.fetchClientValues(message._sFetchProp, message._sFetchPropShard).then(
this.#controller.fetchClientValues(message._sFetchProp, message._sFetchPropShard).then(
(results: unknown) => this.send({ ...resp, _result: results }),
(error: Error) => this.send({ ...resp, _error: makePlainError(error) })
);
@ -380,7 +381,7 @@ class Shard extends EventEmitter
if (message._sEval)
{
const resp = { _sEval: message._sEval, _sEvalShard: message._sEvalShard };
this.#manager._performOnShards('eval', [ message._sEval ], message._sEvalShard).then(
this.#controller._performOnShards('eval', [ message._sEval ], message._sEvalShard).then(
(results: unknown) => this.send({ ...resp, _result: results }),
(error: Error) => this.send({ ...resp, _error: makePlainError(error) })
);
@ -390,7 +391,7 @@ class Shard extends EventEmitter
if (message._sRespawnAll)
{
const { shardDelay, respawnDelay, timeout } = message._sRespawnAll;
this.#manager.respawnAll({ shardDelay, respawnDelay, timeout }).catch(() =>
this.#controller.respawnAll({ shardDelay, respawnDelay, timeout }).catch(() =>
{
//
});

View File

@ -5,8 +5,8 @@ import fs from 'node:fs';
import path from 'node:path';
import { inspect } from 'node:util';
import BaseClient from '../Controller.js';
import { Command, CommandOption, CommandsDef } from '../../../@types/Shared.js';
import BaseClient from './Controller.js';
import { Command, CommandOption, CommandsDef } from '../../@types/Shared.js';
type CommandHashTable = {
global: string | null,

View File

@ -1,6 +0,0 @@
import Shard from './Shard.js';
// import ShardingManager from './ShardingManager.js';
export {
Shard,
// ShardingManager
};

View File

@ -111,7 +111,7 @@
},
"compileOnSave": true,
"exclude": ["archive", "api"],
"include": ["src", "index.ts", "@types"],
"include": ["src/**/*", "index.ts", "@types/*"],
"watchOptions": {
"watchFile": "useFsEvents",
"watchDirectory": "useFsEvents",