tsi 2 سال پیش
والد
کامیت
3693396ed0
1فایلهای تغییر یافته به همراه86 افزوده شده و 73 حذف شده
  1. 86 73
      scripts/send_email.py

+ 86 - 73
scripts/send_email.py

@@ -1,10 +1,21 @@
-import urllib.request, tempfile, smtplib, email, time
+import os
+import ssl
+import smtplib
+import tempfile
+import time
+import urllib.request
 from datetime import datetime, timedelta
+from email.mime.image import MIMEImage
+from email.mime.multipart import MIMEMultipart
+from email.mime.text import MIMEText
 from influxdb import InfluxDBClient
+import requests
 
-tmpdir = tempfile.TemporaryDirectory() 
-beginning = str((1000*int(time.time()))-(17*3600000))
-end = str(1000*int(time.time()))
+# Configurations
+strFrom = 'pv-tannenstr@web.de'
+strTo = ["tobias.siegel@outlook.com", "wsiegel@web.de"]
+bot_token = 'YOUR_TELEGRAM_BOT_TOKEN'
+chat_id = 'YOUR_TELEGRAM_CHAT_ID'
 
 def get_boot_time():
     with open('/proc/uptime', 'r') as f:
@@ -12,72 +23,74 @@ def get_boot_time():
         boot_time = datetime.now() - timedelta(seconds=uptime_seconds) + timedelta(hours=1)
     return boot_time
 
-def get_uptime():
-    with open('/proc/uptime', 'r') as f:
-        uptime_hours = round(float(f.readline().split()[0])/3600, 2)
-    return uptime_hours
-
-get_boot_time()
-client = InfluxDBClient(host='127.0.0.1', port=8086, database='solar')
-result = client.query("SELECT sum(\"eingespeiste_leistung\") *0.000002777777777 FROM \"Tannenstrasse\"  WHERE time >= " + beginning + "ms and time <= " + end + "ms")
-if 'series' in result.raw:
-    kwh = round(result.raw['series'][0]['values'][0][1], 1)
-else:
-    kwh = "0 - Keine Werte"
-
-urllib.request.urlretrieve("http://localhost:3000/render/d-solo/-wCxs6mgk/solaranlage?orgId=1&refresh=10s&panelId=2&from=" + beginning + "&to=" + end + "&width=600&height=300&tz=Europe%2FBerlin", tmpdir.name + "/leistung.png")
-
-# Send an HTML email with an embedded image and a plain text message for
-# email clients that don't want to display the HTML.
-
-from email.mime.multipart import MIMEMultipart
-from email.mime.text import MIMEText
-from email.mime.image import MIMEImage
-
-# Define these once; use them twice!
-strFrom = 'pv-tannenstr@web.de'
-strTo = ["tobias.siegel@outlook.com", "wsiegel@web.de"]
-
-# Create the root message and fill in the from, to, and subject headers
-msgRoot = MIMEMultipart('related')
-msgRoot['Subject'] = datetime.today().strftime('%Y-%m-%d') + ' - ' + str(kwh) + 'kWh - Solaranlage'
-msgRoot['From'] = strFrom
-msgRoot['To'] = ",".join(strTo)
-msgRoot.preamble = 'This is a multi-part message in MIME format.'
-
-# Encapsulate the plain and HTML versions of the message body in an
-# 'alternative' part, so message agents can decide which they want to display.
-msgAlternative = MIMEMultipart('alternative')
-msgRoot.attach(msgAlternative)
-
-msgText = MIMEText('This is the alternative plain text message.')
-msgAlternative.attach(msgText)
-
-# Get Boot Time and Convert it to String
-bt = get_boot_time()
-bt_str = bt.strftime("%d.%m.%Y, %H.%M")
-
-# We reference the image in the IMG SRC attribute by the ID we give it dasdasdbelow
-msgText = MIMEText('<img src="cid:image1"><br><p>Letzter Start: ' + bt_str + ' Uhr</p>', 'html')
-msgAlternative.attach(msgText)
-
-# This example assumes the image is in the current directory
-fp = open(tmpdir.name + '/leistung.png', 'rb')
-msgImage = MIMEImage(fp.read())
-fp.close()
-
-# Define the image's ID as referenced above
-msgImage.add_header('Content-ID', '<image1>')
-msgRoot.attach(msgImage)
-
-# Send the email (this example assumes SMTP authentication is required)
-import smtplib, ssl
-context = ssl.create_default_context()
-with smtplib.SMTP('smtp.web.de', 587) as server:
-    server.ehlo()  # Can be omitted
-    server.starttls(context=context)
-    server.ehlo()  # Can be omitted
-    server.login(strFrom, 'PV-Tannenstr')
-    server.sendmail(strFrom, strTo, msgRoot.as_string())
-
-tmpdir.cleanup()
+def get_kwh(beginning, end):
+    client = InfluxDBClient(host='127.0.0.1', port=8086, database='solar')
+    result = client.query("SELECT sum(\"eingespeiste_leistung\") *0.000002777777777 FROM \"Tannenstrasse\"  WHERE time >= {}ms and time <= {}ms".format(beginning, end))
+    if 'series' in result.raw:
+        return round(result.raw['series'][0]['values'][0][1], 1)
+    else:
+        return "0 - Keine Werte"
+
+def create_email(kwh):
+    msgRoot = MIMEMultipart('related')
+    msgRoot['Subject'] = f'{datetime.today().strftime("%Y-%m-%d")} - {kwh}kWh - Solaranlage'
+    msgRoot['From'] = strFrom
+    msgRoot['To'] = ",".join(strTo)
+    msgRoot.preamble = 'This is a multi-part message in MIME format.'
+
+    msgAlternative = MIMEMultipart('alternative')
+    msgRoot.attach(msgAlternative)
+
+    msgText = MIMEText('This is the alternative plain text message.')
+    msgAlternative.attach(msgText)
+
+    bt = get_boot_time()
+    bt_str = bt.strftime("%d.%m.%Y, %H.%M")
+
+    msgText = MIMEText(f'<img src="cid:image1"><br><p>Letzter Start: {bt_str} Uhr</p>', 'html')
+    msgAlternative.attach(msgText)
+
+    with open(tmpdir.name + '/leistung.png', 'rb') as fp:
+        msgImage = MIMEImage(fp.read())
+
+    msgImage.add_header('Content-ID', '<image1>')
+    msgRoot.attach(msgImage)
+
+    return msgRoot
+
+def send_email(msgRoot):
+    context = ssl.create_default_context()
+    with smtplib.SMTP('smtp.web.de', 587) as server:
+        server.ehlo()
+        server.starttls(context=context)
+        server.ehlo()
+        server.login(strFrom, 'PV-Tannenstr')
+        server.sendmail(strFrom, strTo, msgRoot.as_string())
+
+def send_telegram(bot_token, chat_id, kwh):
+    bot_url = f'https://api.telegram.org/bot{bot_token}/sendPhoto'
+    bt = get_boot_time()
+    bt_str = bt.strftime("%d.%m.%Y, %H.%M")
+    caption = f'{datetime.today().strftime("%Y-%m-%d")} - {kwh}kWh - Solaranlage\nLetzter Start: {bt_str} Uhr'
+
+    with open(tmpdir.name + '/leistung.png', 'rb') as img:
+        response = requests.post(
+            bot_url,
+            data={'chat_id': chat_id, 'caption': caption},
+            files={'photo': img}
+        )
+    return response
+
+if __name__ == "__main__":
+    tmpdir = tempfile.TemporaryDirectory()
+    beginning = str((1000 * int(time.time())) - (17 * 3600000))
+    end = str(1000 * int(time.time()))
+
+    urllib.request.urlretrieve(f"http://localhost:3000/render/d-solo/-wCxs6mgk/solaranlage?orgId=1&refresh=10s&panelId=2&from={beginning}&to={end}&width=600&height=300&tz=Europe%2FBerlin", f"{tmpdir.name}/leistung.png")
+
+    kwh = get_kwh(beginning, end)
+    email_msg = create_email(kwh)
+    send_email(email_msg)
+    send_telegram(bot_token, chat_id, kwh)
+
+    tmpdir.cleanup()