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 #34 from RedRoundRobin/feature/comandiBot
Browse files Browse the repository at this point in the history
Feature/comandi bot
  • Loading branch information
Maxelweb committed Apr 30, 2020
2 parents 7a40917 + 6ccbfc4 commit 05580ad
Show file tree
Hide file tree
Showing 10 changed files with 278 additions and 122 deletions.
10 changes: 5 additions & 5 deletions __tests__/bot.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
const { botStart } = require("../commands/start");
const { botInfo } = require("../commands/info");
const { botLogin } = require("../commands/login");
const { botStatus } = require("../commands/status");
const { botHelp } = require("../commands/help");

const Telegraf = require("telegraf");
const tokenBot = process.env.BOT_TOKEN;
Expand All @@ -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);
Expand Down
161 changes: 148 additions & 13 deletions commands/devices.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,154 @@
const botDevices = (bot) => {
const axios = require("axios");
const Markup = require("telegraf/markup");

const botDevices = (bot, auth) => {
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 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}"));
});
}
};
bot.telegram
.sendMessage(message.chat.id, "esempio bottoni", options)
.then(function (sended) {
// `sended` is the sent message.

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(message).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;
48 changes: 37 additions & 11 deletions commands/info.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,40 @@
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 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;
40 changes: 3 additions & 37 deletions commands/login.js
Original file line number Diff line number Diff line change
@@ -1,43 +1,9 @@
require("dotenv").config();
const axios = require("axios");

const botLogin = (bot) => {
const botLogin = (bot, 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");
}
});
const axiosInstance = axios.create();
auth.jwtAuth(axiosInstance, message, true);
});
};
module.exports.botLogin = botLogin;
2 changes: 1 addition & 1 deletion commands/start.js
Original file line number Diff line number Diff line change
Expand Up @@ -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`);
});
};

Expand Down
41 changes: 0 additions & 41 deletions commands/status.js

This file was deleted.

Loading

0 comments on commit 05580ad

Please sign in to comment.