Teleport2 (no king repositioning) + do not relay some challenges
[vchess.git] / server / sockets.js
index 3a776d1..4a61f68 100644 (file)
@@ -1,7 +1,7 @@
-const url = require('url');
+const Discord = require('discord.js');
+const { token, channel } = require('./config/discord.json');
 
 // Node version in Ubuntu 16.04 does not know about URL class
-// NOTE: url is already transformed, without ?xxx=yyy... parts
 function getJsonFromUrl(url) {
   const query = url.substr(2); //starts with "/?"
   let result = {};
@@ -27,6 +27,13 @@ module.exports = function(wss) {
   // NOTE: only purpose of sidToPages = know when to delete keys in idToSid
   let sidToPages = {};
   let idToSid = {};
+  const discordClient = new Discord.Client();
+  let discordChannel = null;
+  if (token.length > 0) {
+    discordClient.login(token).then( () => {
+      discordChannel = discordClient.channels.cache.get(channel);
+    });
+  }
   wss.on("connection", (socket, req) => {
     const query = getJsonFromUrl(req.url);
     const sid = query["sid"];
@@ -212,6 +219,20 @@ module.exports = function(wss) {
           // "newgame" message can provide a page (corr Game --> Hall)
           notifyRoom(
             obj.page || page, obj.code, {data: obj.data}, obj.excluded);
+          if (
+            obj.code == "newchallenge" &&
+            !obj.data.to && //filter out targeted challenges
+            obj.data.cadence.indexOf('d') < 0 //and correspondance games
+          ) {
+            const challMsg = (
+              "New challenge: **" + obj.data.vname + "** " +
+              "[" + obj.data.cadence + "]"
+            );
+            if (!!discordChannel) discordChannel.send(challMsg);
+            else
+              // Log when running locally (dev, debug):
+              console.log(challMsg);
+          }
           break;
 
         case "rnewgame":