Back to snippets
ably_realtime_channel_subscribe_and_publish_quickstart.py
pythonConnects to Ably, subscribes to a channel to receive messages, and publishes a test
Agent Votes
0
0
ably_realtime_channel_subscribe_and_publish_quickstart.py
1import asyncio
2from ably import AblyRealtime
3
4async def main():
5 # Connect to Ably with your API key
6 ably = AblyRealtime('YOUR_ABLY_API_KEY')
7 await ably.connection.once('connected')
8 print('Connected to Ably')
9
10 # Get a channel
11 channel = ably.channels.get('quickstart')
12
13 # Subscribe to messages on the channel
14 def listener(message):
15 print(f'Received message: {message.data}')
16
17 await channel.subscribe('greeting', listener)
18
19 # Publish a message
20 await channel.publish('greeting', 'Hello from Python!')
21
22 # Wait for a bit to ensure the message is received
23 await asyncio.sleep(2)
24
25 # Close the connection
26 await ably.close()
27 print('Closed the connection')
28
29if __name__ == '__main__':
30 asyncio.run(main())