forked from JonnyPtn/zomboi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathusers.py
212 lines (194 loc) · 8.46 KB
/
users.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
from dataclasses import dataclass, field
from datetime import datetime
import discord
from discord.ext import tasks, commands
from file_read_backwards import FileReadBackwards
import glob
import os
import re
from tabulate import tabulate
from typing import List
from pathlib import Path
import sqlite3
DISCORD_MAX_CHAR = 2000
@dataclass
class User:
"""A class representing a user"""
name: str
hoursAlive: int = 0
recordHoursAlive: int = 0
perks: dict = field(default_factory=lambda: dict())
online: bool = False
lastSeen: datetime = datetime(1, 1, 1)
lastLocation: tuple = (0, 0)
died: List[datetime] = field(default_factory=lambda: [])
class UserHandler(commands.Cog):
"""Handles all the info we get from the user log files"""
def __init__(self, bot, logPath):
self.bot = bot
self.logPath = logPath
self.lastUpdateTimestamp = datetime.now()
self.users = {}
self.notifyDisconnect = os.getenv("DISCONNECTS", "True") == "True"
self.loadHistory()
self.update.start()
self.onlineCount = None
return
def getUser(self, name: str):
"""Get a user from a name, will create if it doesn't exist"""
if not name in self.users:
self.users[name] = User(name)
return self.users[name]
def splitLine(self, line: str):
"""Split a log line into a timestamp and the remaining message"""
timestampStr, message = line.strip()[1:].split("]", 1)
timestamp = datetime.strptime(timestampStr, "%d-%m-%y %H:%M:%S.%f")
return timestamp, message
def getCharName(self, name: str):
"""Looks through the db file to find the name of the user's character"""
# Needs to sleep to let database update after new character creation
from time import sleep
sleep(5)
try:
playerdb = Path(os.getenv("SAVES_PATH")).joinpath("players.db") if os.getenv("SAVES_PATH") else Path.home().joinpath("Zomboid/Saves/Multiplayer/pzserver").joinpath("players.db")
if not playerdb.is_file():
self.bot.log.error("Zomboid saves path was set incorrectly. Please check your environment variables")
return ''
# Connect to the sqlite player db
con = sqlite3.connect(str(playerdb))
cur = con.cursor()
# check the networkPlayers table
cur.execute('SELECT name FROM networkPlayers WHERE username = ?', [name])
charName = cur.fetchone()
charName = charName[0] if charName else None
con.close()
except Exception as e:
self.bot.log.error(e)
charName = None
return charName
@tasks.loop(seconds=2)
async def update(self):
"""Update from the log file anything since the last update"""
files = glob.glob(self.logPath + "/*user.txt")
if len(files) > 0:
with FileReadBackwards(files[0]) as f:
newTimestamp = self.lastUpdateTimestamp
for line in f:
timestamp, message = self.splitLine(line)
if timestamp > newTimestamp:
newTimestamp = timestamp
if timestamp > self.lastUpdateTimestamp:
message = self.handleLog(timestamp, message)
if message is not None and self.bot.channel is not None:
await self.bot.channel.send(message)
else:
break
self.lastUpdateTimestamp = newTimestamp
# Also update the bot activity here
onlineCount = len([user for user in self.users if self.users[user].online])
if onlineCount != self.onlineCount:
playerString = "nobody" if onlineCount == 0 else f"{onlineCount} survivors"
# have to abbreviate or it gets truncated
await self.bot.change_presence(
activity=discord.Game(f"PZ with {playerString}")
)
self.onlineCount = onlineCount
def loadHistory(self):
"""Go through all log files and load the info"""
self.bot.log.info("Loading user history...")
files = glob.glob(self.logPath + "/**/*user.txt", recursive=True)
files.sort(key=os.path.getmtime)
for file in files:
with open(file) as f:
for line in f:
self.handleLog(*self.splitLine(line))
self.bot.log.info("User history loaded")
def handleLog(self, timestamp: datetime, message: str):
"""Parse the log message and store any useful info. Returns a message string if relevant"""
if "disconnected" in message:
matches = re.search(r"\"(.*)\".*\((\d+),(\d+),\d+\)", message)
name = matches.group(1)
user = self.getUser(name)
if timestamp > user.lastSeen:
user.online = False
user.lastSeen = timestamp
user.lastLocation = (matches.group(2), matches.group(3))
if timestamp > self.lastUpdateTimestamp:
self.bot.log.info(f"{user.name} disconnected")
if self.notifyDisconnect:
return f":person_running: {user.name} has left"
elif "fully connected" in message:
matches = re.search(r"\"(.*)\".*\((\d+),(\d+)", message)
name = matches.group(1)
user = self.getUser(name)
if timestamp > user.lastSeen:
user.online = True
user.lastSeen = timestamp
user.lastLocation = (matches.group(2), matches.group(3))
if timestamp > self.lastUpdateTimestamp:
self.bot.log.info(f"{user.name} connected")
else:
# Ignore but mirror log if it's new
if timestamp > self.lastUpdateTimestamp:
self.bot.log.debug(f"Ignored: {message}")
@commands.command()
async def users(self, ctx, arg: str = None):
"""
Return a list of users on the server with basic info
If the user is online -- print all online users
if the arg "all" is supplied, show all users
"""
table = []
headers = ["Name", "Online", "Last Seen", "Hours survived"]
# if the number of users is over 28 (two messages), then only show online users
num_users = len(self.users.values())
show_all = True if arg and arg.lower() == 'all' else False
for user in self.users.values():
if show_all or user.online:
table.append(
[
user.name,
"Yes" if user.online else "No",
user.lastSeen.strftime("%d/%m at %H:%M"),
user.hoursAlive,
]
)
# For each message -> make sure they are under the char limit
# If not make a new table and then send a new message
# Definitely could be more efficient but it works lol
messages = [table]
x = 0
for message in messages:
while len(f'```\n{tabulate(messages[x], headers=headers, tablefmt="fancy_grid")}\n```') > DISCORD_MAX_CHAR:
if x == len(messages) - 1:
messages.append([])
messages[x+1].append(messages[x][-1])
messages[x] = messages[x][0:-1]
await ctx.send(
f'```\n{tabulate(messages[x], headers=headers, tablefmt="fancy_grid")}\n```'
)
x += 1
@commands.command()
async def info(self, ctx, name=None):
"""Get detailed user info
Provide a username, or leave blank to show the user matching your discord name
"""
if name is None:
name = ctx.author.name
if name in self.users:
user = self.users[name]
table = []
table.append(["Name", user.name])
table.append(
[
"Hours survived",
f"{user.hoursAlive} (record: {user.recordHoursAlive})",
]
)
table.append(["Online", "Yes" if user.online else "No"])
table.append(["Last Seen", user.lastSeen.strftime("%d/%m at %H:%M")])
table.append(["Deaths", len(user.died)])
for perk in user.perks:
if int(user.perks[perk]) != 0:
table.append([perk, user.perks[perk]])
await ctx.send(f'```\n{tabulate(table, tablefmt="fancy_grid")}\n```')