save command logs to database

This commit is contained in:
kiriharu 2021-01-30 13:34:08 +03:00
parent 36d8020dd2
commit 6475271234
6 changed files with 18 additions and 3 deletions

View File

@ -14,6 +14,7 @@ aioinflux = "^0.9.0"
loguru = "^0.5.3"
whois-vu = "^0.3.0"
tortoise-orm = "^0.16.20"
aiomysql = "^0.0.21"
[tool.poetry.dev-dependencies]

View File

@ -20,7 +20,7 @@ async def database_init():
await Tortoise.init(
db_url=db_url,
modules={
'default': ['tgbot.models']
'models': ['tgbot.models']
}
)
await Tortoise.generate_schemas()
@ -30,9 +30,9 @@ async def database_init():
async def on_startup(disp: Dispatcher):
await database_init()
handlers.default.setup(disp)
disp.middleware.setup(ThrottlingMiddleware())
disp.middleware.setup(WriteCommandMetric())
disp.middleware.setup(LoggingMiddleware())
disp.middleware.setup(ThrottlingMiddleware())
disp.middleware.setup(UserMiddleware())
if __name__ == '__main__':

View File

@ -1,6 +1,7 @@
from aiogram.dispatcher.middlewares import BaseMiddleware
from aiogram.types import Message
from tgbot.handlers.metrics import push_metric
from tgbot.models import User, UserCheckRequests
class WriteCommandMetric(BaseMiddleware):
@ -9,6 +10,11 @@ class WriteCommandMetric(BaseMiddleware):
super().__init__()
async def on_process_message(self, message: Message, data: dict):
# commands to DB
user, _ = await User.get_or_create(telegram_id=message.from_user.id)
await UserCheckRequests.create(user=user, request=message.text)
# metrics to influxdb
await push_metric(
measurement="bot_processed_messages",
fields=dict(

View File

@ -1 +1,3 @@
from .user import *
from .requests import *

View File

@ -0,0 +1,7 @@
from tortoise import Model, fields
class UserCheckRequests(Model):
id = fields.IntField(pk=True)
user = fields.ForeignKeyField('models.User', related_name='requests')
request = fields.CharField(max_length=255)

View File

@ -5,4 +5,3 @@ class User(Model):
telegram_id = fields.IntField(pk=True)
created_at = fields.DatetimeField(auto_now_add=True)
updated_at = fields.DatetimeField(auto_now=True)