Repository navigation
Expand file tree
/
Copy path__init__.py
More file actions
236 lines (187 loc) · 6.98 KB
/
Copy path__init__.py
File metadata and controls
236 lines (187 loc) · 6.98 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
import math
from abc import ABC, abstractmethod
from typing import Any, TypedDict, Literal, TypeVar
import discord
from discord.ext import commands
from rapidfuzz import fuzz
import breadcord
class _Unset:
def __bool__(self) -> bool:
return False
def __repr__(self) -> str:
return "<unset>"
def __str__(self) -> str:
return "<unset>"
UNSET = _Unset()
class Page:
def __init__(
self,
content: str | _Unset = UNSET,
embed: discord.Embed | None = None,
embeds: list[discord.Embed] | _Unset = UNSET,
attachment: discord.Attachment | discord.File | None = None,
attachments: list[discord.Attachment | discord.File] | _Unset = UNSET,
) -> None:
self.content = content
self.embeds = embeds
self.attachments = attachments
if embed is not None:
if self.embeds is not UNSET:
raise ValueError("Cannot set both `embed` and `embeds`.")
self.embeds = [embed]
if attachment is not None:
if self.attachments is not UNSET:
raise ValueError("Cannot set both `attachment` and `attachments`.")
self.attachments = [attachment]
def unpack(self) -> dict[str, Any]:
return {k: v for k, v in self.__dict__.items() if v is not UNSET}
_T = TypeVar('_T')
class PaginatedView(discord.ui.View, ABC):
"""
Example usage_
.. code-block:: python
view = ExamplePaginatedView(data)
await ctx.reply(**(await view.get_page()).unpack(), view=view)
"""
def __init__(self, data: list[_T], *, starting_index: int = 0, per_page: int = 1) -> None:
super().__init__(timeout=60*60)
self.data = data
self.index = starting_index
self.per_page = per_page
def get_page_data(self) -> list[_T]:
return self.data[self.index:self.index + self.per_page]
@property
def pages(self):
return math.ceil(len(self.data) / self.per_page)
@property
def current_page(self):
return self.index // self.per_page + 1
@discord.ui.button(
label="Previous",
style=discord.ButtonStyle.grey,
emoji="\N{BLACK LEFT-POINTING TRIANGLE}",
disabled=True,
)
async def previous_page(self, interaction: discord.Interaction, _) -> None:
self.index -= self.per_page
self.update_buttons()
await self.update_page(interaction)
@discord.ui.button(
label="Next",
style=discord.ButtonStyle.grey,
emoji="\N{BLACK RIGHT-POINTING TRIANGLE}",
)
async def next_page(self, interaction: discord.Interaction, _) -> None:
self.index += self.per_page
self.update_buttons()
await self.update_page(interaction)
def update_buttons(self) -> None:
self.previous_page.disabled = self.index <= 0
self.next_page.disabled = self.index >= len(self.data) - self.per_page
async def update_page(self, interaction: discord.Interaction) -> None:
await interaction.response.edit_message(view=self, **(await self.get_page()).unpack())
@abstractmethod
async def get_page(self) -> Page:
...
class Treatment(TypedDict):
id: int
label: str
class Experiment(TypedDict):
kind: Literal["user", "guild"]
id: str
label: str
file: str
treatments: list[Treatment]
class DiscordFile(TypedDict):
path: str
tags: list[str]
class DiscordBuild(TypedDict):
release_channels: dict[str, str]
build_hash: str
GLOBAL_ENV: dict[str, Any]
build_date: str
build_number: int
db_created_at: str
db_updated_at: str
environment: Literal["production"] | str
experiments: list[Experiment]
files: list[DiscordFile]
class ExperimentEmbed(discord.Embed):
def __init__(self, experiment: Experiment) -> None:
super().__init__(
title=experiment["label"],
description="\n".join(s for s in (
f"ID: `{experiment['id']}`",
f"Kind: {experiment['kind'].title()}",
f"File: `{experiment['file']}`",
) if s)
)
self.add_field(
name="Treatments",
value="\n".join(
f"- {t}" for t in (
"Not Eligible", "Control Bucket", *(
f"Treatment {treatment['id']}: {treatment['label']}"
for treatment in experiment["treatments"]
)
)
)
)
class ExperimentBrowserView(PaginatedView):
def __init__(self, data: list[Experiment], **kwargs) -> None:
super().__init__(
sorted(data, key=self.sorter, reverse=True),
per_page=20,
**kwargs
)
@staticmethod
def sorter(experiment: Experiment) -> int | str:
experiment_id = experiment["id"][:len("yyyy-mm")]
key = experiment_id.replace("-", "")
return int(key) if key.isdigit() else key
async def get_page(self) -> Page:
experiments: list[Experiment] = self.get_page_data()
embed = discord.Embed(
title=f"Page {self.current_page}/{self.pages}",
description="\n".join(
(
f"- ({experiment['kind'].title()}) `{experiment['id']}`\n"
f" - {discord.utils.escape_markdown(experiment['label'])}"
)
for experiment in experiments
),
)
return Page(embed=embed)
class DiscordData(breadcord.helpers.HTTPModuleCog):
async def get_build(self, build_hash: str | None = None) -> DiscordBuild:
if build_hash is None:
async with self.session.get("https://discord.sale/api/builds/") as response:
response.raise_for_status()
build_hash = (await response.json())["builds"][0]["build_hash"]
async with self.session.get(f"https://discord.sale/api/builds/{build_hash}") as response:
response.raise_for_status()
return await response.json()
@commands.hybrid_command(aliases=["experiment", "exper"])
async def experiments(
self,
ctx: commands.Context,
*, experiment: str | None = None,
build_hash: str | None = None
) -> None:
build = await self.get_build(build_hash)
if experiment:
experiment = experiment.lower()
for exp in build["experiments"]:
if fuzz.partial_ratio(exp["label"].lower(), experiment) > 85:
break
if fuzz.partial_ratio(exp["id"], experiment) > 85:
break
else:
await ctx.reply("No such experiment found.")
return
await ctx.reply(embed=ExperimentEmbed(exp))
return
view = ExperimentBrowserView(data=build["experiments"])
await ctx.reply(**(await view.get_page()).unpack(), view=view)
async def setup(bot: breadcord.Bot, module: breadcord.module.Module) -> None:
await bot.add_cog(DiscordData(module.id))