chipmunkbot3/index.js

57 lines
1.6 KiB
JavaScript

const readline = require('readline')
const createBot = require('./bot.js')
const fs = require('fs')
const path = require('path')
const moment = require('moment')
const json5 = require('json5')
const matrix = require('matrix-js-sdk')
const configPath = process.argv[2] ?? 'config.json5'
if (!fs.existsSync(configPath)) {
fs.copyFileSync(path.join(__dirname, 'default.json5'), configPath)
console.info('No config file was found, so a default one was created.')
}
const config = json5.parse(fs.readFileSync(configPath, 'utf-8'))
const logdir = 'logs'
if (!fs.existsSync(logdir)) fs.mkdirSync(logdir)
let logfile = path.join(logdir, moment().format('YYYY-MM-DD'))
if (fs.existsSync(logfile)) {
const pathWithSeparator = logfile + '-'
let i = 0
while (fs.existsSync(logfile)) {
logfile = pathWithSeparator + (i++)
}
}
logfile += '.log'
fs.writeFileSync(logfile, '')
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
prefix: '> '
})
const matrixClients = {}
for (const key in config.matrixClients) {
const client = matrix.createClient(config.matrixClients[key])
matrixClients[key] = client
client.startClient()
}
const bots = []
for (const options of config.bots) {
const mergedOptions = { ...(config.all ?? {}), ...options }
if (mergedOptions.matrix && typeof mergedOptions.matrix.client !== 'object') mergedOptions.matrix.client = matrixClients[mergedOptions.matrix.client]
const bot = createBot(mergedOptions)
bots.push(bot)
bot.bots = bots
bot.on('error', console.error)
bot.console.filepath = logfile
bot.console.setRl(rl)
}