From e64e3702f63ba9e3e8a0f33d6b44cec9aa3f157a Mon Sep 17 00:00:00 2001 From: b3yond Date: Sat, 30 Dec 2017 16:20:25 +0100 Subject: [PATCH] moved log to own class --- .gitignore | 2 +- config.toml | 27 -------------------------- log.py | 32 +++++++++++++++++++++++++++++++ retootbot.py | 32 +++---------------------------- retweetbot.py | 52 +++++++++++++-------------------------------------- 5 files changed, 49 insertions(+), 96 deletions(-) delete mode 100644 config.toml create mode 100644 log.py diff --git a/.gitignore b/.gitignore index 466f1e9..545a6b5 100644 --- a/.gitignore +++ b/.gitignore @@ -2,11 +2,11 @@ *.pyc .idea/ last_mention -config.toml ticketfrei.cfg seen_toots.pickle seen_toots.pickle.part pip-selfcheck.json +config.toml bin/ include/ lib/ diff --git a/config.toml b/config.toml deleted file mode 100644 index 10176df..0000000 --- a/config.toml +++ /dev/null @@ -1,27 +0,0 @@ -[mapp] -name = 'yourcity_ticketfrei' # :todo: where do you receive the app name? - -[muser] -email = 'youremail@server.tld' # E-mail address of your Mastodon account -password = 'yourpassword' # Password of your Mastodon account -server = 'yourmastodoninstance' # Instance where you have your Mastodon account - -[tapp] -consumer_key = "OD0CLn6twBxHjN2DqMkKuSvli" -consumer_secret = "XkvbViwjBWoWoJzIlseJLXmg2fqluq4HYqvwOwoSHGwxdTNi4l" - -shutdown_contact_userid = 801098086005243904 -shutdown_contact_screen_name = 'links_tech' - -[tuser] -access_token_key = "876046057721008128-J35moxFXUvLb24MnaMVbVpqiEtxBlcc" -access_token_secret = "I7PQZMHuJDS5WslgUhqEeZbEWGhwLhmOetvwFoTn8YDKW" - -# [trigger] -# goodlists are one regex per line. -# badlists are one badword per line. -# a message musst match at least one regex in goodlist and contain none of the badwords. -# the variables mention the directory where the lists are located, not the filenames. - -# goodlist_path = 'goodlists' -# blacklist_path = 'blacklists' diff --git a/log.py b/log.py new file mode 100644 index 0000000..8495284 --- /dev/null +++ b/log.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 + +import os +import datetime + +class Log(object): + + def __init__(self, logpath): + + # initialize logging + if logpath: + self.logpath = logpath + else: + self.logpath = os.path.join("logs", str(datetime.datetime.now())) + print("Path of logfile: " + self.logpath) + + def log(self, message): + """ + Writing an error message & sometimes a traceback to a logfile in logs/ + and prints it. + + :param message: (string) Log message to be displayed + """ + time = str(datetime.datetime.now()) + line = "[" + time + "] " + message + "\n" + with open(self.logpath, 'a') as f: + try: + f.write(line) + except UnicodeEncodeError: + self.log("Failed to save log message due to UTF-8 error. ") + print(line, end="") + diff --git a/retootbot.py b/retootbot.py index 7f48120..5332567 100644 --- a/retootbot.py +++ b/retootbot.py @@ -6,10 +6,8 @@ import os import pickle import re import time -import datetime import trigger -import traceback - +import log class RetootBot(object): def __init__(self, config, filter, logpath=None): @@ -25,31 +23,7 @@ class RetootBot(object): except IOError: self.seen_toots = set() - if logpath: - self.logpath = logpath - else: - self.logpath = os.path.join("logs", str(datetime.datetime.now())) - - def log(self, message, tb=False): - """ - Writing an error message to a logfile in logs/ and prints it. - - :param message: (string) Log message to be displayed - :param tb: String of the Traceback - """ - timenow = str(datetime.datetime.now()) - if tb: - message = message + " The traceback is located at " + os.path.join("logs" + timenow) - with open(os.path.join("logs", timenow), 'w+') as f: - f.write(tb) - line = "[" + timenow + "] " + message + "\n" - with open(self.logpath, 'a') as f: - try: - f.write(line) - except UnicodeEncodeError: - self.log("Failed to save log message due to UTF-8 error. ") - traceback.print_exc() - print(line, end="") + self.log = log.Log(logpath) def register(self): self.client_id = os.path.join( @@ -90,7 +64,7 @@ class RetootBot(object): notification['status']['content']) if not self.filter.is_ok(text_content): continue - self.log('Boosting toot from %s: %s' % ( + self.log.log('Boosting toot from %s: %s' % ( #notification['status']['id'], notification['status']['account']['acct'], notification['status']['content'])) diff --git a/retweetbot.py b/retweetbot.py index cd773da..b6147c0 100644 --- a/retweetbot.py +++ b/retweetbot.py @@ -1,14 +1,13 @@ #!/usr/bin/env python3 import tweepy -import os import sys -import datetime import requests import pytoml as toml import trigger from time import sleep import traceback +import log class RetweetBot(object): @@ -54,13 +53,9 @@ class RetweetBot(object): self.last_mention = self.get_history(self.historypath) self.trigger = trigger self.waitcounter = 0 + + self.log = log.log.log(logpath) - # initialize logging - if logpath: - self.logpath = logpath - else: - self.logpath = os.path.join("logs", str(datetime.datetime.now())) - print("Path of logfile: " + self.logpath) def get_api_keys(self): """ @@ -81,27 +76,6 @@ class RetweetBot(object): self.config['tuser']['access_token_key'], self.config['tuser']['access_token_secret']] return keys - def log(self, message, tb=False): - """ - Writing an error message to a logfile in logs/ and prints it. - - :param message: (string) Log message to be displayed - :param tb: String of the Traceback - """ - time = str(datetime.datetime.now()) - if tb: - message = message + " The traceback is located at " + os.path.join("logs" + time) - with open(os.path.join("logs", time), 'w+') as f: - f.write(tb) - line = "[" + time + "] " + message + "\n" - with open(self.logpath, 'a') as f: - try: - f.write(line) - except UnicodeEncodeError: - self.log("Failed to save log message due to UTF-8 error. ") - traceback.print_exc() - print(line, end="") - def get_history(self, path): """ This counter is needed to keep track of your mentions, so you don't double RT them @@ -161,10 +135,10 @@ class RetweetBot(object): mentions = self.api.mentions_timeline(since_id=self.last_mention) return mentions except tweepy.RateLimitError: - self.log("Twitter API Error: Rate Limit Exceeded.") + self.log.log("Twitter API Error: Rate Limit Exceeded.") self.waitcounter += 60*15 + 1 except requests.exceptions.ConnectionError: - self.log("Twitter API Error: Bad Connection.") + self.log.log("Twitter API Error: Bad Connection.") self.waitcounter += 10 return None @@ -178,18 +152,18 @@ class RetweetBot(object): while 1: try: self.api.retweet(status.id) - self.log("Retweeted: " + self.format_mastodon(status)) + self.log.log("Retweeted: " + self.format_mastodon(status)) if status.id > self.last_mention: self.last_mention = status.id return self.format_mastodon(status) # maybe one day we get rid of this error. If not, try to uncomment # these lines. except requests.exceptions.ConnectionError: - self.log("Twitter API Error: Bad Connection.") + self.log.log("Twitter API Error: Bad Connection.") sleep(10) except tweepy.TweepError as error: - self.log("Twitter Error " + error.api_code + ": " + error.reason + error.response) - # self.log("Twitter API Error: You probably already retweeted this tweet: " + status.text) + self.log.log("Twitter Error " + error.api_code + ": " + error.reason + error.response) + # self.log.log("Twitter API Error: You probably already retweeted this tweet: " + status.text) if status.id > self.last_mention: self.last_mention = status.id return None @@ -207,7 +181,7 @@ class RetweetBot(object): self.api.update_status(status=post) return except requests.exceptions.ConnectionError: - self.log("Twitter API Error: Bad Connection.") + self.log.log("Twitter API Error: Bad Connection.") sleep(10) def flow(self, to_tweet=()): @@ -247,7 +221,7 @@ class RetweetBot(object): logmessage = "Shit went wrong, closing down." if self.screen_name: logmessage = logmessage + " Sending message to " + self.screen_name - self.log(logmessage) + self.log.log(logmessage) if self.no_shutdown_contact: return self.save_last_mention() @@ -255,7 +229,7 @@ class RetweetBot(object): self.api.send_direct_message(self.screen_name, "Help! I broke down. restart me pls :$") except: # traceback.print_exc() - bot.log(traceback.extract_tb(sys.exc_info()[2])) + self.log.log(traceback.extract_tb(sys.exc_info()[2])) print() @@ -274,6 +248,6 @@ if __name__ == "__main__": except KeyboardInterrupt: print("Good bye! Remember to restart the bot.") except: - bot.log(traceback.extract_tb(sys.exc_info()[2])) + bot.log.log(traceback.extract_tb(sys.exc_info()[2])) print() bot.shutdown() \ No newline at end of file