You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.9 KiB

  1. #!/usr/bin/env python3.7
  2. import threading
  3. from ChatConnection import ChatConnection
  4. class ChatInterface(object):
  5. def __init__(self,
  6. connection: ChatConnection,
  7. name: str = '<anonymous>'):
  8. # set connection to use
  9. self.connection = connection
  10. self.name = name
  11. def send(self, msg) -> None:
  12. """
  13. Send message to connection
  14. """
  15. self.connection.send(msg)
  16. # check if input is quit command
  17. if self.connection.isOpen:
  18. if msg[0] == '/':
  19. cmd = msg[1:5]
  20. if cmd == 'quit':
  21. self.connection.close()
  22. elif cmd == 'name':
  23. tmp = msg.split()
  24. if len(tmp) == 2:
  25. self.name = tmp[1]
  26. def listener(self) -> None:
  27. """
  28. Listener method to keep receiving new message from
  29. connection
  30. """
  31. while self.connection.isOpen:
  32. # receive messages from connection
  33. msg = self.connection.recv()
  34. if len(msg) > 0:
  35. # add recevied message to message list
  36. print('\r' +
  37. msg +
  38. '\n' +
  39. '[ME({})]: '.format(self.name), end='')
  40. else:
  41. self.connection.close()
  42. def start(self) -> None:
  43. # initialise background listener as daemon thread
  44. backgroundListener = threading.Thread(target=self.listener)
  45. backgroundListener.daemon = True
  46. backgroundListener.start()
  47. self.send('/name {}'.format(self.name))
  48. while self.connection.isOpen:
  49. try:
  50. msg = input('[ME({})]: '.format(self.name))
  51. except (EOFError, KeyboardInterrupt):
  52. msg = '/quit'
  53. finally:
  54. self.send(msg)