Skip to content
This repository has been archived by the owner on Jul 1, 2020. It is now read-only.

Commit

Permalink
Merge pull request #36 from RedRoundRobin/develop
Browse files Browse the repository at this point in the history
Baseline 0.17
  • Loading branch information
Maxelweb committed May 6, 2020
2 parents 0de4083 + 29b0b27 commit 37f57bf
Show file tree
Hide file tree
Showing 20 changed files with 517 additions and 172 deletions.
3 changes: 3 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
BOT_TOKEN=1120382460:AAGy8CdhjdMxaS99K3za1Jxoqp-ayPuVC1w
URL_API=http://core.host.redroundrobin.site:9999
SERVER_PORT=3000
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.js text eol=lf
9 changes: 1 addition & 8 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,17 +1,10 @@
node_modules
.DS_Store
.env

.idea
target/
out/
coverage/
*.iws
*.iml
*.ipr

Icon

Icon

.env
Icon
6 changes: 6 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -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 3000
WORKDIR /usr/src/telegram
CMD ["sh", "start.sh"]
17 changes: 16 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -34,3 +34,18 @@
- entrare nella cartella con il terminale
- $ npm install
- $ node bot


#### 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`
34 changes: 29 additions & 5 deletions __tests__/bot.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,31 @@
// NON RIMUOVERE LA RIGA SOTTOSTANTE //
require("../main");
// test bot
const { botStart } = require("../commands/start");
const { botInfo } = require("../commands/info");
const { botLogin } = require("../commands/login");
const { botHelp } = require("../commands/help");

test("Extracts value from JSON formatted string", () => {
const num = 4;
expect(num).toBe(4);
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 info", () => {
expect(botInfo(bot)).toBe(undefined);
});
// START
test("Check status", () => {
expect(botStart(bot)).toBe(undefined);
});
// INFO
test("Check help", () => {
expect(botHelp(bot)).toBe(undefined);
});
// const s = {"botLaunch": [Function botLaunch]`;
// const t = JSON.parse(s);
// test("Check launch", () => {
// expect(botLaunch).toBe(t);
// });
46 changes: 46 additions & 0 deletions __tests__/server.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
const { sendMessage, checkChatId } = require("../utils/server");

test("Send message to invalid chat id", () => {
const message = "test";
const chatId = "aaaaa";
try {
sendMessage(message, chatId);
} catch (e) {
expect(e.message).toBe("Errore 400 nell'invio del messaggio");
}
});

test("Send message to valid chat id", () => {
const message = "test";
const chatId = "192645345";
try {
sendMessage(message, chatId);
expect(message).toBe("test");
} catch (e) {
console.log("Errore nell'invio del messaggio");
}
});

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);
});

// 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", () => {
expect(checkChatId(chatId)).toBe(true);
});

// const req = { metod: "POST", reqType: "authentication" };
// test("Check authentication request", () => {
// expect(botServer.toString()).toBe("[object Object]");
// });
154 changes: 154 additions & 0 deletions commands/devices.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
const axios = require("axios");
const Markup = require("telegraf/markup");

const botDevices = (bot, auth) => {
bot.command("devices", (message) => {
const username = message.from.username;
const axiosInstance = axios.create();
let admin = false;
let deviceList = [];
const getDeviceList = async () => {
await auth.jwtAuth(axiosInstance, message);
await axiosInstance
.get(`${process.env.URL_API}/users?telegramName=${username}`)
.then((res) => {
const data = res.data[0];
const typeNumber = data.type;
if (typeNumber === 2) {
admin = true;
} else {
admin = false;
return message.reply(
"Devi essere amministratore per vedere la lista dispositivi"
);
}
});
if (admin) {
await axiosInstance
.get(`${process.env.URL_API}/devices?cmdEnabled=true`)
.then((res) => {
const devices = res.data;
devices.forEach((device) => {
deviceList.push(
Markup.callbackButton(
`${device.name}-D#${device.deviceId}`,
device.name
)
);
});
deviceList.push(Markup.callbackButton("Annulla \u{274C}"));
});
}
};

getDeviceList()
.then(() => {
if (deviceList.length !== 0) {
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."
);
});

// user has selected one device
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?cmdEnabled=true`
)
.then((res) => {
const sensors = res.data;
sensors.forEach((sensor) => {
sensorsList.push(
Markup.callbackButton(
`${sensor.type}-D#${deviceID}-S#${sensor.sensorId}`,
sensor.type
)
);
});
sensorsList.push(Markup.callbackButton("Annulla \u{274C}"));
});
};
getButtons().then(() => {
Markup.removeKeyboard();
message.reply(
"Seleziona il sensore:",
Markup.keyboard(sensorsList).oneTime().resize().extra()
);
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) => {
message.reply(
`\u{2705} Hai richiesto ${
action === "Attiva" ? "l'attivazione" : "la disattivazione"
} del sensore #${sensorID} del dispositivo #${deviceID}`,
Markup.removeKeyboard().extra()
);
})
.catch((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;
}
}
);

// user has selected to switch off one sensor
bot.hears(/(Annulla .*)/g, (message) => {
message.reply(`Operazione annullata`, Markup.removeKeyboard().extra());
});
});
};
module.exports.botDevices = botDevices;
25 changes: 25 additions & 0 deletions commands/help.js
Original file line number Diff line number Diff line change
@@ -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;
49 changes: 39 additions & 10 deletions commands/info.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,40 @@
const botInfo = (bot) => {
bot.command("info", ({ replyWithMarkdown }) =>
replyWithMarkdown(`
Ecco la lista dei comandi disponibili:
- Login: /login
- Status: /status
- Info: /info`
)
);
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(axiosInstance, message);
return await axiosInstance
.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;
module.exports.botInfo = botInfo;
4 changes: 0 additions & 4 deletions commands/launch.js

This file was deleted.

Loading

0 comments on commit 37f57bf

Please sign in to comment.