-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
134 lines (109 loc) · 4.57 KB
/
utils.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
import pandas as pd
from datetime import datetime, timedelta
import os
import pymysql
from configparser import ConfigParser
from glob import glob
config = ConfigParser()
config.read("config.ini")
def get_telegram_name(account_name, style="md"):
registrations = get_registration_table()
if account_name not in registrations.index:
return "N/A"
elif registrations.loc[account_name, "telegram_id"] == 0:
return registrations.loc[account_name, "name"]
else:
name = registrations.loc[account_name, "name"]
id = registrations.loc[account_name, "telegram_id"]
if style == "md":
return f"[{name}](tg://user?id={id})"
elif style == "html":
return f'<a href="tg://user?id={id}">{name}</a>'
else:
raise ValueError("Supported styles are 'md' and 'html'")
def get_player_name(account_name):
registrations = get_registration_table()
try:
return registrations.loc[account_name, "name"]
except KeyError:
return "N/A"
def register_player(account_name, player_name, telegram_id=0):
registrations = get_registration_table()
registrations.loc[account_name, "name"] = player_name
registrations.loc[account_name, "telegram_id"] = telegram_id
registrations.to_csv(get_registration_table_path())
print(f"TM-Account \"{account_name}\" has been mapped to \"{player_name}\".")
def get_registration_table():
try: # already some data saved in the past
registrations = pd.read_csv(get_registration_table_path())
except FileNotFoundError: # no data saved in the past
registrations = pd.DataFrame(columns=["nadeo_account", "name", "telegram_id"])
finally:
registrations["telegram_id"].fillna(0, inplace=True)
registrations["telegram_id"] = registrations["telegram_id"].astype(int)
return registrations.set_index("nadeo_account")
def get_registration_table_path():
return os.path.join(
config.get("LOCAL_STORAGE", "dir"),
config.get("LOCAL_STORAGE", "registrations"),
)
def get_last_SQL_update():
return access_SQL_database("SELECT max(date) FROM `records`")[0][0]
def load_data():
query = "select c.Id, c.Name, c.Author, p.Login, r.Score, r.Date from records r inner join players p on r.PlayerId=p.Id inner join challenges c on r.ChallengeId=c.Id order by c.Name asc, r.Score asc;"
rows = list(access_SQL_database(query))
raw_data = pd.DataFrame(rows, columns=["track_id", "Track", "author", "Player", "Time", "Date"])
times_table = raw_data[["track_id", "Track", "Date", "Player", "Time", "author"]].copy()
times_table["Time"] = times_table["Time"].apply(lambda x: timedelta(milliseconds=x))
times_table["Date"] = times_table["Date"].apply(lambda x: x.to_pydatetime())
times_table["Origin"] = "Player"
return times_table
def access_SQL_database(query):
db = pymysql.connect(
host = config.get("SQL_LOGIN", "host"),
port = config.getint("SQL_LOGIN", "port"),
user = config.get("SQL_LOGIN", "user"),
passwd = config.get("SQL_LOGIN", "passwd"),
database = config.get("SQL_LOGIN", "database"),
)
cur = db.cursor()
cur.execute(query)
result = cur.fetchall()
db.close()
return result
def load_medal_times():
query = "SELECT Id, Name, AuthorTime, GoldTime, SilverTime, BronzeTime from challenges"
rows = list(access_SQL_database(query))
data = pd.DataFrame(
rows,
columns = [
"Id",
"Name",
"Author",
"Gold",
"Silver",
"Bronze",
],
)
data.set_index("Id", inplace=True)
time_cols = ["Author", "Gold", "Silver", "Bronze"]
data[time_cols] = data[time_cols].applymap(lambda x: timedelta(milliseconds=x))
return data
if __name__ == "__main__":
print("\nThis tool will help you set up the mapping of account names to displayed names.")
print("What's your name?")
player_name = input("User: ")
print("\nWhat's your accout name?")
account_name = input(player_name + ": ")
if (player_name == "") or (account_name == ""):
print("Can not map to/from empty name.\n")
raise SystemExit
print(f"\nThe account name \"{account_name}\" will be mapped to player \"{player_name}\". \nDo you wish to continue? (y/n)")
decision = input(player_name + ": ")
if decision == "y":
register_player(account_name, player_name)
elif decision == "n":
print("\nMapping was not saved.")
else:
print(f"\nDecision \"{decision}\" invalid.")
print("Mapping was not saved.")