|
| 1 | +import argparse |
| 2 | +import asyncio |
| 3 | + |
| 4 | +from os import getenv |
| 5 | +from pubnub.callbacks import SubscribeCallback |
| 6 | +from pubnub.pubnub_asyncio import EventEngineSubscriptionManager, PubNubAsyncio |
| 7 | +from pubnub.pnconfiguration import PNConfiguration |
| 8 | + |
| 9 | +parser = argparse.ArgumentParser(description="Chat with others using PubNub") |
| 10 | +parser.add_argument("-n", metavar="name", help="Your name", default=None, required=False) |
| 11 | +parser.add_argument("-c", metavar="channel", help="The channel you want to join", default=None, required=False) |
| 12 | +args = parser.parse_args() |
| 13 | + |
| 14 | + |
| 15 | +class ExampleCallback(SubscribeCallback): |
| 16 | + def message(self, pubnub, message): |
| 17 | + print(f"{message.publisher}> {message.message}\n") |
| 18 | + |
| 19 | + def presence(self, pubnub, presence): |
| 20 | + print(f"-- {presence.uuid} {'joined' if presence.event == 'join' else 'left'} \n") |
| 21 | + |
| 22 | + def status(self, pubnub, status): |
| 23 | + if status.is_error(): |
| 24 | + print(f"! Error: {status.error_data}") |
| 25 | + else: |
| 26 | + print(f"* Status: {status.category.name}") |
| 27 | + |
| 28 | + |
| 29 | +async def async_input(): |
| 30 | + print() |
| 31 | + await asyncio.sleep(0.1) |
| 32 | + return (await asyncio.get_event_loop().run_in_executor(None, input)) |
| 33 | + |
| 34 | + |
| 35 | +async def main(): |
| 36 | + name = args.name if hasattr(args, "name") else input("Enter your name: ") |
| 37 | + channel = args.channel if hasattr(args, "channel") else input("Enter the channel you want to join: ") |
| 38 | + |
| 39 | + print("Welcome to the chat room. Type 'exit' to leave the chat.") |
| 40 | + |
| 41 | + config = PNConfiguration() |
| 42 | + config.subscribe_key = getenv("PN_KEY_SUBSCRIBE") |
| 43 | + config.publish_key = getenv("PN_KEY_PUBLISH") |
| 44 | + config.uuid = name |
| 45 | + |
| 46 | + pubnub = PubNubAsyncio(config, subscription_manager=EventEngineSubscriptionManager) |
| 47 | + pubnub.add_listener(ExampleCallback()) |
| 48 | + |
| 49 | + pubnub.subscribe().channels(channel).with_presence().execute() |
| 50 | + |
| 51 | + while True: |
| 52 | + message = await async_input() |
| 53 | + print("\x1b[2K") |
| 54 | + if message == "exit": |
| 55 | + print("Goodbye!") |
| 56 | + break |
| 57 | + |
| 58 | + await pubnub.publish().channel(channel).message(message).future() |
| 59 | + |
| 60 | + |
| 61 | +if __name__ == '__main__': |
| 62 | + loop = asyncio.get_event_loop() |
| 63 | + loop.run_until_complete(main()) |
0 commit comments