const { client, xml } = require('@xmpp/client'), got = require('got'), config = require('./config'), ChessImageGenerator = require('chess-image-generator'), jsChess = require('js-chess-engine'), xmpp = client({ service: config.service, username: config.username, password: config.password }), sendMessage = async message => { await xmpp.send(xml( 'message', { type: 'groupchat', to: room }, xml('body', {}, message) )) }, room = config.room, nick = config.nick, game = new jsChess.Game(), iaLevel = 3 // level 3 IA max deep let imageGenerator, time xmpp.on('stanza', async stanza => { if (stanza.is('message') && !stanza.getChild('delay')) { const message = stanza.getChildText('body') if (message && game.status && game.status.isFinished) { sendMessage('Jaque mate. Juego terminado.') } else if (message && message.split(' ').length === 3 && message.split(' ')[0] === '.move' && message.split(' ')[1].match(/^[A-H]{1}[1-8]{1}$/) && message.split(' ')[2].match(/^[A-H]{1}[1-8]{1}$/)) { const msg = message.split(' ') msg.shift() game.move(msg[0], msg[1]) const d = Date.now() game.aiMove(iaLevel) time = Date.now() - d if (game.status && game.status.checkMate) { sendMessage('Jaque.') } imageGenerator = new ChessImageGenerator({ size: 720, light: 'rgb(200, 200, 200)', dark: '#333333', style: 'merida' }) await imageGenerator.loadFEN(game.exportFEN()) const buf = await imageGenerator.generateBuffer() await xmpp.send(xml( 'iq', { type: 'get', to: stanza.attrs.from.replace(/\/.*$/, '').split('@')[1], id: 'step_' + Math.floor(Math.random() * 100) }, xml('request', { xmlns: 'urn:xmpp:http:upload:0', filename: 'chess.png', size: buf.byteLength, 'content-type': 'image/png' } ) )).catch(console.error) } } else if (stanza.is('iq') && stanza.attrs.type === 'result') { if (imageGenerator) { const buf = await imageGenerator.generateBuffer() if (buf.byteLength > 0 && stanza.getChild('slot') && stanza.getChild('slot').getChild('put')) { const url = stanza.getChild('slot').getChild('put').attrs.url, req = await got.put(url, { body: buf }).catch(console.error) if (req && req.url && time) { sendMessage(`Su turno: ${req.url} movimiento IA en ${time / 1000}s`) imageGenerator = null time = null } } } } }) xmpp.on('online', async address => { await xmpp.send(xml( 'presence', { to: room + '/' + nick }, xml('x', { xmlns: 'http://jabber.org/protocol/muc' } ) )).catch(console.error) console.log('Connected like: ' + address) sendMessage('Comienza la partida: .move \nEj: .move B2 B3') }) xmpp.on('error', console.error) xmpp.on('offline', () => { console.log('Go to offline') }) xmpp.start().catch(console.error)