-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
431 lines (378 loc) · 12.7 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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
// vvvv for debugging
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
});
const OPTS = require('./config.js');
const messageQueue = [];
const REGEX = {
SET_VOTING_PERIOD: /^!setvotingperiod \d+$/i,
POTENTIAL_MOVE: /^([NBRQK0-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');
let games = {};
let cooldownInterval;
// Socket.io part ---------------------------------------------
let app = require('express')();
let http = require('http').createServer(app);
let io = require('socket.io')(http);
let port = 3000;
app.get('/', (req, res) => {
res.sendFile(__dirname + '/votes.html');
});
io.on('connection', (socket) => {
socket.on('streamer', (streamer) => {
if (!streamer) streamer = OPTS.STREAMER_LICHESS;
socket.join(streamer.toLowerCase());
let game = games[gameIdFromTwitch(streamer)];
if (game) {
socket.emit('status', { state: 'started' });
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: true },
connection: {
secure: true,
reconnect: true,
},
identity: {
username: 'TTVChat', // just realized--this is wrong.. why does it still work?
password: OPTS.BOT_TWITCH_OAUTH,
},
channels: [OPTS.STREAMER_TWITCH],
});
// connect twitch client
client.connect();
// twitch client joins the streamer's chat
client.on('join', () => {
let userstate = client.userstate[`#${OPTS.STREAMER_TWITCH.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_TWITCH, msg);
}
function userIsAuthorized(username) {
return OPTS.AUTHORIZED_USERS.includes(username);
}
function isBotsTurn(game) {
return game.sloppyPGN !== null;
}
function alreadyVoted(username, game) {
return game.voters.has(username);
}
function alreadyOfferedDraw(username, game) {
return game.offeringDraw.has(username);
}
function isDrawOffer(message) {
return (
message.toLowerCase().trim() === 'offer draw' ||
message.toLowerCase().trim() === 'accept draw' ||
message.toLowerCase().trim() === 'offer/accept draw'
);
}
function checkMove(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 'resign';
else if (isDrawOffer(possibleMove)) return '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 emitStatus(game, data) {
io.to(game.streamer.twitch).emit('status', data);
}
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 (const 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)) {
const votingPeriod = parseInt(message.split(' ')[1]);
if (votingPeriod && votingPeriod > 3 && votingPeriod < 1200) {
OPTS.VOTING_PERIOD = votingPeriod;
say(`Voting period is now ${OPTS.VOTING_PERIOD} seconds.`);
}
return;
}
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)))
) {
if (REGEX.KINGSIDE_CASTLE.test(message)) message = 'O-O';
else if (REGEX.QUEENSIDE_CASTLE.test(message)) message = 'O-O-O';
const move = checkMove(message, gameId);
if (move) {
const key = move === 'resign' || move === 'draw' ? move : move.from + move.to;
if (game.candidates[key]) game.candidates[key].votes++;
else game.candidates[key] = { votes: 1, san: move.san };
(key === 'draw' ? game.offeringDraw : game.voters).add(tags.username);
game.candidates.total = new Set([...game.offeringDraw, ...game.voters]).size;
emitCandidates(game);
// log the vote
const msg = `@${tags['display-name']} voted ${
move === 'resign' ? 'to resign.' : move === 'draw' ? 'to offer/accept a draw.' : `for ${move.san}`
}`;
if (OPTS.ACKNOWLEDGE_VOTE) say(msg);
else console.log(msg);
}
}
});
function streamIncomingEvents() {
const options = {
hostname: 'lichess.org',
path: '/api/stream/event',
headers: { Authorization: `Bearer ${OPTS.BOT_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.BOT_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 (const 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.BOT_LICHESS.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) {
let moves = json.moves.split(' ');
let streamerMove = moves.pop();
let chess = games[gameId].initialFen ? new Chess(games[gameId].initialFen) : new Chess();
for (const 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');
}
}
}
} 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_TWITCH, msg);
}
async function initiateVote(gameId, moves, revote = 0) {
const game = games[gameId];
if (!game) 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.voters = new Set();
game.offeringDraw = new Set();
game.candidates = {};
game.sloppyPGN = moves;
emitStatus(game, { timer: OPTS.VOTING_PERIOD });
setTimeout(async () => {
const game = games[gameId];
if (!game) return;
const arr = Object.entries(game.candidates).filter(([key, _]) => key !== 'total' && key !== 'draw');
if (arr.length === 0) {
await initiateVote(gameId, moves, ++revote);
return;
}
const winningMove = arr.sort(([_, a], [__, b]) => b.votes - a.votes)[0];
const draw = (game.candidates.draw?.votes ?? 0) / game.candidates.total >= 0.5;
game.sloppyPGN = null;
if (winningMove[0] === 'resign') await resignGame(gameId);
else await makeMove(gameId, winningMove[0], draw);
say(`Playing move: ${winningMove[1].san}`);
}, OPTS.VOTING_PERIOD * 1000);
}
async function beginGame(gameId) {
try {
say('Game started!', gameId);
const game = {
white: null,
sloppyPGN: null,
candidates: {},
voters: new Set(),
offeringDraw: new Set(),
streamer: { twitch: OPTS.STREAMER_TWITCH.toLowerCase(), lichess: OPTS.STREAMER_LICHESS },
};
games[gameId] = game;
emitStatus(game, { state: 'started' });
let 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_TWITCH} 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.error(e);
}
}
async function acceptChallenge(challengeId) {
const options = {
hostname: 'lichess.org',
path: `/api/challenge/${challengeId}/accept`,
headers: { Authorization: `Bearer ${OPTS.BOT_LICHESS_OAUTH}` },
method: 'POST',
};
return new Promise((resolve, reject) => {
let 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.BOT_LICHESS_OAUTH}` },
method: 'POST',
};
return new Promise((resolve, reject) => {
const 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.BOT_LICHESS_OAUTH}` },
method: 'POST',
};
return new Promise((resolve, reject) => {
const 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();