Now with visual stats

This commit is contained in:
Remy Moll 2021-01-03 18:39:41 +01:00
parent 069c83e796
commit 5fe02d4bcd
6 changed files with 67 additions and 22 deletions

View File

@ -43,8 +43,13 @@ class TelegramIO():
def process_message(self): def process_message(self):
"""Inspects the first message from self.message_queue and reacts accordingly.""" """Inspects the first message from self.message_queue and reacts accordingly."""
message_data = self.message_queue.pop(0) message_data = self.message_queue.pop(0)
current_hour = int(datetime.datetime.now().timestamp() // 3600)
if len(self.persistence["bot"]["receive_activity"]["hour"]) == 0 or current_hour != self.persistence["bot"]["receive_activity"]["hour"][-1]:
self.persistence["bot"]["receive_activity"]["hour"].append(current_hour)
self.persistence["bot"]["receive_activity"]["count"].append(1)
else:
self.persistence["bot"]["receive_activity"]["count"][-1] += 1
self.persistence["bot"]["messages_read"] += 1
self.offset = message_data["update_id"] + 1 self.offset = message_data["update_id"] + 1
if "edited_message" in message_data: if "edited_message" in message_data:
@ -112,7 +117,13 @@ class TelegramIO():
r = requests.post(send_url, data=data) r = requests.post(send_url, data=data)
if (r.status_code != 200): if (r.status_code != 200):
raise Exception raise Exception
self.persistence["bot"]["messages_sent"]
current_hour = int(datetime.datetime.now().timestamp() // 3600)
if len(self.persistence["bot"]["send_activity"]["hour"]) == 0 or current_hour != self.persistence["bot"]["send_activity"]["hour"][-1]:
self.persistence["bot"]["send_activity"]["hour"].append(current_hour)
self.persistence["bot"]["send_activity"]["count"].append(1)
else:
self.persistence["bot"]["send_activity"]["count"][-1] += 1
except: except:
out = datetime.datetime.now().strftime("%d.%m.%y - %H:%M") out = datetime.datetime.now().strftime("%d.%m.%y - %H:%M")
out += " @ " + "telegram.send_message" out += " @ " + "telegram.send_message"

View File

@ -87,6 +87,13 @@ class BotFramework():
# *params means the list is unpacked and handed over as separate arguments. # *params means the list is unpacked and handed over as separate arguments.
self.telegram.send_message(result) self.telegram.send_message(result)
current_hour = int(datetime.datetime.now().timestamp() // 3600)
if len(self.persistence["bot"]["execute_activity"]["hour"]) == 0 or current_hour != self.persistence["bot"]["execute_activity"]["hour"][-1]:
self.persistence["bot"]["execute_activity"]["hour"].append(current_hour)
self.persistence["bot"]["execute_activity"]["count"].append(1)
else:
self.persistence["bot"]["execute_activity"]["count"][-1] += 1
if self.is_command(cmd): # first word if self.is_command(cmd): # first word
call_command(cmd, params) call_command(cmd, params)
elif cmd in self.persistence["bot"]["aliases"]: elif cmd in self.persistence["bot"]["aliases"]:

View File

@ -2,6 +2,7 @@ import datetime
from bot.api import telegram, google, weather, reddit from bot.api import telegram, google, weather, reddit
import requests import requests
import numpy as np
import time import time
import json import json
import datetime import datetime
@ -64,13 +65,20 @@ class ChatBot(FW.BotFramework):
ip = requests.get('https://api.ipify.org').text ip = requests.get('https://api.ipify.org').text
except: except:
ip = "not fetchable" ip = "not fetchable"
message += "<pre>Status: Running :green_circle:\n" message += "<pre>Status: Running :green_circle:\n"
message += "Uptime: " + delta[:delta.rfind(".")] + "\n" message += "Uptime: " + delta[:delta.rfind(".")] + "\n"
message += "Reboots: " + str(self.persistence["global"]["reboots"]) + "\n" message += "Reboots: " + str(self.persistence["global"]["reboots"]) + "\n"
message += "IP-Adress: " + ip + "\n" message += "IP-Adress: " + ip + "\n"
message += "Messages read: " + str(self.persistence["bot"]["messages_read"]) + "\n"
message += "Messages sent: " + str(self.persistence["bot"]["messages_sent"]) + "\n" tot_r = np.array(self.persistence["bot"]["receive_activity"]["count"]).sum()
message += "Commands executed " + str(self.persistence["bot"]["commands_executed"]) + "</pre>" message += "Total messages read: " + str(tot_r) + "\n"
tot_s = np.array(self.persistence["bot"]["send_activity"]["count"]).sum()
message += "Total messages sent: " + str(tot_s) + "\n"
tot_e = np.array(self.persistence["bot"]["execute_activity"]["count"]).sum()
message += "Commands executed " + str(tot_e) + "</pre>"
return message return message

View File

@ -2,6 +2,7 @@ import dash
import dash_bootstrap_components as dbc import dash_bootstrap_components as dbc
import dash_html_components as html import dash_html_components as html
import dash_core_components as dcc import dash_core_components as dcc
import plotly.graph_objects as go
from dash.dependencies import Input, Output from dash.dependencies import Input, Output
import locale import locale
@ -15,6 +16,7 @@ import xmltodict
import requests import requests
import emoji import emoji
class DashBoard(): class DashBoard():
"""""" """"""
def __init__(self, host_ip, prst): def __init__(self, host_ip, prst):
@ -32,7 +34,8 @@ class DashBoard():
interval=3600*1000, # in milliseconds interval=3600*1000, # in milliseconds
n_intervals=0 n_intervals=0
) )
]) ]#,style={'background-image':'url("static/background.jpg")'}
)
@self.app.callback(Output('layout-update','children'), Input('interval-component','n_intervals')) @self.app.callback(Output('layout-update','children'), Input('interval-component','n_intervals'))
def update_layout(n): def update_layout(n):
@ -40,16 +43,14 @@ class DashBoard():
kids = [ kids = [
self.card_header(), self.card_header(),
dbc.CardColumns([ dbc.CardColumns([
self.card_weather(),
*self.cards_lists(), *self.cards_lists(),
self.card_bot_stats(),
self.card_news(), self.card_news(),
self.card_xkcd(), self.card_xkcd(),
self.card_weather()
]) ])
] ]
return kids return kids
#[card_header, dbc.CardColumns([card_shopping_list,card_placeholder,card_placeholder,card_placeholder,card_placeholder,card_placeholder])]
def launch_dashboard(self): def launch_dashboard(self):
@ -89,8 +90,31 @@ class DashBoard():
return ret return ret
# def card_bot_stats(self): def card_bot_stats(self):
# return card xs = self.persistence["bot"]["send_activity"]["hour"]
ys = self.persistence["bot"]["send_activity"]["count"]
xr = self.persistence["bot"]["receive_activity"]["hour"]
yr = self.persistence["bot"]["receive_activity"]["count"]
xe = self.persistence["bot"]["execute_activity"]["hour"]
ye = self.persistence["bot"]["execute_activity"]["count"]
fig = go.Figure()
fig.add_trace(go.Scatter(x=xs, y=ys, fill="tozeroy", mode="lines", text="Gesendet"))
fig.add_trace(go.Scatter(x=xr, y=yr, fill="tozeroy", mode="lines", text="Gelesen"))
fig.add_trace(go.Scatter(x=xe, y=ye, fill="tozeroy", mode="lines", text="Ausgeführt"))
fig.layout.update(showlegend=False,margin=dict(l=0, r=0, t=0, b=0),)
card = dbc.Card(
[
dbc.CardBody([
html.H4("Statistiken", className="card-title"),
dcc.Graph(figure=fig,config={'displayModeBar': False})
]),
],
color="dark",
inverse=True,
)
return card
def card_weather(self): def card_weather(self):
try: try:
@ -187,8 +211,3 @@ class DashBoard():
inverse=True, inverse=True,
) )
return card return card
if __name__ == "__main__":
test = DashBoard(host_ip="0.0.0.0")

Binary file not shown.

After

Width:  |  Height:  |  Size: 331 KiB

View File

@ -45,9 +45,9 @@ class Launcher():
def init_persistence(self): def init_persistence(self):
print("New Persistence created") print("New Persistence created")
self.persistence["bot"] = { self.persistence["bot"] = {
"messages_read": 0, "send_activity" : {"hour":[], "count":[]},
"messages_sent": 0, "receive_activity" : {"hour":[], "count":[]},
"commands_executed": 0, "execute_activity" : {"hour":[], "count":[]},
"photos_sent": 0, "photos_sent": 0,
"log": [], "log": [],
"chat_members": {}, "chat_members": {},