Because every message flows through the mediator, the room is the perfect place to enforce policy in one location. Add a banned-words filter so a blocked message is stopped once, for everyone, instead of being checked in many places.
The room stores a list of banned words (starting empty). Implement set_banned_words(words) to replace that list with the given words. Then update broadcast so that if the message contains any banned word (as a substring), it is delivered to no one; otherwise it is delivered as before to every user except the sender.
A clean message goes through normally; a message containing a banned word reaches nobody.
class User:
def __init__(self, name):
self.name = name
self.inbox = []
self.room = None
def send(self, message):
self.room.broadcast(self, message)
class ChatRoom:
def __init__(self):
self.users = []
self.banned_words = []
def register(self, user):
self.users.append(user)
user.room = self
def set_banned_words(self, words):
"""Replace the room's banned-words list with the given words."""
# TODO: store a copy of words as self.banned_words
pass
def broadcast(self, sender, message):
# TODO: if message contains any banned word, deliver to no one
for user in self.users:
if user is not sender:
user.inbox.append(message)
def send_private(self, sender, target_name, message):
for user in self.users:
if user.name == target_name:
user.inbox.append(message)
return
def unregister(self, user):
if user in self.users:
self.users.remove(user)
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
Because every message flows through the mediator, the room is the perfect place to enforce policy in one location. Add a banned-words filter so a blocked message is stopped once, for everyone, instead of being checked in many places.
The room stores a list of banned words (starting empty). Implement set_banned_words(words) to replace that list with the given words. Then update broadcast so that if the message contains any banned word (as a substring), it is delivered to no one; otherwise it is delivered as before to every user except the sender.
A clean message goes through normally; a message containing a banned word reaches nobody.
Press Run Tests or ββ© to check your solution.