import json import asyncio import pika from pika.adapters.asyncio_connection import AsyncioConnection class RabbitMQPublisher: def __init__(self, rabbitmq_host: str, rabbitmq_port: int): self._connection = AsyncioConnection( pika.ConnectionParameters(host=rabbitmq_host, port=rabbitmq_port), on_open_callback=self._on_connection_open, on_open_error_callback=self._on_connection_open_error, on_close_callback=self._on_connection_closed, ) self._channel = None def _on_connection_open(self, connection: AsyncioConnection) -> None: self._connection.channel(on_open_callback=self._on_channel_open) def _on_connection_open_error(self, connection: AsyncioConnection, error: Exception) -> None: print(f'Failed to open connection') self._connection.ioloop.stop() raise error def _on_connection_closed(self, connection: AsyncioConnection, reason: Exception) -> None: print(f'Connection closed') raise reason self._connection.ioloop.stop() def _on_channel_open(self, channel: pika.channel.Channel) -> None: self._channel = channel def _publish(self, topic: str, data: str) -> None: self._channel.basic_publish(exchange='broadcast', routing_key=topic, body=data) def send_notification(self, system: str, user: str, priority: str, message: str) -> None: self._publish(f'notification.{system}.{user}.{priority}', message) def send_call(self, caller: str, user: str, message: str) -> None: self._publish(f'call.{caller}.{user}', json.dumps({ 'ringtone': { 'filename': 'Magic.mp3', 'trim': { 'start_time': '00:01:34.64', 'end_time': '00:01:41.53' } }, 'message': message }))