From 703b838af111549fc2ac2a161894f65a7c76365f Mon Sep 17 00:00:00 2001 From: Alessandro Date: Sat, 28 Mar 2020 12:42:52 +0100 Subject: [PATCH 01/71] Update richieste server --- server.js | 51 ++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 38 insertions(+), 13 deletions(-) diff --git a/server.js b/server.js index 42d34e6..03aa465 100644 --- a/server.js +++ b/server.js @@ -12,19 +12,44 @@ exports.botServer = http.createServer((req, res) => { console.log(JSON.parse(jsonRes)); const response = JSON.parse(jsonRes); const chatId = response.chat_id; - const authCode = response.auth_code; - axios - .post( - `https://api.telegram.org/bot${tokenBot}/sendMessage?chat_id=${chatId}&text=Ecco il tuo codice di autenticazione: ${authCode}` - ) - .then(() => { - console.log("Messaggio inviato con successo"); - }) - .catch((err) => { - console.log( - "Errore " + err.response.status + " nell'invio del messaggio" - ); - }); + if (response.req_type == "authentication") { + const authCode = response.auth_code; + axios + .post( + `https://api.telegram.org/bot${tokenBot}/sendMessage?chat_id=${chatId}&text=Ecco il tuo codice di autenticazione: ${authCode}` + ) + .then(() => { + console.log("Messaggio inviato con successo"); + }) + .catch((err) => { + console.log( + "Errore " + err.response.status + " nell'invio del messaggio" + ); + }); + } else if (response.req_type == "alert") { + const deviceId = response.device_id; + const sensorId = response.sensor_id; + const sensorValue = response.sensor_value; + const threshold = response.threshold; + const valueType = response.value_type; + + const message1 = `⚠️ Il sensore ${sensorId} del dispositivo ${deviceId} ha registrato un valore di `; + const message2 = `${sensorValue} ${valueType} superando la soglia di ${threshold}`; + axios + .post( + `https://api.telegram.org/bot${tokenBot}/sendMessage?chat_id=${chatId}&text=` + + message1 + + message2 + ) + .then(() => { + console.log("Messaggio inviato con successo"); + }) + .catch((err) => { + console.log( + "Errore " + err.response.status + " nell'invio del messaggio" + ); + }); + } }); req.on("end", () => { console.log(JSON.parse(jsonRes)); From 0b1df078559eae43d0a4d7163d1c002757925d7d Mon Sep 17 00:00:00 2001 From: Alessandro Date: Sat, 28 Mar 2020 13:33:30 +0100 Subject: [PATCH 02/71] Aggiunta ricezione alert --- server.js | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/server.js b/server.js index 03aa465..fcc9515 100644 --- a/server.js +++ b/server.js @@ -2,7 +2,7 @@ const http = require("http"); // Richieste http const axios = require("axios"); - +const tokenBot = process.env.BOT_TOKEN; exports.botServer = http.createServer((req, res) => { // Request and Response object if (req.method === "POST") { @@ -33,8 +33,9 @@ exports.botServer = http.createServer((req, res) => { const threshold = response.threshold; const valueType = response.value_type; - const message1 = `⚠️ Il sensore ${sensorId} del dispositivo ${deviceId} ha registrato un valore di `; - const message2 = `${sensorValue} ${valueType} superando la soglia di ${threshold}`; + + const message1 = `Attenzione: il sensore ${sensorId} del dispositivo ${deviceId} ha registrato un valore di `; + const message2 = `${sensorValue} ${valueType} superando la soglia (${threshold})`; axios .post( `https://api.telegram.org/bot${tokenBot}/sendMessage?chat_id=${chatId}&text=` + @@ -45,9 +46,7 @@ exports.botServer = http.createServer((req, res) => { console.log("Messaggio inviato con successo"); }) .catch((err) => { - console.log( - "Errore " + err.response.status + " nell'invio del messaggio" - ); + console.log("Errore: " + err + " nell'invio del messaggio"); }); } }); @@ -55,6 +54,5 @@ exports.botServer = http.createServer((req, res) => { console.log(JSON.parse(jsonRes)); res.end("ok"); }); - console.log(jsonRes); } }); From 0c85e4efe59b45ef99cc884d699178cacc4b623a Mon Sep 17 00:00:00 2001 From: Alessandro Date: Sat, 28 Mar 2020 13:36:45 +0100 Subject: [PATCH 03/71] Rimosso spazio --- server.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/server.js b/server.js index fcc9515..fc317ec 100644 --- a/server.js +++ b/server.js @@ -32,8 +32,6 @@ exports.botServer = http.createServer((req, res) => { const sensorValue = response.sensor_value; const threshold = response.threshold; const valueType = response.value_type; - - const message1 = `Attenzione: il sensore ${sensorId} del dispositivo ${deviceId} ha registrato un valore di `; const message2 = `${sensorValue} ${valueType} superando la soglia (${threshold})`; axios From 9a51a399bbec49daae686350e8e1897b868a8e83 Mon Sep 17 00:00:00 2001 From: Alessandro Date: Sun, 29 Mar 2020 12:57:19 +0200 Subject: [PATCH 04/71] =?UTF-8?q?Aggiunta=20possibilit=C3=A0=20di=20riceve?= =?UTF-8?q?re=20pi=C3=B9=20chatId=20=20per=20alert?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server.js | 39 ++++++++++++++++++++++----------------- 1 file changed, 22 insertions(+), 17 deletions(-) diff --git a/server.js b/server.js index fc317ec..1f26ae5 100644 --- a/server.js +++ b/server.js @@ -11,9 +11,9 @@ exports.botServer = http.createServer((req, res) => { jsonRes += data.toString(); console.log(JSON.parse(jsonRes)); const response = JSON.parse(jsonRes); - const chatId = response.chat_id; - if (response.req_type == "authentication") { - const authCode = response.auth_code; + if (response.reqType == "authentication") { + const authCode = response.authCode; + const chatId = response.chat_id; axios .post( `https://api.telegram.org/bot${tokenBot}/sendMessage?chat_id=${chatId}&text=Ecco il tuo codice di autenticazione: ${authCode}` @@ -26,7 +26,8 @@ exports.botServer = http.createServer((req, res) => { "Errore " + err.response.status + " nell'invio del messaggio" ); }); - } else if (response.req_type == "alert") { + } else if (response.reqType == "alert") { + const chatsId = response.chat_id; const deviceId = response.device_id; const sensorId = response.sensor_id; const sensorValue = response.sensor_value; @@ -34,22 +35,26 @@ exports.botServer = http.createServer((req, res) => { const valueType = response.value_type; const message1 = `Attenzione: il sensore ${sensorId} del dispositivo ${deviceId} ha registrato un valore di `; const message2 = `${sensorValue} ${valueType} superando la soglia (${threshold})`; - axios - .post( - `https://api.telegram.org/bot${tokenBot}/sendMessage?chat_id=${chatId}&text=` + - message1 + - message2 - ) - .then(() => { - console.log("Messaggio inviato con successo"); - }) - .catch((err) => { - console.log("Errore: " + err + " nell'invio del messaggio"); - }); + // eslint-disable-next-line guard-for-in + for (const index in chatsId) { + console.log(chatsId[index]); + const chatId = chatsId[index]; + axios + .post( + `https://api.telegram.org/bot${tokenBot}/sendMessage?chat_id=${chatId}&text=` + + message1 + + message2 + ) + .then(() => { + console.log("Messaggio inviato con successo"); + }) + .catch((err) => { + console.log("Errore: " + err + " nell'invio del messaggio"); + }); + } } }); req.on("end", () => { - console.log(JSON.parse(jsonRes)); res.end("ok"); }); } From d9700bb80e73036ccbf6afaef774e5aacb4429f9 Mon Sep 17 00:00:00 2001 From: Alessandro Date: Mon, 30 Mar 2020 17:57:01 +0200 Subject: [PATCH 05/71] Aggiunti test server.js --- __tests__/bot.test.js | 7 ---- __tests__/server.test.js | 26 ++++++++++++++ commands/info.js | 11 +++--- commands/launch.js | 2 +- commands/login.js | 76 ++++++++++++++++++++-------------------- commands/start.js | 15 ++++---- commands/status.js | 56 ++++++++++++++--------------- main.js | 5 +-- server.js | 71 ++++++++++++++++++++++--------------- 9 files changed, 151 insertions(+), 118 deletions(-) delete mode 100644 __tests__/bot.test.js create mode 100644 __tests__/server.test.js diff --git a/__tests__/bot.test.js b/__tests__/bot.test.js deleted file mode 100644 index 73c4fc4..0000000 --- a/__tests__/bot.test.js +++ /dev/null @@ -1,7 +0,0 @@ -// NON RIMUOVERE LA RIGA SOTTOSTANTE // -require("../main"); - -test("Extracts value from JSON formatted string", () => { - const num = 4; - expect(num).toBe(4); -}); diff --git a/__tests__/server.test.js b/__tests__/server.test.js new file mode 100644 index 0000000..bd1a2aa --- /dev/null +++ b/__tests__/server.test.js @@ -0,0 +1,26 @@ +const { sendMessage, checkChatId } = require("../server"); + +test("Send message to invalid chat id", () => { + const message = "test"; + const chatId = "aaaaa"; + try { + sendMessage(message, chatId); + } catch (e) { + expect(e.message).toBe("Request failed with status code 400"); + } +}); + +test("Check chat id with invalid characters", () => { + const invalidChatId = "a48422329"; + expect(checkChatId(invalidChatId)).toBe(false); +}); + +test("Check chat id with invalid length", () => { + const invalidChatId = "167"; + expect(checkChatId(invalidChatId)).toBe(false); +}); + +test("Check valid chat id", () => { + const validChatId = "148422328"; + expect(checkChatId(validChatId)).toBe(true); +}); diff --git a/commands/info.js b/commands/info.js index c64448a..4396b16 100644 --- a/commands/info.js +++ b/commands/info.js @@ -1,11 +1,10 @@ const botInfo = (bot) => { - bot.command("info", ({ replyWithMarkdown }) => - replyWithMarkdown(` + bot.command("info", ({ replyWithMarkdown }) => + replyWithMarkdown(` Ecco la lista dei comandi disponibili: - Login: /login - Status: /status -- Info: /info` - ) - ); +- Info: /info`) + ); }; -module.exports.botInfo = botInfo; \ No newline at end of file +module.exports.botInfo = botInfo; diff --git a/commands/launch.js b/commands/launch.js index 545a88e..76be2f7 100644 --- a/commands/launch.js +++ b/commands/launch.js @@ -1,4 +1,4 @@ const botLaunch = (bot) => { - bot.launch(); + bot.launch(); }; module.exports.botLaunch = botLaunch; \ No newline at end of file diff --git a/commands/login.js b/commands/login.js index 0d9163c..1c76f41 100644 --- a/commands/login.js +++ b/commands/login.js @@ -2,43 +2,43 @@ const axios = require("axios"); const botLogin = (bot) => { - bot.command("login", (message) => { - const username = message.from.username; - const chatId = message.from.id; - axios - .post(`http://localhost:9999/auth/telegram`, { - telegramName: username, - telegramChat: chatId, - }) - .then((res) => { - const code = res.data.code; - const token = res.data.token; + bot.command("login", (message) => { + const username = message.from.username; + const chatId = message.from.id; + axios + .post(`http://localhost:9999/auth/telegram`, { + telegramName: username, + telegramChat: chatId, + }) + .then((res) => { + const code = res.data.code; + const token = res.data.token; - if (code === 1) { - axios.defaults.headers.common["Authorization"] = "Bearer " + token; - return message.reply("Username trovato, registrazione riuscita"); - } else if (code === 2) { - axios.defaults.headers.common["Authorization"] = "Bearer " + token; - return message.reply( - "Account già registrato, nessuna modifica apportata" - ); - } else if (code === 0) { - return message.reply( - "Username non trovato, registra il tuo Username dalla web-app" - ); - } - }) - .catch((err) => { - console.log(err); - // console.log(err.status); - if (err.response.status === 403) { - return message.reply( - "Rieffettua l'autenticazione usando il comando /login" - ); - } else { - return message.reply("Errore nel controllo dei dati"); - } - }); - }); + if (code === 1) { + axios.defaults.headers.common["Authorization"] = "Bearer " + token; + return message.reply("Username trovato, registrazione riuscita"); + } else if (code === 2) { + axios.defaults.headers.common["Authorization"] = "Bearer " + token; + return message.reply( + "Account già registrato, nessuna modifica apportata" + ); + } else if (code === 0) { + return message.reply( + "Username non trovato, registra il tuo Username dalla web-app" + ); + } + }) + .catch((err) => { + console.log(err); + // console.log(err.status); + if (err.response.status === 403) { + return message.reply( + "Rieffettua l'autenticazione usando il comando /login" + ); + } else { + return message.reply("Errore nel controllo dei dati"); + } + }); + }); }; -module.exports.botLogin = botLogin; \ No newline at end of file +module.exports.botLogin = botLogin; diff --git a/commands/start.js b/commands/start.js index 6a10402..a260967 100644 --- a/commands/start.js +++ b/commands/start.js @@ -1,13 +1,12 @@ const botStart = (bot) => { - bot.start((message) => { - console.log("started:", message.from.id); - const username = message.from.username; - return message.replyWithMarkdown(` + bot.start((message) => { + console.log("started:", message.from.id); + const username = message.from.username; + return message.replyWithMarkdown(` Ciao *${username}*, benvenuto nel bot di ThiReMa! Usa il comando /login per effettuare l'autenticazione. -Per vedere la lista del comandi che puoi utilizzare usa il comando /info` - ); - }); +Per vedere la lista del comandi che puoi utilizzare usa il comando /info`); + }); }; -module.exports.botStart = botStart; \ No newline at end of file +module.exports.botStart = botStart; diff --git a/commands/status.js b/commands/status.js index da77b24..36b1598 100644 --- a/commands/status.js +++ b/commands/status.js @@ -2,37 +2,37 @@ const axios = require("axios"); const botStatus = (bot) => { - bot.command("status", (message) => { - axios - .get(`http://localhost:9999/status`) - .then((res) => { - const data = res.data; - const name = data.name; - const surname = data.surname; - const email = data.email; - const typeNumber = data.type; - let type = "Utente"; - if (typeNumber === 1) { - type = "Moderatore"; - } else if (typeNumber === 2) { - type = "Amministratore"; - } - return message.replyWithMarkdown( - ` + bot.command("status", (message) => { + axios + .get(`http://localhost:9999/status`) + .then((res) => { + const data = res.data; + const name = data.name; + const surname = data.surname; + const email = data.email; + const typeNumber = data.type; + let type = "Utente"; + if (typeNumber === 1) { + type = "Moderatore"; + } else if (typeNumber === 2) { + type = "Amministratore"; + } + return message.replyWithMarkdown( + ` Ecco i tuoi dati *${message.from.username}* - *Nome:* ${name} - *Cognome:* ${surname} - *Email:* ${email} - *Tipo:* ${type}` - ); - }) - .catch((err) => { - if (err.response.status === 403) { - message.reply("Rieffettua l'autenticazione usando il comando /login"); - } else { - message.reply("Errore nel controllo dei dati"); - } - }); - }); + ); + }) + .catch((err) => { + if (err.response.status === 403) { + message.reply("Rieffettua l'autenticazione usando il comando /login"); + } else { + message.reply("Errore nel controllo dei dati"); + } + }); + }); }; -module.exports.botStatus = botStatus; \ No newline at end of file +module.exports.botStatus = botStatus; diff --git a/main.js b/main.js index 46d5411..866c8cc 100644 --- a/main.js +++ b/main.js @@ -5,7 +5,8 @@ const Telegraf = require("telegraf"); const tokenBot = process.env.BOT_TOKEN; const bot = new Telegraf(tokenBot); -const server = require("./server"); +// eslint-disable-next-line no-unused-vars +const { botServer, checkChatId, sendMessage } = require("./server"); const botLaunch = require("./commands/launch"); const botStart = require("./commands/start"); const botInfo = require("./commands/info"); @@ -19,7 +20,7 @@ botInfo.botInfo(bot); botLogin.botLogin(bot); botStatus.botStatus(bot); -server.botServer.listen(3000, "127.0.0.1"); +botServer.listen(3000, "127.0.0.1"); console.log("Server to port 3000"); botLaunch.botLaunch(bot); diff --git a/server.js b/server.js index 1f26ae5..f98de2d 100644 --- a/server.js +++ b/server.js @@ -3,7 +3,34 @@ const http = require("http"); // Richieste http const axios = require("axios"); const tokenBot = process.env.BOT_TOKEN; -exports.botServer = http.createServer((req, res) => { + +/** + * Sending a message to a given Telegram chat id + * @param {string} message + * @param {string} chatId + */ +const sendMessage = (message, chatId) => { + axios + .post( + `https://api.telegram.org/bot${tokenBot}/sendMessage?chat_id=${chatId}&text=Ecco il tuo codice di autenticazione: ${message}` + ) + .then(() => { + console.log("Messaggio inviato con successo"); + }) + .catch((err) => { + console.log( + "Errore " + err.response.status + " nell'invio del messaggio" + ); + }); +}; + +const checkChatId = (chatId) => { + const pattern = "^[0-9]{6,}$"; + const regex = new RegExp(pattern); + return regex.test(chatId); +}; + +const botServer = http.createServer((req, res) => { // Request and Response object if (req.method === "POST") { let jsonRes = ""; @@ -14,18 +41,12 @@ exports.botServer = http.createServer((req, res) => { if (response.reqType == "authentication") { const authCode = response.authCode; const chatId = response.chat_id; - axios - .post( - `https://api.telegram.org/bot${tokenBot}/sendMessage?chat_id=${chatId}&text=Ecco il tuo codice di autenticazione: ${authCode}` - ) - .then(() => { - console.log("Messaggio inviato con successo"); - }) - .catch((err) => { - console.log( - "Errore " + err.response.status + " nell'invio del messaggio" - ); - }); + if (!checkChatId(chatId)) { + console.log("Invalid chat id"); + } else { + const message = `Ecco il tuo codice di autenticazione: ${authCode}`; + sendMessage(message, chatId); + } } else if (response.reqType == "alert") { const chatsId = response.chat_id; const deviceId = response.device_id; @@ -33,24 +54,17 @@ exports.botServer = http.createServer((req, res) => { const sensorValue = response.sensor_value; const threshold = response.threshold; const valueType = response.value_type; - const message1 = `Attenzione: il sensore ${sensorId} del dispositivo ${deviceId} ha registrato un valore di `; - const message2 = `${sensorValue} ${valueType} superando la soglia (${threshold})`; + const messagePart1 = `Attenzione: il sensore ${sensorId} del dispositivo ${deviceId} ha registrato un valore di `; + const messagePart2 = `${sensorValue} ${valueType} superando la soglia (${threshold})`; + const message = messagePart1 + messagePart2; // eslint-disable-next-line guard-for-in for (const index in chatsId) { - console.log(chatsId[index]); const chatId = chatsId[index]; - axios - .post( - `https://api.telegram.org/bot${tokenBot}/sendMessage?chat_id=${chatId}&text=` + - message1 + - message2 - ) - .then(() => { - console.log("Messaggio inviato con successo"); - }) - .catch((err) => { - console.log("Errore: " + err + " nell'invio del messaggio"); - }); + if (!checkChatId(chatId)) { + console.log("Invalid chat id"); + } else { + sendMessage(message, chatId); + } } } }); @@ -59,3 +73,4 @@ exports.botServer = http.createServer((req, res) => { }); } }); +module.exports = { botServer, checkChatId, sendMessage }; From e9b8115dd0ca6dfc0501cd5f069eccc39d276f98 Mon Sep 17 00:00:00 2001 From: Alessandro Date: Tue, 31 Mar 2020 10:19:45 +0200 Subject: [PATCH 06/71] Fix messaggio --- server.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/server.js b/server.js index f98de2d..14aa37c 100644 --- a/server.js +++ b/server.js @@ -12,7 +12,7 @@ const tokenBot = process.env.BOT_TOKEN; const sendMessage = (message, chatId) => { axios .post( - `https://api.telegram.org/bot${tokenBot}/sendMessage?chat_id=${chatId}&text=Ecco il tuo codice di autenticazione: ${message}` + `https://api.telegram.org/bot${tokenBot}/sendMessage?chat_id=${chatId}&text=${message}` ) .then(() => { console.log("Messaggio inviato con successo"); @@ -44,8 +44,8 @@ const botServer = http.createServer((req, res) => { if (!checkChatId(chatId)) { console.log("Invalid chat id"); } else { - const message = `Ecco il tuo codice di autenticazione: ${authCode}`; - sendMessage(message, chatId); + const authMessage = `Ecco il tuo codice di autenticazione: ${authCode}`; + sendMessage(authMessage, chatId); } } else if (response.reqType == "alert") { const chatsId = response.chat_id; @@ -56,14 +56,14 @@ const botServer = http.createServer((req, res) => { const valueType = response.value_type; const messagePart1 = `Attenzione: il sensore ${sensorId} del dispositivo ${deviceId} ha registrato un valore di `; const messagePart2 = `${sensorValue} ${valueType} superando la soglia (${threshold})`; - const message = messagePart1 + messagePart2; + const alertMessage = messagePart1 + messagePart2; // eslint-disable-next-line guard-for-in for (const index in chatsId) { const chatId = chatsId[index]; if (!checkChatId(chatId)) { console.log("Invalid chat id"); } else { - sendMessage(message, chatId); + sendMessage(alertMessage, chatId); } } } From 739d127e4e44280243c3c6f2e576c3cee9e88e05 Mon Sep 17 00:00:00 2001 From: Lorenzo Dei Negri Date: Fri, 10 Apr 2020 12:18:18 +0200 Subject: [PATCH 07/71] Prima versione del dockerfile e dello script --- Dockerfile | 6 ++++++ start.sh | 11 +++++++++++ 2 files changed, 17 insertions(+) create mode 100644 Dockerfile create mode 100644 start.sh diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..f9b0fa6 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,6 @@ +# docker run --run -d -p 9999:9999 rrr/api +FROM node:12.16.2-alpine3.11 +COPY . /usr/src/telegram +EXPOSE 9999 +WORKDIR /usr/src/telegram +CMD ["sh", "start.sh"] diff --git a/start.sh b/start.sh new file mode 100644 index 0000000..4525cdf --- /dev/null +++ b/start.sh @@ -0,0 +1,11 @@ +#!/bin/sh + +npm update + +npm install --production + +# TODO: add BOT_TOKEN + +node main.js + +echo "Telegram bot started..." From 6a6d0a8547abe66a760551ecc4b349214eca4147 Mon Sep 17 00:00:00 2001 From: Giovanni Date: Fri, 10 Apr 2020 21:15:22 +0200 Subject: [PATCH 08/71] test --- bot.test.js | 17 +++++++++++++++++ server.js | 5 ++++- 2 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 bot.test.js diff --git a/bot.test.js b/bot.test.js new file mode 100644 index 0000000..0481a11 --- /dev/null +++ b/bot.test.js @@ -0,0 +1,17 @@ +// test bot +const { checkChatId, sendMessage } = require("./server"); + +// CHATID TEST +// eslint-disable-next-line require-jsdoc +function getRandomArbitrary(min, max) { + return Math.floor(Math.random() * (max - min + 1) + min); +} +const chatId = getRandomArbitrary(100000000, 999999999); +test("Chat id: ", () => { + expect(checkChatId(chatId)).toBe(true); +}); + +// SEND MESSAGE TEST da cambiare undefined +test("sendMessage", () => { + expect(sendMessage("ciao", "226026285")).toBe(undefined); +}); diff --git a/server.js b/server.js index 14aa37c..7130732 100644 --- a/server.js +++ b/server.js @@ -14,8 +14,11 @@ const sendMessage = (message, chatId) => { .post( `https://api.telegram.org/bot${tokenBot}/sendMessage?chat_id=${chatId}&text=${message}` ) - .then(() => { + .then((res) => { console.log("Messaggio inviato con successo"); + console.log(res.response.status); + console.log(res.data); + res.json("OK"); }) .catch((err) => { console.log( From f23a5a47816fdd996689beed258a47d5d385f05f Mon Sep 17 00:00:00 2001 From: Giovanni Date: Fri, 10 Apr 2020 22:17:12 +0200 Subject: [PATCH 09/71] test login --- __tests__/server.test.js | 1 + bot.test.js | 6 ++++++ server.js | 1 + 3 files changed, 8 insertions(+) diff --git a/__tests__/server.test.js b/__tests__/server.test.js index bd1a2aa..81a3c68 100644 --- a/__tests__/server.test.js +++ b/__tests__/server.test.js @@ -1,5 +1,6 @@ const { sendMessage, checkChatId } = require("../server"); + test("Send message to invalid chat id", () => { const message = "test"; const chatId = "aaaaa"; diff --git a/bot.test.js b/bot.test.js index 0481a11..3fead97 100644 --- a/bot.test.js +++ b/bot.test.js @@ -1,5 +1,7 @@ // test bot const { checkChatId, sendMessage } = require("./server"); +const { botLogin } = require("./commands/login"); +const bot = require("telegraf"); // CHATID TEST // eslint-disable-next-line require-jsdoc @@ -15,3 +17,7 @@ test("Chat id: ", () => { test("sendMessage", () => { expect(sendMessage("ciao", "226026285")).toBe(undefined); }); + +test("login", () => { + expect(botLogin(bot)).toBe(undefined); +}); \ No newline at end of file diff --git a/server.js b/server.js index 7130732..e58d19b 100644 --- a/server.js +++ b/server.js @@ -19,6 +19,7 @@ const sendMessage = (message, chatId) => { console.log(res.response.status); console.log(res.data); res.json("OK"); + return message.reply("OK"); }) .catch((err) => { console.log( From 8124f0baf3e0396cf23c0b700298c1334e9893a8 Mon Sep 17 00:00:00 2001 From: Giovanni Date: Fri, 10 Apr 2020 22:20:04 +0200 Subject: [PATCH 10/71] Update bot.test.js --- bot.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot.test.js b/bot.test.js index 3fead97..41fbdb5 100644 --- a/bot.test.js +++ b/bot.test.js @@ -20,4 +20,4 @@ test("sendMessage", () => { test("login", () => { expect(botLogin(bot)).toBe(undefined); -}); \ No newline at end of file +}); From e0e7e041975861cf80a946a792c447749e79212a Mon Sep 17 00:00:00 2001 From: Giovanni Date: Sat, 11 Apr 2020 18:08:14 +0200 Subject: [PATCH 11/71] test comandi --- __tests__/bot.test.js | 33 +++++++++++++++++++++++++++++++++ __tests__/server.test.js | 27 +++++++++++++++++++++++---- bot.test.js | 23 ----------------------- commands/launch.js | 2 +- server.js | 1 - 5 files changed, 57 insertions(+), 29 deletions(-) create mode 100644 __tests__/bot.test.js delete mode 100644 bot.test.js diff --git a/__tests__/bot.test.js b/__tests__/bot.test.js new file mode 100644 index 0000000..0b06d85 --- /dev/null +++ b/__tests__/bot.test.js @@ -0,0 +1,33 @@ +// test bot +const { checkChatId, sendMessage } = require("../server"); +const botLaunch = require("../commands/launch"); +const { botStart } = require("../commands/start"); +const { botInfo } = require("../commands/info"); +const { botLogin } = require("../commands/login"); +const { botStatus } = require("../commands/status"); + +const Telegraf = require("telegraf"); +const tokenBot = process.env.BOT_TOKEN; +const bot = new Telegraf(tokenBot); + +// LOGIN +test("Check login", () => { + expect(botLogin(bot)).toBe(undefined); +}); +// LAUNCH +test("Check status", () => { + expect(botStatus(bot)).toBe(undefined); +}); +// START +test("Check status", () => { + expect(botStart(bot)).toBe(undefined); +}); +// INFO +test("Check info", () => { + expect(botInfo(bot)).toBe(undefined); +}); +// const s = {"botLaunch": [Function botLaunch]`; +// const t = JSON.parse(s); +// test("Check launch", () => { +// expect(botLaunch).toBe(t); +// }); diff --git a/__tests__/server.test.js b/__tests__/server.test.js index 81a3c68..143e599 100644 --- a/__tests__/server.test.js +++ b/__tests__/server.test.js @@ -1,5 +1,5 @@ -const { sendMessage, checkChatId } = require("../server"); - +const { botServer, sendMessage, checkChatId } = require("../server"); +const http = require("http"); test("Send message to invalid chat id", () => { const message = "test"; @@ -11,6 +11,16 @@ test("Send message to invalid chat id", () => { } }); +test("Send message to valid chat id", () => { + const message = "test"; + const chatId = "192645345"; + try { + sendMessage(message, chatId); + expect(message).toBe("test"); + } catch (e) { + } +}); + test("Check chat id with invalid characters", () => { const invalidChatId = "a48422329"; expect(checkChatId(invalidChatId)).toBe(false); @@ -21,7 +31,16 @@ test("Check chat id with invalid length", () => { expect(checkChatId(invalidChatId)).toBe(false); }); +// eslint-disable-next-line require-jsdoc +function getRandomArbitrary(min, max) { + return Math.floor(Math.random() * (max - min + 1) + min); +} +const chatId = getRandomArbitrary(100000000, 999999999); test("Check valid chat id", () => { - const validChatId = "148422328"; - expect(checkChatId(validChatId)).toBe(true); + expect(checkChatId(chatId)).toBe(true); }); + +// const req = { metod: "POST", reqType: "authentication" }; +// test("Check authentication request", () => { +// expect(botServer.toString()).toBe("[object Object]"); +// }); diff --git a/bot.test.js b/bot.test.js deleted file mode 100644 index 41fbdb5..0000000 --- a/bot.test.js +++ /dev/null @@ -1,23 +0,0 @@ -// test bot -const { checkChatId, sendMessage } = require("./server"); -const { botLogin } = require("./commands/login"); -const bot = require("telegraf"); - -// CHATID TEST -// eslint-disable-next-line require-jsdoc -function getRandomArbitrary(min, max) { - return Math.floor(Math.random() * (max - min + 1) + min); -} -const chatId = getRandomArbitrary(100000000, 999999999); -test("Chat id: ", () => { - expect(checkChatId(chatId)).toBe(true); -}); - -// SEND MESSAGE TEST da cambiare undefined -test("sendMessage", () => { - expect(sendMessage("ciao", "226026285")).toBe(undefined); -}); - -test("login", () => { - expect(botLogin(bot)).toBe(undefined); -}); diff --git a/commands/launch.js b/commands/launch.js index 76be2f7..97d5e20 100644 --- a/commands/launch.js +++ b/commands/launch.js @@ -1,4 +1,4 @@ const botLaunch = (bot) => { bot.launch(); }; -module.exports.botLaunch = botLaunch; \ No newline at end of file +module.exports.botLaunch = botLaunch; diff --git a/server.js b/server.js index e58d19b..7130732 100644 --- a/server.js +++ b/server.js @@ -19,7 +19,6 @@ const sendMessage = (message, chatId) => { console.log(res.response.status); console.log(res.data); res.json("OK"); - return message.reply("OK"); }) .catch((err) => { console.log( From c80cc58726be0c89907c5a71c89da031a890a463 Mon Sep 17 00:00:00 2001 From: Mariano Date: Sat, 11 Apr 2020 20:02:52 +0200 Subject: [PATCH 12/71] Aggiunta file .env --- .env | 1 + .gitignore | 9 +-------- 2 files changed, 2 insertions(+), 8 deletions(-) create mode 100644 .env diff --git a/.env b/.env new file mode 100644 index 0000000..2b516de --- /dev/null +++ b/.env @@ -0,0 +1 @@ +BOT_TOKEN=1120382460:AAGy8CdhjdMxaS99K3za1Jxoqp-ayPuVC1w \ No newline at end of file diff --git a/.gitignore b/.gitignore index 5daf6b0..c7afe10 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,5 @@ node_modules .DS_Store -.env - .idea target/ out/ @@ -9,9 +7,4 @@ coverage/ *.iws *.iml *.ipr - -Icon - -Icon - -.env +Icon From a5d82ea9962763751010b04fb0f03a6bc4fae445 Mon Sep 17 00:00:00 2001 From: Lorenzo Dei Negri Date: Sat, 11 Apr 2020 20:08:07 +0200 Subject: [PATCH 13/71] Fixoni --- Dockerfile | 2 +- start.sh | 4 ---- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/Dockerfile b/Dockerfile index f9b0fa6..1113212 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,6 @@ # docker run --run -d -p 9999:9999 rrr/api FROM node:12.16.2-alpine3.11 COPY . /usr/src/telegram -EXPOSE 9999 +EXPOSE 3000 WORKDIR /usr/src/telegram CMD ["sh", "start.sh"] diff --git a/start.sh b/start.sh index 4525cdf..19ed22f 100644 --- a/start.sh +++ b/start.sh @@ -1,11 +1,7 @@ #!/bin/sh -npm update - npm install --production -# TODO: add BOT_TOKEN - node main.js echo "Telegram bot started..." From 48c1be61b0196e198bca80f0d473b2fa59a1689b Mon Sep 17 00:00:00 2001 From: Mariano Date: Sat, 11 Apr 2020 20:21:58 +0200 Subject: [PATCH 14/71] Nuovo host comandi --- commands/login.js | 2 +- commands/status.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/commands/login.js b/commands/login.js index 0d9163c..a49321b 100644 --- a/commands/login.js +++ b/commands/login.js @@ -6,7 +6,7 @@ const botLogin = (bot) => { const username = message.from.username; const chatId = message.from.id; axios - .post(`http://localhost:9999/auth/telegram`, { + .post(`http://core.host.redroundrobin.site:9999/auth/telegram`, { telegramName: username, telegramChat: chatId, }) diff --git a/commands/status.js b/commands/status.js index da77b24..29122ea 100644 --- a/commands/status.js +++ b/commands/status.js @@ -4,7 +4,7 @@ const axios = require("axios"); const botStatus = (bot) => { bot.command("status", (message) => { axios - .get(`http://localhost:9999/status`) + .get(`http://core.host.redroundrobin.site:9999/status`) .then((res) => { const data = res.data; const name = data.name; From 4a203ad01d7e5f8b47686ef27d060a578b94fb3e Mon Sep 17 00:00:00 2001 From: Mariano Date: Sat, 11 Apr 2020 21:11:29 +0200 Subject: [PATCH 15/71] Update main.js --- main.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.js b/main.js index 46d5411..1a85fbc 100644 --- a/main.js +++ b/main.js @@ -19,7 +19,7 @@ botInfo.botInfo(bot); botLogin.botLogin(bot); botStatus.botStatus(bot); -server.botServer.listen(3000, "127.0.0.1"); +server.botServer.listen(3000, "core.host.redroundrobin.site"); console.log("Server to port 3000"); botLaunch.botLaunch(bot); From 14edc84c60c99a0de57379be7b257f954baabccd Mon Sep 17 00:00:00 2001 From: Lorenzo Dei Negri Date: Sat, 11 Apr 2020 22:19:44 +0200 Subject: [PATCH 16/71] Update main.js --- main.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.js b/main.js index 1a85fbc..ffc76a2 100644 --- a/main.js +++ b/main.js @@ -19,7 +19,7 @@ botInfo.botInfo(bot); botLogin.botLogin(bot); botStatus.botStatus(bot); -server.botServer.listen(3000, "core.host.redroundrobin.site"); +server.botServer.listen(3000); console.log("Server to port 3000"); botLaunch.botLaunch(bot); From 4a8935f8cb1c1fb18aa65a149b82f2f1c2fc1b5c Mon Sep 17 00:00:00 2001 From: Lorenzo Dei Negri Date: Sat, 11 Apr 2020 22:48:11 +0200 Subject: [PATCH 17/71] Update main.js --- main.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/main.js b/main.js index ffc76a2..62eccbb 100644 --- a/main.js +++ b/main.js @@ -2,7 +2,8 @@ require("dotenv").config(); const Telegraf = require("telegraf"); // Tokenbot e creazione bot -const tokenBot = process.env.BOT_TOKEN; +// const tokenBot = process.env.BOT_TOKEN; +const tokenBot = "1120382460:AAGy8CdhjdMxaS99K3za1Jxoqp-ayPuVC1w" const bot = new Telegraf(tokenBot); const server = require("./server"); From 00ab27d4bd24c1d486f3a1f7e63ea08d148d6733 Mon Sep 17 00:00:00 2001 From: Lorenzo Dei Negri Date: Sat, 11 Apr 2020 22:51:46 +0200 Subject: [PATCH 18/71] Update main.js --- main.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.js b/main.js index 62eccbb..7ea3ec0 100644 --- a/main.js +++ b/main.js @@ -3,7 +3,7 @@ const Telegraf = require("telegraf"); // Tokenbot e creazione bot // const tokenBot = process.env.BOT_TOKEN; -const tokenBot = "1120382460:AAGy8CdhjdMxaS99K3za1Jxoqp-ayPuVC1w" +const tokenBot = "1120382460:AAGy8CdhjdMxaS99K3za1Jxoqp-ayPuVC1w"; const bot = new Telegraf(tokenBot); const server = require("./server"); From b8da153934b53679b90bcdd6236e7361a46e8e91 Mon Sep 17 00:00:00 2001 From: Mariano Date: Sat, 11 Apr 2020 22:56:07 +0200 Subject: [PATCH 19/71] Stockastico --- main.js | 3 +-- server.js | 4 ++++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/main.js b/main.js index 7ea3ec0..ffc76a2 100644 --- a/main.js +++ b/main.js @@ -2,8 +2,7 @@ require("dotenv").config(); const Telegraf = require("telegraf"); // Tokenbot e creazione bot -// const tokenBot = process.env.BOT_TOKEN; -const tokenBot = "1120382460:AAGy8CdhjdMxaS99K3za1Jxoqp-ayPuVC1w"; +const tokenBot = process.env.BOT_TOKEN; const bot = new Telegraf(tokenBot); const server = require("./server"); diff --git a/server.js b/server.js index 42d34e6..06ea45d 100644 --- a/server.js +++ b/server.js @@ -1,7 +1,11 @@ +require("dotenv").config(); + // Richiesta per creazione server const http = require("http"); // Richieste http const axios = require("axios"); +// TokenBot +const tokenBot = process.env.BOT_TOKEN; exports.botServer = http.createServer((req, res) => { // Request and Response object From b08011bb677fca8292e04365a9362136d37f9a7e Mon Sep 17 00:00:00 2001 From: Mariano Date: Sat, 11 Apr 2020 23:21:03 +0200 Subject: [PATCH 20/71] Update server.js --- server.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server.js b/server.js index 98067c1..6ea924a 100644 --- a/server.js +++ b/server.js @@ -46,7 +46,7 @@ const botServer = http.createServer((req, res) => { const response = JSON.parse(jsonRes); if (response.reqType == "authentication") { const authCode = response.authCode; - const chatId = response.chat_id; + const chatId = response.chatId; if (!checkChatId(chatId)) { console.log("Invalid chat id"); } else { From f9f0282835278c8f6e63f0943da266b15adc18f0 Mon Sep 17 00:00:00 2001 From: Mariano Date: Sat, 11 Apr 2020 23:22:23 +0200 Subject: [PATCH 21/71] Update server.js --- server.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/server.js b/server.js index 6ea924a..d435f6d 100644 --- a/server.js +++ b/server.js @@ -54,12 +54,12 @@ const botServer = http.createServer((req, res) => { sendMessage(authMessage, chatId); } } else if (response.reqType == "alert") { - const chatsId = response.chat_id; - const deviceId = response.device_id; - const sensorId = response.sensor_id; - const sensorValue = response.sensor_value; + const chatsId = response.chatId; + const deviceId = response.deviceId; + const sensorId = response.sensorId; + const sensorValue = response.sensorValue; const threshold = response.threshold; - const valueType = response.value_type; + const valueType = response.valueType; const messagePart1 = `Attenzione: il sensore ${sensorId} del dispositivo ${deviceId} ha registrato un valore di `; const messagePart2 = `${sensorValue} ${valueType} superando la soglia (${threshold})`; const alertMessage = messagePart1 + messagePart2; From 76635e9c4972824812c83b6d3735c5a7b8b12058 Mon Sep 17 00:00:00 2001 From: Mariano Date: Sat, 11 Apr 2020 23:25:54 +0200 Subject: [PATCH 22/71] Update main.js --- main.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/main.js b/main.js index f880721..5468e9a 100644 --- a/main.js +++ b/main.js @@ -20,8 +20,7 @@ botInfo.botInfo(bot); botLogin.botLogin(bot); botStatus.botStatus(bot); -server.botServer.listen(3000); - +botServer.listen(3000); console.log("Server to port 3000"); botLaunch.botLaunch(bot); From 99c6970f3dc6e831c28e07f56c10237bd0b7c8bd Mon Sep 17 00:00:00 2001 From: Giovanni Date: Mon, 13 Apr 2020 14:29:43 +0200 Subject: [PATCH 23/71] test CI --- __tests__/bot.test.js | 2 -- __tests__/server.test.js | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/__tests__/bot.test.js b/__tests__/bot.test.js index 0b06d85..2d7d165 100644 --- a/__tests__/bot.test.js +++ b/__tests__/bot.test.js @@ -1,6 +1,4 @@ // test bot -const { checkChatId, sendMessage } = require("../server"); -const botLaunch = require("../commands/launch"); const { botStart } = require("../commands/start"); const { botInfo } = require("../commands/info"); const { botLogin } = require("../commands/login"); diff --git a/__tests__/server.test.js b/__tests__/server.test.js index 143e599..5f111d0 100644 --- a/__tests__/server.test.js +++ b/__tests__/server.test.js @@ -1,4 +1,4 @@ -const { botServer, sendMessage, checkChatId } = require("../server"); +const { sendMessage, checkChatId } = require("../server"); const http = require("http"); test("Send message to invalid chat id", () => { From 94d62e523837d9d235f53adf21bf0d99f9820d71 Mon Sep 17 00:00:00 2001 From: Giovanni Date: Mon, 13 Apr 2020 14:34:48 +0200 Subject: [PATCH 24/71] Update server.test.js --- __tests__/server.test.js | 1 - 1 file changed, 1 deletion(-) diff --git a/__tests__/server.test.js b/__tests__/server.test.js index 5f111d0..a2681b9 100644 --- a/__tests__/server.test.js +++ b/__tests__/server.test.js @@ -1,5 +1,4 @@ const { sendMessage, checkChatId } = require("../server"); -const http = require("http"); test("Send message to invalid chat id", () => { const message = "test"; From 55c39df73c2079aefaa00181f515afa2258693d6 Mon Sep 17 00:00:00 2001 From: Giovanni Date: Mon, 13 Apr 2020 14:38:52 +0200 Subject: [PATCH 25/71] Update server.test.js --- __tests__/server.test.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/__tests__/server.test.js b/__tests__/server.test.js index a2681b9..aa26dd4 100644 --- a/__tests__/server.test.js +++ b/__tests__/server.test.js @@ -6,7 +6,7 @@ test("Send message to invalid chat id", () => { try { sendMessage(message, chatId); } catch (e) { - expect(e.message).toBe("Request failed with status code 400"); + expect(e.message).toBe("Errore 400 nell'invio del messaggio"); } }); @@ -17,6 +17,7 @@ test("Send message to valid chat id", () => { sendMessage(message, chatId); expect(message).toBe("test"); } catch (e) { + console.log("Errore nell'invio del messaggio"); } }); From 97825ace7637a44468e7a0e806b4f550206f1fb2 Mon Sep 17 00:00:00 2001 From: Lorenzo Dei Negri Date: Tue, 14 Apr 2020 22:55:14 +0200 Subject: [PATCH 26/71] Fix indirizzo --- commands/login.js | 2 +- commands/status.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/commands/login.js b/commands/login.js index 45ec6e1..7af55f1 100644 --- a/commands/login.js +++ b/commands/login.js @@ -6,7 +6,7 @@ const botLogin = (bot) => { const username = message.from.username; const chatId = message.from.id; axios - .post(`http://core.host.redroundrobin.site:9999/auth/telegram`, { + .post(`http://thirema_api:9999/auth/telegram`, { telegramName: username, telegramChat: chatId, }) diff --git a/commands/status.js b/commands/status.js index f85ce19..17073bf 100644 --- a/commands/status.js +++ b/commands/status.js @@ -4,7 +4,7 @@ const axios = require("axios"); const botStatus = (bot) => { bot.command("status", (message) => { axios - .get(`http://core.host.redroundrobin.site:9999/status`) + .get(`http://thirema_api:9999/status`) .then((res) => { const data = res.data; const name = data.name; From 32274297dcd9ede74ee84e8fe74426b4e79e72fd Mon Sep 17 00:00:00 2001 From: Lorenzo Dei Negri Date: Tue, 14 Apr 2020 23:47:22 +0200 Subject: [PATCH 27/71] Hostname changed --- commands/login.js | 2 +- commands/status.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/commands/login.js b/commands/login.js index 7af55f1..f8dfb16 100644 --- a/commands/login.js +++ b/commands/login.js @@ -6,7 +6,7 @@ const botLogin = (bot) => { const username = message.from.username; const chatId = message.from.id; axios - .post(`http://thirema_api:9999/auth/telegram`, { + .post(`http://thirema-api:9999/auth/telegram`, { telegramName: username, telegramChat: chatId, }) diff --git a/commands/status.js b/commands/status.js index 17073bf..2d112dc 100644 --- a/commands/status.js +++ b/commands/status.js @@ -4,7 +4,7 @@ const axios = require("axios"); const botStatus = (bot) => { bot.command("status", (message) => { axios - .get(`http://thirema_api:9999/status`) + .get(`http://thirema-api:9999/status`) .then((res) => { const data = res.data; const name = data.name; From 8a7388edab3fc8795bf6badefa512f8dd8ebce4e Mon Sep 17 00:00:00 2001 From: Fritz Date: Wed, 15 Apr 2020 22:36:06 +0200 Subject: [PATCH 28/71] Fix res.response non esistente --- server.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server.js b/server.js index d435f6d..3ca4ab9 100644 --- a/server.js +++ b/server.js @@ -19,7 +19,7 @@ const sendMessage = (message, chatId) => { ) .then((res) => { console.log("Messaggio inviato con successo"); - console.log(res.response.status); + console.log(res.status); console.log(res.data); res.json("OK"); }) From 035e8f5c70fe6289fb731cae72162f13d9e7db0a Mon Sep 17 00:00:00 2001 From: Fritz Date: Wed, 15 Apr 2020 22:37:38 +0200 Subject: [PATCH 29/71] Fix invio degli alert a telegram --- server.js | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/server.js b/server.js index 3ca4ab9..2afe915 100644 --- a/server.js +++ b/server.js @@ -54,18 +54,28 @@ const botServer = http.createServer((req, res) => { sendMessage(authMessage, chatId); } } else if (response.reqType == "alert") { - const chatsId = response.chatId; - const deviceId = response.deviceId; - const sensorId = response.sensorId; - const sensorValue = response.sensorValue; - const threshold = response.threshold; - const valueType = response.valueType; + const chatIds = response.telegramChatIds; + const deviceId = response.realDeviceId; + const sensorId = response.realSensorId; + const sensorValue = response.currentValue; + const threshold = response.currentThreshold; + let valueType; + switch (response.currentThresholdType) { + case 0: + valueType = "superiore"; + break; + case 1: + valueType = "inferiore"; + break; + case 2: + valueType = "uguale"; + } const messagePart1 = `Attenzione: il sensore ${sensorId} del dispositivo ${deviceId} ha registrato un valore di `; - const messagePart2 = `${sensorValue} ${valueType} superando la soglia (${threshold})`; + const messagePart2 = `${sensorValue} ${valueType} alla soglia (${threshold})`; const alertMessage = messagePart1 + messagePart2; // eslint-disable-next-line guard-for-in - for (const index in chatsId) { - const chatId = chatsId[index]; + for (const index in chatIds) { + const chatId = chatIds[index]; if (!checkChatId(chatId)) { console.log("Invalid chat id"); } else { From 22e677c107cfcddf069d370103712b6aa669266f Mon Sep 17 00:00:00 2001 From: Fritz Date: Wed, 15 Apr 2020 22:53:46 +0200 Subject: [PATCH 30/71] Fix telegram /status che fa richiesta a /users?telegramName=username --- commands/status.js | 37 ++++++++++++++++++++----------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/commands/status.js b/commands/status.js index 2d112dc..6c31a67 100644 --- a/commands/status.js +++ b/commands/status.js @@ -2,23 +2,26 @@ const axios = require("axios"); const botStatus = (bot) => { - bot.command("status", (message) => { - axios - .get(`http://thirema-api:9999/status`) - .then((res) => { - const data = res.data; - const name = data.name; - const surname = data.surname; - const email = data.email; - const typeNumber = data.type; - let type = "Utente"; - if (typeNumber === 1) { - type = "Moderatore"; - } else if (typeNumber === 2) { - type = "Amministratore"; - } - return message.replyWithMarkdown( - ` + bot.command("status", (message) => { + const username = message.from.username; + console.log(username); + axios + .get(`http://localhost:9999/users?telegramName=` + username) + .then((res) => { + console.log(res.data); + const data = res.data[0]; + const name = data.name; + const surname = data.surname; + const email = data.email; + const typeNumber = data.type; + let type = "Utente"; + if (typeNumber === 1) { + type = "Moderatore"; + } else if (typeNumber === 2) { + type = "Amministratore"; + } + return message.replyWithMarkdown( + ` Ecco i tuoi dati *${message.from.username}* - *Nome:* ${name} - *Cognome:* ${surname} From d1df3e36ab048cf6f9a48c188332446dc09d9b9f Mon Sep 17 00:00:00 2001 From: Fritz Date: Wed, 15 Apr 2020 23:00:24 +0200 Subject: [PATCH 31/71] Fix checkstyle --- commands/login.js | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/commands/login.js b/commands/login.js index f8dfb16..10c58b1 100644 --- a/commands/login.js +++ b/commands/login.js @@ -2,17 +2,17 @@ const axios = require("axios"); const botLogin = (bot) => { - bot.command("login", (message) => { - const username = message.from.username; - const chatId = message.from.id; - axios - .post(`http://thirema-api:9999/auth/telegram`, { - telegramName: username, - telegramChat: chatId, - }) - .then((res) => { - const code = res.data.code; - const token = res.data.token; + bot.command("login", (message) => { + const username = message.from.username; + const chatId = message.from.id; + axios + .post(`http://localhost:9999/auth/telegram`, { + telegramName: username, + telegramChat: chatId, + }) + .then((res) => { + const code = res.data.code; + const token = res.data.token; if (code === 1) { axios.defaults.headers.common["Authorization"] = "Bearer " + token; return message.reply("Username trovato, registrazione riuscita"); From b2010498053beebf383d9bb5c60a79bb41e41695 Mon Sep 17 00:00:00 2001 From: Fritz Date: Wed, 15 Apr 2020 23:38:09 +0200 Subject: [PATCH 32/71] Fix api url --- commands/login.js | 4 ++-- commands/status.js | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/commands/login.js b/commands/login.js index 10c58b1..41bbf34 100644 --- a/commands/login.js +++ b/commands/login.js @@ -6,7 +6,7 @@ const botLogin = (bot) => { const username = message.from.username; const chatId = message.from.id; axios - .post(`http://localhost:9999/auth/telegram`, { + .post(`http://thirema-api:9999/auth/telegram`, { telegramName: username, telegramChat: chatId, }) @@ -30,7 +30,7 @@ const botLogin = (bot) => { .catch((err) => { console.log(err); // console.log(err.status); - if (err.response.status === 403) { + if (err.response != null && err.response.status === 403) { return message.reply( "Rieffettua l'autenticazione usando il comando /login" ); diff --git a/commands/status.js b/commands/status.js index 6c31a67..d96e991 100644 --- a/commands/status.js +++ b/commands/status.js @@ -6,7 +6,7 @@ const botStatus = (bot) => { const username = message.from.username; console.log(username); axios - .get(`http://localhost:9999/users?telegramName=` + username) + .get(`http://thirema-api:9999/users?telegramName=` + username) .then((res) => { console.log(res.data); const data = res.data[0]; @@ -30,7 +30,7 @@ const botStatus = (bot) => { ); }) .catch((err) => { - if (err.response.status === 403) { + if (err.response != null && err.response.status === 403) { message.reply("Rieffettua l'autenticazione usando il comando /login"); } else { message.reply("Errore nel controllo dei dati"); From 88f3d201b06902dcc72ca18f56a7c7230de062af Mon Sep 17 00:00:00 2001 From: Lorenzo Dei Negri Date: Wed, 22 Apr 2020 12:07:31 +0200 Subject: [PATCH 33/71] Update README.md --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index c581d9b..75afa65 100644 --- a/README.md +++ b/README.md @@ -34,3 +34,9 @@ - entrare nella cartella con il terminale - $ npm install - $ node bot + + +#### Comandi per code style JS + +`npm run prettier-eslint` +`npm run prettier-eslint-test` From f8018fc931df8659929b70ad5878193ed3bcaa72 Mon Sep 17 00:00:00 2001 From: Lorenzo Dei Negri Date: Wed, 22 Apr 2020 13:05:30 +0200 Subject: [PATCH 34/71] Update README.md --- README.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/README.md b/README.md index 75afa65..a92f34a 100644 --- a/README.md +++ b/README.md @@ -38,5 +38,14 @@ #### Comandi per code style JS +- Check: +`npm run prettier-eslint-check` +`npm run prettier-eslint-test-check` +- Autofix: `npm run prettier-eslint` `npm run prettier-eslint-test` + + +#### Comandi per i test JS + +`npm test` From 94b41e0a8f077a5050b6afac3646366c21d8f241 Mon Sep 17 00:00:00 2001 From: Giovanni Date: Thu, 23 Apr 2020 12:45:24 +0200 Subject: [PATCH 35/71] .env update --- .env | 4 +++- commands/login.js | 50 +++++++++++++++++++++++----------------------- commands/status.js | 5 +++-- 3 files changed, 31 insertions(+), 28 deletions(-) diff --git a/.env b/.env index 2b516de..44768b5 100644 --- a/.env +++ b/.env @@ -1 +1,3 @@ -BOT_TOKEN=1120382460:AAGy8CdhjdMxaS99K3za1Jxoqp-ayPuVC1w \ No newline at end of file +BOT_TOKEN=1120382460:AAGy8CdhjdMxaS99K3za1Jxoqp-ayPuVC1w + +LINK_API=http://core.host.redroundrobin.site:9999/status \ No newline at end of file diff --git a/commands/login.js b/commands/login.js index 45ec6e1..bfa20e4 100644 --- a/commands/login.js +++ b/commands/login.js @@ -13,31 +13,31 @@ const botLogin = (bot) => { .then((res) => { const code = res.data.code; const token = res.data.token; - if (code === 1) { - axios.defaults.headers.common["Authorization"] = "Bearer " + token; - return message.reply("Username trovato, registrazione riuscita"); - } else if (code === 2) { - axios.defaults.headers.common["Authorization"] = "Bearer " + token; - return message.reply( - "Account già registrato, nessuna modifica apportata" - ); - } else if (code === 0) { - return message.reply( - "Username non trovato, registra il tuo Username dalla web-app" - ); - } - }) - .catch((err) => { - console.log(err); - // console.log(err.status); - if (err.response.status === 403) { - return message.reply( - "Rieffettua l'autenticazione usando il comando /login" - ); - } else { - return message.reply("Errore nel controllo dei dati"); - } - }); + if (code === 1) { + axios.defaults.headers.common["Authorization"] = "Bearer " + token; + return message.reply("Username trovato, registrazione riuscita"); + } else if (code === 2) { + axios.defaults.headers.common["Authorization"] = "Bearer " + token; + return message.reply( + "Account già registrato, nessuna modifica apportata" + ); + } else if (code === 0) { + return message.reply( + "Username non trovato, registra il tuo Username dalla web-app" + ); + } + }) + .catch((err) => { + console.log(err); + // console.log(err.status); + if (err.response.status === 403) { + return message.reply( + "Rieffettua l'autenticazione usando il comando /login" + ); + } else { + return message.reply("Errore nel controllo dei dati"); + } + }); }); }; module.exports.botLogin = botLogin; diff --git a/commands/status.js b/commands/status.js index f85ce19..573a378 100644 --- a/commands/status.js +++ b/commands/status.js @@ -1,10 +1,11 @@ -// Richieste http +require("dotenv").config(); +const linkAPI = process.env.LINK_API; const axios = require("axios"); const botStatus = (bot) => { bot.command("status", (message) => { axios - .get(`http://core.host.redroundrobin.site:9999/status`) + .get(`${linkAPI}/status`) .then((res) => { const data = res.data; const name = data.name; From 28b2701fe533be21610160425ed14b98b05ce729 Mon Sep 17 00:00:00 2001 From: Giovanni Date: Thu, 23 Apr 2020 12:52:50 +0200 Subject: [PATCH 36/71] Link api .env --- .env | 2 +- commands/login.js | 3 ++- commands/status.js | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/.env b/.env index 44768b5..b14bc12 100644 --- a/.env +++ b/.env @@ -1,3 +1,3 @@ BOT_TOKEN=1120382460:AAGy8CdhjdMxaS99K3za1Jxoqp-ayPuVC1w -LINK_API=http://core.host.redroundrobin.site:9999/status \ No newline at end of file +LINK_API=http://core.host.redroundrobin.site:9999 \ No newline at end of file diff --git a/commands/login.js b/commands/login.js index 41bbf34..3a6c50f 100644 --- a/commands/login.js +++ b/commands/login.js @@ -1,12 +1,13 @@ // Richieste http const axios = require("axios"); +const linkAPI = process.env.LINK_API; const botLogin = (bot) => { bot.command("login", (message) => { const username = message.from.username; const chatId = message.from.id; axios - .post(`http://thirema-api:9999/auth/telegram`, { + .post(`${linkAPI}/auth/telegram`, { telegramName: username, telegramChat: chatId, }) diff --git a/commands/status.js b/commands/status.js index 4ac22eb..22f0b86 100644 --- a/commands/status.js +++ b/commands/status.js @@ -8,7 +8,7 @@ const botStatus = (bot) => { const username = message.from.username; console.log(username); axios - .get(`http://thirema-api:9999/users?telegramName=` + username) + .get(`${linkAPI}/users?telegramName=` + username) .then((res) => { console.log(res.data); const data = res.data[0]; From 9c48e4af96dd3ad57b4d2d1ef6c3392646958f00 Mon Sep 17 00:00:00 2001 From: Mariano Date: Thu, 23 Apr 2020 14:45:21 +0200 Subject: [PATCH 37/71] Create .gitattributes --- .gitattributes | 1 + 1 file changed, 1 insertion(+) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..30ddbbb --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +*.js text eol=lf \ No newline at end of file From 947c8d681e3cde335da22f775523e5fa932df81d Mon Sep 17 00:00:00 2001 From: Giovanni Date: Thu, 23 Apr 2020 17:12:22 +0200 Subject: [PATCH 38/71] Update info.js --- commands/info.js | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/commands/info.js b/commands/info.js index 4396b16..ffde3cd 100644 --- a/commands/info.js +++ b/commands/info.js @@ -1,10 +1,25 @@ const botInfo = (bot) => { - bot.command("info", ({ replyWithMarkdown }) => + bot.command("info", ( message, { replyWithMarkdown } ) => + const chatId=message.chat.id; replyWithMarkdown(` Ecco la lista dei comandi disponibili: - Login: /login - Status: /status -- Info: /info`) - ); +- Info: /info +sssss + `) + // let options = { + // reply_markup: JSON.stringify({ + // inline_keyboard: [ + // [{ text: 'OK 1', callback_data: '1' }], + // [{ text: 'OK 2', callback_data: '2' }], + // [{ text: 'OK 3', callback_data: '3' }] + // ] + // }) + // }; + // bot.sendMessage('Provaaaaa', chatId) + // .then( () => { + // console.log("OK") + // }); }; module.exports.botInfo = botInfo; From c0d7187f24cedc2c92f75f2056210124f25155c6 Mon Sep 17 00:00:00 2001 From: Alessandro Date: Thu, 23 Apr 2020 17:16:46 +0200 Subject: [PATCH 39/71] fix --- commands/info.js | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/commands/info.js b/commands/info.js index ffde3cd..53435da 100644 --- a/commands/info.js +++ b/commands/info.js @@ -1,25 +1,25 @@ const botInfo = (bot) => { - bot.command("info", ( message, { replyWithMarkdown } ) => - const chatId=message.chat.id; + bot.command("info", ({ replyWithMarkdown }) => { replyWithMarkdown(` Ecco la lista dei comandi disponibili: - Login: /login - Status: /status - Info: /info sssss - `) - // let options = { - // reply_markup: JSON.stringify({ - // inline_keyboard: [ - // [{ text: 'OK 1', callback_data: '1' }], - // [{ text: 'OK 2', callback_data: '2' }], - // [{ text: 'OK 3', callback_data: '3' }] - // ] - // }) - // }; - // bot.sendMessage('Provaaaaa', chatId) - // .then( () => { - // console.log("OK") - // }); + `); + // let options = { + // reply_markup: JSON.stringify({ + // inline_keyboard: [ + // [{ text: 'OK 1', callback_data: '1' }], + // [{ text: 'OK 2', callback_data: '2' }], + // [{ text: 'OK 3', callback_data: '3' }] + // ] + // }) + // }; + // bot.sendMessage('Provaaaaa', chatId) + // .then( () => { + // console.log("OK") + // }); + }); }; module.exports.botInfo = botInfo; From 3ad0a051fc3bd68833f8e8497be8c3b2028b2cf1 Mon Sep 17 00:00:00 2001 From: Giovanni Date: Thu, 23 Apr 2020 18:54:04 +0200 Subject: [PATCH 40/71] bozza comando dispositivi --- commands/dispositivi.js | 18 ++++++++++++++++++ commands/info.js | 16 ++-------------- commands/status.js | 2 -- main.js | 4 +++- 4 files changed, 23 insertions(+), 17 deletions(-) create mode 100644 commands/dispositivi.js diff --git a/commands/dispositivi.js b/commands/dispositivi.js new file mode 100644 index 0000000..1e343f1 --- /dev/null +++ b/commands/dispositivi.js @@ -0,0 +1,18 @@ +const axios = require("axios"); +const Telegram = require("telegraf/telegram"); +const telegram = new Telegram("1120382460:AAGy8CdhjdMxaS99K3za1Jxoqp-ayPuVC1w"); +const botDispositivi = (bot) => { + bot.command("dispositivi", (message) => { + axios + .get( + "https://api.telegram.org/bot1120382460:AAGy8CdhjdMxaS99K3za1Jxoqp-ayPuVC1w/getMyCommands" + ) + .then((res) => { + console.log(res.data); + }) + .catch(() => { + console.log("errore caricamento dati"); + }); + }); +}; +module.exports.botDispositivi = botDispositivi; diff --git a/commands/info.js b/commands/info.js index 53435da..74d4350 100644 --- a/commands/info.js +++ b/commands/info.js @@ -1,3 +1,4 @@ + const botInfo = (bot) => { bot.command("info", ({ replyWithMarkdown }) => { replyWithMarkdown(` @@ -5,21 +6,8 @@ Ecco la lista dei comandi disponibili: - Login: /login - Status: /status - Info: /info -sssss +- Lista dispositivi: /dispositivi `); - // let options = { - // reply_markup: JSON.stringify({ - // inline_keyboard: [ - // [{ text: 'OK 1', callback_data: '1' }], - // [{ text: 'OK 2', callback_data: '2' }], - // [{ text: 'OK 3', callback_data: '3' }] - // ] - // }) - // }; - // bot.sendMessage('Provaaaaa', chatId) - // .then( () => { - // console.log("OK") - // }); }); }; module.exports.botInfo = botInfo; diff --git a/commands/status.js b/commands/status.js index 22f0b86..ca10c50 100644 --- a/commands/status.js +++ b/commands/status.js @@ -3,14 +3,12 @@ const linkAPI = process.env.LINK_API; const axios = require("axios"); const botStatus = (bot) => { - bot.command("status", (message) => { const username = message.from.username; console.log(username); axios .get(`${linkAPI}/users?telegramName=` + username) .then((res) => { - console.log(res.data); const data = res.data[0]; const name = data.name; const surname = data.surname; diff --git a/main.js b/main.js index 5468e9a..d1da5fb 100644 --- a/main.js +++ b/main.js @@ -6,12 +6,13 @@ const tokenBot = process.env.BOT_TOKEN; const bot = new Telegraf(tokenBot); // eslint-disable-next-line no-unused-vars -const { botServer, checkChatId, sendMessage } = require("./server"); +const { botServer } = require("./server"); const botLaunch = require("./commands/launch"); const botStart = require("./commands/start"); const botInfo = require("./commands/info"); const botLogin = require("./commands/login"); const botStatus = require("./commands/status"); +const botDispositivi = require("./commands/dispositivi"); // const botStart = require("./commands"); // Comandi bot @@ -19,6 +20,7 @@ botStart.botStart(bot); botInfo.botInfo(bot); botLogin.botLogin(bot); botStatus.botStatus(bot); +botDispositivi.botDispositivi(bot); botServer.listen(3000); console.log("Server to port 3000"); From aaaf999a0c43faf4ce104df356d66ea152b212c2 Mon Sep 17 00:00:00 2001 From: Giovanni Date: Thu, 23 Apr 2020 19:11:50 +0200 Subject: [PATCH 41/71] Caricamento comandi dinamico --- commands/info.js | 1 - main.js | 19 +++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/commands/info.js b/commands/info.js index 74d4350..4f565a0 100644 --- a/commands/info.js +++ b/commands/info.js @@ -1,4 +1,3 @@ - const botInfo = (bot) => { bot.command("info", ({ replyWithMarkdown }) => { replyWithMarkdown(` diff --git a/main.js b/main.js index d1da5fb..25041da 100644 --- a/main.js +++ b/main.js @@ -5,6 +5,25 @@ const Telegraf = require("telegraf"); const tokenBot = process.env.BOT_TOKEN; const bot = new Telegraf(tokenBot); +// Richiesta POST per settare i comandi +const axios = require("axios"); +const botCommands = [ + { command: "info", description: "Comandi supportati" }, + { command: "login", description: "Autenticazione al sistema ThiReMa" }, + { command: "status", description: "Controllo dello status dell'utente" }, + { command: "dispositivi", description: "Visualizza lista dispositivi" }, +]; +axios + .post(`https://api.telegram.org/bot${tokenBot}/setMyCommands`, { + commands: botCommands, + }) + .then(() => { + console.log("Comandi caricati"); + }) + .catch(() => { + console.log("Errore caricamento comandi"); + }); + // eslint-disable-next-line no-unused-vars const { botServer } = require("./server"); const botLaunch = require("./commands/launch"); From fa1cc0b5b47f406baf98f499f501997a0e84c56b Mon Sep 17 00:00:00 2001 From: Giovanni Date: Thu, 23 Apr 2020 19:21:43 +0200 Subject: [PATCH 42/71] Update dispositivi.js --- commands/dispositivi.js | 32 ++++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/commands/dispositivi.js b/commands/dispositivi.js index 1e343f1..e3afa50 100644 --- a/commands/dispositivi.js +++ b/commands/dispositivi.js @@ -3,16 +3,28 @@ const Telegram = require("telegraf/telegram"); const telegram = new Telegram("1120382460:AAGy8CdhjdMxaS99K3za1Jxoqp-ayPuVC1w"); const botDispositivi = (bot) => { bot.command("dispositivi", (message) => { - axios - .get( - "https://api.telegram.org/bot1120382460:AAGy8CdhjdMxaS99K3za1Jxoqp-ayPuVC1w/getMyCommands" - ) - .then((res) => { - console.log(res.data); - }) - .catch(() => { - console.log("errore caricamento dati"); - }); + // axios + // // .get( + // // "https://api.telegram.org/bot1120382460:AAGy8CdhjdMxaS99K3za1Jxoqp-ayPuVC1w/getMyCommands" + // // ) + // // .then((res) => { + // // console.log(res.data); + // // }) + // // .catch(() => { + // // console.log("errore caricamento dati"); + // // }); + const opts = { + reply_markup: { + inline_keyboard: [ + [ + { text: "Accendi", callback_data: "A1" }, + { text: "Spegni", callback_data: "C1" }, + ], + ], + }, + }; + console.log(message.from.id); + bot.sendMessage(message.from.id, "Message text", opts); }); }; module.exports.botDispositivi = botDispositivi; From d7e351df1a8ce9626e946b058f3f483308a282d4 Mon Sep 17 00:00:00 2001 From: Giovanni Date: Thu, 23 Apr 2020 19:26:44 +0200 Subject: [PATCH 43/71] Bottoni command --- commands/dispositivi.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/commands/dispositivi.js b/commands/dispositivi.js index e3afa50..9c10ad9 100644 --- a/commands/dispositivi.js +++ b/commands/dispositivi.js @@ -23,8 +23,7 @@ const botDispositivi = (bot) => { ], }, }; - console.log(message.from.id); - bot.sendMessage(message.from.id, "Message text", opts); + bot.telegram.sendMessage(message.from.id, "Message text", opts); }); }; module.exports.botDispositivi = botDispositivi; From 1ea7aaec1db9bee7f2843179bb373cb3389f4cd8 Mon Sep 17 00:00:00 2001 From: Lorenzo Dei Negri Date: Thu, 23 Apr 2020 20:14:19 +0200 Subject: [PATCH 44/71] Update start.sh --- start.sh | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/start.sh b/start.sh index 19ed22f..504526d 100644 --- a/start.sh +++ b/start.sh @@ -1,6 +1,10 @@ #!/bin/sh -npm install --production +if [ ! -d "node_modules/" ]; then + + npm install --production + +fi node main.js From 15cec0a06292652a6b28a59b4cc50a6898f68a7c Mon Sep 17 00:00:00 2001 From: Mariano Date: Thu, 23 Apr 2020 21:12:43 +0200 Subject: [PATCH 45/71] Refactoring del bot --- .env | 4 +-- .eslintrc.json | 2 ++ __tests__/server.test.js | 2 +- commands/devices.js | 16 +++++++++ commands/dispositivi.js | 29 ---------------- commands/info.js | 10 +++--- commands/launch.js | 4 --- commands/login.js | 16 ++++----- commands/status.js | 12 +++---- main.js | 64 ++++++++++++------------------------ utils/config.js | 22 +++++++++++++ server.js => utils/server.js | 17 ++-------- 12 files changed, 84 insertions(+), 114 deletions(-) create mode 100644 commands/devices.js delete mode 100644 commands/dispositivi.js delete mode 100644 commands/launch.js create mode 100644 utils/config.js rename server.js => utils/server.js (84%) diff --git a/.env b/.env index b14bc12..2b293fd 100644 --- a/.env +++ b/.env @@ -1,3 +1,3 @@ BOT_TOKEN=1120382460:AAGy8CdhjdMxaS99K3za1Jxoqp-ayPuVC1w - -LINK_API=http://core.host.redroundrobin.site:9999 \ No newline at end of file +URL_API=http://core.host.redroundrobin.site:9999 +SERVER_PORT=3000 \ No newline at end of file diff --git a/.eslintrc.json b/.eslintrc.json index cfa0571..be7a17c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -1,4 +1,6 @@ { + + "env": { "node": true, "es6": true, diff --git a/__tests__/server.test.js b/__tests__/server.test.js index aa26dd4..3e73203 100644 --- a/__tests__/server.test.js +++ b/__tests__/server.test.js @@ -1,4 +1,4 @@ -const { sendMessage, checkChatId } = require("../server"); +const { sendMessage, checkChatId } = require("../utils/server"); test("Send message to invalid chat id", () => { const message = "test"; diff --git a/commands/devices.js b/commands/devices.js new file mode 100644 index 0000000..48fb76c --- /dev/null +++ b/commands/devices.js @@ -0,0 +1,16 @@ +const botDevices = (bot) => { + bot.command("devices", (message) => { + const opts = { + reply_markup: { + inline_keyboard: [ + [ + { text: "Accendi", callback_data: "A1" }, + { text: "Spegni", callback_data: "C1" }, + ], + ], + }, + }; + bot.telegram.sendMessage(message.from.id, "Message text", opts); + }); +}; +module.exports.botDevices = botDevices; diff --git a/commands/dispositivi.js b/commands/dispositivi.js deleted file mode 100644 index 9c10ad9..0000000 --- a/commands/dispositivi.js +++ /dev/null @@ -1,29 +0,0 @@ -const axios = require("axios"); -const Telegram = require("telegraf/telegram"); -const telegram = new Telegram("1120382460:AAGy8CdhjdMxaS99K3za1Jxoqp-ayPuVC1w"); -const botDispositivi = (bot) => { - bot.command("dispositivi", (message) => { - // axios - // // .get( - // // "https://api.telegram.org/bot1120382460:AAGy8CdhjdMxaS99K3za1Jxoqp-ayPuVC1w/getMyCommands" - // // ) - // // .then((res) => { - // // console.log(res.data); - // // }) - // // .catch(() => { - // // console.log("errore caricamento dati"); - // // }); - const opts = { - reply_markup: { - inline_keyboard: [ - [ - { text: "Accendi", callback_data: "A1" }, - { text: "Spegni", callback_data: "C1" }, - ], - ], - }, - }; - bot.telegram.sendMessage(message.from.id, "Message text", opts); - }); -}; -module.exports.botDispositivi = botDispositivi; diff --git a/commands/info.js b/commands/info.js index 4f565a0..d9fba52 100644 --- a/commands/info.js +++ b/commands/info.js @@ -1,11 +1,13 @@ const botInfo = (bot) => { bot.command("info", ({ replyWithMarkdown }) => { replyWithMarkdown(` +RIoT Bot +-------- Ecco la lista dei comandi disponibili: -- Login: /login -- Status: /status -- Info: /info -- Lista dispositivi: /dispositivi +- /login - primo avvio e registrazione account +- /status - informazioni utente corrente +- /info - queste informazioni +- /devices - dispositivi a cui è possibile inviare input `); }); }; diff --git a/commands/launch.js b/commands/launch.js deleted file mode 100644 index 97d5e20..0000000 --- a/commands/launch.js +++ /dev/null @@ -1,4 +0,0 @@ -const botLaunch = (bot) => { - bot.launch(); -}; -module.exports.botLaunch = botLaunch; diff --git a/commands/login.js b/commands/login.js index 3a6c50f..9a0ebe1 100644 --- a/commands/login.js +++ b/commands/login.js @@ -1,13 +1,9 @@ -// Richieste http -const axios = require("axios"); -const linkAPI = process.env.LINK_API; - -const botLogin = (bot) => { +const botLogin = (bot, axios) => { bot.command("login", (message) => { const username = message.from.username; const chatId = message.from.id; axios - .post(`${linkAPI}/auth/telegram`, { + .post(`${process.env.URL_API}/auth/telegram`, { telegramName: username, telegramChat: chatId, }) @@ -16,15 +12,15 @@ const botLogin = (bot) => { const token = res.data.token; if (code === 1) { axios.defaults.headers.common["Authorization"] = "Bearer " + token; - return message.reply("Username trovato, registrazione riuscita"); + return message.reply("Username trovato, registrazione riuscita!"); } else if (code === 2) { axios.defaults.headers.common["Authorization"] = "Bearer " + token; return message.reply( - "Account già registrato, nessuna modifica apportata" + "Account già registrato, nessuna modifica apportata." ); } else if (code === 0) { return message.reply( - "Username non trovato, registra il tuo Username dalla web-app" + "Username non trovato, registra il tuo Username dalle impostazioni della webapp" ); } }) @@ -33,7 +29,7 @@ const botLogin = (bot) => { // console.log(err.status); if (err.response != null && err.response.status === 403) { return message.reply( - "Rieffettua l'autenticazione usando il comando /login" + "Effettua nuovamente l'autenticazione usando il comando /login" ); } else { return message.reply("Errore nel controllo dei dati"); diff --git a/commands/status.js b/commands/status.js index ca10c50..b33fd98 100644 --- a/commands/status.js +++ b/commands/status.js @@ -1,13 +1,9 @@ -require("dotenv").config(); -const linkAPI = process.env.LINK_API; -const axios = require("axios"); - -const botStatus = (bot) => { +const botStatus = (bot, axios) => { bot.command("status", (message) => { const username = message.from.username; console.log(username); axios - .get(`${linkAPI}/users?telegramName=` + username) + .get(`${process.env.LINK_API}/users?telegramName=` + username) .then((res) => { const data = res.data[0]; const name = data.name; @@ -31,7 +27,9 @@ const botStatus = (bot) => { }) .catch((err) => { if (err.response != null && err.response.status === 403) { - message.reply("Rieffettua l'autenticazione usando il comando /login"); + message.reply( + "Effettua prima l'autenticazione usando il comando /login" + ); } else { message.reply("Errore nel controllo dei dati"); } diff --git a/main.js b/main.js index 25041da..656e507 100644 --- a/main.js +++ b/main.js @@ -1,48 +1,26 @@ -require("dotenv").config(); +const { axios } = require("./utils/config"); const Telegraf = require("telegraf"); +const bot = new Telegraf(process.env.BOT_TOKEN); -// Tokenbot e creazione bot -const tokenBot = process.env.BOT_TOKEN; -const bot = new Telegraf(tokenBot); +const botServer = require("./utils/server"); +const cmdStart = require("./commands/start"); +const cmdInfo = require("./commands/info"); +const cmdLogin = require("./commands/login"); +const cmdStatus = require("./commands/status"); +const cmdDevices = require("./commands/devices"); -// Richiesta POST per settare i comandi -const axios = require("axios"); -const botCommands = [ - { command: "info", description: "Comandi supportati" }, - { command: "login", description: "Autenticazione al sistema ThiReMa" }, - { command: "status", description: "Controllo dello status dell'utente" }, - { command: "dispositivi", description: "Visualizza lista dispositivi" }, -]; -axios - .post(`https://api.telegram.org/bot${tokenBot}/setMyCommands`, { - commands: botCommands, - }) - .then(() => { - console.log("Comandi caricati"); - }) - .catch(() => { - console.log("Errore caricamento comandi"); - }); +cmdStart.botStart(bot); +cmdInfo.botInfo(bot); +cmdLogin.botLogin(bot, axios); +cmdStatus.botStatus(bot, axios); +cmdDevices.botDevices(bot); -// eslint-disable-next-line no-unused-vars -const { botServer } = require("./server"); -const botLaunch = require("./commands/launch"); -const botStart = require("./commands/start"); -const botInfo = require("./commands/info"); -const botLogin = require("./commands/login"); -const botStatus = require("./commands/status"); -const botDispositivi = require("./commands/dispositivi"); -// const botStart = require("./commands"); +botServer.listen(process.env.SERVER_PORT); +console.log( + "[Telegram] Server di ascolto per API avviato (porta " + + process.env.SERVER_PORT + + ")" +); -// Comandi bot -botStart.botStart(bot); -botInfo.botInfo(bot); -botLogin.botLogin(bot); -botStatus.botStatus(bot); -botDispositivi.botDispositivi(bot); - -botServer.listen(3000); -console.log("Server to port 3000"); - -botLaunch.botLaunch(bot); -console.log("Bot avviato correttamente"); +bot.launch(); +console.log("[Telegram] Bot avviato!"); diff --git a/utils/config.js b/utils/config.js new file mode 100644 index 0000000..e12f18f --- /dev/null +++ b/utils/config.js @@ -0,0 +1,22 @@ +const axios = require("axios"); + +const botCommands = [ + { command: "info", description: "Lista dei comandi del bot e informazioni" }, + { command: "login", description: "Autenticazione al sistema" }, + { command: "status", description: "Controllo dello status dell'utente" }, + { + command: "dispositivi", + description: "[Admin] Visualizza lista dispositivi a cui inviare input", + }, +]; + +axios + .post(`https://api.telegram.org/bot${process.env.BOT_TOKEN}/setMyCommands`, { + commands: botCommands, + }) + .then(() => { + console.log("Comandi caricati"); + }) + .catch(() => { + console.log("Errore caricamento comandi"); + }); diff --git a/server.js b/utils/server.js similarity index 84% rename from server.js rename to utils/server.js index 2afe915..75cd703 100644 --- a/server.js +++ b/utils/server.js @@ -1,21 +1,10 @@ -require("dotenv").config(); - -// Richiesta per creazione server const http = require("http"); -// Richieste http const axios = require("axios"); -const tokenBot = process.env.BOT_TOKEN; - -/** - * Sending a message to a given Telegram chat id - * @param {string} message - * @param {string} chatId - */ const sendMessage = (message, chatId) => { axios .post( - `https://api.telegram.org/bot${tokenBot}/sendMessage?chat_id=${chatId}&text=${message}` + `https://api.telegram.org/bot${process.env.BOT_TOKEN}/sendMessage?chat_id=${chatId}&text=${message}` ) .then((res) => { console.log("Messaggio inviato con successo"); @@ -44,7 +33,7 @@ const botServer = http.createServer((req, res) => { jsonRes += data.toString(); console.log(JSON.parse(jsonRes)); const response = JSON.parse(jsonRes); - if (response.reqType == "authentication") { + if (response.reqType === "authentication") { const authCode = response.authCode; const chatId = response.chatId; if (!checkChatId(chatId)) { @@ -53,7 +42,7 @@ const botServer = http.createServer((req, res) => { const authMessage = `Ecco il tuo codice di autenticazione: ${authCode}`; sendMessage(authMessage, chatId); } - } else if (response.reqType == "alert") { + } else if (response.reqType === "alert") { const chatIds = response.telegramChatIds; const deviceId = response.realDeviceId; const sensorId = response.realSensorId; From 142dfc21a962c8fdc2a760972d9f0167ad844974 Mon Sep 17 00:00:00 2001 From: Giovanni Date: Sat, 25 Apr 2020 11:41:02 +0200 Subject: [PATCH 46/71] Bug fixed and inline buttons --- commands/devices.js | 19 +++++++++++-------- commands/login.js | 1 + commands/start.js | 2 +- commands/status.js | 1 + main.js | 3 ++- utils/config.js | 1 + utils/server.js | 1 + 7 files changed, 18 insertions(+), 10 deletions(-) diff --git a/commands/devices.js b/commands/devices.js index 48fb76c..c38f2b6 100644 --- a/commands/devices.js +++ b/commands/devices.js @@ -1,16 +1,19 @@ const botDevices = (bot) => { bot.command("devices", (message) => { - const opts = { - reply_markup: { + const options = { + reply_markup: JSON.stringify({ inline_keyboard: [ - [ - { text: "Accendi", callback_data: "A1" }, - { text: "Spegni", callback_data: "C1" }, - ], + [{ text: "Accendi", callback_data: "1" }], + [{ text: "Spegni", callback_data: "2" }], + [{ text: "Esplodi", callback_data: "3" }], ], - }, + }), }; - bot.telegram.sendMessage(message.from.id, "Message text", opts); + bot.telegram + .sendMessage(message.chat.id, "esempio bottoni", options) + .then(function (sended) { + // `sended` is the sent message. + }); }); }; module.exports.botDevices = botDevices; diff --git a/commands/login.js b/commands/login.js index 9a0ebe1..985b42d 100644 --- a/commands/login.js +++ b/commands/login.js @@ -1,3 +1,4 @@ +require("dotenv").config(); const botLogin = (bot, axios) => { bot.command("login", (message) => { const username = message.from.username; diff --git a/commands/start.js b/commands/start.js index a260967..17d1448 100644 --- a/commands/start.js +++ b/commands/start.js @@ -3,7 +3,7 @@ const botStart = (bot) => { console.log("started:", message.from.id); const username = message.from.username; return message.replyWithMarkdown(` -Ciao *${username}*, benvenuto nel bot di ThiReMa! +Ciao *${username}*, benvenuto nel RIoT bot! Usa il comando /login per effettuare l'autenticazione. Per vedere la lista del comandi che puoi utilizzare usa il comando /info`); }); diff --git a/commands/status.js b/commands/status.js index b33fd98..61471ed 100644 --- a/commands/status.js +++ b/commands/status.js @@ -1,3 +1,4 @@ +require("dotenv").config(); const botStatus = (bot, axios) => { bot.command("status", (message) => { const username = message.from.username; diff --git a/main.js b/main.js index 656e507..755c7ff 100644 --- a/main.js +++ b/main.js @@ -1,8 +1,9 @@ const { axios } = require("./utils/config"); +require("dotenv").config(); const Telegraf = require("telegraf"); const bot = new Telegraf(process.env.BOT_TOKEN); -const botServer = require("./utils/server"); +const { botServer } = require("./utils/server"); const cmdStart = require("./commands/start"); const cmdInfo = require("./commands/info"); const cmdLogin = require("./commands/login"); diff --git a/utils/config.js b/utils/config.js index e12f18f..79d6e1a 100644 --- a/utils/config.js +++ b/utils/config.js @@ -1,3 +1,4 @@ +require("dotenv").config(); const axios = require("axios"); const botCommands = [ diff --git a/utils/server.js b/utils/server.js index 75cd703..33055fd 100644 --- a/utils/server.js +++ b/utils/server.js @@ -1,3 +1,4 @@ +require("dotenv").config(); const http = require("http"); const axios = require("axios"); From ff4bd2ad55f371ebece8c502d27b387d5ae6f807 Mon Sep 17 00:00:00 2001 From: Giovanni Date: Sat, 25 Apr 2020 11:53:13 +0200 Subject: [PATCH 47/71] Fix comandi --- commands/login.js | 4 +++- commands/status.js | 7 ++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/commands/login.js b/commands/login.js index 985b42d..2db712c 100644 --- a/commands/login.js +++ b/commands/login.js @@ -1,5 +1,7 @@ require("dotenv").config(); -const botLogin = (bot, axios) => { +const axios = require("axios"); + +const botLogin = (bot) => { bot.command("login", (message) => { const username = message.from.username; const chatId = message.from.id; diff --git a/commands/status.js b/commands/status.js index 61471ed..77c6c7a 100644 --- a/commands/status.js +++ b/commands/status.js @@ -1,10 +1,11 @@ require("dotenv").config(); -const botStatus = (bot, axios) => { +const axios = require("axios"); + +const botStatus = (bot) => { bot.command("status", (message) => { const username = message.from.username; - console.log(username); axios - .get(`${process.env.LINK_API}/users?telegramName=` + username) + .get(`${process.env.URL_API}/users?telegramName=${username}`) .then((res) => { const data = res.data[0]; const name = data.name; From 71689ed8a520401730a77fd7674fcdbeeb75b4e3 Mon Sep 17 00:00:00 2001 From: Giovanni Date: Sat, 25 Apr 2020 14:49:36 +0200 Subject: [PATCH 48/71] Lista dinamica dispositivi admin --- commands/devices.js | 43 ++++++++++++++++++++++++++++++------------- commands/status.js | 2 +- 2 files changed, 31 insertions(+), 14 deletions(-) diff --git a/commands/devices.js b/commands/devices.js index c38f2b6..7c9932e 100644 --- a/commands/devices.js +++ b/commands/devices.js @@ -1,19 +1,36 @@ +require("dotenv").config(); +const axios = require("axios"); + const botDevices = (bot) => { bot.command("devices", (message) => { - const options = { - reply_markup: JSON.stringify({ - inline_keyboard: [ - [{ text: "Accendi", callback_data: "1" }], - [{ text: "Spegni", callback_data: "2" }], - [{ text: "Esplodi", callback_data: "3" }], - ], - }), + const buttonList = []; + const getButtons = async () => { + const response = await axios + .get(`${process.env.URL_API}/devices`) + .then((res) => { + const devices = res.data; + devices.forEach((device) => { + buttonList.push([{ text: device.name, callback_data: "1" }]); + }); + }) + .catch(() => { + return reply.message("Errore caricamento lista dispositivi"); + }); + const buttonsData = await response; + return buttonsData; }; - bot.telegram - .sendMessage(message.chat.id, "esempio bottoni", options) - .then(function (sended) { - // `sended` is the sent message. - }); + getButtons().then(() => { + const options = { + reply_markup: JSON.stringify({ + inline_keyboard: buttonList, + }), + }; + bot.telegram + .sendMessage(message.chat.id, "Ecco la lista dei dispositivi:", options) + .then(function (sended) { + // `sended` is the sent message. + }); + }); }); }; module.exports.botDevices = botDevices; diff --git a/commands/status.js b/commands/status.js index 77c6c7a..5c73400 100644 --- a/commands/status.js +++ b/commands/status.js @@ -33,7 +33,7 @@ const botStatus = (bot) => { "Effettua prima l'autenticazione usando il comando /login" ); } else { - message.reply("Errore nel controllo dei dati"); + message.reply("Errore nel controllo dei dati!"); } }); }); From 802b08607bc32407632e87607b1eccd058e3d58f Mon Sep 17 00:00:00 2001 From: Giovanni Date: Sat, 25 Apr 2020 16:21:04 +0200 Subject: [PATCH 49/71] Admin --- commands/devices.js | 77 ++++++++++++++++++++++++++++++++------------- 1 file changed, 56 insertions(+), 21 deletions(-) diff --git a/commands/devices.js b/commands/devices.js index 7c9932e..cc3c512 100644 --- a/commands/devices.js +++ b/commands/devices.js @@ -1,35 +1,70 @@ require("dotenv").config(); const axios = require("axios"); +let admin = false; const botDevices = (bot) => { bot.command("devices", (message) => { - const buttonList = []; - const getButtons = async () => { - const response = await axios - .get(`${process.env.URL_API}/devices`) + const username = message.from.username; + const getType = async () => { + const resType = await axios + .get(`${process.env.URL_API}/users?telegramName=${username}`) .then((res) => { - const devices = res.data; - devices.forEach((device) => { - buttonList.push([{ text: device.name, callback_data: "1" }]); - }); + const data = res.data[0]; + const typeNumber = data.type; + if (typeNumber === 2) { + admin = true; + console.log("IS admin"); + } + else { + admin = false; + console.log("IS not admin"); + } }) .catch(() => { - return reply.message("Errore caricamento lista dispositivi"); + return message.reply(`Errore verifica account, esegui il comando /login`); }); - const buttonsData = await response; - return buttonsData; + const typeUser = await resType; + return typeUser; }; - getButtons().then(() => { - const options = { - reply_markup: JSON.stringify({ - inline_keyboard: buttonList, - }), - }; - bot.telegram - .sendMessage(message.chat.id, "Ecco la lista dei dispositivi:", options) - .then(function (sended) { - // `sended` is the sent message. + getType().then(() => { + if (admin) { + const buttonList = []; + const getButtons = async () => { + const response = await axios + .get(`${process.env.URL_API}/devices`) + .then((res) => { + admin = true; + const devices = res.data; + devices.forEach((device) => { + buttonList.push([{ text: device.name, callback_data: "1" }]); + }); + }) + .catch((err) => { + admin = false; + return message.reply("Devi essere un amministratore"); + }); + const buttonsData = await response; + return buttonsData; + }; + getButtons().then(() => { + const options = { + reply_markup: JSON.stringify({ + inline_keyboard: buttonList, + }), + }; + bot.telegram + .sendMessage( + message.chat.id, + "Ecco la lista dei dispositivi", + options + ) + .then(function (sended) { + // `sended` is the sent message. + }); }); + } else { + return message.reply("Devi essere un amministratore"); + } }); }); }; From 5c254f15e87dbfbabff529101a37668798b7c245 Mon Sep 17 00:00:00 2001 From: Giovanni Date: Sat, 25 Apr 2020 16:37:38 +0200 Subject: [PATCH 50/71] bug fixed --- commands/devices.js | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/commands/devices.js b/commands/devices.js index cc3c512..1197540 100644 --- a/commands/devices.js +++ b/commands/devices.js @@ -13,15 +13,20 @@ const botDevices = (bot) => { const typeNumber = data.type; if (typeNumber === 2) { admin = true; - console.log("IS admin"); - } - else { + console.log("IS ADMIN") + } else { admin = false; - console.log("IS not admin"); + return message.reply("Devi essere amministratore per vedere la lista dispositivi") } }) - .catch(() => { - return message.reply(`Errore verifica account, esegui il comando /login`); + .catch((err) => { + if (err.response.status === 403) { + admin = false; + return message.reply("Devi essere amministratore per vedere la lista dispositivi") + } else { + admin = false; + return message.reply(`Esegui di nuovo il comando /login`); + } }); const typeUser = await resType; return typeUser; @@ -41,7 +46,6 @@ const botDevices = (bot) => { }) .catch((err) => { admin = false; - return message.reply("Devi essere un amministratore"); }); const buttonsData = await response; return buttonsData; @@ -62,8 +66,6 @@ const botDevices = (bot) => { // `sended` is the sent message. }); }); - } else { - return message.reply("Devi essere un amministratore"); } }); }); From 560d27cec691b4b0b6a5d6b2068321ee2a75476a Mon Sep 17 00:00:00 2001 From: Giovanni Date: Sat, 25 Apr 2020 18:23:56 +0200 Subject: [PATCH 51/71] Update devices.js --- commands/devices.js | 48 +++++++++++++++++++++++++++++++++------------ 1 file changed, 36 insertions(+), 12 deletions(-) diff --git a/commands/devices.js b/commands/devices.js index 1197540..8d1d1e1 100644 --- a/commands/devices.js +++ b/commands/devices.js @@ -2,8 +2,32 @@ require("dotenv").config(); const axios = require("axios"); let admin = false; +const callBackFunction = (message,bot) => { + console.log(message.chat.id); + const options = { + reply_markup: JSON.stringify({ + keyboard: [ + [{ text: "Attiva sensore", callback_data: "1" }], + [{ text: "Disattiva sensore", callback_data: "2" }], + ], + }), + }; + console.log(options); + bot.telegram + .sendMessage(message.chat.id, "Segli l'opzione", options) + .then(function (sended) { + // `sended` is the sent message. + console.log("FATTO"); + }) + .catch(() => { + console.log("Errore"); + }); +}; + const botDevices = (bot) => { + let message2; bot.command("devices", (message) => { + message2=message; const username = message.from.username; const getType = async () => { const resType = await axios @@ -13,25 +37,23 @@ const botDevices = (bot) => { const typeNumber = data.type; if (typeNumber === 2) { admin = true; - console.log("IS ADMIN") + console.log("IS ADMIN"); } else { admin = false; - return message.reply("Devi essere amministratore per vedere la lista dispositivi") + return message.reply( + "Devi essere amministratore per vedere la lista dispositivi" + ); } }) .catch((err) => { - if (err.response.status === 403) { - admin = false; - return message.reply("Devi essere amministratore per vedere la lista dispositivi") - } else { - admin = false; - return message.reply(`Esegui di nuovo il comando /login`); - } + admin = false; + return message.reply(`Esegui di nuovo il comando /login`); }); const typeUser = await resType; return typeUser; }; getType().then(() => { + console.log(getType()); if (admin) { const buttonList = []; const getButtons = async () => { @@ -41,10 +63,12 @@ const botDevices = (bot) => { admin = true; const devices = res.data; devices.forEach((device) => { - buttonList.push([{ text: device.name, callback_data: "1" }]); + buttonList.push([ + { text: device.name, callback_data: "callBackFunction(message2,bot)" }, + ]); }); }) - .catch((err) => { + .catch(() => { admin = false; }); const buttonsData = await response; @@ -53,7 +77,7 @@ const botDevices = (bot) => { getButtons().then(() => { const options = { reply_markup: JSON.stringify({ - inline_keyboard: buttonList, + keyboard: buttonList, }), }; bot.telegram From efd4bf8897b7f6b2c0f08709e8ced37a56ee2621 Mon Sep 17 00:00:00 2001 From: Mariano Date: Sat, 25 Apr 2020 20:20:24 +0200 Subject: [PATCH 52/71] Refactor di Login, aggiunta l'autenticazione automatica ai comandi che lo richiedono --- __tests__/bot.test.js | 4 ++-- commands/devices.js | 13 +++++------ commands/help.js | 25 +++++++++++++++++++++ commands/info.js | 47 ++++++++++++++++++++++++++++++---------- commands/login.js | 41 ++--------------------------------- commands/login_backup.js | 40 ++++++++++++++++++++++++++++++++++ commands/start.js | 2 +- commands/status.js | 41 ----------------------------------- main.js | 14 ++++++------ utils/auth.js | 41 +++++++++++++++++++++++++++++++++++ utils/config.js | 12 +++++----- 11 files changed, 167 insertions(+), 113 deletions(-) create mode 100644 commands/help.js create mode 100644 commands/login_backup.js delete mode 100644 commands/status.js create mode 100644 utils/auth.js diff --git a/__tests__/bot.test.js b/__tests__/bot.test.js index 2d7d165..0d0836f 100644 --- a/__tests__/bot.test.js +++ b/__tests__/bot.test.js @@ -1,8 +1,8 @@ // test bot const { botStart } = require("../commands/start"); -const { botInfo } = require("../commands/info"); +const { botInfo } = require("../commands/help"); const { botLogin } = require("../commands/login"); -const { botStatus } = require("../commands/status"); +const { botStatus } = require("../commands/info"); const Telegraf = require("telegraf"); const tokenBot = process.env.BOT_TOKEN; diff --git a/commands/devices.js b/commands/devices.js index 8d1d1e1..b22cf07 100644 --- a/commands/devices.js +++ b/commands/devices.js @@ -1,5 +1,3 @@ -require("dotenv").config(); -const axios = require("axios"); let admin = false; const callBackFunction = (message,bot) => { @@ -14,7 +12,7 @@ const callBackFunction = (message,bot) => { }; console.log(options); bot.telegram - .sendMessage(message.chat.id, "Segli l'opzione", options) + .sendMessage(message.chat.id, "Scegli l'opzione", options) .then(function (sended) { // `sended` is the sent message. console.log("FATTO"); @@ -24,12 +22,13 @@ const callBackFunction = (message,bot) => { }); }; -const botDevices = (bot) => { - let message2; +const botDevices = (bot, axios, auth) => { bot.command("devices", (message) => { - message2=message; const username = message.from.username; const getType = async () => { + + await auth.jwtAuth(axios, message); + const resType = await axios .get(`${process.env.URL_API}/users?telegramName=${username}`) .then((res) => { @@ -64,7 +63,7 @@ const botDevices = (bot) => { const devices = res.data; devices.forEach((device) => { buttonList.push([ - { text: device.name, callback_data: "callBackFunction(message2,bot)" }, + { text: device.name, callback_data: "callBackFunction(message,bot)" }, ]); }); }) diff --git a/commands/help.js b/commands/help.js new file mode 100644 index 0000000..9ad516f --- /dev/null +++ b/commands/help.js @@ -0,0 +1,25 @@ +const botHelp = (bot) => { + bot.command("help", ({ replyWithMarkdown }) => { + replyWithMarkdown(` +*RIoT - Telegram Bot* + +Ecco la lista dei comandi disponibili: + +- /help - informazioni di supporto (corrente) +- /login - primo avvio e registrazione account +- /info - informazioni utente corrente +- /devices - dispositivi a cui è possibile inviare input + +*Procedura di autenticazione Telegram* + +1. Accedere alla web-app +2. Spostarsi nella sezione *impostazioni* +3. Compilare il campo Telegram nel primo modulo delle impostazioni +4. Tornare al bot Telegram +5. Eseguire il comando /login + +In caso di problemi con la procedura, contattare il proprio moderatore ente. + `); + }); +}; +module.exports.botHelp = botHelp; diff --git a/commands/info.js b/commands/info.js index d9fba52..e059263 100644 --- a/commands/info.js +++ b/commands/info.js @@ -1,14 +1,39 @@ -const botInfo = (bot) => { - bot.command("info", ({ replyWithMarkdown }) => { - replyWithMarkdown(` -RIoT Bot --------- -Ecco la lista dei comandi disponibili: -- /login - primo avvio e registrazione account -- /status - informazioni utente corrente -- /info - queste informazioni -- /devices - dispositivi a cui è possibile inviare input - `); +const botInfo = (bot, axios, auth) => { + bot.command("info", (message) => { + const username = message.from.username; + + const getUserInfo = async () => { + await auth.jwtAuth(axios, message); + + await axios + .get(`${process.env.URL_API}/users?telegramName=${username}`) + .then((res) => { + const data = res.data[0]; + const name = data.name; + const surname = data.surname; + const email = data.email; + const typeNumber = data.type; + let type = "Utente"; + if (typeNumber === 1) { + type = "Moderatore"; + } else if (typeNumber === 2) { + type = "Amministratore"; + } + return message.replyWithMarkdown( + ` + Ecco i tuoi dati *${message.from.username}* + - *Nome:* ${name} + - *Cognome:* ${surname} + - *Email:* ${email} + - *Tipo:* ${type}` + ); + }) + .catch((err) => { + console.log(err); + message.reply("Errore nel controllo dei dati!"); + }); + }; + return getUserInfo(); }); }; module.exports.botInfo = botInfo; diff --git a/commands/login.js b/commands/login.js index 2db712c..6641637 100644 --- a/commands/login.js +++ b/commands/login.js @@ -1,43 +1,6 @@ -require("dotenv").config(); -const axios = require("axios"); - -const botLogin = (bot) => { +const botLogin = (bot, axios, auth) => { bot.command("login", (message) => { - const username = message.from.username; - const chatId = message.from.id; - axios - .post(`${process.env.URL_API}/auth/telegram`, { - telegramName: username, - telegramChat: chatId, - }) - .then((res) => { - const code = res.data.code; - const token = res.data.token; - if (code === 1) { - axios.defaults.headers.common["Authorization"] = "Bearer " + token; - return message.reply("Username trovato, registrazione riuscita!"); - } else if (code === 2) { - axios.defaults.headers.common["Authorization"] = "Bearer " + token; - return message.reply( - "Account già registrato, nessuna modifica apportata." - ); - } else if (code === 0) { - return message.reply( - "Username non trovato, registra il tuo Username dalle impostazioni della webapp" - ); - } - }) - .catch((err) => { - console.log(err); - // console.log(err.status); - if (err.response != null && err.response.status === 403) { - return message.reply( - "Effettua nuovamente l'autenticazione usando il comando /login" - ); - } else { - return message.reply("Errore nel controllo dei dati"); - } - }); + auth.jwtAuth(axios, message, true); }); }; module.exports.botLogin = botLogin; diff --git a/commands/login_backup.js b/commands/login_backup.js new file mode 100644 index 0000000..0d9cabb --- /dev/null +++ b/commands/login_backup.js @@ -0,0 +1,40 @@ +const botLogin = (bot, axios, auth) => { + bot.command("login", (message) => { + const username = message.from.username; + const chatId = message.from.id; + axios + .post(`${process.env.URL_API}/auth/telegram`, { + telegramName: username, + telegramChat: chatId, + }) + .then((res) => { + const code = res.data.code; + const token = res.data.token; + if (code === 1) { + axios.defaults.headers.common["Authorization"] = "Bearer " + token; + return message.reply("Username trovato, registrazione riuscita!"); + } else if (code === 2) { + axios.defaults.headers.common["Authorization"] = "Bearer " + token; + return message.reply( + "Account già registrato, nessuna modifica apportata." + ); + } else if (code === 0) { + return message.reply( + "Username non trovato, registra il tuo Username dalle impostazioni della web-app" + ); + } + }) + .catch((err) => { + console.log(err); + // console.log(err.status); + if (err.response != null && err.response.status === 403) { + return message.reply( + "Effettua nuovamente l'autenticazione usando il comando /login" + ); + } else { + return message.reply("Errore nel controllo dei dati"); + } + }); + }); +}; +module.exports.botLogin = botLogin; diff --git a/commands/start.js b/commands/start.js index 17d1448..ea0dd09 100644 --- a/commands/start.js +++ b/commands/start.js @@ -5,7 +5,7 @@ const botStart = (bot) => { return message.replyWithMarkdown(` Ciao *${username}*, benvenuto nel RIoT bot! Usa il comando /login per effettuare l'autenticazione. -Per vedere la lista del comandi che puoi utilizzare usa il comando /info`); +Se hai bisogno di aiuto digita il comando /help`); }); }; diff --git a/commands/status.js b/commands/status.js deleted file mode 100644 index 5c73400..0000000 --- a/commands/status.js +++ /dev/null @@ -1,41 +0,0 @@ -require("dotenv").config(); -const axios = require("axios"); - -const botStatus = (bot) => { - bot.command("status", (message) => { - const username = message.from.username; - axios - .get(`${process.env.URL_API}/users?telegramName=${username}`) - .then((res) => { - const data = res.data[0]; - const name = data.name; - const surname = data.surname; - const email = data.email; - const typeNumber = data.type; - let type = "Utente"; - if (typeNumber === 1) { - type = "Moderatore"; - } else if (typeNumber === 2) { - type = "Amministratore"; - } - return message.replyWithMarkdown( - ` - Ecco i tuoi dati *${message.from.username}* - - *Nome:* ${name} - - *Cognome:* ${surname} - - *Email:* ${email} - - *Tipo:* ${type}` - ); - }) - .catch((err) => { - if (err.response != null && err.response.status === 403) { - message.reply( - "Effettua prima l'autenticazione usando il comando /login" - ); - } else { - message.reply("Errore nel controllo dei dati!"); - } - }); - }); -}; -module.exports.botStatus = botStatus; diff --git a/main.js b/main.js index 755c7ff..45d1372 100644 --- a/main.js +++ b/main.js @@ -1,20 +1,20 @@ const { axios } = require("./utils/config"); -require("dotenv").config(); const Telegraf = require("telegraf"); const bot = new Telegraf(process.env.BOT_TOKEN); const { botServer } = require("./utils/server"); +const auth = require("./utils/auth"); const cmdStart = require("./commands/start"); -const cmdInfo = require("./commands/info"); +const cmdHelp = require("./commands/help"); const cmdLogin = require("./commands/login"); -const cmdStatus = require("./commands/status"); +const cmdInfo = require("./commands/info"); const cmdDevices = require("./commands/devices"); cmdStart.botStart(bot); -cmdInfo.botInfo(bot); -cmdLogin.botLogin(bot, axios); -cmdStatus.botStatus(bot, axios); -cmdDevices.botDevices(bot); +cmdHelp.botHelp(bot); +cmdLogin.botLogin(bot, axios, auth); +cmdInfo.botInfo(bot, axios, auth); +cmdDevices.botDevices(bot, axios, auth); botServer.listen(process.env.SERVER_PORT); console.log( diff --git a/utils/auth.js b/utils/auth.js new file mode 100644 index 0000000..b7ecf3d --- /dev/null +++ b/utils/auth.js @@ -0,0 +1,41 @@ +const jwtAuth = (axios, message, displayReply = false) => { + const username = message.from.username; + const chatId = message.from.id; + return axios + .post(`${process.env.URL_API}/auth/telegram`, { + telegramName: username, + telegramChat: chatId, + }) + .then((res) => { + const code = res.data.code; + const token = res.data.token; + if (code === 1 || code === 2) { + axios.defaults.headers.common["Authorization"] = "Bearer " + token; + } + if (displayReply) { + switch (code) { + case 1: + return message.reply("Username trovato, registrazione riuscita!"); + case 2: + return message.reply( + "Account già registrato, nessuna modifica apportata." + ); + case 3: + return message.reply( + "Username non trovato, registra il tuo username Telegram dalle impostazioni della web-app." + ); + default: + break; + } + } + }) + .catch((err) => { + console.log(err); + if (displayReply) { + return message.reply( + "Errore nel controllo dei dati, prova ad eseguire nuovamente /login o nel caso contatta l'amministrazione." + ); + } + }); +}; +module.exports.jwtAuth = jwtAuth; diff --git a/utils/config.js b/utils/config.js index 79d6e1a..c0b98c9 100644 --- a/utils/config.js +++ b/utils/config.js @@ -3,10 +3,10 @@ const axios = require("axios"); const botCommands = [ { command: "info", description: "Lista dei comandi del bot e informazioni" }, - { command: "login", description: "Autenticazione al sistema" }, - { command: "status", description: "Controllo dello status dell'utente" }, + { command: "login", description: "Avvio e autenticazione al sistema" }, + { command: "info", description: "Controllo delle informazioni dell'utente" }, { - command: "dispositivi", + command: "devices", description: "[Admin] Visualizza lista dispositivi a cui inviare input", }, ]; @@ -16,8 +16,10 @@ axios commands: botCommands, }) .then(() => { - console.log("Comandi caricati"); + console.log("[Telegram] Info comandi caricati!"); }) .catch(() => { - console.log("Errore caricamento comandi"); + console.log("[Telegram] Errore caricamento comandi"); }); + +module.exports.axios = axios; From 0def5a79a03190c81ac879754e27979747f42def Mon Sep 17 00:00:00 2001 From: Mariano Date: Sat, 25 Apr 2020 20:30:22 +0200 Subject: [PATCH 53/71] Fix minore devices --- commands/devices.js | 15 ++++++--------- commands/login_backup.js | 40 ---------------------------------------- 2 files changed, 6 insertions(+), 49 deletions(-) delete mode 100644 commands/login_backup.js diff --git a/commands/devices.js b/commands/devices.js index b22cf07..85f9feb 100644 --- a/commands/devices.js +++ b/commands/devices.js @@ -26,10 +26,8 @@ const botDevices = (bot, axios, auth) => { bot.command("devices", (message) => { const username = message.from.username; const getType = async () => { - await auth.jwtAuth(axios, message); - - const resType = await axios + return await axios .get(`${process.env.URL_API}/users?telegramName=${username}`) .then((res) => { const data = res.data[0]; @@ -48,30 +46,29 @@ const botDevices = (bot, axios, auth) => { admin = false; return message.reply(`Esegui di nuovo il comando /login`); }); - const typeUser = await resType; - return typeUser; }; getType().then(() => { console.log(getType()); if (admin) { const buttonList = []; const getButtons = async () => { - const response = await axios + return await axios .get(`${process.env.URL_API}/devices`) .then((res) => { admin = true; const devices = res.data; devices.forEach((device) => { buttonList.push([ - { text: device.name, callback_data: "callBackFunction(message,bot)" }, + { + text: device.name, + callback_data: "callBackFunction(message, bot)", + }, ]); }); }) .catch(() => { admin = false; }); - const buttonsData = await response; - return buttonsData; }; getButtons().then(() => { const options = { diff --git a/commands/login_backup.js b/commands/login_backup.js deleted file mode 100644 index 0d9cabb..0000000 --- a/commands/login_backup.js +++ /dev/null @@ -1,40 +0,0 @@ -const botLogin = (bot, axios, auth) => { - bot.command("login", (message) => { - const username = message.from.username; - const chatId = message.from.id; - axios - .post(`${process.env.URL_API}/auth/telegram`, { - telegramName: username, - telegramChat: chatId, - }) - .then((res) => { - const code = res.data.code; - const token = res.data.token; - if (code === 1) { - axios.defaults.headers.common["Authorization"] = "Bearer " + token; - return message.reply("Username trovato, registrazione riuscita!"); - } else if (code === 2) { - axios.defaults.headers.common["Authorization"] = "Bearer " + token; - return message.reply( - "Account già registrato, nessuna modifica apportata." - ); - } else if (code === 0) { - return message.reply( - "Username non trovato, registra il tuo Username dalle impostazioni della web-app" - ); - } - }) - .catch((err) => { - console.log(err); - // console.log(err.status); - if (err.response != null && err.response.status === 403) { - return message.reply( - "Effettua nuovamente l'autenticazione usando il comando /login" - ); - } else { - return message.reply("Errore nel controllo dei dati"); - } - }); - }); -}; -module.exports.botLogin = botLogin; From 888c6ccef123a90bddf33eda84d84f05d5a5d457 Mon Sep 17 00:00:00 2001 From: Mariano Date: Sat, 25 Apr 2020 20:34:23 +0200 Subject: [PATCH 54/71] Update bot.test.js --- __tests__/bot.test.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/__tests__/bot.test.js b/__tests__/bot.test.js index 0d0836f..22cb79a 100644 --- a/__tests__/bot.test.js +++ b/__tests__/bot.test.js @@ -1,8 +1,8 @@ // test bot const { botStart } = require("../commands/start"); -const { botInfo } = require("../commands/help"); +const { botInfo } = require("../commands/info"); const { botLogin } = require("../commands/login"); -const { botStatus } = require("../commands/info"); +const { botHelp } = require("../commands/help"); const Telegraf = require("telegraf"); const tokenBot = process.env.BOT_TOKEN; @@ -13,16 +13,16 @@ test("Check login", () => { expect(botLogin(bot)).toBe(undefined); }); // LAUNCH -test("Check status", () => { - expect(botStatus(bot)).toBe(undefined); +test("Check info", () => { + expect(botInfo(bot)).toBe(undefined); }); // START test("Check status", () => { expect(botStart(bot)).toBe(undefined); }); // INFO -test("Check info", () => { - expect(botInfo(bot)).toBe(undefined); +test("Check help", () => { + expect(botHelp(bot)).toBe(undefined); }); // const s = {"botLaunch": [Function botLaunch]`; // const t = JSON.parse(s); From da9f2a4d534a0f0ae13fe12d75244596c517222a Mon Sep 17 00:00:00 2001 From: Giovanni Date: Sun, 26 Apr 2020 12:09:56 +0200 Subject: [PATCH 55/71] upload devices --- commands/devices.js | 24 ++++++++++++++++-------- utils/config.js | 2 +- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/commands/devices.js b/commands/devices.js index 85f9feb..6872307 100644 --- a/commands/devices.js +++ b/commands/devices.js @@ -1,6 +1,6 @@ let admin = false; -const callBackFunction = (message,bot) => { +const callBackFunction = (message, bot) => { console.log(message.chat.id); const options = { reply_markup: JSON.stringify({ @@ -18,7 +18,7 @@ const callBackFunction = (message,bot) => { console.log("FATTO"); }) .catch(() => { - console.log("Errore"); + console.log("Errore nell'invio del messaggio"); }); }; @@ -34,7 +34,6 @@ const botDevices = (bot, axios, auth) => { const typeNumber = data.type; if (typeNumber === 2) { admin = true; - console.log("IS ADMIN"); } else { admin = false; return message.reply( @@ -42,13 +41,12 @@ const botDevices = (bot, axios, auth) => { ); } }) - .catch((err) => { + .catch(() => { admin = false; return message.reply(`Esegui di nuovo il comando /login`); }); }; getType().then(() => { - console.log(getType()); if (admin) { const buttonList = []; const getButtons = async () => { @@ -61,7 +59,7 @@ const botDevices = (bot, axios, auth) => { buttonList.push([ { text: device.name, - callback_data: "callBackFunction(message, bot)", + callback_query: "1", }, ]); }); @@ -74,6 +72,9 @@ const botDevices = (bot, axios, auth) => { const options = { reply_markup: JSON.stringify({ keyboard: buttonList, + one_time_keyboard: true, + resize_keyboard: true, + callback_data: "click", }), }; bot.telegram @@ -82,12 +83,19 @@ const botDevices = (bot, axios, auth) => { "Ecco la lista dei dispositivi", options ) - .then(function (sended) { - // `sended` is the sent message. + .then((sent) => { + // sent is the message }); }); } }); }); + bot.on("callback_query", (callbackQuery) => { + const msg = callbackQuery.message; + console.log("sono qui") + bot.telegram + .answerCallbackQuery(callbackQuery.id) + .then(() => bot.sendMessage(msg.chat.id, "You clicked!")); + }); }; module.exports.botDevices = botDevices; diff --git a/utils/config.js b/utils/config.js index c0b98c9..b96d408 100644 --- a/utils/config.js +++ b/utils/config.js @@ -2,7 +2,7 @@ require("dotenv").config(); const axios = require("axios"); const botCommands = [ - { command: "info", description: "Lista dei comandi del bot e informazioni" }, + { command: "help", description: "Lista dei comandi del bot e informazioni" }, { command: "login", description: "Avvio e autenticazione al sistema" }, { command: "info", description: "Controllo delle informazioni dell'utente" }, { From 226c1cc32599ba84b5738da69229f8884c70deab Mon Sep 17 00:00:00 2001 From: Giovanni Date: Sun, 26 Apr 2020 14:45:31 +0200 Subject: [PATCH 56/71] Update devices.js --- commands/devices.js | 69 +++++++++++++-------------------------------- 1 file changed, 19 insertions(+), 50 deletions(-) diff --git a/commands/devices.js b/commands/devices.js index 6872307..e2e2a44 100644 --- a/commands/devices.js +++ b/commands/devices.js @@ -1,29 +1,10 @@ +const Markup = require("telegraf/markup"); +const Extra = require("telegraf/extra"); let admin = false; -const callBackFunction = (message, bot) => { - console.log(message.chat.id); - const options = { - reply_markup: JSON.stringify({ - keyboard: [ - [{ text: "Attiva sensore", callback_data: "1" }], - [{ text: "Disattiva sensore", callback_data: "2" }], - ], - }), - }; - console.log(options); - bot.telegram - .sendMessage(message.chat.id, "Scegli l'opzione", options) - .then(function (sended) { - // `sended` is the sent message. - console.log("FATTO"); - }) - .catch(() => { - console.log("Errore nell'invio del messaggio"); - }); -}; - const botDevices = (bot, axios, auth) => { - bot.command("devices", (message) => { + let deviceList = []; + bot.command("devices", ({ message, reply }) => { const username = message.from.username; const getType = async () => { await auth.jwtAuth(axios, message); @@ -48,7 +29,6 @@ const botDevices = (bot, axios, auth) => { }; getType().then(() => { if (admin) { - const buttonList = []; const getButtons = async () => { return await axios .get(`${process.env.URL_API}/devices`) @@ -56,10 +36,9 @@ const botDevices = (bot, axios, auth) => { admin = true; const devices = res.data; devices.forEach((device) => { - buttonList.push([ + deviceList.push([ { text: device.name, - callback_query: "1", }, ]); }); @@ -69,33 +48,23 @@ const botDevices = (bot, axios, auth) => { }); }; getButtons().then(() => { - const options = { - reply_markup: JSON.stringify({ - keyboard: buttonList, - one_time_keyboard: true, - resize_keyboard: true, - callback_data: "click", - }), - }; - bot.telegram - .sendMessage( - message.chat.id, - "Ecco la lista dei dispositivi", - options - ) - .then((sent) => { - // sent is the message - }); + console.log("Lista dispositivi caricata correttamente"); }); } }); - }); - bot.on("callback_query", (callbackQuery) => { - const msg = callbackQuery.message; - console.log("sono qui") - bot.telegram - .answerCallbackQuery(callbackQuery.id) - .then(() => bot.sendMessage(msg.chat.id, "You clicked!")); + + reply( + "Seleziona il dispositivo a cui inviare un comando", + Markup.keyboard(deviceList).oneTime().resize().extra() + ); + deviceList = []; + + bot.hears("WATER-MACHINE", (ctx) => { + return ctx.reply( + "Seleziona il sensore", + Extra.markup(Markup.keyboard(["sensore1", "sensore2", "sensore3"])) + ); + }); }); }; module.exports.botDevices = botDevices; From 3b5f603ce31a914fa556e9c652b5f629dd825104 Mon Sep 17 00:00:00 2001 From: Giovanni Date: Sun, 26 Apr 2020 15:50:11 +0200 Subject: [PATCH 57/71] Update devices.js --- commands/devices.js | 39 ++++++++++++++++++++++++++++++--------- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/commands/devices.js b/commands/devices.js index e2e2a44..e4ae4da 100644 --- a/commands/devices.js +++ b/commands/devices.js @@ -4,7 +4,7 @@ let admin = false; const botDevices = (bot, axios, auth) => { let deviceList = []; - bot.command("devices", ({ message, reply }) => { + bot.command("devices", (message) => { const username = message.from.username; const getType = async () => { await auth.jwtAuth(axios, message); @@ -35,6 +35,7 @@ const botDevices = (bot, axios, auth) => { .then((res) => { admin = true; const devices = res.data; + // text: device.name, devices.forEach((device) => { deviceList.push([ { @@ -52,19 +53,39 @@ const botDevices = (bot, axios, auth) => { }); } }); - - reply( - "Seleziona il dispositivo a cui inviare un comando", + return message.reply( + "random example", Markup.keyboard(deviceList).oneTime().resize().extra() ); + console.log(deviceList); + // reply( + // "Seleziona il dispositivo a cui inviare un comando", + // Markup.keyboard(deviceList).oneTime().resize().extra() + // ); deviceList = []; - - bot.hears("WATER-MACHINE", (ctx) => { - return ctx.reply( + // bot.action("WATER-MACHINE", (ctx, next) => { + // return ctx + // .reply( + // "Seleziona il sensore", + // Extra.markup(Markup.keyboard(["sensore1", "sensore2", "sensore3"])) + // ) + // .then(() => next()); + // }) + + // bot.hears("WATER-MACHINE", (ctx) => { + // return ctx.reply( + // "Seleziona il sensore", + // Extra.markup(Markup.keyboard(["sensore1", "sensore2", "sensore3"])) + // ); + // }); + }); + bot.action("WATER-MACHINE", (ctx, next) => { + return ctx + .reply( "Seleziona il sensore", Extra.markup(Markup.keyboard(["sensore1", "sensore2", "sensore3"])) - ); - }); + ) + .then(() => next()); }); }; module.exports.botDevices = botDevices; From 8cd2e5e209cda8dbab6f5dcd81db96cf3ae86807 Mon Sep 17 00:00:00 2001 From: Mariano Date: Sun, 26 Apr 2020 16:44:55 +0200 Subject: [PATCH 58/71] Update devices.js --- commands/devices.js | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/commands/devices.js b/commands/devices.js index e4ae4da..86b28b2 100644 --- a/commands/devices.js +++ b/commands/devices.js @@ -35,14 +35,15 @@ const botDevices = (bot, axios, auth) => { .then((res) => { admin = true; const devices = res.data; - // text: device.name, devices.forEach((device) => { - deviceList.push([ - { - text: device.name, - }, - ]); + deviceList.push( + Markup.callbackButton( + "device_" + device.name, + device.name + ) + ); }); + deviceList.push(Markup.callbackButton("bottone senza risposta", "ciaone")); }) .catch(() => { admin = false; @@ -53,11 +54,15 @@ const botDevices = (bot, axios, auth) => { }); } }); + return message.reply( "random example", - Markup.keyboard(deviceList).oneTime().resize().extra() + Markup.keyboard(deviceList) + .oneTime() + .resize() + .extra() ); - console.log(deviceList); + // console.log(deviceList); // reply( // "Seleziona il dispositivo a cui inviare un comando", // Markup.keyboard(deviceList).oneTime().resize().extra() @@ -79,13 +84,17 @@ const botDevices = (bot, axios, auth) => { // ); // }); }); - bot.action("WATER-MACHINE", (ctx, next) => { - return ctx + bot.hears(/^(device_)(.*)$/gi, (ctx) => { + console.log("Robe"); + /* return ctx .reply( - "Seleziona il sensore", + "Seleziona il sensore:", Extra.markup(Markup.keyboard(["sensore1", "sensore2", "sensore3"])) ) .then(() => next()); + */ + + return ctx.reply(`Oh, ` + ctx.match[0] + ` Great choice`); }); }; module.exports.botDevices = botDevices; From ed62e862235c7b92851ccea6517cf55a6cc4a847 Mon Sep 17 00:00:00 2001 From: Giovanni Date: Sun, 26 Apr 2020 17:48:30 +0200 Subject: [PATCH 59/71] Update devices.js --- commands/devices.js | 38 +++++++------------------------------- 1 file changed, 7 insertions(+), 31 deletions(-) diff --git a/commands/devices.js b/commands/devices.js index 86b28b2..229b2f4 100644 --- a/commands/devices.js +++ b/commands/devices.js @@ -37,13 +37,12 @@ const botDevices = (bot, axios, auth) => { const devices = res.data; devices.forEach((device) => { deviceList.push( - Markup.callbackButton( - "device_" + device.name, - device.name - ) + Markup.callbackButton(`device_${device.name}`, device.name) ); }); - deviceList.push(Markup.callbackButton("bottone senza risposta", "ciaone")); + deviceList.push( + Markup.callbackButton("bottone senza risposta", "ciaone") + ); }) .catch(() => { admin = false; @@ -55,34 +54,11 @@ const botDevices = (bot, axios, auth) => { } }); - return message.reply( + message.reply( "random example", - Markup.keyboard(deviceList) - .oneTime() - .resize() - .extra() + Markup.keyboard(deviceList).oneTime().resize().extra() ); - // console.log(deviceList); - // reply( - // "Seleziona il dispositivo a cui inviare un comando", - // Markup.keyboard(deviceList).oneTime().resize().extra() - // ); deviceList = []; - // bot.action("WATER-MACHINE", (ctx, next) => { - // return ctx - // .reply( - // "Seleziona il sensore", - // Extra.markup(Markup.keyboard(["sensore1", "sensore2", "sensore3"])) - // ) - // .then(() => next()); - // }) - - // bot.hears("WATER-MACHINE", (ctx) => { - // return ctx.reply( - // "Seleziona il sensore", - // Extra.markup(Markup.keyboard(["sensore1", "sensore2", "sensore3"])) - // ); - // }); }); bot.hears(/^(device_)(.*)$/gi, (ctx) => { console.log("Robe"); @@ -94,7 +70,7 @@ const botDevices = (bot, axios, auth) => { .then(() => next()); */ - return ctx.reply(`Oh, ` + ctx.match[0] + ` Great choice`); + return ctx.reply(`Oh, ${ctx.match[0]} Great choice`); }); }; module.exports.botDevices = botDevices; From a8f4ea63430c1a77ba9438f81acf9adcd331efa5 Mon Sep 17 00:00:00 2001 From: Giovanni Date: Mon, 27 Apr 2020 13:03:42 +0200 Subject: [PATCH 60/71] viasualizza lista sensori dispositivo e override keyboard --- commands/devices.js | 56 ++++++++++++++++++++++++++++++--------------- 1 file changed, 37 insertions(+), 19 deletions(-) diff --git a/commands/devices.js b/commands/devices.js index 229b2f4..8b18d6a 100644 --- a/commands/devices.js +++ b/commands/devices.js @@ -3,7 +3,7 @@ const Extra = require("telegraf/extra"); let admin = false; const botDevices = (bot, axios, auth) => { - let deviceList = []; + const deviceList = []; bot.command("devices", (message) => { const username = message.from.username; const getType = async () => { @@ -37,7 +37,10 @@ const botDevices = (bot, axios, auth) => { const devices = res.data; devices.forEach((device) => { deviceList.push( - Markup.callbackButton(`device_${device.name}`, device.name) + Markup.callbackButton( + `${device.deviceId}_${device.name}`, + device.name + ) ); }); deviceList.push( @@ -48,29 +51,44 @@ const botDevices = (bot, axios, auth) => { admin = false; }); }; - getButtons().then(() => { + getButtons(message).then(() => { console.log("Lista dispositivi caricata correttamente"); + message.reply("", Markup.removeKeyboard(true)); + message.reply( + "Ecco la lista dei dispositivi a quali puoi inviare un comando:", + Markup.keyboard(deviceList).oneTime().resize().extra() + ); }); } }); - - message.reply( - "random example", - Markup.keyboard(deviceList).oneTime().resize().extra() - ); - deviceList = []; }); - bot.hears(/^(device_)(.*)$/gi, (ctx) => { - console.log("Robe"); - /* return ctx - .reply( + bot.hears(/^\d(_)(.*)$/gi, (message) => { + const deviceID = message.match[0].match(/^\d/gi); + let sensorsList = []; + const getButtons = async () => { + return axios + .get(`${process.env.URL_API}/devices/${deviceID}/sensors`) + .then((res) => { + const sensors = res.data; + sensors.forEach((sensor) => { + sensorsList.push( + Markup.callbackButton( + `${sensor.sensorId}_${sensor.type}`, + sensor.type + ) + ); + }); + }); + }; + getButtons(message).then(() => { + console.log("Lista sensori caricata correttamente"); + message.reply("", Markup.removeKeyboard(true)); + message.reply( "Seleziona il sensore:", - Extra.markup(Markup.keyboard(["sensore1", "sensore2", "sensore3"])) - ) - .then(() => next()); - */ - - return ctx.reply(`Oh, ${ctx.match[0]} Great choice`); + Markup.keyboard(sensorsList).oneTime().resize().extra() + ); + sensorsList = []; + }); }); }; module.exports.botDevices = botDevices; From 965fd347fcd10ae428586ab826077958c592af53 Mon Sep 17 00:00:00 2001 From: Giovanni Date: Mon, 27 Apr 2020 14:29:25 +0200 Subject: [PATCH 61/71] Bug fixed, attiva/disattiva sensore --- commands/devices.js | 57 +++++++++++++++++++++++++++++++++++---------- 1 file changed, 45 insertions(+), 12 deletions(-) diff --git a/commands/devices.js b/commands/devices.js index 8b18d6a..5e1d487 100644 --- a/commands/devices.js +++ b/commands/devices.js @@ -1,12 +1,12 @@ const Markup = require("telegraf/markup"); -const Extra = require("telegraf/extra"); +// const Extra = require("telegraf/extra"); let admin = false; const botDevices = (bot, axios, auth) => { - const deviceList = []; + let deviceList = []; bot.command("devices", (message) => { const username = message.from.username; - const getType = async () => { + const getTypeUser = async () => { await auth.jwtAuth(axios, message); return await axios .get(`${process.env.URL_API}/users?telegramName=${username}`) @@ -27,7 +27,7 @@ const botDevices = (bot, axios, auth) => { return message.reply(`Esegui di nuovo il comando /login`); }); }; - getType().then(() => { + getTypeUser().then(() => { if (admin) { const getButtons = async () => { return await axios @@ -43,9 +43,9 @@ const botDevices = (bot, axios, auth) => { ) ); }); - deviceList.push( - Markup.callbackButton("bottone senza risposta", "ciaone") - ); + // deviceList.push( + // Markup.callbackButton("bottone senza risposta", "ciaone") + // ); }) .catch(() => { admin = false; @@ -53,16 +53,49 @@ const botDevices = (bot, axios, auth) => { }; getButtons(message).then(() => { console.log("Lista dispositivi caricata correttamente"); - message.reply("", Markup.removeKeyboard(true)); + Markup.removeKeyboard(); message.reply( - "Ecco la lista dei dispositivi a quali puoi inviare un comando:", + "Seleziona il dispositivo a cui inviare un comando:", Markup.keyboard(deviceList).oneTime().resize().extra() ); + deviceList = []; }); } }); }); - bot.hears(/^\d(_)(.*)$/gi, (message) => { + // user has selected to switch on one sensor + bot.hears(/^\d(_)+\d(_)(Attiva)/g, (message) => { + const devSensID = message.match[0].match(/\d/gi); + Markup.removeKeyboard(); + message.reply( + `Il sensore ${devSensID[1]} del dispositivo ${devSensID[0]} è stato attivato con successo!` + ); + }); + // user has selected to switch off one sensor + bot.hears(/^\d(_)+\d(_)(Disattiva)/g, (message) => { + const devSensID = message.match[0].match(/\d/gi); + Markup.removeKeyboard(); + message.reply( + `Il sensore ${devSensID[1]} del dispositivo ${devSensID[0]} è stato disattivato con successo!` + ); + }); + // user has selected one sensor + bot.hears(/^\d(_)+\d(_)(.*)/g, (message) => { + const sensorID = message.match[0].match(/\d/gi); + Markup.removeKeyboard(); + message.reply( + "Seleziona l'opzione:", + Markup.keyboard([ + `${sensorID[0]}_${sensorID[1]}_Attiva`, + `${sensorID[0]}_${sensorID[1]}_Disattiva`, + ]) + .oneTime() + .resize() + .extra() + ); + }); + // user has selected one device + bot.hears(/^\d(_)(.*)/g, (message) => { const deviceID = message.match[0].match(/^\d/gi); let sensorsList = []; const getButtons = async () => { @@ -73,7 +106,7 @@ const botDevices = (bot, axios, auth) => { sensors.forEach((sensor) => { sensorsList.push( Markup.callbackButton( - `${sensor.sensorId}_${sensor.type}`, + `${deviceID}_${sensor.sensorId}_${sensor.type}`, sensor.type ) ); @@ -82,7 +115,7 @@ const botDevices = (bot, axios, auth) => { }; getButtons(message).then(() => { console.log("Lista sensori caricata correttamente"); - message.reply("", Markup.removeKeyboard(true)); + Markup.removeKeyboard(); message.reply( "Seleziona il sensore:", Markup.keyboard(sensorsList).oneTime().resize().extra() From 9ec62b05a86245131674e9e952cb446fd2148415 Mon Sep 17 00:00:00 2001 From: Giovanni Date: Mon, 27 Apr 2020 16:52:22 +0200 Subject: [PATCH 62/71] Update devices.js --- commands/devices.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/commands/devices.js b/commands/devices.js index 5e1d487..b80acb5 100644 --- a/commands/devices.js +++ b/commands/devices.js @@ -64,7 +64,7 @@ const botDevices = (bot, axios, auth) => { }); }); // user has selected to switch on one sensor - bot.hears(/^\d(_)+\d(_)(Attiva)/g, (message) => { + bot.hears(/^\d{1,2}(_)+\d{1,2}(_)(Attiva)/g, (message) => { const devSensID = message.match[0].match(/\d/gi); Markup.removeKeyboard(); message.reply( @@ -72,7 +72,7 @@ const botDevices = (bot, axios, auth) => { ); }); // user has selected to switch off one sensor - bot.hears(/^\d(_)+\d(_)(Disattiva)/g, (message) => { + bot.hears(/^\d{1,2}(_)+\d{1,2}(_)(Disattiva)/g, (message) => { const devSensID = message.match[0].match(/\d/gi); Markup.removeKeyboard(); message.reply( @@ -80,7 +80,7 @@ const botDevices = (bot, axios, auth) => { ); }); // user has selected one sensor - bot.hears(/^\d(_)+\d(_)(.*)/g, (message) => { + bot.hears(/^\d{1,2}(_)+\d{1,2}(_)(.*)/g, (message) => { const sensorID = message.match[0].match(/\d/gi); Markup.removeKeyboard(); message.reply( @@ -95,7 +95,7 @@ const botDevices = (bot, axios, auth) => { ); }); // user has selected one device - bot.hears(/^\d(_)(.*)/g, (message) => { + bot.hears(/^\d{1,2}(_)(.*)/g, (message) => { const deviceID = message.match[0].match(/^\d/gi); let sensorsList = []; const getButtons = async () => { From d758b901b179035d09aa527cd4ff1f4fefe62240 Mon Sep 17 00:00:00 2001 From: Mariano Date: Tue, 28 Apr 2020 15:59:10 +0200 Subject: [PATCH 63/71] Axios instance --- commands/devices.js | 25 +++++++++++++------------ commands/info.js | 11 ++++++----- commands/login.js | 7 +++++-- main.js | 8 ++++---- utils/auth.js | 8 +++++--- 5 files changed, 33 insertions(+), 26 deletions(-) diff --git a/commands/devices.js b/commands/devices.js index b80acb5..2cbfec9 100644 --- a/commands/devices.js +++ b/commands/devices.js @@ -1,14 +1,15 @@ +const axios = require("axios"); const Markup = require("telegraf/markup"); -// const Extra = require("telegraf/extra"); -let admin = false; -const botDevices = (bot, axios, auth) => { +const botDevices = (bot, auth) => { + let admin = false; let deviceList = []; bot.command("devices", (message) => { const username = message.from.username; - const getTypeUser = async () => { - await auth.jwtAuth(axios, message); - return await axios + const axiosInstance = axios.create(); + const getUserRank = async () => { + await auth.jwtAuth(axiosInstance, message); + return await axiosInstance .get(`${process.env.URL_API}/users?telegramName=${username}`) .then((res) => { const data = res.data[0]; @@ -27,10 +28,11 @@ const botDevices = (bot, axios, auth) => { return message.reply(`Esegui di nuovo il comando /login`); }); }; - getTypeUser().then(() => { + getUserRank().then(() => { if (admin) { const getButtons = async () => { - return await axios + await auth.jwtAuth(axiosInstance, message); + return await axiosInstance .get(`${process.env.URL_API}/devices`) .then((res) => { admin = true; @@ -43,9 +45,6 @@ const botDevices = (bot, axios, auth) => { ) ); }); - // deviceList.push( - // Markup.callbackButton("bottone senza risposta", "ciaone") - // ); }) .catch(() => { admin = false; @@ -98,8 +97,10 @@ const botDevices = (bot, axios, auth) => { bot.hears(/^\d{1,2}(_)(.*)/g, (message) => { const deviceID = message.match[0].match(/^\d/gi); let sensorsList = []; + const axiosInstance = axios.create(); const getButtons = async () => { - return axios + await auth.jwtAuth(axiosInstance, message); + return axiosInstance .get(`${process.env.URL_API}/devices/${deviceID}/sensors`) .then((res) => { const sensors = res.data; diff --git a/commands/info.js b/commands/info.js index e059263..e990ee2 100644 --- a/commands/info.js +++ b/commands/info.js @@ -1,11 +1,12 @@ -const botInfo = (bot, axios, auth) => { +const axios = require("axios"); + +const botInfo = (bot, auth) => { bot.command("info", (message) => { const username = message.from.username; - + const axiosInstance = axios.create(); const getUserInfo = async () => { - await auth.jwtAuth(axios, message); - - await axios + await auth.jwtAuth(axiosInstance, message); + return await axiosInstance .get(`${process.env.URL_API}/users?telegramName=${username}`) .then((res) => { const data = res.data[0]; diff --git a/commands/login.js b/commands/login.js index 6641637..ce876f1 100644 --- a/commands/login.js +++ b/commands/login.js @@ -1,6 +1,9 @@ -const botLogin = (bot, axios, auth) => { +const axios = require("axios"); + +const botLogin = (bot, auth) => { bot.command("login", (message) => { - auth.jwtAuth(axios, message, true); + const axiosInstance = axios.create(); + auth.jwtAuth(axiosInstance, message, true); }); }; module.exports.botLogin = botLogin; diff --git a/main.js b/main.js index 45d1372..3b56b7c 100644 --- a/main.js +++ b/main.js @@ -1,4 +1,4 @@ -const { axios } = require("./utils/config"); +require("./utils/config"); const Telegraf = require("telegraf"); const bot = new Telegraf(process.env.BOT_TOKEN); @@ -12,9 +12,9 @@ const cmdDevices = require("./commands/devices"); cmdStart.botStart(bot); cmdHelp.botHelp(bot); -cmdLogin.botLogin(bot, axios, auth); -cmdInfo.botInfo(bot, axios, auth); -cmdDevices.botDevices(bot, axios, auth); +cmdLogin.botLogin(bot, auth); +cmdInfo.botInfo(bot, auth); +cmdDevices.botDevices(bot, auth); botServer.listen(process.env.SERVER_PORT); console.log( diff --git a/utils/auth.js b/utils/auth.js index b7ecf3d..80b1f87 100644 --- a/utils/auth.js +++ b/utils/auth.js @@ -1,7 +1,8 @@ -const jwtAuth = (axios, message, displayReply = false) => { +const jwtAuth = (axiosInstance, message, displayReply = false) => { const username = message.from.username; const chatId = message.from.id; - return axios + + return axiosInstance .post(`${process.env.URL_API}/auth/telegram`, { telegramName: username, telegramChat: chatId, @@ -10,7 +11,8 @@ const jwtAuth = (axios, message, displayReply = false) => { const code = res.data.code; const token = res.data.token; if (code === 1 || code === 2) { - axios.defaults.headers.common["Authorization"] = "Bearer " + token; + axiosInstance.defaults.headers.common["Authorization"] = + "Bearer " + token; } if (displayReply) { switch (code) { From 937c60846ec5129a629f26480d73eff28d3b2758 Mon Sep 17 00:00:00 2001 From: Mariano Date: Tue, 28 Apr 2020 16:50:39 +0200 Subject: [PATCH 64/71] Update devices.js --- commands/devices.js | 176 ++++++++++++++++++++++---------------------- 1 file changed, 87 insertions(+), 89 deletions(-) diff --git a/commands/devices.js b/commands/devices.js index 2cbfec9..af74edc 100644 --- a/commands/devices.js +++ b/commands/devices.js @@ -2,14 +2,14 @@ const axios = require("axios"); const Markup = require("telegraf/markup"); const botDevices = (bot, auth) => { - let admin = false; - let deviceList = []; bot.command("devices", (message) => { const username = message.from.username; const axiosInstance = axios.create(); - const getUserRank = async () => { + let admin = false; + let deviceList = []; + const getDeviceList = async () => { await auth.jwtAuth(axiosInstance, message); - return await axiosInstance + await axiosInstance .get(`${process.env.URL_API}/users?telegramName=${username}`) .then((res) => { const data = res.data[0]; @@ -22,35 +22,28 @@ const botDevices = (bot, auth) => { "Devi essere amministratore per vedere la lista dispositivi" ); } - }) - .catch(() => { - admin = false; - return message.reply(`Esegui di nuovo il comando /login`); }); - }; - getUserRank().then(() => { if (admin) { - const getButtons = async () => { - await auth.jwtAuth(axiosInstance, message); - return await axiosInstance - .get(`${process.env.URL_API}/devices`) - .then((res) => { - admin = true; - const devices = res.data; - devices.forEach((device) => { - deviceList.push( - Markup.callbackButton( - `${device.deviceId}_${device.name}`, - device.name - ) - ); - }); - }) - .catch(() => { - admin = false; + await axiosInstance + .get(`${process.env.URL_API}/devices`) + .then((res) => { + admin = true; + const devices = res.data; + devices.forEach((device) => { + deviceList.push( + Markup.callbackButton( + `${device.deviceId}_${device.name}`, + device.name + ) + ); }); - }; - getButtons(message).then(() => { + }); + } + }; + + if (deviceList.length > 0) { + getDeviceList() + .then(() => { console.log("Lista dispositivi caricata correttamente"); Markup.removeKeyboard(); message.reply( @@ -58,70 +51,75 @@ const botDevices = (bot, auth) => { Markup.keyboard(deviceList).oneTime().resize().extra() ); deviceList = []; + }) + .catch(() => { + message.reply( + "Errore, non hai i permessi per eseguire questa azione, oppure il servizio non è al momento disponibile." + ); }); - } + } + + // user has selected to switch on one sensor + bot.hears(/^\d{1,2}(_)+\d{1,2}(_)(Attiva)/g, (message) => { + const devSensID = message.match[0].match(/\d/gi); + Markup.removeKeyboard(); + message.reply( + `Il sensore @${devSensID[1]} del dispositivo @${devSensID[0]} è stato attivato con successo!` + ); }); - }); - // user has selected to switch on one sensor - bot.hears(/^\d{1,2}(_)+\d{1,2}(_)(Attiva)/g, (message) => { - const devSensID = message.match[0].match(/\d/gi); - Markup.removeKeyboard(); - message.reply( - `Il sensore ${devSensID[1]} del dispositivo ${devSensID[0]} è stato attivato con successo!` - ); - }); - // user has selected to switch off one sensor - bot.hears(/^\d{1,2}(_)+\d{1,2}(_)(Disattiva)/g, (message) => { - const devSensID = message.match[0].match(/\d/gi); - Markup.removeKeyboard(); - message.reply( - `Il sensore ${devSensID[1]} del dispositivo ${devSensID[0]} è stato disattivato con successo!` - ); - }); - // user has selected one sensor - bot.hears(/^\d{1,2}(_)+\d{1,2}(_)(.*)/g, (message) => { - const sensorID = message.match[0].match(/\d/gi); - Markup.removeKeyboard(); - message.reply( - "Seleziona l'opzione:", - Markup.keyboard([ - `${sensorID[0]}_${sensorID[1]}_Attiva`, - `${sensorID[0]}_${sensorID[1]}_Disattiva`, - ]) - .oneTime() - .resize() - .extra() - ); - }); - // user has selected one device - bot.hears(/^\d{1,2}(_)(.*)/g, (message) => { - const deviceID = message.match[0].match(/^\d/gi); - let sensorsList = []; - const axiosInstance = axios.create(); - const getButtons = async () => { - await auth.jwtAuth(axiosInstance, message); - return axiosInstance - .get(`${process.env.URL_API}/devices/${deviceID}/sensors`) - .then((res) => { - const sensors = res.data; - sensors.forEach((sensor) => { - sensorsList.push( - Markup.callbackButton( - `${deviceID}_${sensor.sensorId}_${sensor.type}`, - sensor.type - ) - ); - }); - }); - }; - getButtons(message).then(() => { - console.log("Lista sensori caricata correttamente"); + // user has selected to switch off one sensor + bot.hears(/^\d{1,2}(_)+\d{1,2}(_)(Disattiva)/g, (message) => { + const devSensID = message.match[0].match(/\d/gi); + Markup.removeKeyboard(); + message.reply( + `Il sensore @${devSensID[1]} del dispositivo @${devSensID[0]} è stato disattivato con successo!` + ); + }); + // user has selected one sensor + bot.hears(/^\d{1,2}(_)+\d{1,2}(_)(.*)/g, (message) => { + const sensorID = message.match[0].match(/\d/gi); Markup.removeKeyboard(); message.reply( - "Seleziona il sensore:", - Markup.keyboard(sensorsList).oneTime().resize().extra() + "Seleziona l'opzione:", + Markup.keyboard([ + `${sensorID[0]}_${sensorID[1]}_Attiva`, + `${sensorID[0]}_${sensorID[1]}_Disattiva`, + ]) + .oneTime() + .resize() + .extra() ); - sensorsList = []; + }); + // user has selected one device + bot.hears(/^\d{1,2}(_)(.*)/g, (message) => { + const deviceID = message.match[0].match(/^\d/gi); + let sensorsList = []; + const axiosInstance = axios.create(); + const getButtons = async () => { + await auth.jwtAuth(axiosInstance, message); + return axiosInstance + .get(`${process.env.URL_API}/devices/${deviceID}/sensors`) + .then((res) => { + const sensors = res.data; + sensors.forEach((sensor) => { + sensorsList.push( + Markup.callbackButton( + `${deviceID}_${sensor.sensorId}_${sensor.type}`, + sensor.type + ) + ); + }); + }); + }; + getButtons(message).then(() => { + console.log("Lista sensori caricata correttamente"); + Markup.removeKeyboard(); + message.reply( + "Seleziona il sensore:", + Markup.keyboard(sensorsList).oneTime().resize().extra() + ); + sensorsList = []; + }); }); }); }; From 94fcf686fa4726417884b5684a0e44591cb6757d Mon Sep 17 00:00:00 2001 From: Mariano Date: Tue, 28 Apr 2020 17:38:10 +0200 Subject: [PATCH 65/71] Update devices.js --- commands/devices.js | 56 ++++++++++++++++++++++++++------------------- 1 file changed, 32 insertions(+), 24 deletions(-) diff --git a/commands/devices.js b/commands/devices.js index af74edc..a2efa06 100644 --- a/commands/devices.js +++ b/commands/devices.js @@ -27,7 +27,6 @@ const botDevices = (bot, auth) => { await axiosInstance .get(`${process.env.URL_API}/devices`) .then((res) => { - admin = true; const devices = res.data; devices.forEach((device) => { deviceList.push( @@ -37,62 +36,70 @@ const botDevices = (bot, auth) => { ) ); }); + deviceList.push(Markup.callbackButton("Annulla \u{274C}")); }); } }; - if (deviceList.length > 0) { - getDeviceList() - .then(() => { + getDeviceList() + .then(() => { + if (deviceList.length !== 0) { console.log("Lista dispositivi caricata correttamente"); - Markup.removeKeyboard(); message.reply( "Seleziona il dispositivo a cui inviare un comando:", Markup.keyboard(deviceList).oneTime().resize().extra() ); deviceList = []; - }) - .catch(() => { - message.reply( - "Errore, non hai i permessi per eseguire questa azione, oppure il servizio non è al momento disponibile." - ); - }); - } + } + }) + .catch(() => { + message.reply( + "Errore, non hai i permessi per eseguire questa azione, oppure il servizio non è al momento disponibile." + ); + }); // user has selected to switch on one sensor - bot.hears(/^\d{1,2}(_)+\d{1,2}(_)(Attiva)/g, (message) => { + bot.hears(/^\d{1,11}(_)+\d{1,11}(_)(Attiva)/g, (message) => { const devSensID = message.match[0].match(/\d/gi); - Markup.removeKeyboard(); message.reply( - `Il sensore @${devSensID[1]} del dispositivo @${devSensID[0]} è stato attivato con successo!` + `Il sensore @${devSensID[1]} del dispositivo @${devSensID[0]} è stato attivato con successo!`, + Markup.removeKeyboard().extra() ); }); // user has selected to switch off one sensor - bot.hears(/^\d{1,2}(_)+\d{1,2}(_)(Disattiva)/g, (message) => { + bot.hears(/^\d{1,11}(_)+\d{1,11}(_)(Disattiva)/g, (message) => { const devSensID = message.match[0].match(/\d/gi); - Markup.removeKeyboard(); message.reply( - `Il sensore @${devSensID[1]} del dispositivo @${devSensID[0]} è stato disattivato con successo!` + `Il sensore @${devSensID[1]} del dispositivo @${devSensID[0]} è stato disattivato con successo!`, + Markup.removeKeyboard().extra() ); }); + + // user has selected to switch off one sensor + bot.hears(/(Annulla .*)/g, (message) => { + // eslint-disable-next-line new-cap + message.reply(`Operazione annullata`, Markup.removeKeyboard().extra()); + }); + // user has selected one sensor - bot.hears(/^\d{1,2}(_)+\d{1,2}(_)(.*)/g, (message) => { + bot.hears(/^\d{1,11}(_)+\d{1,11}(_)(.*)/g, (message) => { const sensorID = message.match[0].match(/\d/gi); - Markup.removeKeyboard(); message.reply( - "Seleziona l'opzione:", + "Seleziona un input da inviare al comando:", Markup.keyboard([ `${sensorID[0]}_${sensorID[1]}_Attiva`, `${sensorID[0]}_${sensorID[1]}_Disattiva`, + `Annulla \u{274C}`, ]) .oneTime() .resize() .extra() ); }); + // user has selected one device - bot.hears(/^\d{1,2}(_)(.*)/g, (message) => { - const deviceID = message.match[0].match(/^\d/gi); + bot.hears(/^\d{1,11}(_)(.*)/g, (message) => { + const deviceID = message.match[0].match(/^\d{1,11}/gi); let sensorsList = []; const axiosInstance = axios.create(); const getButtons = async () => { @@ -104,11 +111,12 @@ const botDevices = (bot, auth) => { sensors.forEach((sensor) => { sensorsList.push( Markup.callbackButton( - `${deviceID}_${sensor.sensorId}_${sensor.type}`, + `${sensor.realSensorId}_${sensor.sensorId}_${sensor.type}`, sensor.type ) ); }); + sensorsList.push(Markup.callbackButton("Annulla \u{274C}")); }); }; getButtons(message).then(() => { From 3641dbde21ea954c844de43b3600858809e2f697 Mon Sep 17 00:00:00 2001 From: Mariano Date: Tue, 28 Apr 2020 17:38:58 +0200 Subject: [PATCH 66/71] Update devices.js --- commands/devices.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/commands/devices.js b/commands/devices.js index a2efa06..f6331f8 100644 --- a/commands/devices.js +++ b/commands/devices.js @@ -111,7 +111,7 @@ const botDevices = (bot, auth) => { sensors.forEach((sensor) => { sensorsList.push( Markup.callbackButton( - `${sensor.realSensorId}_${sensor.sensorId}_${sensor.type}`, + `${deviceID}_${sensor.sensorId}_${sensor.type}`, sensor.type ) ); From 4d652328d5d436a22195e0d56b68b1fffe19b29d Mon Sep 17 00:00:00 2001 From: Mariano Date: Tue, 28 Apr 2020 18:46:04 +0200 Subject: [PATCH 67/71] Update devices.js --- commands/devices.js | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/commands/devices.js b/commands/devices.js index f6331f8..3b5daed 100644 --- a/commands/devices.js +++ b/commands/devices.js @@ -31,7 +31,7 @@ const botDevices = (bot, auth) => { devices.forEach((device) => { deviceList.push( Markup.callbackButton( - `${device.deviceId}_${device.name}`, + `${device.name}-D#${device.deviceId}`, device.name ) ); @@ -59,18 +59,21 @@ const botDevices = (bot, auth) => { }); // user has selected to switch on one sensor - bot.hears(/^\d{1,11}(_)+\d{1,11}(_)(Attiva)/g, (message) => { - const devSensID = message.match[0].match(/\d/gi); + bot.hears(/^(.*)(Attiva)(_)(D#\d{1,11})(-)(S#\d{1,11})/g, (message) => { + const deviceID = message.match[0].match(/(\d{1,11})/gi)[0]; + const sensorID = message.match[0].match(/(\d{1,11})$/gi); + message.reply( - `Il sensore @${devSensID[1]} del dispositivo @${devSensID[0]} è stato attivato con successo!`, + `\u{2705} Hai richiesto l'attivazione del sensore ${sensorID} del dispositivo ${deviceID}`, Markup.removeKeyboard().extra() ); }); // user has selected to switch off one sensor - bot.hears(/^\d{1,11}(_)+\d{1,11}(_)(Disattiva)/g, (message) => { - const devSensID = message.match[0].match(/\d/gi); + bot.hears(/^(.*)(Disattiva)(_)(D#\d{1,11})(-)(S#\d{1,11})/g, (message) => { + const deviceID = message.match[0].match(/(\d{1,11})/gi)[0]; + const sensorID = message.match[0].match(/(\d{1,11})$/gi); message.reply( - `Il sensore @${devSensID[1]} del dispositivo @${devSensID[0]} è stato disattivato con successo!`, + `\u{2705} Hai richiesto la disattivazione del sensore ${sensorID} del dispositivo ${deviceID}`, Markup.removeKeyboard().extra() ); }); @@ -82,13 +85,13 @@ const botDevices = (bot, auth) => { }); // user has selected one sensor - bot.hears(/^\d{1,11}(_)+\d{1,11}(_)(.*)/g, (message) => { - const sensorID = message.match[0].match(/\d/gi); + bot.hears(/^(.*)(-)(D#\d{1,11})(-)(S#\d{1,11})/g, (message) => { + const deviceSensorID = message.match[0].match(/(#\d{1,11})/gi); message.reply( "Seleziona un input da inviare al comando:", Markup.keyboard([ - `${sensorID[0]}_${sensorID[1]}_Attiva`, - `${sensorID[0]}_${sensorID[1]}_Disattiva`, + `\u{1F7E2} Attiva_D${deviceSensorID[0]}-S${deviceSensorID[1]}`, + `\u{1F534} Disattiva_D${deviceSensorID[0]}-S${deviceSensorID[1]}`, `Annulla \u{274C}`, ]) .oneTime() @@ -98,8 +101,8 @@ const botDevices = (bot, auth) => { }); // user has selected one device - bot.hears(/^\d{1,11}(_)(.*)/g, (message) => { - const deviceID = message.match[0].match(/^\d{1,11}/gi); + bot.hears(/^(.*)(-)(D#\d{1,11})/g, (message) => { + const deviceID = message.match[0].match(/(\d{1,11})$/g); let sensorsList = []; const axiosInstance = axios.create(); const getButtons = async () => { @@ -111,7 +114,7 @@ const botDevices = (bot, auth) => { sensors.forEach((sensor) => { sensorsList.push( Markup.callbackButton( - `${deviceID}_${sensor.sensorId}_${sensor.type}`, + `${sensor.type}-D#${deviceID}-S#${sensor.sensorId}`, sensor.type ) ); From 7da4b5d2fce775f9d8fbabe659ab6fbc60c7ea15 Mon Sep 17 00:00:00 2001 From: Mariano Date: Wed, 29 Apr 2020 13:20:48 +0200 Subject: [PATCH 68/71] Update devices.js --- commands/devices.js | 106 +++++++++++++++++++++++++------------------- 1 file changed, 61 insertions(+), 45 deletions(-) diff --git a/commands/devices.js b/commands/devices.js index 3b5daed..24d7bfd 100644 --- a/commands/devices.js +++ b/commands/devices.js @@ -25,7 +25,7 @@ const botDevices = (bot, auth) => { }); if (admin) { await axiosInstance - .get(`${process.env.URL_API}/devices`) + .get(`${process.env.URL_API}/devices?cmdEnabled=true`) .then((res) => { const devices = res.data; devices.forEach((device) => { @@ -58,57 +58,17 @@ const botDevices = (bot, auth) => { ); }); - // user has selected to switch on one sensor - bot.hears(/^(.*)(Attiva)(_)(D#\d{1,11})(-)(S#\d{1,11})/g, (message) => { - const deviceID = message.match[0].match(/(\d{1,11})/gi)[0]; - const sensorID = message.match[0].match(/(\d{1,11})$/gi); - - message.reply( - `\u{2705} Hai richiesto l'attivazione del sensore ${sensorID} del dispositivo ${deviceID}`, - Markup.removeKeyboard().extra() - ); - }); - // user has selected to switch off one sensor - bot.hears(/^(.*)(Disattiva)(_)(D#\d{1,11})(-)(S#\d{1,11})/g, (message) => { - const deviceID = message.match[0].match(/(\d{1,11})/gi)[0]; - const sensorID = message.match[0].match(/(\d{1,11})$/gi); - message.reply( - `\u{2705} Hai richiesto la disattivazione del sensore ${sensorID} del dispositivo ${deviceID}`, - Markup.removeKeyboard().extra() - ); - }); - - // user has selected to switch off one sensor - bot.hears(/(Annulla .*)/g, (message) => { - // eslint-disable-next-line new-cap - message.reply(`Operazione annullata`, Markup.removeKeyboard().extra()); - }); - - // user has selected one sensor - bot.hears(/^(.*)(-)(D#\d{1,11})(-)(S#\d{1,11})/g, (message) => { - const deviceSensorID = message.match[0].match(/(#\d{1,11})/gi); - message.reply( - "Seleziona un input da inviare al comando:", - Markup.keyboard([ - `\u{1F7E2} Attiva_D${deviceSensorID[0]}-S${deviceSensorID[1]}`, - `\u{1F534} Disattiva_D${deviceSensorID[0]}-S${deviceSensorID[1]}`, - `Annulla \u{274C}`, - ]) - .oneTime() - .resize() - .extra() - ); - }); - // user has selected one device - bot.hears(/^(.*)(-)(D#\d{1,11})/g, (message) => { + bot.hears(/^(.*)(-)(D#\d{1,11})$/g, (message) => { const deviceID = message.match[0].match(/(\d{1,11})$/g); let sensorsList = []; const axiosInstance = axios.create(); const getButtons = async () => { await auth.jwtAuth(axiosInstance, message); return axiosInstance - .get(`${process.env.URL_API}/devices/${deviceID}/sensors`) + .get( + `${process.env.URL_API}/devices/${deviceID}/sensors?cmdEnabled=true` + ) .then((res) => { const sensors = res.data; sensors.forEach((sensor) => { @@ -132,6 +92,62 @@ const botDevices = (bot, auth) => { sensorsList = []; }); }); + + // user has selected one sensor + bot.hears(/^(.*)(-)(D#\d{1,11})(-)(S#\d{1,11})$/g, (message) => { + const deviceSensorID = message.match[0].match(/(#\d{1,11})/gi); + message.reply( + "Seleziona un input da inviare al comando:", + Markup.keyboard([ + `\u{1F7E2} Attiva_D${deviceSensorID[0]}-S${deviceSensorID[1]}`, + `\u{1F534} Disattiva_D${deviceSensorID[0]}-S${deviceSensorID[1]}`, + `Annulla \u{274C}`, + ]) + .oneTime() + .resize() + .extra() + ); + }); + // user has selected to switch on one sensor + bot.hears( + /^(.*)(Attiva|Disattiva)(_)(D#\d{1,11})(-)(S#\d{1,11})$/g, + (message) => { + const action = message.match[0].match(/(Attiva|Disattiva)/g)[0]; + const deviceID = message.match[0].match(/(\d{1,11})/gi)[0]; + const sensorID = message.match[0].match(/(\d{1,11})$/gi); + const axiosInstance = axios.create(); + const sendCommandToAPI = async (realCommand) => { + await auth.jwtAuth(axiosInstance, message); + await axiosInstance + .put(`${process.env.URL_API}/sensors/${sensorID}`, { + data: realCommand, + }) + .then((res) => { + console.log(res); + }) + .catch((err) => { + console.log(err); + }); + }; + switch (action) { + case "Attiva": + sendCommandToAPI(1); + case "Disattiva": + sendCommandToAPI(0); + } + message.reply( + `\u{2705} Hai richiesto ${ + action === "Attiva" ? "l'attivazione" : "la disattivazione" + } del sensore #${sensorID} del dispositivo #${deviceID}`, + Markup.removeKeyboard().extra() + ); + } + ); + + // user has selected to switch off one sensor + bot.hears(/(Annulla .*)/g, (message) => { + message.reply(`Operazione annullata`, Markup.removeKeyboard().extra()); + }); }); }; module.exports.botDevices = botDevices; From 6ccbfc4b2605586365e9ed6feec58ac73a239ca8 Mon Sep 17 00:00:00 2001 From: Mariano Date: Thu, 30 Apr 2020 10:46:53 +0200 Subject: [PATCH 69/71] Update devices.js --- commands/devices.js | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/commands/devices.js b/commands/devices.js index 24d7bfd..a17b24f 100644 --- a/commands/devices.js +++ b/commands/devices.js @@ -44,7 +44,6 @@ const botDevices = (bot, auth) => { getDeviceList() .then(() => { if (deviceList.length !== 0) { - console.log("Lista dispositivi caricata correttamente"); message.reply( "Seleziona il dispositivo a cui inviare un comando:", Markup.keyboard(deviceList).oneTime().resize().extra() @@ -83,7 +82,6 @@ const botDevices = (bot, auth) => { }); }; getButtons(message).then(() => { - console.log("Lista sensori caricata correttamente"); Markup.removeKeyboard(); message.reply( "Seleziona il sensore:", @@ -123,24 +121,27 @@ const botDevices = (bot, auth) => { data: realCommand, }) .then((res) => { - console.log(res); + message.reply( + `\u{2705} Hai richiesto ${ + action === "Attiva" ? "l'attivazione" : "la disattivazione" + } del sensore #${sensorID} del dispositivo #${deviceID}`, + Markup.removeKeyboard().extra() + ); }) .catch((err) => { - console.log(err); + message.reply( + `[Errore] La richiesta *non* è andata a buon fine. La configurazione potrebbe essere cambiata. Riprova.`, + Markup.removeKeyboard().extra()); }); }; switch (action) { case "Attiva": sendCommandToAPI(1); + break; case "Disattiva": sendCommandToAPI(0); + break; } - message.reply( - `\u{2705} Hai richiesto ${ - action === "Attiva" ? "l'attivazione" : "la disattivazione" - } del sensore #${sensorID} del dispositivo #${deviceID}`, - Markup.removeKeyboard().extra() - ); } ); From 401edb88f06e4bce63df740eeae7e50c2dcb23eb Mon Sep 17 00:00:00 2001 From: Mariano Date: Thu, 30 Apr 2020 11:05:59 +0200 Subject: [PATCH 70/71] Rimosso message come argomento di getButtons() --- .eslintrc.json | 2 -- commands/devices.js | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/.eslintrc.json b/.eslintrc.json index be7a17c..cfa0571 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -1,6 +1,4 @@ { - - "env": { "node": true, "es6": true, diff --git a/commands/devices.js b/commands/devices.js index a17b24f..2c945cc 100644 --- a/commands/devices.js +++ b/commands/devices.js @@ -81,7 +81,7 @@ const botDevices = (bot, auth) => { sensorsList.push(Markup.callbackButton("Annulla \u{274C}")); }); }; - getButtons(message).then(() => { + getButtons().then(() => { Markup.removeKeyboard(); message.reply( "Seleziona il sensore:", From 29b0b27afb3e2f22bc85deb6bc20944a6f399f92 Mon Sep 17 00:00:00 2001 From: Mariano Sciacco <34033090+Maxelweb@users.noreply.github.com> Date: Wed, 6 May 2020 20:38:47 +0200 Subject: [PATCH 71/71] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a92f34a..7c188fd 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ # Telegram Bot - ThiReMa -:fire: Versione componente: `v0.1.0-dev` +:fire: Versione componente: `v0.2.0-rc` :pushpin: Main repo: [swe-thirema](https://github.com/Maxelweb/swe-thirema)