the mailbot can now receive messages from /var/mail/test

This commit is contained in:
b3yond 2018-08-08 17:09:26 +02:00
parent ec399db2eb
commit 57a2e4dcb1
6 changed files with 46 additions and 18 deletions

View file

@ -3,6 +3,7 @@
import logging import logging
import sendmail import sendmail
import datetime import datetime
import mailbox
import email import email
import report import report
from bot import Bot from bot import Bot
@ -16,9 +17,9 @@ class Mailbot(Bot):
# returns a list of Report objects # returns a list of Report objects
def crawl(self, user): def crawl(self, user):
reports = [] reports = []
mails = [] # todo: look if new reports are in mailbox mails = mailbox.mbox('/var/mail/test') # todo: adjust to actual mailbox file
for msg in mails: for msg in mails:
if msg.date > user.get_seen_mail(): if get_date_from_header(msg['Date']) > user.get_seen_mail():
reports.append(make_report(msg, user)) reports.append(make_report(msg, user))
return reports return reports
@ -29,10 +30,11 @@ class Mailbot(Bot):
rec = rec[0] rec = rec[0]
unsubscribe_link = "" # todo: generate unsubscribe link unsubscribe_link = "" # todo: generate unsubscribe link
body = report.text + unsubscribe_link body = report.text + unsubscribe_link
print(body)
if report.author != rec: if report.author != rec:
try: try:
sendmail.sendmail(rec, "Ticketfrei " + user.get_city() + sendmail.sendmail(rec, "Ticketfrei " + user.get_city() +
" Report", body=body) " Report", body=body)
except Exception: except Exception:
logger.error("Sending Mail failed.", exc_info=True) logger.error("Sending Mail failed.", exc_info=True)
@ -45,16 +47,24 @@ def make_report(msg, user):
:return: post: report.Report object :return: post: report.Report object
""" """
# get a comparable date out of the email # get a comparable date out of the email
date_tuple = email.utils.parsedate_tz(msg['Date']) date = get_date_from_header(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 author = msg['From'] # get mail author from email header
# :todo take only the part before the @ # :todo take only the part in between the < >
text = msg.get_payload() text = msg.get_payload()
post = report.Report(author, "mail", text, None, date) post = report.Report(author, "mail", text, None, date)
user.save_seen_mail(date) user.save_seen_mail(date)
return post return post
def get_date_from_header(header):
"""
:param header: msg['Date']
:return: float: total seconds
"""
date_tuple = email.utils.parsedate_tz(header)
date_tuple = datetime.datetime.fromtimestamp(
email.utils.mktime_tz(date_tuple)
)
return (date_tuple - datetime.datetime(1970, 1, 1)).total_seconds()

View file

@ -53,7 +53,10 @@ class MastodonBot(Bot):
return mentions return mentions
def post(self, user, report): def post(self, user, report):
m = Mastodon(*user.get_masto_credentials()) try:
m = Mastodon(*user.get_masto_credentials())
except TypeError:
return # no mastodon account for this user.
if report.source == self: if report.source == self:
try: try:
m.status_reblog(report.id) m.status_reblog(report.id)

View file

@ -27,7 +27,10 @@ class TwitterBot(Bot):
:return: reports: (list of report.Report objects) :return: reports: (list of report.Report objects)
""" """
reports = [] reports = []
api = self.get_api(user) try:
api = self.get_api(user)
except IndexError:
return reports # no twitter account for this user.
last_dm = user.get_seen_dm() last_dm = user.get_seen_dm()
try: try:
if last_dm == None: if last_dm == None:

View file

@ -12,6 +12,7 @@ logger = logging.getLogger(__name__)
class TwitterBot(Bot): class TwitterBot(Bot):
def get_api(self, user): def get_api(self, user):
keys = user.get_twitter_credentials() keys = user.get_twitter_credentials()
auth = tweepy.OAuthHandler(consumer_key=keys[0], auth = tweepy.OAuthHandler(consumer_key=keys[0],
@ -60,7 +61,10 @@ class TwitterBot(Bot):
return [] return []
def post(self, user, report): def post(self, user, report):
api = self.get_api(user) try:
api = self.get_api(user)
except IndexError:
return # no twitter account for this user.
try: try:
if report.source == self: if report.source == self:
api.retweet(report.id) api.retweet(report.id)

8
db.py
View file

@ -122,6 +122,12 @@ class DB(object):
active INTEGER, active INTEGER,
FOREIGN KEY(user_id) REFERENCES user(id) FOREIGN KEY(user_id) REFERENCES user(id)
); );
CREATE TABLE IF NOT EXISTS seen_mail (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
user_id INTEGER,
mail_date REAL,
FOREIGN KEY(user_id) REFERENCES user(id)
);
CREATE TABLE IF NOT EXISTS cities ( CREATE TABLE IF NOT EXISTS cities (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
user_id INTEGER, user_id INTEGER,
@ -211,6 +217,8 @@ u\d\d?
active) VALUES(?, ?, ?);""", (uid, "", 1)) active) VALUES(?, ?, ?);""", (uid, "", 1))
self.commit() self.commit()
user = User(uid) user = User(uid)
self.execute("INSERT INTO seen_mail (user_id, mail_date) VALUES (?,?)",
(uid, 0))
user.set_city(city) user.set_city(city)
return user return user

10
user.py
View file

@ -57,11 +57,11 @@ class User(object):
}, db.secret).decode('ascii') }, db.secret).decode('ascii')
def is_appropriate(self, report): def is_appropriate(self, report):
db.execute("SELECT pattern FROM triggerpatterns WHERE user_id=?;", db.execute("SELECT patterns FROM triggerpatterns WHERE user_id=?;",
(self.uid, )) (self.uid, ))
patterns = db.cur.fetchone() patterns = db.cur.fetchone()[0]
for pattern in patterns.splitlines(): for pattern in patterns.splitlines():
if pattern.search(report.text) is not None: if pattern in report.text:
break break
else: else:
# no pattern matched # no pattern matched
@ -81,7 +81,7 @@ nigger
neger neger
schlitz schlitz
""" """
db.execute("SELECT word FROM badwords WHERE user_id=?;", db.execute("SELECT words FROM badwords WHERE user_id=?;",
(self.uid, )) (self.uid, ))
badwords = db.cur.fetchone() badwords = db.cur.fetchone()
for word in report.text.lower().splitlines(): for word in report.text.lower().splitlines():
@ -144,7 +144,7 @@ schlitz
return db.cur.fetchall() return db.cur.fetchall()
def get_seen_mail(self): def get_seen_mail(self):
db.execute("SELECT mail_date FROM seen_mails WHERE user_id = ?;", (self.uid, )) db.execute("SELECT mail_date FROM seen_mail WHERE user_id = ?;", (self.uid, ))
return db.cur.fetchone()[0] return db.cur.fetchone()[0]
def save_seen_mail(self, mail_date): def save_seen_mail(self, mail_date):