diff --git a/app/bot/tasks.py b/app/bot/tasks.py new file mode 100644 index 0000000..15a691c --- /dev/null +++ b/app/bot/tasks.py @@ -0,0 +1,19 @@ +from celery.app import shared_task +from django.core.mail import send_mail + +from project.settings import EMAIL_HOST_USER + + + + +@shared_task +def send_email(email, code): + subject = "Код подтверждения для регистрации" + message = f"Ваш код подтверждения: {code}" + recipient_list = [email] + + try: + send_mail(subject, message, EMAIL_HOST_USER, recipient_list) + print(f"Код отправлен на {email}") + except Exception as e: + print(f"Ошибка при отправке email: {e}") diff --git a/app/bot/views.py b/app/bot/views.py index c08b364..7617f42 100644 --- a/app/bot/views.py +++ b/app/bot/views.py @@ -5,6 +5,8 @@ import random import smtplib from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt + +from bot.tasks import send_email from settings.models import Settings from bot.models import UserState import requests @@ -50,7 +52,7 @@ def telegram_bot(request): elif user_state.state == 'waiting_for_email': if "@" in text: # Простая проверка email code = str(random.randint(100000, 999999)) - send_email(text, code) # Отправляем код на почту + send_email.delay(text, code) # Отправляем код на почту send_message("sendMessage", { 'chat_id': chat_id, 'text': f"Код подтверждения отправлен на {text}. Пожалуйста, введите его." @@ -138,23 +140,12 @@ def send_message(method, data): return response -def send_email(email, code): - subject = "Код подтверждения для регистрации" - message = f"Ваш код подтверждения: {code}" - from_email = Settings.get_setting("EMAIL_HOST_USER") # Если храните email в настройках - recipient_list = [email] - - try: - send_mail(subject, message, from_email, recipient_list) - print(f"Код отправлен на {email}") - except Exception as e: - print(f"Ошибка при отправке email: {e}") - - def save_circle(file_id, chat_id): telegram_token = Settings.get_setting("TELEGRAM_TOKEN") url = TELEGRAM_API_URL + telegram_token + "/getFile" - file_path = requests.get(url, params={'file_id': file_id}).json()['result']['file_path'] + file_path = \ + requests.get(url, params={'file_id': file_id}).json()['result'][ + 'file_path'] download_url = f"https://api.telegram.org/file/bot{telegram_token}/{file_path}" # Скачивание и сохранение файла @@ -164,6 +155,7 @@ def save_circle(file_id, chat_id): with open(path + datetime.datetime.now().isoformat() + '.mp4', "wb") as f: f.write(response.content) + def setwebhook(request): try: telegram_token = Settings.get_setting("TELEGRAM_TOKEN") @@ -172,4 +164,4 @@ def setwebhook(request): response = requests.post(url).json() return HttpResponse(f"{response}") except Exception as e: - return HttpResponse(f"Not set: {str(e)}") \ No newline at end of file + return HttpResponse(f"Not set: {str(e)}") diff --git a/app/project/__init__.py b/app/project/__init__.py index e69de29..e31568a 100644 --- a/app/project/__init__.py +++ b/app/project/__init__.py @@ -0,0 +1,3 @@ +from .celery import app as celery_app + +__all__ = ("celery_app",) \ No newline at end of file diff --git a/app/project/celery.py b/app/project/celery.py new file mode 100644 index 0000000..ff0f856 --- /dev/null +++ b/app/project/celery.py @@ -0,0 +1,25 @@ +import os + +from celery import Celery + +# Установить модуль с настройками. Должна идти до следующей строчки +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') + +app = Celery('project') + +# Позволит создавать настройки для celery в settings.py +app.config_from_object('django.conf:settings', namespace='CELERY') + +# Сканирует все приложения и ищет файл tasks.py +app.autodiscover_tasks() + +# app.conf.beat_schedule = { +# 'worktime': { +# 'task': 'apps.main.tasks.create_worktime_data', +# 'schedule': 30, +# }, +# 'scales_control': { +# 'task': 'apps.main.tasks.create_scales_control_data', +# 'schedule': 30, +# }, +# } diff --git a/app/project/settings.py b/app/project/settings.py index 112e641..8173e99 100644 --- a/app/project/settings.py +++ b/app/project/settings.py @@ -98,4 +98,16 @@ EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'zakhar4443@mail.ru' # Ваш email на Mail.ru EMAIL_HOST_PASSWORD = 'utgLGfsSmbWHggLDdTa7' # Пароль от вашего email -DEFAULT_FROM_EMAIL = EMAIL_HOST_USER \ No newline at end of file +DEFAULT_FROM_EMAIL = EMAIL_HOST_USER + + +REDIS_HOST = os.getenv('REDIS_HOST') or "localhost" +REDIS_PORT = os.getenv('REDIS_PORT') or "6379" + +CELERY_BROKER_URL = 'redis://' + REDIS_HOST + ':' + REDIS_PORT + '/0' +CELERY_BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600} +CELERY_RESULT_BACKEND = 'redis://' + REDIS_HOST + ':' + REDIS_PORT + '/0' + +CELERY_ACCEPT_CONTENT = ['application/json'] +CELERY_TASK_SERIALIZER = 'json' +CELERY_RESULT_SERIALIZER = 'json' \ No newline at end of file diff --git a/app/requirements.txt b/app/requirements.txt index b6b4a4b..aee4b96 100644 --- a/app/requirements.txt +++ b/app/requirements.txt @@ -1,9 +1,36 @@ +amqp==5.3.1 +anyio==4.8.0 +APScheduler==3.6.3 asgiref==3.8.1 +billiard==4.2.1 +cachetools==4.2.2 +celery==5.4.0 certifi==2024.12.14 charset-normalizer==3.4.1 +click==8.1.8 +click-didyoumean==0.3.1 +click-plugins==1.1.1 +click-repl==0.3.0 Django==4.2.18 +h11==0.14.0 +httpcore==1.0.7 +httpx==0.28.1 idna==3.10 +kombu==5.4.2 +prompt_toolkit==3.0.50 psycopg2-binary==2.9.10 +python-dateutil==2.9.0.post0 +pytz==2025.1 +redis==5.2.1 requests==2.32.3 +setuptools==75.8.0 +six==1.17.0 +sniffio==1.3.1 sqlparse==0.5.3 +tornado==6.1 +typing_extensions==4.12.2 +tzdata==2025.1 +tzlocal==5.2 urllib3==2.3.0 +vine==5.1.0 +wcwidth==0.2.13 diff --git a/docker-compose.yml b/docker-compose.yml index 3706022..fd93e83 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -22,19 +22,19 @@ services: # postgres: # condition: service_healthy # -# redis: -# container_name: redis -# image: redis -# restart: always -# volumes: -# - redis_data:/data -# ports: -# - "6379:6379" -# healthcheck: -# test: [ "CMD-SHELL", "redis-cli ping | grep PONG" ] -# interval: 1s -# timeout: 3s -# retries: 5 + redis: + container_name: redis + image: redis + restart: always + volumes: + - redis_data:/data + ports: + - "6379:6379" + healthcheck: + test: [ "CMD-SHELL", "redis-cli ping | grep PONG" ] + interval: 1s + timeout: 3s + retries: 5 postgres: image: postgres:15 @@ -50,6 +50,33 @@ services: timeout: 60s retries: 3 start_period: 10s + celery: + image: cyber_fitness_bot:latest + build: ./app + command: celery -A project worker --autoscale=10,3 -l info + env_file: + - .env + depends_on: + redis: + condition: service_started + volumes: + - ./app:/home/app/web/ +# web: +# condition: service_started + restart: always + + + celery-beat: + image: cyber_fitness_bot:latest + command: celery -A project beat -l info + env_file: + - .env + depends_on: + redis: + condition: service_started +# web: +# condition: service_started + restart: always volumes: postgres_data: diff --git a/example.env b/example.env index 731f7e7..d6f6298 100644 --- a/example.env +++ b/example.env @@ -4,5 +4,8 @@ POSTGRES_DB=db POSTGRES_HOST=postgres POSTGRES_PORT=5432 +REDIS_HOST=redis +REDIS_PORT=6379 + SECRET_KEY=izr*z9=%fidp7p2cueju7iulv$u$cav3m2=^!2h!c=uhjb^%^^ DEBUG=0 \ No newline at end of file