-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.py
223 lines (184 loc) · 6.5 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
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
from discord import app_commands
import discord
import typing
from difflib import SequenceMatcher
import re
import traceback
import discord
from discord.ext import commands
from datetime import datetime
class PaginationView(discord.ui.View):
def __init__(
self,
embeds: list[discord.Embed],
author: discord.Member
) -> None:
super().__init__(
timeout=300
)
self.embeds: list[discord.Embed] = embeds
self.index: int = 0
self.message: typing.Optional[discord.Message] = None
self.author: discord.Member = author
self.update_buttons()
def update_buttons(self) -> None:
self.previous_button.disabled = (self.index == 0)
self.next_button.disabled = (self.index == len(self.embeds) - 1)
self.page_indicator.label = f"{self.index + 1}/{len(self.embeds)}"
async def interaction_check(self, interaction: discord.Interaction) -> bool:
if interaction.user != self.author:
await interaction.response.send_message("This button is not for you", ephemeral=True)
return False
return True
@discord.ui.button(
label="<",
style=discord.ButtonStyle.gray
)
async def previous_button(
self,
interaction: discord.Interaction,
button: discord.ui.Button
) -> None:
self.index -= 1
self.update_buttons()
await interaction.response.edit_message(embed=self.embeds[self.index], view=self)
@discord.ui.button(
label="1/1",
style=discord.ButtonStyle.gray,
disabled=True
)
async def page_indicator(
self,
interaction: discord.Interaction,
button: discord.ui.Button
) -> None:
pass
@discord.ui.button(
label=">",
style=discord.ButtonStyle.gray
)
async def next_button(
self,
interaction: discord.Interaction,
button: discord.ui.Button
) -> None:
self.index += 1
self.update_buttons()
await interaction.response.edit_message(embed=self.embeds[self.index], view=self)
async def on_timeout(
self
) -> None:
for item in self.children:
item.disabled = True
if self.message:
await self.message.edit(view=self)
def create_autocomplete_from_list(
options: list[str]
) -> typing.Callable[[discord.Interaction, str], typing.Coroutine[typing.Any, typing.Any, list[app_commands.Choice[str]]]]:
async def autocomplete_function(
interaction: discord.Interaction,
current: str
) -> list[app_commands.Choice[str]]:
return [
app_commands.Choice(name=option, value=option)
for option in options
if current.lower() in option.lower()
]
return autocomplete_function
def create_autocomplete_from_dict(
options: dict[str, typing.Any]
) -> typing.Callable[[discord.Interaction, str], typing.Coroutine[typing.Any, typing.Any, list[app_commands.Choice[str]]]]:
async def autocomplete_function(
interaction: discord.Interaction,
current: str
) -> list[app_commands.Choice[str]]:
return [
app_commands.Choice(name=key, value=value)
for key, value in options.items()
if current.lower() in key.lower()
]
return autocomplete_function
def create_autocomplete_from_dict_keys(
options: dict[str, typing.Any]
) -> typing.Callable[[discord.Interaction, str], typing.Coroutine[typing.Any, typing.Any, list[app_commands.Choice[str]]]]:
async def autocomplete_function(
interaction: discord.Interaction,
current: str
) -> list[app_commands.Choice[str]]:
return [
app_commands.Choice(name=key, value=key)
for key in options.keys()
if current.lower() in key.lower()
]
return autocomplete_function
async def find_member(
guild: discord.Guild,
query: str
) -> typing.Optional[discord.Member]:
best_match: typing.Optional[discord.Member] = None
best_score: float = 0
count: int = 0
for member in guild.members:
if query.isdigit() and str(member.id).startswith(query):
return member
username_score = SequenceMatcher(None, query.lower(), member.name.lower()).ratio()
if username_score > best_score:
best_match = member
best_score = username_score
if member.display_name != member.name:
display_name_score = SequenceMatcher(None, query.lower(), member.display_name.lower()).ratio()
if display_name_score > best_score:
best_match = member
best_score = display_name_score
count += 1
print(f"{count} {best_score} {best_match.name}")
return best_match
async def find_role(
guild: discord.Guild,
query: str
) -> typing.Optional[discord.Role]:
def calculate_similarity(a: str, b: str) -> float:
return SequenceMatcher(None, a.lower(), b.lower()).ratio()
best_match: typing.Optional[discord.Role] = None
best_score: float = 0
for role in guild.roles:
if query in str(role.id):
return role
role_name_score = calculate_similarity(query, role.name)
if role_name_score > best_score:
best_match = role
best_score = role_name_score
return best_match
def has_higher_role(
user: discord.Member,
target: discord.Member
) -> bool:
return user.top_role > target.top_role
def parse_time_string(
time_str: str
) -> int:
total_seconds = 0
pattern = re.compile(r'(?:(\d+)\s*(hr|hrs|h|hour|hours|mins|min|m|minutes|seconds|sec|s|second|secs)?\s*)')
matches = pattern.findall(time_str)
for value, unit in matches:
value = int(value)
if unit in ['hr', 'hrs', 'h', 'hour', 'hours']:
total_seconds += value * 3600
elif unit in ['min', 'mins', 'm', 'minutes']:
total_seconds += value * 60
elif unit in ['sec', 's', 'seconds', 'secs']:
total_seconds += value
return total_seconds
def format_seconds(
total_seconds: int
) -> str:
if total_seconds < 60:
return f"{total_seconds}s"
minutes = total_seconds // 60
if minutes < 60:
return f"{minutes}m"
hours = minutes // 60
if hours < 24:
return f"{hours}h {minutes % 60}m" if minutes % 60 else f"{hours}h"
days = hours // 24
return f"{days}d {hours % 24}h" if hours % 24 else f"{days}d"