Skip to content

Instantly share code, notes, and snippets.

@rfdez
Last active September 29, 2023 17:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rfdez/b03bfcfaf510a6355cb79b99617def32 to your computer and use it in GitHub Desktop.
Save rfdez/b03bfcfaf510a6355cb79b99617def32 to your computer and use it in GitHub Desktop.
Electricity Notification n8n Workflow
{
"name": "Electricity Notification",
"nodes": [
{
"parameters": {
"rule": {
"interval": [
{
"triggerAtHour": 21
}
]
}
},
"id": "6a27d3e8-2a4f-4b3f-bc26-8a3ec821ede5",
"name": "Schedule Trigger",
"type": "n8n-nodes-base.scheduleTrigger",
"typeVersion": 1,
"position": [
-20,
340
]
},
{
"parameters": {
"url": "https://api.esios.ree.es/indicators/1001",
"authentication": "genericCredentialType",
"genericAuthType": "httpHeaderAuth",
"sendQuery": true,
"queryParameters": {
"parameters": [
{
"name": "start_date",
"value": "={{ DateTime.fromISO($json.timestamp).plus({days: 1}).startOf(\"day\").toISO() }}"
},
{
"name": "end_date",
"value": "={{ DateTime.fromISO($json.timestamp).plus({days: 1}).endOf(\"day\").toISO() }}"
},
{
"name": "time_trunc",
"value": "hour"
},
{
"name": "geo_ids[]",
"value": "8741"
}
]
},
"sendHeaders": true,
"headerParameters": {
"parameters": [
{
"name": "Accept",
"value": "application/json; application/vnd.esios-api-v2+json"
},
{
"name": "Content-Type",
"value": "application/json"
}
]
},
"options": {}
},
"id": "c6f5c6d7-41fc-40a9-ad61-3adf354f51ea",
"name": "HTTP Request",
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 3,
"position": [
220,
340
],
"retryOnFail": true,
"waitBetweenTries": 5000,
"credentials": {
"httpHeaderAuth": {
"id": "11",
"name": "API ESIOS REE"
}
}
},
{
"parameters": {
"fieldToSplitOut": "indicator.values",
"options": {}
},
"id": "39ee3fb2-0a51-4e79-897c-63db9aa45da1",
"name": "Split",
"type": "n8n-nodes-base.itemLists",
"typeVersion": 1,
"position": [
460,
340
]
},
{
"parameters": {
"userKey": "id del usuario de pushover",
"message": "=Para mañana, las mejores horas para poner un electrodoméstico es entre las {{ DateTime.fromISO($json.hours.first()).format(\"HH:mm\") }} y las {{ DateTime.fromISO($json.hours.last()).format(\"HH:mm\") }}.\n\nEl precio medio de la electricidad para esas horas será {{ Number($json['average']).toFixed(2) }} €/MWh.",
"priority": 0,
"additionalFields": {
"sound": "risa_ignatius",
"timestamp": "={{ $today.set({hour: 21}).toMillis() }}",
"title": "Hacer uso de la electricidad."
}
},
"id": "944287eb-9e15-470e-bf18-7ee7ad030940",
"name": "Pushover",
"type": "n8n-nodes-base.pushover",
"typeVersion": 1,
"position": [
1560,
340
],
"credentials": {
"pushoverApi": {
"id": "2",
"name": "Pushover account"
}
}
},
{
"parameters": {
"operation": "sort",
"sortFieldsUi": {
"sortField": [
{
"fieldName": "average"
}
]
},
"options": {}
},
"id": "37a2faa5-d931-4509-a2b5-802739e7646a",
"name": "Sort by average",
"type": "n8n-nodes-base.itemLists",
"typeVersion": 2.2,
"position": [
1120,
340
]
},
{
"parameters": {
"operation": "sort",
"sortFieldsUi": {
"sortField": [
{
"fieldName": "datetime"
}
]
},
"options": {}
},
"id": "0af242bf-b14c-4b27-8d45-cd6a4acc6885",
"name": "Sort by date",
"type": "n8n-nodes-base.itemLists",
"typeVersion": 1,
"position": [
680,
340
]
},
{
"parameters": {
"jsCode": "const AGGREGATED_HOURS_COUNT = 3\n\nconst result = []\n\nfor (const [index, price] of $input.all().entries()) {\n if (index + AGGREGATED_HOURS_COUNT > $input.all().length) {\n break\n }\n\n let sum = price.json.value\n const hours = [price.json.datetime]\n for (let i = 1; i < AGGREGATED_HOURS_COUNT; i++) {\n sum += $input.all()[index + i].json.value\n hours.push($input.all()[index + i].json.datetime)\n }\n\n const avg = sum / AGGREGATED_HOURS_COUNT\n \n result.push({\n hours,\n average: avg\n })\n}\n\nreturn result"
},
"id": "d6f6bd85-cdf1-41ad-9dd3-5113b070d7d6",
"name": "Best hours",
"type": "n8n-nodes-base.code",
"typeVersion": 1,
"position": [
900,
340
]
},
{
"parameters": {
"operation": "limit"
},
"id": "f9dab715-22d7-4da7-bf6d-52f766297cb5",
"name": "First",
"type": "n8n-nodes-base.itemLists",
"typeVersion": 2.2,
"position": [
1340,
340
]
},
{
"parameters": {
"content": "## Notas\nPara conseguir el token de la Red Eléctrica de España: [REE](https://api.esios.ree.es/)\nHay otra API que no necesita token: [REData](https://www.ree.es/es/apidatos)\n\n**Importante** el workflow se ejecuta a las 21:00 ya que los precios del día siguiente los proveen a las 20 y pico.",
"height": 207.16279069767424,
"width": 486.6976744186047
},
"id": "c8e204d6-ffee-4893-9cb4-fb9346827e01",
"name": "Sticky Note",
"type": "n8n-nodes-base.stickyNote",
"typeVersion": 1,
"position": [
-40,
40
]
}
],
"pinData": {},
"connections": {
"Schedule Trigger": {
"main": [
[
{
"node": "HTTP Request",
"type": "main",
"index": 0
}
]
]
},
"Split": {
"main": [
[
{
"node": "Sort by date",
"type": "main",
"index": 0
}
]
]
},
"HTTP Request": {
"main": [
[
{
"node": "Split",
"type": "main",
"index": 0
}
]
]
},
"Sort by average": {
"main": [
[
{
"node": "First",
"type": "main",
"index": 0
}
]
]
},
"Sort by date": {
"main": [
[
{
"node": "Best hours",
"type": "main",
"index": 0
}
]
]
},
"Best hours": {
"main": [
[
{
"node": "Sort by average",
"type": "main",
"index": 0
}
]
]
},
"First": {
"main": [
[
{
"node": "Pushover",
"type": "main",
"index": 0
}
]
]
}
},
"active": true,
"settings": {
"saveManualExecutions": false,
"callerPolicy": "workflowsFromSameOwner",
"errorWorkflow": "5",
"timezone": "Europe/Madrid"
},
"versionId": "e9d79e07-9fbe-4287-80fc-96c867afe005",
"id": "t7VQNKrtOZwCim4Y",
"meta": {
"instanceId": "f1051bc6f9bea0459d8b3d624b80b4d7bee9255533aced4ed412bf70c5819685"
},
"tags": [
{
"createdAt": "2023-04-20T15:49:41.705Z",
"updatedAt": "2023-04-20T15:49:41.705Z",
"id": "3",
"name": "Saving"
}
]
}
@Lazaro000
Copy link

Lazaro000 commented Sep 9, 2023

Hola buenas,

Me da el siguiente error al ejecutar el workflow en local.

image

Estos son los parámetros que estoy usando:

image
image
image

Dónde habría que poner el token de Red Eléctrica que indicas en las notas?
Comentas que hay otra API, que no necesita token, en ese caso el endpoint sería https://apidatos.ree.es/es/indicators/1001 ???

Disculpa por mi ignorancia sobre el asunto, un saludo.

@rfdez
Copy link
Author

rfdez commented Sep 11, 2023

Buenas, @Lazaro000:

En primer lugar tendrías que solicitar un token personal, en su documentación tienes un enlace para hacerlo. Es solo enviar un correo solicitando un token.

image

Después, ese token hay que enviarlo mediante una cabecera en el nodo HTTP. Si te fijas en la siguiente imagen:

image

en este caso n8n utiliza la credencial predefinida por cabecera. En este caso esa casilla la tienes vacía, tendrías que crear esa crendencial con el token que te proporcionen.

image

La API solicita que el nombre de la cabecera de autenticación sea la de la imagen anterior (x-api-key), debajo debes poner el token.

Efectivamente, hay otra API. El endpoint sería https://apidatos.ree.es/datos/mercados/precios-mercados-tiempo-real añadiento los parámetros de fechas y demás, en su documentación tienes más detalles.

Cabe destacar que estas APIs son para mercados eléctricos de España.

Espero haberte ayudado, un saludo!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment