update bot code

This commit is contained in:
Jay 2018-02-13 13:41:32 +08:00
parent 725791dd4e
commit 79eed290d4

View File

@ -3,33 +3,51 @@ const config = require('../config')
const dbPool = require('./database') const dbPool = require('./database')
const request = require('request') const request = require('request')
const log = require('debug')('BOT:IRC') 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) console.error(err)
}) ws = null
runBot()
// do reconnect
}
ws.on('close', (code, reason) => { function handleExit(code) {
console.log('exit', code, reason) // do reconnect
}) ws = null
runBot()
}
function handleMessage (data) { function handleMessage(data) {
let d = data.toString() let d = data.toString()
let darr = d.split(/\n/).filter(t => t).map(t => t.replace(/\r$/, '')) let darr = d.split(/\n/).filter(t => t).map(t => t.replace(/\r$/, ''))
for (let i in darr) { for (let i in darr) {
log(darr[i]) 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 db = await dbPool.connect()
let body = null let body = null
@ -61,7 +79,7 @@ async function handleOpen () {
} catch (err) { } catch (err) {
console.log(err) console.log(err)
} }
if (body === null || !('access_token' in body)) throw new Error('access token not found') if (body === null || !('access_token' in body)) throw new Error('access token not found')
ws.send('PASS oauth:' + body.access_token) ws.send('PASS oauth:' + body.access_token)
@ -81,4 +99,4 @@ async function handleOpen () {
} }
} }
module.exports = ws module.exports = ws