-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.py
79 lines (60 loc) · 1.73 KB
/
client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import time
import _thread as thread
import click
import termcolor
import websocket
def on_message(ws, message):
"""
Handle on_message event.
:param ws: websocket instance
:param message: Message received
:return:
"""
print(termcolor.colored(message, "green"))
def on_error(ws, error):
"""
Handle on_error event
:param ws: websocket instance
:param error: Error message received
:return:
"""
print(termcolor.colored(error, "red"))
def on_close(ws):
"""
Handle on_close event
:param ws: websocket instance
:return:
"""
print(termcolor.colored("Bye! See you again.", "blue"))
ws.close()
def on_open(ws):
"""
Handle on_open event
:param ws: websocket instance
:return:
"""
def run():
ws.send('{"action": "sendnotify"}')
while True:
message = input()
print("\033[A\033[A") # clear the entered input
data = f'{{"action": "sendmessage", "message": "{message}"}}'
ws.send(data)
time.sleep(1)
thread.start_new_thread(run, ())
@click.command()
@click.option("--server-url", default="wss://nss4v73glk.execute-api.ap-southeast-1.amazonaws.com/Prod", help="Websocket Server URL")
@click.option("--username", prompt="Your username", help="Your chat username")
def main(server_url, username):
"""
Main method to start chat client.
:param server_url: WebSocket server url
:param username: A username to chat
:return:
"""
ws_url = f"{server_url}?username={username}"
ws = websocket.WebSocketApp(ws_url, on_message=on_message, on_error=on_error, on_close=on_close)
ws.on_open = on_open
ws.run_forever()
if __name__ == '__main__':
main()