const dbPool = require('./database') const config = require('../config') /** * @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) { // server heartbeat message if (/^ping$/i.test(txtarr[0])) { // reply server heartbeat ws.send(`PONG ${txtarr[1]}`) return } // chat message if (/^privmsg$/i.test(txtarr[1])) { // message format // :user!user@user.tmi.twitch.tv PRIVMSG #channel :message let user = txtarr[0].split('!')[0].substr(1) if (user === config.twitch.bot_account) return let channel = txtarr[2] // get message txtarr = txtarr.slice(3, txtarr.length) // remove message first : 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(' ') // get channel name without hashtag 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, "mtime" = now()` let param = [cmd, ch, tmpmsg] await db.query(query, param) m = `command "${cmd}" has added` // remove cmd } else if (/^!-/.test(txt[0])) { let cmd = txt[0].substr(2) let query = `update "public"."commands" set "active" = $1, "mtime" = now() where "command" = $2 and "channel" = $3` let param = [false, cmd, ch] await db.query(query, param) m = `command "${cmd}" has removed` // run cmd } 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 }