zeppelin/game/context.js
2025-03-16 15:02:23 +01:00

79 lines
2.2 KiB
JavaScript

const fs = require('fs');
const _ = require('underscore');
const cache = require('../backbone/cache.js');
const alias = require('./alias.json');
let commands = {};
fs.readdirSync('./game/commands').forEach(file => {
require(`./commands/${file}`)(commands);
});
function a(context) {
try {
let cmd = context.alias[context.command].command;
if(context.alias[context.command].arg) {
let args = alias[context.command].arg + context.args;
context.args = args;
}
context.command = cmd;
} catch {
console.info(`[${context.id}] Not an alias <${context.command}>`);
}
}
const ex = /^!(?:([\w\d]+)|(?:([\w\d]+?)\s(.+)))$/
function c (context) {
return new Promise((resolve, reject) => {
let match = ex.exec(context.message.content);
if (match) {
context.command = match[2] ? match[2] : match[1];
context.args = match[3];
context.alias = alias;
a(context);
context.commands = commands;
context.pid = context.message.author.id;
cache.state(context.id)
.then(data => {
context.state = data;
resolve(context);
}).catch(err => reject(err));
} else { resolve(false); }
});
}
function p(message) {
return new Promise((resolve, reject) => {
let context = { message: message, id: message.guild.id };
c(context)
.then(context => resolve(context))
.catch(err => reject(err));
});
}
function x(context) {
return new Promise((resolve, reject) => {
if(context) {
if(_.has(commands, context.command)) {
console.info(`[${context.id}] Execute command <${context.command}>`);
commands[context.command](context)
.then(() => {
if(context.stateChanged){
cache.commit(context.id);
} else {
console.info(`[${context.id}] No change to commit (Context.stateChanged == false)`);
}
resolve();
})
.catch(err => reject(err));
} else {
console.warn(`[${context.id}] Unknown command <${context.command}>`);
}
}
});
}
module.exports = {
parse: p,
execute: x
}