diff --git a/.gitmodules b/.gitmodules index 95f4a68..13f8341 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,3 @@ [submodule "metrika/sdk"] - path = metrika/sdk - url = git@github.com:codex-bot/sdk-python.git + path = metrika/sdk + url = https://github.com/codex-bot/sdk-python.git 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..504a48d 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,36 @@ async def stats(self, payload): token = user_data['access_token'] - hits, users = self.get_stats(counter['counter_id'], token, period) + hits, users, _ = 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)) - - await self.sdk.send_text_to_chat( - payload["chat"], - message - ) + "{} просмотров\n\n".format(counter['counter_name'], int(users), int(hits))) + + 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) + except: + pass + + def get_graph(self, users_day): + now = datetime.now() + 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') + 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 +109,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 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