seyfert
Version:
The most advanced framework for discord bots
239 lines (238 loc) • 9.76 kB
JavaScript
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.EventHandler = void 0;
const common_1 = require("../common");
const RawEvents = __importStar(require("../events/hooks"));
const types_1 = require("../types");
class EventHandler extends common_1.BaseHandler {
client;
constructor(client) {
super(client.logger);
this.client = client;
}
onFail = (event, err) => this.logger.warn('<Client>.events.onFail', err, event);
filter = (path) => path.endsWith('.js') || (!path.endsWith('.d.ts') && path.endsWith('.ts'));
values = {};
discordEvents = Object.keys(RawEvents).map(x => common_1.ReplaceRegex.camel(x.toLowerCase()));
set(events) {
for (const event of events) {
const instance = this.callback(event);
if (!instance)
continue;
if (typeof instance?.run !== 'function') {
this.logger.warn('Missing event run function');
continue;
}
this.values[this.discordEvents.includes(instance.data.name)
? common_1.ReplaceRegex.snake(instance.data.name).toUpperCase()
: instance.data.name] = instance;
}
}
async load(eventsDir) {
const paths = await this.loadFilesK(await this.getFiles(eventsDir));
for (const { events, file } of paths.map(x => ({ events: this.onFile(x.file), file: x }))) {
if (!events)
continue;
for (const i of events) {
const instance = this.callback(i);
if (!instance)
continue;
if (typeof instance?.run !== 'function') {
this.logger.warn(file.path.split(process.cwd()).slice(1).join(process.cwd()), 'Missing run function, use `export default {...}` syntax');
continue;
}
instance.__filePath = file.path;
this.values[this.discordEvents.includes(instance.data.name)
? common_1.ReplaceRegex.snake(instance.data.name).toUpperCase()
: instance.data.name] = instance;
}
}
}
async execute(raw, client, shardId) {
switch (raw.t) {
case 'MESSAGE_DELETE':
{
if (!client.components.values.size)
break;
const value = client.components.values.get(raw.d.id);
if (value) {
client.components.deleteValue(value.messageId, 'messageDelete');
}
}
break;
case 'MESSAGE_DELETE_BULK':
{
if (!client.components.values.size)
break;
for (const id of raw.d.ids) {
const value = client.components.values.get(id);
if (value) {
client.components.deleteValue(value.messageId, 'messageDelete');
}
}
}
break;
case 'GUILD_DELETE':
{
if (!client.components.values.size)
break;
// ignore unavailable guilds?
if (raw.d.unavailable)
break;
for (const [messageId, value] of client.components.values) {
if (value.guildId === raw.d.id)
client.components.deleteValue(messageId, 'guildDelete');
}
}
break;
case 'CHANNEL_DELETE':
{
if (!client.components.values.size)
break;
if (raw.d.type === types_1.ChannelType.DM || raw.d.type === types_1.ChannelType.GroupDM) {
for (const value of client.components.values) {
if (raw.d.id === value[1].channelId)
client.components.deleteValue(value[0], 'channelDelete');
}
}
else {
if (!raw.d.guild_id)
break;
// this is why we dont recommend to use collectors, use ComponentCommand instead
const channels = await client.cache.channels?.valuesRaw(raw.d.guild_id);
const threads = channels
?.filter(x => [types_1.ChannelType.PublicThread, types_1.ChannelType.PrivateThread, types_1.ChannelType.AnnouncementThread].includes(x.type) && x.parent_id === raw.d.id)
.map(x => x.id);
for (const value of client.components.values) {
const channelId = value[1].channelId;
if (raw.d.id === channelId || threads?.includes(channelId)) {
client.components.deleteValue(value[0], 'channelDelete');
}
}
}
}
break;
case 'THREAD_DELETE':
{
if (!client.components.values.size)
break;
for (const value of client.components.values) {
if (value[1].channelId === raw.d.id) {
client.components.deleteValue(value[0], 'channelDelete');
}
}
}
break;
}
await Promise.all([
this.runEvent(raw.t, client, raw.d, shardId),
this.client.collectors.run(raw.t, raw.d, this.client),
]);
}
async runEvent(name, client, packet, shardId, runCache = true) {
const Event = this.values[name];
try {
if (!Event || (Event.data.once && Event.fired)) {
return runCache
? this.client.cache.onPacket({
t: name,
d: packet,
})
: undefined;
}
Event.fired = true;
const hook = await RawEvents[name]?.(client, packet);
if (runCache)
await this.client.cache.onPacket({
t: name,
d: packet,
});
await Event.run(hook, client, shardId);
}
catch (e) {
await this.onFail(name, e);
}
}
async runCustom(name, ...args) {
const Event = this.values[name];
try {
if (!Event || (Event.data.once && Event.fired)) {
// @ts-expect-error
return this.client.collectors.run(name, args, this.client);
}
Event.fired = true;
this.logger.debug(`executed a custom event [${name}]`, Event.data.once ? 'once' : '');
await Promise.all([
Event.run(...args, this.client),
// @ts-expect-error
this.client.collectors.run(name, args, this.client),
]);
}
catch (e) {
await this.onFail(name, e);
}
}
async reload(name) {
if ((0, common_1.isCloudfareWorker)()) {
throw new Error('Reload in cloudfare worker is not supported');
}
const event = this.values[name];
if (!event?.__filePath)
return null;
delete require.cache[event.__filePath];
const imported = await (0, common_1.magicImport)(event.__filePath).then(x => x.default ?? x);
imported.__filePath = event.__filePath;
this.values[name] = imported;
return imported;
}
async reloadAll(stopIfFail = true) {
for (const i in this.values) {
try {
await this.reload(i);
}
catch (e) {
if (stopIfFail) {
throw e;
}
}
}
}
onFile(file) {
return file.default ? (Array.isArray(file.default) ? file.default : [file.default]) : undefined;
}
callback = (file) => file;
}
exports.EventHandler = EventHandler;