-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
406 lines (353 loc) · 13.1 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
// vvvv for debugging
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
});
var OPTS = require('./config.js');
var messageQueue = [];
const REGEX = {
SET_VOTING_PERIOD: /^!setvotingperiod \d+$/i,
POTENTIAL_MOVE: /^([RNBKQK0-8a-h+#x=-]{2,7}|resign|offer draw|accept draw|offer\/accept draw)$/i, // very crude guesstimate
KINGSIDE_CASTLE: /^[Oo0]-[Oo0]$/,
QUEENSIDE_CASTLE: /^[Oo0]-[Oo0]-[Oo0]$/
};
const { Chess } = require('chess.js');
var games = {};
var cooldownInterval;
// Socket.io part ---------------------------------------------
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var port = 3000;
app.get('/', (req, res) => {
res.sendFile(__dirname + '/votes.html');
});
io.on('connection', (socket) => {
socket.on('streamer', (streamer) => {
socket.join(streamer.toLowerCase());
let game = games[gameIdFromTwitch(streamer)];
if (game) socket.emit('candidates', game.candidates);
});
});
http.listen(port, () => {
console.log(`Express server listening on *:${port}`);
});
// ------------------------------------------------------------
// module to send http requests / communicate with the lichess api
const https = require('https');
// twitch messaging interface module
const tmi = require('tmi.js');
const client = new tmi.Client({
options: { debug: false }, // set to false to get rid of console messages
connection: {
secure: true,
reconnect: true
},
identity: {
username: 'TTVChat', // just realized--this is wrong.. why does it still work?
password: OPTS.TWITCH_OAUTH
},
channels: [ OPTS.STREAMER ]
});
// connect twitch client
client.connect();
// twitch client joins the streamer's chat
client.on('join', () => {
let userstate = client.userstate[`#${OPTS.STREAMER.toLowerCase()}`];
OPTS.CHAT_COOLDOWN_APPLIES = !isModOrVIP(userstate);
if (OPTS.CHAT_COOLDOWN_APPLIES && !cooldownInterval)
cooldownInterval = setInterval(shiftChatQueue, OPTS.CHAT_COOLDOWN);
});
function isModOrVIP(userstate) { return userstate.mod || (userstate.badges && userstate.badges.vip); }
function shiftChatQueue() { let msg; if (msg = messageQueue.shift()) client.say(OPTS.STREAMER, msg); }
function userIsAuthorized(username) { return OPTS.AUTHORIZED_USERS.includes(username); }
function isBotsTurn(game) { return !(game.sloppyPGN === null); }
function alreadyVoted(username, game) { return game.voters.includes(username); }
function alreadyOfferedDraw(username, game) { return game.offeringDraw.includes(username); }
function isDrawOffer(message) { return message.toLowerCase().trim() === 'offer draw' || message.toLowerCase().trim() === 'accept draw' || message.toLowerCase().trim() === 'offer/accept draw'; }
function testMove(possibleMove, gameId) {
let chess = games[gameId].initialFen ? new Chess(games[gameId].initialFen) : new Chess();
for (move of games[gameId].sloppyPGN.split(' ')) {
chess.move(move, { sloppy: true });
}
let result;
if (possibleMove.toLowerCase().trim() === 'resign')
return { from: 'resign', to: '', san: 'resign'}
else if (isDrawOffer(possibleMove))
return { from: 'offer/accept draw', to: '', san: 'offer/accept draw' }
else if (result = chess.move(possibleMove, { sloppy: true }))
return result;
else
return chess.move(possibleMove.charAt(0).toUpperCase() + possibleMove.slice(1), { sloppy: true });
}
function emitCandidates(game) { io.to(game.streamer.twitch).emit('candidates', game.candidates); }
function validChallenge(json) {
return json.type === 'challenge' && json.challenge.challenger.id === OPTS.STREAMER_LICHESS.toLowerCase();
}
function gameIdFromTwitch(twitch) {
for (gameId of Object.keys(games)) {
let game = games[gameId];
if (game.streamer.twitch === twitch.toLowerCase()) return gameId;
}
return false;
}
client.on('message', (channel, tags, message, self) => {
if (self) return;
if (userIsAuthorized(tags.username) && REGEX.SET_VOTING_PERIOD.test(message)) {
let voting_period;
if ((voting_period = parseInt(message.split(' ')[1])) && voting_period > 3 && voting_period < 1200) {
OPTS.VOTING_PERIOD = voting_period;
say(`Voting period is now ${OPTS.VOTING_PERIOD} seconds.`);
}
}
channel = channel.substr(1);
let gameId = gameIdFromTwitch(channel);
let game = games[gameId];
if (game
&& isBotsTurn(game)
&& REGEX.POTENTIAL_MOVE.test(message)
&& ((!alreadyVoted(tags.username, game) && !isDrawOffer(message)) || (!alreadyOfferedDraw(tags.username, game) && isDrawOffer(message)))
/*&& tags.username !== OPTS.STREAMER.toLowerCase()*/) {
// message is likely a move
if (REGEX.KINGSIDE_CASTLE.test(message) ) message = 'O-O';
else if (REGEX.QUEENSIDE_CASTLE.test(message)) message = 'O-O-O';
let move;
if (move = testMove(message, gameId)) {
let UCI = move.from + move.to, SAN = move.san;
if (game.candidates[UCI])
game.candidates[UCI].votes++;
else
game.candidates[UCI] = { votes: 1, SAN };
if (UCI === 'offer/accept draw') {
game.offeringDraw.push(tags.username);
var allUsers = [...new Set(game.voters.concat(game.offeringDraw))];
var pctDraw = Math.floor(game.offeringDraw.length / allUsers.length * 100);
game.candidates[UCI].pct = pctDraw;
} else {
game.voters.push(tags.username);
}
emitCandidates(game);
// log the vote
if (OPTS.ACKNOWLEDGE_VOTE)
say(`@${tags['display-name']} voted ${UCI === 'offer/accept draw' ? 'to offer/accept a draw.' : `for ${SAN}!`}`);
else
console.log(`@${tags['display-name']} voted ${UCI === 'offer/accept draw' ? 'to offer/accept a draw.' : `for ${SAN}!`}`);
}
}
});
function streamIncomingEvents() {
const options = {
hostname: 'lichess.org',
path: '/api/stream/event',
headers: { Authorization: `Bearer ${OPTS.LICHESS_OAUTH}` }
};
return new Promise((resolve, reject) => {
https.get(options, (res) => {
res.on('data', (chunk) => {
let data = chunk.toString();
try {
let json = JSON.parse(data);
if (validChallenge(json)) {
acceptChallenge(json.challenge.id);
} else if (json.type === 'gameStart') {
beginGame(json.game.id);
}
} catch (e) { return; }
});
res.on('end', () => {
reject(new Error('[streamIncomingEvents()] Stream ended.'));
});
});
});
}
async function streamGameState(gameId) {
const options = {
hostname: 'lichess.org',
path: `/api/bot/game/stream/${gameId}`,
headers: { Authorization: `Bearer ${OPTS.LICHESS_OAUTH}` }
};
return new Promise((resolve, reject) => {
https.get(options, (res) => {
res.on('data', async (chunk) => {
let data = chunk.toString();
if (!data.trim()) return;
try {
let lines = data.split('\n');
for (line of lines) {
if (!line) return;
let json = JSON.parse(line);
if (json.type === 'gameFull') {
// game started
let initialFen = json.initialFen;
games[gameId].initialFen = initialFen === 'startpos' ? null : initialFen;
games[gameId].white = json.white.id === OPTS.LICHESS_BOT.toLowerCase();
json = json.state;
}
if (json.type === 'gameState') {
if (json.status === 'started') {
// game in progress
let numMoves = json.moves ? json.moves.split(' ').length : 0;
if (numMoves % 2 != games[gameId].white) {
// bot's turn to move
if (numMoves >= 1) {
// nicer way to write this code? had to add it in a pinch
let moves = json.moves.split(' ');
let streamerMove = moves.pop();
let chess = games[gameId].initialFen ? new Chess(games[gameId].initialFen) : new Chess();
for (move of moves) {
chess.move(move, { sloppy: true });
}
streamerMove = chess.move(streamerMove, { sloppy: true });
say(`Streamer played: ${streamerMove.san}`);
}
await initiateVote(gameId, json.moves);
}
} else if (json.winner || json.status === 'draw') {
// game over
if (json.status === 'draw') resolve('draw');
if (json.winner === 'white' ^ games[gameId].white)
resolve('streamer');
else
resolve('chat');
}
}// else if (json.type === 'chatLine' && json.room === 'player' && json.username === 'lichess') {}
}
} catch (e) { console.log(`Data: ${data}`, `Error: ${e}`); }
});
res.on('end', () => {
resolve();
});
});
});
}
function say(msg) {
console.log(...arguments);
if (OPTS.CHAT_COOLDOWN_APPLIES)
messageQueue.push(msg);
else
client.say(OPTS.STREAMER, msg);
}
async function initiateVote(gameId, moves, revote=0) {
let game;
if (!(game = games[gameId])) return;
// say(revote ? `Nobody voted for a valid move! You have ${OPTS.VOTING_PERIOD} seconds to vote again. (${revote})` : `Voting time! You have ${OPTS.VOTING_PERIOD} seconds to name a move (UCI format, ex: e2e4).`);
if (!revote) say(`Voting time! You have ${OPTS.VOTING_PERIOD} seconds to name a move.`);
game.sloppyPGN = moves;
setTimeout(async () => {
if (!(game = games[gameId])) return;
var arr = Object.keys(game.candidates).map(key => [key, game.candidates[key].votes, game.candidates[key].SAN]);
if (arr.length === 0 || (arr[0][0] === 'offer/accept draw' && arr.length === 1)) {
await initiateVote(gameId, moves, ++revote);
return;
}
var winningMove = arr.sort((a, b) => b[1] - a[1])[0];
if (winningMove[0] === 'offer/accept draw') winningMove = arr.sort((a, b) => b[1] - a[1])[1];
var allUsers = [...new Set(game.voters.concat(game.offeringDraw))];
var pctDraw = game.offeringDraw.length / allUsers.length;
game.sloppyPGN = null;
game.voters = [];
game.offeringDraw = [];
game.candidates = {};
emitCandidates(game);
if (winningMove[0] === 'resign')
await resignGame(gameId);
else
await makeMove(gameId, winningMove[0] /* UCI */, pctDraw >= 0.50);
say(`Playing move: ${winningMove[2] /* SAN */}`);
}, OPTS.VOTING_PERIOD * 1000);
}
async function beginGame(gameId) {
try {
say('Game started!', gameId);
games[gameId] = { white: null, sloppyPGN: null, candidates: {}, voters: [], offeringDraw: [], streamer: { twitch: OPTS.STREAMER.toLowerCase(), lichess: OPTS.STREAMER_LICHESS } };
var result = await streamGameState(gameId);
delete games[gameId];
switch (result) {
case 'draw':
say('Game over - It\'s a draw!', gameId);
break;
case 'chat':
say('Chat wins! PogChamp', gameId);
break;
case 'streamer':
say(`${OPTS.STREAMER} wins! Better luck next time chat.`, gameId);
break;
default: // should only happen if game state stops streaming for unknown reason
say('Game over.', gameId);
}
} catch (e) {
console.log(e);
}
}
async function acceptChallenge(challengeId) {
const options = {
hostname: 'lichess.org',
path: `/api/challenge/${challengeId}/accept`,
headers: { Authorization: `Bearer ${OPTS.LICHESS_OAUTH}` },
method: 'POST'
};
return new Promise((resolve, reject) => {
var req = https.request(options, (res) => {
res.on('data', (data) => {
data = JSON.parse(data.toString());
if (data.ok) {
resolve(true);
} else {
reject(data);
}
});
});
req.on('error', (e) => {
reject(e);
});
req.end();
});
}
async function resignGame(gameId) {
const options = {
hostname: 'lichess.org',
path: `/api/bot/game/${gameId}/resign`,
headers: { Authorization: `Bearer ${OPTS.LICHESS_OAUTH}` },
method: 'POST'
};
return new Promise((resolve, reject) => {
var req = https.request(options, (res) => {
res.on('data', (data) => {
data = JSON.parse(data.toString());
if (data.ok) {
resolve(true);
} else {
reject(data);
}
});
});
req.on('error', (e) => {
reject(e);
});
req.end();
});
}
async function makeMove(gameId, move, draw=false) {
const options = {
hostname: 'lichess.org',
path: `/api/bot/game/${gameId}/move/${move}?offeringDraw=${draw}`,
headers: { Authorization: `Bearer ${OPTS.LICHESS_OAUTH}` },
method: 'POST'
};
return new Promise((resolve, reject) => {
var req = https.request(options, (res) => {
res.on('data', (data) => {
data = JSON.parse(data.toString());
if (data.ok) {
resolve(true);
} else {
reject(data);
}
});
});
req.on('error', (e) => {
reject(e);
});
req.end();
});
}
streamIncomingEvents();