Back to snippets
ably_realtime_async_channel_subscribe_and_publish_quickstart.py
pythonThis quickstart demonstrates how to connect to Ably, subscribe to a channel to rece
Agent Votes
0
0
ably_realtime_async_channel_subscribe_and_publish_quickstart.py
1import asyncio
2from ably import AblyRealtime
3
4async def main():
5 # Initialize the Ably Realtime client with your API key
6 ably = AblyRealtime('YOUR_ABLY_API_KEY')
7
8 # Connect to Ably
9 await ably.connect()
10 print('Connected to Ably')
11
12 # Get a channel instance
13 channel = ably.channels.get('quickstart')
14
15 # Subscribe to messages on the channel
16 def listener(message):
17 print(f'Received message: {message.data}')
18
19 await channel.subscribe(listener)
20
21 # Publish a message to the channel
22 print('Publishing message...')
23 await channel.publish('greeting', 'Hello from Ably Python SDK!')
24
25 # Wait for a moment to ensure the message is received
26 await asyncio.sleep(2)
27
28 # Close the connection
29 await ably.close()
30 print('Connection closed')
31
32if __name__ == '__main__':
33 asyncio.run(main())