Compare commits

..

4 Commits

Author SHA1 Message Date
c6a2710087 Merge pull request 'fix' (#4) from master into dev
Reviewed-on: #4
2024-11-27 04:11:15 +03:00
42fc5552ab Merge pull request 'fix' (#3) from master into dev
Reviewed-on: #3
2024-11-27 04:09:16 +03:00
499eed49e0 Merge pull request 'fix' (#2) from master into dev
Reviewed-on: #2
2024-11-27 04:07:49 +03:00
349df7eb17 Merge pull request 'req' (#1) from master into dev
Reviewed-on: #1
2024-11-27 04:06:16 +03:00
9 changed files with 43 additions and 108 deletions

View File

@@ -22,7 +22,6 @@ services:
networks:
- configurator
- queues
- monitoring
environment:
STAGE: "production"
command: mailbox
@@ -39,5 +38,3 @@ networks:
external: true
queues:
external: true
monitoring:
external: true

5
.gitignore vendored
View File

@@ -117,8 +117,3 @@ GitHub.sublime-settings
!.vscode/launch.json
!.vscode/extensions.json
.history
local_platform.json
*pb2*
schemas

View File

@@ -4,5 +4,4 @@ WORKDIR /usr/src/app
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
ENV PYTHONUNBUFFERED 1
ENTRYPOINT ["python", "main.py"]

View File

@@ -1,5 +1,3 @@
import pydantic
from telebot import apihelper
from daemons import base
@@ -7,13 +5,6 @@ from utils import platform
from utils import queues
class Message(pydantic.BaseModel):
project: str
name: str
body: dict
method: str = 'send_message'
class Daemon(base.Daemon, queues.TasksHandlerMixin):
def execute(self):
self.poll()
@@ -22,19 +13,16 @@ class Daemon(base.Daemon, queues.TasksHandlerMixin):
def queue_name(self):
return 'botalka_mailbox'
def process(self, payload: dict):
message = Message.model_validate(payload)
bot = platform.platform_client.get_config('bots')[message.project][message.name]
def process(self, payload):
bot = platform.platform_client.get_config('bots')[payload['project']][payload['name']]
if not bot['mailbox_enabled']:
return
if bot['type'] == 'telegram':
token = bot['secrets']['telegram_token']
self.process_telegram(token, message.method, message.body)
else:
print('Unknown bot type:', bot['type'])
self.process_telegram(token, payload['body'])
def process_telegram(self, token, method, payload):
def process_telegram(self, token, payload):
try:
getattr(apihelper, method)(token, **payload)
apihelper.send_message(token, **payload)
except Exception as exc:
print('Error', str(exc))

View File

@@ -1,7 +1,6 @@
import telebot
import multiprocessing
import time
import json
from daemons import base
from utils import platform
@@ -10,37 +9,35 @@ from utils import queues
class Daemon(base.Daemon):
def __init__(self):
self.processes: dict[str, multiprocessing.Process|None] = {}
self.telegram_pollers: dict[str, dict[str, multiprocessing.Process|None]] = {}
def execute(self):
while True:
bots = platform.platform_client.get_config('bots')
for project_name, project in bots.items():
if project_name not in self.telegram_pollers:
self.telegram_pollers[project_name] = {}
for bot_name, bot_info in project.items():
key = f'{project_name}_{bot_name}'
proc = self.processes.get(key)
if bot_name not in self.telegram_pollers[project_name]:
self.telegram_pollers[project_name][bot_name] = None
process = self.telegram_pollers[project_name][bot_name]
if bot_info.get('poll_enabled'):
if proc and proc.is_alive():
print(f'process for {project_name} {bot_name} is alive')
if process is not None and process.is_alive:
continue
print(f'starting process for {project_name} {bot_name}')
process = multiprocessing.Process(target=self.start_polling, args=(bot_info['secrets']['telegram_token'], bot_info['queue']))
process.start()
self.processes[key] = process
print(f'started process for {project_name} {bot_name}')
new_process = multiprocessing.Process(target=self.start_polling, args=[bot_info['secrets']['telegram_token'], bot_info['queue']])
new_process.start()
self.telegram_pollers[project_name][bot_name] = new_process
else:
if proc is None:
print(f'process for {project_name} {bot_name} is not alive')
if process is None:
continue
print(f'terminating process for {project_name} {bot_name}')
proc.terminate()
self.processes[key] = None
print(f'terminated process for {project_name} {bot_name}')
if process.is_alive:
process.terminate()
self.telegram_pollers[project_name][bot_name] = None
time.sleep(10)
def start_polling(self, token: str, queue: str):
bot = telebot.TeleBot(token)
@bot.message_handler(content_types=['audio', 'photo', 'voice', 'video', 'document', 'animation', 'text', 'location', 'contact', 'sticker', 'video_note'])
def do_action(message: telebot.types.Message):
def start_polling(telegram_token, queue):
bot = telebot.TeleBot(telegram_token)
@bot.message_handler()
def do_action(message):
queues.set_task(queue, message.json, 1)
bot.polling()

20
main.py
View File

@@ -2,16 +2,14 @@ import sys
arg = sys.argv[-1]
# arg = 'poll'
if __name__ == '__main__':
if arg == "poll":
print("poll is starting")
from daemons.poll import Daemon
elif arg == 'mailbox':
print("mailbox is starting")
from daemons.mailbox import Daemon
else:
raise ValueError(f"Unknown param {arg}")
if arg == "poll":
print("poll is starting")
from daemons.poll import Daemon
elif arg == 'mailbox':
print("mailbox is starting")
from daemons.mailbox import Daemon
else:
raise ValueError(f"Unknown param {arg}")
Daemon().execute()
Daemon().execute()

View File

@@ -1,10 +1,6 @@
annotated-types==0.7.0
certifi==2024.12.14
certifi==2024.8.30
charset-normalizer==3.4.0
idna==3.10
pydantic==2.10.4
pydantic_core==2.27.2
pyTelegramBotAPI==4.1.1
requests==2.32.3
typing_extensions==4.12.2
urllib3==2.3.0
urllib3==2.2.3

View File

@@ -88,6 +88,6 @@ class PlatformClient:
platform_client = PlatformClient(
'Botalka',
os.getenv('STAGE', 'local'),
os.getenv('STAGE'),
need_poll=True,
)

View File

@@ -1,9 +1,4 @@
from concurrent.futures import ThreadPoolExecutor
import datetime
import json
import os
import uuid
import zoneinfo
import requests
import time
@@ -20,54 +15,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
response = requests.get(f'{QUEUES_URL}/api/v1/take', headers={'queue': self.queue_name}).json()
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:
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)
continue
try:
resp = requests.post(f'{QUEUES_URL}/api/v1/finish', json={'id': task['id']})
if resp.status_code != 202:
raise QueuesException
except:
print(f'Failed to finish task id={task["id"]}')
@property
def queue_name(self):