initializing logger is also done by ticketfrei now

This commit is contained in:
b3yond 2018-03-23 11:18:00 +01:00
parent 32e86a3c0e
commit a3b74dcfff
4 changed files with 31 additions and 57 deletions

View file

@ -6,12 +6,10 @@ import time
import trigger import trigger
import datetime import datetime
import email import email
import logging import ticketfrei
import imaplib import imaplib
import report import report
logger = logging.getLogger(__name__)
class Mailbot(object): class Mailbot(object):
""" """
@ -27,6 +25,7 @@ class Mailbot(object):
:param config: (dictionary) config.toml as a dictionary of dictionaries :param config: (dictionary) config.toml as a dictionary of dictionaries
""" """
self.config = config self.config = config
self.logger = ticketfrei.get_logger(config)
self.history_path = history_path self.history_path = history_path
self.last_mail = self.get_history(self.history_path) self.last_mail = self.get_history(self.history_path)
@ -41,18 +40,18 @@ class Mailbot(object):
try: try:
self.mailbox.starttls(ssl_context=context) self.mailbox.starttls(ssl_context=context)
except: except:
logger.error('StartTLS failed', exc_info=True) self.logger.error('StartTLS failed', exc_info=True)
try: try:
self.mailbox.login(self.config["mail"]["user"], self.config["mail"]["passphrase"]) self.mailbox.login(self.config["mail"]["user"], self.config["mail"]["passphrase"])
except imaplib.IMAP4.error: except imaplib.IMAP4.error:
logger.error("Login to mail server failed", exc_info=True) self.logger.error("Login to mail server failed", exc_info=True)
try: try:
mailer = sendmail.Mailer(config) mailer = sendmail.Mailer(config)
mailer.send('', config['mail']['contact'], mailer.send('', config['mail']['contact'],
'Ticketfrei Crash Report', 'Ticketfrei Crash Report',
attachment=config['logging']['logpath']) attachment=config['logging']['logpath'])
except: except:
logger.error('Mail sending failed', exc_info=True) self.logger.error('Mail sending failed', exc_info=True)
def repost(self, status): def repost(self, status):
""" """
@ -72,7 +71,7 @@ class Mailbot(object):
try: try:
rv, data = self.mailbox.select("Inbox") rv, data = self.mailbox.select("Inbox")
except imaplib.IMAP4.abort: except imaplib.IMAP4.abort:
logger.error("Crawling Mail failed", exc_info=True) self.logger.error("Crawling Mail failed", exc_info=True)
rv = False rv = False
msgs = [] msgs = []
if rv == 'OK': if rv == 'OK':
@ -83,7 +82,7 @@ class Mailbot(object):
for num in data[0].split(): for num in data[0].split():
rv, data = self.mailbox.fetch(num, '(RFC822)') rv, data = self.mailbox.fetch(num, '(RFC822)')
if rv != 'OK': if rv != 'OK':
logger.error("Couldn't fetch mail %s %s" % (rv, str(data))) self.logger.error("Couldn't fetch mail %s %s" % (rv, str(data)))
return msgs return msgs
msg = email.message_from_bytes(data[0][1]) msg = email.message_from_bytes(data[0][1])
@ -172,15 +171,8 @@ class Mailbot(object):
if __name__ == "__main__": if __name__ == "__main__":
import ticketfrei
config = ticketfrei.get_config() config = ticketfrei.get_config()
# set log file
logger = logging.getLogger()
fh = logging.FileHandler(config['logging']['logpath'])
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)
# initialise trigger # initialise trigger
trigger = trigger.Trigger(config) trigger = trigger.Trigger(config)
@ -195,7 +187,7 @@ if __name__ == "__main__":
except KeyboardInterrupt: except KeyboardInterrupt:
print("Good bye. Remember to restart the bot!") print("Good bye. Remember to restart the bot!")
except: except:
logger.error('Shutdown', exc_info=True) m.logger.error('Shutdown', exc_info=True)
m.save_last() m.save_last()
try: try:
mailer = sendmail.Mailer(config) mailer = sendmail.Mailer(config)
@ -203,4 +195,4 @@ if __name__ == "__main__":
'Ticketfrei Crash Report', 'Ticketfrei Crash Report',
attachment=config['logging']['logpath']) attachment=config['logging']['logpath'])
except: except:
logger.error('Mail sending failed', exc_info=True) m.logger.error('Mail sending failed', exc_info=True)

View file

@ -6,16 +6,14 @@ import pickle
import re import re
import time import time
import trigger import trigger
import logging
import sendmail import sendmail
import report import report
import ticketfrei
logger = logging.getLogger(__name__)
class RetootBot(object): class RetootBot(object):
def __init__(self, config): def __init__(self, config):
self.config = config self.config = config
self.logger = ticketfrei.get_logger(config)
self.client_id = self.register() self.client_id = self.register()
self.m = self.login() self.m = self.login()
@ -73,7 +71,7 @@ class RetootBot(object):
try: try:
all = self.m.notifications() all = self.m.notifications()
except: # mastodon.Mastodon.MastodonAPIError is unfortunately not in __init__.py except: # mastodon.Mastodon.MastodonAPIError is unfortunately not in __init__.py
logger.error("Unknown Mastodon API Error.", exc_info=True) self.logger.error("Unknown Mastodon API Error.", exc_info=True)
return mentions return mentions
for status in all: for status in all:
if (status['type'] == 'mention' and status['status']['id'] not in self.seen_toots): if (status['type'] == 'mention' and status['status']['id'] not in self.seen_toots):
@ -96,7 +94,7 @@ class RetootBot(object):
:param mention: (report.Report object) :param mention: (report.Report object)
""" """
logger.info('Boosting toot from %s' % ( self.logger.info('Boosting toot from %s' % (
mention.format())) mention.format()))
self.m.status_reblog(mention.id) self.m.status_reblog(mention.id)
@ -128,13 +126,8 @@ class RetootBot(object):
if __name__ == '__main__': if __name__ == '__main__':
import ticketfrei
config = ticketfrei.get_config() config = ticketfrei.get_config()
fh = logging.FileHandler(config['logging']['logpath'])
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)
trigger = trigger.Trigger(config) trigger = trigger.Trigger(config)
bot = RetootBot(config) bot = RetootBot(config)
@ -145,11 +138,11 @@ if __name__ == '__main__':
except KeyboardInterrupt: except KeyboardInterrupt:
print("Good bye. Remember to restart the bot!") print("Good bye. Remember to restart the bot!")
except: except:
logger.error('Shutdown', exc_info=True) bot.logger.error('Shutdown', exc_info=True)
try: try:
mailer = sendmail.Mailer(config) mailer = sendmail.Mailer(config)
mailer.send('', config['mail']['contact'], mailer.send('', config['mail']['contact'],
'Ticketfrei Crash Report', 'Ticketfrei Crash Report',
attachment=config['logging']['logpath']) attachment=config['logging']['logpath'])
except: except:
logger.error('Mail sending failed', exc_info=True) bot.logger.error('Mail sending failed', exc_info=True)

View file

@ -6,12 +6,9 @@ import requests
import trigger import trigger
from time import sleep from time import sleep
import report import report
import logging import ticketfrei
import sendmail import sendmail
logger = logging.getLogger(__name__)
class RetweetBot(object): class RetweetBot(object):
""" """
This bot retweets all tweets which This bot retweets all tweets which
@ -32,6 +29,7 @@ class RetweetBot(object):
Tweet Tweet
""" """
self.config = config self.config = config
self.logger = ticketfrei.get_logger(config)
# initialize API access # initialize API access
keys = self.get_api_keys() keys = self.get_api_keys()
@ -120,13 +118,13 @@ class RetweetBot(object):
self.save_last() self.save_last()
return reports return reports
except tweepy.RateLimitError: except tweepy.RateLimitError:
logger.error("Twitter API Error: Rate Limit Exceeded", exc_info=True) self.logger.error("Twitter API Error: Rate Limit Exceeded", exc_info=True)
self.waitcounter += 60*15 + 1 self.waitcounter += 60*15 + 1
except requests.exceptions.ConnectionError: except requests.exceptions.ConnectionError:
logger.error("Twitter API Error: Bad Connection", exc_info=True) self.logger.error("Twitter API Error: Bad Connection", exc_info=True)
self.waitcounter += 10 self.waitcounter += 10
except tweepy.TweepError: except tweepy.TweepError:
logger.error("Twitter API Error: General Error", exc_info=True) self.logger.error("Twitter API Error: General Error", exc_info=True)
return [] return []
def repost(self, status): def repost(self, status):
@ -139,17 +137,17 @@ class RetweetBot(object):
while 1: while 1:
try: try:
self.api.retweet(status.id) self.api.retweet(status.id)
logger.info("Retweeted: " + status.format()) self.logger.info("Retweeted: " + status.format())
if status.id > self.last_mention: if status.id > self.last_mention:
self.last_mention = status.id self.last_mention = status.id
self.save_last() self.save_last()
return status.format() return status.format()
except requests.exceptions.ConnectionError: except requests.exceptions.ConnectionError:
logger.error("Twitter API Error: Bad Connection", exc_info=True) self.logger.error("Twitter API Error: Bad Connection", exc_info=True)
sleep(10) sleep(10)
# maybe one day we get rid of this error: # maybe one day we get rid of this error:
except tweepy.TweepError: except tweepy.TweepError:
logger.error("Twitter Error", exc_info=True) self.logger.error("Twitter Error", exc_info=True)
if status.id > self.last_mention: if status.id > self.last_mention:
self.last_mention = status.id self.last_mention = status.id
self.save_last() self.save_last()
@ -169,7 +167,7 @@ class RetweetBot(object):
self.api.update_status(status=text) self.api.update_status(status=text)
return return
except requests.exceptions.ConnectionError: except requests.exceptions.ConnectionError:
logger.error("Twitter API Error: Bad Connection", exc_info=True) self.logger.error("Twitter API Error: Bad Connection", exc_info=True)
sleep(10) sleep(10)
def flow(self, trigger, to_tweet=()): def flow(self, trigger, to_tweet=()):
@ -202,14 +200,8 @@ class RetweetBot(object):
if __name__ == "__main__": if __name__ == "__main__":
import ticketfrei
config = ticketfrei.get_config() config = ticketfrei.get_config()
# set log file
fh = logging.FileHandler(config['logging']['logpath'])
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)
# initialise trigger # initialise trigger
trigger = trigger.Trigger(config) trigger = trigger.Trigger(config)
@ -224,7 +216,7 @@ if __name__ == "__main__":
except KeyboardInterrupt: except KeyboardInterrupt:
print("Good bye. Remember to restart the bot!") print("Good bye. Remember to restart the bot!")
except: except:
logger.error('Shutdown', exc_info=True) bot.logger.error('Shutdown', exc_info=True)
bot.save_last() bot.save_last()
try: try:
mailer = sendmail.Mailer(config) mailer = sendmail.Mailer(config)
@ -232,4 +224,4 @@ if __name__ == "__main__":
'Ticketfrei Crash Report', 'Ticketfrei Crash Report',
attachment=config['logging']['logpath']) attachment=config['logging']['logpath'])
except: except:
logger.error('Mail sending failed', exc_info=True) bot.logger.error('Mail sending failed', exc_info=True)

View file

@ -10,10 +10,10 @@ from retweetbot import RetweetBot
from mailbot import Mailbot from mailbot import Mailbot
from trigger import Trigger from trigger import Trigger
def set_logfile(config): def get_logger(config):
logfile = config['logging']['logpath'] logpath = config['logging']['logpath']
logger = logging.getLogger() logger = logging.getLogger()
fh = logging.FileHandler(logfile) fh = logging.FileHandler(logpath)
fh.setLevel(logging.DEBUG) fh.setLevel(logging.DEBUG)
logger.addHandler(fh) logger.addHandler(fh)
return logger return logger
@ -25,11 +25,8 @@ def get_config():
return config return config
def run(): def run():
# get config
config = get_config() config = get_config()
logger = get_logger(config)
# set log file
logger = set_logfile(config)
# set trigger # set trigger
trigger = Trigger(config) trigger = Trigger(config)
@ -63,8 +60,8 @@ def run():
logger.error('Shutdown', exc_info=True) logger.error('Shutdown', exc_info=True)
for bot in bots: for bot in bots:
bot.save_last() bot.save_last()
try:
mailer = sendmail.Mailer(config) mailer = sendmail.Mailer(config)
try:
mailer.send('', config['mail']['contact'], mailer.send('', config['mail']['contact'],
'Ticketfrei Crash Report', 'Ticketfrei Crash Report',
attachment=config['logging']['logpath']) attachment=config['logging']['logpath'])