diff --git a/libs/botClient.js b/libs/botClient.js index 6bca69c..cad4e4d 100644 --- a/libs/botClient.js +++ b/libs/botClient.js @@ -3,33 +3,51 @@ const config = require('../config') const dbPool = require('./database') const request = require('request') const log = require('debug')('BOT:IRC') -const { msgSplit } = require('./twitchParser') +const { + msgSplit +} = require('./twitchParser') -const ws = new WebSocket(`wss://${config.twitch.chat_host}:443`, 'irc') +/** @type {WebSocket} */ +var ws = null -ws.on('open', handleOpen) +runBot() -ws.on('message', handleMessage) +function runBot() { + ws = new WebSocket(`wss://${config.twitch.chat_host}:443`, 'irc') -ws.on('error', (err) => { + ws.on('open', handleOpen) + + ws.on('message', handleMessage) + + ws.on('error', handleError) + + ws.on('close', handleExit) +} + +function handleError(err) { console.error(err) -}) + ws = null + runBot() + // do reconnect +} -ws.on('close', (code, reason) => { - console.log('exit', code, reason) -}) +function handleExit(code) { + // do reconnect + ws = null + runBot() +} -function handleMessage (data) { +function handleMessage(data) { let d = data.toString() let darr = d.split(/\n/).filter(t => t).map(t => t.replace(/\r$/, '')) for (let i in darr) { log(darr[i]) - msgSplit(ws, darr[i]).then(() => { }) + msgSplit(ws, darr[i]).then(() => {}) } } -async function handleOpen () { +async function handleOpen() { let db = await dbPool.connect() let body = null @@ -61,7 +79,7 @@ async function handleOpen () { } catch (err) { console.log(err) } - + if (body === null || !('access_token' in body)) throw new Error('access token not found') ws.send('PASS oauth:' + body.access_token) @@ -81,4 +99,4 @@ async function handleOpen () { } } -module.exports = ws +module.exports = ws \ No newline at end of file