def handle_join(self, message): ''' Handle a authentication message from the member. ''' if self.channel.has(self): self.respond_with_error("Already in the channel.") self.nick = message.body self.channel.join(self) Message(MT.join, self.nick).send(self) self.broadcast(Message(MT.join, self.nick, sender=self))
def on_message(self, message): try: message = Message.from_json(message) message.sender = self getattr(self, 'handle_' + message.kind.name)(message) except ValueError: self.respond_with_error("Invalid message format.") except KeyError: self.respond_with_error("Invalid message kind.")
def on_close(self): if not self.channel: return self.channel.connections -= 1 if self.channel.has(self): self.channel.part(self) self.broadcast(Message(MT.part, sender=self)) if self.channel.connections <= 0: L.debug('Deleting channel: %s', self.channel_id) Channels.remove(self.channel_id)
def open(self, channel_id): self.channel_id = channel_id try: self.channel = Channels.get(self.channel_id) self.id = self.channel.new_id() # Tell the user their id and the channel's meta data. Message(MT.config, body={ "id": self.id, "meta": self.channel.meta }).send(self) self.channel.connections += 1 except ChannelDoesNotExist: self.respond_with_error("Channel does not exist.") self.close()
def test_json(self): obj = m("chat", "test") message = Message.from_json(json.dumps(obj)) self.assertEqual(obj, message.as_json())
def test_object(self): message = Message.from_object( m(MessageTypes["chat"], "test", Mock(nick="test", id="foo")) ) self.assertEqual(m("chat", "test", "foo"), message.as_json())
def handle_ping(self, _): ''' Re-broadcast any chat messages that come in. ''' Message(MT.pong).send(self)
def handle_members(self, _): ''' Handle a chat message. ''' Message(MT.members, body=self.channel.members).send(self)
def respond_with_error(self, error="An error occured."): L.warn("Error response @%s: %s", self.channel_id, error) Message(MT.error, body=error).send(self)
def test_object(self): message = Message.from_object( m(MessageTypes["chat"], "test", Mock(nick="test", id="foo"))) self.assertEqual(m("chat", "test", "foo"), message.as_json())