Compare commits

..

28 Commits

Author SHA1 Message Date
Egor Matveev
8799b3107b fix
All checks were successful
Deploy Dev / Build (pull_request) Successful in 22s
Deploy Dev / Push (pull_request) Successful in 13s
Deploy Dev / Deploy dev (pull_request) Successful in 17s
Deploy Prod / Build (pull_request) Successful in 6s
Deploy Prod / Push (pull_request) Successful in 9s
Deploy Prod / Deploy prod (pull_request) Successful in 17s
2025-09-15 00:33:18 +03:00
Egor Matveev
7a2950e480 fix
All checks were successful
Deploy Dev / Build (pull_request) Successful in 6s
Deploy Dev / Push (pull_request) Successful in 9s
Deploy Dev / Deploy dev (pull_request) Successful in 17s
2025-09-15 00:28:09 +03:00
Egor Matveev
7448b4e0c6 fix
All checks were successful
Deploy Dev / Build (pull_request) Successful in 20s
Deploy Dev / Push (pull_request) Successful in 9s
Deploy Dev / Deploy dev (pull_request) Successful in 17s
2025-09-15 00:19:20 +03:00
5e2c725bc2 Update helpers/answer.py
All checks were successful
Deploy Dev / Build (pull_request) Successful in 5s
Deploy Dev / Push (pull_request) Successful in 9s
Deploy Dev / Deploy dev (pull_request) Successful in 15s
Deploy Prod / Build (pull_request) Successful in 6s
Deploy Prod / Push (pull_request) Successful in 10s
Deploy Prod / Deploy prod (pull_request) Successful in 15s
2025-09-14 10:13:29 +03:00
595dfd0f6d Update .deploy/deploy-prod.yaml
All checks were successful
Deploy Dev / Build (pull_request) Successful in 52s
Deploy Dev / Push (pull_request) Successful in 28s
Deploy Dev / Deploy dev (pull_request) Successful in 15s
2025-09-12 21:20:29 +03:00
0990f684da Update .deploy/deploy-dev.yaml 2025-09-12 21:20:03 +03:00
Egor Matveev
5fa5789559 fix
All checks were successful
Deploy Prod / Build (pull_request) Successful in 4s
Deploy Prod / Push (pull_request) Successful in 9s
Deploy Prod / Deploy prod (pull_request) Successful in 14s
2025-06-15 23:30:50 +03:00
Egor Matveev
7fcbb316e6 fix
Some checks failed
Deploy Dev / Build (pull_request) Successful in 5s
Deploy Dev / Push (pull_request) Successful in 8s
Deploy Dev / Deploy dev (pull_request) Successful in 20s
Deploy Prod / Push (pull_request) Has been cancelled
Deploy Prod / Deploy prod (pull_request) Has been cancelled
Deploy Prod / Build (pull_request) Has been cancelled
2025-06-15 23:26:18 +03:00
Egor Matveev
e9ecb7d94f fix
All checks were successful
Deploy Dev / Build (pull_request) Successful in 5s
Deploy Dev / Push (pull_request) Successful in 10s
Deploy Dev / Deploy dev (pull_request) Successful in 23s
2025-06-15 15:02:35 +03:00
Egor Matveev
dbe5df157b fix
Some checks failed
Deploy Dev / Build (pull_request) Successful in 5s
Deploy Dev / Push (pull_request) Successful in 9s
Deploy Dev / Deploy dev (pull_request) Failing after 7s
2025-06-15 15:01:22 +03:00
Egor Matveev
f4af02ec1d fix
Some checks failed
Deploy Dev / Push (pull_request) Successful in 25s
Deploy Dev / Build (pull_request) Successful in 48s
Deploy Dev / Deploy dev (pull_request) Failing after 6s
2025-06-15 14:56:49 +03:00
156e1407ed fix
All checks were successful
Deploy Prod / Build (pull_request) Successful in 5s
Deploy Prod / Push (pull_request) Successful in 8s
Deploy Prod / Deploy prod (pull_request) Successful in 14s
2024-11-27 19:11:14 +03:00
18aabe497b fix
All checks were successful
Deploy Dev / Build (pull_request) Successful in 4s
Deploy Dev / Push (pull_request) Successful in 7s
Deploy Dev / Deploy dev (pull_request) Successful in 14s
Deploy Prod / Build (pull_request) Successful in 4s
Deploy Prod / Push (pull_request) Successful in 8s
Deploy Prod / Deploy prod (pull_request) Successful in 20s
2024-11-27 16:37:59 +03:00
144e5d4335 fix
All checks were successful
Deploy Dev / Build (pull_request) Successful in 4s
Deploy Dev / Push (pull_request) Successful in 7s
Deploy Dev / Deploy dev (pull_request) Successful in 15s
2024-11-27 16:35:19 +03:00
48ab0d1797 Merge branch 'master' of https://gitea.sprinthub.ru/self/ruz-bot
All checks were successful
Deploy Dev / Build (pull_request) Successful in 4s
Deploy Dev / Push (pull_request) Successful in 8s
Deploy Dev / Deploy dev (pull_request) Successful in 14s
2024-11-27 16:30:16 +03:00
ddfd5596d9 add 2024-11-27 16:29:37 +03:00
f8417edc94 Merge pull request 'queues' (#19) from queues into master
Reviewed-on: #19
2024-11-27 02:46:58 +03:00
292bacc963 fix
All checks were successful
Deploy Dev / Build (pull_request) Successful in 5s
Deploy Dev / Push (pull_request) Successful in 7s
Deploy Dev / Deploy dev (pull_request) Successful in 16s
Deploy Prod / Build (pull_request) Successful in 4s
Deploy Prod / Push (pull_request) Successful in 8s
Deploy Prod / Deploy prod (pull_request) Successful in 17s
2024-11-27 02:44:10 +03:00
e76cfc7994 fix
All checks were successful
Deploy Prod / Build (pull_request) Successful in 5s
Deploy Prod / Push (pull_request) Successful in 10s
Deploy Prod / Deploy prod (pull_request) Successful in 24s
2024-11-26 19:59:08 +03:00
c146fc7f1e fix
All checks were successful
Deploy Dev / Build (pull_request) Successful in 5s
Deploy Dev / Push (pull_request) Successful in 8s
Deploy Dev / Deploy dev (pull_request) Successful in 19s
Deploy Prod / Build (pull_request) Successful in 4s
Deploy Prod / Push (pull_request) Successful in 8s
Deploy Prod / Deploy prod (pull_request) Successful in 19s
2024-11-25 00:00:26 +03:00
2425ee2988 fix
All checks were successful
Deploy Dev / Build (pull_request) Successful in 4s
Deploy Dev / Push (pull_request) Successful in 8s
Deploy Dev / Deploy dev (pull_request) Successful in 17s
2024-11-24 23:55:46 +03:00
bc4f74e20f add 2024-11-24 23:54:28 +03:00
4e5d483208 fix
All checks were successful
Deploy Dev / Build (pull_request) Successful in 4s
Deploy Dev / Push (pull_request) Successful in 8s
Deploy Dev / Deploy dev (pull_request) Successful in 20s
2024-11-23 22:31:36 +03:00
1d00a27b15 fix
Some checks failed
Deploy Dev / Build (pull_request) Successful in 5s
Deploy Dev / Push (pull_request) Successful in 8s
Deploy Dev / Deploy dev (pull_request) Failing after 4s
2024-11-23 22:26:35 +03:00
c3886433ac fix
All checks were successful
Deploy Dev / Build (pull_request) Successful in 4s
Deploy Dev / Push (pull_request) Successful in 7s
Deploy Dev / Deploy dev (pull_request) Successful in 17s
2024-11-22 01:52:20 +03:00
ac1c8745dc fix
All checks were successful
Deploy Dev / Build (pull_request) Successful in 4s
Deploy Dev / Push (pull_request) Successful in 8s
Deploy Dev / Deploy dev (pull_request) Successful in 17s
2024-11-22 01:47:46 +03:00
17c9b1b693 fix
All checks were successful
Deploy Dev / Build (pull_request) Successful in 4s
Deploy Dev / Push (pull_request) Successful in 8s
Deploy Dev / Deploy dev (pull_request) Successful in 17s
2024-11-17 23:07:37 +03:00
e286a3078e fix
All checks were successful
Deploy Dev / Build (pull_request) Successful in 5s
Deploy Dev / Push (pull_request) Successful in 10s
Deploy Dev / Deploy dev (pull_request) Successful in 19s
2024-11-17 23:02:07 +03:00
14 changed files with 110 additions and 199 deletions

View File

@@ -3,29 +3,15 @@ version: "3.4"
services: services:
poll:
image: mathwave/sprint-repo:ruz-bot
environment:
STAGE: "development"
TELEGRAM_TOKEN: $TELEGRAM_TOKEN_DEV
QUEUES_TOKEN: $QUEUES_TOKEN_DEV
command: poll
deploy:
mode: replicated
restart_policy:
condition: any
update_config:
parallelism: 1
order: start-first
worker: worker:
image: mathwave/sprint-repo:ruz-bot image: mathwave/sprint-repo:ruz-bot
environment: environment:
MONGO_HOST: "mongo.develop.sprinthub.ru"
STAGE: "development" STAGE: "development"
MONGO_PASSWORD: $MONGO_PASSWORD_DEV MONGO_PASSWORD: $MONGO_PASSWORD_DEV
PLATFORM_SECURITY_TOKEN: $PLATFORM_SECURITY_TOKEN networks:
QUEUES_TOKEN: $QUEUES_TOKEN_DEV - queues-development
- configurator
- mongo-development
command: worker command: worker
deploy: deploy:
mode: replicated mode: replicated
@@ -35,29 +21,14 @@ services:
parallelism: 1 parallelism: 1
order: start-first order: start-first
mailbox:
image: mathwave/sprint-repo:ruz-bot
environment:
STAGE: "development"
TELEGRAM_TOKEN: $TELEGRAM_TOKEN_DEV
QUEUES_TOKEN: $QUEUES_TOKEN_DEV
command: mailbox
deploy:
mode: replicated
restart_policy:
condition: any
update_config:
parallelism: 1
order: start-first
fetch: fetch:
image: mathwave/sprint-repo:ruz-bot image: mathwave/sprint-repo:ruz-bot
environment: environment:
MONGO_HOST: "mongo.develop.sprinthub.ru"
STAGE: "development" STAGE: "development"
MONGO_PASSWORD: $MONGO_PASSWORD_DEV MONGO_PASSWORD: $MONGO_PASSWORD_DEV
PLATFORM_SECURITY_TOKEN: $PLATFORM_SECURITY_TOKEN networks:
QUEUES_TOKEN: $QUEUES_TOKEN_DEV - queues-development
- mongo-development
command: fetch command: fetch
deploy: deploy:
mode: replicated mode: replicated
@@ -70,11 +41,11 @@ services:
notify: notify:
image: mathwave/sprint-repo:ruz-bot image: mathwave/sprint-repo:ruz-bot
environment: environment:
MONGO_HOST: "mongo.develop.sprinthub.ru"
STAGE: "development" STAGE: "development"
MONGO_PASSWORD: $MONGO_PASSWORD_DEV MONGO_PASSWORD: $MONGO_PASSWORD_DEV
PLATFORM_SECURITY_TOKEN: $PLATFORM_SECURITY_TOKEN networks:
QUEUES_TOKEN: $QUEUES_TOKEN_DEV - queues-development
- mongo-development
command: notify command: notify
deploy: deploy:
mode: replicated mode: replicated
@@ -87,13 +58,12 @@ services:
ruz-bot-nginx: ruz-bot-nginx:
image: mathwave/sprint-repo:ruz-bot image: mathwave/sprint-repo:ruz-bot
networks: networks:
- common-infra-nginx - common-infra-nginx-development
- queues-development
- mongo-development
environment: environment:
MONGO_HOST: "mongo.develop.sprinthub.ru"
STAGE: "development" STAGE: "development"
MONGO_PASSWORD: $MONGO_PASSWORD_DEV MONGO_PASSWORD: $MONGO_PASSWORD_DEV
PLATFORM_SECURITY_TOKEN: $PLATFORM_SECURITY_TOKEN
QUEUES_TOKEN: $QUEUES_TOKEN_DEV
command: api command: api
deploy: deploy:
mode: replicated mode: replicated
@@ -104,5 +74,11 @@ services:
order: start-first order: start-first
networks: networks:
common-infra-nginx: common-infra-nginx-development:
external: true
queues-development:
external: true
configurator:
external: true
mongo-development:
external: true external: true

View File

@@ -3,29 +3,15 @@ version: "3.4"
services: services:
poll:
image: mathwave/sprint-repo:ruz-bot
environment:
STAGE: "production"
TELEGRAM_TOKEN: $TELEGRAM_TOKEN_PROD
QUEUES_TOKEN: $QUEUES_TOKEN_PROD
command: poll
deploy:
mode: replicated
restart_policy:
condition: any
update_config:
parallelism: 1
order: start-first
worker: worker:
image: mathwave/sprint-repo:ruz-bot image: mathwave/sprint-repo:ruz-bot
environment: environment:
MONGO_HOST: "mongo.sprinthub.ru"
STAGE: "production" STAGE: "production"
MONGO_PASSWORD: $MONGO_PASSWORD_PROD MONGO_PASSWORD: $MONGO_PASSWORD_PROD
PLATFORM_SECURITY_TOKEN: $PLATFORM_SECURITY_TOKEN networks:
QUEUES_TOKEN: $QUEUES_TOKEN_PROD - queues
- configurator
- mongo
command: worker command: worker
deploy: deploy:
mode: replicated mode: replicated
@@ -35,39 +21,21 @@ services:
parallelism: 1 parallelism: 1
order: start-first order: start-first
mailbox:
image: mathwave/sprint-repo:ruz-bot
environment:
STAGE: "production"
TELEGRAM_TOKEN: $TELEGRAM_TOKEN_PROD
QUEUES_TOKEN: $QUEUES_TOKEN_PROD
command: mailbox
deploy:
mode: replicated
restart_policy:
condition: any
update_config:
parallelism: 1
order: start-first
fetch: fetch:
image: mathwave/sprint-repo:ruz-bot image: mathwave/sprint-repo:ruz-bot
environment: environment:
MONGO_HOST: "mongo.sprinthub.ru"
STAGE: "production" STAGE: "production"
MONGO_PASSWORD: $MONGO_PASSWORD_PROD MONGO_PASSWORD: $MONGO_PASSWORD_PROD
PLATFORM_SECURITY_TOKEN: $PLATFORM_SECURITY_TOKEN
DEBUG: "false" DEBUG: "false"
QUEUES_TOKEN: $QUEUES_TOKEN_PROD networks:
- queues
- configurator
- mongo
command: fetch command: fetch
deploy: deploy:
mode: replicated mode: replicated
restart_policy: restart_policy:
condition: any condition: any
placement:
constraints:
- node.role == worker
- node.labels.zone == ru
update_config: update_config:
parallelism: 1 parallelism: 1
order: start-first order: start-first
@@ -75,21 +43,18 @@ services:
notify: notify:
image: mathwave/sprint-repo:ruz-bot image: mathwave/sprint-repo:ruz-bot
environment: environment:
MONGO_HOST: "mongo.sprinthub.ru"
STAGE: "production" STAGE: "production"
MONGO_PASSWORD: $MONGO_PASSWORD_PROD MONGO_PASSWORD: $MONGO_PASSWORD_PROD
PLATFORM_SECURITY_TOKEN: $PLATFORM_SECURITY_TOKEN
DEBUG: "false" DEBUG: "false"
QUEUES_TOKEN: $QUEUES_TOKEN_PROD networks:
- queues
- configurator
- mongo
command: notify command: notify
deploy: deploy:
mode: replicated mode: replicated
restart_policy: restart_policy:
condition: any condition: any
placement:
constraints:
- node.role == worker
- node.labels.zone == ru
update_config: update_config:
parallelism: 1 parallelism: 1
order: start-first order: start-first
@@ -98,21 +63,17 @@ services:
image: mathwave/sprint-repo:ruz-bot image: mathwave/sprint-repo:ruz-bot
networks: networks:
- common-infra-nginx - common-infra-nginx
- configurator
- mongo
environment: environment:
MONGO_HOST: "mongo.sprinthub.ru"
STAGE: "production" STAGE: "production"
MONGO_PASSWORD: $MONGO_PASSWORD_PROD MONGO_PASSWORD: $MONGO_PASSWORD_PROD
PLATFORM_SECURITY_TOKEN: $PLATFORM_SECURITY_TOKEN
DEBUG: "false" DEBUG: "false"
command: api command: api
deploy: deploy:
mode: replicated mode: replicated
restart_policy: restart_policy:
condition: any condition: any
placement:
constraints:
- node.role == worker
- node.labels.zone == ru
update_config: update_config:
parallelism: 1 parallelism: 1
order: start-first order: start-first
@@ -120,3 +81,9 @@ services:
networks: networks:
common-infra-nginx: common-infra-nginx:
external: true external: true
queues:
external: true
configurator:
external: true
mongo:
external: true

View File

@@ -28,7 +28,7 @@ jobs:
run: docker push mathwave/sprint-repo:ruz-bot run: docker push mathwave/sprint-repo:ruz-bot
deploy-dev: deploy-dev:
name: Deploy dev name: Deploy dev
runs-on: [dev] runs-on: [prod]
needs: push needs: push
steps: steps:
- name: login - name: login
@@ -41,6 +41,4 @@ jobs:
env: env:
TELEGRAM_TOKEN_DEV: ${{ secrets.TELEGRAM_TOKEN_DEV }} TELEGRAM_TOKEN_DEV: ${{ secrets.TELEGRAM_TOKEN_DEV }}
MONGO_PASSWORD_DEV: ${{ secrets.MONGO_PASSWORD_DEV }} MONGO_PASSWORD_DEV: ${{ secrets.MONGO_PASSWORD_DEV }}
PLATFORM_SECURITY_TOKEN: ${{ secrets.PLATFORM_SECURITY_TOKEN }} run: docker stack deploy --with-registry-auth -c ./.deploy/deploy-dev.yaml ruz-bot-development
QUEUES_TOKEN_DEV: ${{ secrets.QUEUES_TOKEN_DEV }}
run: docker stack deploy --with-registry-auth -c ./.deploy/deploy-dev.yaml ruz-bot

View File

@@ -42,5 +42,4 @@ jobs:
TELEGRAM_TOKEN_PROD: ${{ secrets.TELEGRAM_TOKEN_PROD }} TELEGRAM_TOKEN_PROD: ${{ secrets.TELEGRAM_TOKEN_PROD }}
MONGO_PASSWORD_PROD: ${{ secrets.MONGO_PASSWORD_PROD }} MONGO_PASSWORD_PROD: ${{ secrets.MONGO_PASSWORD_PROD }}
PLATFORM_SECURITY_TOKEN: ${{ secrets.PLATFORM_SECURITY_TOKEN }} PLATFORM_SECURITY_TOKEN: ${{ secrets.PLATFORM_SECURITY_TOKEN }}
QUEUES_TOKEN_PROD: ${{ secrets.QUEUES_TOKEN_PROD }}
run: docker stack deploy --with-registry-auth -c ./.deploy/deploy-prod.yaml ruz-bot run: docker stack deploy --with-registry-auth -c ./.deploy/deploy-prod.yaml ruz-bot

View File

@@ -7,6 +7,7 @@ RUN apt-get install -y locales locales-all
ENV LANGUAGE ru_RU.UTF-8 ENV LANGUAGE ru_RU.UTF-8
ENV LANG ru_RU.UTF-8 ENV LANG ru_RU.UTF-8
ENV LC_ALL ru_RU.UTF-8 ENV LC_ALL ru_RU.UTF-8
ENV PYTHONUNBUFFERED=1
COPY requirements.txt requirements.txt COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt RUN pip install -r requirements.txt
COPY . . COPY . .

View File

@@ -1,28 +0,0 @@
import telebot
import os
from daemons import base
from utils import queues
class Daemon(base.Daemon, queues.TasksHandlerMixin):
def __init__(self):
super().__init__()
self.bot = telebot.TeleBot(os.getenv("TELEGRAM_TOKEN"))
@property
def queue_name(self):
return 'pizda_bot_mailbox'
def execute(self):
self.poll()
def process(self, payload):
body = {
'chat_id': payload['chat_id'],
'text': payload['text'],
}
reply_markup = payload.get('reply_markup')
if reply_markup:
body['reply_markup'] = reply_markup
self.bot.send_message(**body, parse_mode='Markdown')

View File

@@ -25,7 +25,7 @@ def process():
ans += f"🧑‍🏫 {(lesson['lecturer'] or 'Неизвестно')}\n" ans += f"🧑‍🏫 {(lesson['lecturer'] or 'Неизвестно')}\n"
if lesson.get('link', None): if lesson.get('link', None):
ans += f"🔗 {lesson['link']}" ans += f"🔗 {lesson['link']}"
queues.set_task('ruz_bot_mailbox', {'text': f"Через {user['notify_minutes']} минут у тебя занятие!\n" + ans, 'chat_id': user["chat_id"]}, 1) queues.set_task('botalka_mailbox', {'project': 'ruz-bot', 'name': 'telegram-bot', 'body': {'text': f"Через {user['notify_minutes']} минут у тебя занятие!\n" + ans, 'chat_id': user["chat_id"], 'parse_mode': 'Markdown'}}, 1)
mongo.lessons_collection.update_one({"_id": lesson['_id']}, {"$set": {"notified": True}}) mongo.lessons_collection.update_one({"_id": lesson['_id']}, {"$set": {"notified": True}})
time_now = datetime.datetime.now() time_now = datetime.datetime.now()
for user in mongo.users_collection.find({"next_daily_notify_time": {"$lte": time_now}}): for user in mongo.users_collection.find({"next_daily_notify_time": {"$lte": time_now}}):
@@ -40,7 +40,7 @@ def process():
else: else:
text = ruz.schedule_builder(lessons) text = ruz.schedule_builder(lessons)
try: try:
queues.set_task('ruz_bot_mailbox', {'text': f"Уведомляю о занятиях! Твое расписание на {'сегодня' if user.get('daily_notify_today', True) else 'завтра'}:\n" + text, 'chat_id': user["chat_id"]}, 1) queues.set_task('botalka_mailbox', {'project': 'ruz-bot', 'name': 'telegram-bot', 'body': {'text': f"Уведомляю о занятиях! Твое расписание на {'сегодня' if user.get('daily_notify_today', True) else 'завтра'}:\n" + text, 'chat_id': user["chat_id"], 'parse_mode': 'Markdown'}}, 1)
except: except:
pass pass
mongo.users_collection.update_one( mongo.users_collection.update_one(
@@ -72,7 +72,7 @@ def process():
else: else:
mess += "12 часов" mess += "12 часов"
mess += "!\n\nТвоя первая пара:\n\n" + ans mess += "!\n\nТвоя первая пара:\n\n" + ans
queues.set_task('ruz_bot_mailbox', {'text': mess, 'chat_id': user["chat_id"]}, 1) queues.set_task('botalka_mailbox', {'project': 'ruz-bot', 'name': 'telegram-bot', 'body': {'text': mess, 'chat_id': user["chat_id"], 'parse_mode': 'Markdown'}}, 1)
start_of_day = datetime.datetime(year=time_now.year, month=time_now.month, day=time_now.day) start_of_day = datetime.datetime(year=time_now.year, month=time_now.month, day=time_now.day)
mongo.lessons_collection.update_many({"begin": {"$gte": start_of_day, "$lt": (start_of_day + datetime.timedelta(days=1))}, "user_email": user["email"]}, {"$set": {"notified_today": True}}) mongo.lessons_collection.update_many({"begin": {"$gte": start_of_day, "$lt": (start_of_day + datetime.timedelta(days=1))}, "user_email": user["email"]}, {"$set": {"notified_today": True}})
break break

View File

@@ -1,15 +0,0 @@
import os
import telebot
from daemons import base
from telebot import types
from utils import queues
class Daemon(base.Daemon):
def execute(self):
bot = telebot.TeleBot(os.getenv("TELEGRAM_TOKEN"))
@bot.message_handler()
def do_action(message: types.Message):
queues.set_task('ruz_bot_worker', message.json, 1)
bot.polling()

View File

@@ -1,9 +1,9 @@
import logging import logging
from typing import Optional from typing import Optional
from daemons.bot import bot
from helpers import now from helpers import now
from helpers.mongo import mongo from helpers.mongo import mongo
from utils import queues
def try_parse(message: str) -> Optional[int]: def try_parse(message: str) -> Optional[int]:
@@ -84,7 +84,7 @@ class Processor:
} }
else: else:
mongo.users_collection.update_one({"yandex_code": code}, {"$set": {"yandex_id": self.user_id, "yandex_code": None}}) mongo.users_collection.update_one({"yandex_code": code}, {"$set": {"yandex_id": self.user_id, "yandex_code": None}})
bot.send_message(user['chat_id'], "Алиса успешно подключена!") queues.set_task('ruz_bot_mailbox', {'text': "Алиса успешно подключена!", 'chat_id': user["chat_id"]}, 1)
lesson = self.get_lesson_for_user(user['chat_id']) lesson = self.get_lesson_for_user(user['chat_id'])
if lesson is None: if lesson is None:
return { return {

View File

@@ -55,13 +55,6 @@ class Answer:
def process(self): def process(self):
user = User(self.user['chat_id']) user = User(self.user['chat_id'])
try:
bot_enabled_exp = platform.get_experiment('bot_enabled')
if not bot_enabled_exp['enabled'] or not eval(bot_enabled_exp['condition']):
return
except Exception as exc:
logging.info(exc)
return
getattr( getattr(
self, self,
"handle_state_" + self.user['state'], "handle_state_" + self.user['state'],
@@ -74,10 +67,10 @@ class Answer:
def send_message(self, text, reply_markup=None, remove_keyboard=True, **kwargs): def send_message(self, text, reply_markup=None, remove_keyboard=True, **kwargs):
if reply_markup is None and remove_keyboard: if reply_markup is None and remove_keyboard:
reply_markup = ReplyKeyboardRemove() reply_markup = ReplyKeyboardRemove()
body = {'text': text, 'chat_id': self.user['chat_id']} body = {'text': text, 'chat_id': self.user['chat_id'], 'parse_mode': 'Markdown'}
if reply_markup: if reply_markup:
body['reply_markup'] = reply_markup.to_json() body['reply_markup'] = reply_markup.to_json()
queues.set_task('ruz_bot_mailbox', body, 1) queues.set_task('botalka_mailbox', {'project': 'ruz-bot', 'name': 'telegram-bot', 'body': body}, 5)
def set_state(self, state: str): def set_state(self, state: str):
self.user['state'] = state self.user['state'] = state

View File

@@ -9,7 +9,7 @@ from helpers import now
class Mongo: class Mongo:
def __init__(self): def __init__(self):
url = f"mongodb://{settings.MONGO_USER}:{settings.MONGO_PASSWORD}@{settings.MONGO_HOST}:27017/" url = f"mongodb://{settings.MONGO_USER}:{settings.MONGO_PASSWORD}@mongo:27017/"
self.client = pymongo.MongoClient(url) self.client = pymongo.MongoClient(url)
self.database = self.client.get_database("ruz-bot") self.database = self.client.get_database("ruz-bot")
self.users_collection.create_index([ self.users_collection.create_index([

View File

@@ -12,7 +12,8 @@ fields = [
'date_start', 'date_start',
'date_end', 'date_end',
'lecturer_profiles', 'lecturer_profiles',
'stream_links' 'stream_links',
'type',
] ]

View File

@@ -15,11 +15,8 @@ class PlatformClient:
self.stage = stage self.stage = stage
self.configs = configs self.configs = configs
self.experiments = experiments self.experiments = experiments
self.endpoint = 'https://platform.sprinthub.ru/' self.endpoint = 'http://configurator/'
self.configs_url = urllib.parse.urljoin(self.endpoint, 'configs/get') self.fetch_url = urllib.parse.urljoin(self.endpoint, '/api/v1/fetch')
self.experiments_url = urllib.parse.urljoin(self.endpoint, 'experiments/get')
self.staff_url = urllib.parse.urljoin(self.endpoint, 'is_staff')
self.fetch_url = urllib.parse.urljoin(self.endpoint, 'fetch')
self.config_storage = {} self.config_storage = {}
self.experiment_storage = {} self.experiment_storage = {}
self.staff_storage = {} self.staff_storage = {}
@@ -44,7 +41,6 @@ class PlatformClient:
try: try:
response = get( response = get(
url, url,
headers={'X-Security-Token': self.platform_security_token},
params=params params=params
) )
if response.status_code == 200: if response.status_code == 200:

View File

@@ -1,18 +1,17 @@
import json from concurrent.futures import ThreadPoolExecutor
import datetime
import os import os
import traceback
import zoneinfo
import requests import requests
import time import time
stage = os.getenv("STAGE", 'local') stage = os.getenv("STAGE", 'local')
if stage == 'development': if stage == 'local':
QUEUES_URL = 'https://queues.develop.sprinthub.ru' QUEUES_URL = 'http://localhost:1239'
elif stage == 'production':
QUEUES_URL = 'https://queues.sprinthub.ru'
else: else:
QUEUES_URL = None QUEUES_URL = 'http://queues:1239'
token = os.getenv('QUEUES_TOKEN')
class QueuesException(Exception): class QueuesException(Exception):
@@ -20,31 +19,55 @@ class QueuesException(Exception):
class TasksHandlerMixin: class TasksHandlerMixin:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.executor = ThreadPoolExecutor(max_workers=1)
def _send_metric(self, start: datetime.datetime, end: datetime.datetime, success: bool):
def send():
requests.post(f'{QUEUES_URL}/api/v1/metric', json={
'service': 'ruz-bot',
'queue': self.queue_name,
'success': success,
'timestamp': start.strftime("%Y-%m-%dT%H:%M:%S") + "Z",
"success": success,
"execution_time_ms": (end - start).microseconds // 1000,
"environment": stage,
})
self.executor.submit(send)
def poll(self): def poll(self):
while True: while True:
if QUEUES_URL is None:
data = {'payload': json.loads(input('Input message: '))}
else:
response = requests.get(f'{QUEUES_URL}/api/v1/take', headers={'queue': self.queue_name, 'X-Queues-Token': token})
if response.status_code == 404:
time.sleep(0.2)
continue
if response.status_code == 403:
raise NotImplemented('QUEUE_TOKEN is incorrect')
data = response.json()
try: try:
self.process(data['payload']) response = requests.get(f'{QUEUES_URL}/api/v1/take', headers={'queue': self.queue_name}).json()
except requests.JSONDecodeError:
print('Unable to decode json')
time.sleep(3)
continue
task = response.get('task')
if not task:
time.sleep(0.2)
continue
start = datetime.datetime.now(zoneinfo.ZoneInfo("Europe/Moscow"))
try:
print(f'process task with id {task["id"]}, attempt {task["attempt"]}')
self.process(task['payload'])
success = True
except Exception as exc: except Exception as exc:
print(f'Error processing message id={data["id"]}, payload={data["payload"]}, exc={exc}') print(f'Error processing message id={task["id"]}, payload={task["payload"]}, exc={exc}')
continue traceback.print_exc()
if QUEUES_URL is None: success = False
continue end = datetime.datetime.now(zoneinfo.ZoneInfo("Europe/Moscow"))
try: if success:
resp = requests.post(f'{QUEUES_URL}/api/v1/finish', json={'id': data['id']}, headers={'X-Queues-Token': token}) try:
if resp.status_code != 202: resp = requests.post(f'{QUEUES_URL}/api/v1/finish', json={'id': task['id']})
raise QueuesException if resp.status_code != 202:
except: raise QueuesException
print(f'Failed to finish task id={data["id"]}') print(f'finish task with id {task["id"]}')
except:
print(f'Failed to finish task id={task["id"]}')
self._send_metric(start, end, success)
@property @property
def queue_name(self): def queue_name(self):
@@ -55,7 +78,7 @@ class TasksHandlerMixin:
def set_task(queue_name: str, payload: dict, seconds_to_execute: int, delay: int|None = None): def set_task(queue_name: str, payload: dict, seconds_to_execute: int, delay: int|None = None):
resp = requests.post(f'{QUEUES_URL}/api/v1/put', headers={'queue': queue_name, 'X-Queues-Token': token}, json={ resp = requests.post(f'{QUEUES_URL}/api/v1/put', headers={'queue': queue_name}, json={
'payload': payload, 'payload': payload,
'seconds_to_execute': seconds_to_execute, 'seconds_to_execute': seconds_to_execute,
'delay': delay, 'delay': delay,