repl.it
@HunterW1/

Chatroom-2

Python

No description

fork
loading
Files
  • main.py
  • censored.txt
  • db.py
  • query.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
BANNER = (
"""
Rules:
  No spam
  No offensive messages
  No impersonation
I will delete anything that breaks the rules.

Commands:
  !refresh
  Refresh the messages. This will remove deleted messages.
  
  !say|stuff
  Say 'stuff' in the chat. This is mostly useless, but
  people who know a password can use it to do spoopy stuff.
  
  !id|msg
  Get the id of the poster of a message.
  msg is the number to the left of the message.
  This will print the user id.
  
  !run_other|pw|who|command|args
  pw is the password. Only admins know the password. who is who to run
  the command on. It can be in a few formats:
    username - everyone with that username
    !username - everyone except people with that username
    @id - everyone with that user id
    [email protected] - evryone except people with that user id
    
  command is the command to run. If it was say, it would say something.
  args are the parameters to run the command with.
  
  For example:
    !run_other|password|Zavexeon|say|hi
    would make every user named Zavexeon say hi.
    
  !mute|who
  Mute a user. You can't see what they say after this
  But you will have to refresh to remove their previous
  messages. Don't try to hack around this, it's client side.
  !unmute|name
  See above.
  !exec|code
  Run the code 'code'. Don't try to hack with this, it'll
  only do it to you.
  !who
  Shows who is in the room.
  !refall|pw
  Password protected (can cause lag). Refreshes everyone.
  !change|room
  Move to the room 'room'. You start in 'lobby'.
  !kick|msg
  Kick YOURSELF.
  !color|color|attrs|text
  !c|color|attrs|text
  Say colored text. color is the color.
  attr is the abbreviations for attributes:
    b: bold
    d: dark
    u: underline
  So bu would be bold and underlined. Leave attr empty for no attributes.
  text is just what to say.
  !colordefault|color|attrs
  !cd|color|attrs
  Change your default color. See above for uses.
""")

import threading
import time
import collections
import hashlib
import random
import re

from termcolor import colored

# from replit import clear
# replit module is broken

def clear():
  print("\n" * 100)

import db
from query import *

PW = "4e7dd01a7a580429a0fc85e15ecc82b1" # hashed password
SPOOPY_PW = "ceff37812d348373f5ad210805bd95d5"

CENSOR_CHAR = "*"

CENSORED = []

with open("censored.txt") as censored:
  words = iter(censored)
  try:
    while True:
      pattern = next(words).strip()
      repl = next(words).strip()
      CENSORED.append((repl, re.compile(pattern, re.IGNORECASE)))
      next(words)
  except StopIteration:
    pass

PUNCTUATION = set("\"',./<>?`1234567890-=+_)(*&^%$#@!~[{]}\|;:")

TIME = [
  ("minute", 60),
  ("hour", 60),
]

ATTR_ABRV = {
  "b":  "bold",
  "d":  "dark",
  "u":  "underline",
}

COLORS = [
  "grey",
  "red",
  "green",
  "yellow",
  "blue",
  "magenta",
  "cyan",
  "white",
]

VERSION = 4

def md5(string):
  return hashlib.md5(bytes(string, "utf-8")).hexdigest()

def censor(string):
  res = string
  for r, c in CENSORED:
    res = c.sub(r, res)
  return res
  

def does_who_select(who):
  if who == "all":
    return True
  if who[0] == "!":
    return name != who[1:]
  elif who[0] == "@":
    if who[1] == "!":
      return int(who[2:]) != uid
    else:
      return int(who[1:]) == uid
  else:
    return name == who

class NewMessageGetter():
  def __init__(self, curr_id):
    self.curr_id = curr_id
    self.muted = set()
    self.msgs = []
  
  def fetch_new_messages(self):
    new_messages = messages.query(Attr("id") >= self.curr_id)
    if new_messages:
      self.curr_id = new_messages[-1]["id"] + 1
    return new_messages
  
  def recv_message(self, msg):
    self.msgs.append(msg)
    if "v" in msg and msg["v"] > VERSION:
      print("ERROR: outdated program detected. Try reloading the page, or")
      print("if you are using a forked version, go back to using the")
      print("original program so updates can be applied.")
    if "forkonly" in msg: # alert for people with forked clients, ignore
      return
    if "room" not in msg or msg["room"] != room_id:
      # if its a different room
      return
    if "pm_recv" in msg:
      if not does_who_select(msg["pm_recv"]):
        return
      else:
        if "what" in msg and md5(msg["pw"]) == PW:
          COMMANDS[msg["what"]](*msg["args"])
        else:
          print("PM: ", end="")
    
    if msg["type"] == "text": # if its text
      if msg["sender"] not in self.muted:
        print(f"({str(msg['id']).zfill(5)})  "
              f"{censor(msg['sender'])[:50]}: {censor(msg['text'])[:100]}")
    elif msg["type"] == "command": # if its a command
      if does_who_select(msg["who"]) and md5(msg["pw"]) == PW:
        run_command(msg["command"], msg["args"], io=False)
    elif msg["type"] == "who_req":
      pw(msg["sender"], "is here.")
  
  def print_new_messages(self):
    for msg in self.fetch_new_messages():
      try:
        self.recv_message(msg)
      except Exception as e:
        print("Unexpected error encountered:")
        print(e)

def refresh(): # refresh the chat
  clear()
  
  curr_msg = messages.curr_id()

  old_message_id = max(curr_msg - 50, 0)
  msg_getter.msgs = []
  msg_getter.curr_id = old_message_id

def say(*what): # say stuff
  what = "|".join(what)
  msg = {
    "type": "text",
    "room": room_id,
    "when": time.time(),
    "sender": name,
    "uid": uid,
    "text": what,
    "v": VERSION,
  }
  if alive:
    messages.insert([msg])

def run_other(*what):
  if what:
    pw, who, command, *args = what
    if md5(pw) == PW:
      msg = {
        "type": "command",
        "room": room_id,
        "who": who,
        "pw": pw,
        "command": command,
        "args": list(args),
        "v": VERSION,
      }
      command_pk, = messages.insert([msg])
      time.sleep(1)
      messages.delete(Pks([command_pk]))
    else:
      print("Password incorrect")
  else:
    pw = input("pw: ")
    who = input("who: ")
    command = input("command: ")
    args = input("args: ").split("|")
    run_other(pw, who, command, *args)

def mute(name):
  msg_getter.muted.add(name)

def unmute(name):
  msg_getter.muted.remove(name)

def code_exec(code):
  exec(code.replace(r"\n","\n"), globals(), globals())

def who(*other):
  msg = {
    "type": "who_req",
    "room": room_id,
    "sender": name,
    "v": VERSION,
  }
  pk, = messages.insert([msg])
  time.sleep(1)
  messages.delete(Pks([pk]))

def refall(pw=None):
  if not pw:
    pw = input("pw: ")
  run_other(pw, "all", "refresh")

def fake(pw, who, *what):
  if md5(pw) == PW:
    what = "|".join(what)
    msg = {
      "type": "text",
      "room": room_id,
      "sender": who,
      "uid": random.randint(0, 999999),
      "text": what,
      "v": VERSION,
    }
    messages.insert([msg])

def pm(who, *what):
  what = "|".join(what)
  msg = {
    "type": "text",
    "when": time.time(),
    "pm_recv": who,
    "room": room_id,
    "sender": name,
    "uid": uid,
    "text": what,
    "v": VERSION,
  }
  messages.insert([msg])

def when(id_):
  msg = messages.query(Attr("id") == int(id_))
  if msg:
    msg = msg[0]
    if "when" in msg:
      diff = time.time() - msg['when']
      unit = "second"
      for new_unit, scale in TIME:
        if diff >= scale:
          diff /= scale
          unit = new_unit
        else:
          break
      print(f"{round(diff,2)} {unit}s ago.")
    else:
      print("When not supported for that message.")

def reset(pw):
  if md5(pw) == PW:
    messages.delete(True)
  else:
    print("Password incorrect")

def change(room):
  global room_id
  room_id = room.lower()
  refresh()

def get_id(id_):
  msg = messages.query(Attr("id") == int(id_))
  if msg:
    msg = msg[0]
    if "uid" in msg:
      print(msg["uid"])
    else:
      print("No id")

def kick(msg):
  say(f"was kicked for {msg}")
  global alive
  alive = False
  raise RuntimeError(msg)

def color(color, attrs, *what):
  what = "|".join(what)
  attrs = [ATTR_ABRV[attr] for attr in attrs]
  what = colored(what, color, attrs=attrs)
  say(what)

def color_def(color_, attrs_):
  global color, attrs
  if color_ in COLORS:
    color = color_
    attrs = [ATTR_ABRV[attr] for attr in attrs_ if attr in ATTR_ABRV]
  else:
    print(f"No color {color_}")

def last_ro(dis, pw, who, what, *args):
  msg = {
    "type": "text",
    "when": time.time(),
    "pm_recv": who,
    "room": room_id,
    "sender": name,
    "uid": uid,
    "text": dis,
    "v": VERSION,
    "what": what,
    "args": list(args),
    "pw": pw,
  }
  messages.insert([msg])

COMMANDS = {
  "refresh": refresh,
  "say": say,
  "run_other": run_other,
  "mute": mute,
  "unmute": unmute,
  "exec": code_exec,
  "who": who,
  "refall": refall,
  "fake": fake,
  "pm": pm,
  "when": when,
  "reset": reset,
  "change": change,
  "id": get_id,
  "kick": kick,
  "color": color,
  "c": color,
  "colordefault": color_def,
  "cd": color_def,
  "lr-ro": last_ro,
}

def run_command(command, args, io=True): # run a command
  if command == "kick":
    kick(*args) # no error handling
  if io:
    print_ = print
  else:
    print_ = lambda *a, **k: None
  if command in COMMANDS:
    try:
      COMMANDS[command](*args)
      print_("Command complete")
    except Exception as e:
      print_(e)
  else:
    print_(f"Command {command} not found")


messages = db.ConnectedDatabase("chatroom", "messages")

msg_getter = NewMessageGetter(0)

refresh()

def getter_loop():
  while True:
    msg_getter.print_new_messages()
    time.sleep(0.1)

name = input("Enter your username: ")
while "|" in name or "!" in name or "@" in name:
  print("No |, !, or @ in names.")
  name = input("Enter your username: ")

clear()

uid = random.randint(0, 999999)

print("Welcome to the chatroom!")
print(BANNER)

input("Press enter to continue")

room_id = "lobby"

alive = True

say("has joined.")  # user: has joined.

getter = threading.Thread(target=getter_loop)
getter.daemon = True
getter.start()

clear()

attrs = []
color = "white"

while True:
  msg = input().strip()
  if msg:
    if msg[0] == "!":
      command = msg[1:]
      command, *args = command.split("|") # get command and args
      run_command(command, args) # run it
    else:
      msg = colored(msg, color, attrs=attrs)
      say(msg)
Fetching token
?