repl.it
@pyelias/

Not-IRC client

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
import time
import threading
import json

import requests

URL = "https://Not-IRC--a5rocks.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 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, author, text):
    """Send a message"""
    requests.post(self.url + "/send", json={"author": author, "content": text})
  
  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

c = Client(URL)
def print_msgs():
  while True:
    for message in c.get_messages():
      print(f"{message[1]}: {message[0]}")
    time.sleep(1)

name = input("name: ")

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

c.send(name, "joined!")
while True:
  text = input()
  print(f"{CSI}A{CSI}K", end="", flush=True)
  c.send(name, text)