summaryrefslogtreecommitdiff
path: root/src/api
diff options
context:
space:
mode:
authorElizabeth Hunt <elizabeth.hunt@simponic.xyz>2023-05-29 14:48:50 -0700
committerElizabeth Hunt <elizabeth.hunt@simponic.xyz>2023-11-21 17:57:10 -0700
commitf0ca174ada81a0ec4b1bbff9b70fcc680e4ca0ad (patch)
tree309e713bcb63918a4015c623fd778514c977e8ae /src/api
downloadchessh_bot-f0ca174ada81a0ec4b1bbff9b70fcc680e4ca0ad.tar.gz
chessh_bot-f0ca174ada81a0ec4b1bbff9b70fcc680e4ca0ad.zip
squash everything since there was profanity in the commit log and maybe people won't like thatHEADmain
Diffstat (limited to 'src/api')
-rw-r--r--src/api/Chessh.ts18
-rw-r--r--src/api/index.ts57
2 files changed, 75 insertions, 0 deletions
diff --git a/src/api/Chessh.ts b/src/api/Chessh.ts
new file mode 100644
index 0000000..7a35444
--- /dev/null
+++ b/src/api/Chessh.ts
@@ -0,0 +1,18 @@
+export interface BotMoveRequest {
+ bot_id: number;
+ bot_name: string;
+ game_id: number;
+ fen: string;
+ turn: string;
+ bot_turn: boolean;
+ last_move: string;
+ status: string;
+}
+
+export interface BotMoveAttempt {
+ attempted_move: string;
+}
+
+export interface BotMoveResponse {
+ message: string;
+}
diff --git a/src/api/index.ts b/src/api/index.ts
new file mode 100644
index 0000000..c55bb21
--- /dev/null
+++ b/src/api/index.ts
@@ -0,0 +1,57 @@
+import express from 'express';
+import {
+ BotMoveRequest,
+ BotMoveAttempt,
+ BotMoveResponse,
+} from './Chessh';
+import axios from 'axios';
+import { aiMove } from 'js-chess-engine';
+
+const router = express.Router();
+
+const chesshMovePath = (gameId: number) =>
+ process.env.CHESSH_MOVE_PATH!.replace(
+ ':gameId',
+ gameId.toString(),
+ );
+
+const sendNextMove = (gameId: number, move: string): Promise<BotMoveResponse> =>
+ axios
+ .post(chesshMovePath(gameId), {
+ attempted_move: move.toLowerCase(),
+ } as BotMoveAttempt, {
+ headers: {
+ "authorization": process.env.BOT_TOKEN!
+ }
+ })
+ .then((r): BotMoveResponse => {
+ const body = r.data as BotMoveResponse;
+ if (r.status === 200) {
+ return body;
+ }
+ throw new Error(
+ 'Move request unsuccessful, got back from cheSSH: ' +
+ JSON.stringify(body),
+ );
+ });
+
+router.post<BotMoveRequest, string>('/move', async (req, res) => {
+ const updateMessages: BotMoveRequest[] = Array.isArray(req.body)
+ ? req.body
+ : [req.body];
+
+ for (const update of updateMessages) {
+ if (update.bot_turn) {
+ const move = aiMove(update.fen, 3);
+
+ const moveFrom = Object.keys(move)[0];
+ const moveTo = move[moveFrom];
+
+ await sendNextMove(update.game_id, moveFrom + moveTo);
+ }
+ }
+
+ res.status(200).send('OK');
+});
+
+export default router;