-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdorfbot.py
1399 lines (1150 loc) · 59 KB
/
dorfbot.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging
import socketio
import discord
from discord import app_commands
from typing import Optional
import os
import asyncio
import dice
import re
import random
import requests
import msgsplitter
DORF_STRINGS = ['!Dorf', '!dorf', '@DORFBOT', '!DORF']
FILE_DELIMITER = "/"
CURRENT_DIR = f"{os.path.dirname(os.path.realpath(__file__))}/"
SEARCH_PARAM_DIRECTORIES = ["spells", "monsters", "magicitems", "weapons"]
default_prompt = '''Adopt the role of a wise old dwarf that lives under the bridge. NEVER mention that you're an AI. Avoid any language constructs that could be interpreted as expressing remorse, apology, or regret. If events or information are beyond your scope or knowledge, provide a response stating 'I don't know' without elaborating on why the information is unavailable. Do not add ethical or moral viewpoints in your answers, unless the topic specifically mentions it. Keep responses unique and free of repetition.> '''
#default_prompt = 'The expected response for a cranky old wise Dwarf that lives under a mountain to> '
# Create a Socket.IO client
sio = socketio.Client()
# Connect to the server and register the callback function
sio.connect('ws://localhost:3000')
class DorfbotClient(discord.Client):
SUPPORT_GUILD = discord.Object(id=779141961532833803)
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
# This copies the global commands over to your guild.
logging.info("Copying guild tree commands to support guild server...")
self.tree.copy_global_to(guild=self.SUPPORT_GUILD)
await self.tree.sync(guild=self.SUPPORT_GUILD)
INTENTS = discord.Intents.default()
INTENTS.message_content = True
client = DorfbotClient(intents=INTENTS)
@client.event
async def on_ready():
logging.info(f'{client.user} has connected to Discord!')
def prune(strings, message):
for string in strings:
message = message.replace(string, '')
return message
# Set up logging
logging.basicConfig(level=logging.INFO)
#########
def searchResponse(responseResults, filteredEntityInput: str):
# Sets entity name/title to lowercase and removes spaces
def parse(entityHeader):
return entityHeader.replace(" ", "").lower()
matches = []
for apiEntity in responseResults:
# Documents don't have a name attribute
if "title" in apiEntity:
# Look for a partial match if no exact match can be found. Exact matches are pushed to front
if filteredEntityInput == parse(apiEntity["title"]):
matches.insert(0, {"entity": apiEntity, "partial": False})
elif filteredEntityInput in parse(apiEntity["title"]):
matches.append({"entity": apiEntity, "partial": True})
elif "name" in apiEntity:
if filteredEntityInput == parse(apiEntity["name"]):
matches.insert(0, {"entity": apiEntity, "partial": False})
elif filteredEntityInput in parse(apiEntity["name"]):
matches.append({"entity": apiEntity, "partial": True})
return matches
def requestScryfall(splitSearchTerm: list):
requestStr = f"https://api.scryfall.com/cards/search?q={' '.join(splitSearchTerm)}&include_extras=true&include_multilingual=true&include_variations=true"
scryfallRequest = requests.get(requestStr)
# Try again with the first arg if nothing was found
foundItem = {}
if scryfallRequest.status_code == 404:
logging.info(f"Scryfall 1st Attempt - No matches found for: {requestStr}")
requestStr = f"https://api.scryfall.com/cards/search?q={splitSearchTerm[0]}&include_extras=true&include_multilingual=true&include_variations=true"
scryfallWordRequest = requests.get(requestStr)
if scryfallWordRequest.status_code != 200:
logging.info(f"Scryfall 2nd Attempt - No matches found for: {requestStr}")
return scryfallWordRequest.status_code
else:
foundItem = scryfallWordRequest.json()["data"][0]
# Return code if API request failed
elif scryfallRequest.status_code != 200:
logging.warning(f"Scryfall 1st Attempt - API Request failed for: {requestStr}")
return scryfallRequest.status_code
# Otherwise, return the cropped image url
else:
foundItem = scryfallRequest.json()["data"][0]
# Verify there is a valid card face and image
if "card_faces" in foundItem.keys() and len(foundItem["card_faces"]) >= 1:
foundCardFace = list(foundItem["card_faces"])[0]
if "image_uris" in foundCardFace.keys() and len(foundCardFace["image_uris"].keys()) >= 1:
imageUris = dict(foundCardFace["image_uris"])
if "art_crop" in imageUris.keys():
return imageUris["art_crop"]
# Otherwise, no valid image found
return 404
def getRequestType(route: str):
# Determine filter type (search can only be used for some directories)
if route in SEARCH_PARAM_DIRECTORIES:
return "search"
else:
return "text"
def requestOpen5e(query: str, filteredEntityInput: str, wideSearch: bool, listResults: bool):
# API Request
request = requests.get(query)
# Return code if not successful
if request.status_code != 200:
return {"code": request.status_code, "query": query}
# Iterate through the results
results = searchResponse(request.json()["results"], filteredEntityInput)
if results == []:
# No full or partial matches were found
return []
elif listResults is True:
# Return all the full and partial matches
return results
else:
firstMatchedEntity = results[0]
if wideSearch is True:
# Request directory using the first word of the name to filter results
route = firstMatchedEntity['entity']["route"]
# Determine filter type (search can only be used for some directories)
filterType = getRequestType(route)
if "title" in results:
directoryRequest = requests.get(
f"https://api.open5e.com/{route}?format=json&limit=10000&{filterType}={firstMatchedEntity['entity']['title'].split()[0]}"
)
else:
directoryRequest = requests.get(
f"https://api.open5e.com/{route}?format=json&limit=10000&{filterType}={firstMatchedEntity['entity']['name'].split()[0]}"
)
# Return code if not successful
if directoryRequest.status_code != 200:
return {
"code": directoryRequest.status_code,
"query": f"https://api.open5e.com/{route}?format=json&limit=10000&search={firstMatchedEntity['entity']['name'].split()[0]}"
}
# Search response again for the actual object, return empty array if none was found
actualMatch = searchResponse(directoryRequest.json()["results"], filteredEntityInput)
if actualMatch != []:
actualMatch[0]["route"] = route
return actualMatch[0]
else:
return []
else:
# We already got a match, return it
return firstMatchedEntity
def constructResponse(entityInput: str, route: str, matchedObj: dict):
responses = {"files": list(), "embeds": list()}
# Document
if "document" in route:
# Get document link
docLink = matchedObj['url']
if "http" not in docLink:
docLink = f"http://{matchedObj['url']}"
if len(matchedObj["desc"]) >= 2048:
documentEmbed = discord.Embed(
colour=discord.Colour.green(),
title=f"{matchedObj['title']} (DOCUMENT)",
description=matchedObj["desc"][:2047],
url=docLink
)
documentEmbed.add_field(name="Description Continued...", value=matchedObj["desc"][2048:])
else:
documentEmbed = discord.Embed(
colour=discord.Colour.green(),
title=f"{matchedObj['title']} (DOCUMENT)",
description=matchedObj["desc"],
url=docLink
)
documentEmbed.add_field(name="Authors", value=matchedObj["author"], inline=False)
documentEmbed.add_field(name="Link", value=matchedObj["url"], inline=True)
documentEmbed.set_thumbnail(url="https://i.imgur.com/lnkhxCe.jpg")
responses["embeds"].append(documentEmbed)
# Spell
elif "spell" in route:
spellLink = f"https://open5e.com/spells/{matchedObj['slug']}/"
if len(matchedObj["desc"]) >= 2048:
spellEmbed = discord.Embed(
colour=discord.Colour.green(),
title=f"{matchedObj['name']} (SPELL)",
description=matchedObj["desc"][:2047],
url=spellLink
)
spellEmbed.add_field(name="Description Continued...", value=matchedObj["desc"][2048:], inline=False)
else:
spellEmbed = discord.Embed(
colour=discord.Colour.green(),
title=matchedObj["name"],
description=f"{matchedObj['desc']} (SPELL)",
url=spellLink
)
if matchedObj["higher_level"] != "":
spellEmbed.add_field(name="Higher Level", value=matchedObj["higher_level"], inline=False)
spellEmbed.add_field(name="School", value=matchedObj["school"], inline=False)
spellEmbed.add_field(name="Level", value=matchedObj["level"], inline=True)
spellEmbed.add_field(name="Duration", value=matchedObj["duration"], inline=True)
spellEmbed.add_field(name="Casting Time", value=matchedObj["casting_time"], inline=True)
spellEmbed.add_field(name="Range", value=matchedObj["range"], inline=True)
spellEmbed.add_field(name="Concentration?", value=matchedObj["concentration"], inline=True)
spellEmbed.add_field(name="Ritual?", value=matchedObj["ritual"], inline=True)
spellEmbed.add_field(name="Spell Components", value=matchedObj["components"], inline=True)
if "M" in matchedObj["components"]:
spellEmbed.add_field(name="Material", value=matchedObj["material"], inline=True)
spellEmbed.add_field(name="Page Number", value=matchedObj["page"], inline=True)
spellEmbed.set_thumbnail(url="https://i.imgur.com/W15EmNT.jpg")
responses["embeds"].append(spellEmbed)
# Monster
elif "monster" in route:
## 1ST EMBED ##
monsterLink = f"https://open5e.com/monsters/{matchedObj['slug']}/"
monsterEmbedBasics = discord.Embed(
colour=discord.Colour.green(),
title=f"{matchedObj['name']} (MONSTER) - STATS",
description="**TYPE**: {}\n**SUBTYPE**: {}\n**ALIGNMENT**: {}\n**SIZE**: {}\n**CHALLENGE RATING**: {}".format(
matchedObj["type"] if matchedObj["type"] != "" else "None",
matchedObj["subtype"] if matchedObj["subtype"] != "" else "None",
matchedObj["alignment"] if matchedObj["alignment"] != "" else "None",
matchedObj["size"],
matchedObj["challenge_rating"]
),
url=monsterLink
)
# Str
if matchedObj["strength_save"] is not None:
monsterEmbedBasics.add_field(
name="STRENGTH",
value=f"{matchedObj['strength']} (SAVE: **{matchedObj['strength_save']}**)",
inline=True
)
else:
monsterEmbedBasics.add_field(
name="STRENGTH",
value=f"{matchedObj['strength']}",
inline=True
)
# Dex
if matchedObj["dexterity_save"] is not None:
monsterEmbedBasics.add_field(
name="DEXTERITY",
value=f"{matchedObj['dexterity']} (SAVE: **{matchedObj['dexterity_save']}**)",
inline=True
)
else:
monsterEmbedBasics.add_field(
name="DEXTERITY",
value=f"{matchedObj['dexterity']}",
inline=True
)
# Con
if matchedObj["constitution_save"] is not None:
monsterEmbedBasics.add_field(
name="CONSTITUTION",
value=f"{matchedObj['constitution']} (SAVE: **{matchedObj['constitution_save']}**)",
inline=True
)
else:
monsterEmbedBasics.add_field(
name="CONSTITUTION",
value=f"{matchedObj['constitution']}",
inline=True
)
# Int
if matchedObj["intelligence_save"] is not None:
monsterEmbedBasics.add_field(
name="INTELLIGENCE",
value=f"{matchedObj['intelligence']} (SAVE: **{matchedObj['intelligence_save']}**)",
inline=True
)
else:
monsterEmbedBasics.add_field(
name="INTELLIGENCE",
value=f"{matchedObj['intelligence']}",
inline=True
)
# Wis
if matchedObj["wisdom_save"] is not None:
monsterEmbedBasics.add_field(
name="WISDOM",
value=f"{matchedObj['wisdom']} (SAVE: **{matchedObj['wisdom_save']}**)",
inline=True
)
else:
monsterEmbedBasics.add_field(
name="WISDOM",
value=f"{matchedObj['wisdom']}",
inline=True
)
# Cha
if matchedObj["charisma_save"] is not None:
monsterEmbedBasics.add_field(
name="CHARISMA",
value=f"{matchedObj['charisma']} (SAVE: **{matchedObj['charisma_save']}**)",
inline=True
)
else:
monsterEmbedBasics.add_field(
name="CHARISMA",
value=f"{matchedObj['charisma']}",
inline=True
)
# Hit points/dice
monsterEmbedBasics.add_field(
name=f"HIT POINTS (**{str(matchedObj['hit_points'])}**)",
value=matchedObj["hit_dice"],
inline=True
)
# Speeds
monsterSpeeds = ""
for speedType, speed in matchedObj["speed"].items():
monsterSpeeds += f"**{speedType}**: {speed}\n"
monsterEmbedBasics.add_field(name="SPEED", value=monsterSpeeds, inline=True)
# Armour
monsterEmbedBasics.add_field(
name="ARMOUR CLASS",
value=f"{str(matchedObj['armor_class'])} ({matchedObj['armor_desc']})",
inline=True
)
responses["embeds"].append(monsterEmbedBasics)
## 2ND EMBED ##
monsterEmbedSkills = discord.Embed(
colour=discord.Colour.green(),
title=f"{matchedObj['name']} (MONSTER) - SKILLS & PROFICIENCIES",
url=monsterLink
)
# Skills & Perception
if matchedObj["skills"] != {}:
monsterSkills = ""
for skillName, skillValue in matchedObj["skills"].items():
monsterSkills += f"**{skillName}**: {skillValue}\n"
monsterEmbedSkills.add_field(name="SKILLS", value=monsterSkills, inline=True)
# Senses
monsterEmbedSkills.add_field(name="SENSES", value=matchedObj["senses"], inline=True)
# Languages
if matchedObj["languages"] != "":
monsterEmbedSkills.add_field(name="LANGUAGES", value=matchedObj["languages"], inline=True)
# Damage conditionals
monsterEmbedSkills.add_field(
name="STRENGTHS & WEAKNESSES",
value="**VULNERABLE TO:** {}\n**RESISTANT TO:** {}\n**IMMUNE TO:** {}".format(
matchedObj["damage_vulnerabilities"] if matchedObj["damage_vulnerabilities"] != "" else "Nothing",
matchedObj["damage_resistances"] if matchedObj["damage_resistances"] != "" else "Nothing",
matchedObj["damage_immunities"] if matchedObj["damage_immunities"] != "" else "Nothing" + ", " + matchedObj["condition_immunities"] if matchedObj["condition_immunities"] is not None else "Nothing",
),
inline=False
)
responses["embeds"].append(monsterEmbedSkills)
## 3RD EMBED ##
monsterEmbedActions = discord.Embed(
colour=discord.Colour.green(),
title=f"{matchedObj['name']} (MONSTER) - ACTIONS & ABILITIES",
url=monsterLink
)
# Actions
for action in matchedObj["actions"]:
monsterEmbedActions.add_field(
name=f"{action['name']} (ACTION)",
value=action["desc"],
inline=False
)
# Reactions
if matchedObj["reactions"] != "":
for reaction in matchedObj["reactions"]:
monsterEmbedActions.add_field(
name=f"{reaction['name']} (REACTION)",
value=reaction["desc"],
inline=False
)
# Specials
for special in matchedObj["special_abilities"]:
if len(special["desc"]) >= 1024:
monsterEmbedActions.add_field(
name=f"{special['name']} (SPECIAL)",
value=special["desc"][:1023],
inline=False
)
monsterEmbedActions.add_field(
name=f"{special['name']} (SPECIAL) Continued...",
value=special["desc"][1024:],
inline=False
)
else:
monsterEmbedActions.add_field(
name=f"{special['name']} (SPECIAL)",
value=special["desc"],
inline=False
)
# Spells
if matchedObj["spell_list"] != []:
for spell in matchedObj["spell_list"]:
# Split the spell link down (e.g. https://api.open5e.com/spells/light/), [:-1] removes trailing whitespace
spellSplit = spell.replace("-", " ").split("/")[:-1]
monsterEmbedActions.add_field(
name=spellSplit[-1],
value=f"To see spell info, `/searchdir spells {spellSplit[-1]}`",
inline=False
)
responses["embeds"].append(monsterEmbedActions)
## 4TH EMBED (only used if it has legendary actions) ##
if matchedObj["legendary_desc"] != "":
monsterEmbedLegend = discord.Embed(
colour=discord.Colour.green(),
title=f"{matchedObj['name']} (MONSTER): LEGENDARY ACTIONS & ABILITIES",
description=matchedObj["legendary_desc"],
url=monsterLink
)
for action in matchedObj["legendary_actions"]:
monsterEmbedLegend.add_field(
name=action["name"],
value=action["desc"],
inline=False
)
responses["embeds"].append(monsterEmbedLegend)
# Author & Image for all embeds
for embed in responses["embeds"]:
if matchedObj["img_main"] is not None:
embed.set_thumbnail(url=matchedObj["img_main"])
else:
embed.set_thumbnail(url="https://i.imgur.com/6HsoQ7H.jpg")
# Background
elif "background" in route:
# 1st Embed (Basics)
bckLink = "https://open5e.com/sections/backgrounds"
backgroundEmbed = discord.Embed(
colour=discord.Colour.green(),
title=f"{matchedObj['name']} (BACKGROUND) - BASICS",
description=matchedObj["desc"],
url=bckLink
)
# Profs
if matchedObj["tool_proficiencies"] is not None:
backgroundEmbed.add_field(
name="PROFICIENCIES",
value=f"**SKILLS**: {matchedObj['skill_proficiencies']}\n**TOOLS**: {matchedObj['tool_proficiencies']}",
inline=True
)
else:
backgroundEmbed.add_field(
name="PROFICIENCIES",
value=f"**SKILL**: {matchedObj['skill_proficiencies']}",
inline=True
)
# Languages
if matchedObj["languages"] is not None:
backgroundEmbed.add_field(name="LANGUAGES", value=matchedObj["languages"], inline=True)
# Equipment
backgroundEmbed.add_field(name="EQUIPMENT", value=matchedObj["equipment"], inline=False)
# Feature
backgroundEmbed.add_field(name=matchedObj["feature"], value=matchedObj["feature_desc"], inline=False)
responses["embeds"].append(backgroundEmbed)
# 2nd Embed (feature)
backgroundFeatureEmbed = discord.Embed(
colour=discord.Colour.green(),
title=f"{matchedObj['name']} (BACKGROUND)\nFEATURE ({matchedObj['feature']})",
description=matchedObj["feature_desc"],
url=bckLink
)
responses["embeds"].append(backgroundFeatureEmbed)
# 3rd Embed & File (suggested characteristics)
if matchedObj["suggested_characteristics"] is not None:
if len(matchedObj["suggested_characteristics"]) <= 2047:
backgroundChars = discord.Embed(
colour=discord.Colour.green(),
title=f"{matchedObj['name']} (BACKGROUND): CHARACTERISTICS",
description=matchedObj["suggested_characteristics"],
url=bckLink
)
responses["embeds"].append(backgroundChars)
else:
backgroundChars = discord.Embed(
colour=discord.Colour.green(),
title=f"{matchedObj['name']} (BACKGROUND): CHARACTERISTICS",
description=matchedObj["suggested_characteristics"][:2047],
url=bckLink
)
bckFileName = generateFileName("background")
backgroundChars.add_field(
name="LENGTH OF CHARACTERISTICS TOO LONG FOR DISCORD",
value=f"See `{bckFileName}` for full description",
inline=False
)
responses["embeds"].append(backgroundChars)
# Create characteristics file
logging.info(f"Creating file: {bckFileName}")
with open(f"{CURRENT_DIR}data{FILE_DELIMITER}{bckFileName}", "w+") as characteristicsFile:
characteristicsFile.write(matchedObj["suggested_characteristics"])
responses["files"].append(discord.File(f"{CURRENT_DIR}data{FILE_DELIMITER + bckFileName}"))
for response in responses["embeds"]:
response.set_thumbnail(url="https://i.imgur.com/GhGODan.jpg")
# Plane
elif "plane" in route:
planeEmbed = discord.Embed(
colour=discord.Colour.green(),
title=f"{matchedObj['name']} (PLANE)",
description=matchedObj["desc"],
url="https://open5e.com/sections/planes"
)
planeEmbed.set_thumbnail(url="https://i.imgur.com/GJk1HFh.jpg")
responses["embeds"].append(planeEmbed)
# Section
elif "section" in route:
secLink = f"https://open5e.com/sections/{matchedObj['slug']}/"
if len(matchedObj["desc"]) >= 2048:
sectionEmbedDesc = discord.Embed(
colour=discord.Colour.green(),
title=f"{matchedObj['name']} (SECTION) - {matchedObj['parent']}",
description=matchedObj["desc"][:2047],
url=secLink
)
sectionFilename = generateFileName("section")
sectionEmbedDesc.add_field(
name="LENGTH OF DESCRIPTION TOO LONG FOR DISCORD",
value=f"See `{sectionFilename}` for full description",
inline=False
)
sectionEmbedDesc.set_thumbnail(url="https://i.imgur.com/J75S6bF.jpg")
responses["embeds"].append(sectionEmbedDesc)
# Full description as a file
logging.info(f"Creating file: {sectionFilename}")
with open(f"{CURRENT_DIR}data{FILE_DELIMITER}{sectionFilename}", "w+") as secDescFile:
secDescFile.write(matchedObj["desc"])
responses["files"].append(discord.File(f"{CURRENT_DIR}data{FILE_DELIMITER + sectionFilename}"))
else:
sectionEmbedDesc = discord.Embed(
colour=discord.Colour.green(),
title=f"{matchedObj['name']} (SECTION) - {matchedObj['parent']}",
description=matchedObj["desc"],
url=secLink
)
sectionEmbedDesc.set_thumbnail(url="https://i.imgur.com/J75S6bF.jpg")
responses["embeds"].append(sectionEmbedDesc)
# Feat
elif "feat" in route:
# Open5e website doesn't have a website entry for Urls yet
featEmbed = discord.Embed(
colour=discord.Colour.green(),
title=f"{matchedObj['name']} (FEAT)",
description=f"PREREQUISITES: **{matchedObj['prerequisite']}**"
)
featEmbed.add_field(name="DESCRIPTION", value=matchedObj["desc"], inline=False)
featEmbed.set_thumbnail(url="https://i.imgur.com/X1l7Aif.jpg")
responses["embeds"].append(featEmbed)
# Condition
elif "condition" in route:
conLink = "https://open5e.com/gameplay-mechanics/conditions"
if len(matchedObj["desc"]) >= 2048:
conditionEmbed = discord.Embed(
colour=discord.Colour.green(),
title=f"{matchedObj['name']} (CONDITION)",
description=matchedObj["desc"][:2047],
url=conLink
)
conditionEmbed.add_field(name="DESCRIPTION continued...", value=matchedObj["desc"][2048:], inline=False)
else:
conditionEmbed = discord.Embed(
colour=discord.Colour.green(),
title=f"{matchedObj['name']} (CONDITION)",
description=matchedObj["desc"],
url=conLink
)
conditionEmbed.set_thumbnail(url="https://i.imgur.com/tOdL5n3.jpg")
responses["embeds"].append(conditionEmbed)
# Race
elif "race" in route:
raceLink = f"https://open5e.com/races/{matchedObj['slug']}"
raceEmbed = discord.Embed(
colour=discord.Colour.green(),
title=f"{matchedObj['name']} (RACE)",
description=matchedObj["desc"],
url=raceLink
)
# Asi Description
raceEmbed.add_field(name="BENEFITS", value=matchedObj["asi_desc"], inline=False)
# Age, Alignment, Size
raceEmbed.add_field(name="AGE", value=matchedObj["age"], inline=True)
raceEmbed.add_field(name="ALIGNMENT", value=matchedObj["alignment"], inline=True)
raceEmbed.add_field(name="SIZE", value=matchedObj["size"], inline=True)
# Speeds
raceEmbed.add_field(name="SPEEDS", value=matchedObj["speed_desc"], inline=False)
# Languages
raceEmbed.add_field(name="LANGUAGES", value=matchedObj["languages"], inline=True)
# Vision buffs
if matchedObj["vision"] != "":
raceEmbed.add_field(name="VISION", value=matchedObj["vision"], inline=True)
# Traits
if matchedObj["traits"] != "":
if len(matchedObj["traits"]) >= 1024:
raceEmbed.add_field(name="TRAITS", value=matchedObj["traits"][:1023], inline=False)
raceEmbed.add_field(name="TRAITS continued...", value=matchedObj["traits"][1024:], inline=False)
else:
raceEmbed.add_field(name="TRAITS", value=matchedObj["traits"], inline=False)
raceEmbed.set_thumbnail(url="https://i.imgur.com/OUSzh8W.jpg")
responses["embeds"].append(raceEmbed)
# Start new embed for any subraces
if matchedObj["subraces"] != []:
for subrace in matchedObj["subraces"]:
subraceEmbed = discord.Embed(
colour=discord.Colour.green(),
title=f"{subrace['name']} (Subrace of **{matchedObj['name']})",
description=subrace["desc"],
url=raceLink
)
# Subrace Benefits
subraceEmbed.add_field(name="SUBRACE BENEFITS", value=subrace["asi_desc"], inline=False)
# Subrace traits
if subrace["traits"] != "":
if len(subrace["traits"]) >= 1024:
subraceEmbed.add_field(name="TRAITS", value=subrace["traits"][:1023], inline=False)
subraceEmbed.add_field(name="TRAITS continued...", value=subrace["traits"][1024:], inline=False)
else:
subraceEmbed.add_field(name="TRAITS", value=subrace["traits"], inline=False)
subraceEmbed.set_thumbnail(url="https://i.imgur.com/OUSzh8W.jpg")
responses["embeds"].append(subraceEmbed)
# Class
elif "class" in route:
# 1st Embed & File (BASIC)
classLink = f"https://open5e.com/classes/{matchedObj['slug']}"
classDescEmbed = discord.Embed(
colour=discord.Colour.green(),
title=f"{matchedObj['name']} (CLASS): Basics",
description=matchedObj["desc"][:2047],
url=classLink
)
# Spell casting
if matchedObj["spellcasting_ability"] != "":
classDescEmbed.add_field(name="CASTING ABILITY", value=matchedObj["spellcasting_ability"], inline=False)
clsDesFileName = generateFileName("clsdescription")
clsTblFileName = generateFileName("clstable")
classDescEmbed.add_field(
name="LENGTH OF DESCRIPTION & TABLE TOO LONG FOR DISCORD",
value=f"See `{clsDesFileName}` for full description\nSee `{clsTblFileName}` for class table",
inline=False
)
responses["embeds"].append(classDescEmbed)
# Full description as a file
logging.info(f"Creating file: {clsDesFileName}")
with open(f"{CURRENT_DIR}data{FILE_DELIMITER}{clsDesFileName}", "w+") as descFile:
descFile.write(matchedObj["desc"])
responses["files"].append(discord.File(f"{CURRENT_DIR}data{FILE_DELIMITER + clsDesFileName}"))
# Class table as a file
logging.info(f"Creating file: {clsTblFileName}")
with open(f"{CURRENT_DIR}data{FILE_DELIMITER}{clsTblFileName}", "w+") as tableFile:
tableFile.write(matchedObj["table"])
responses["files"].append(discord.File(f"{CURRENT_DIR}data{FILE_DELIMITER + clsTblFileName}"))
# 2nd Embed (DETAILS)
classDetailsEmbed = discord.Embed(
colour=discord.Colour.green(),
title=f"{matchedObj['name']} (CLASS): Profs & Details",
description=f"**ARMOUR**: {matchedObj['prof_armor']}\n**WEAPONS**: {matchedObj['prof_weapons']}\n**TOOLS**: {matchedObj['prof_tools']}\n**SAVE THROWS**: {matchedObj['prof_saving_throws']}\n**SKILLS**: {matchedObj['prof_skills']}",
url=classLink
)
classDetailsEmbed.add_field(
name="Hit points",
value=f"**Hit Dice**: {matchedObj['hit_dice']}\n**HP at first level**: {matchedObj['hp_at_1st_level']}\n**HP at other levels**: {matchedObj['hp_at_higher_levels']}",
inline=False
)
# Equipment
if len(matchedObj["equipment"]) >= 1024:
classDetailsEmbed.add_field(name="EQUIPMENT", value=matchedObj["equipment"][:1023], inline=False)
classDetailsEmbed.add_field(name="EQUIPMENT continued", value=matchedObj["equipment"][1024:], inline=False)
else:
classDetailsEmbed.add_field(name="EQUIPMENT", value=matchedObj["equipment"], inline=False)
responses["embeds"].append(classDetailsEmbed)
# 3rd Embed (ARCHETYPES)
if matchedObj["archetypes"] != []:
for archtype in matchedObj["archetypes"]:
archTypeEmbed = None
if len(archtype["desc"]) <= 2047:
archTypeEmbed = discord.Embed(
colour=discord.Colour.green(),
title=f"{archtype['name']} (ARCHETYPES)",
description=archtype["desc"],
url=classLink
)
responses["embeds"].append(archTypeEmbed)
else:
archTypeEmbed = discord.Embed(
colour=discord.Colour.green(),
title=f"{archtype['name']} (ARCHETYPES)\n{matchedObj['subtypes_name'] if matchedObj['subtypes_name'] != '' else 'None'} (SUBTYPE)",
description=archtype["desc"][:2047],
url=classLink
)
clsArchFileName = generateFileName("clsarchetype")
archTypeEmbed.add_field(
name="LENGTH OF DESCRIPTION TOO LONG FOR DISCORD",
value=f"See `{clsArchFileName}` for full description",
inline=False
)
responses["embeds"].append(archTypeEmbed)
logging.info(f"Creating file: {clsArchFileName}")
with open(f"{CURRENT_DIR}data{FILE_DELIMITER}{clsArchFileName}", "w+") as archDesFile:
archDesFile.write(archtype["desc"])
responses["files"].append(discord.File(f"{CURRENT_DIR}data{FILE_DELIMITER + clsArchFileName}"))
# Finish up
for response in responses["embeds"]:
response.set_thumbnail(url="https://i.imgur.com/Mjh6AAi.jpg")
# Magic Item
elif "magicitem" in route:
itemLink = f"https://open5e.com/magicitems/{matchedObj['slug']}"
if len(matchedObj["desc"]) >= 2048:
magicItemEmbed = discord.Embed(
colour=discord.Colour.green(),
title=f"{matchedObj['name']} (MAGIC ITEM)",
description=matchedObj["desc"][:2047],
url=itemLink
)
mIfileName = generateFileName("magicitem")
magicItemEmbed.add_field(
name="LENGTH OF DESCRIPTION TOO LONG FOR DISCORD",
value=f"See `{mIfileName}` for full description",
inline=False
)
responses["embeds"].append(magicItemEmbed)
logging.info(f"Creating file: {mIfileName}")
with open(f"{CURRENT_DIR}data{FILE_DELIMITER}{mIfileName}", "w+") as itemFile:
itemFile.write(matchedObj["desc"])
responses["files"].append(discord.File(f"{CURRENT_DIR}data{FILE_DELIMITER + mIfileName}"))
else:
magicItemEmbed = discord.Embed(
colour=discord.Colour.green(),
title=f"{matchedObj['name']} (MAGIC ITEM)",
description=matchedObj["desc"],
url=itemLink
)
responses["embeds"].append(magicItemEmbed)
for response in responses["embeds"]:
response.add_field(name="TYPE", value=matchedObj["type"], inline=True)
response.add_field(name="RARITY", value=matchedObj["rarity"], inline=True)
if matchedObj["requires_attunement"] == "requires_attunement":
response.add_field(name="ATTUNEMENT REQUIRED?", value="YES", inline=True)
else:
response.add_field(name="ATTUNEMENT REQUIRED?", value="NO", inline=True)
response.set_thumbnail(url="https://i.imgur.com/2wzBEjB.png")
# Remove this break if magicitems produces more than 1 embed in the future
break
# Weapon
elif "weapon" in route:
weaponEmbed = discord.Embed(
colour=discord.Colour.green(),
title=f"{matchedObj['name']} (WEAPON)",
description=f"**PROPERTIES**: {' | '.join(matchedObj['properties']) if matchedObj['properties'] != [] else 'None'}",
url="https://open5e.com/sections/weapons"
)
weaponEmbed.add_field(
name="DAMAGE",
value=f"{matchedObj['damage_dice']} ({matchedObj['damage_type']})",
inline=True
)
weaponEmbed.add_field(name="WEIGHT", value=matchedObj["weight"], inline=True)
weaponEmbed.add_field(name="COST", value=matchedObj["cost"], inline=True)
weaponEmbed.add_field(name="CATEGORY", value=matchedObj["category"], inline=False)
weaponEmbed.set_thumbnail(url="https://i.imgur.com/pXEe4L9.png")
responses["embeds"].append(weaponEmbed)
else:
badObjectFilename = generateFileName("badobject")
logging.info(f"Creating file: {badObjectFilename}")
with open(f"{CURRENT_DIR}data{FILE_DELIMITER}{badObjectFilename}", "w+") as itemFile:
itemFile.write(matchedObj)
noRouteEmbed = discord.Embed(
colour=discord.Colour.red(),
title="The matched item's type (i.e. spell, monster, etc) was not recognized",
description=f"Please create an issue describing this failure and with the following values at https://github.com/M-Davies/oghma/issues\n**Input**: {entityInput}\n**Route**: {route}\n**Troublesome Object**: SEE `{badObjectFilename}`"
)
noRouteEmbed.set_thumbnail(url="https://i.imgur.com/j3OoT8F.png")
responses["embeds"].append(noRouteEmbed)
responses["files"].append(discord.File(f"{CURRENT_DIR}data{FILE_DELIMITER + badObjectFilename}"))
return responses
def generateFileName(fileType: str):
return f"{fileType}-{str(random.randrange(1,1000000))}.md"
def codeError(statusCode: int, query: str):
codeEmbed = discord.Embed(
colour=discord.Colour.red(),
title=f"ERROR - API Request FAILED. Status Code: **{str(statusCode)}**",
description=f"Query: {query}"
)
codeEmbed.add_field(
name="For more idea on what went wrong:",
value="See status codes at https://www.django-rest-framework.org/api-guide/status-codes/",
inline=False
)
codeEmbed.set_thumbnail(url="https://i.imgur.com/j3OoT8F.png")
logging.error(f"Sending Open5e Root API Request FAILED embed = {codeEmbed.to_dict()}")
return codeEmbed
def argLengthError():
argLengthErrorEmbed = discord.Embed(
color=discord.Colour.red(),
title="Invalid argument length",
description="This command does not support more than 200 words in a single message. Try splitting up your query."
)
argLengthErrorEmbed.set_thumbnail(url="https://i.imgur.com/j3OoT8F.png")
return argLengthErrorEmbed
def getOpen5eRoot():
# Get API Root
rootRequest = requests.get("https://api.open5e.com?format=json")
if rootRequest.status_code == 200:
# Remove search directory from list (not used)
allDirectories = list(rootRequest.json().keys())
allDirectories.remove("search")
return allDirectories
else:
# Throw if Root request wasn't successful
logging.error(f"API Request to Open5e root directory FAILED. Code: {rootRequest.status_code}")
return rootRequest.status_co
@client.tree.command(description="Displays a help message that shows usage information")
async def help(interaction: discord.Interaction):
helpEmbed = discord.Embed(
title="DORFBOT",
url="https://mcgillij.dev",
description=f"__Current Latency__\n\n{round(client.latency, 1)} seconds\n\n__Available commands__\n\n**/help** - Displays this message (duh)\n\n**/search [ENTITY]** - Searches the D&D database for your chosen entity.\n\n**/searchdir [DIRECTORY] [ENTITY]** - Searches a specific category of the D&D database for your chosen entity a lot faster than */search*.\n\n**/lst [DIRECTORY] [ENTITY]** - Queries the API to get all the fully and partially matching entities based on the search term.",
color=discord.Colour.purple()
)
helpEmbed.set_author(
name="robbbot#6138",
url="https://github.com/mcgillij",
icon_url="https://github.com/mcgillij.png"
)
helpEmbed.set_thumbnail(url="https://github.com/mcgillij.png")
helpEmbed.add_field(name="LINKS", value="------------------", inline=False)
helpEmbed.add_field(name="GitHub", value="https://github.com/mcgillij/DORFBOT", inline=True)
return await interaction.response.send_message(embed=helpEmbed)
@client.tree.command(description="Queries the Open5e API to get the requested entity")