-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.py
More file actions
330 lines (271 loc) · 12.5 KB
/
Copy pathfunctions.py
File metadata and controls
330 lines (271 loc) · 12.5 KB
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
import json
import logging
import os
import asyncio
from datetime import datetime
from json import JSONDecodeError
from dateutil.relativedelta import relativedelta
import pytz
import discord
from discord import app_commands
from discord.ext import commands
from dao.pollDao import pollDao
from data import config
from view.poll import pollView
project_path = os.path.dirname(os.path.realpath(__file__))
def is_me(ctx: commands.Context) -> bool:
return ctx.author.id == 236853417681616906
def singular_or_plural(number: int) -> str:
return "s" if number > 1 else ""
class Utils:
__instance = None
server_config: dict
@staticmethod
def get_instance(client):
if Utils.__instance is None:
Utils.__instance = Utils(client)
return Utils.__instance
def __init__(self, client: discord.Client):
self.client = client
self._color = 0x989eec
self.pollDao = pollDao.get_instance()
self.load_server_config()
def invisible_string(self) -> str:
return " "
def server_exists_in_config(self, guild_id: int) -> bool:
return str(guild_id) in self.server_config
def add_new_server(self, guild_id: int):
self.server_config[str(guild_id)] = {
"welcome_message": {
"active": False,
"message": ""
},
"logs": {
"active": False,
"channel_id": 0
},
"autorole": {
"active": False,
"role_id": 0
},
"rolevocal": {
"active": False,
"role_id": 0
}
}
self._save_server_config()
def get_server_config(self, guild_id: int, *keys: str):
if len(keys) == 0:
return self.server_config[str(guild_id)]
else:
config = self.server_config[str(guild_id)]
for arg in keys:
config = config[arg]
return config
def load_server_config(self):
try:
self.server_config = json.load(open(os.path.join(project_path, "databases", "server_config.json"), "r", encoding="utf-8"))
except (FileNotFoundError, JSONDecodeError) as e:
logging.error(f"Error loading server config: {e}\ncreating a new file...")
self.server_config = {}
self._save_server_config()
def _save_server_config(self):
json.dump(self.server_config,
open(os.path.join(self.bot_path(), "databases", "server_config.json"), "w", encoding="utf-8"),
indent=4)
def set_server_config(self, guild_id: int, *keys: str, value):
config = self.server_config[str(guild_id)]
for key in keys[:-1]:
config = config[key]
config[keys[-1]] = value
self._save_server_config()
def bot_path(self) -> str:
return project_path
def replaces(self, string, *args):
for i in range(0, len(args), 2):
string = string.replace(args[i], args[i + 1])
return string
async def is_member(self, member: str, guild: discord.Guild) -> bool:
for char in ["<", "@", "!", ">"]:
member = member.replace(char, "")
if not member.isdigit() and len(member) != 18:
return False
member = await guild.fetch_member(member)
return member is not None
async def is_user(self, member: str) -> bool:
for char in ["<", "@", "!", ">"]:
member = member.replace(char, "")
if not member.isdigit() and len(member) != 18:
return False
member = await self.client.fetch_user(member)
return member is not None
def apply_timezone(self, date: datetime) -> datetime:
return date.astimezone(pytz.timezone(config.timezone))
def get_date_time(self):
return datetime.now(pytz.timezone(config.timezone)).strftime("%d/%m/%Y %H:%M:%S")
def embed_color(self):
return self._color
def error_message(self, error: discord.DiscordException) -> str:
if isinstance(error, commands.MissingRequiredArgument):
return "Il manque un ou plusieurs arguments\nutilisez `/help` pour plus d'informations"
elif isinstance(error, commands.MissingPermissions) or isinstance(error,
app_commands.errors.MissingPermissions):
return "Vous n'avez pas les permissions d'utiliser cette commande"
elif isinstance(error, commands.BotMissingPermissions) or isinstance(error,
app_commands.errors.BotMissingPermissions):
return "Le bot n'a pas les permissions d'utiliser cette commande"
else:
return None
async def start_game_multi(self, ctx, limit, name_game):
"""
Args:
-----
ctx : ctx
limit : le nombre de manches dans le jeu
name_game : nom du jeu
return:
-------
list : liste des participants
dict : dictionnaire des points
"""
if str(limit).isdigit():
limit = int(limit)
else:
limit = 5
msg = await ctx.send(f"**Partie de {name_game} lancée !**\npour participer réagissez avec 🖐️")
await msg.add_reaction("🖐️")
await asyncio.sleep(15)
list_user = []
async for e in ctx.channel.history(limit=100):
if e.id == msg.id:
for reaction_of_message in e.reactions:
if reaction_of_message.emoji == "🖐️":
async for user in reaction_of_message.users():
if user.id != self.client.user.id:
list_user.append(user)
break
if len(list_user) == 0:
await ctx.reply("Aucun joueur n'a rejoint la partie", mention_author=False)
return [], []
str_name = ""
dico_points = {}
for i in list_user:
dico_points[i.id] = 0
str_name += ", " + i.name
str_name = str_name.replace(", ", "", 1)
await ctx.send(f"Liste des participants: {str_name}\nC'est parti pour {limit} manches !")
await asyncio.sleep(3)
return list_user, dico_points
async def start_game_duo(self, ctx: commands.Context, member, name_game):
member = ctx.guild.get_member(member)
if member is None:
await ctx.send("Vous n'avez pas mentionné un joueur")
return False, None
await ctx.send(f"{member.mention} acceptez-vous la partie de {name_game} contre **{ctx.author.name}** ?")
try:
msg = await self.client.wait_for("message", check=lambda message: message.author.id in [member.id,
ctx.author.id] and message.content.lower() in [
"y", "o", "n", "yes", "oui", "no",
"non"],
timeout=180)
except asyncio.TimeoutError:
await ctx.reply(f"**{member.name}** n'a pas répondu", mention_author=False)
return False, None
if msg.content.lower() in ["n", "non", "no"]:
await ctx.send("Partie refusée")
return False, None
else:
return True, member
async def end_game(self, ctx, list_user, dico_points):
"""
Args:
-----
ctx : ctx
list_user : liste de tous les participants
dico_points : dictionnaire des points
"""
n = (list_user[0].id, dico_points[list_user[0].id])
for id, point in dico_points.items():
if n[1] < point:
n = (id, point)
list_winner = [id for id, point in dico_points.items() if n[1] == point]
if len(list_winner) == 1:
username = self.client.get_user(list_winner[0])
await ctx.send(
f" \n**Partie finie !**\nLe vainqueur est {username.mention} avec {dico_points[username.id]} points !")
else:
str_winner = ""
for e in list_winner:
username = self.client.get_user(e)
str_winner += " " + username.mention
await ctx.send(
f" \n**Partie finie !**\nLes vainqueurs sont {str_winner} avec {dico_points[username.id]} points !")
def get_img(self, name: str) -> str:
"""
power
shuffle
add
minus
notif
edit
add_rond
cross_no
cross_add
speaker
trash
setting
speaker_x
mic
exit
enter
setting_bar
face
pile
"""
return dico[name]
def get_poll_object(self, guild: int, channel: int, poll_msg_id: int):
json_poll = self.pollDao.get_poll(guild, channel, poll_msg_id)
return pollView(guild, channel, poll_msg_id, json_poll["end_date"], json_poll["question"], json_poll["choix"])
def string_duration_to_datetime(self, duration: str) -> datetime:
duration = duration.split(" ")
# on considère que la durée est au format "x jour(s) y heure(s) z minute(s)"
now = datetime.now()
# on prend les éléments de la liste par 2
for i in range(0, len(duration), 2):
number, unit = duration[i], duration[i + 1]
if unit in ["années", "année", "a", "an", "ans" "years", "year", "yr", "y"]:
now += relativedelta(years=int(number))
elif unit in ["mois", "m", "months", "month", "mn", "mns"]:
now += relativedelta(months=int(number))
elif unit in ["semaines", "semaine", "w", "weeks", "week", "wk", "wks"]:
now += relativedelta(weeks=int(number))
elif unit in ["jours", "jour", "j", "days", "day", "d"]:
now += relativedelta(days=int(number))
elif unit in ["heures", "heure", "h", "hours", "hour", "hr", "hrs"]:
now += relativedelta(hours=int(number))
elif unit in ["minutes", "minute", "min", "mins"]:
now += relativedelta(minutes=int(number))
elif unit in ["secondes", "seconde", "s", "seconds", "second", "sec", "secs"]:
now += relativedelta(seconds=int(number))
return now
dico = {
"power": "https://media.discordapp.net/attachments/836943322580516904/971846167078006814/unknown.png",
"shuffle": "https://media.discordapp.net/attachments/836943322580516904/971846499443019776/unknown.png",
"add": "https://media.discordapp.net/attachments/836943322580516904/971846604321599548/unknown.png",
"minus": "https://media.discordapp.net/attachments/836943322580516904/971847114445443112/unknown.png",
"notif": "https://media.discordapp.net/attachments/836943322580516904/971847177741684826/unknown.png",
"edit": "https://media.discordapp.net/attachments/836943322580516904/971847238395498646/unknown.png",
"add_rond": "https://media.discordapp.net/attachments/836943322580516904/971847381379350578/unknown.png",
"cross_no": "https://media.discordapp.net/attachments/836943322580516904/971847400287268924/unknown.png",
"cross_add": "https://media.discordapp.net/attachments/836943322580516904/971847415143485460/unknown.png",
"speaker": "https://media.discordapp.net/attachments/836943322580516904/971847435041247385/unknown.png",
"trash": "https://media.discordapp.net/attachments/836943322580516904/971847444780425266/unknown.png",
"setting": "https://media.discordapp.net/attachments/836943322580516904/971847454892908614/unknown.png",
"speaker_x": "https://media.discordapp.net/attachments/836943322580516904/971847489453961296/unknown.png",
"mic": "https://media.discordapp.net/attachments/836943322580516904/971847505920786492/unknown.png",
"exit": "https://media.discordapp.net/attachments/836943322580516904/971847553664548934/unknown.png",
"enter": "https://media.discordapp.net/attachments/836943322580516904/971847616151298078/unknown.png",
"setting_bar": "https://media.discordapp.net/attachments/836943322580516904/971847628667097198/unknown.png",
"face": "https://media.discordapp.net/attachments/836943322580516904/971841674156339370/face_eula.png",
"pile": "https://media.discordapp.net/attachments/836943322580516904/971843297117077584/pile_eula.png",
}