Sfoglia il codice sorgente

initial upload from pyanaf

marton levente 1 anno fa
parent
commit
8548ec251e
4 ha cambiato i file con 267 aggiunte e 0 eliminazioni
  1. 1 0
      .gitignore
  2. 138 0
      mail_alert.py
  3. 91 0
      mail_alert2.py
  4. 37 0
      start_mail_alert.py

+ 1 - 0
.gitignore

@@ -192,3 +192,4 @@ target/
 # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
 hs_err_pid*
 
+/bot

+ 138 - 0
mail_alert.py

@@ -0,0 +1,138 @@
+'''Created Sep 28, 2021 Levi'''
+
+import configparser
+import sys
+import traceback
+import ssl
+from time import sleep
+from collections import deque
+from threading import Event
+
+import telegram
+import keyring
+from bs4 import BeautifulSoup
+from telegram.error import BadRequest
+from imap_tools import MailBox, AND, OR
+
+#-> for python 3.10, the dh key too small problem
+context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
+context.set_ciphers('DEFAULT@SECLEVEL=1')
+
+config = configparser.ConfigParser()
+config.read('bot')
+bot = telegram.Bot(token=config['AUTH']['token'])
+bot2 = telegram.Bot(token=config['AUTH']['bank'])
+mailbox = MailBox(host=config['email']['host'], ssl_context=context)
+mailbox2 = MailBox(host=config['email']['host'], ssl_context=context)
+
+def pretty_exc():
+    exc_type, _exc_obj, exc_tb = sys.exc_info()
+    # fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
+    for tb in list(traceback.format_exception(exc_type, _exc_obj, exc_tb)):
+            print(tb)
+
+def mask(msg, to_):
+    return any([to_ == msg.from_,
+                to_ in msg.to,
+                to_ in msg.cc,
+                to_ in msg.bcc])
+
+def mask2(msg, to_):
+    return any([to_ == msg.from_,
+                to_ in msg.to,
+                to_ in msg.cc,
+                to_ in msg.bcc,
+                to_ in msg.subject])
+
+
+def mail_alert(event):
+    '''mail alert Inbox'''
+    container = deque(maxlen=500)
+    bot = telegram.Bot(token=config['AUTH']['token'])
+    mailbox.login(config['email']['user'], keyring.get_password('yagmail', 'levente.marton@mzk.ro'), initial_folder='Inbox')
+    while not event.is_set():
+        try:
+            sleep(15)
+            msgs = [msgs for msgs in mailbox.fetch(AND(seen=False), mark_seen=False)]
+            for msg in msgs:
+                chk = mask(msg, 'levente.marton@mzk.ro')
+                if chk:
+                    msg_text = msg.text
+                    if 'end of day extras/intraday' in msg.subject:
+                        msg_text = msg.text.replace('<br>', '\n')
+                    if msg.uid not in container:
+                        try:
+                            if len(msg.text) != 0:
+                                bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg_text}')
+                            else:
+                                bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg.html}')
+                            container.appendleft(msg.uid)
+                            print('message appended', len(container))
+                        except BadRequest:
+                            try:
+                                if len(msg.text) != 0:
+                                    bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg_text[:len(msg_text) // 5]}')
+                                else:
+                                    bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg.html[:len(msg.html) // 5]}')
+                                container.appendleft(msg.uid)
+                                print('message appended', len(container))
+                            except BadRequest:
+                                bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\nMessage is too long')
+                                container.appendleft(msg.uid)
+                                print('message appended', len(container), '!! last message was to long !!')
+                        except Exception:
+                            mailbox.logout()
+                            pretty_exc()
+                            break
+        except Exception:
+            mailbox.logout()
+            break
+
+def mail_alert2(event):
+    container = deque(maxlen=500)
+    mailbox2.login(config['email']['user'], keyring.get_password('yagmail', 'levente.marton@mzk.ro'), initial_folder='bank_events')
+    while not event.is_set():
+        try:
+            sleep(15)
+            msgs = [msgs for msgs in mailbox2.fetch(AND(seen=False), mark_seen=True)]
+            for msg in msgs:
+                chk = mask2(msg, 'account')
+                if chk:
+                    if msg.uid not in container:
+                        soup = BeautifulSoup(msg.html, 'html.parser')
+                        msg_text = soup.prettify().replace('<br/>', '').replace('<html>', '').replace('<head>', '').replace('</head>', '').replace('<body>', '').replace('<div>', '').replace('</div>', '').replace('</body>', '').replace('</html>', '')
+                        try:
+                            if len(msg.text) != 0:
+                                bot2.send_message(chat_id=config['AUTH']['chatid'], text=msg_text)
+                            else:
+                                bot2.send_message(chat_id=config['AUTH']['chatid'], text=msg_text)
+                            container.appendleft(msg.uid)
+                            print('message appended', len(container))
+                        except BadRequest:
+                            try:
+                                if len(msg.text) != 0:
+                                    bot2.send_message(chat_id=config['AUTH']['chatid'], text=msg_text // 5)
+                                else:
+                                    bot2.send_message(chat_id=config['AUTH']['chatid'], text=msg_text // 5)
+                                container.appendleft(msg.uid)
+                                print('message appended', len(container))
+                            except BadRequest:
+                                bot2.send_message(chat_id=config['AUTH']['chatid'], text=f'Message is too long')
+                                container.appendleft(msg.uid)
+                                print('message appended', len(container), '!! last message was to long !!')
+                        except Exception:
+                            mailbox2.logout()
+                            pretty_exc()
+                            break
+        except Exception:
+            # pretty_exc()
+            mailbox2.logout()
+            break
+
+
+if __name__ == '__main__':
+    try:
+        event = Event()
+        mail_alert2(event=event)
+    except KeyboardInterrupt:
+        event.set()

+ 91 - 0
mail_alert2.py

@@ -0,0 +1,91 @@
+'''Created Sep 28, 2021 Levi'''
+
+import configparser
+import sys
+import traceback
+import ssl
+from time import sleep
+from collections import deque
+
+import telegram
+import keyring
+from bs4 import BeautifulSoup
+from telegram.error import BadRequest
+from imap_tools import MailBox, AND
+
+#-> for python 3.10, the dh key too small problem
+context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
+context.set_ciphers('DEFAULT@SECLEVEL=1')
+
+config = configparser.ConfigParser()
+config.read('bot')
+bot = telegram.Bot(token=config['AUTH']['bank'])
+mailbox = MailBox(host=config['email']['host'], ssl_context=context)
+
+def pretty_exc():
+    exc_type, _exc_obj, exc_tb = sys.exc_info()
+    # fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
+    for tb in list(traceback.format_exception(exc_type, _exc_obj, exc_tb)):
+            print(tb)
+
+def mask(msg, to_):
+    return any([to_ == msg.from_,
+                to_ in msg.to,
+                to_ in msg.cc,
+                to_ in msg.bcc,
+                to_ in msg.subject])
+
+
+def mail_alert():
+    container = deque(maxlen=500)
+    mailbox.login(config['email']['user'], keyring.get_password('yagmail', 'levente.marton@mzk.ro'), initial_folder='bank_events')
+    while True:
+        try:
+            sleep(15)
+            msgs = [msgs for msgs in mailbox.fetch(AND(seen=False), mark_seen=True)]
+            for msg in msgs:
+                chk = mask(msg, 'account')
+                if chk:
+                    if msg.uid not in container:
+                        soup = BeautifulSoup(msg.html, 'html.parser')
+                        msg_text = soup.prettify().replace('<br/>', '').replace('<html>', '').replace('<head>', '').replace('</head>', '').replace('<body>', '').replace('<div>', '').replace('</div>', '').replace('</body>', '').replace('</html>', '')
+                        try:
+                            if len(msg.text) != 0:
+                                bot.send_message(chat_id=config['AUTH']['chatid'], text=msg_text)
+                            else:
+                                bot.send_message(chat_id=config['AUTH']['chatid'], text=msg_text)
+                            container.appendleft(msg.uid)
+                            print('message appended', len(container))
+                        except BadRequest:
+                            try:
+                                if len(msg.text) != 0:
+                                    bot.send_message(chat_id=config['AUTH']['chatid'], text=msg_text // 5)
+                                else:
+                                    bot.send_message(chat_id=config['AUTH']['chatid'], text=msg_text // 5)
+                                container.appendleft(msg.uid)
+                                print('message appended', len(container))
+                            except BadRequest:
+                                bot.send_message(chat_id=config['AUTH']['chatid'], text=f'Message is too long')
+                                container.appendleft(msg.uid)
+                                print('message appended', len(container), '!! last message was to long !!')
+                        except Exception:
+                            mailbox.logout()
+                            pretty_exc()
+                            break
+        except Exception:
+            # pretty_exc()
+            mailbox.logout()
+            break
+
+
+if __name__ == '__main__':
+    mail_alert()
+    # mailbox.login(config['email']['user'], keyring.get_password('yagmail', 'levente.marton@mzk.ro'), initial_folder='bank_events')
+    # msgs = [msgs for msgs in mailbox.fetch(AND(seen=False), mark_seen=True, reverse=True)]
+    # for msg in msgs:
+    #     chk = mask(msg, 'account')
+    #     if chk:
+    #         print(msg.uid, msg.subject)
+    # msg = msgs[0]
+    # soup = BeautifulSoup(msg.html, 'html.parser')
+    # print(soup.prettify().replace('<br/>', ''))

+ 37 - 0
start_mail_alert.py

@@ -0,0 +1,37 @@
+'''Created 16 Nov 2022 Levi'''
+
+from threading import Event
+from threading import Thread
+from time import sleep
+
+import mail_alert
+
+event1 = Event()
+event2 = Event()
+thread1 = Thread(target=mail_alert.mail_alert, args=(event1,))
+thread2 = Thread(target=mail_alert.mail_alert2, args=(event2,))
+# thread3 =
+# thread4 =
+# thread5 =
+# thread6 =
+
+if __name__ == '__main__':
+    thread1.start()
+    print(f'started mail alert Inbox')
+    # sleep(0.5)
+    thread2.start()
+    print(f'started mail alert Bank events')
+    # sleep(0.5)
+    while True:
+        try:
+            sleep(1)
+        except KeyboardInterrupt:
+            event1.set()
+            event2.set()
+            thread1.join()
+            print(f'stopped mail alert Inbox')
+            # sleep(0.5)
+            thread2.join()
+            print(f'stopped mail alert Bank events')
+            # sleep(0.5)
+            break