From 6f51209517074faa546716679cd0ff7758dc07d6 Mon Sep 17 00:00:00 2001 From: N0str Date: Sun, 12 Aug 2018 14:34:24 +0300 Subject: [PATCH 1/6] Add matplotlib graph --- metrika/commands/help.py | 3 ++- metrika/commands/statistics.py | 47 +++++++++++++++++++++++++++------- metrika/main.py | 2 ++ 3 files changed, 42 insertions(+), 10 deletions(-) diff --git a/metrika/commands/help.py b/metrika/commands/help.py index 882788c..a649a72 100644 --- a/metrika/commands/help.py +++ b/metrika/commands/help.py @@ -15,7 +15,8 @@ async def __call__(self, payload): "/metrika_subscriptions - настройка ежедневных отчётов\n" \ "/metrika_stop - отключение счетчиков\n" \ "/metrika_counters - список подключенных счётчиков\n" \ - "/metrika_access - отключение пользователей от чата" + "/metrika_access - отключение пользователей от чата\n" \ + "/today, /weekly, /monthly - получить статистику посещений за сегодняшний день/неделю/месяц" await self.sdk.send_text_to_chat( payload["chat"], diff --git a/metrika/commands/statistics.py b/metrika/commands/statistics.py index 78a32c8..7b3f29a 100644 --- a/metrika/commands/statistics.py +++ b/metrika/commands/statistics.py @@ -1,6 +1,11 @@ +import io + from .base import CommandBase import requests from datetime import datetime, timedelta +import matplotlib.pyplot as plt +import numpy as np +import pycapella class CommandStatistics(CommandBase): @@ -49,6 +54,8 @@ async def stats(self, payload): date['hour'], date['minute']) + await self.sdk.send_text_to_chat(payload["chat"], message) + for counter in counters: user_data = self.sdk.db.find_one(self.COLLECTIONS['tokens'], { 'user_id': counter['user_id'] @@ -56,16 +63,35 @@ async def stats(self, payload): token = user_data['access_token'] - hits, users = self.get_stats(counter['counter_id'], token, period) + hits, users, users_day = self.get_stats(counter['counter_id'], token, period) - message += "{}:\n" \ + await self.sdk.send_text_to_chat(payload["chat"], + "{}:\n" \ "{} уникальных посетителей\n" \ - "{} просмотров\n\n".format(counter['counter_name'], int(users), int(hits)) + "{} просмотров\n\n".format(counter['counter_name'], int(users), int(hits))) + + if payload['command'] == 'weekly': + try: + url = self.get_graph(users_day) + if url: + await self.sdk.send_image_to_chat(payload["chat"], url) + except: + pass - await self.sdk.send_text_to_chat( - payload["chat"], - message - ) + def get_graph(self, users_day): + now = datetime.now() + axes_labels = [(now - timedelta(i)).strftime("%d.%m") for i in range(now.weekday(), -1, -1)] + fig = plt.figure(figsize=(6, 3), dpi=80) + ax = fig.add_subplot(111) + ax.plot(axes_labels, np.array(users_day), 'b') + buf = io.BytesIO() + fig.savefig(buf, format='png') + try: + response = pycapella.Capella().upload_file(buf.getvalue(), raw_input=True) + except: + return None + else: + return response['url'] def get_stats(self, counter, token, date1): """ @@ -82,13 +108,16 @@ def get_stats(self, counter, token, date1): 'oauth_token': token, 'metrics': 'ym:s:pageviews,ym:s:users', 'date1': date1, - 'date2': 'today' + 'date2': 'today', + 'group': 'day' } statistic = requests.get(self.API_URL, params=params, timeout=5).json() hits, users = statistic['totals'][0] - return hits, users + users_day = statistic['data'][0]['metrics'][1] + + return hits, users,users_day @staticmethod def get_date(): diff --git a/metrika/main.py b/metrika/main.py index 26110f0..5a7702f 100644 --- a/metrika/main.py +++ b/metrika/main.py @@ -1,3 +1,5 @@ +import matplotlib +matplotlib.use('Agg') from commands.subscribe import CommandSubscribe from commands.statistics import CommandStatistics from commands.unsubscribe import CommandUnsubscribe From 30f549491362189dcfcea61a8920b34e493c7392 Mon Sep 17 00:00:00 2001 From: N0str Date: Sun, 12 Aug 2018 14:35:54 +0300 Subject: [PATCH 2/6] update requirements --- requirements.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/requirements.txt b/requirements.txt index aac15db..af54d64 100644 --- a/requirements.txt +++ b/requirements.txt @@ -18,3 +18,5 @@ setuptools==35.0.2 - six [required: Any, installed: 1.10.0] - six [required: >=1.6.0, installed: 1.10.0] wheel==0.29.0 +pycapella +matplotlib==2.2.2 From ac0a7021ab020a333c9990ade440b07e6c09d7e8 Mon Sep 17 00:00:00 2001 From: N0str Date: Mon, 13 Aug 2018 22:19:20 +0300 Subject: [PATCH 3/6] Make always show 7 days graph --- metrika/commands/statistics.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/metrika/commands/statistics.py b/metrika/commands/statistics.py index 7b3f29a..2472678 100644 --- a/metrika/commands/statistics.py +++ b/metrika/commands/statistics.py @@ -63,7 +63,7 @@ async def stats(self, payload): token = user_data['access_token'] - hits, users, users_day = self.get_stats(counter['counter_id'], token, period) + hits, users, _ = self.get_stats(counter['counter_id'], token, period) await self.sdk.send_text_to_chat(payload["chat"], "{}:\n" \ @@ -72,6 +72,7 @@ async def stats(self, payload): if payload['command'] == 'weekly': try: + _, _, users_day = self.get_stats(counter['counter_id'], token, '6daysAgo') url = self.get_graph(users_day) if url: await self.sdk.send_image_to_chat(payload["chat"], url) @@ -80,7 +81,7 @@ async def stats(self, payload): def get_graph(self, users_day): now = datetime.now() - axes_labels = [(now - timedelta(i)).strftime("%d.%m") for i in range(now.weekday(), -1, -1)] + axes_labels = [(now - timedelta(i)).strftime("%d.%m") for i in range(7, 0, -1)] fig = plt.figure(figsize=(6, 3), dpi=80) ax = fig.add_subplot(111) ax.plot(axes_labels, np.array(users_day), 'b') From 5fc81a5284fe5713d0268a25a72f0318b98cfe3b Mon Sep 17 00:00:00 2001 From: N0str Date: Wed, 15 Aug 2018 18:51:29 +0300 Subject: [PATCH 4/6] Fix dates captions --- metrika/commands/statistics.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/metrika/commands/statistics.py b/metrika/commands/statistics.py index 2472678..504a48d 100644 --- a/metrika/commands/statistics.py +++ b/metrika/commands/statistics.py @@ -81,7 +81,7 @@ async def stats(self, payload): def get_graph(self, users_day): now = datetime.now() - axes_labels = [(now - timedelta(i)).strftime("%d.%m") for i in range(7, 0, -1)] + axes_labels = [(now - timedelta(i)).strftime("%d.%m") for i in range(6, -1, -1)] fig = plt.figure(figsize=(6, 3), dpi=80) ax = fig.add_subplot(111) ax.plot(axes_labels, np.array(users_day), 'b') From e860654353dcb45f5682850ab8393a3c9201d4fc Mon Sep 17 00:00:00 2001 From: N0str Date: Sun, 2 Dec 2018 16:19:20 +0300 Subject: [PATCH 5/6] change git@ to https --- .gitmodules | 3 --- 1 file changed, 3 deletions(-) diff --git a/.gitmodules b/.gitmodules index 95f4a68..e69de29 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +0,0 @@ -[submodule "metrika/sdk"] - path = metrika/sdk - url = git@github.com:codex-bot/sdk-python.git From 55423c560fb89cf9f3cf90a3ffc2ffdd8eed08ca Mon Sep 17 00:00:00 2001 From: N0str Date: Sun, 2 Dec 2018 16:25:32 +0300 Subject: [PATCH 6/6] change git@ to https --- .gitmodules | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitmodules b/.gitmodules index e69de29..13f8341 100644 --- a/.gitmodules +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "metrika/sdk"] + path = metrika/sdk + url = https://github.com/codex-bot/sdk-python.git