moved log to own class

This commit is contained in:
b3yond 2017-12-30 16:20:25 +01:00
parent 594b3fb5de
commit e64e3702f6
5 changed files with 49 additions and 96 deletions

2
.gitignore vendored
View file

@ -2,11 +2,11 @@
*.pyc *.pyc
.idea/ .idea/
last_mention last_mention
config.toml
ticketfrei.cfg ticketfrei.cfg
seen_toots.pickle seen_toots.pickle
seen_toots.pickle.part seen_toots.pickle.part
pip-selfcheck.json pip-selfcheck.json
config.toml
bin/ bin/
include/ include/
lib/ lib/

View file

@ -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'

32
log.py Normal file
View file

@ -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="")

View file

@ -6,10 +6,8 @@ import os
import pickle import pickle
import re import re
import time import time
import datetime
import trigger import trigger
import traceback import log
class RetootBot(object): class RetootBot(object):
def __init__(self, config, filter, logpath=None): def __init__(self, config, filter, logpath=None):
@ -25,31 +23,7 @@ class RetootBot(object):
except IOError: except IOError:
self.seen_toots = set() self.seen_toots = set()
if logpath: self.log = log.Log(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="")
def register(self): def register(self):
self.client_id = os.path.join( self.client_id = os.path.join(
@ -90,7 +64,7 @@ class RetootBot(object):
notification['status']['content']) notification['status']['content'])
if not self.filter.is_ok(text_content): if not self.filter.is_ok(text_content):
continue continue
self.log('Boosting toot from %s: %s' % ( self.log.log('Boosting toot from %s: %s' % (
#notification['status']['id'], #notification['status']['id'],
notification['status']['account']['acct'], notification['status']['account']['acct'],
notification['status']['content'])) notification['status']['content']))

View file

@ -1,14 +1,13 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import tweepy import tweepy
import os
import sys import sys
import datetime
import requests import requests
import pytoml as toml import pytoml as toml
import trigger import trigger
from time import sleep from time import sleep
import traceback import traceback
import log
class RetweetBot(object): class RetweetBot(object):
@ -54,13 +53,9 @@ class RetweetBot(object):
self.last_mention = self.get_history(self.historypath) self.last_mention = self.get_history(self.historypath)
self.trigger = trigger self.trigger = trigger
self.waitcounter = 0 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): def get_api_keys(self):
""" """
@ -81,27 +76,6 @@ class RetweetBot(object):
self.config['tuser']['access_token_key'], self.config['tuser']['access_token_secret']] self.config['tuser']['access_token_key'], self.config['tuser']['access_token_secret']]
return keys 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): def get_history(self, path):
""" This counter is needed to keep track of your mentions, so you """ This counter is needed to keep track of your mentions, so you
don't double RT them don't double RT them
@ -161,10 +135,10 @@ class RetweetBot(object):
mentions = self.api.mentions_timeline(since_id=self.last_mention) mentions = self.api.mentions_timeline(since_id=self.last_mention)
return mentions return mentions
except tweepy.RateLimitError: 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 self.waitcounter += 60*15 + 1
except requests.exceptions.ConnectionError: except requests.exceptions.ConnectionError:
self.log("Twitter API Error: Bad Connection.") self.log.log("Twitter API Error: Bad Connection.")
self.waitcounter += 10 self.waitcounter += 10
return None return None
@ -178,18 +152,18 @@ class RetweetBot(object):
while 1: while 1:
try: try:
self.api.retweet(status.id) 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: if status.id > self.last_mention:
self.last_mention = status.id self.last_mention = status.id
return self.format_mastodon(status) return self.format_mastodon(status)
# maybe one day we get rid of this error. If not, try to uncomment # maybe one day we get rid of this error. If not, try to uncomment
# these lines. # these lines.
except requests.exceptions.ConnectionError: except requests.exceptions.ConnectionError:
self.log("Twitter API Error: Bad Connection.") self.log.log("Twitter API Error: Bad Connection.")
sleep(10) sleep(10)
except tweepy.TweepError as error: except tweepy.TweepError as error:
self.log("Twitter Error " + error.api_code + ": " + error.reason + error.response) self.log.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 API Error: You probably already retweeted this tweet: " + status.text)
if status.id > self.last_mention: if status.id > self.last_mention:
self.last_mention = status.id self.last_mention = status.id
return None return None
@ -207,7 +181,7 @@ class RetweetBot(object):
self.api.update_status(status=post) self.api.update_status(status=post)
return return
except requests.exceptions.ConnectionError: except requests.exceptions.ConnectionError:
self.log("Twitter API Error: Bad Connection.") self.log.log("Twitter API Error: Bad Connection.")
sleep(10) sleep(10)
def flow(self, to_tweet=()): def flow(self, to_tweet=()):
@ -247,7 +221,7 @@ class RetweetBot(object):
logmessage = "Shit went wrong, closing down." logmessage = "Shit went wrong, closing down."
if self.screen_name: if self.screen_name:
logmessage = logmessage + " Sending message to " + self.screen_name logmessage = logmessage + " Sending message to " + self.screen_name
self.log(logmessage) self.log.log(logmessage)
if self.no_shutdown_contact: if self.no_shutdown_contact:
return return
self.save_last_mention() 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 :$") self.api.send_direct_message(self.screen_name, "Help! I broke down. restart me pls :$")
except: except:
# traceback.print_exc() # traceback.print_exc()
bot.log(traceback.extract_tb(sys.exc_info()[2])) self.log.log(traceback.extract_tb(sys.exc_info()[2]))
print() print()
@ -274,6 +248,6 @@ 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:
bot.log(traceback.extract_tb(sys.exc_info()[2])) bot.log.log(traceback.extract_tb(sys.exc_info()[2]))
print() print()
bot.shutdown() bot.shutdown()