|
|
@@ -1,89 +1,122 @@
|
|
|
-import urllib.request, tempfile, smtplib, email, time
|
|
|
+import os
|
|
|
+import requests
|
|
|
+import smtplib
|
|
|
+import ssl
|
|
|
+import tempfile
|
|
|
+import time
|
|
|
+import urllib.request
|
|
|
+import json
|
|
|
from datetime import datetime, timedelta
|
|
|
+from email.mime.image import MIMEImage
|
|
|
+from email.mime.multipart import MIMEMultipart
|
|
|
+from email.mime.text import MIMEText
|
|
|
|
|
|
|
|
|
-tmpdir = tempfile.TemporaryDirectory()
|
|
|
-beginning = str(1000*(int(time.time()))-(17*3600000))[:-3]
|
|
|
-end = str(1000*int(time.time()))[:-3]
|
|
|
+def send_to_telegram(bot_token, chat_id, caption, *image_paths):
|
|
|
+ url = f"https://api.telegram.org/bot{bot_token}/sendMediaGroup"
|
|
|
|
|
|
-def get_boot_time():
|
|
|
- with open('/proc/uptime', 'r') as f:
|
|
|
- uptime_seconds = int(float(f.readline().split()[0]))
|
|
|
- boot_time = datetime.now() - timedelta(seconds=uptime_seconds) + timedelta(hours=1)
|
|
|
- return boot_time
|
|
|
+ media_group = []
|
|
|
|
|
|
-def get_uptime():
|
|
|
- with open('/proc/uptime', 'r') as f:
|
|
|
- uptime_hours = round(float(f.readline().split()[0])/3600, 2)
|
|
|
- return uptime_hours
|
|
|
+ for i, image_path in enumerate(image_paths):
|
|
|
+ with open(image_path, 'rb') as image_file:
|
|
|
+ image_data = image_file.read()
|
|
|
|
|
|
-get_boot_time()
|
|
|
+ files = {
|
|
|
+ 'photo': ('image.jpg', image_data, 'image/jpeg'),
|
|
|
+ }
|
|
|
|
|
|
+ response = requests.post(f"https://api.telegram.org/bot{bot_token}/uploadPhoto", files=files)
|
|
|
+ file_id = response.json()['result']['photo'][0]['file_id']
|
|
|
|
|
|
-# Send an HTML email with an embedded image and a plain text message for
|
|
|
-# email clients that don't want to display the HTML.
|
|
|
-urllib.request.urlretrieve("http://localhost/cacti/graph_image.php?local_graph_id=109&graph_start=" + beginning + "&graph_end=" + end + "&graph_width=700&graph_height=200", tmpdir.name + "/ping.png")
|
|
|
+ media_group.append({
|
|
|
+ 'type': 'photo',
|
|
|
+ 'media': file_id,
|
|
|
+ 'caption': caption if i == 0 else "",
|
|
|
+ 'parse_mode': 'HTML',
|
|
|
+ })
|
|
|
|
|
|
-urllib.request.urlretrieve("http://localhost/cacti/graph_image.php?local_graph_id=103&graph_start=" + beginning + "&graph_end=" + end + "&graph_width=695&graph_height=198", tmpdir.name + "/traffic.png")
|
|
|
+ data = {
|
|
|
+ 'chat_id': chat_id,
|
|
|
+ 'media': json.dumps(media_group),
|
|
|
+ }
|
|
|
|
|
|
+ response = requests.post(url, data=data)
|
|
|
+
|
|
|
+ if response.status_code != 200:
|
|
|
+ raise ValueError(f"Request to Telegram API returned an error: {response.status_code}, {response.text}")
|
|
|
|
|
|
-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"]
|
|
|
+def create_email(sender_email, recipient_emails, subject, boot_time_str, image_path1, image_path2):
|
|
|
+ msg = MIMEMultipart("related")
|
|
|
+ msg["From"] = sender_email
|
|
|
+ msg["To"] = ",".join(recipient_emails)
|
|
|
+ msg["Subject"] = subject
|
|
|
|
|
|
-# Create the root message and fill in the from, to, and subject headers
|
|
|
-msgRoot = MIMEMultipart('related')
|
|
|
-msgRoot['Subject'] = datetime.today().strftime('%Y-%m-%d') + ' Darmstadt'
|
|
|
-msgRoot['From'] = strFrom
|
|
|
-msgRoot['To'] = ",".join(strTo)
|
|
|
-msgRoot.preamble = 'This is a multi-part message in MIME format.'
|
|
|
+ msg_alternative = MIMEMultipart("alternative")
|
|
|
+ msg.attach(msg_alternative)
|
|
|
|
|
|
-# 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)
|
|
|
+ msg_text = MIMEText("This is the alternative plain text message.")
|
|
|
+ msg_alternative.attach(msg_text)
|
|
|
|
|
|
-msgText = MIMEText('This is the alternative plain text message.')
|
|
|
-msgAlternative.attach(msgText)
|
|
|
+ html_text = f'<img src="cid:image1"><br><img src="cid:image2"><br><br><p>Letzter Start: {boot_time_str} Uhr</p>'
|
|
|
+ msg_html = MIMEText(html_text, "html")
|
|
|
+ msg_alternative.attach(msg_html)
|
|
|
|
|
|
-# Get Boot Time and Convert it to String
|
|
|
-bt = get_boot_time()
|
|
|
-bt_str = bt.strftime("%d.%m.%Y, %H.%M")
|
|
|
+ with open(image_path1, "rb") as file:
|
|
|
+ msg_image1 = MIMEImage(file.read())
|
|
|
+ msg_image1.add_header("Content-ID", "<image1>")
|
|
|
+ msg.attach(msg_image1)
|
|
|
|
|
|
-# We reference the image in the IMG SRC attribute by the ID we give it dasdasdbelow
|
|
|
-msgText = MIMEText('<img src="cid:image1"><br><img src="cid:image2"><br><br><p>Letzter Start: ' + bt_str + ' Uhr</p>', 'html')
|
|
|
-msgAlternative.attach(msgText)
|
|
|
+ with open(image_path2, "rb") as file:
|
|
|
+ msg_image2 = MIMEImage(file.read())
|
|
|
+ msg_image2.add_header("Content-ID", "<image2>")
|
|
|
+ msg.attach(msg_image2)
|
|
|
|
|
|
+ return msg
|
|
|
+
|
|
|
+
|
|
|
+def send_email(sender_email, recipient_emails, msg):
|
|
|
+ context = ssl.create_default_context()
|
|
|
+ with smtplib.SMTP("smtp.web.de", 587) as server:
|
|
|
+ server.ehlo()
|
|
|
+ server.starttls(context=context)
|
|
|
+ server.ehlo()
|
|
|
+ server.login(sender_email, "PV-Tannenstr1")
|
|
|
+ server.sendmail(sender_email, recipient_emails, msg.as_string())
|
|
|
+
|
|
|
+
|
|
|
+def get_boot_time():
|
|
|
+ with open("/proc/uptime", "r") as f:
|
|
|
+ uptime_seconds = int(float(f.readline().split()[0]))
|
|
|
+ boot_time = datetime.now() - timedelta(seconds=uptime_seconds) + timedelta(hours=1)
|
|
|
+ return boot_time
|
|
|
+
|
|
|
+tmpdir = tempfile.TemporaryDirectory()
|
|
|
+beginning = str(1000 * (int(time.time())) - (17 * 3600000))[:-3]
|
|
|
+end = str(1000 * int(time.time()))[:-3]
|
|
|
+
|
|
|
+urllib.request.urlretrieve("http://localhost/cacti/graph_image.php?local_graph_id=109&graph_start=" + beginning + "&graph_end=" + end + "&graph_width=700&graph_height=200", tmpdir.name + "/ping.png")
|
|
|
+
|
|
|
+urllib.request.urlretrieve("http://localhost/cacti/graph_image.php?local_graph_id=103&graph_start=" + beginning + "&graph_end=" + end + "&graph_width=695&graph_height=198", tmpdir.name + "/traffic.png")
|
|
|
|
|
|
-# This example assumes the image is in the current directory
|
|
|
-fp = open(tmpdir.name + '/traffic.png', 'rb')
|
|
|
-msgImage1 = MIMEImage(fp.read())
|
|
|
-fp.close()
|
|
|
+# Bot token and chat ID for Telegram
|
|
|
+bot_token = "949332240:AAHNsQEmCW4it86Esa7F5o07XxwrotSM7s8"
|
|
|
+chat_id = "-914111351"
|
|
|
|
|
|
-fp = open(tmpdir.name + '/ping.png', 'rb')
|
|
|
-msgImage2 = MIMEImage(fp.read())
|
|
|
-fp.close()
|
|
|
+boot_time = get_boot_time()
|
|
|
+boot_time_str = boot_time.strftime("%d.%m.%Y, %H.%M")
|
|
|
|
|
|
+subject = datetime.today().strftime('%Y-%m-%d') + ' Darmstadt'
|
|
|
+sender_email = 'pv-tannenstr@web.de'
|
|
|
+recipient_emails = ["tobias.siegel@outlook.com", "wsiegel@web.de"]
|
|
|
|
|
|
-# Define the image's ID as referenced above
|
|
|
-msgImage1.add_header('Content-ID', '<image1>')
|
|
|
-msgRoot.attach(msgImage1)
|
|
|
-msgImage2.add_header('Content-ID', '<image2>')
|
|
|
-msgRoot.attach(msgImage2)
|
|
|
+email_msg = create_email(sender_email, recipient_emails, subject, boot_time_str, tmpdir.name + "/traffic.png", tmpdir.name + "/ping.png")
|
|
|
|
|
|
+send_email(sender_email, recipient_emails, email_msg)
|
|
|
|
|
|
-# 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-Tannenstr1')
|
|
|
- server.sendmail(strFrom, strTo, msgRoot.as_string())
|
|
|
+try:
|
|
|
+ send_to_telegram(bot_token, chat_id, f"<b>{subject}</b>\nLetzter Start: {boot_time_str} Uhr", tmpdir.name + "/traffic.png", tmpdir.name + "/ping.png")
|
|
|
+except ValueError as e:
|
|
|
+ print(f"Failed to send images to Telegram: {e}")
|
|
|
|
|
|
-tmpdir.cleanup()
|
|
|
+tmpdir.cleanup()
|