From aef463304b43db23b03a338288249994d3e56640 Mon Sep 17 00:00:00 2001 From: supachris28 Date: Wed, 18 Jan 2017 10:09:40 +0000 Subject: [PATCH 1/6] wOT? --- splackt_actions/jira_slack.py | 47 +++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 splackt_actions/jira_slack.py diff --git a/splackt_actions/jira_slack.py b/splackt_actions/jira_slack.py new file mode 100644 index 0000000..ed1c91f --- /dev/null +++ b/splackt_actions/jira_slack.py @@ -0,0 +1,47 @@ +from slackbot.bot import respond_to, listen_to +import io +import re +import json +import requests +import slackbot_settings + +jira_reg = '(\w+-\d+)' +@listen_to(jira_reg) +@respond_to(jira_reg) +def check_slack(message, incoming_message): + jira_url = 'https://packtpub.atlassian.net/rest/api/2/search?jql=id=' + incoming_message + print('checking JIRA for ' + incoming_message) + r = requests.get(url=jira_url, headers={'Authorization': splackt_settings.JIRA_AUTH, 'Content-Type': 'application/json', 'accept':'application/json'}) + j = r.json() + if r.status_code == 200 and j['total'] == 1: + title = j['issues'][0]['fields']['summary'] + status = j['issues'][0]['fields']['status']['name'] + key = j['issues'][0]['key'] + url = 'https://packtpub.atlassian.net/browse/' + key + description = j['issues'][0]['fields']['description'] + creator = j['issues'][0]['fields']['creator']['displayName'] + assignee = '' + if j['issues'][0]['fields']['assignee']: + assignee = j['issues'][0]['fields']['assignee']['displayName'] + reply = key + ': `' + status + '`' + att = [ + { + 'fallback': description, + 'title': title, + 'title_link': url, + 'fields': [ + { + "title": "Creator", + "value": creator, + "short": True + }, + { + "title": "Assignee", + "value": assignee, + "short": True + } + ], + 'text': description + } + ] + message.send_webapi(reply, json.dumps(att)) From 8cb0cbc3eb9762f1f361b0ea367ca2a44a928049 Mon Sep 17 00:00:00 2001 From: supachris28 Date: Wed, 18 Jan 2017 10:10:30 +0000 Subject: [PATCH 2/6] Removed duplicate version --- splackt_actions/jira_slack.py | 47 ----------------------------------- 1 file changed, 47 deletions(-) delete mode 100644 splackt_actions/jira_slack.py diff --git a/splackt_actions/jira_slack.py b/splackt_actions/jira_slack.py deleted file mode 100644 index ed1c91f..0000000 --- a/splackt_actions/jira_slack.py +++ /dev/null @@ -1,47 +0,0 @@ -from slackbot.bot import respond_to, listen_to -import io -import re -import json -import requests -import slackbot_settings - -jira_reg = '(\w+-\d+)' -@listen_to(jira_reg) -@respond_to(jira_reg) -def check_slack(message, incoming_message): - jira_url = 'https://packtpub.atlassian.net/rest/api/2/search?jql=id=' + incoming_message - print('checking JIRA for ' + incoming_message) - r = requests.get(url=jira_url, headers={'Authorization': splackt_settings.JIRA_AUTH, 'Content-Type': 'application/json', 'accept':'application/json'}) - j = r.json() - if r.status_code == 200 and j['total'] == 1: - title = j['issues'][0]['fields']['summary'] - status = j['issues'][0]['fields']['status']['name'] - key = j['issues'][0]['key'] - url = 'https://packtpub.atlassian.net/browse/' + key - description = j['issues'][0]['fields']['description'] - creator = j['issues'][0]['fields']['creator']['displayName'] - assignee = '' - if j['issues'][0]['fields']['assignee']: - assignee = j['issues'][0]['fields']['assignee']['displayName'] - reply = key + ': `' + status + '`' - att = [ - { - 'fallback': description, - 'title': title, - 'title_link': url, - 'fields': [ - { - "title": "Creator", - "value": creator, - "short": True - }, - { - "title": "Assignee", - "value": assignee, - "short": True - } - ], - 'text': description - } - ] - message.send_webapi(reply, json.dumps(att)) From 28f38f847376595a25d6aeddbb2213c943dc98d2 Mon Sep 17 00:00:00 2001 From: supachris28 Date: Mon, 23 Jan 2017 08:28:20 +0000 Subject: [PATCH 3/6] Split Splackt into different plugins --- splackt_actions/splackt.py | 210 ------------------------------- splackt_actions/splackt_sales.py | 146 +++++++++++++++++++++ splackt_helper.py | 103 +++++++++++++++ 3 files changed, 249 insertions(+), 210 deletions(-) create mode 100644 splackt_actions/splackt_sales.py create mode 100644 splackt_helper.py diff --git a/splackt_actions/splackt.py b/splackt_actions/splackt.py index 087e323..c8d9d89 100644 --- a/splackt_actions/splackt.py +++ b/splackt_actions/splackt.py @@ -32,170 +32,6 @@ def joke(message, incoming_message): joke_response = requests.get('http://tambal.azurewebsites.net/joke/random') message.send_webapi(joke_response.json()['joke']) - -@respond_to("(.*)") -#@listen_to("(.*)") -def testLooking(message, incoming_message): - - incoming_message = incoming_message.replace('?', '') - - #data search variables - search_type = "" - search_content = "" - search_period = "" - - response = "You're looking for" - - if re.search(sales_keywords, incoming_message, re.IGNORECASE): - response += " sales (value)" - search_type = "sales-value" - - if re.search(quantity_keywords, incoming_message, re.IGNORECASE): - response += " sales (volume)" - search_type = "sales-volume" - - m = re.search(engagement_keywords, incoming_message, re.IGNORECASE) - if m: - response += " " + m.group(0) - search_type = "engagement" - - - response += " info" - - m = re.search(product_types, incoming_message, re.IGNORECASE) - if m: - response += " for " + m.group(0) - search_content = m.group(0) - - tagged = timex.tag(incoming_message) - print (tagged) - base_date = datetime.datetime.now() - grounded = timex.ground(tagged, base_date) - - print(grounded) - - m = re.search("TIMEX2 val=\"(.*)\"", grounded) - if m: - response += " over the period " + m.group(1) - search_period = m.group(1) - - - if response == "You're looking for info": - response = "I don't understand you.... try it again in Klingon" - return - - message.reply(response) - getSimpleData(message, incoming_message, search_type, search_content, search_period) - -def getSimpleData(message, incoming_message, search_type, search_content, search_period): - print("searching:" + search_type) - print("for: " + search_content) - - sql = "" - date_value = "" - table_name = "" - metric = "" - - if search_type == "sales-volume" or search_type == "sales-value": - if search_type == "sales-volume": - date_value = "order_transaction_date" - table_name = "home.fact_direct_sales" - metric = "COUNT(*) as `count`" - - if search_type == "sales-value": - date_value = "order_transaction_date" - table_name = "home.fact_direct_sales" - #metric = "CONCAT('£',CAST(SUM(order_gbp_paid) as char(10))) as `sum`" - metric = "SUM(order_gbp_paid) as `sum`" - - group_by = check_each(incoming_message, date_value) - sql = "SELECT " + group_by - if group_by != "": - sql += ", " - sql += metric + " FROM " + table_name + " WHERE 1=1 " - - - if search_content != "": - sql += " AND order_sale_type = '" + search_content + "'" - - if search_period != "": - print("search_period: " + search_period) - if len(search_period) == 4: - sql += " AND " + date_value + " BETWEEN '" + date_to_string(period_to_date(search_period)) + "' AND '" + date_to_string(date_add_year(period_to_date(search_period))) + "'" - if search_period.count('-') == 1: - sql += " AND " + date_value + " BETWEEN '" + date_to_string(period_to_date(search_period)) + "' AND '" + date_to_string(date_add_month(period_to_date(search_period))) + "'" - if search_period.count('-') == 2: - sql += " AND " + date_value + " BETWEEN '" + date_to_string(period_to_date(search_period)) + "' AND '" + date_to_string(date_add_day(period_to_date(search_period))) + "'" - if 'W' in search_period: - sql += " AND " + date_value + " BETWEEN '" + date_to_string(period_to_date(search_period)) + "' AND '" + date_to_string(date_add_week(period_to_date(search_period))) + "'" - else: - today = datetime.datetime.now() - this_month = period_to_date(str(today.year) + "-" + str(today.month)) - sql += " AND " + date_value + " BETWEEN '" + date_to_string(this_month) +"' AND '" + date_to_string(date_add_month(this_month)) + "'" - message.reply("No date found so looking for this month only...") - - if group_by != "": - sql += " GROUP BY " + group_by + " ORDER BY 1 " - - if sql != "": - print(sql) - message.reply("Looking...") - ox = titlator.db.p.ex(sql) - - - #print(ox) - if group_by: - plot_results(message, ox, "", re.search("(by|each) (day|week|month)", incoming_message.lower(), re.IGNORECASE).group(2), search_type) - message.reply('\n'.join(map(lambda x: '%s - %s' %x, ox))) - else: - message.reply("Answer: " + str(ox[0][0])) - else: - message.reply("I can't figure that out yet, ask someone in the data team...") - -def check_each(incoming_message, date_value): - m = re.search("(by|each) (day|week|month)", incoming_message.lower(), re.IGNORECASE) - if m: - if m.group(2) == "day": - return "DATE_FORMAT(" + date_value + ", '%Y-%m-%d')" - if m.group(2) == "week": - return "DATE_FORMAT(" + date_value + ", '%Y-%U')" - if m.group(2) == "month": - return "DATE_FORMAT(" + date_value + ", '%Y-%m-%b')" - return "" - -def period_to_date(search_period): - if 'W' in search_period: - search_period = str(Week.fromstring(search_period).monday()) - if search_period.count('-') < 2: - search_period += "-01" - if search_period.count('-') < 2: - search_period += "-01" - - return datetime.datetime.strptime(search_period, '%Y-%m-%d') - -def date_to_string(date_in): - return date_in.strftime('%Y-%m-%d') - -def date_add_month(date_in, months=1): - month = date_in.month - 1 + months - year = int(date_in.year + month / 12 ) - month = month % 12 + 1 - day = min(date_in.day,calendar.monthrange(year,month)[1]) - return datetime.date(year,month,day) - -def date_add_year(date_in, years=1): - year = date_in.year + years - month = date_in.month - day = min(date_in.day,calendar.monthrange(year,month)[1]) - return datetime.date(year,month,day) - -def date_add_day(date_in, days=1): - return date_in + datetime.timedelta(days=days) - -def date_add_week(date_in, weeks=1): - return date_in + datetime.timedelta(weeks=weeks) - - @respond_to('hello') def hello(message): message.reply('yo') @@ -272,49 +108,3 @@ def getme(message, tags =''): message.reply('from book: %s' % i.bname) message.reply('has score %.2f' % i.aboutness) message.reply('========') - -def plot_results(message, result, title, x_label, y_label): - data = [] - xTickMarks = [] - plt.style.use('fivethirtyeight') - fig = plt.figure() - ax = fig.add_subplot(111) - - for row in result: - data.append(int(row[1])) - xTickMarks.append(str(row[0])) - - - ## necessary variables - ind = np.arange(len(data)) # the x locations for the groups - width = 0.35 # the width of the bars - - ## the bars - rects1 = ax.bar(ind, data, width, - color='black', - error_kw=dict(elinewidth=2,ecolor='red')) - - - # axes and labels - ax.set_xlim(-width,len(ind)+width) - ax.set_ylim(0,max(data)) - - - ax.set_ylabel(y_label) - ax.set_xlabel(x_label) - ax.set_title(title) - - ax.set_xticks(ind+width) - xtickNames = ax.set_xticklabels(xTickMarks) - - plt.setp(xtickNames, rotation=45, fontsize=10) - fig.subplots_adjust(bottom=0.2,left=0.15) - filename = str(uuid.uuid1()) + '.png' - plt.savefig(filename) - post_image(filename, slackbot_settings.API_TOKEN, message.channel._body['id']) - - -def post_image(filename, token, channels): - f = {'file': (filename, open(filename, 'rb'), 'image/png', {'Expires':'0'})} - response = requests.post(url='https://slack.com/api/files.upload', data={'token': token, 'channels': channels, 'media': f}, headers={'Accept': 'application/json'}, files=f) - print(response.text) diff --git a/splackt_actions/splackt_sales.py b/splackt_actions/splackt_sales.py new file mode 100644 index 0000000..df44299 --- /dev/null +++ b/splackt_actions/splackt_sales.py @@ -0,0 +1,146 @@ +from slackbot.bot import respond_to, listen_to +import io +import re +import uuid +import py2neo +import dbapi as pdbc +import titlator, json +import requests +import timex +import datetime +import calendar +from isoweek import Week +import numpy as np +import matplotlib.pyplot as plt +import slackbot_settings +import splackt_helper + +#import pandas + +g = py2neo.Graph('http://neo4j:skynet@178.62.55.202:7474/db/data') + + +# standard word lists +product_types = "(book|ebook|video|subscription)" +sales_keywords = "(sales|value|revenue|quantity)" +quantity_keywords = "(many (\w+ )* ?sold|sell|quantity)" +engagement_keywords = "(page ?views|engagement)" + +@respond_to("(.*)") +#@listen_to("(.*)") +def testLooking(message, incoming_message): + + incoming_message = incoming_message.replace('?', '') + + #data search variables + search_type = "" + search_content = "" + search_period = "" + + response = "You're looking for" + + if re.search(sales_keywords, incoming_message, re.IGNORECASE): + response += " sales (value)" + search_type = "sales-value" + + if re.search(quantity_keywords, incoming_message, re.IGNORECASE): + response += " sales (volume)" + search_type = "sales-volume" + + m = re.search(engagement_keywords, incoming_message, re.IGNORECASE) + if m: + response += " " + m.group(0) + search_type = "engagement" + + + response += " info" + + m = re.search(product_types, incoming_message, re.IGNORECASE) + if m: + response += " for " + m.group(0) + search_content = m.group(0) + + tagged = timex.tag(incoming_message) + print (tagged) + base_date = datetime.datetime.now() + grounded = timex.ground(tagged, base_date) + + print(grounded) + + m = re.search("TIMEX2 val=\"(.*)\"", grounded) + if m: + response += " over the period " + m.group(1) + search_period = m.group(1) + + + if response == "You're looking for info": + response = "I don't understand you.... try it again in Klingon" + return + + message.reply(response) + getSimpleData(message, incoming_message, search_type, search_content, search_period) + +def getSimpleData(message, incoming_message, search_type, search_content, search_period): + print("searching:" + search_type) + print("for: " + search_content) + + sql = "" + date_value = "" + table_name = "" + metric = "" + + if search_type == "sales-volume" or search_type == "sales-value": + if search_type == "sales-volume": + date_value = "order_transaction_date" + table_name = "home.fact_direct_sales" + metric = "COUNT(*) as `count`" + + if search_type == "sales-value": + date_value = "order_transaction_date" + table_name = "home.fact_direct_sales" + #metric = "CONCAT('£',CAST(SUM(order_gbp_paid) as char(10))) as `sum`" + metric = "SUM(order_gbp_paid) as `sum`" + + group_by = splackt_helper.check_each(incoming_message, date_value) + sql = "SELECT " + group_by + if group_by != "": + sql += ", " + sql += metric + " FROM " + table_name + " WHERE 1=1 " + + + if search_content != "": + sql += " AND order_sale_type = '" + search_content + "'" + + if search_period != "": + print("search_period: " + search_period) + if len(search_period) == 4: + sql += " AND " + date_value + " BETWEEN '" + splackt_helper.date_to_string(splackt_helper.period_to_date(search_period)) + "' AND '" + splackt_helper.date_to_string(splackt_helper.date_add_year(splackt_helper.period_to_date(search_period))) + "'" + if search_period.count('-') == 1: + sql += " AND " + date_value + " BETWEEN '" + splackt_helper.date_to_string(splackt_helper.period_to_date(search_period)) + "' AND '" + splackt_helper.date_to_string(splackt_helper.date_add_month(splackt_helper.period_to_date(search_period))) + "'" + if search_period.count('-') == 2: + sql += " AND " + date_value + " BETWEEN '" + splackt_helper.date_to_string(splackt_helper.period_to_date(search_period)) + "' AND '" + splackt_helper.date_to_string(splackt_helper.date_add_day(splackt_helper.period_to_date(search_period))) + "'" + if 'W' in search_period: + sql += " AND " + date_value + " BETWEEN '" + splackt_helper.date_to_string(splackt_helper.period_to_date(search_period)) + "' AND '" + splackt_helper.date_to_string(splackt_helper.date_add_week(splackt_helper.period_to_date(search_period))) + "'" + else: + today = datetime.datetime.now() + this_month = splackt_helper.period_to_date(str(today.year) + "-" + str(today.month)) + sql += " AND " + date_value + " BETWEEN '" + splackt_helper.date_to_string(this_month) +"' AND '" + splackt_helper.date_to_string(splackt_helper.date_add_month(this_month)) + "'" + message.reply("No date found so looking for this month only...") + + if group_by != "": + sql += " GROUP BY " + group_by + " ORDER BY 1 " + + if sql != "": + print(sql) + message.reply("Looking...") + ox = titlator.db.p.ex(sql) + + + #print(ox) + if group_by: + splackt_helper.plot_results(message, ox, "", re.search("(by|each) (day|week|month)", incoming_message.lower(), re.IGNORECASE).group(2), search_type) + message.reply('\n'.join(map(lambda x: '%s - %s' %x, ox))) + else: + message.reply("Answer: " + str(ox[0][0])) + else: + message.reply("I can't figure that out yet, ask someone in the data team...") diff --git a/splackt_helper.py b/splackt_helper.py new file mode 100644 index 0000000..4793f32 --- /dev/null +++ b/splackt_helper.py @@ -0,0 +1,103 @@ +import io +import re +import uuid +import py2neo +import dbapi as pdbc +import titlator, json +import requests +import timex +import datetime +import calendar +from isoweek import Week +import numpy as np +import matplotlib.pyplot as plt +import slackbot_settings + +def plot_results(message, result, title, x_label, y_label): + data = [] + xTickMarks = [] + plt.style.use('fivethirtyeight') + fig = plt.figure() + ax = fig.add_subplot(111) + + for row in result: + data.append(int(row[1])) + xTickMarks.append(str(row[0])) + + + ## necessary variables + ind = np.arange(len(data)) # the x locations for the groups + width = 0.35 # the width of the bars + + ## the bars + rects1 = ax.bar(ind, data, width, + color='black', + error_kw=dict(elinewidth=2,ecolor='red')) + + + # axes and labels + ax.set_xlim(-width,len(ind)+width) + ax.set_ylim(0,max(data)) + + + ax.set_ylabel(y_label) + ax.set_xlabel(x_label) + ax.set_title(title) + + ax.set_xticks(ind+width) + xtickNames = ax.set_xticklabels(xTickMarks) + + plt.setp(xtickNames, rotation=45, fontsize=10) + fig.subplots_adjust(bottom=0.2,left=0.15) + filename = str(uuid.uuid1()) + '.png' + plt.savefig(filename) + post_image(filename, slackbot_settings.API_TOKEN, message.channel._body['id']) + + +def post_image(filename, token, channels): + f = {'file': (filename, open(filename, 'rb'), 'image/png', {'Expires':'0'})} + response = requests.post(url='https://slack.com/api/files.upload', data={'token': token, 'channels': channels, 'media': f}, headers={'Accept': 'application/json'}, files=f) + print(response.text) + + def check_each(incoming_message, date_value): + m = re.search("(by|each) (day|week|month)", incoming_message.lower(), re.IGNORECASE) + if m: + if m.group(2) == "day": + return "DATE_FORMAT(" + date_value + ", '%Y-%m-%d')" + if m.group(2) == "week": + return "DATE_FORMAT(" + date_value + ", '%Y-%U')" + if m.group(2) == "month": + return "DATE_FORMAT(" + date_value + ", '%Y-%m-%b')" + return "" + +def period_to_date(search_period): + if 'W' in search_period: + search_period = str(Week.fromstring(search_period).monday()) + if search_period.count('-') < 2: + search_period += "-01" + if search_period.count('-') < 2: + search_period += "-01" + + return datetime.datetime.strptime(search_period, '%Y-%m-%d') + +def date_to_string(date_in): + return date_in.strftime('%Y-%m-%d') + +def date_add_month(date_in, months=1): + month = date_in.month - 1 + months + year = int(date_in.year + month / 12 ) + month = month % 12 + 1 + day = min(date_in.day,calendar.monthrange(year,month)[1]) + return datetime.date(year,month,day) + +def date_add_year(date_in, years=1): + year = date_in.year + years + month = date_in.month + day = min(date_in.day,calendar.monthrange(year,month)[1]) + return datetime.date(year,month,day) + +def date_add_day(date_in, days=1): + return date_in + datetime.timedelta(days=days) + +def date_add_week(date_in, weeks=1): + return date_in + datetime.timedelta(weeks=weeks) From c7a760a6a6673d846754231ce1f093afe847eb4c Mon Sep 17 00:00:00 2001 From: supachris28 Date: Mon, 23 Jan 2017 08:29:06 +0000 Subject: [PATCH 4/6] Revert "Split Splackt into different plugins" This reverts commit 28f38f847376595a25d6aeddbb2213c943dc98d2. --- splackt_actions/splackt.py | 210 +++++++++++++++++++++++++++++++ splackt_actions/splackt_sales.py | 146 --------------------- splackt_helper.py | 103 --------------- 3 files changed, 210 insertions(+), 249 deletions(-) delete mode 100644 splackt_actions/splackt_sales.py delete mode 100644 splackt_helper.py diff --git a/splackt_actions/splackt.py b/splackt_actions/splackt.py index c8d9d89..087e323 100644 --- a/splackt_actions/splackt.py +++ b/splackt_actions/splackt.py @@ -32,6 +32,170 @@ def joke(message, incoming_message): joke_response = requests.get('http://tambal.azurewebsites.net/joke/random') message.send_webapi(joke_response.json()['joke']) + +@respond_to("(.*)") +#@listen_to("(.*)") +def testLooking(message, incoming_message): + + incoming_message = incoming_message.replace('?', '') + + #data search variables + search_type = "" + search_content = "" + search_period = "" + + response = "You're looking for" + + if re.search(sales_keywords, incoming_message, re.IGNORECASE): + response += " sales (value)" + search_type = "sales-value" + + if re.search(quantity_keywords, incoming_message, re.IGNORECASE): + response += " sales (volume)" + search_type = "sales-volume" + + m = re.search(engagement_keywords, incoming_message, re.IGNORECASE) + if m: + response += " " + m.group(0) + search_type = "engagement" + + + response += " info" + + m = re.search(product_types, incoming_message, re.IGNORECASE) + if m: + response += " for " + m.group(0) + search_content = m.group(0) + + tagged = timex.tag(incoming_message) + print (tagged) + base_date = datetime.datetime.now() + grounded = timex.ground(tagged, base_date) + + print(grounded) + + m = re.search("TIMEX2 val=\"(.*)\"", grounded) + if m: + response += " over the period " + m.group(1) + search_period = m.group(1) + + + if response == "You're looking for info": + response = "I don't understand you.... try it again in Klingon" + return + + message.reply(response) + getSimpleData(message, incoming_message, search_type, search_content, search_period) + +def getSimpleData(message, incoming_message, search_type, search_content, search_period): + print("searching:" + search_type) + print("for: " + search_content) + + sql = "" + date_value = "" + table_name = "" + metric = "" + + if search_type == "sales-volume" or search_type == "sales-value": + if search_type == "sales-volume": + date_value = "order_transaction_date" + table_name = "home.fact_direct_sales" + metric = "COUNT(*) as `count`" + + if search_type == "sales-value": + date_value = "order_transaction_date" + table_name = "home.fact_direct_sales" + #metric = "CONCAT('£',CAST(SUM(order_gbp_paid) as char(10))) as `sum`" + metric = "SUM(order_gbp_paid) as `sum`" + + group_by = check_each(incoming_message, date_value) + sql = "SELECT " + group_by + if group_by != "": + sql += ", " + sql += metric + " FROM " + table_name + " WHERE 1=1 " + + + if search_content != "": + sql += " AND order_sale_type = '" + search_content + "'" + + if search_period != "": + print("search_period: " + search_period) + if len(search_period) == 4: + sql += " AND " + date_value + " BETWEEN '" + date_to_string(period_to_date(search_period)) + "' AND '" + date_to_string(date_add_year(period_to_date(search_period))) + "'" + if search_period.count('-') == 1: + sql += " AND " + date_value + " BETWEEN '" + date_to_string(period_to_date(search_period)) + "' AND '" + date_to_string(date_add_month(period_to_date(search_period))) + "'" + if search_period.count('-') == 2: + sql += " AND " + date_value + " BETWEEN '" + date_to_string(period_to_date(search_period)) + "' AND '" + date_to_string(date_add_day(period_to_date(search_period))) + "'" + if 'W' in search_period: + sql += " AND " + date_value + " BETWEEN '" + date_to_string(period_to_date(search_period)) + "' AND '" + date_to_string(date_add_week(period_to_date(search_period))) + "'" + else: + today = datetime.datetime.now() + this_month = period_to_date(str(today.year) + "-" + str(today.month)) + sql += " AND " + date_value + " BETWEEN '" + date_to_string(this_month) +"' AND '" + date_to_string(date_add_month(this_month)) + "'" + message.reply("No date found so looking for this month only...") + + if group_by != "": + sql += " GROUP BY " + group_by + " ORDER BY 1 " + + if sql != "": + print(sql) + message.reply("Looking...") + ox = titlator.db.p.ex(sql) + + + #print(ox) + if group_by: + plot_results(message, ox, "", re.search("(by|each) (day|week|month)", incoming_message.lower(), re.IGNORECASE).group(2), search_type) + message.reply('\n'.join(map(lambda x: '%s - %s' %x, ox))) + else: + message.reply("Answer: " + str(ox[0][0])) + else: + message.reply("I can't figure that out yet, ask someone in the data team...") + +def check_each(incoming_message, date_value): + m = re.search("(by|each) (day|week|month)", incoming_message.lower(), re.IGNORECASE) + if m: + if m.group(2) == "day": + return "DATE_FORMAT(" + date_value + ", '%Y-%m-%d')" + if m.group(2) == "week": + return "DATE_FORMAT(" + date_value + ", '%Y-%U')" + if m.group(2) == "month": + return "DATE_FORMAT(" + date_value + ", '%Y-%m-%b')" + return "" + +def period_to_date(search_period): + if 'W' in search_period: + search_period = str(Week.fromstring(search_period).monday()) + if search_period.count('-') < 2: + search_period += "-01" + if search_period.count('-') < 2: + search_period += "-01" + + return datetime.datetime.strptime(search_period, '%Y-%m-%d') + +def date_to_string(date_in): + return date_in.strftime('%Y-%m-%d') + +def date_add_month(date_in, months=1): + month = date_in.month - 1 + months + year = int(date_in.year + month / 12 ) + month = month % 12 + 1 + day = min(date_in.day,calendar.monthrange(year,month)[1]) + return datetime.date(year,month,day) + +def date_add_year(date_in, years=1): + year = date_in.year + years + month = date_in.month + day = min(date_in.day,calendar.monthrange(year,month)[1]) + return datetime.date(year,month,day) + +def date_add_day(date_in, days=1): + return date_in + datetime.timedelta(days=days) + +def date_add_week(date_in, weeks=1): + return date_in + datetime.timedelta(weeks=weeks) + + @respond_to('hello') def hello(message): message.reply('yo') @@ -108,3 +272,49 @@ def getme(message, tags =''): message.reply('from book: %s' % i.bname) message.reply('has score %.2f' % i.aboutness) message.reply('========') + +def plot_results(message, result, title, x_label, y_label): + data = [] + xTickMarks = [] + plt.style.use('fivethirtyeight') + fig = plt.figure() + ax = fig.add_subplot(111) + + for row in result: + data.append(int(row[1])) + xTickMarks.append(str(row[0])) + + + ## necessary variables + ind = np.arange(len(data)) # the x locations for the groups + width = 0.35 # the width of the bars + + ## the bars + rects1 = ax.bar(ind, data, width, + color='black', + error_kw=dict(elinewidth=2,ecolor='red')) + + + # axes and labels + ax.set_xlim(-width,len(ind)+width) + ax.set_ylim(0,max(data)) + + + ax.set_ylabel(y_label) + ax.set_xlabel(x_label) + ax.set_title(title) + + ax.set_xticks(ind+width) + xtickNames = ax.set_xticklabels(xTickMarks) + + plt.setp(xtickNames, rotation=45, fontsize=10) + fig.subplots_adjust(bottom=0.2,left=0.15) + filename = str(uuid.uuid1()) + '.png' + plt.savefig(filename) + post_image(filename, slackbot_settings.API_TOKEN, message.channel._body['id']) + + +def post_image(filename, token, channels): + f = {'file': (filename, open(filename, 'rb'), 'image/png', {'Expires':'0'})} + response = requests.post(url='https://slack.com/api/files.upload', data={'token': token, 'channels': channels, 'media': f}, headers={'Accept': 'application/json'}, files=f) + print(response.text) diff --git a/splackt_actions/splackt_sales.py b/splackt_actions/splackt_sales.py deleted file mode 100644 index df44299..0000000 --- a/splackt_actions/splackt_sales.py +++ /dev/null @@ -1,146 +0,0 @@ -from slackbot.bot import respond_to, listen_to -import io -import re -import uuid -import py2neo -import dbapi as pdbc -import titlator, json -import requests -import timex -import datetime -import calendar -from isoweek import Week -import numpy as np -import matplotlib.pyplot as plt -import slackbot_settings -import splackt_helper - -#import pandas - -g = py2neo.Graph('http://neo4j:skynet@178.62.55.202:7474/db/data') - - -# standard word lists -product_types = "(book|ebook|video|subscription)" -sales_keywords = "(sales|value|revenue|quantity)" -quantity_keywords = "(many (\w+ )* ?sold|sell|quantity)" -engagement_keywords = "(page ?views|engagement)" - -@respond_to("(.*)") -#@listen_to("(.*)") -def testLooking(message, incoming_message): - - incoming_message = incoming_message.replace('?', '') - - #data search variables - search_type = "" - search_content = "" - search_period = "" - - response = "You're looking for" - - if re.search(sales_keywords, incoming_message, re.IGNORECASE): - response += " sales (value)" - search_type = "sales-value" - - if re.search(quantity_keywords, incoming_message, re.IGNORECASE): - response += " sales (volume)" - search_type = "sales-volume" - - m = re.search(engagement_keywords, incoming_message, re.IGNORECASE) - if m: - response += " " + m.group(0) - search_type = "engagement" - - - response += " info" - - m = re.search(product_types, incoming_message, re.IGNORECASE) - if m: - response += " for " + m.group(0) - search_content = m.group(0) - - tagged = timex.tag(incoming_message) - print (tagged) - base_date = datetime.datetime.now() - grounded = timex.ground(tagged, base_date) - - print(grounded) - - m = re.search("TIMEX2 val=\"(.*)\"", grounded) - if m: - response += " over the period " + m.group(1) - search_period = m.group(1) - - - if response == "You're looking for info": - response = "I don't understand you.... try it again in Klingon" - return - - message.reply(response) - getSimpleData(message, incoming_message, search_type, search_content, search_period) - -def getSimpleData(message, incoming_message, search_type, search_content, search_period): - print("searching:" + search_type) - print("for: " + search_content) - - sql = "" - date_value = "" - table_name = "" - metric = "" - - if search_type == "sales-volume" or search_type == "sales-value": - if search_type == "sales-volume": - date_value = "order_transaction_date" - table_name = "home.fact_direct_sales" - metric = "COUNT(*) as `count`" - - if search_type == "sales-value": - date_value = "order_transaction_date" - table_name = "home.fact_direct_sales" - #metric = "CONCAT('£',CAST(SUM(order_gbp_paid) as char(10))) as `sum`" - metric = "SUM(order_gbp_paid) as `sum`" - - group_by = splackt_helper.check_each(incoming_message, date_value) - sql = "SELECT " + group_by - if group_by != "": - sql += ", " - sql += metric + " FROM " + table_name + " WHERE 1=1 " - - - if search_content != "": - sql += " AND order_sale_type = '" + search_content + "'" - - if search_period != "": - print("search_period: " + search_period) - if len(search_period) == 4: - sql += " AND " + date_value + " BETWEEN '" + splackt_helper.date_to_string(splackt_helper.period_to_date(search_period)) + "' AND '" + splackt_helper.date_to_string(splackt_helper.date_add_year(splackt_helper.period_to_date(search_period))) + "'" - if search_period.count('-') == 1: - sql += " AND " + date_value + " BETWEEN '" + splackt_helper.date_to_string(splackt_helper.period_to_date(search_period)) + "' AND '" + splackt_helper.date_to_string(splackt_helper.date_add_month(splackt_helper.period_to_date(search_period))) + "'" - if search_period.count('-') == 2: - sql += " AND " + date_value + " BETWEEN '" + splackt_helper.date_to_string(splackt_helper.period_to_date(search_period)) + "' AND '" + splackt_helper.date_to_string(splackt_helper.date_add_day(splackt_helper.period_to_date(search_period))) + "'" - if 'W' in search_period: - sql += " AND " + date_value + " BETWEEN '" + splackt_helper.date_to_string(splackt_helper.period_to_date(search_period)) + "' AND '" + splackt_helper.date_to_string(splackt_helper.date_add_week(splackt_helper.period_to_date(search_period))) + "'" - else: - today = datetime.datetime.now() - this_month = splackt_helper.period_to_date(str(today.year) + "-" + str(today.month)) - sql += " AND " + date_value + " BETWEEN '" + splackt_helper.date_to_string(this_month) +"' AND '" + splackt_helper.date_to_string(splackt_helper.date_add_month(this_month)) + "'" - message.reply("No date found so looking for this month only...") - - if group_by != "": - sql += " GROUP BY " + group_by + " ORDER BY 1 " - - if sql != "": - print(sql) - message.reply("Looking...") - ox = titlator.db.p.ex(sql) - - - #print(ox) - if group_by: - splackt_helper.plot_results(message, ox, "", re.search("(by|each) (day|week|month)", incoming_message.lower(), re.IGNORECASE).group(2), search_type) - message.reply('\n'.join(map(lambda x: '%s - %s' %x, ox))) - else: - message.reply("Answer: " + str(ox[0][0])) - else: - message.reply("I can't figure that out yet, ask someone in the data team...") diff --git a/splackt_helper.py b/splackt_helper.py deleted file mode 100644 index 4793f32..0000000 --- a/splackt_helper.py +++ /dev/null @@ -1,103 +0,0 @@ -import io -import re -import uuid -import py2neo -import dbapi as pdbc -import titlator, json -import requests -import timex -import datetime -import calendar -from isoweek import Week -import numpy as np -import matplotlib.pyplot as plt -import slackbot_settings - -def plot_results(message, result, title, x_label, y_label): - data = [] - xTickMarks = [] - plt.style.use('fivethirtyeight') - fig = plt.figure() - ax = fig.add_subplot(111) - - for row in result: - data.append(int(row[1])) - xTickMarks.append(str(row[0])) - - - ## necessary variables - ind = np.arange(len(data)) # the x locations for the groups - width = 0.35 # the width of the bars - - ## the bars - rects1 = ax.bar(ind, data, width, - color='black', - error_kw=dict(elinewidth=2,ecolor='red')) - - - # axes and labels - ax.set_xlim(-width,len(ind)+width) - ax.set_ylim(0,max(data)) - - - ax.set_ylabel(y_label) - ax.set_xlabel(x_label) - ax.set_title(title) - - ax.set_xticks(ind+width) - xtickNames = ax.set_xticklabels(xTickMarks) - - plt.setp(xtickNames, rotation=45, fontsize=10) - fig.subplots_adjust(bottom=0.2,left=0.15) - filename = str(uuid.uuid1()) + '.png' - plt.savefig(filename) - post_image(filename, slackbot_settings.API_TOKEN, message.channel._body['id']) - - -def post_image(filename, token, channels): - f = {'file': (filename, open(filename, 'rb'), 'image/png', {'Expires':'0'})} - response = requests.post(url='https://slack.com/api/files.upload', data={'token': token, 'channels': channels, 'media': f}, headers={'Accept': 'application/json'}, files=f) - print(response.text) - - def check_each(incoming_message, date_value): - m = re.search("(by|each) (day|week|month)", incoming_message.lower(), re.IGNORECASE) - if m: - if m.group(2) == "day": - return "DATE_FORMAT(" + date_value + ", '%Y-%m-%d')" - if m.group(2) == "week": - return "DATE_FORMAT(" + date_value + ", '%Y-%U')" - if m.group(2) == "month": - return "DATE_FORMAT(" + date_value + ", '%Y-%m-%b')" - return "" - -def period_to_date(search_period): - if 'W' in search_period: - search_period = str(Week.fromstring(search_period).monday()) - if search_period.count('-') < 2: - search_period += "-01" - if search_period.count('-') < 2: - search_period += "-01" - - return datetime.datetime.strptime(search_period, '%Y-%m-%d') - -def date_to_string(date_in): - return date_in.strftime('%Y-%m-%d') - -def date_add_month(date_in, months=1): - month = date_in.month - 1 + months - year = int(date_in.year + month / 12 ) - month = month % 12 + 1 - day = min(date_in.day,calendar.monthrange(year,month)[1]) - return datetime.date(year,month,day) - -def date_add_year(date_in, years=1): - year = date_in.year + years - month = date_in.month - day = min(date_in.day,calendar.monthrange(year,month)[1]) - return datetime.date(year,month,day) - -def date_add_day(date_in, days=1): - return date_in + datetime.timedelta(days=days) - -def date_add_week(date_in, weeks=1): - return date_in + datetime.timedelta(weeks=weeks) From fab1d40863f466b806a3a4b005713d75df069a3a Mon Sep 17 00:00:00 2001 From: supachris28 Date: Mon, 23 Jan 2017 09:25:59 +0000 Subject: [PATCH 5/6] Fixes for Python 3 --- splackt_actions/splackt_sales.py | 89 ++++++++++++++++ splackt_helper.py | 175 +++++++++++++++++++++++++++++++ 2 files changed, 264 insertions(+) create mode 100644 splackt_actions/splackt_sales.py create mode 100644 splackt_helper.py diff --git a/splackt_actions/splackt_sales.py b/splackt_actions/splackt_sales.py new file mode 100644 index 0000000..7edcc07 --- /dev/null +++ b/splackt_actions/splackt_sales.py @@ -0,0 +1,89 @@ +# coding=utf-8 + +from slackbot.bot import respond_to, listen_to +import io +import re +import uuid +import py2neo +import dbapi as pdbc +import titlator, json +import requests +import timex +import datetime +import calendar +from isoweek import Week +import numpy as np +import matplotlib +import matplotlib.pyplot as plt +import slackbot_settings +import splackt_helper + +#import pandas + +g = py2neo.Graph('http://neo4j:skynet@178.62.55.202:7474/db/data') + + +#Change mpl backend +matplotlib.use('Agg') + + +# standard word lists +product_types = "(book|ebook|video|subscription)" +sales_keywords = "(sales|value|revenue|quantity)" +quantity_keywords = "(many (\w+ )* ?sold|sell|quantity)" +engagement_keywords = "(page ?views|engagement)" + + +@respond_to("(.*)") +#@listen_to("(.*)") +def testLooking(message, incoming_message): + + incoming_message = incoming_message.replace('?', '') + + #data search variables + search_type = "" + search_content = "" + search_period = "" + + response = "You're looking for" + + if re.search(sales_keywords, incoming_message, re.IGNORECASE): + response += " sales (value)" + search_type = "sales-value" + + if re.search(quantity_keywords, incoming_message, re.IGNORECASE): + response += " sales (volume)" + search_type = "sales-volume" + + m = re.search(engagement_keywords, incoming_message, re.IGNORECASE) + if m: + response += " " + m.group(0) + search_type = "engagement" + + + response += " info" + + m = re.search(product_types, incoming_message, re.IGNORECASE) + if m: + response += " for " + m.group(0) + search_content = m.group(0) + + tagged = timex.tag(incoming_message) + print (tagged) + base_date = datetime.datetime.now() + grounded = timex.ground(tagged, base_date) + + print(grounded) + + m = re.search("TIMEX2 val=\"(.*)\"", grounded) + if m: + response += " over the period " + m.group(1) + search_period = m.group(1) + + + if response == "You're looking for info": + response = "I don't understand you.... try it again in Klingon" + return + + message.reply(response) + splackt_helper.getSimpleSalesData(message, incoming_message, search_type, search_content, search_period) diff --git a/splackt_helper.py b/splackt_helper.py new file mode 100644 index 0000000..27becc2 --- /dev/null +++ b/splackt_helper.py @@ -0,0 +1,175 @@ +# coding=utf-8 + +from slackbot.bot import respond_to, listen_to +import io +import re +import uuid +import py2neo +import dbapi as pdbc +import titlator, json +import requests +import timex +import datetime +import calendar +from isoweek import Week +import numpy as np +import matplotlib +import matplotlib.pyplot as plt +import slackbot_settings + + +def getSimpleSalesData(message, incoming_message, search_type, search_content, search_period): + print("searching:" + search_type) + print("for: " + search_content) + + sql = "" + date_value = "" + table_name = "" + metric = "" + + if search_type == "sales-volume" or search_type == "sales-value": + if search_type == "sales-volume": + date_value = "order_transaction_date" + table_name = "home.fact_direct_sales" + metric = "COUNT(*) as `count`" + + if search_type == "sales-value": + date_value = "order_transaction_date" + table_name = "home.fact_direct_sales" + #metric = "CONCAT('£',CAST(SUM(order_gbp_paid) as char(10))) as `sum`" + metric = "SUM(order_gbp_paid) as `sum`" + + group_by = check_each(incoming_message, date_value) + sql = "SELECT " + group_by + if group_by != "": + sql += ", " + sql += metric + " FROM " + table_name + " WHERE 1=1 " + + + if search_content != "": + sql += " AND order_sale_type = '" + search_content + "'" + + if search_period != "": + print("search_period: " + search_period) + if len(search_period) == 4: + sql += " AND " + date_value + " BETWEEN '" + date_to_string(period_to_date(search_period)) + "' AND '" + date_to_string(date_add_year(period_to_date(search_period))) + "'" + if search_period.count('-') == 1: + sql += " AND " + date_value + " BETWEEN '" + date_to_string(period_to_date(search_period)) + "' AND '" + date_to_string(date_add_month(period_to_date(search_period))) + "'" + if search_period.count('-') == 2: + sql += " AND " + date_value + " BETWEEN '" + date_to_string(period_to_date(search_period)) + "' AND '" + date_to_string(date_add_day(period_to_date(search_period))) + "'" + if 'W' in search_period: + sql += " AND " + date_value + " BETWEEN '" + date_to_string(period_to_date(search_period)) + "' AND '" + date_to_string(date_add_week(period_to_date(search_period))) + "'" + else: + today = datetime.datetime.now() + this_month = period_to_date(str(today.year) + "-" + str(today.month)) + sql += " AND " + date_value + " BETWEEN '" + date_to_string(this_month) +"' AND '" + date_to_string(date_add_month(this_month)) + "'" + message.reply("No date found so looking for this month only...") + + if group_by != "": + sql += " GROUP BY " + group_by + " ORDER BY 1 " + + if sql != "": + print(sql) + message.reply("Looking...") + res = titlator.db.p.execute(sql) + ox = res.fetchall() + + + print(ox) + if group_by: + plot_results(message, ox, "", re.search("(by|each) (day|week|month)", incoming_message.lower(), re.IGNORECASE).group(2), search_type) + message.reply('\n'.join(map(lambda x: '{0} - {1}'.format(x[0],x[1]), ox))) + else: + message.reply("Answer: " + str(ox[0][0])) + else: + message.reply("I can't figure that out yet, ask someone in the data team...") + +def check_each(incoming_message, date_value): + m = re.search("(by|each) (day|week|month)", incoming_message.lower(), re.IGNORECASE) + if m: + if m.group(2) == "day": + return "DATE_FORMAT(" + date_value + ", '%%Y-%%m-%%d')" + if m.group(2) == "week": + return "DATE_FORMAT(" + date_value + ", '%%Y-%%U')" + if m.group(2) == "month": + return "DATE_FORMAT(" + date_value + ", '%%Y-%%m-%%b')" + return "" + +def period_to_date(search_period): + if 'W' in search_period: + search_period = str(Week.fromstring(search_period).monday()) + if search_period.count('-') < 2: + search_period += "-01" + if search_period.count('-') < 2: + search_period += "-01" + + return datetime.datetime.strptime(search_period, '%Y-%m-%d') + +def date_to_string(date_in): + return date_in.strftime('%Y-%m-%d') + +def date_add_month(date_in, months=1): + month = date_in.month - 1 + months + year = int(date_in.year + month / 12 ) + month = month % 12 + 1 + day = min(date_in.day,calendar.monthrange(year,month)[1]) + return datetime.date(year,month,day) + +def date_add_year(date_in, years=1): + year = date_in.year + years + month = date_in.month + day = min(date_in.day,calendar.monthrange(year,month)[1]) + return datetime.date(year,month,day) + +def date_add_day(date_in, days=1): + return date_in + datetime.timedelta(days=days) + +def date_add_week(date_in, weeks=1): + return date_in + datetime.timedelta(weeks=weeks) + + +def plot_results(message, result, title, x_label, y_label): + data = [] + xTickMarks = [] + plt.style.use('fivethirtyeight') + fig = plt.figure() + ax = fig.add_subplot(111) + + for row in result: + data.append(int(row[1])) + xTickMarks.append(str(row[0])) + + + ## necessary variables + ind = np.arange(len(data)) # the x locations for the groups + width = 0.35 # the width of the bars + + ## the bars + rects1 = ax.bar(ind, data, width, + color='black', + error_kw=dict(elinewidth=2,ecolor='red')) + + + # axes and labels + ax.set_xlim(-width,len(ind)+width) + ax.set_ylim(0,max(data)) + + + ax.set_ylabel(y_label) + ax.set_xlabel(x_label) + ax.set_title(title) + + ax.set_xticks(ind+width) + xtickNames = ax.set_xticklabels(xTickMarks) + + plt.setp(xtickNames, rotation=45, fontsize=10) + fig.subplots_adjust(bottom=0.2,left=0.15) + filename = str(uuid.uuid1()) + '.png' + plt.savefig(filename) + post_image(filename, slackbot_settings.API_TOKEN, message.channel._body['id']) + + +def post_image(filename, token, channels): + f = {'file': (filename, open(filename, 'rb'), 'image/png', {'Expires':'0'})} + response = requests.post(url='https://slack.com/api/files.upload', data={'token': token, 'channels': channels, 'media': f}, headers={'Accept': 'application/json'}, files=f) + print(response.text) From b6c54148fdde4308509d3943080bd89e5d2e39b6 Mon Sep 17 00:00:00 2001 From: supachris28 Date: Mon, 23 Jan 2017 09:41:24 +0000 Subject: [PATCH 6/6] Refactor fixed and working --- .gitignore | 1 + splackt_actions/splackt.py | 7 ------- splackt_actions/splackt_sales.py | 6 ------ splackt_helper.py | 12 ++++++++++-- 4 files changed, 11 insertions(+), 15 deletions(-) diff --git a/.gitignore b/.gitignore index 287e4fd..90b840d 100644 --- a/.gitignore +++ b/.gitignore @@ -139,3 +139,4 @@ $RECYCLE.BIN/ *.lnk dbapi.py slackbot_settings.py +charts/* diff --git a/splackt_actions/splackt.py b/splackt_actions/splackt.py index 057f42c..71e9445 100644 --- a/splackt_actions/splackt.py +++ b/splackt_actions/splackt.py @@ -13,19 +13,12 @@ import calendar from isoweek import Week import numpy as np -import matplotlib -import matplotlib.pyplot as plt import slackbot_settings #import pandas g = py2neo.Graph('http://neo4j:skynet@178.62.55.202:7474/db/data') - -#Change mpl backend -matplotlib.use('Agg') - - # standard word lists product_types = "(book|ebook|video|subscription)" sales_keywords = "(sales|value|revenue|quantity)" diff --git a/splackt_actions/splackt_sales.py b/splackt_actions/splackt_sales.py index 7edcc07..98afe41 100644 --- a/splackt_actions/splackt_sales.py +++ b/splackt_actions/splackt_sales.py @@ -13,8 +13,6 @@ import calendar from isoweek import Week import numpy as np -import matplotlib -import matplotlib.pyplot as plt import slackbot_settings import splackt_helper @@ -23,10 +21,6 @@ g = py2neo.Graph('http://neo4j:skynet@178.62.55.202:7474/db/data') -#Change mpl backend -matplotlib.use('Agg') - - # standard word lists product_types = "(book|ebook|video|subscription)" sales_keywords = "(sales|value|revenue|quantity)" diff --git a/splackt_helper.py b/splackt_helper.py index 27becc2..df5aa47 100644 --- a/splackt_helper.py +++ b/splackt_helper.py @@ -2,6 +2,7 @@ from slackbot.bot import respond_to, listen_to import io +import os import re import uuid import py2neo @@ -14,6 +15,7 @@ from isoweek import Week import numpy as np import matplotlib +matplotlib.use('Agg') import matplotlib.pyplot as plt import slackbot_settings @@ -164,7 +166,13 @@ def plot_results(message, result, title, x_label, y_label): plt.setp(xtickNames, rotation=45, fontsize=10) fig.subplots_adjust(bottom=0.2,left=0.15) - filename = str(uuid.uuid1()) + '.png' + filename = 'charts/' + str(uuid.uuid1()) + '.png' + dir = os.path.dirname(filename) + + try: + os.stat(dir) + except: + os.mkdir(dir) plt.savefig(filename) post_image(filename, slackbot_settings.API_TOKEN, message.channel._body['id']) @@ -172,4 +180,4 @@ def plot_results(message, result, title, x_label, y_label): def post_image(filename, token, channels): f = {'file': (filename, open(filename, 'rb'), 'image/png', {'Expires':'0'})} response = requests.post(url='https://slack.com/api/files.upload', data={'token': token, 'channels': channels, 'media': f}, headers={'Accept': 'application/json'}, files=f) - print(response.text) + #print(response.text)