-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
348 lines (260 loc) · 12.6 KB
/
Copy pathmain.py
File metadata and controls
348 lines (260 loc) · 12.6 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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
import json
import os
import random
import unicodedata
import discord
import dotenv
from discord import Option
from titlecase import titlecase
import grotto_db
import parsers
from utils import create_embed, dev_tag
dotenv.load_dotenv()
token = os.getenv("TOKEN")
bot = discord.Bot(intents=discord.Intents.all())
dev_id = 496392770374860811
guild_id = 655390550698098700
testing_channel = 973619817317797919
grotto_bot_commands_channel = 845339551173050389
logo_url = "https://cdn.discordapp.com/emojis/856330729528361000.png"
website_url = "https://dq9.carrd.co"
server_invite_url = "https://discord.gg/"
server_invite_code = ""
character_image_url = "https://www.woodus.com/den/games/dq9ds/characreate/index.php?"
translation_data_dir = "data/translations"
def _load_general_translations():
translations = []
for file in os.listdir(translation_data_dir):
if not file.endswith(".json"):
continue
with open(os.path.join(translation_data_dir, file), "r", encoding="utf-8") as fp:
translations.extend(json.load(fp)["translations"])
return translations
def _build_translation_autocomplete_values(translations):
values_by_language = {language: [] for language in parsers.translation_languages_simple}
seen_by_language = {language: set() for language in parsers.translation_languages_simple}
all_values = []
all_seen = set()
for translation in translations:
for language in parsers.translation_languages_simple:
value = translation.get(language, "")
if value == "":
continue
if value not in seen_by_language[language]:
values_by_language[language].append(value)
seen_by_language[language].add(value)
if value not in all_seen:
all_values.append(value)
all_seen.add(value)
alias = translation.get("alias", "")
if alias != "":
if alias not in seen_by_language["english"]:
values_by_language["english"].append(alias)
seen_by_language["english"].add(alias)
if alias not in all_seen:
all_values.append(alias)
all_seen.add(alias)
return values_by_language, all_values
def _normalize_translation_language(language):
if language is None:
return None
if language in parsers.translation_languages_simple:
return language
try:
return parsers.translation_languages_simple[parsers.translation_languages.index(language)]
except ValueError:
return None
def _normalize_translation_text(text):
if text is None:
return ""
normalized = unicodedata.normalize("NFKD", text.casefold())
return "".join(
char for char in normalized
if not unicodedata.combining(char) and char not in {" ", "'", "’", ".", "-"}
)
def _extract_leading_number(value):
if value is None:
return None
candidate = str(value).split(" - ", 1)[0].strip().removeprefix("#")
return int(candidate) if candidate.isdecimal() else None
async def get_translations(ctx: discord.AutocompleteContext):
language_input = _normalize_translation_language((ctx.options or {}).get("language_input"))
values = all_translation_values if language_input is None else translation_values_by_language[language_input]
query = _normalize_translation_text(ctx.value or "")
results = []
for value in values:
if query in _normalize_translation_text(value):
results.append(value)
if len(results) == 25:
break
return results
async def get_quests(ctx: discord.AutocompleteContext):
with open("data/quests.json", "r", encoding="utf-8") as fp:
quests = json.load(fp)["quests"]
query = _normalize_translation_text(ctx.value or "")
results = []
for quest in quests:
quest_number = str(quest["number"])
quest_name = quest["name"]
label = f"{quest_number} - {quest_name}"
if query in _normalize_translation_text(quest_number) or query in _normalize_translation_text(quest_name):
results.append(label)
if len(results) == 25:
break
return results
general_translations = _load_general_translations()
translation_values_by_language, all_translation_values = _build_translation_autocomplete_values(general_translations)
@bot.event
async def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
with open("config.json", "r", encoding="utf-8") as fp:
data = json.load(fp)
global server_invite_code
server_invite_code = data["server_invite_code"]
for command in bot.commands:
print(f"{command.name} | {command.id}")
await bot.change_presence(
activity=discord.Activity(type=discord.ActivityType.watching, name="over The Quester's Rest. Type /help ."))
@bot.command(name="help", description="Get help for using the bot.")
async def _help(ctx):
description = f'''
A bot created by <@{dev_id}> for The Quester's Rest (<{server_invite_url + server_invite_code}>).
</character:984820203483459635> - *Generate a random character*
</gg:1038001809660334122> - *Get grotto info (location required) - <#{grotto_bot_commands_channel}> only*
</grotto:1038001809660334121> - *Search for a grotto - <#{grotto_bot_commands_channel}> only*
</grotto_seed:1519476166929420308> - *Get a grotto directly by seed and rank - <#{grotto_bot_commands_channel}> only*
</monster:980895182859935765> - *Get monster info*
</quest:977175507558875167> - *Get quest info*
</recipe:977175507558875168> - *Get an item's recipe*
</recipe_cascade:1236865730683863070> - *Get cascading info about a recipe*
</song:1132033677585563799> - *Play a song*
</songs_all:1132513511570935809>- *Play all songs*
</stop:1132497509353267275> - *Stop playing songs*
</translate:1038483499121913956> - *Translate a word or phrase*
</quote:1258579663354335302> - *Get a quote*
</grotto_location:1241043446882500681> - *Get grotto location info - <#{grotto_bot_commands_channel}> only*
/grotto_translate [language] - *Translate a grotto - <#{grotto_bot_commands_channel}> only*
</help:977004400352583690> - *Displays this message*
'''
if ctx.guild_id != guild_id:
description = description.replace(f" - <#{grotto_bot_commands_channel}> only", "")
embed = create_embed("Collapsus Help [Click For Server Website]", description=description, error="", image=logo_url,
url=website_url)
await ctx.respond(embed=embed)
@bot.command(name="quest", description="Sends info about a quest.")
async def _quest(ctx, quest_number: Option(str, "Quest Number (1-184)", autocomplete=get_quests, required=True)):
with open("data/quests.json", "r", encoding="utf-8") as fp:
data = json.load(fp)
quests = data["quests"]
quest_number_value = _extract_leading_number(quest_number)
if quest_number_value is None:
embed = create_embed("No quest found with the number `%s`. Please check number and try again." % quest_number)
return await ctx.respond(embed=embed)
index = quest_number_value - 1
if index >= len(quests) or index < 0:
embed = create_embed("No quest found with the number `%s`. Please check number and try again." % quest_number)
return await ctx.respond(embed=embed)
quest = parsers.Quest.from_dict(quests[index])
title = ":star: Quest #%i - %s :star:" % (quest.number, quest.name) if quest.story else "Quest #%i - %s" % (
quest.number, quest.name)
color = discord.Color.gold() if quest.story else discord.Color.green()
embed = create_embed(title, color=color)
if quest.location != "":
embed.add_field(name="Location", value=quest.location, inline=False)
if quest.request != "":
embed.add_field(name="Request", value=quest.request, inline=False)
if quest.solution != "":
embed.add_field(name="Solution", value="||%s||" % quest.solution, inline=False)
if quest.reward != "":
reward = quest.reward
if quest.story:
reward = "||%s||" % reward
embed.add_field(name="Reward", value=reward, inline=False)
embed.add_field(name="Repeat", value="Yes" if quest.repeat else "No", inline=False)
embed.add_field(name="Prerequisites", value=quest.prerequisite, inline=False)
await ctx.respond(embed=embed)
@bot.command(name="translate", description="Translate a word or phrase to a different language.")
async def _translate(ctx,
language_input: Option(str, "Input Language (Ex. English)", choices=parsers.translation_languages,
required=True),
phrase: Option(str, "Word or Phrase (Ex. Copper Sword)", autocomplete=get_translations,
required=True),
language_output: Option(str, "Output Language (Ex. Japanese)",
choices=parsers.translation_languages, required=False)):
language_input_simple = _normalize_translation_language(language_input)
language_output_simple = _normalize_translation_language(language_output)
normalized_phrase = _normalize_translation_text(phrase)
index = next(
filter(lambda t: _normalize_translation_text(t.get(language_input_simple, "")) == normalized_phrase,
general_translations),
None
)
if index is None and language_input_simple == "english":
index = next(
filter(lambda t: _normalize_translation_text(t.get("alias", "")) == normalized_phrase, general_translations),
None
)
if index is None:
embed = create_embed("No word or phrase found matching `%s`. Please check phrase and try again." % phrase,
error="Any errors? Want to contribute data? Please speak to %s" % dev_tag)
return await ctx.respond(embed=embed)
translation = parsers.Translation.from_dict(index)
all_languages = [translation.english, translation.japanese, translation.spanish, translation.french,
translation.german, translation.italian]
title = "Translation of: %s" % titlecase(
all_languages[parsers.translation_languages_simple.index(language_input_simple)]
)
color = discord.Color.green()
embed = create_embed(title, color=color, error="Any errors? Want to contribute data? Please speak to %s" % dev_tag)
if language_output is not None:
value = titlecase(all_languages[parsers.translation_languages_simple.index(language_output_simple)])
if value != "":
embed.add_field(name=language_output, value=value, inline=False)
else:
embed = create_embed("The word or phrase `%s` has not been translated to `%s`." % (phrase, language_output),
error="Any errors? Want to contribute data? Please speak to %s" % dev_tag)
return await ctx.respond(embed=embed)
else:
for language, translation in zip(parsers.translation_languages, all_languages):
if translation != "":
embed.add_field(name=language, value=titlecase(translation), inline=False)
await ctx.respond(embed=embed)
@bot.command(name="character", description="Sends info for a randomly-generated character.")
async def _character(ctx):
gender = random.choice(["Male", "Female"])
body_type = random.randint(1, 5)
hair_style = random.randint(1, 10)
hair_color = random.randint(1, 10)
face_style = random.randint(1, 10)
skin_tone = random.randint(1, 8)
eye_color = random.randint(1, 8)
keys = {"headcolor": skin_tone, "hairnum": hair_style, "haircolor": hair_color, "eyecolor": eye_color, }
remapped_eyes_female = {1: 1, 2: 2, 3: 3, 4: 12, 5: 13, 6: 14, 7: 15, 8: 16, 9: 17, 10: 20, }
remapped_eyes_male = {1: 4, 2: 5, 3: 6, 4: 7, 5: 8, 6: 9, 7: 10, 8: 11, 9: 18, 10: 19, }
if gender == "Male":
keys["hairnum"] += 10
keys["eyesnum"] = remapped_eyes_male[face_style]
else:
keys["eyesnum"] = remapped_eyes_female[face_style]
description = '''
**Gender:** %s
**Body Type:** %s
**Hair Style:** %s
**Hair Color:** %s
**Face Style:** %s
**Skin Tone:** %s
**Eye Color:** %s
''' % (gender, body_type, hair_style, hair_color, face_style, skin_tone, eye_color)
params = ""
for key, value in keys.items():
params += "%s=%s&" % (key, value)
embed = create_embed("Random Character Generator", description, image=character_image_url + params[:-1])
await ctx.respond(embed=embed)
grotto_db.create_table()
cogs = [f"cogs.{f[:-3]}" for f in os.listdir("cogs") if f.endswith(".py")]
for cog in cogs:
bot.load_extension(cog)
bot.run(token)