twitch-bot/libs/twitchParser.js
2018-02-13 00:34:26 +08:00

84 lines
2.3 KiB
JavaScript

const dbPool = require('./database')
/**
* @param {WebSocket} ws
* @param {string} msg
*/
const msgSplit = async function (ws, msg) {
if (!msg || typeof msg !== 'string') return null
let txtarr = msg.split(' ')
if (txtarr.length > 2) {
if (/^ping$/i.test(txtarr[0])) {
ws.send(`PONG ${txtarr[1]}`)
return
}
// chat message
if (/^privmsg$/i.test(txtarr[1])) {
let user = txtarr[0].split('!')[0].substr(1)
if (user === 'mtfosbot') return
let channel = txtarr[2]
txtarr = txtarr.slice(3, txtarr.length)
let m = txtarr.join(' ').substr(1)
let result = await parseCMD(user, channel, m)
if (result && typeof result === 'string') {
ws.send(`PRIVMSG ${channel} :${result}`)
}
}
}
}
/**
*
* @param {string} user
* @param {string} channel
* @param {string} msg
*/
const parseCMD = async function (user, channel, msg) {
let db = await dbPool.connect()
let m = null
try {
let txt = msg.trim().split(' ')
let ch = channel[0] === '#' ? channel.substr(1) : channel
if (txt.length < 1) {
await db.end()
return null
}
// add cmd
if (/^!\+/.test(txt[0])) {
let cmd = txt[0].substr(2)
let tmpmsg = txt.slice(1, txt.length).join(' ')
let query = `insert into "public"."commands" ("command", "channel", "message") values
($1, $2, $3)
on conflict ("command", "channel") do update set
"message" = $3,
"active" = true`
let param = [cmd, ch, tmpmsg]
await db.query(query, param)
} else if (/^!-/.test(txt[0])) {
let cmd = txt[0].substr(2)
let query = `update "public"."commands" set "active" = $1 where "command" = $2 and "channel" = $3`
let param = [false, cmd, ch]
await db.query(query, param)
m = `command "${cmd}" has removed`
} else if (/^!/.test(txt[0])) {
let cmd = txt[0].substr(1)
let query = `select "message", "command" from "public"."commands" where "command" = $1 and "channel" = $2 and "active" = $3 limit 1`
let param = [cmd, ch, true]
let result = await db.query(query, param)
if (result === null || result.rows.length === 0) return null
m = result.rows[0].message
}
} catch (err) {
console.error(err)
} finally {
await db.end()
}
return m
}
module.exports = {
msgSplit
}