mtfosbot/libs/line-message/commands/index.js

46 lines
1.2 KiB
JavaScript
Raw Normal View History

2018-06-27 09:50:56 +00:00
const DB = require('../../database')
2018-06-28 15:41:16 +00:00
const actions = require('./actions')
2018-06-27 09:50:56 +00:00
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(/^!/, '')
2018-06-28 13:26:44 +00:00
2018-06-27 09:50:56 +00:00
let db = await DB.connect()
2018-06-28 15:41:16 +00:00
let reply = null
2018-06-27 09:50:56 +00:00
try {
2018-06-28 13:26:44 +00:00
let result = await db.query({
2018-06-28 15:41:16 +00:00
text: `select "message" from "public"."commands" where "cmd" = $1`,
values: [cmd]
2018-06-28 13:26:44 +00:00
})
2018-06-28 15:41:16 +00:00
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
}
}
2018-06-28 13:26:44 +00:00
}
2018-06-27 09:50:56 +00:00
} catch (err) {
console.log(err)
}
2018-06-28 15:41:16 +00:00
2018-06-27 09:50:56 +00:00
db.release()
2018-06-28 15:41:16 +00:00
return reply
2018-06-27 09:50:56 +00:00
}
module.exports = parseCMD