-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.py
88 lines (66 loc) · 2.07 KB
/
util.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
import bs4
import re
from enum import Enum
def escape_nick(nick):
return "\u200D".join(nick)
def strip_html(html):
return bs4.BeautifulSoup(html).text
def linkify(url):
# Replace url to link
urls = re.compile(
r"((https?):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)",
re.MULTILINE | re.UNICODE)
url = urls.sub(r'<a href="\1" target="_blank">\1</a>', url)
# Replace email to mailto
urls = re.compile(
r"([\w\-\.]+@(\w[\w\-]+\.)+[\w\-]+)", re.MULTILINE | re.UNICODE)
url = urls.sub(r'<a href="mailto:\1">\1</a>', url)
return url
def is_command(msg):
try:
return msg[0] == '.'
except IndexError:
return False
# enum to allow determining the type of a message
class MsgType(Enum):
TEXT = 1
ACTION = 2
NICK = 3
JOIN = 4
PART = 5
# message passing bus
class Bus(object):
def __init__(self):
self.listeners = set()
def add_listener(self, listener):
self.listeners.add(listener)
def remove_listener(self, listener):
self.listeners.remove(listener)
def broadcast(self, *args, **kwargs):
for listener in self.listeners:
listener(*args, **kwargs)
# maintains a list of client prefix -> client mappings to allow for
# simple commands that depend on another client (such as user listing)
class CommandProcessor(object):
def __init__(self):
self.clients = dict()
def add_client(self, client):
self.clients[client.prefix] = client
def remove_client(self, client):
self.clients.pop(client.prefix)
def get_users(self, prefix):
try:
client = self.clients[prefix]
except KeyError:
return []
return client.get_user_list()
def get_topic(self, prefix):
try:
client = self.clients[prefix]
except KeyError:
return None
return client.get_topic()
def get_prefixes(self):
return ", ".join(
["{}: {}".format(key, val.name)
for key, val in self.clients.items()])