{"id":19077892,"url":"https://github.com/backendstack21/realtime-pubsub-client-python","last_synced_at":"2025-04-30T04:34:12.500Z","repository":{"id":257813847,"uuid":"868384853","full_name":"BackendStack21/realtime-pubsub-client-python","owner":"BackendStack21","description":"The official Realtime Pub/Sub client for Python","archived":false,"fork":false,"pushed_at":"2024-11-08T18:30:18.000Z","size":62,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-25T12:06:55.824Z","etag":null,"topics":["client","messaging","publish-subscribe","python","realtime","websocket"],"latest_commit_sha":null,"homepage":"https://realtime.21no.de","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/BackendStack21.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-10-06T08:45:31.000Z","updated_at":"2024-11-08T18:30:22.000Z","dependencies_parsed_at":"2024-11-08T19:26:52.253Z","dependency_job_id":null,"html_url":"https://github.com/BackendStack21/realtime-pubsub-client-python","commit_stats":null,"previous_names":["backendstack21/realtime-pubsub-client-python"],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BackendStack21%2Frealtime-pubsub-client-python","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BackendStack21%2Frealtime-pubsub-client-python/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BackendStack21%2Frealtime-pubsub-client-python/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BackendStack21%2Frealtime-pubsub-client-python/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/BackendStack21","download_url":"https://codeload.github.com/BackendStack21/realtime-pubsub-client-python/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251643150,"owners_count":21620433,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["client","messaging","publish-subscribe","python","realtime","websocket"],"created_at":"2024-11-09T02:03:51.445Z","updated_at":"2025-04-30T04:34:12.475Z","avatar_url":"https://github.com/BackendStack21.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Realtime Pub/Sub Client for Python\n\nThe `realtime-pubsub-client` is a Python client library for interacting\nwith [Realtime Pub/Sub](https://realtime.21no.de) applications. It enables developers to manage real-time WebSocket\nconnections, handle subscriptions, and process messages efficiently. The library provides a simple and flexible API to\ninteract with realtime applications, supporting features like publishing/sending messages, subscribing to topics,\nhandling acknowledgements, and waiting for replies with timeout support.\n\n## Features\n\n- **WebSocket Connection Management**: Seamlessly connect and disconnect from the Realtime Pub/Sub service with\n  automatic reconnection support.\n- **Topic Subscription**: Subscribe and unsubscribe to topics for receiving messages.\n- **Topic Publishing**: [Publish](https://realtime.21no.de/documentation/#publishers) messages to specific topics with\n  optional message types and compression.\n- **Message Sending**: [Send](https://realtime.21no.de/documentation/#websocket-inbound-messaging) messages to backend\n  applications with optional message types and compression.\n- **Event Handling**: Handle incoming messages with custom event listeners.\n- **Acknowledgements and Replies**: Wait for gateway acknowledgements or replies to messages with timeout support.\n- **Error Handling**: Robust error handling and logging capabilities.\n- **Asynchronous Support**: Built using `asyncio` for efficient asynchronous programming.\n\n## Installation\n\nInstall the `realtime-pubsub-client` library via pip:\n\n```bash\npip install realtime-pubsub-client\n```\n\n## Getting Started\n\nThis guide will help you set up and use the `realtime-pubsub-client` library in your Python project.\n\n### Connecting to the Server\n\nFirst, import the `RealtimeClient` class and create a new instance with the required configuration:\n\n```python\nimport asyncio\nimport logging\nimport os\nfrom realtime_pubsub_client import RealtimeClient\n\n\nasync def main():\n    async def get_url():\n        # replace with your access token retrieval strategy\n        access_token = os.environ.get('ACCESS_TOKEN')\n        app_id = os.environ.get('APP_ID')\n\n        # return the WebSocket URL with the access token\n        return f\"wss://genesis.r7.21no.de/apps/{app_id}?access_token={access_token}\"\n\n    client_options = {\n        'logger': logging.getLogger('RealtimeClient'),\n        'websocket_options': {\n            'url_provider': get_url,\n        },\n    }\n    client = RealtimeClient(client_options)\n\n    async def on_session_started(connection_info):\n        print('Connection ID:', connection_info['id'])\n        # Subscribe to topics here\n        await client.subscribe_remote_topic('topic1')\n        await client.subscribe_remote_topic('topic2')\n\n    client.on('session.started', on_session_started)\n\n    await client.connect()\n    await client.wait_for('session.started')\n\n\nasyncio.run(main())\n```\n\n### Subscribing to Incoming Messages\n\nYou can handle messages for specific topics and message types:\n\n\u003e **Note**: The topic and message type are separated by a dot (`.`) in the event name.\n\n```python\ndef handle_message(message, reply_fn):\n    # Message handling logic here\n    print('Received message:', message['data']['payload'])\n\n\nclient.on('topic1.action1', handle_message)\n```\n\nWildcard subscriptions are also supported:\n\n```python\nclient.on('topic1.*', handle_message)\n```\n\n### Publishing Messages\n\nPublish messages to a topic:\n\n```python\nawait client.publish('topic1', 'Hello, world!', message_type='text-message')\n```\n\n### Responding to Incoming Messages\n\nSet up event listeners to handle incoming messages:\n\n```python\nasync def handle_message(message, reply_fn):\n    # Processing the message\n    print('Received message:', message['data']['payload'])\n\n    # Sending a reply\n    await reply_fn('Message received!', 'ok')\n\n\nclient.on('topic1.text-message', handle_message)\n```\n\n### Waiting for Acknowledgements and Replies\n\n- **`wait_for_ack(timeout=None)`**: Waits for an acknowledgement of the message, with an optional timeout in seconds.\n- **`wait_for_reply(timeout=None)`**: Waits for a reply to the message, with an optional timeout in seconds.\n\nWait for the Realtime Gateway acknowledgement after publishing a message:\n\n```python\nwaiter = await client.publish('secure/peer-to-peer1', 'Hi', message_type='text-message')\nawait waiter.wait_for_ack()\n```\n\nWait for the Realtime Gateway acknowledgement after sending a message:\n\n```python\nwaiter = await client.send({\n    # Message payload\n}, message_type='create')\nawait waiter.wait_for_ack()\n```\n\nWait for a reply with a timeout:\n\n```python\nwaiter = await client.send({\n    # Message payload\n}, message_type='create')\nawait waiter.wait_for_reply(timeout=5)  # Wait for up to 5 seconds\n```\n\n### Error Handling\n\nHandle errors and disconnections:\n\n```python\ndef on_error(error):\n    print('WebSocket error:', error)\n\n\ndef on_close(event):\n    print('WebSocket closed:', event)\n\n\nclient.on('error', on_error)\nclient.on('close', on_close)\n```\n\n## API Reference\n\n### RealtimeClient\n\n#### Constructor\n\n```python\nRealtimeClient(config)\n```\n\nCreates a new `RealtimeClient` instance.\n\n- **`config`**: Configuration options for the client.\n\n#### Methods\n\n- **`connect()`**: Connects the client to the WebSocket Messaging Gateway.\n\n  ```python\n  await client.connect()\n  ```\n\n- **`disconnect()`**: Terminates the WebSocket connection.\n\n  ```python\n  await client.disconnect()\n  ```\n\n- **`subscribe_remote_topic(topic)`**: [Subscribes](https://realtime.21no.de/documentation/#subscribers) the connection\n  to a remote topic.\n\n  ```python\n  await client.subscribe_remote_topic(topic)\n  ```\n\n- **`unsubscribe_remote_topic(topic)`**: [Unsubscribes](https://realtime.21no.de/documentation/#subscribers) the\n  connection from a remote topic.\n\n  ```python\n  await client.unsubscribe_remote_topic(topic)\n  ```\n\n- **`publish(topic, payload, message_type=\"broadcast\", compress=False, message_id=None)`**: Publishes a message to a topic.\n\n  ```python\n  waiter = await client.publish(topic, payload)\n  ```\n\n  Returns a `WaitFor` instance to wait for acknowledgements or replies.\n\n- **`send(payload, compress=False, message_id=None)`**: Sends a message to the server.\n\n  ```python\n  waiter = await client.send(payload, options)\n  ```\n\n  Returns a `WaitFor` instance to wait for acknowledgements or replies.\n\n- **`wait(ms)`**: Waits for a specified duration in milliseconds. Utility function for waiting in async functions.\n\n  ```python\n  await wait(ms)\n  ```\n\n#### Events\n\n- **`'session.started'`**: Emitted when the session starts.\n\n  ```python\n  client.on('session.started', on_session_started)\n  ```\n\n- **`'error'`**: Emitted on WebSocket errors.\n\n  ```python\n  client.on('error', on_error)\n  ```\n\n- **`'close'`**: Emitted when the WebSocket connection closes.\n\n  ```python\n  client.on('close', on_close)\n  ```\n\n- **Custom Events**: Handle custom events based on topic and message type.\n\n  ```python\n  client.on('TOPIC_NAME.MESSAGE_TYPE', handle_message)\n  ```\n\n  \u003e **Note**: Wildcard subscriptions are also supported.\n\n## License\n\nThis library is licensed under the MIT License.\n\n---\n\nFor more detailed examples and advanced configurations, please refer to\nthe [documentation](https://realtime.21no.de/docs).\n\n## Notes\n\n- Ensure that you have an account and an app set up with [Realtime Pub/Sub](https://realtime.21no.de).\n- Customize the `url_provider` or URL to retrieve the access token for connecting to your realtime application.\n- Implement the `get_auth_token` function according to your authentication mechanism.\n- Optionally use the `logger` option to integrate with your application's logging system.\n- Handle errors and disconnections gracefully to improve the robustness of your application.\n- Make sure to handle timeouts when waiting for replies to avoid hanging operations.\n\n---\n\nFeel free to contribute to this project by submitting issues or pull requests\non [GitHub](https://github.com/BackendStack21/realtime-pubsub-client-python).","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbackendstack21%2Frealtime-pubsub-client-python","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbackendstack21%2Frealtime-pubsub-client-python","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbackendstack21%2Frealtime-pubsub-client-python/lists"}