#!/bin/python3 import os import sys import json import psycopg2 import requests from datetime import datetime from datetime import timedelta from tzlocal import get_localzone # variables apiKey = os.environ['el_tibber_token'] apiUrl = "https://api.tibber.com/v1-beta/gql" pg_db = os.environ['el_pg_db'] pg_host = os.environ['el_pg_host'] pg_table = "tibber_consumption" startTime = datetime.now(get_localzone()) - timedelta(days = 1) startTime = startTime.isoformat('T') endTime = datetime.now(get_localzone()).isoformat('T') # Get the data try: url = apiUrl # Request headers hdr = { 'Authorization': "Bearer " + apiKey, 'Content-Type': 'application/json', } body = {"query":"""{ viewer { homes { consumption(resolution: HOURLY, last:100) { nodes { from to cost unitPrice unitPriceVAT consumption consumptionUnit } } } } }"""} response = requests.post(url, headers=hdr, json=body) if response.status_code != 200: print(response.status_code) print("Oh shit") response.raise_for_status() except Exception as e: print("oh lol") sys.exit(e) data = response.json() numdata = len(data["data"]["viewer"]["homes"][0]["consumption"]["nodes"]) print("Got " + str(numdata) + " rows from Tibber") ### insert data into database # consumption values = [] for item in data["data"]["viewer"]["homes"][0]["consumption"]["nodes"]: if item["consumption"] is not None: values.append((item["from"],item["to"],item["consumption"],item["consumptionUnit"],item["cost"],item["unitPrice"],item["unitPriceVAT"])) # connect to db conn = psycopg2.connect(database=pg_db, host=pg_host) cur = conn.cursor() # count rows before we start cur.execute("SELECT COUNT(*) FROM " + pg_table) before = cur.fetchone() # insert data try: cur.executemany("INSERT INTO " + pg_table + " VALUES(%s,%s,%s,%s,%s,%s,%s) ON CONFLICT (startTime,endTime) DO NOTHING", values) conn.commit() except Exception as e: conn.rollback() raise e # count rows after we finnish cur.execute("SELECT COUNT(*) FROM " + pg_table) after = cur.fetchone() # count *new* rows newRows = after[0] - before[0] # close connection conn.close() print("Successfully inserted " + str(newRows) + " records into the database")