From ef62e85097d4b48f615979a67194366c79bdec09 Mon Sep 17 00:00:00 2001 From: Horse Man Date: Sun, 28 Aug 2016 00:31:54 +0200 Subject: [PATCH] init --- .gitignore | 7 ++++ slackorator.py | 44 +++++++++++++++++++++ slackorator.sample.cfg | 3 ++ tannlegen.py | 73 +++++++++++++++++++++++++++++++++++ test_rgb.py | 46 ++++++++++++++++++++++ tldb.py | 87 ++++++++++++++++++++++++++++++++++++++++++ tldb.sample.cfg | 6 +++ tweetorator.py | 73 +++++++++++++++++++++++++++++++++++ tweetorator.sample.cfg | 6 +++ 9 files changed, 345 insertions(+) create mode 100644 .gitignore create mode 100755 slackorator.py create mode 100644 slackorator.sample.cfg create mode 100755 tannlegen.py create mode 100755 test_rgb.py create mode 100755 tldb.py create mode 100644 tldb.sample.cfg create mode 100755 tweetorator.py create mode 100644 tweetorator.sample.cfg diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a18f371 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +*.pyc + +slackorator.cfg +tldb.cfg +tweetorator.cfg + +tannlegen.log diff --git a/slackorator.py b/slackorator.py new file mode 100755 index 0000000..c70f509 --- /dev/null +++ b/slackorator.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python +#coding: utf-8 +import ConfigParser +import json +import logging +import re +import requests +import sys + +""" +hello this is documentation +""" + +__version__ = "0.1" + +template = { + 'channel': '#tannlegen', + 'username': 'Tannlegen', + 'icon_emoji': ':beers:' +} + +configname = "slackorator.cfg" +cfg = ConfigParser.RawConfigParser() +cfg.read(configname) + +headers = {'content-type': 'application/json'} +hook = cfg.get("stuff", "hook") + +def post_confession(text): + # Return if text only contains whitespace + if re.search(r'\S', text) is None: + logging.info("Confession only containing whitespace. Abort") + return + + logging.info("Attempting to post confession to slack") + try: + r = requests.post(hook, + data=json.dumps(dict({'text': text}, **template)), + headers=headers) + r.raise_for_status() + except Exception, e: + logging.error("Failed to post confession to slack") + logging.exception(e) + pass diff --git a/slackorator.sample.cfg b/slackorator.sample.cfg new file mode 100644 index 0000000..2b716dd --- /dev/null +++ b/slackorator.sample.cfg @@ -0,0 +1,3 @@ +[stuff] +hook = https://hooks.slack.com/services/something/something/dangerzone + diff --git a/tannlegen.py b/tannlegen.py new file mode 100755 index 0000000..d9cbb65 --- /dev/null +++ b/tannlegen.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python +#coding: utf-8 +import sys +import urwid +import random +import tweetorator +import slackorator +import os +import logging +from time import sleep + +logging.basicConfig(format='[%(asctime)s] %(levelname)s: %(message)s', filename='tannlegen.log', level=logging.DEBUG) + +__version__ = "0.2" + +asciiheader = """ ___ ___ ___ ___ ___ ___ ___ ___ ___ \n /\ \ /\ \ /\__\ /\__\ /\__\ /\ \ /\ \ /\ \ /\__\ \n \:\ \ /::\ \ /::| | /::| | /:/ / /::\ \ /::\ \ /::\ \ /::| | \n \:\ \ /:/\:\ \ /:|:| | /:|:| | /:/ / /:/\:\ \ /:/\:\ \ /:/\:\ \ /:|:| | \n /::\ \ /::\~\:\ \ /:/|:| |__ /:/|:| |__ /:/ / /::\~\:\ \ /:/ \:\ \ /::\~\:\ \ /:/|:| |__ \n /:/\:\__\ /:/\:\ \:\__\ /:/ |:| /\__\ /:/ |:| /\__\ /:/__/ /:/\:\ \:\__\ /:/__/_\:\__\ /:/\:\ \:\__\ /:/ |:| /\__\\\n /:/ \/__/ \/__\:\/:/ / \/__|:|/:/ / \/__|:|/:/ / \:\ \ \:\~\:\ \/__/ \:\ /\ \/__/ \:\~\:\ \/__/ \/__|:|/:/ /\n/:/ / \::/ / |:/:/ / |:/:/ / \:\ \ \:\ \:\__\ \:\ \:\__\ \:\ \:\__\ |:/:/ / \n\/__/ /:/ / |::/ / |::/ / \:\ \ \:\ \/__/ \:\/:/ / \:\ \/__/ |::/ / \n /:/ / /:/ / /:/ / \:\__\ \:\__\ \::/ / \:\__\ /:/ / \n \/__/ \/__/ \/__/ \/__/ \/__/ \/__/ \/__/ \/__/ \n Landets frieste tannlegestol""" + +palette = [ + ('header', 'white', 'dark red'), + ('inside', '', 'dark green'), + ('outside', '', 'dark green'), + ('statusbar', 'white', 'dark red'), + ('err', 'black', 'dark red'), + ('suc', 'black', 'dark green')] + +def get_edit_box(prompt=None): + prompts = [u"What's happening?", + u"How are you feeling?", + u"What's going on?", + u"How are you doing?", + u"How's it going?"] + if not prompt: + prompt = random.choice(prompts) + prompt = prompt + ":\n" + return urwid.Edit(prompt) + +def exit_on_q(key): + if key in ('q', 'Q'): + raise urwid.ExitMainLoop() + +class ConfessionBox(urwid.Filler): + def keypress(self, size, key): + """ + if key == 'f12': + statusbar.base_widget.set_text([('err', u"test err"),('suc', u"test suc")]) + """ + if key != 'enter': + return super(ConfessionBox, self).keypress(size, key) + text = self.original_widget.get_edit_text() + tweetorator.post_confession(text) + #slackorator.post_confession(text) + self.original_widget = get_edit_box() + +outside = urwid.AttrMap(urwid.Divider(), 'outside') +inside = urwid.AttrMap(urwid.Divider(), 'inside') +text = urwid.AttrMap(urwid.Text(asciiheader, align='center'), 'header') +pile = urwid.Pile([]) +for item in [outside, inside, text, inside, outside]: + pile.contents.append((item, pile.options())) + +edit = get_edit_box() +bf = ConfessionBox(edit, valign='top') + +statusbar = urwid.AttrMap(urwid.Text(u"Status bar of epic failure"), 'statusbar') + +frame = urwid.Frame(bf, pile, statusbar) + +loop = urwid.MainLoop(frame, palette, unhandled_input=exit_on_q) +loop.widget = frame +try: + loop.run() +except: + logging.error("GREPTHISLINE: Random error in loop:%s" %sys.exc_info()[0]) diff --git a/test_rgb.py b/test_rgb.py new file mode 100755 index 0000000..30ebe4f --- /dev/null +++ b/test_rgb.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python +#coding: utf-8 +import urwid +from time import sleep + +palette = [ + ('streak', '', '', '', '#ffa', '#60a'), + ('inside', '', '', '', 'g38', '#808'), + ('outside', '', '', '', 'g27', '#a06'), + ('bg', '', '', '', '#ffa', '#606'), + ('err', '', '', '', '#000', '#f00'), + ('suc', '', '', '', '#000', '#0f0') ] + +def exit_on_q(key): + if key in ('q', 'Q'): + raise urwid.ExitMainLoop() + +class ConfessionBox(urwid.Filler): + def keypress(self, size, key): + if key == 'f12': + statusbar.base_widget.set_text([('err', u"db"),('suc', u"tw")]) + if key != 'enter': + return super(ConfessionBox, self).keypress(size, key) + text = self.original_widget.get_edit_text() + self.original_widget = urwid.Edit(text +"\n") + +placeholder = urwid.SolidFill() +loop = urwid.MainLoop(placeholder, palette, unhandled_input=exit_on_q) +loop.screen.set_terminal_properties(colors=256) + +outside = urwid.AttrMap(urwid.Divider(), 'outside') +inside = urwid.AttrMap(urwid.Divider(), 'inside') +text = urwid.AttrMap(urwid.Text(u"\nHello World\n", align='center'), 'streak') +pile = urwid.Pile([]) +for item in [outside, inside, text, inside, outside]: + pile.contents.append((item, pile.options())) + +edit = urwid.Edit(u"What?:\n") +bf = ConfessionBox(edit, valign='top') + +statusbar = urwid.AttrMap(urwid.Text(u"Status bar"), 'bg') + +frame = urwid.Frame(bf, pile, statusbar) + +loop.widget = frame +loop.run() diff --git a/tldb.py b/tldb.py new file mode 100755 index 0000000..0c469a2 --- /dev/null +++ b/tldb.py @@ -0,0 +1,87 @@ +#!/usr/bin/evn python +#coding: utf-8 +import MySQLdb +import json +import time +import ConfigParser +import locale +import logging +from datetime import datetime +from dateutil import tz + +__version__ = "1.3" + +_con = None +_cfg = None + +def loadCfg(configname): + global _cfg + _cfg = ConfigParser.RawConfigParser() + _cfg.read(configname) + +def connect(): + global _con + try: + _con = MySQLdb.connect(host=_cfg.get('DB', 'host'), user=_cfg.get('DB', 'username'), + db=_cfg.get('DB', 'dbname'), passwd=_cfg.get('DB', 'password'), connect_timeout=5) + except MySQLdb.OperationalError: + logging.error('Could not connect to database') + +def disconnect(): + if _con.open: + _con.close() + else: + logging.warn('Tried do disconnect from closed database connection') + +def addConfession(text, tweet=None): + connect() + cur = _con.cursor() + res = 0L + try: + if tweet: + created_at = _twitterUTCToLocal(json.loads(tweet)['created_at']) + tweet_id_str = str(json.loads(tweet)['id']) + sql = u'INSERT INTO confession (text, created_at, tweet_id_str) VALUES (%s, %s, %s)' + res = cur.execute(sql, (text, created_at, tweet_id_str)) + insertid = cur.lastrowid + else: + sql = u'INSERT INTO confession (text) VALUES (%s)' + res = cur.execute(sql, (text,)) + insertid = cur.lastrowid + except MySQLdb.Error as e: + logging.error(e) + pass + + if not res: + logging.warn('Result was empty') + else: + logging.debug('Inserted new confession with id: %s', insertid) + + cur.close() + disconnect() + return res + +def _twitterUTCToUTC(twittertime): + twitterutc = u'%a %b %d %H:%M:%S +0000 %Y' + utc = u'%Y-%m-%d %H:%M:%S' + + #curloc = locale.getlocale() + #locale.setlocale(locale.LC_ALL, ('en_US', 'UTF8')) + newtime = time.strftime(utc, time.strptime(twittertime, twitterutc)) + #locale.setlocale(locale.LC_ALL, curloc) + + return newtime + +def _twitterUTCToLocal(twittertime): + twitterutcformat = u'%a %b %d %H:%M:%S +0000 %Y' + datetimeformat = u'%Y-%m-%d %H:%M:%S' + + from_zone = tz.tzutc() + to_zone = tz.tzlocal() + + utc = datetime.strptime(twittertime, twitterutcformat).replace(tzinfo=from_zone) + #utc = utc.replace(tzinfo=from_zone) + + localtime = utc.astimezone(to_zone) + + return localtime.strftime('%Y-%m-%d %H:%M:%S') diff --git a/tldb.sample.cfg b/tldb.sample.cfg new file mode 100644 index 0000000..c998ca8 --- /dev/null +++ b/tldb.sample.cfg @@ -0,0 +1,6 @@ +[DB] +host = example.com +dbname = yolo_db +username = herp +password = derp + diff --git a/tweetorator.py b/tweetorator.py new file mode 100755 index 0000000..240eb96 --- /dev/null +++ b/tweetorator.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python +#coding: utf-8 +import sys +import twitter +import logging +import tldb +import re + +""" +THE NINJA IS STRONG WITH THIS ONE +TODO: FIX EVERYTHING +""" + +__version__ = "0.1" + +_api = None +initialized = False + +def init(): + global _api + +# TWITTER IS FUCKED. paalbra 2016-06-08 +# cfg = ConfigParser.RawConfigParser() +# cfg.read("tweetorator.cfg") +# consumer_key = cfg.get("twitter", "consumer_key") +# consumer_secret = cfg.get("twitter", "consumer_secret") +# access_token_key = cfg.get("twitter", "access_token_key") +# access_token_secret = cfg.get("twitter", "access_token_secret") +# _api = twitter.Api(consumer_key = consumer_key, +# consumer_secret = consumer_secret, +# access_token_key = access_token_key, +# access_token_secret = access_token_secret) +# +# logging.debug("VerifyCredentials: %s" % _api.VerifyCredentials()) + + tldb.loadCfg('tldb.cfg') + +def post_confession(text): + global _api + + # Return if text only contains whitespace + if re.search(r'\S', text) is None: + logging.info("Confession only containing whitespace. Abort") + return + + if not initialized: + init() + +## UNFUCK START + logging.info("Adding unfucked confession") + try: + tldb.addConfession(text) + except: + logging.error("%s, 0, text was >>%s<<" % (sys.exc_info()[0], text)) + pass +## UNFUCK END + +# THIS IS FUCKED BEFAUSE TWITTER IS FUCKED. paalbra 2016-06-08 +# if len(text) > 140: +# logging.info("Adding confession longer than 140") +# try: +# tldb.addConfession(text) +# except: +# logging.error("%s, 1, text was >>%s<<" % (sys.exc_info()[0], text)) +# pass +# else: +# logging.info("Adding confession shorter than 140") +# try: +# status = _api.PostUpdate(text) +# tldb.addConfession(text, status.AsJsonString()) +# except: +# logging.error("%s, 2, text was >>%s<<" % (sys.exc_info()[0], text)) +# pass diff --git a/tweetorator.sample.cfg b/tweetorator.sample.cfg new file mode 100644 index 0000000..51e0ac8 --- /dev/null +++ b/tweetorator.sample.cfg @@ -0,0 +1,6 @@ +[twitter] +access_token_key = very_secret_acces_token_key +access_token_secret = very_secret_access_token_secret +consumer_key = very_secret_consumer_key +consumer_secret = kindof_cute_consumer_secret +