File: chat.py

package info (click to toggle)
python-falcon 3.1.1-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 5,204 kB
  • sloc: python: 28,455; makefile: 184; sh: 139; javascript: 66
file content (43 lines) | stat: -rw-r--r-- 1,253 bytes parent folder | download | duplicates (2)
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
import re


class Chat:
    ALL = re.compile(r'^/all\s+(.+)$')
    MSG = re.compile(r'^/msg\s+(\w+)\s+(.+)$')

    def __init__(self, hub):
        self._hub = hub

    async def on_websocket(self, req, ws, name):
        await ws.accept()

        try:
            await self._hub.broadcast(f'{name} CONNECTED')
            self._hub.add_user(name, ws)

            await ws.send_text(f'Hello, {name}!')

            while True:
                message = await ws.receive_text()

                if message == '/quit':
                    await ws.send_text(f'Bye, {name}!')
                    break

                command = self.ALL.match(message)
                if command:
                    text = command.group(1)
                    await self._hub.broadcast(f'[{name}] {text}')
                    continue

                command = self.MSG.match(message)
                if command:
                    recipient, text = command.groups()
                    await self._hub.message(recipient, f'[{name}] {text}')
                    continue

                await ws.send_text('Supported commands: /all /msg /quit')

        finally:
            self._hub.remove_user(name)
            await self._hub.broadcast(f'{name} DISCONNECTED')