|
| 1 | +import os |
| 2 | +import asyncio |
| 3 | + |
| 4 | +from pubnub.pnconfiguration import PNConfiguration |
| 5 | +from pubnub.pubnub_asyncio import PubNubAsyncio, SubscribeCallback |
| 6 | +from pubnub.enums import PNStatusCategory |
| 7 | + |
| 8 | + |
| 9 | +class MySubscribeCallback(SubscribeCallback): |
| 10 | + def status(self, pubnub, status): |
| 11 | + if status.category == PNStatusCategory.PNUnexpectedDisconnectCategory: |
| 12 | + print("Disconnected") |
| 13 | + elif status.category == PNStatusCategory.PNConnectedCategory: |
| 14 | + print("Connected") |
| 15 | + elif status.category == PNStatusCategory.PNReconnectedCategory: |
| 16 | + print("Reconnected") |
| 17 | + elif status.category == PNStatusCategory.PNDecryptionErrorCategory: |
| 18 | + print("Decryption error") |
| 19 | + |
| 20 | + def message(self, pubnub, message): |
| 21 | + print(f"Received message: {message.message} on channel: {message.channel}") |
| 22 | + |
| 23 | + def presence(self, pubnub, presence): |
| 24 | + print(f"Presence event: {presence.event}") |
| 25 | + |
| 26 | + |
| 27 | +async def main(pubnub): |
| 28 | + pubnub.subscribe().channels('my_channel').execute() |
| 29 | + print("Listening for messages...") |
| 30 | + while True: |
| 31 | + await asyncio.sleep(1) |
| 32 | + |
| 33 | +if __name__ == "__main__": |
| 34 | + loop = asyncio.new_event_loop() |
| 35 | + asyncio.set_event_loop(loop) |
| 36 | + |
| 37 | + pnconfig = PNConfiguration() |
| 38 | + pnconfig.subscribe_key = os.getenv('PUBNUB_SUBSCRIBE_KEY') or 'demo' |
| 39 | + pnconfig.publish_key = os.getenv('PUBNUB_PUBLISH_KEY') or 'demo' |
| 40 | + pnconfig.user_id = "my_unique_user_id" # Set a unique user ID |
| 41 | + |
| 42 | + pubnub = PubNubAsyncio(pnconfig) |
| 43 | + callback = MySubscribeCallback() |
| 44 | + pubnub.add_listener(callback) |
| 45 | + |
| 46 | + try: |
| 47 | + loop.run_until_complete(main(pubnub)) |
| 48 | + except KeyboardInterrupt: |
| 49 | + print("Interrupted by user. Exiting...") |
| 50 | + finally: |
| 51 | + loop.run_until_complete(pubnub.stop()) # Assuming 'pubnub' is in scope |
| 52 | + loop.close() |
0 commit comments