added function to create logs

This commit is contained in:
b3yond 2017-07-20 22:30:43 +02:00
parent b3e00368c4
commit 2f998a6e83
3 changed files with 73 additions and 19 deletions

View file

@ -6,12 +6,12 @@ import os
import pickle import pickle
import re import re
import time import time
import datetime
import trigger import trigger
class RetootBot(object): class RetootBot(object):
def __init__(self, config, filter): def __init__(self, config, filter, logpath=None):
self.config = config self.config = config
self.filter = filter self.filter = filter
self.register() self.register()
@ -24,6 +24,28 @@ class RetootBot(object):
except IOError: except IOError:
self.seen_toots = set() self.seen_toots = set()
if logpath:
self.logpath = logpath
else:
self.logpath = os.path.join("logs", "{%Y-%m-%d_%H:%M:%S}".format(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
"""
time = "{%Y-%m-%d_%H:%M:%S}".format(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
with open(self.logpath, 'a') as f:
f.write(line)
print line
def register(self): def register(self):
self.client_id = os.path.join( self.client_id = os.path.join(
'appkeys', 'appkeys',
@ -63,7 +85,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
print('Boosting toot %d from %s: %s' % ( self.log('Boosting toot %d 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,6 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
import twitter import twitter
import os
import datetime import datetime
import requests import requests
import pytoml as toml import pytoml as toml
@ -22,8 +23,7 @@ class RetweetBot(object):
last_mention: the ID of the last tweet which mentioned you last_mention: the ID of the last tweet which mentioned you
""" """
def __init__(self, trigger, config, def __init__(self, trigger, config, historypath="last_mention", logpath=None):
historypath="last_mention"):
""" """
Initializes the bot and loads all the necessary data. Initializes the bot and loads all the necessary data.
@ -45,6 +45,11 @@ class RetweetBot(object):
self.no_shutdown_contact = True self.no_shutdown_contact = True
self.last_mention = self.get_history(self.historypath) self.last_mention = self.get_history(self.historypath)
self.trigger = trigger self.trigger = trigger
if logpath:
self.logpath = logpath
else:
self.logpath = os.path.join("logs", "{%Y-%m-%d_%H:%M:%S}".format(datetime.datetime.now()))
print "Path of logfile: " + self.logpath
def get_api_keys(self): def get_api_keys(self):
""" """
@ -68,6 +73,23 @@ class RetweetBot(object):
keys.append(self.config['tuser']['access_token_secret']) keys.append(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 = "{%Y-%m-%d_%H:%M:%S}".format(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
with open(self.logpath, 'a') as f:
f.write(line)
print line
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
@ -113,11 +135,10 @@ class RetweetBot(object):
mentions = self.api.GetMentions(since_id=self.last_mention) mentions = self.api.GetMentions(since_id=self.last_mention)
return mentions return mentions
except twitter.TwitterError: except twitter.TwitterError:
traceback.print_exc() self.log("Twitter API Error: Rate Limit Exceeded.")
print "[ERROR] Rate Limit Exceeded at {:%d.%m.%Y %H:%M:%S}".format(datetime.datetime.now()) # debug
sleep(60) sleep(60)
except requests.exceptions.ConnectionError: except requests.exceptions.ConnectionError:
print("[ERROR] Bad Connection.") self.log("Twitter API Error: Bad Connection.")
sleep(10) sleep(10)
def retweet(self, status): def retweet(self, status):
@ -130,21 +151,19 @@ class RetweetBot(object):
while 1: while 1:
try: try:
self.api.PostRetweet(status.id) self.api.PostRetweet(status.id)
print("Tweeted: " + self.format_mastodon(status)) # debug self.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 twitter.error.TwitterError: except twitter.error.TwitterError:
traceback.print_exc() self.log("Twitter API Error: You probably already retweeted this tweet: " + status.text)
print("[ERROR] probably you 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
except requests.exceptions.ConnectionError: except requests.exceptions.ConnectionError:
traceback.print_exc() self.log("Twitter API Error: Bad Connection.")
print("[ERROR] Bad Connection.")
sleep(10) sleep(10)
def tweet(self, post): def tweet(self, post):
@ -160,8 +179,7 @@ class RetweetBot(object):
self.api.PostUpdate(status=post) self.api.PostUpdate(status=post)
return return
except requests.exceptions.ConnectionError: except requests.exceptions.ConnectionError:
traceback.print_exc() self.log("Twitter API Error: Bad Connection.")
print("[ERROR] Bad Connection.")
sleep(10) sleep(10)
def flow(self, to_tweet=()): def flow(self, to_tweet=()):
@ -197,12 +215,19 @@ class RetweetBot(object):
def shutdown(self): def shutdown(self):
""" If something breaks, it shuts down the bot and messages the owner. """ If something breaks, it shuts down the bot and messages the owner.
""" """
print("[ERROR] Shit went wrong, closing down.") logmessage = "Shit went wrong, closing down."
if self.screen_name:
logmessage = logmessage + " Sending message to " + self.screen_name
self.log(logmessage)
if self.no_shutdown_contact: if self.no_shutdown_contact:
return return
self.save_last_mention() self.save_last_mention()
try:
self.api.PostDirectMessage("Help! I broke down. restart me pls :$", self.api.PostDirectMessage("Help! I broke down. restart me pls :$",
self.user_id, self.screen_name) self.user_id, self.screen_name)
except:
traceback.print_exc()
print
if __name__ == "__main__": if __name__ == "__main__":
@ -219,4 +244,5 @@ if __name__ == "__main__":
sleep(10) sleep(10)
except: except:
traceback.print_exc() traceback.print_exc()
print
bot.shutdown() bot.shutdown()

View file

@ -1,6 +1,10 @@
#!/usr/bin/env python
import pytoml as toml import pytoml as toml
import time import time
import traceback import traceback
import os
import datetime
from retootbot import RetootBot from retootbot import RetootBot
from retweetbot import RetweetBot from retweetbot import RetweetBot
@ -14,8 +18,10 @@ if __name__ == '__main__':
trigger = Trigger(config) trigger = Trigger(config)
mbot = RetootBot(config, trigger) logpath = os.path.join("logs", "{%Y-%m-%d_%H:%M:%S}".format(datetime.datetime.now()))
tbot = RetweetBot(trigger, config)
mbot = RetootBot(config, trigger, logpath=logpath)
tbot = RetweetBot(trigger, config, logpath=logpath)
try: try:
statuses = [] statuses = []