UNPKG

modernirc

Version:

IRC library for creating modern IRC bots

124 lines (123 loc) 3.24 kB
import path from 'node:path' import { Worker } from 'node:worker_threads' /** * Starts the HTTP API * @param bot {object} Bot object * @param options {object} Bot options */ export function createApi(bot, options) { if (!options.api?.auth?.key) { throw new Error('a key is required if you want to enable the api feature') } const api = new Worker(path.join(path.dirname(import.meta.url).replace('file:/', ''), 'index.js'), { workerData: { opts: options.api, logger: options.logger.options, }, }) api.on('message', async ({ data, ports }) => { switch (data.action) { case 'get-identity': ports[0].postMessage({ statusCode: 200, data: { nickname: options.identity.nickname, username: options.identity.username, realname: options.identity.realname, }, }) break case 'get-channels': ports[0].postMessage({ statusCode: 200, data: bot.joinedChannels, }) break case 'get-modules': ports[0].postMessage({ statusCode: 200, data: Object.keys(options.modules).map((modname) => ({ name: modname, enabled: options.modules[modname].enabled, })), }) break case 'nick': bot.changeNickname(data.args.nickname) ports[0].postMessage({ statusCode: 200, data: { ok: true }, }) break case 'join': bot.join(data.args.channel, data.args.key) ports[0].postMessage({ statusCode: 200, data: { ok: true }, }) break case 'part': bot.part(data.args.channel, data.args.reason) ports[0].postMessage({ statusCode: 200, data: { ok: true }, }) break case 'privmsg': bot.message(data.args.target, data.args.message) ports[0].postMessage({ statusCode: 200, data: { ok: true }, }) break case 'action': bot.me(data.args.target, data.args.action) ports[0].postMessage({ statusCode: 200, data: { ok: true }, }) break case 'notice': bot.notice(data.args.target, data.args.message) ports[0].postMessage({ statusCode: 200, data: { ok: true }, }) break case 'kick': bot.kick(data.args.channel, data.args.target, data.args.reason) ports[0].postMessage({ statusCode: 200, data: { ok: true }, }) break case 'message-to-module': { const { moduleName, ...args } = data.args const _runner = bot.loadedModules.find(({ name }) => name === moduleName) if (!_runner || typeof _runner.runner.onApiRequest !== 'function') { ports[0].postMessage({ statusCode: 404, data: { ok: false }, }) } else { const result = await _runner.runner.onApiRequest(args) ports[0].postMessage({ statusCode: 200, data: { ok: true, result: result ?? null }, }) } break } default: ports[0].postMessage({ statusCode: 404, data: { ok: false }, }) break } }) api.on('error', (err) => { console.error(err) }) }