const DB = require('../../database') const actions = require('./actions') const parseCMD = async (text = '', source = {}) => { if (typeof text !== 'string' || text.trim().length === 0) return null if (!source || typeof source !== 'object' || !('type' in source)) return null let txt = text.trim() let arr = txt.split(' ').map(t => t.trim()) if (arr.length === 0) return null if (arr[0][0] !== '!') return null let cmd = arr[0].replace(/^!/, '') let db = await DB.connect() let reply = null try { let result = await db.query({ text: `select "message" from "public"."commands" where "cmd" = $1`, values: [cmd] }) if (result.rowCount > 0) { let content = result.rows[0].message let m = content.match(/{{(.+?)}}/g) if (m !== null && m.length > 0) { for (let i = 0; i < m.length; i++) { let c = m[i].replace(/^{{/, '').replace(/}}$/, '') let res = await actions(c, arr.slice(1).join(' '), source) content = content.replace(m[i], res || '') } } if (content.trim().length > 0) { reply = { reply: content } } } } catch (err) { console.log(err) } db.release() return reply } module.exports = parseCMD