Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New new weather widget and telegram bot #2

Open
wants to merge 34 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
fdc27ad
[ADD] widget structure]
ric98esley Dec 23, 2022
f99a535
[FIX] Environment Variables in nuxt.config
ric98esley Dec 23, 2022
040b6b5
[ADD] City Info Detail This component will show the city data from th…
ric98esley Dec 24, 2022
8535d42
[ADD] City info Main
ric98esley Dec 25, 2022
2e0b8f4
[UPDATE] Weather widget
ric98esley Dec 26, 2022
0830154
[UPDATE] Simple Widget Create and working
ric98esley Dec 27, 2022
f9db381
[TEST] adding geolocation by api
ric98esley Dec 27, 2022
f4e3d91
[UPDATE] Weather widget working with geocoding api
ric98esley Dec 28, 2022
732777b
[UPDATE] Widget Weather, add styles
ric98esley Dec 28, 2022
6f712f9
[ADD] Conection with mqtt
ric98esley Dec 29, 2022
0157806
[UPDATE] Styles, template and logid bt weather widget
ric98esley Dec 29, 2022
8a89be7
[UPDATE] add perfect scroll bar
ric98esley Dec 30, 2022
cb1e005
[ADD] Widget on dashboard
ric98esley Jan 4, 2023
7e5f70b
[ADD and Fix] add Function to edit and fix some weather widget issus
ric98esley Jan 5, 2023
3c0f67d
[REFACTOR] Template view for edit
ric98esley Jan 6, 2023
b3e1463
[UPDATE] Edit working, there is bug with add widget
ric98esley Jan 7, 2023
69d4bd2
[FIX] Bug with edit button
ric98esley Jan 8, 2023
a911e28
[UPDATE] Api by update template
ric98esley Jan 10, 2023
4d57eb9
[ADD] update template button working
ric98esley Jan 11, 2023
836acb1
[UPDATE] the widgets now can move with buttons
ric98esley Jan 12, 2023
79d223e
[UPDATE] edite template working full
ric98esley Jan 13, 2023
69212d9
Merge pull request #1 from XavierSVO/edit-dashboard
ric98esley Jan 19, 2023
6b2d8c7
[add] call to telegram api from backend
ric98esley Feb 8, 2023
f1565db
[ADD] call to telegram with time set from resourses
ric98esley Feb 9, 2023
4a7bd3c
[ADD] alarm resouce with telegram ID
ric98esley Feb 10, 2023
f93c4dc
[Fix] telegram id of null
ric98esley Feb 11, 2023
fef7aba
Merge pull request #2 from XavierSVO/telegram-bot
ric98esley Feb 11, 2023
d6fa000
[ADD] check for telegram
ric98esley Feb 14, 2023
380d5ff
[ADD] telegra bot commands and ngrok for dev enviroment
ric98esley Feb 15, 2023
7e760f6
[UPDATE] telegram by Model user
ric98esley Feb 15, 2023
1e8ed12
[ADD] profile view
ric98esley Feb 16, 2023
12ec2ae
[BUG] model user can't valite maxlenght
ric98esley Feb 17, 2023
18efa0c
[UPDATE] Alarm model, tigger time telegram, alarm webhook check if te…
ric98esley Feb 18, 2023
5fbadcb
Merge pull request #3 from XavierSVO/telegram-bot
ric98esley Feb 20, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
environment=dev

# A P I - N O D E
API_PORT=3001
WEBHOOKS_HOST=localhost


# M O N G O
MONGO_USERNAME=admin
MONGO_PASSWORD=123456
MONGO_HOST=localhost
MONGO_PORT=27017
MONGO_DATABASE=god_level

EMQX_DEFAULT_APPLICATION_SECRET=emqxsecrets
EMQX_NODE_SUPERUSER_USER=superuser
EMQX_NODE_SUPERUSER_PASSWORD=superuser
EMQX_API_HOST=localhost
EMQX_API_TOKEN=121212
EMQX_RESOURCES_DELAY=1000


# F R O N T
APP_PORT=3000
AXIOS_BASE_URL=http://127.0.0.1:3001/api
MQTT_PORT=8083
MQTT_HOST=localhost
MQTT_PREFIX=ws://

# W E A T H E R

WEATHER_API_KEY='YOUR_API_KEY_HERE'


# T E L E G R A M

TELEGRAM_API_KEY='your bot api here'
TELEGRAM_API_PORT='the on listen telegram'
45 changes: 45 additions & 0 deletions api/bot/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
const express = require('express');
const ngrok = require('ngrok');
const { Telegraf } = require('telegraf');

const app3 = express();


const bot = new Telegraf(`${process.env.TELEGRAM_API_KEY}`);

// Comprueba si estamos en un entorno de desarrollo
if (process.env.environment === 'dev') {

// Crea un túnel ngrok al puerto 8443
(async function() {
try {
const url = await ngrok.connect(process.env.TELEGRAM_API_PORT);
bot.telegram.setWebhook(`${url}/${process.env.TELEGRAM_API_KEY}`);

} catch (error) {

}
})();
} else if (process.env.environment === 'prod') {
// Usa una URL fija como webhook para tu bot de Telegram
bot.telegram.setWebhook(`https://${process.env.WEBHOOKS_HOST}:${process.env.TELEGRAM_API_PORT}/${process.env.TELEGRAM_API_KEY}`);
}

// Inicia el servidor en el puerto 8443
app3.listen(8443, () => {
console.log(`Servidor iniciado en el puerto ${process.env.TELEGRAM_API_PORT}`);
});


bot.start((ctx) => {
ctx.reply('¡Hola! Envía /miid para recibir tu ID de chat.');
});

bot.command('miid', (ctx) => {
const chatId = ctx.chat.id;
ctx.reply(`Tu ID de chat es: ${chatId}`);
});

bot.launch();

module.exports = bot;
5 changes: 5 additions & 0 deletions api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,12 @@ app.use("/api", require("./routes/dataprovider.js"));

module.exports = app;

// Importa el archivo de conexión con Telegram
const bot = require('./bot');


//listener

app.listen(process.env.API_PORT, () => {
console.log("API server listening on port " + process.env.API_PORT);
});
Expand Down
4 changes: 3 additions & 1 deletion api/models/emqx_alarm_rule.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ const alarmRuleSchema = new Schema({
triggerTime: { type: Number },
status: { type: Boolean },
counter: { type: Number, default: 0},
createdTime: {type: Number}
createdTime: {type: Number},
telegramID: {type: Number},
triggerTimeTelegram: {type: Number},
});


Expand Down
6 changes: 4 additions & 2 deletions api/models/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ const Schema = mongoose.Schema;
const userSchema = new Schema({
name: { type: String, required: [true] },
email: { type: String, required: [true], unique: true},
password: { type: String, required: [true]},
password: { type: String, required: [true]},
telegramID: { type: String, maxlength: 10 }
});


//Validator
//Validators

userSchema.plugin(uniqueValidator, { message: 'Error, email already exists.'});


Expand Down
7 changes: 5 additions & 2 deletions api/routes/alarms.js
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,9 @@ async function createAlarmRule(newAlarm) {
value: newAlarm.value,
condition: newAlarm.condition,
triggerTime: newAlarm.triggerTime,
createTime: Date.now()
triggerTimeTelegram: newAlarm.triggerTimeTelegram,
createTime: Date.now(),
telegramID: newAlarm.telegramID
});

const url = "http://"+process.env.EMQX_API_HOST+":8085/api/v4/rules/" + mongoRule.emqxRuleId;
Expand All @@ -183,7 +185,8 @@ async function createAlarmRule(newAlarm) {
newAlarm.variableFullName +
'","triggerTime":' +
newAlarm.triggerTime +
"}";
`${(!newAlarm.telegramID) ? "": `, "telegramID": ${newAlarm.telegramID}`}` +
`${(!newAlarm.triggerTimeTelegram) ? "}": `, "triggerTimeTelegram": ${newAlarm.triggerTimeTelegram} }`}`;

newRule.actions[0].params.payload_tmpl = payload_templ;

Expand Down
196 changes: 105 additions & 91 deletions api/routes/templates.js
Original file line number Diff line number Diff line change
@@ -1,122 +1,136 @@
const express = require('express');
const express = require("express");
const router = express.Router();
const { checkAuth } = require('../middlewares/authentication.js');
const { checkAuth } = require("../middlewares/authentication.js");

//models import
import Template from '../models/template.js';
import Device from '../models/device.js';
import Template from "../models/template.js";
import Device from "../models/device.js";

//get templates
router.get('/template', checkAuth, async (req, res) => {
router.get("/template", checkAuth, async (req, res) => {
try {
const userId = req.userData._id;

try {
const templates = await Template.find({ userId: userId });

const userId = req.userData._id;
const response = {
status: "success",
data: templates
};

const templates = await Template.find({userId: userId});
return res.json(response);
} catch (error) {
console.log(error);

console.log(userId);
console.log(templates)

const response = {
status: "success",
data: templates
}

return res.json(response);

} catch (error) {

console.log(error);

const response = {
status: "error",
error: error
}

return res.status(500).json(response);

}
const response = {
status: "error",
error: error
};

return res.status(500).json(response);
}
});

//create template
router.post('/template', checkAuth, async (req, res) => {

try {

const userId = req.userData._id;

var newTemplate = req.body.template;
router.post("/template", checkAuth, async (req, res) => {
try {
const userId = req.userData._id;

newTemplate.userId = userId;
newTemplate.createdTime = Date.now();
var newTemplate = req.body.template;

const r = await Template.create(newTemplate);
newTemplate.userId = userId;
newTemplate.createdTime = Date.now();

const response = {
status: "success",
}
const r = await Template.create(newTemplate);

return res.json(response)
const response = {
status: "success"
};

} catch (error) {
return res.json(response);
} catch (error) {
console.log(error);

console.log(error);

const response = {
status: "error",
error: error
}

return res.status(500).json(response);

}
const response = {
status: "error",
error: error
};

return res.status(500).json(response);
}
});

//delete template
router.delete('/template', checkAuth, async (req, res) => {

try {

const userId = req.userData._id;
const templateId = req.query.templateId;

const devices = await Device.find({userId: userId, templateId: templateId });


if (devices.length > 0){

const response = {
status: "fail",
error: "template in use"
}

return res.json(response);
}

const r = await Template.deleteOne({userId: userId, _id: templateId});

const response = {
status: "success",
}

return res.json(response)
router.delete("/template", checkAuth, async (req, res) => {
try {
const userId = req.userData._id;
const templateId = req.query.templateId;

const devices = await Device.find({
userId: userId,
templateId: templateId
});

if (devices.length > 0) {
const response = {
status: "fail",
error: "template in use"
};

return res.json(response);
}

} catch (error) {
const r = await Template.deleteOne({ userId: userId, _id: templateId });

console.log(error);
const response = {
status: "success"
};

const response = {
status: "error",
error: error
}
return res.json(response);
} catch (error) {
console.log(error);

return res.status(500).json(response);
const response = {
status: "error",
error: error
};

}
return res.status(500).json(response);
}
});

// Modifica un documento en la colección "Template"
router.put("/template", checkAuth, async (req, res) => {
try {
const userId = req.userData._id;
const templateId = req.query.templateId;
const update = req.body;

console.log(userId);
console.log(templateId);
console.log(update);

// Utiliza el método "updateOne()" para modificar el documento
const r = await Template.updateOne(
{ userId: userId, _id: templateId },
update
);

const response = {
status: "success"
};

return res.json(response);
} catch (error) {
console.log(error);

const response = {
status: "error",
error: error
};

return res.status(500).json(response);
}
});

module.exports = router;
module.exports = router;
Loading