Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion metrika/commands/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
Expand Down
47 changes: 38 additions & 9 deletions metrika/commands/statistics.py
Original file line number Diff line number Diff line change
@@ -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):
Expand Down Expand Up @@ -49,23 +54,44 @@ 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']
})

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):
"""
Expand All @@ -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():
Expand Down
2 changes: 2 additions & 0 deletions metrika/main.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import matplotlib
matplotlib.use('Agg')
from commands.subscribe import CommandSubscribe
from commands.statistics import CommandStatistics
from commands.unsubscribe import CommandUnsubscribe
Expand Down
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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