aboutsummaryrefslogtreecommitdiff
path: root/mcwrapper/players.py
blob: ef1528d429b1aa3eb8939f7f13108f8ed7f9fa96 (plain)
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
# vim: expandtab ft=python ts=4 sw=4 sts=4:
import os

from . import prints

__PLAYERSFILE__ = 'players'


class MCPlayers:
    "Tracks online players"
    def __init__(self, wrapper, file_export=False):
        self.players = set()
        self.wrapper = wrapper
        wrapper.hook_start(self.__reset__)
        wrapper.hook_stop(self.__reset__)
        wrapper.hook_line('joined the game', self.__user_join__)
        wrapper.hook_line('left the game', self.__user_leave__)
        self.file_export = file_export
        self.__reset__()

    def clean(self):
        try:
            os.remove(__PLAYERSFILE__)
        except FileNotFoundError:
            pass

    def __reset__(self):
        if self.file_export:
            open(__PLAYERSFILE__, 'w')  # Just create empty file

    def __user_join__(self, line):
        username = line[len('[00:00:00] [Server thread/INFO]: '):]
        username = username[:username.index(' joined the game')]
        prints.info("User '" + username + "' joined server.")
        self.players.add(username)
        if self.file_export:
            with open(__PLAYERSFILE__, 'a') as file:
                file.write(username + '\n')

    def __user_leave__(self, line):
        username = line[len('[00:00:00] [Server thread/INFO]: '):]
        username = username[:username.index(' left the game')]
        prints.info("User '" + username + "' left server.")
        self.players.remove(username)
        if self.file_export:
            with open(__PLAYERSFILE__, 'w') as file:
                file.write('\n'.join(self.players))
                if self.players:
                    file.write('\n')