Skip to content

Commit

Permalink
подключил redis, сделал сохранение данных в redis
Browse files Browse the repository at this point in the history
  • Loading branch information
Павел Сарыгин committed Feb 5, 2024
1 parent ceb9d23 commit 87e0826
Show file tree
Hide file tree
Showing 8 changed files with 106 additions and 55 deletions.
20 changes: 15 additions & 5 deletions infra/docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ services:
frontend:
container_name: frontend
image: zali1813/short_tracker_frontend:v1
restart: always
# restart: always
volumes:
- ../frontend/:/app/result_build/
# depends_on:
Expand Down Expand Up @@ -40,18 +40,28 @@ services:
- media_value:/var/html/media/
# depends_on:
# - backend

redis:
image: redis:alpine
restart: on-failure
ports:
- "6379:6379"
volumes:
- redis_data:/data
bot:
container_name: bot
image: zali1813/short_tracker_bot:v1
#image: zali1813/short_tracker_bot:v1
build:
context: ../short_tracker_bot
dockerfile: Dockerfile
restart: always
env_file:
- ./.env
# depends_on:
# - backend
depends_on:
- redis

volumes:
static_value:
media_value:
postgres_data:
redis_data:

6 changes: 4 additions & 2 deletions short_tracker_bot/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ FROM python:3.9

WORKDIR /app

COPY short_tracker_bot/requirements.txt .
COPY requirements.txt .

RUN pip install -r requirements.txt --no-cache-dir

RUN chmod 755 .

COPY ./short_tracker_bot .

# RUN python3 short_tracker_bot/bot.py
WORKDIR /app/short_tracker_bot
WORKDIR /app

CMD ["python3", "bot.py"]
Binary file modified short_tracker_bot/requirements.txt
Binary file not shown.
9 changes: 5 additions & 4 deletions short_tracker_bot/short_tracker_bot/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@

import dotenv
from aiogram import Bot, Dispatcher
from aiogram.fsm.storage.memory import MemoryStorage

from aiogram.fsm.storage.redis import RedisStorage
from aioredis import Redis
from config import COMMANDS
from handlers.hello import router

Expand All @@ -14,8 +14,9 @@

async def main():
bot = Bot(token=os.getenv('TOKEN'))
memory = MemoryStorage()
dp = Dispatcher(memory=memory)
redis = Redis(host='redis')
storage = RedisStorage(redis=redis)
dp = Dispatcher(storage=storage)
dp.include_router(router)
await bot.set_my_commands(commands=COMMANDS)
await dp.start_polling(bot)
Expand Down
8 changes: 6 additions & 2 deletions short_tracker_bot/short_tracker_bot/config.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
from aiogram.types import BotCommand


TOKEN = '6787434498:AAHW5Y2gUJQLqttiQ-Vj9qulyBoTCHYYVu4'
URL = 'https://short-tracker.acceleratorpracticum.ru/api/v1/'
COMMANDS = [BotCommand(command='/start', description='Запуск бота')
]
]
HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
' AppleWebKit/537.36 (KHTML, like Gecko)'
' Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0'
}
98 changes: 58 additions & 40 deletions short_tracker_bot/short_tracker_bot/handlers/hello.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,17 @@
import asyncio
import logging

from aiogram import F, Router, Bot
from aiogram import types
from aiogram import Bot, Router, types
from aiogram.filters import CommandStart
from keyboards.keyboards import start_keyboard
from aiogram.fsm.state import State, StatesGroup
from aiogram.fsm.context import FSMContext
from aiogram.fsm.state import State, StatesGroup
from config import HEADERS, URL
from keyboards.keyboards import start_keyboard

from .redis_data import get_data_from_redis, save_data_to_redis
from .requests import request_get, request_post
from config import URL

router = Router()
OLD_MESSAGES = []
OLD_REPLIES = []
TASKS_DICT = dict()
TASKS_EXPIRED = []
HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
' AppleWebKit/537.36 (KHTML, like Gecko)'
' Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0'
}


class Login(StatesGroup):
Expand Down Expand Up @@ -49,6 +40,7 @@ async def get_token(state, bot):
await state.update_data(new_token=f'Bearer {token.value}')
data_fsm = await state.get_data()
logging.info(f'NEW TOKEN {data_fsm["new_token"]}')
await bot.send_message('Вход успешно выполнен!')
return data_fsm['new_token']
else:
await bot.send_message(
Expand All @@ -61,21 +53,65 @@ async def get_token(state, bot):

async def get_messages(data, chat_id, bot: Bot):
for msg in data['results'][0]['messages']:
if msg['id'] not in OLD_MESSAGES:
OLD_MESSAGES.append(msg['id'])
if not get_data_from_redis(f'{chat_id}_msg_{msg["id"]}'):
await save_data_to_redis(
f'{chat_id}_msg_{msg["id"]}', msg['message_body']
)
await bot.send_message(
chat_id,
text=f'У вас новое сообщение\n\"{msg["message_body"]}\"'
)
for reply in msg['reply']:
if reply['id'] not in OLD_REPLIES:
OLD_REPLIES.append(reply['id'])
if not get_data_from_redis(f'{chat_id}_reply_{msg["id"]}'):
await save_data_to_redis(
f'{chat_id}_reply_{msg["id"]}',
reply["reply_body"]
)
await bot.send_message(
chat_id,
text=f'На ваш запрос к лиду поступил ответ:\n{reply["reply_body"]}'
text=f'На ваш запрос к лиду поступил ответ:'
f'\n{reply["reply_body"]}'
)


async def get_tasks(data, chat_id, bot: Bot):
for task in data['results'][0]['tasks_for_user']:
if not get_data_from_redis(f'{chat_id}_task_{task["id"]}'):
await bot.send_message(
chat_id=chat_id,
text=f'У Вас появилась новая задача'
f' \"{task["description"]}\"'
)
await save_data_to_redis(
f'{chat_id}_task_{task["id"]}',
task['status']
)
if task['status'] != get_data_from_redis(
f'{chat_id}_task_{task["id"]}'
):
await save_data_to_redis(
f'{chat_id}_task_{task["id"]}',
task["id"]
)
await bot.send_message(
chat_id=chat_id,
text=f'Изменен статус задачи '
f'\"{task["description"]}\" на {task["status"]}')
if task['is_expired'] and not get_data_from_redis(
f'{chat_id}_status_{task["id"]}'
):
await save_data_to_redis(
f'{chat_id}_status_{task["id"]}',
task['is_expired']
)
performers = [performer['full_name'] for performer in task['performers']]
await bot.send_message(
chat_id=chat_id,
text=f'Задача \"{task["description"]}\" сотрудника'
f' {", ".join(performers)} просрочена'
)


async def get_data(state: FSMContext, bot: Bot):
data_fsm = await state.get_data()
token = data_fsm['new_token']
Expand All @@ -102,35 +138,17 @@ async def get_data(state: FSMContext, bot: Bot):
headers=headers)
logging.info('Запрос сообщений')
await get_messages(data, chat_id, bot)
for task in data['results'][0]['tasks_for_user']:
if task['id'] not in TASKS_DICT.keys():
await bot.send_message(
chat_id=chat_id,
text=f'У Вас появилась новая задача \"{task["description"]}\"'
)
TASKS_DICT[task['id']] = task['status']
if task['status'] != TASKS_DICT[task['id']]:
TASKS_DICT[task['id']] = task['status']
await bot.send_message(
chat_id=chat_id,
text=f'Изменен статус задачи \"{task["description"]}\" на {task["status"]}')
if task['is_expired'] and task['id'] not in TASKS_EXPIRED:
TASKS_EXPIRED.append(task['id'])
performers = [performer['full_name'] for performer in task['performers']]
await bot.send_message(
chat_id=chat_id,
text=f'Задача \"{task["description"]}\" сотрудника'
f' {", ".join(performers)} просрочена'
)
await get_tasks(data, chat_id, bot)
except Exception:
logging.error('Не удалось получить данные')
finally:
await asyncio.sleep(600)
await asyncio.sleep(15)


@router.message(CommandStart())
async def email(message: types.Message, state: FSMContext):
await state.update_data(chat_id=message.chat.id)

await state.set_state(Login.email)
await message.answer('Введите свою почту')

Expand Down
17 changes: 17 additions & 0 deletions short_tracker_bot/short_tracker_bot/handlers/redis_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import asyncio
import logging

import aioredis

redis = aioredis.Redis(host='redis')


async def save_data_to_redis(key, value):
logging.info(f'Сохранение в redis {key, value}')
await redis.sadd(key, value)


async def get_data_from_redis(key):
data = await redis.get(key)
logging.info(f'get data {data}')
return data
3 changes: 1 addition & 2 deletions short_tracker_bot/short_tracker_bot/keyboards/keyboards.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from aiogram.utils.keyboard import ReplyKeyboardMarkup, KeyboardButton

from aiogram.utils.keyboard import KeyboardButton, ReplyKeyboardMarkup

keyboard_button = KeyboardButton(text='/войти')

Expand Down

0 comments on commit 87e0826

Please sign in to comment.