chipmunkbot3/commands/client.js

66 lines
2.5 KiB
JavaScript

const name = 'client'
const description = 'Creates and manages clients using minecraft-protocol.'
const usages = ['create <options (json)>', 'end <i>', 'write <i> <name> <data (json)>', 'list']
const aliases = ['client']
const enabled = true
const permLevel = 0
const mc = require('minecraft-protocol')
const clients = []
const sectionRegex = /\u00a7.?/g
const util = require('util')
function execute (bot, cmd, player, args, handler) {
const subCmd = args.shift()
switch (subCmd) {
case 'create': {
const options = { host: bot.host, port: bot.port, ...JSON.parse(args.join(' ').replace(sectionRegex, '')) }
const client = mc.createClient(options)
const idx = clients.length
client.once('login', () => bot.core.run('minecraft:tellraw @a ' + JSON.stringify([{ text: client.username, color: bot.colors.primary }, ' logged in'])))
client.on('end', () => {
clients.splice(idx, 1)
bot.core.run('minecraft:tellraw @a ' + JSON.stringify([{ text: client.username, color: bot.colors.primary }, ' ended']))
})
client.on('error', (err) => bot.core.run('minecraft:tellraw @a ' + JSON.stringify({ text: util.inspect(err).replace(/\n.*/g, ''), color: bot.colors.error })))
clients.push(client)
}
break
case 'end': {
const stridx = args.join(' ').replace(sectionRegex, '')
let idx = Number(stridx)
if (!Number.isInteger(idx)) clients.forEach((client, cidx) => { if (client.username === stridx) idx = cidx })
if (!Number.isInteger(idx)) throw new Error('Unknown client: ' + stridx)
clients[idx].end()
clients.splice(idx, 1)
}
break
case 'write': {
const stridx = args.shift().replace(sectionRegex, '')
let idx = Number(stridx)
if (!Number.isInteger(idx)) clients.forEach((client, cidx) => { if (client.username === stridx) idx = cidx })
if (!Number.isInteger(idx)) throw new Error('Unknown client: ' + stridx)
const name = args.shift()
const data = JSON.parse(args.join(' ').replace(sectionRegex, ''))
clients[idx].write(name, data)
}
break
case 'list':
bot.core.run('minecraft:tellraw @a ' + JSON.stringify({ text: 'Clients: ' + clients.map(client => client.username).join('\u00a7r, '), color: bot.colors.primary }))
break
default:
throw new Error('Invalid or missing argument')
}
}
module.exports = { name, description, usages, aliases, enabled, execute, permLevel }