import asyncio import json import logging from aio_pika import connect_robust, exceptions as aio_exceptions from app import create_app, db from app.models import Users logger = logging.getLogger(__name__) rate_limit_semaphore = asyncio.Semaphore(25) RABBITMQ_URL = "amqp://guest:guest@localhost/" RABBITMQ_QUEUE = "your_queue" async def send_message(backend_bot, chat_id, message_text): telegram_id = "unknown" try: async with rate_limit_semaphore: async def get_user(): with app.app_context(): user = Users.query.get(chat_id) return user.telegram_id if user else "unknown" telegram_id = await asyncio.to_thread(get_user) await asyncio.to_thread( backend_bot.bot.send_message, chat_id, message_text, parse_mode="HTML" ) logger.info(f"[RabbitMQ] Sent to {telegram_id} ({chat_id}): {message_text}") except Exception as e: logger.error(f"Error sending message to {telegram_id} ({chat_id}): {e}") async def consume_from_queue(backend_bot): while True: try: connection = await connect_robust(RABBITMQ_URL) async with connection: channel = await connection.channel() queue = await channel.declare_queue(RABBITMQ_QUEUE, durable=True) async for message in queue: async with message.process(): try: data = json.loads(message.body.decode('utf-8')) await send_message(backend_bot, data["chat_id"], data["message"]) except (json.JSONDecodeError, KeyError) as e: logger.error(f"Error decoding message: {e}") except aio_exceptions.AMQPError as e: logger.error(f"RabbitMQ AMQPError: {e}") except Exception as e: logger.error(f"Unhandled error in consumer: {e}") finally: await asyncio.sleep(5)