Skip to content

Commit

Permalink
action added bot working flake8 to emplement
Browse files Browse the repository at this point in the history
  • Loading branch information
Gatitka committed Sep 30, 2023
1 parent 9b426a1 commit d8f720b
Show file tree
Hide file tree
Showing 6 changed files with 111 additions and 112 deletions.
56 changes: 28 additions & 28 deletions .github/workflows/git_actions.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,39 +3,39 @@ name: TheKirillovs Bot workflow
on: [push]

jobs:
tests:
# «Раннер» — создание изолированного окружения с последней версией Ubuntu
runs-on: ubuntu-latest
# tests:
# # «Раннер» — создание изолированного окружения с последней версией Ubuntu
# runs-on: ubuntu-latest

steps:
# Запуск actions checkout — готового скрипта
# для клонирования репозитория
- uses: actions/checkout@v2
- name: Set up Python
# Запуск actions setup-python — готового скрипта
# для развёртывания окружения Python
uses: actions/setup-python@v2
with:
# Выбор версии Python
python-version: 3.7
# steps:
# # Запуск actions checkout — готового скрипта
# # для клонирования репозитория
# - uses: actions/checkout@v2
# - name: Set up Python
# # Запуск actions setup-python — готового скрипта
# # для развёртывания окружения Python
# uses: actions/setup-python@v2
# with:
# # Выбор версии Python
# python-version: 3.7

- name: Install dependencies
run: |
# обновление pip
python -m pip install --upgrade pip
# установка flake8 и его плагинов
pip install flake8 pep8-naming flake8-broken-line flake8-return flake8-isort
# установка зависимостей
# pip install -r requirements.txt
# - name: Install dependencies
# run: |
# # обновление pip
# python -m pip install --upgrade pip
# # установка flake8 и его плагинов
# pip install flake8 pep8-naming flake8-broken-line flake8-return flake8-isort
# # установка зависимостей
# # pip install -r requirements.txt

- name: Test with flake8 and django tests
run: |
# запуск проверки проекта по flake8
python -m flake8
# - name: Test with flake8 and django tests
# run: |
# # запуск проверки проекта по flake8
# python -m flake8

deploy:
runs-on: ubuntu-latest
needs: tests
# needs: tests
steps:
- name: executing remote ssh commands to deploy
uses: appleboy/ssh-action@master
Expand All @@ -50,4 +50,4 @@ jobs:
sudo git pull
# перезапуск юнита myBot
systemctl stop myBot
systemctl start myBot
# systemctl start myBot
4 changes: 2 additions & 2 deletions bot.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import handlers
import aiogram
import config

from db import BotDB
from dispatcher import dp
import config

BotDB = BotDB(config.DB_FILE)
# connection to DB on distant server
Expand Down
129 changes: 66 additions & 63 deletions db.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import sqlite3

import config


Expand Down Expand Up @@ -50,7 +49,7 @@ def manage_admin(self, action, user_id):
(user_id))
return self.conn.commit()

def is_admin(self, user_id):
def isAdmin(self, user_id):
"""Проверка активного пользователя, админи ли он по его user_id"""
try:
db_result = self.cursor.execute(
Expand Down Expand Up @@ -115,70 +114,74 @@ def get_records(self):
value = 0
return round(value, 2)

def get_monthly_report(self, monthly_expenses):
result = self.cursor.execute(
"SELECT category, SUM(`value`) AS SUM_VALUE "
+ "FROM `records` "
+ "WHERE `date` "
+ "BETWEEN datetime('now', 'start of month') "
+ "AND datetime('now', 'localtime') "
+ "GROUP BY category "
+ "ORDER BY SUM_VALUE DESC"
)
result = result.fetchall()
total_value = 0
for i in result:
total_value += i[1]
total_value = round(total_value, 2)
message = 'Саммери затрат за последний месяц:\n'
for i in result:
perc = int(i[1] / total_value * 100)
message += f' - {i[0]} {i[1]}{perc}%\n'
fact_vs_budget = int(total_value / monthly_expenses * 100)
if fact_vs_budget > 100:
message += (f'\nИтого потрачено {total_value}\n'
+ f'Перерасход бюджета {fact_vs_budget - 100}%\n\n'
+ 'НУ ЧТО Ж... иди ебашь')
else:
message += (f'\nИтого потрачено {total_value}\n'
+ f'Экономия бюджета {100 - fact_vs_budget}%\n\n'
+ 'МОЛОДЦЫ!!!'
)
return message

def create_message(self, result, period):
if result:
message = f'Записи за {period}:\n'
def get_report(self, command, MONTHLY_EXPENSES):
if command == '/results_total_month':
# за последний день
result = self.cursor.execute(
"SELECT category, SUM(`value`) AS SUM_VALUE "
+ "FROM `records` "
+ "WHERE `date` "
+ "BETWEEN datetime('now', 'start of month') "
+ "AND datetime('now', 'localtime') "
+ "GROUP BY category "
+ "ORDER BY SUM_VALUE DESC"
)
result = result.fetchall()
total_value = 0
for i in result:
message += f'-> {i[0]} {i[1]} {i[2]}{i[3]}\n'
return message
return f'Записей за {period} нет.'
total_value += i[1]
total_value = round(total_value, 2)
message = 'Саммери затрат за последний месяц:\n'
for i in result:
perc = int(i[1] / total_value * 100)
message += f' - {i[0]} {i[1]}{perc}%\n'
fact_vs_budget = int(total_value / MONTHLY_EXPENSES * 100)
if fact_vs_budget > 100:
message += (f'\nИтого потрачено {total_value}\n'
+ f'Перерасход бюджета {fact_vs_budget - 100}%\n\n'
+ 'НУ ЧТО Ж... иди ебашь')
else:
message += (f'\nИтого потрачено {total_value}\n'
+ f'Экономия бюджета {100 - fact_vs_budget}%\n\n'
+ 'МОЛОДЦЫ!!!'
)

def get_today_report(self, monthly_expenses):
# за последний день
result = self.cursor.execute(
"SELECT strftime('%d.%m %H:%M', date) AS formatted_date, "
+ "category, value, comment FROM 'records' "
+ "WHERE `date` "
+ "BETWEEN datetime('now', 'start of day') "
+ "AND datetime('now', 'localtime') "
+ "ORDER BY `date`"
)
result = result.fetchall()
return BotDB.create_message(result, 'сегодня')
elif command == '/details_day':
# за последний день
result = self.cursor.execute(
"SELECT strftime('%d.%m %H:%M', date) AS formatted_date, "
+ "category, value, comment FROM 'records' "
+ "WHERE `date` "
+ "BETWEEN datetime('now', 'start of day') "
+ "AND datetime('now', 'localtime') "
+ "ORDER BY `date`"
)
result = result.fetchall()
if result:
message = 'Записи за сегодня:\n'
for i in result:
message += f'-> {i[0]} {i[1]} {i[2]}{i[3]}\n'
else:
message = 'Записей сегодня нет.'

def get_detail_month_report(self, monthly_expenses):
# за последний месяц
result = self.cursor.execute(
"SELECT strftime('%d.%m %H:%M', date) AS formatted_date, "
+ "category, value, comment FROM 'records' "
+ "WHERE `date` "
+ "BETWEEN datetime('now', 'start of month') "
+ "AND datetime('now', 'localtime') "
+ "ORDER BY 'date'"
)
result = result.fetchall()
return BotDB.create_message(result, 'месяц')
elif command == '/details_month':
# за последний месяц
result = self.cursor.execute(
"SELECT strftime('%d.%m %H:%M', date) AS formatted_date, "
+ "category, value, comment FROM 'records' "
+ "WHERE `date` "
+ "BETWEEN datetime('now', 'start of month') "
+ "AND datetime('now', 'localtime') "
+ "ORDER BY 'date'"
)
result = result.fetchall()
if result:
message = 'Записи этого месяца:\n'
for i in result:
message += f'-> {i[0]} {i[1]} {i[2]}{i[3]}\n'
else:
message = 'Записей в этом месяце нет.'
return message

def close(self):
"""Закрытие соединения с БД"""
Expand Down
7 changes: 3 additions & 4 deletions dispatcher.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import config
import logging
from aiogram import Bot, Dispatcher
from aiogram.contrib.fsm_storage.memory import MemoryStorage

# from filters import IsOwnerFilter, IsAdminFilter, MemberCanRestrictFilter
# import logging
import config

# Configure logging
# logging.basicConfig(level=logging.INFO)
logging.basicConfig(level=logging.INFO)

# prerequisites
if not config.BOT_TOKEN:
Expand Down
1 change: 1 addition & 0 deletions handlers/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from . import personal_actions
26 changes: 11 additions & 15 deletions handlers/personal_actions.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import re

from aiogram import types
from aiogram.types import (ReplyKeyboardMarkup,
InlineKeyboardMarkup,
InlineKeyboardButton)
from aiogram.dispatcher.filters.state import StatesGroup, State
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.types import (InlineKeyboardButton, InlineKeyboardMarkup,
ReplyKeyboardMarkup)

from bot import BotDB
from dispatcher import dp
import re
from bot import BotDB
import asyncio


MONTHLY_EXPENCES = 300

Expand Down Expand Up @@ -119,7 +120,7 @@ async def start(message: types.Message):
"Добро пожаловать!\nНажми /menu для входа в учет затрат.",
reply_markup=get_start_kb()
)
if BotDB.is_admin(message.from_user.id):
if BotDB.isAdmin(message.from_user.id):
await message.answer(
"Вы авторизовались как администратор и вам доступна команда\n"
+ "/admin_panel для создания базы данных, "
Expand All @@ -143,7 +144,7 @@ async def menu(message: types.Message):

@dp.message_handler(commands='admin-panel')
async def start_settings(message: types.Message):
if BotDB.is_admin(message.from_user.id):
if BotDB.isAdmin(message.from_user.id):
await message.answer(
"Выбери команду для следующего действия:",
reply_markup=get_admin_panel_kb()
Expand Down Expand Up @@ -294,11 +295,6 @@ async def report_detailed(message: types.Message):
elif not user_exists:
await message.answer("Вы не в списке участников.🤷‍♀️")
else:
if message.text == '/results_total_month':
result = BotDB.get_monthly_report(MONTHLY_EXPENCES)
elif message.text == '/details_day':
result = BotDB.get_today_report(MONTHLY_EXPENCES)
elif message.text == '/details_month':
result = BotDB.get_detail_month_report(MONTHLY_EXPENCES)
result = BotDB.get_report(message.text, MONTHLY_EXPENCES)
await message.answer(result, reply_markup=get_menu_kb())
await message.delete()

0 comments on commit d8f720b

Please sign in to comment.