From ec399db2eb3e14daeb0a5c15f845efb51b74ed16 Mon Sep 17 00:00:00 2001 From: b3yond Date: Wed, 8 Aug 2018 14:04:31 +0200 Subject: [PATCH] started to build a mailbot implementing bot.py --- active_bots/mailbot.py | 60 ++++++++++++++++++++++++++++++++++++++++++ report.py | 2 +- user.py | 2 +- 3 files changed, 62 insertions(+), 2 deletions(-) create mode 100644 active_bots/mailbot.py diff --git a/active_bots/mailbot.py b/active_bots/mailbot.py new file mode 100644 index 0000000..172d701 --- /dev/null +++ b/active_bots/mailbot.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 + +import logging +import sendmail +import datetime +import email +import report +from bot import Bot + + +logger = logging.getLogger(__name__) + + +class Mailbot(Bot): + + # returns a list of Report objects + def crawl(self, user): + reports = [] + mails = [] # todo: look if new reports are in mailbox + for msg in mails: + if msg.date > user.get_seen_mail(): + reports.append(make_report(msg, user)) + return reports + + # post/boost Report object + def post(self, user, report): + recipients = user.get_mailinglist() + for rec in recipients: + rec = rec[0] + unsubscribe_link = "" # todo: generate unsubscribe link + body = report.text + unsubscribe_link + if report.author != rec: + try: + sendmail.sendmail(rec, "Ticketfrei " + user.get_city() + + " Report", body=body) + except Exception: + logger.error("Sending Mail failed.", exc_info=True) + + +def make_report(msg, user): + """ + generates a report out of a mail + + :param msg: email.parser.Message object + :return: post: report.Report object + """ + # get a comparable date out of the email + date_tuple = email.utils.parsedate_tz(msg['Date']) + date_tuple = datetime.datetime.fromtimestamp( + email.utils.mktime_tz(date_tuple) + ) + date = (date_tuple - datetime.datetime(1970, 1, 1)).total_seconds() + + author = msg.get("From") # get mail author from email header + # :todo take only the part before the @ + + text = msg.get_payload() + post = report.Report(author, "mail", text, None, date) + user.save_seen_mail(date) + return post diff --git a/report.py b/report.py index aa34fed..5cf2c13 100644 --- a/report.py +++ b/report.py @@ -19,7 +19,7 @@ class Report(object): :param timestamp: time of the report """ self.author = author - self.type = source + self.source = source self.text = text self.timestamp = timestamp self.id = id diff --git a/user.py b/user.py index fb592be..faf535c 100644 --- a/user.py +++ b/user.py @@ -141,7 +141,7 @@ schlitz def get_mailinglist(self): db.execute("SELECT email FROM mailinglist WHERE user_id = ? AND active = 1;", (self.uid, )) - return db.cur.fetchone()[0] + return db.cur.fetchall() def get_seen_mail(self): db.execute("SELECT mail_date FROM seen_mails WHERE user_id = ?;", (self.uid, ))