const WebSocket = require('ws') const config = require('../config') const dbPool = require('./database') const request = require('request') const log = require('debug')('BOT:IRC') const { msgSplit } = require('./twitchParser') const ws = new WebSocket(`wss://${config.twitch.chat_host}:443`, 'irc') ws.on('open', async () => { let db = await dbPool.connect() let body = null try { let options = { method: 'POST', url: config.twitch.token_url, headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' }, form: { grant_type: 'refresh_token', refresh_token: config.twitch.refresh_token, client_id: config.twitch.client_id, client_secret: config.twitch.secret } } body = await new Promise((resolve, reject) => { request(options, function (error, response, body) { if (error) { reject(error) return } console.log(response.statusCode) resolve(body) }) }) } catch (err) { console.log(err) } console.log(typeof body) if (body === null || !('access_token' in body)) throw new Error('access token not found') ws.send('PASS oauth:' + body.access_token) ws.send('NICK mtfosbot') ws.send('CAP REQ :twitch.tv/membership :twitch.tv/commands') let query = `select "name", "join" from "public"."channels" where "join" = $1` let param = [true] let result = await db.query(query, param) if (result !== null && result.rows.length > 0) { for (let row of result.rows) { if ('name' in row) { ws.send('JOIN #' + row.name) } } } }) ws.on('message', (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(() => { }) } }) ws.on('error', (err) => { console.error(err) }) ws.on('close', (code, reason) => { console.log('exit', code, reason) }) module.exports = ws