'''Created Sep 28, 2021 Levi''' import configparser import sys import traceback import ssl from time import sleep from imaplib import IMAP4 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']['token']) bot2 = telegram.Bot(token=config['AUTH']['bank']) 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 clean_html(text) -> str: soup = BeautifulSoup(text, 'html.parser') stripped_text = soup.get_text() lines = (line.strip() for line in stripped_text.splitlines()) # break multi-headlines into a line each chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) # drop blank lines text = '\n'.join(chunk for chunk in chunks if chunk) return text async def mail_alert(container) -> list | str: '''mail alert Inbox''' # container: deque = deque(maxlen=500) # while True: try: mailbox = MailBox(host=config['email']['host'], ssl_context=context) mailbox.login(config['email']['user'], keyring.get_password('yagmail', 'levente.marton@mzk.ro'), initial_folder='Inbox') # noqa E:mypy sleep(15) msgs = [msgs for msgs in mailbox.fetch(AND(seen=False), mark_seen=False)] ids: list = [] 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('
', '\n') if msg.uid not in container: try: if len(msg.text) != 0: await bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg_text}') else: await 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: await bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg_text[:len(msg_text) // 5]}') else: await 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: await 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: try: mailbox.logout() pretty_exc() except IMAP4.abort: pass # break ids.append(msg.uid) mailbox.logout() # return msg.uid return ids except Exception: try: mailbox.logout() except IMAP4.abort: pass return 'empty box' async def mail_alert2(container) -> list | str: # container: deque = deque(maxlen=500) # while True: try: mailbox2 = MailBox(host=config['email']['host'], ssl_context=context) mailbox2.login(config['email']['user'], keyring.get_password('yagmail', 'levente.marton@mzk.ro'), initial_folder='bank_events') # noqa E:mypy sleep(15) msgs = [msgs for msgs in mailbox2.fetch(AND(seen=False), mark_seen=True)] ids: list = [] 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('
', '').replace('', '').replace('', '').replace('', '').replace('', '').replace('
', '').replace('
', '').replace('', '').replace('', '') msg_text = msg_text[:msg_text.find('Intraday transactions')] msg_text = clean_html(msg_text) try: if len(msg.text) or len(msg.html) != 0: await bot2.send_message(chat_id=config['AUTH']['chatid'], text=msg_text) else: await 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) or len(msg.html) != 0: await bot2.send_message(chat_id=config['AUTH']['chatid'], text=msg_text // 5) # noqa E:mypy else: await bot2.send_message(chat_id=config['AUTH']['chatid'], text=msg_text // 5) # noqa E:mypy # container.appendleft(msg.uid) print('message appended', len(container)) except BadRequest: await 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: try: mailbox2.logout() pretty_exc() except IMAP4.abort: pass # break ids.append(msg.uid) mailbox2.logout() # return msg.uid return ids except Exception: # pretty_exc() try: mailbox2.logout() except IMAP4.abort: pass return 'empty box' async def mail_alert3(container) -> list | str: '''mail alert Inbox''' # container: deque = deque(maxlen=500) # while True: try: mailbox3 = MailBox(host=config['email']['host'], ssl_context=context) mailbox3.login(config['email']['user'], keyring.get_password('yagmail', 'levente.marton@mzk.ro'), initial_folder='API') # noqa E:mypy sleep(15) msgs = [msgs for msgs in mailbox3.fetch(AND(seen=False), mark_seen=True)] ids: list = [] for msg in msgs: chk = mask(msg, 'Ciel_notifier@mzk.ro') if chk: msg_text = msg.text # if 'end of day extras/intraday' in msg.subject: # msg_text = msg.text.replace('
', '\n') if msg.uid not in container: try: if len(msg.text) != 0: await bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg_text}') else: await 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: await bot.send_message(chat_id=config['AUTH']['chatid'], text=f'{msg.from_}\nsubj: {msg.subject}\n\n{msg_text[:len(msg_text) // 5]}') else: await 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: await 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: try: mailbox3.logout() pretty_exc() except IMAP4.abort: pass # break ids.append(msg.uid) mailbox3.logout() # return msg.uid return ids except Exception: try: mailbox3.logout() except IMAP4.abort: pass return 'empty box' # if __name__ == '__main__': # try: # # event = Event() # asyncio.run(mail_alert()) # except KeyboardInterrupt: # loop = asyncio.get_event_loop() # loop.stop()