repl.it
Python

No description

fork
loading
Files
  • main.py
  • 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
"""
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.
  !run_other|pw|who|command|args
  Password protected command. You don't need to know how
  to use this.
  !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.Hi
"""

import threading
import time
import collections
import hashlib
import random

# from replit import clear
# replit module is broken

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

import db
from query import *

PW = '4e7dd01a7a580429a0fc85e15ecc82b1' # hashed password

CENSORED = {  # md5 of censored words
  "99754106633f94d350db34d548d6091a",
  "1223b8c30a347321299611f873b449ad",
  "4dd77ecaf88620f5da8967bbd91d9506",
  "c35312fb3a7e05b7a44db2326bd29040",
  "bf4b3ba0692b4378406f3df1df1e326a",
  "b52b073595ccb35eaebb87178227b779",
  "7f55a0ed8b021080de00960cc73768fb",
  "e87cdcaeed6aa12fb52ed552de99d1aa", # this one's just "flop" for testing
}

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

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

VERSION = 2

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

def does_who_select(who):
  if who in ["", "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:
        print("PM recieved:")
    
    if msg["type"] == "text": # if its text
      if msg["sender"] not in self.muted:
        text = msg["text"].split()
        for ind, word in enumerate(text):
          word = "".join(letter
                        for letter in word
                        if letter not in PUNCTUATION)
          if md5(word.lower()) in CENSORED: # if its a cuss
            text[ind] = "*" * len(word)
        print(f"({str(msg['id']).zfill(5)})  {msg['sender']}: {' '.join(text)}")
    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": # if its a !who request
      pm(msg["author"], "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,
  }
  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():
  msg = {
    "type": "who_req",
    "room": room_id,
    "author": 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, "", "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}")
  raise RuntimeError(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,
}

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("Rules:")
print("  No spam")
print("  No offensive messages")
print("I will delete anything that breaks the rules")
print()
print("Commands:")
print("  !refresh")
print("  Refresh the messages. This will remove deleted messages.")
print("  !say|stuff")
print("  Say 'stuff' in the chat. This is mostly useless, but")
print("  people who know a password can use it to do spoopy stuff.")
print("  !run_other|pw|who|command|args")
print("  Password protected command. You don't need to know how")
print("  to use this.")
print("  !mute|who")
print("  Mute a user. You can't see what they say after this")
print("  But you will have to refresh to remove their previous")
print("  messages. Don't try to hack around this, it's client side.")
print("  !unmute|name")
print("  See above.")
print("  !exec|code")
print("  Run the code 'code'. Don't try to hack with this, it'll")
print("  only do it to you.")
print("  !who")
print("  Shows who is in the room.")
print("  !refall|pw")
print("  Password protected (can cause lag). Refreshes everyone.")
print("  !change|room")
print("  Move to the room 'room'. You start in 'lobby'")
print("  !kick|msg")
print("  Kick YOURSELF.")
print()

input("Press enter to continue")

room_id = "lobby"

say("has joined.")

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

clear()

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