-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.py
348 lines (281 loc) · 9.52 KB
/
util.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
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
from typing import Generator, Iterable, Sequence, Union, Optional, Any
import logging, coloredlogs
import discord
import asyncio
from discord.ext import commands
from discord.message import Message
from turns import *
from pkmntypes import *
RESPONSE_REACTIONS = [
"🇦", "🇧", "🇨", "🇩", "🇪", "🇫", "🇬", "🇭", "🇮", "🇯", "🇰", "🇱", "🇲", "🇳", "🇴", "🇵"
]
log = logging.getLogger(__name__)
coloredlogs.install(level='DEBUG', logger=log)
async def prompt_menu(
bot: commands.Bot,
user: discord.User,
content: str,
title: str,
description: str,
items: Sequence[Union[str, tuple[str, str]]],
use_channel: Optional[discord.TextChannel] = None
):
"""Create menu for the user to choose between several options."""
if use_channel:
channel = use_channel
else:
if not user.dm_channel:
await user.create_dm()
channel = user.dm_channel
embed = discord.Embed(title=title, description=description)
count = 0
for item in items:
name, value = None, None
if isinstance(item, tuple):
name, value = item
else:
name = item
embed.add_field(
name=f"{RESPONSE_REACTIONS[count]}: {name}",
value=value if value else count,
inline=False
)
count += 1
msg: Message = await channel.send(content=content, embed=embed)
for r in RESPONSE_REACTIONS[:len(items)]:
bot.loop.create_task(msg.add_reaction(r))
def check(payload):
log.debug(f"checking payload {payload}")
return payload.message_id == msg.id and payload.user_id == user.id and str(
payload.emoji
) in RESPONSE_REACTIONS
try:
log.debug("waiting for user's reaction")
# HACK: reaction_add doesn't work in DMs
payload = await bot.wait_for("raw_reaction_add", check=check)
except asyncio.TimeoutError as e:
await channel.send("timed out")
raise e
reactionId = RESPONSE_REACTIONS.index(str(payload.emoji))
embed.clear_fields()
reaction = [items[reactionId]]
for item in reaction:
name, value = None, None
if isinstance(item, tuple):
name, value = item
else:
name = item
embed.add_field(name=name, value=value if value else "Selected", inline=False)
await msg.edit(content="Selected", embed=embed)
return reactionId
async def prompt_message(
bot: commands.Bot, user: discord.User, msg: discord.Message, emojis: list[str]
):
"""Works very similar to prompt_menu except it takes in the message and a list of reactions instead of the specific menu_items."""
for r in emojis:
bot.loop.create_task(msg.add_reaction(r))
def check(payload):
log.debug(f"checking payload {payload}")
return payload.message_id == msg.id and payload.user_id == user.id and str(
payload.emoji
) in emojis
try:
log.debug("waiting for user's reaction")
# HACK: reaction_add doesn't work in DMs
payload = await bot.wait_for("raw_reaction_add", check=check)
except asyncio.TimeoutError as e:
log.error("timed out")
raise e
reactionId = emojis.index(str(payload.emoji))
return reactionId
async def prompt_for_turn(
bot: commands.Bot,
user: discord.User,
battlecontext: BattleContext,
use_channel: Optional[discord.TextChannel] = None
) -> Turn:
"""Prompt the given user for a turn.
:param bot: The discord bot
:param user: The discord user
:param battlecontext: The :class:`BattleContext` that will be given to the user.
:param use_channel: Override the channel that is used to communicate with the user. By default, it will use the user's :class:`discord.DMChannel` to send the prompt. Primarily used for tests.
:returns: The turn that the user made.
TODO: prompt user for what type of turn
"""
title = f"{battlecontext.pokemon.Name} {battlecontext.pokemon.StatusEffects.non_volatile.emoji or ''}"
description = f"{battlecontext.pokemon.CurrentHP} HP {safe_display_types(battlecontext.pokemon.Type)}"
content = "Select a move"
menu_items = []
for i, move in enumerate(battlecontext.pokemon.Moves):
menu_items.append(
(
f"{move.name}",
f"{safe_display_types(move.elemental_type)} {move.current_pp}/{move.max_pp}"
)
)
moveId = await prompt_menu(
bot, user, content, title, description, menu_items, use_channel
)
target = battlecontext.opponents[0]
return FightTurn(party=target.party, slot=target.slot, move=moveId)
def status_to_string(status: Union[int, StatusCondition]) -> set[str]:
"""Get the human-readbale form of a Pokemon's Status Condition.
:param status: pokemon battle status as defined in pokemonbattlelib
:raises ValueError: raised if `status` is not of the proper format
:return: a set of status name strings
"""
if isinstance(status, StatusCondition):
status = status.value
nonvolatile = [
"None",
"Burn",
"Freeze",
"Paralyze",
"Poison",
"BadlyPoison",
"Sleep",
]
volatile = [
"Bound",
"CantEscape",
"Confusion",
"Cursed",
"Embargo",
"Flinch",
"HealBlock",
"Identified",
"Infatuation",
"LeechSeed",
"Nightmare",
"PerishSong",
"Taunt",
"Torment",
]
try:
bitmask = status & ((1 << 3) - 1)
if bitmask != 0:
nonvolatile = [nonvolatile[bitmask]]
else:
nonvolatile = []
bitmask = status >> 3
volatile = [
flag for (index, flag) in enumerate(volatile) if (bitmask & 1 << index)
]
return set(nonvolatile + volatile)
except IndexError:
raise ValueError("invalid value for status")
def type_to_string(elemental_type: int) -> set[str]:
"""Convert a bit mask of elemental types to human readable strings.
:param elemental_type: A bit mask of elemental types.
:returns: A set of all elemental types indicated by the bit mask.
"""
return set(
[
flag for (index, flag) in enumerate(TYPE_ELEMENTS)
if (elemental_type & 1 << index)
]
)
def type_emoji_name(t: str) -> str:
"""Get the name of the emoji associated with the given type."""
return f"type{t.lower()}"
emoji_cache: dict[str, discord.Emoji] = {}
def cache_emoji(emoji: discord.Emoji):
"""Add the given emoji to a global cache so we can access them later without a reference to `bot`."""
global emoji_cache
if emoji.name not in emoji_cache:
log.debug(f"Adding emoji {emoji.name} to cache")
emoji_cache[emoji.name] = emoji
def safe_display_types(elemental_type: int) -> str:
"""Use custom emojis to display the types, if available. Otherwise, just use strings."""
types = sorted(type_to_string(elemental_type))
combined = []
for text in types:
combined += [
emoji_cache[ename] if
(ename := type_emoji_name(text)) in emoji_cache else f"[{text}]"
]
return ' '.join(map(str, combined))
def build_teams_single(*parties: Union[Party, list[Pokemon]]) -> list[Team]:
"""Take 2 parties of pokemon, creates a list of teams suitable to create a single battle.
:returns: List of teams with 1 party each.
"""
assert len(parties) == 2, "must be given 2 parties"
teams = []
for party in parties:
if isinstance(party, Party):
team = Team(parties=[party])
else:
team = Team(parties=[Party(pokemon=party)])
teams += [team]
return teams
def taggify(s: Iterable[str]) -> str:
"""Pretty print the outputs from `status_to_string` and `type_to_string`, surounding each item with square brackets.
:returns: A prettier representation.
"""
return ''.join([f'[{x}]' for x in s])
def prettify_all_transactions(transactions: list[Transaction],
context: list[Team]) -> list[str]:
"""Prettify all transactions, and concatenate/truncate them such that they fit inside the description of a :class:`discord.Embed`.
:param transactions: The list of transactions to prettify.
"""
return strings_to_embed_text([t.pretty(context) for t in transactions])
def strings_to_embed_text(strings: list[str]) -> list[str]:
"""Concatenate/truncate a list of strings such that they fit inside the description of a :class:`discord.Embed`."""
texts = []
current = ""
char_limit = 2048
while len(strings) > 0:
value = strings.pop(0)
if len(current) + len(value) + 1 > char_limit:
if len(current) > 0:
texts += [current]
if len(value) > char_limit:
texts += [value[:char_limit]]
continue
current = ""
current += value + "\n"
if len(current) > 0:
texts += [current]
return texts
def get_link(msg: Message):
"""Get the direct link for a message."""
return f"https://discord.com/channels/{msg.guild.id}/{msg.channel.id}/{msg.id}"
def json_parse(self, kwargs: dict[str, Any]):
"""Parse json dicts into the correct object according to type annotations."""
assert self.json_fields, f"{type(self)} does not have a json_fields attribute."
assert isinstance(
self.json_fields, dict
), f"json_fields must be a dict, got ({type(self.json_fields)} instead)"
def parse_obj(attr_type, obj):
try:
if isinstance(obj, list):
item_type = attr_type.__args__[0]
value = [parse_obj(item_type, i) for i in obj if i != None]
else:
if isinstance(obj, dict):
value = attr_type(**obj)
else:
value = attr_type(obj)
return value
except Exception as e:
raise Exception(
f"Error when parsing: attr_type={attr_type}, obj type={type(obj)}, obj={obj}"
) from e
for k, v in kwargs.items():
if k in self.json_fields:
attr_type = self.__annotations__[self.json_fields[k]]
attr_value = parse_obj(attr_type, v)
self.__setattr__(self.json_fields[k], attr_value)
assert self.json_fields[k] in self.__dict__
elif k in self.__annotations__:
self.__setattr__(k, v)
else:
raise KeyError(f"Unknown keyword argument: {k}")
def resolve_target(teams: list[Team], target: Target) -> Target:
"""Return `target` with the `pokemon` field populated according to the party and slot in `teams`."""
parties = []
for team in teams:
for party in team.parties:
parties.append(party)
target.pokemon = parties[target.party].pokemon[target.slot]
return target