Compare commits
No commits in common. "master" and "queues" have entirely different histories.
@ -2,6 +2,23 @@ version: "3.4"
|
||||
|
||||
|
||||
services:
|
||||
|
||||
poll:
|
||||
image: mathwave/sprint-repo:pizda-bot
|
||||
command: poll
|
||||
environment:
|
||||
TELEGRAM_TOKEN: $TELEGRAM_TOKEN_DEV
|
||||
STAGE: "development"
|
||||
networks:
|
||||
- queues
|
||||
deploy:
|
||||
mode: replicated
|
||||
restart_policy:
|
||||
condition: any
|
||||
update_config:
|
||||
parallelism: 1
|
||||
order: start-first
|
||||
|
||||
worker:
|
||||
image: mathwave/sprint-repo:pizda-bot
|
||||
command: worker
|
||||
@ -9,9 +26,25 @@ services:
|
||||
MONGO_HOST: "mongo.develop.sprinthub.ru"
|
||||
MONGO_PASSWORD: $MONGO_PASSWORD_DEV
|
||||
STAGE: "development"
|
||||
PLATFORM_SECURITY_TOKEN: $PLATFORM_SECURITY_TOKEN
|
||||
networks:
|
||||
- queues-development
|
||||
- configurator
|
||||
- queues
|
||||
deploy:
|
||||
mode: replicated
|
||||
restart_policy:
|
||||
condition: any
|
||||
update_config:
|
||||
parallelism: 1
|
||||
order: start-first
|
||||
|
||||
mailbox:
|
||||
image: mathwave/sprint-repo:pizda-bot
|
||||
command: mailbox
|
||||
environment:
|
||||
TELEGRAM_TOKEN: $TELEGRAM_TOKEN_DEV
|
||||
STAGE: "development"
|
||||
networks:
|
||||
- queues
|
||||
deploy:
|
||||
mode: replicated
|
||||
restart_policy:
|
||||
@ -24,11 +57,13 @@ services:
|
||||
image: mathwave/sprint-repo:pizda-bot
|
||||
command: api
|
||||
environment:
|
||||
TELEGRAM_TOKEN: $TELEGRAM_TOKEN_DEV
|
||||
MONGO_HOST: "mongo.develop.sprinthub.ru"
|
||||
MONGO_PASSWORD: $MONGO_PASSWORD_DEV
|
||||
PLATFORM_SECURITY_TOKEN: $PLATFORM_SECURITY_TOKEN
|
||||
STAGE: "development"
|
||||
networks:
|
||||
- common-infra-nginx-development
|
||||
- common-infra-nginx
|
||||
deploy:
|
||||
mode: replicated
|
||||
restart_policy:
|
||||
@ -38,9 +73,7 @@ services:
|
||||
order: start-first
|
||||
|
||||
networks:
|
||||
common-infra-nginx-development:
|
||||
common-infra-nginx:
|
||||
external: true
|
||||
queues-development:
|
||||
external: true
|
||||
configurator:
|
||||
queues:
|
||||
external: true
|
||||
|
@ -2,6 +2,23 @@ version: "3.4"
|
||||
|
||||
|
||||
services:
|
||||
|
||||
poll:
|
||||
image: mathwave/sprint-repo:pizda-bot
|
||||
command: poll
|
||||
environment:
|
||||
TELEGRAM_TOKEN: $TELEGRAM_TOKEN_PROD
|
||||
STAGE: "production"
|
||||
networks:
|
||||
- queues
|
||||
deploy:
|
||||
mode: replicated
|
||||
restart_policy:
|
||||
condition: any
|
||||
update_config:
|
||||
parallelism: 1
|
||||
order: start-first
|
||||
|
||||
worker:
|
||||
image: mathwave/sprint-repo:pizda-bot
|
||||
command: worker
|
||||
@ -9,9 +26,25 @@ services:
|
||||
MONGO_HOST: "mongo.sprinthub.ru"
|
||||
MONGO_PASSWORD: $MONGO_PASSWORD_PROD
|
||||
STAGE: "production"
|
||||
PLATFORM_SECURITY_TOKEN: $PLATFORM_SECURITY_TOKEN
|
||||
networks:
|
||||
- queues
|
||||
deploy:
|
||||
mode: replicated
|
||||
restart_policy:
|
||||
condition: any
|
||||
update_config:
|
||||
parallelism: 1
|
||||
order: start-first
|
||||
|
||||
mailbox:
|
||||
image: mathwave/sprint-repo:pizda-bot
|
||||
command: mailbox
|
||||
environment:
|
||||
TELEGRAM_TOKEN: $TELEGRAM_TOKEN_PROD
|
||||
STAGE: "production"
|
||||
networks:
|
||||
- queues
|
||||
- configurator
|
||||
deploy:
|
||||
mode: replicated
|
||||
restart_policy:
|
||||
@ -24,8 +57,11 @@ services:
|
||||
image: mathwave/sprint-repo:pizda-bot
|
||||
command: api
|
||||
environment:
|
||||
TELEGRAM_TOKEN: $TELEGRAM_TOKEN_PROD
|
||||
MONGO_HOST: "mongo.sprinthub.ru"
|
||||
MONGO_PASSWORD: $MONGO_PASSWORD_PROD
|
||||
PLATFORM_SECURITY_TOKEN: $PLATFORM_SECURITY_TOKEN
|
||||
STAGE: "production"
|
||||
networks:
|
||||
- common-infra-nginx
|
||||
deploy:
|
||||
@ -41,5 +77,3 @@ networks:
|
||||
external: true
|
||||
queues:
|
||||
external: true
|
||||
configurator:
|
||||
external: true
|
||||
|
@ -28,7 +28,7 @@ jobs:
|
||||
run: docker push mathwave/sprint-repo:pizda-bot
|
||||
deploy-dev:
|
||||
name: Deploy dev
|
||||
runs-on: [prod]
|
||||
runs-on: [dev]
|
||||
needs: push
|
||||
steps:
|
||||
- name: login
|
||||
@ -39,5 +39,7 @@ jobs:
|
||||
ref: dev
|
||||
- name: deploy
|
||||
env:
|
||||
TELEGRAM_TOKEN_DEV: ${{ secrets.TELEGRAM_TOKEN_DEV }}
|
||||
MONGO_PASSWORD_DEV: ${{ secrets.MONGO_PASSWORD_DEV }}
|
||||
run: docker stack deploy --with-registry-auth -c ./.deploy/deploy-dev.yaml pizda-bot-development
|
||||
PLATFORM_SECURITY_TOKEN: ${{ secrets.PLATFORM_SECURITY_TOKEN }}
|
||||
run: docker stack deploy --with-registry-auth -c ./.deploy/deploy-dev.yaml pizda-bot
|
||||
|
@ -39,5 +39,7 @@ jobs:
|
||||
ref: prod
|
||||
- name: deploy
|
||||
env:
|
||||
TELEGRAM_TOKEN_PROD: ${{ secrets.TELEGRAM_TOKEN_PROD }}
|
||||
MONGO_PASSWORD_PROD: ${{ secrets.MONGO_PASSWORD_PROD }}
|
||||
PLATFORM_SECURITY_TOKEN: ${{ secrets.PLATFORM_SECURITY_TOKEN }}
|
||||
run: docker stack deploy --with-registry-auth -c ./.deploy/deploy-prod.yaml pizda-bot
|
||||
|
4
.gitignore
vendored
4
.gitignore
vendored
@ -116,6 +116,4 @@ GitHub.sublime-settings
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
.history
|
||||
|
||||
*pb2*
|
||||
.history
|
51
.gitlab-ci.yml
Normal file
51
.gitlab-ci.yml
Normal file
@ -0,0 +1,51 @@
|
||||
stages:
|
||||
- build
|
||||
- deploy-dev
|
||||
- deploy-prod
|
||||
|
||||
build:
|
||||
stage: build
|
||||
tags:
|
||||
- dev
|
||||
before_script:
|
||||
- docker login -u mathwave -p $DOCKERHUB_PASSWORD
|
||||
script:
|
||||
- docker build -t mathwave/sprint-repo:pizda-bot .
|
||||
|
||||
push:
|
||||
stage: build
|
||||
tags:
|
||||
- dev
|
||||
before_script:
|
||||
- docker login -u mathwave -p $DOCKERHUB_PASSWORD
|
||||
script:
|
||||
- docker push mathwave/sprint-repo:pizda-bot
|
||||
|
||||
.deploy:
|
||||
before_script:
|
||||
- docker login -u mathwave -p $DOCKERHUB_PASSWORD
|
||||
|
||||
deploy-dev:
|
||||
extends:
|
||||
- .deploy
|
||||
stage: deploy-dev
|
||||
tags:
|
||||
- dev
|
||||
rules:
|
||||
- if: '$CI_COMMIT_BRANCH == "master"'
|
||||
when: on_success
|
||||
- when: manual
|
||||
script:
|
||||
- docker stack deploy --with-registry-auth -c ./.deploy/deploy-dev.yaml pizda-bot
|
||||
|
||||
deploy-prod:
|
||||
extends:
|
||||
- .deploy
|
||||
stage: deploy-prod
|
||||
tags:
|
||||
- prod
|
||||
only:
|
||||
- master
|
||||
when: manual
|
||||
script:
|
||||
- docker stack deploy --with-registry-auth -c ./.deploy/deploy-prod.yaml pizda-bot
|
@ -2,7 +2,7 @@ from collections import defaultdict
|
||||
|
||||
from flask import Flask
|
||||
|
||||
from utils.mongo import mongo
|
||||
from mongo import mongo
|
||||
|
||||
app = Flask(__name__)
|
||||
|
@ -1,13 +1,3 @@
|
||||
import os
|
||||
|
||||
|
||||
stage = os.getenv("STAGE", 'local')
|
||||
if stage == 'local':
|
||||
QUEUES_URL = 'localhost:50051'
|
||||
else:
|
||||
QUEUES_URL = 'queues-grpc:50051'
|
||||
|
||||
|
||||
class Daemon:
|
||||
class BaseDaemon:
|
||||
def execute(self):
|
||||
raise NotImplemented
|
||||
raise NotImplementedError
|
||||
|
27
daemons/mailbox.py
Normal file
27
daemons/mailbox.py
Normal file
@ -0,0 +1,27 @@
|
||||
import telebot
|
||||
import os
|
||||
|
||||
from daemons import base
|
||||
from utils import queues
|
||||
|
||||
|
||||
class Daemon(base.BaseDaemon, 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['message'],
|
||||
}
|
||||
if payload['action'] == 'reply':
|
||||
body['reply_to_message_id'] = payload['reply_to']
|
||||
self.bot.send_message(**body)
|
16
daemons/poll.py
Normal file
16
daemons/poll.py
Normal file
@ -0,0 +1,16 @@
|
||||
import os
|
||||
import json
|
||||
import telebot
|
||||
|
||||
from daemons import base
|
||||
from telebot import types
|
||||
from utils import queues
|
||||
|
||||
|
||||
class Daemon(base.BaseDaemon):
|
||||
def execute(self):
|
||||
bot = telebot.TeleBot(os.getenv("TELEGRAM_TOKEN"))
|
||||
@bot.message_handler()
|
||||
def do_action(message: types.Message):
|
||||
queues.set_task('pizda_bot_worker', message.json, 1)
|
||||
bot.polling()
|
@ -6,9 +6,9 @@ from utils import queues
|
||||
from telebot.types import Message
|
||||
import json
|
||||
|
||||
from utils.mongo import mongo
|
||||
from utils.sprint_platform import PlatformClient
|
||||
from utils.storage import set_values, get_chat_info
|
||||
from mongo import mongo
|
||||
from sprint_platform import PlatformClient
|
||||
from storage import set_values, get_chat_info
|
||||
|
||||
security_token = os.getenv("PLATFORM_SECURITY_TOKEN")
|
||||
stage = os.getenv("STAGE", 'local')
|
||||
@ -35,15 +35,11 @@ def get_answers():
|
||||
return client.get_config('answers')
|
||||
|
||||
|
||||
def get_ignored_users():
|
||||
return client.get_config('ignored_users')['users']
|
||||
|
||||
|
||||
def get_replies():
|
||||
return client.get_config('replies')
|
||||
|
||||
|
||||
class Daemon(base.Daemon, queues.TasksHandlerMixin):
|
||||
class Daemon(base.BaseDaemon, queues.TasksHandlerMixin):
|
||||
@property
|
||||
def queue_name(self):
|
||||
return 'pizda_bot_worker'
|
||||
@ -53,29 +49,23 @@ class Daemon(base.Daemon, queues.TasksHandlerMixin):
|
||||
|
||||
def reply(self, text: str, chat_id: int, message_id: int):
|
||||
queues.set_task(
|
||||
'botalka_mailbox',
|
||||
'pizda_bot_mailbox',
|
||||
{
|
||||
'project': 'pizda-bot',
|
||||
'name': 'telegram-bot',
|
||||
'body': {
|
||||
'text': text,
|
||||
'reply_to_message_id': message_id,
|
||||
'chat_id': chat_id,
|
||||
}
|
||||
'action': 'reply',
|
||||
'message': text,
|
||||
'reply_to': message_id,
|
||||
'chat_id': chat_id
|
||||
},
|
||||
1,
|
||||
)
|
||||
|
||||
def send(self, text: str, chat_id: int):
|
||||
queues.set_task(
|
||||
'botalka_mailbox',
|
||||
'pizda_bot_mailbox',
|
||||
{
|
||||
'project': 'pizda-bot',
|
||||
'name': 'telegram-bot',
|
||||
'body': {
|
||||
'text': text,
|
||||
'chat_id': chat_id,
|
||||
}
|
||||
'action': 'send',
|
||||
'message': text,
|
||||
'chat_id': chat_id
|
||||
},
|
||||
1,
|
||||
)
|
||||
@ -123,8 +113,6 @@ class Daemon(base.Daemon, queues.TasksHandlerMixin):
|
||||
|
||||
def process(self, payload):
|
||||
message: Message = Message.de_json(json.dumps(payload))
|
||||
if not message.text:
|
||||
return
|
||||
if message.text.startswith('/'):
|
||||
self.process_command(message)
|
||||
return
|
||||
@ -155,6 +143,6 @@ class Daemon(base.Daemon, queues.TasksHandlerMixin):
|
||||
else:
|
||||
return
|
||||
ans = get_answers().get(convert_text)
|
||||
if ans is not None and randrange(1, 101) <= info["probability"] and message.from_user.id not in get_ignored_users():
|
||||
if ans is not None and randrange(1, 101) <= info["probability"]:
|
||||
self.reply(ans, message.chat.id, message.message_id)
|
||||
mongo.inc(message.from_user.username, message.chat.id)
|
||||
|
0
launch.json
Normal file
0
launch.json
Normal file
5
local_platform.json
Normal file
5
local_platform.json
Normal file
@ -0,0 +1,5 @@
|
||||
{
|
||||
"configs": {},
|
||||
"experiments": {},
|
||||
"platform_staff": {}
|
||||
}
|
10
main.py
10
main.py
@ -2,11 +2,17 @@ import sys
|
||||
|
||||
|
||||
arg = sys.argv[-1]
|
||||
if arg == 'worker':
|
||||
if arg == 'poll':
|
||||
from daemons import poll
|
||||
daemon = poll.Daemon()
|
||||
elif arg == 'worker':
|
||||
from daemons import worker
|
||||
daemon = worker.Daemon()
|
||||
elif arg == 'mailbox':
|
||||
from daemons import mailbox
|
||||
daemon = mailbox.Daemon()
|
||||
else:
|
||||
from daemons.api import app
|
||||
from api import app
|
||||
app.run(host="0.0.0.0", port=1238)
|
||||
|
||||
daemon.execute()
|
||||
|
@ -1,14 +1,10 @@
|
||||
import pymongo
|
||||
import os
|
||||
|
||||
MONGO_USER = os.getenv("MONGO_USER", "mongo")
|
||||
MONGO_PASSWORD = os.getenv("MONGO_PASSWORD", "password")
|
||||
MONGO_HOST = os.getenv("MONGO_HOST", "localhost")
|
||||
import settings
|
||||
|
||||
|
||||
class Mongo:
|
||||
def __init__(self):
|
||||
url = f"mongodb://{MONGO_USER}:{MONGO_PASSWORD}@{MONGO_HOST}:27017/"
|
||||
url = f"mongodb://{settings.MONGO_USER}:{settings.MONGO_PASSWORD}@{settings.MONGO_HOST}:27017/"
|
||||
self.client = pymongo.MongoClient(url)
|
||||
self.database = self.client.get_database("pizda-bot")
|
||||
self.chats_collection.create_index([
|
10
settings.py
Normal file
10
settings.py
Normal file
@ -0,0 +1,10 @@
|
||||
import os
|
||||
import sys
|
||||
import zoneinfo
|
||||
|
||||
MONGO_USER = os.getenv("MONGO_USER", "mongo")
|
||||
MONGO_PASSWORD = os.getenv("MONGO_PASSWORD", "password")
|
||||
MONGO_HOST = os.getenv("MONGO_HOST", "localhost")
|
||||
|
||||
CACHE_SIZE = int(os.getenv("CACHE_SIZE", 1000))
|
||||
CACHE_TTL = int(os.getenv("CACHE_TTL", 3600))
|
@ -14,8 +14,11 @@ class PlatformClient:
|
||||
self.stage = stage
|
||||
self.configs = configs
|
||||
self.experiments = experiments
|
||||
self.endpoint = 'http://configurator/'
|
||||
self.fetch_url = urllib.parse.urljoin(self.endpoint, '/api/v1/fetch')
|
||||
self.endpoint = 'https://platform.sprinthub.ru/'
|
||||
self.configs_url = urllib.parse.urljoin(self.endpoint, 'configs/get')
|
||||
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.experiment_storage = {}
|
||||
self.staff_storage = {}
|
||||
@ -40,6 +43,7 @@ class PlatformClient:
|
||||
try:
|
||||
response = get(
|
||||
url,
|
||||
headers={'X-Security-Token': self.platform_security_token},
|
||||
params=params
|
||||
)
|
||||
if response.status_code == 200:
|
@ -1,12 +1,9 @@
|
||||
from cachetools import TTLCache
|
||||
import os
|
||||
|
||||
from utils.mongo import mongo
|
||||
import settings
|
||||
from mongo import mongo
|
||||
|
||||
CACHE_SIZE = int(os.getenv("CACHE_SIZE", 1000))
|
||||
CACHE_TTL = int(os.getenv("CACHE_TTL", 3600))
|
||||
|
||||
cache = TTLCache(CACHE_SIZE, CACHE_TTL)
|
||||
cache = TTLCache(settings.CACHE_SIZE, settings.CACHE_TTL)
|
||||
|
||||
|
||||
def get_chat_info(chat_id: int) -> dict:
|
@ -2,7 +2,7 @@ import datetime
|
||||
import random
|
||||
from time import sleep
|
||||
|
||||
from utils.mongo import mongo
|
||||
from mongo import mongo
|
||||
|
||||
|
||||
def update():
|
@ -1,7 +1,5 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
import zoneinfo
|
||||
import requests
|
||||
import time
|
||||
|
||||
@ -18,54 +16,24 @@ class QueuesException(Exception):
|
||||
|
||||
|
||||
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': 'botalka',
|
||||
'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):
|
||||
while True:
|
||||
try:
|
||||
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:
|
||||
response = requests.get(f'{QUEUES_URL}/api/v1/take', headers={'queue': self.queue_name})
|
||||
if response.status_code == 404:
|
||||
time.sleep(0.2)
|
||||
continue
|
||||
start = datetime.datetime.now(zoneinfo.ZoneInfo("Europe/Moscow"))
|
||||
data = response.json()
|
||||
try:
|
||||
print(f'process task with id {task["id"]}, attempt {task["attempt"]}')
|
||||
self.process(task['payload'])
|
||||
success = True
|
||||
self.process(data['payload'])
|
||||
except Exception as exc:
|
||||
print(f'Error processing message id={task["id"]}, payload={task["payload"]}, exc={exc}')
|
||||
success = False
|
||||
end = datetime.datetime.now(zoneinfo.ZoneInfo("Europe/Moscow"))
|
||||
if success:
|
||||
try:
|
||||
resp = requests.post(f'{QUEUES_URL}/api/v1/finish', json={'id': task['id']})
|
||||
if resp.status_code != 202:
|
||||
raise QueuesException
|
||||
print(f'finish task with id {task["id"]}')
|
||||
except:
|
||||
print(f'Failed to finish task id={task["id"]}')
|
||||
self._send_metric(start, end, success)
|
||||
print(f'Error processing message id={data["id"]}, payload={data["payload"]}, exc={exc}')
|
||||
continue
|
||||
try:
|
||||
resp = requests.post(f'{QUEUES_URL}/api/v1/finish', json={'id': data['id']})
|
||||
if resp.status_code != 202:
|
||||
raise QueuesException
|
||||
except:
|
||||
print(f'Failed to finish task id={data["id"]}')
|
||||
|
||||
@property
|
||||
def queue_name(self):
|
||||
|
Loading…
Reference in New Issue
Block a user