56 lines
1.4 KiB
TypeScript
56 lines
1.4 KiB
TypeScript
import { ISqueebotCore, logger } from '@squeebot/core/lib/core';
|
|
import {
|
|
Plugin,
|
|
EventListener,
|
|
} from '@squeebot/core/lib/plugin';
|
|
|
|
class XProtocolPlugin extends Plugin {
|
|
private core: ISqueebotCore | null = null;
|
|
|
|
@EventListener('pluginUnload')
|
|
public unloadEventHandler(plugin: string | Plugin): void {
|
|
if (plugin === this.name || plugin === this) {
|
|
this.core = null;
|
|
this.emit('pluginUnloaded', this);
|
|
}
|
|
}
|
|
|
|
public async sendTo(target: string, ...data: any[]): Promise<boolean> {
|
|
if (!this.core) {
|
|
return false;
|
|
}
|
|
|
|
// Find target plugin
|
|
const rxSplit = target.split('/');
|
|
const plugin = this.core.pluginManager.getLoadedByName(rxSplit[0]);
|
|
if (!plugin || !plugin.service) {
|
|
return false;
|
|
}
|
|
|
|
// Find target protocol
|
|
const protocol = plugin.service.getProtocolByName(rxSplit[1]);
|
|
if (!protocol || !protocol.running) {
|
|
return false;
|
|
}
|
|
|
|
return protocol.sendTo(target, ...data);
|
|
}
|
|
|
|
initialize(): void {
|
|
this.on('core', (core: ISqueebotCore) => {
|
|
this.core = core;
|
|
});
|
|
|
|
this.emitTo('core', 'request-core', this.name);
|
|
|
|
this.on('send', (data: any[]) => {
|
|
const target = data[0];
|
|
this.sendTo(target, ...data.slice(1)).catch((error: Error) => {
|
|
logger.error(`[xprotocol] Sending to protocol from event failed:`, error.message ?? error);
|
|
});
|
|
});
|
|
}
|
|
}
|
|
|
|
module.exports = XProtocolPlugin;
|