@Nathan_42/

Pychat

Python

No description

fork
loading
Files
  • main.py
main.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
from time import sleep
import threading
import json
import requests
import termcolor
import datetime
from os import system
from hashlib import sha512

URL = "https://Chat-server--ebest.repl.co"

CSI = "\x1b["

class Client():
	def __init__(self, url, start_id=0):
		self.url = url
		self.curr_id = start_id
		self.start_ts = None
	def sname(self, name):
		if name in ["Aidan", "Ebest"]:
			self.isuser = True
		else:
			self.isuser = False
		self.name = name
	def gname(self):
		return self.name
	def sr(self, room):
		self.room = room
	def gr(self):
		return self.room
	def check_restart(self, msgs):
		"""Check if the server restarted by looking at the first timestamp
		if it did, reset the current message id"""
		first = msgs["0"]
		ts = first[2]

		if self.start_ts is None: # if no registered start
			self.start_ts = ts
			return

		if ts != self.start_ts: # if the new first message changed
			self.start_ts = ts
			self.curr_id = 0

	def send(self, cmd, room = None, mauthor = None, mtext = None, margs = None):
		"""Send a message"""
		if margs == None:
			time = str(datetime.datetime.now().month) + "-" + str(datetime.datetime.now().day) + "-" + str(datetime.datetime.now().year) + " " +  str(datetime.datetime.now().hour) + ":" + str(datetime.datetime.now().minute)
			requests.post(self.url + "/send", json={"cmd": cmd, "room": room, "author": mauthor, "message": mtext, "args": margs, "time": time, "version": 3})
		else:
			time = str(datetime.datetime.now().month) + "-" + str(datetime.datetime.now().day) + "-" + str(datetime.datetime.now().year) + " " +  str(datetime.datetime.now().hour) + ":" + str(datetime.datetime.now().minute)
			requests.post(self.url + "/send", json={"cmd": cmd, "room": room, "author": mauthor, "message": mtext, "args": margs, "time": time, "version": 3})
  
	def get_messages(self):
		"""Get all un-read messages and yield them"""
		try:
			msgs = requests.get(self.url + "/get_messages").json()
		except json.decoder.JSONDecodeError: # server is down
			return

		self.check_restart(msgs)
		
		while str(self.curr_id) in msgs:
			yield msgs[str(self.curr_id)]
			self.curr_id += 1
	def exit(self):
		self.send("msg", self.room, self.name, "has left.")

c = Client(URL)

def print_msgs():
	while True:
		for message in c.get_messages():
			if message[0] == "msg":
				if message[1] == c.gr():
					print(f"[{message[4]}] {c.gr().capitalize()} {message[3]}: {message[2]}")
			elif message[0] == "kick":
				print(message[4])
				if message[4] == c.gname():
					c.sr("spamroom")
			elif message[0] == "dmsg":
				if message[4] == c.gname():

					print(f"direct {message[2]} [{message[5]}]: {message[3]}")
			elif message[0] == "who":
				time = str(datetime.datetime.now().month) + "-" + str(datetime.datetime.now().day) + "-" + str(datetime.datetime.now().year) + " " +  str(datetime.datetime.now().hour) + ":" + str(datetime.datetime.now().minute)
				if str(message[4]) == str(time):
					c.send("dmsg", c.gr(), name, "Is here", message[3])
			elif message[0] == "reset":
				system('clear')
			elif message[0] == "sec":
				c.send("check", name)
		sleep(0.1)

namel = {"Aidan": ["magenta", "878e4e9d771fecfb2a567f3955a67bbfc7e4a1dc2f1f18cc74533a3c34a524eddd7186213065bd8185c5886c09b472344c983dbb758bd8e9ce07b33e7f164cb6"], "Ebest": ["cyan", "017582974880914c3d14eeb22468d36f09c9f68be3da621b9e209c0b3a6676843b0fba9599ac3da8bf329c016ef15b747127805851325bb3b51fc78487bbf329"]}

admins = ["Aidan", "Ebest"]

adminstat = False

name = input("name: ")

c.sname(name)

if name in namel:
	passw = input("What's the password? ")
	salt = "3d987fbc3c8146c1a4903e5d198512c9"
	hashed_password = sha512(passw.encode() + salt.encode()).hexdigest()
	if hashed_password == namel[name][1]:
		if name in admins:
			adminstat = True
		name = termcolor.colored(name, namel[name][0])

c.sr("lobby")
password = "a570319bf4d58ae4b6b06fc9d4c05312d8981d21e75263562cf2fbc9ffb954030ce201a03589ddb262a0b3f8c6b0eab9454af90d8175dd82df1b3c2db4bb7525" 

threading.Thread(target=print_msgs).start()

c.send("msg", c.gr(), name, "joined!", None)

color = 'white'

while True:
	text = input()
	print(f"{CSI}A{CSI}K", end="", flush=True)
	if text != "!switchroom" and text != "!kick" and text != "!who" and text != "!dmsg" and text != "!reset" and text != "!colorc" and text != "!commands":
		c.send("msg", c.gr(), name, termcolor.colored(text, color), None)
	elif text == "!kick":
		target = input("Target? ")
		if adminstat == False:
			passw = input("Password? ")
			salt = "3d987fbc3c8146c1a4903e5d198512c9"
			tpassword = sha512(passw.encode() + salt.encode()).hexdigest()
			if tpassword == password:
				c.send("kick", str(c.gr()), name, "Kicked!", target)
		else:
			c.send("kick", str(c.gr()), name, "Kicked!", target)

	elif text == "!switchroom":
		room = input("Room?")
		c.sr(room)

	elif text == "!reset":
		if adminstat == False:
			passw = input("Password? ")
			salt = "3d987fbc3c8146c1a4903e5d198512c9"
			tpassword = sha512(passw.encode() + salt.encode()).hexdigest()
			if tpassword == password:
				c.send("reset")
		else:
			c.send("reset")
	elif text == "!dmsg":
		msg = input("Message? ")
		target = input("Reciver? ")
		c.send("dmsg", c.gr(), name, msg, target)
	elif text == "!who":
		c.send("who", None, c.gname(), c.gname())
	elif text == "!exit":
		c.exit()
	elif text == "!colorc":
		ncolor = input("new color? ")
		if ncolor in ["red", "green", "yellow", "blue", "magneta", "cyan", "white"]:
			color = ncolor
	elif text == "!commands": 
		print("""
!dmsg          |      Direct Message
!who           |      Show users
!colorc        |      Change text color
!reset         |      Reset Chatroom
!switchroom    |      Switch Room
!commands      |      Show this page
!exit          |      Exit Chatroom
""")