-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDrystan.py
1531 lines (1376 loc) · 75 KB
/
Drystan.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
#region IMPORTS
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from math import ceil
from random import randint
import re
import discord
from discord.ext import commands
from discord.errors import HTTPException
#endregion
#region INITIATION
prefix = ">"
bot = commands.Bot(command_prefix=prefix)
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('Drystan-fda22d2bcc9d.json', scope)
gc = gspread.authorize(credentials)
tempfile = open('private-tables.txt','r')
secrettable1 = tempfile.readline().strip()
secrettable2 = tempfile.readline().strip()
secrettable3 = tempfile.readline().strip()
tempfile.close()
tempfile = open('bot-token.txt','r')
token = tempfile.readline()
tempfile.close()
helpersheetdict = {}
greenquestions = [
"What is the name of your character?", "What does your character worship?", "What is your character's gender?", "What is your character's alignment?", "How much experience has your character earned?",
"What is your character's race?", "What is your character's subrace?", "What is your first class?", "What is your first class's archetype?", "What is your first class's level?", "What is the hit die your first class uses?", "What is your second class?", "What is your second class's archetype?", "What is your second class's level?", "What is the hit die your second class uses?", "What is your third class?", "What is your third class's archetype?", "What is your third class's level?", "What is the hit die your third class uses?",
"What is your character's strength score?", "What is your character's proficiency for their strength saving throw?", "What is your character's proficiency in ahtletics?",
"What is your character's dexterity score?", "What is your character's proficiency in proficiency in their dexterity saving throw?", "What is your character's proficiency in acrobatics?", "What is your character's proficiency in sleight of hand?", "What is your character's proficiency in stealth?",
"What is your character's constitution score?", "What is your character's proficiency in their constitution saving throw?",
"What is your character's intelligence score?", "What is your character's proficiency in their intelligence saving throw?", "What is your character's proficiency in arcana?", "What is your character's proficiency in history?", "What is your character's proficiency in investigation?", "What is your character's proficiency in nature?", "What is your character's proficiency in religion?",
"What is your character's wisdom score?", "What is your character's proficiency in their wisdom saving throw?", "What is your character's proficiency in animal handling?", "What is your character's proficiency in insight?", "What is your character's proficiency in medicine?", "What is your character's proficiency in perception?", "What is your character's proficiency in survival?",
"What is your character's charisma score?", "What is your character's proficiency in their charisma saving throw?", "What is your character's proficiency in deception?", "What is your character's proficiency in intimidation?", "What is your character's proficiency in performance?", "What is your character's proficiency in persuasion?",
"Is your character a Jack of All Trades?",
"What is your character's walking speed?", "What is your character's swimming speed?", "What is your character's flying speed?", "What is your character's climbing speed?", "What is your character's burrowing speed?",
"What is your character's current health?", "What is your character's maximum health?", "What is your character's temporary health?", "How many successful death saves has your character made?", "How many failed death saves has your character made?",
"How many unused D6 does your character have?", "How many unused D8 does your character have?", "How many unused D10 does your character have?", "How many unused D12 does your character have?",
"What armor is your character wearing?", "What bonus does the armor provide to your character's AC?", "How much does the armor weigh?", "What shield is your character holding?", "What bonus does the shield provide to your character's AC?", "How much does the shield weigh?"]
greenkeys = [
'Name', 'Deity', 'Gender', 'Alignment', 'Experience',
'Race', 'Subrace', 'Class 1', 'Archetype 1', 'Level 1', 'Hit Die 1', 'Class 2', 'Archetype 2', 'Level 2', 'Hit Die 2', 'Class 3', 'Archetype 3', 'Level 3', 'Hit Die 3',
'Strength Score', 'Strength Saving Prof', 'Athletics Prof',
'Dexterity Score', 'Dexterity Saving Prof', 'Acrobatics Prof', 'Sleight of Hand Prof', 'Stealth Prof',
'Constitution Score', 'Constitution Saving Prof',
'Intelligence Score', 'Intelligence Saving Prof', 'Arcana Prof', 'History Prof', 'Investigation Prof', 'Nature Prof', 'Religion Prof',
'Wisdom Score', 'Wisdom Saving Prof', 'Animal Handling Prof', 'Insight Prof', 'Medicine Prof', 'Perception Prof', 'Survival Prof',
'Charisma Score', 'Charisma Saving Prof', 'Deception Prof', 'Intimidation Prof', 'Performance Prof', 'Persuasion Prof',
'Jack of All Trades',
'Walking Speed', 'Swimming Speed', 'Flying Speed', 'Climbing Speed', 'Burrowing Speed',
'Current Health', 'Maximum Health', 'Temporary Health', 'Successful Death Saves', 'Failed Death Saves',
'Remaining D6', 'Remaining D8', 'Remaining D10', 'Remaining D12',
'Armor Name', 'Armor AC Bonus', 'Armor Weight', 'Shield Name', 'Shield AC Bonus', 'Shield Weight']
cellvaluedict = {
#region general info
'name' : [2, 1],
'deity' : [2, 2],
'gender' : [4, 1],
'alignment' : [4, 2],
'experience': [6, 1],
'level' : [6, 2],
#endregion
#region race & class info
'race' : [2, 3],
'subrace' : [4, 3],
'class 1' : [2, 4],
'archetype 1' : [4, 4],
'level 1' : [6, 4],
'hit die 1' : [8, 4],
'class 2' : [2, 5],
'archetype 2' : [4, 5],
'level 2' : [6, 5],
'hit die 2' : [8, 5],
'class 3' : [2, 6],
'archetype 3' : [4, 6],
'level 3' : [6, 6],
'hit die 3' : [8, 6],
#endregion
#region abilities
#region strength
'strength score' : [2, 7],
'strength bonus' : [2, 8],
'strength saving prof' : [4, 7],
'strength saving bonus' : [4, 8],
'athletics prof' : [6, 7],
'athletics bonus' : [6, 8],
#endregion
#region dexterity
'dexterity score' : [2, 9],
'dexterity bonus' : [2, 10],
'dexterity saving prof' : [4, 9],
'dexterity saving bonus': [4, 10],
'acrobatics prof' : [6, 9],
'acrobatics bonus' : [6, 10],
'sleight of hand prof' : [8, 9],
'sleight of hand bonus' : [8, 10],
'stealth prof' : [10, 9],
'stealth bonus' : [10, 10],
#endregion
#region constitution
'constitution score' : [2, 11],
'constitution bonus' : [2, 12],
'constitution saving prof' : [4, 11],
'constitution saving bonus': [4, 12],
#endregion
#region intelligence
'intelligence score' : [2, 13],
'intelligence bonus' : [2, 14],
'intelligence saving prof' : [4, 13],
'intelligence saving bonus': [4, 14],
'arcana prof' : [6, 13],
'arcana bonus' : [6, 14],
'history prof' : [8, 13],
'history bonus' : [8, 14],
'investigation prof' : [10, 13],
'investigation bonus' : [10, 14],
'nature prof' : [12, 13],
'nature bonus' : [12, 14],
'religion prof' : [14, 13],
'religion bonus' : [14, 14],
#endregion
#region wisdom
'wisdom score' : [2, 15],
'wisdom bonus' : [2, 16],
'wisdom saving prof' : [4, 15],
'wisdom saving bonus' : [4, 16],
'animal handling prof' : [6, 15],
'animal handling bonus': [6, 16],
'insight prof' : [8, 15],
'insight bonus' : [8, 16],
'medicine prof' : [10, 15],
'medicine bonus' : [10, 16],
'perception prof' : [12, 15],
'perception bonus' : [12, 16],
'survival prof' : [14, 15],
'survival bonus' : [14, 16],
#endregion
#region charisma
'charisma score' : [2, 17],
'charisma bonus' : [2, 18],
'charisma saving prof' : [4, 17],
'charisma saving bonus' : [4, 18],
'deception prof' : [6, 17],
'deception bonus' : [6, 18],
'intimidation prof' : [8, 17],
'intimidation bonus' : [8, 18],
'performance prof' : [10, 17],
'performance bonus' : [10, 18],
'persuasion prof' : [12, 17],
'persuasion bonus' : [12, 18],
#endregion
#region overall skip increment here
'proficiency' : [6, 3],
'passive perception': [8, 1],
'passive insight' : [8, 2],
'initiative' : [8, 3],
'jack of all trades': [10, 6],
#endregion
#endregion
#region battle stats increment from here
#region speeds
'walking speed' : [10, 1],
'swimming speed' : [10, 2],
'flying speed' : [10, 3],
'climbing speed' : [10, 4],
'burrowing speed' : [10, 5],
#endregion
#region health, ac, deathsaves
'current health' : [12, 1],
'maximum health' : [12, 2],
'temporary health' : [12, 3],
'successful death saves' : [12, 4],
'failed death saves' : [12, 5],
'armor class' : [14, 5],
'armor class with shield' : [14, 6],
#endregion
#region hit die
'remaining d6' : [14, 1],
'remaining d8' : [14, 2],
'remaining d10' : [14, 3],
'remaining d12' : [14, 4],
'maximum d6' : [16, 1],
'maximum d8' : [16, 2],
'maximum d10' : [16, 3],
'maximum d12' : [16, 4],
#endregion
#endregion
#region gear
'armor name' : [16, 7],
'armor ac bonus' : [16, 8],
'armor weight' : [16, 9],
'shield name' : [16, 10],
'shield ac bonus' : [16, 11],
'shield weight' : [16, 12],
#endregion
}
#endregion
#region BASIC COMMANDS
@bot.event
async def on_ready():
print("My name is Drystan, and I'll be your mechanics handler today!")
@bot.command()
async def ping(ctx):
'''
This command shows the ping of the bot to your server
'''
# Get the latency of the bot
latency = bot.latency # Included in the Discord.py library
# Send it to the user
await ctx.send(latency)
#endregion
#region SAVE/LIST COMMANDS
@bot.command(pass_context = True)
async def savechar(ctx):
'''
>savechar charactername linktocharacter : Saves the character to a private googlesheet, must be shared with [email protected]
'''
await ctx.send(save_sheet(2, ctx))
@bot.command(pass_context=True)
async def savetable(ctx):
'''
>savetable tablename linktotable : Saves the table to a private googlesheet, must be shared with [email protected]
'''
try:
result = save_sheet(1, ctx)
except AttributeError:
result = "You forgot either the name of the table or the link to the table"
await ctx.send(result)
@bot.command(pass_context = True)
async def listchars(ctx):
'''
>listchars (key) : List all characters saved by you. Type key after the command to view the keys as well.
'''
await ctx.send("\n".join(list_saved_sheets(2, ctx)))
@bot.command(pass_context = True)
async def listtables(ctx):
'''
>listtables (key) : List all tables saved by you. Type key after the command to view the keys as well.
'''
await ctx.send("\n".join(list_saved_sheets(1, ctx)))
#endregion
#region ROLL COMMANDS
@bot.command()
async def roll(ctx, *, content:str):
'''
Takes in a formatted roll (examples below) and returns a complex output (containing the rolls, what you did to it, any errors that occured, and the final total)
The first thing after ">roll " must be either a Roll, or a number (if you want the bot to do simple math for you). After that, everything else can be in any order.
Regex: | Examples:
Roll - #d# | 1d20 or 50d30
Operation - +#, -#, /#, *#, ^# | +5 or - 100 or /3 or *8 or ^4
Vantage - avan, dvan | avan or dvan
Explosion - !, !!, !#, !!# | ! or !6 or !!13 (no number defaults to on crit)
Title - &t "Title here" | &t "I'm attacking!"
Description - &d "Description here" | &d "Depiction of me stabbing his eye out: ~|-- O"
To hit and damage roll - <#, <=#, =#, >=#, ># | 1d20 <5 1d4+2 or 1d20+5 >=15 1d10+2
Seperate multiple rolls - rollhere ; rollhere | 1d20+10 ; 1d20+1 ; 1d10+8
Simple ouput - &s | &s (This is the same as typing ">r rollstuffhere")
'''
embeds = do_all_rolls(content, False)
for each in embeds:
if each[0] == True:
await ctx.send(None, embed = each[1])
else:
await ctx.send(each[1])
@bot.command()
async def r(ctx, *, content:str):
'''
Takes in a formatted roll (examples below) and returns a simplified output (total only)
Basic Input: | Examples:
Roll - #d# | 1d20 or 50d30
Operation - +#, -#, /#, *#, ^# | +5 or - 100 or /3 or *8 or ^4
Vantage - avan, dvan | avan or dvan
Explosion - !, !!, !#, !!3 | ! or !6 or !!13 (no number defaults to on crit)
To hit and damage roll - <#, <=#, =#, >=#, ># | 1d20 <5 1d4+2 or 1d20+5 >=15 1d10+2
Seperate multiple rolls - rollhere ; rollhere | 1d20+10 ; 1d20+1 or 5 + 10 ; 1d10+8
'''
texts = do_all_rolls(content, True)
for each in texts:
await ctx.send(each[1])
@bot.command(pass_content=True)
async def rollchar(ctx):
'''
>rollchar linkhere option
Pass read enable sharing link or name of saved character, and what score you want to roll
Rolls given a character with a sheet named "Helper Sheet". See "Character for Drystan" for formatting. Must be shared with [email protected]
'''
result = ""
match = re.match("(\S+)\s(\S+)", ctx.message.content[10:], re.I)
if match is None:
await ctx.send("You need to provide two arguments")
return
inputsheet = match.group(1).strip()
value = match.group(2).strip().lower()
sheet = None
if re.match("https://drive.google.com/open\?id=\S+/", inputsheet, re.I) or re.match("https://docs.google.com/spreadsheets/d/\S+/edit\?usp=sharing", inputsheet, re.I):
sheet = gc.open_by_key(proper_find_id(inputsheet))
else:
key = open_saved_sheet(2, ctx.message.author.id, inputsheet)
if key is None:
await ctx.send("You haven't saved a character named " + inputsheet)
return
sheet = gc.open_by_key(key)
helpersheet = sheet.worksheet("Helper Sheet")
set_helperdict(helpersheet.get_all_values())
if value[-5:] != 'bonus':
value += " bonus"
valueinfo = get_value(value) #value, formatted
if valueinfo[0] == "Invalid Input":
await ctx.send("That's not a valid bonus to use!")
return
operations = [bonus_formatter(valueinfo[0])]
temp = run_roll(1, 20, None, None, operations) #rolls, formattedrolls, errorlist, total
try:
embed = discord.Embed(title = "**" + str(sheet.title) + "**", description = "*You rolled " + str(temp[1][0]) + " " + listToString(", ", operations) + " (" + str(valueinfo[1]) + " bonus) = " + str(temp[3]) + "*\u0020", color=0x89eaf8)
except HTTPException:
await ctx.send("Your title and description are too long! Shorten one or both.")
await ctx.send(None, embed = embed)
@bot.command(pass_context=True)
async def rolltable(ctx):
'''
Pass read enable sharing link or name of saved table
Rolls given a table with a sheet named "Main". See "Table for Drystan" for formatting. Must be shared with [email protected]
'''
result = ""
inputsheet = ctx.message.content[11:]
sheet = None
if re.match("https://drive.google.com/open\?id=\S+/", inputsheet, re.I) or re.match("https://docs.google.com/spreadsheets/d/\S+/edit\?usp=sharing", inputsheet, re.I):
sheet = gc.open_by_key(proper_find_id(inputsheet))
else:
sheet = gc.open_by_key(open_saved_sheet(1, ctx.message.author.id, inputsheet))
currtable = sheet.worksheet("Main")
info = currtable.get_all_values() #list of lists [row][col]
if len(info[0]) < 2:
await ctx.send("You must have at least two columns: one for the rolling and one for the name.")
foundrow = roll_on_table(info)
name1 = info[foundrow][1]
desc1 = ""
name2 = ""
desc2 = ""
if len(info[foundrow]) <= 4:
desc1 = info[foundrow][2]
if info[foundrow][3] == "TRUE":
currtable = sheet.worksheet(name1)
info = currtable.get_all_values() #list of lists [row][col]
foundrow = roll_on_table(info)
name2 = info[foundrow][1]
if len(info[foundrow]) > 2:
desc2 = info[foundrow][2]
try:
embed = discord.Embed(title = "**" + name1 + "**", description = "*" + desc1 + "*" if desc1 else "", color=0x89eaf8)
except HTTPException:
await ctx.send("Your title and description are too long! Shorten one or both.")
if embed and name2:
try:
embed.add_field(name = name2, value = desc2 if desc2 else "\u200b", inline = True)
except HTTPException:
await ctx.send("Your secondary title and description are too long! Shorten one or both.")
await ctx.send(None, embed = embed)
#endregion
#region CHARACTER SHEET INTERACTION COMMANDS
@bot.command(pass_context=True)
async def showchar(ctx):
'''
>showchar character sheetpart - Input saved character key, or link to valid character sheet, and the part of the sheet you want to view
Basic - Displays gender, deity, alignment, and experience
Build - Displays race and subrace, as well as all classes and archetypes, and their associated level and hit die
Abilities - Displays all ability scores and bonuses, as well as skill proficiencies and bonuses (Can also type Strength, Dexterity, Constitution, Intelligence, Wisdom or Charisma to view just one ability's table)
Battle - Displays health, death saves, and AC, as well as remaining and maximum hit die
Gear - Displays armor and shield, with bonus to AC and weight
Complete - Displays all of the above
Note: All of the above display your character's name, total level, and first class
'''
match = re.match("(\S+)\s(\S+)", ctx.message.content[9:].strip())
if match is None:
await ctx.send("You need to input two arguments")
return
inputsheet = match.group(1)
sheetpart = match.group(2).lower()
sheet = None
if re.match("https://drive.google.com/open\?id=\S+/", inputsheet, re.I) or re.match("https://docs.google.com/spreadsheets/d/\S+/edit\?usp=sharing", inputsheet, re.I):
sheet = gc.open_by_key(proper_find_id(inputsheet))
else:
key = open_saved_sheet(2, ctx.message.author.id, inputsheet)
if key is None:
await ctx.send("You haven't saved a character named " + inputsheet)
return
sheet = gc.open_by_key(key)
helpersheet = sheet.worksheet("Helper Sheet").get_all_values()
set_helperdict(helpersheet)
try:
embed = discord.Embed(title = "**" + get_value("Name")[0] + "**", description = "----------------------------------------------------------------------------------------", color=0x89eaf8)
except HTTPException:
await ctx.send("Your character's name is too long! Shorten it to view in Discord.")
if embed:
blocks = block_builder(helpersheet, sheetpart)
try:
if sheetpart != "complete" and sheetpart != "abilities":
embed.add_field(name = sheetpart.lower().capitalize(), value = (blocks[0])[1:])
else:
for i in blocks:
check = int(i[0])
embed.add_field(name = "Basic" if check == 1 else "" + "Build" if check == 2 else "" + "Abilities" if check == 3 else "" + "Battle" if check == 4 else "" + "Gear" if check == 5 else "Generic Name", value = i[1:])
except IndexError:
await ctx.send("That isn't a valid part of the character sheet.")
return
await ctx.send(None, embed = embed)
@bot.command(pass_context=True)
async def editchar(ctx):
'''
>editchar character - Input saved character key, or link to valid character sheet
'''
inputsheet = ctx.message.content[9:].strip()
myauth = ctx.message.author
mychannel = ctx.message.channel
if re.match("https://drive.google.com/open\?id=\S+/", inputsheet, re.I) or re.match("https://docs.google.com/spreadsheets/d/\S+/edit\?usp=sharing", inputsheet, re.I):
sheet = gc.open_by_key(proper_find_id(inputsheet))
else:
key = open_saved_sheet(2, ctx.message.author.id, inputsheet)
if key is None:
await ctx.send("You haven't saved a character named " + inputsheet)
return
sheet = gc.open_by_key(key)
helpersheet = sheet.worksheet("Helper Sheet")
set_helperdict(helpersheet.get_all_values())
await ctx.send("What would you like to edit?")
def check(m):
return m.author == myauth and m.channel == mychannel
mykey = (await bot.wait_for('message', check = check)).content
myvalue = get_value(mykey)
if myvalue[0] == 'Invalid Input':
await ctx.send(mykey + " is not a valid part of the sheet")
return
await ctx.send("The current value is " + myvalue[0])
await ctx.send("What would you like the new " + myvalue[1] + " to be?")
newvalue = await bot.wait_for('message', check = check)
result = change_value(helpersheet, mykey, newvalue)
await ctx.send("Your character's " + myvalue[1] + " is now " + newvalue.content)
@bot.command(pass_context=True)
async def createchar(ctx):
'''
>createchar character - Input saved character key, or link to valid character sheet
Creates a character from scratch - Asks for all inputtable values (green)
'''
inputsheet = ctx.message.content[11:].strip()
sheet = None
if re.match("https://drive.google.com/open\?id=\S+/", inputsheet, re.I) or re.match("https://docs.google.com/spreadsheets/d/\S+/edit\?usp=sharing", inputsheet, re.I):
sheet = gc.open_by_key(proper_find_id(inputsheet))
else:
key = open_saved_sheet(2, ctx.message.author.id, inputsheet)
if key is None:
await ctx.send("You haven't saved a character named " + inputsheet)
return
sheet = gc.open_by_key(key)
helpersheet = sheet.worksheet("Helper Sheet")
myauth = ctx.message.author
mychannel = ctx.message.channel
await ctx.send("To skip answering, send a message containing only \"(S)\". To quit, send a message containing only \"(X)\". For questions about proficiency, answer with \"Exp\" for expertise, \"Prof\" for proficient, and \"(S)\" for none.")
def check(m):
return m.author == myauth and m.channel == mychannel
for i in range(len(greenkeys)):
await ctx.send(greenquestions[i])
msg = await bot.wait_for('message', check = check)
result = change_value(helpersheet, greenkeys[i], msg)
if result == False:
break
await ctx.send("Your character has been created.")
#endregion
#region COMBAT TRACKER
@bot.command()
async def combat(ctx):
finalembed = None
channel = ctx.message.channel
author = ctx.message.author
fullcontent = ctx.message.content[7:].strip() #dont lower here cause might have things to repeat back
firstarg = fullcontent[:fullcontent.find(" ")].lower() if fullcontent.find(" ") != -1 else fullcontent
restargs = fullcontent[fullcontent.find(" "):] if fullcontent.find(" ") != -1 else None
finalembed = [False, "Nothing was accomplished"]
print(firstarg)
print(restargs)
#firstargs: start, end, add, remove, nextturn, lastturn, gototurn
if firstarg == "start":
print("start")
finalembed = start_combat(channel, author, ctx.message.mentions[0] if len(ctx.message.mentions) == 1 else False)
if firstarg == "end":
print("end")
finalembed = end_combat(channel, author)
if firstarg == "powers":
print("powers")
finalembed = list_powers(channel, author)
if firstarg == "add":
print("add(players)")
finalembed = await add_players(channel, author, ctx)
if finalembed[0] == False:
await ctx.send(finalembed[1])
return
else:
await ctx.send(None, finalembed[1])
return
#endregion
#region HELPER FUNCTIONS / NON COMMANDS
#region general
def listToString(separator, mylist):
result = ""
for i in range(len(mylist)):
result += str(mylist[i])
if i < len(mylist)-1:
if mylist[i] != "**|**" and mylist[i+1] != "**|**":
result += str(separator)
else:
result += " "
if result == "":
return "None"
else:
return result
def toInt(nonint):
matchcase = re.compile(r"[0-9]+", re.I).search(str(nonint))
if matchcase is None:
return 0
return int(matchcase.group(0))
def bonus_formatter(rawnum):
if rawnum.isdigit():
if int(rawnum) >= 0:
rawnum = "+" + rawnum
elif int(rawnum) < 0:
rawnum = "-" + rawnum
return rawnum
def go_int(stringtoint, baseint):
if stringtoint.isdigit():
return int(stringtoint)
else:
return baseint
def correct_spacing(string, numspaces):
if len(string) < numspaces:
for i in range(numspaces - len(string)):
string += " "
elif len(string) > numspaces:
string = string[:numspaces]
return string
def is_outside_quotes(fullstring, charindex):
numright = re.findall('"', fullstring[charindex:])
if len(numright) % 2 == 0:
return True
else:
return False
#endregion
#region roll/r helpers
def do_all_rolls(fullcontent, simple):
myrolls = find_all_rolls(fullcontent)
finishedrolls = []
for each in myrolls:
finishedrolls.extend(do_full_roll(each, simple))
embeds = []
for each in finishedrolls:
embeds.append(create_roll_embed(each))
return embeds
def do_full_roll(content, simple): #this one takes in between semicolon stuff, returns one or two embeds (depending on if there's dependent rolls)
dependized = find_dependent_info(content) #indepcontent, depnum, deptype, depcontent
if dependized[1] != None:
allembeds = [do_one_roll(dependized[0], simple)]
total = allembeds[0][8]
if ">" in dependized[1] and total > dependized[2]:
allembeds.append(do_one_roll(dependized[3], simple))
if "=" in dependized[1] and total == dependized[2]:
allembeds.append(do_one_roll(dependized[3], simple))
if "<" in dependized[1] and total < dependized[2]:
allembeds.append(do_one_roll(dependized[3], simple))
return allembeds
else:
return [do_one_roll(content, simple)]
# 0 1 2 3 4 5 6 7 8 9 10
def do_one_roll(content, simple): #this one takes in one in/dependized roll, returns title, desc, vantagename, explosion, formattedrolls, numdice, numsides, operations, total, errorlist, simple
#region
giventitle = ""
givendesc = ""
errorList = []
numdice = 0
numsides = 0
operations = []
vantage = 0 #0 - None; 1 - Advantage; 2 - Disadvantage
explosion = ""
if simple == False:
temp = find_embed_info(content)
content = temp[0]
giventitle = temp[1]
givendesc = temp[2]
errorList.extend(temp[3])
simple = temp[4]
temp = find_roll_info(content)
content = temp[0]
numsides = temp[1]
numdice = temp[2]
errorList.extend(temp[3])
impossible = temp[4]
temp = find_operation_info(content)
content = temp[0]
operations = temp[1]
temp = find_vantage_info(content)
content = temp[0]
vantage = temp[1]
temp = find_explosion_info(content)
content = temp[0]
explosion = temp[1]
rolls = [] #list of rolls for editing
formattedrolls = [] #list of formatted rolls to be displayed in the "Rolled" field
total = 0 #int displayed in the "Total"
#endregion
if impossible is True and re.search("^[0-9]+",content,re.I) is None:
total = "Impossible"
else:
if numsides == 0 and numdice == 0:
matchcase = re.search("^[0-9]+",content,re.I)
if matchcase:
rolls = [int(matchcase.group(0))]
formattedrolls = [int(matchcase.group(0))]
temp = run_operations(rolls, operations)
errorList.extend(temp[0])
total = temp[1]
else:
#run the roll
temp = run_roll(numdice, numsides, vantage, explosion, operations)
rolls = temp[0]
formattedrolls = temp[1]
errorList.extend(temp[2])
total = temp[3]
if giventitle == "":
giventitle = "Roll"
if givendesc == "":
givendesc = "The dice rattle against the table!"
vantagename = ""
if vantage == 1:
vantagename = "Advantage"
elif vantage == 2:
vantagename = "Disadvantage"
else:
vantagename = "None"
return [giventitle, givendesc, vantagename, explosion, formattedrolls, numdice, numsides, operations, total, errorList, simple]
def create_roll_embed(onerollcontentlist):
if onerollcontentlist[10] == True:
return [False, "You rolled " + listToString(",", onerollcontentlist[4]) + " and your total is " + str(onerollcontentlist[8])]
else:
try:
embed = discord.Embed(title = "**" + onerollcontentlist[0] + "**", description = "*" + onerollcontentlist[1] + "*", color=0x89eaf8)
except HTTPException:
return [False, "Your title and description are too long! Shorten one or both."]
if embed:
embed.add_field(name = "Vantage", value = onerollcontentlist[2], inline = True)
embed.add_field(name = "Explosiveness", value = onerollcontentlist[3] if onerollcontentlist[3] else "None", inline = True)
if len(listToString(", ", onerollcontentlist[4])) < 1024 - len("Rolled " + str(onerollcontentlist[5]) + "d" + str(onerollcontentlist[6])):
embed.add_field(name = "Rolled " + str(onerollcontentlist[5]) + "d" + str(onerollcontentlist[6]), value = listToString(", ", onerollcontentlist[4]), inline = False)
else:
embed.add_field(name = "Rolled " + str(onerollcontentlist[5]) + "d" + str(onerollcontentlist[6]), value = "Exceeds displayable length", inline = False)
embed.add_field(name = "Operators", value = listToString(", ",onerollcontentlist[7]) if onerollcontentlist[7] else "None", inline = False)
embed.add_field(name = "Total", value = str(onerollcontentlist[8]), inline = False)
embed.set_footer(text = "Errors: " + listToString("\n", onerollcontentlist[9]))
return [True, embed]
#find dependent info - leftroll ># rightroll - if >= / <= / = # is achieved in left roll, right roll will be run
def find_embed_info(content):
regextitle = r'\s(&t\s?")([^"]+)(")'
regexdesc = r'\s(&d\s?")([^"]+)(")'
giventitle = ""
givendesc = ""
errorList = []
simple = False
matchcase = re.compile(regextitle, re.I).search(content)
while(matchcase): #Title for embed
if giventitle:
errorList.append("You really shouldn't give me two titles")
giventitle += str(matchcase.group(2))
content = content[:matchcase.start()] + content[matchcase.end():]
matchcase = re.compile(regextitle, re.I).search(content)
matchcase = re.compile(regexdesc, re.I).search(content)
while(matchcase): #Description for embed
if givendesc:
errorList.append("You really shouldn't give me two descriptions")
givendesc += str(matchcase.group(2))
content = content[:matchcase.start()] + content[matchcase.end():]
matchcase = re.compile(regexdesc, re.I).search(content)
matchcase = re.search("&s", content, re.I)
if matchcase:
simple = True
content = content[:matchcase.start()] + content[matchcase.end():]
return [content, giventitle, givendesc, errorList, simple]
def find_all_rolls(content):
rolls = []
match = re.search(';', content)
while match:
if is_outside_quotes(content, match.start()):
rolls.append(content[:match.start()])
content = content[match.end():]
match = re.search(';', content)
else:
match = re.search(';', content[match.end():])
if len(content) > 0:
rolls.append(content)
return rolls
def find_dependent_info(content):
dependenttype = None
dependentnum = None
dependentcontent = None
matchcase = re.search('(?P<dependenttype><|<=|=|>=|>)\s?(?P<dependentnum>[0-9]+)', content, re.I)
if matchcase: #A valid explosion was found - add to explosion to be used later
dependenttype = (matchcase.group("dependenttype"))
dependentnum = int((matchcase.group("dependentnum")))
dependentcontent = content[matchcase.end():]
content = content[:matchcase.start()]
return [content, dependenttype, dependentnum, dependentcontent]
def find_roll_info(content):
regexroll = r"^[0-9]+[dD][0-9]+"
numsides = 0
numdice = 0
errorList = []
impossible = False
content = content.strip()
matchcase = re.compile(regexroll, re.I).search(content)
if(matchcase): #A valid roll was found - find d, slice on either side, set as num dice and num sides
numdice = int(content[matchcase.start():matchcase.start()+matchcase.group(0).lower().find("d")])
numsides = int(content[matchcase.start()+matchcase.group(0).lower().find("d")+1:matchcase.end()])
content = content[:matchcase.start()] + content[matchcase.end():]
if numdice == 0:
errorList.append("You can't have zero dice")
impossible = True
if numdice < 0:
errorList.append("You can't have negative dice")
impossible = True
if numsides == 0:
errorList.append("You can't have zero sides on your dice")
impossible = True
if numsides < 0:
errorList.append("You can't have negative sides on your dice")
impossible = True
if numsides*numdice > 100000:
errorList.append("That's a very large roll you're asking me to do for free, and I'm not doing it!")
impossible = True
return [content, numsides, numdice, errorList, impossible]
def find_operation_info(content):
regexoperation = r"[\s]?[(\+)(\-)(\*)(/)(\%)(\^)][\s]?[0-9]+"
operations = []
matchcase = re.compile(regexoperation, re.I).search(content)
while(matchcase): #A valid operation was found - add to operation list to be used later
operations.append(matchcase.group(0))
content = content[:matchcase.start()] + content[matchcase.end():]
matchcase = re.compile(regexoperation, re.I).search(content)
return [content, operations]
def find_vantage_info(content):
regexvantage = r"\s([ad]van)"
vantage = 0
matchcase = re.search("\s([ad])(van)",content,re.I)
if matchcase: #Advantage or disadvantage was found in the content
if matchcase.group(1).lower() == "a":
vantage = 1
elif matchcase.group(1).lower() == "d":
vantage = 2
content = content[:matchcase.start()] + content[matchcase.end():]
return [content, vantage]
def find_explosion_info(content):
regexexplosion = r"!{1,2}[0-9]*"
explosion = ""
matchcase = re.search(regexexplosion, content, re.I)
if matchcase: #A valid explosion was found - add to explosion to be used later
explosion = (matchcase.group(0))
content = content[:matchcase.start()] + content[matchcase.end():]
return [content, explosion]
def run_roll(numdice, numsides, vantage, explosion, operations):
rolls = []
formattedrolls = []
errorList = []
total = 0
operand = 0
#roll beginning bit
for i in range(numdice):
temp = randint(1,numsides)
rolls.append(temp)
formattedrolls.append(temp)
#apply advantage to rolls
if vantage != None:
temp = run_vantage(rolls, formattedrolls, vantage, numdice, numsides)
rolls = temp[0]
formattedrolls = temp[1]
#apply explosions to rolls post-advantage
if explosion != None:
temp = run_explosion(rolls, formattedrolls, explosion, numdice, numsides)
rolls = temp[0]
formattedrolls = temp[1]
errorList.extend(temp[2])
operand = temp[3]
#format the roll
temp = format_roll(rolls, formattedrolls, numsides, operand)
rolls = temp[0]
formattedrolls = temp[1]
#apply the operations
if operations != None:
temp = run_operations(rolls, operations)
errorList.extend(temp[0])
total = temp[1]
#return everything
return [rolls, formattedrolls, errorList, total]
def run_vantage(rolls, formattedrolls, vantage, numdice, numsides):
#add second layer of dice rolls
if vantage != 0:
for i in range(numdice):
temp = randint(1,numsides)
rolls.append(temp)
formattedrolls.append(temp)
#format the crits, then simultaneously remove from rolls/crossout in formattedrolls for avan/dvan
if vantage == 1: #advantage
for i in range(numdice):
minind = rolls.index(min(rolls))
formattedrolls[minind] = "~~" + str(formattedrolls[minind]) + "~~"
rolls[minind] = float('inf')
elif vantage == 2: #disadvantage
for i in range(numdice):
maxind = rolls.index(max(rolls))
formattedrolls[maxind] = "~~" + str(formattedrolls[maxind]) + "~~"
rolls[maxind] = float('-inf')
return [rolls, formattedrolls]
def run_explosion(rolls, formattedrolls, explosion, numdice, numsides):
errorList = []
operand = 0
if explosion != "":
#see if exploding on num other than max/crit
explodeon = re.search("[0-9]+", explosion)
if explodeon is None:
operand = numsides
else:
operand = int(explodeon.group(0))
if operand > numsides: #Make sure the explosion is valid
errorList.append("You can't explode on a number greater than the highest possible roll")
#The actual explosion stuffs!
elif "!!" in explosion and operand in rolls:
iterations = 0
newrolls = []
for i in range(numdice):
if rolls[i] == operand:
newrolls.append(randint(1,numsides))
while operand in newrolls and iterations < 20:
rolls.extend(newrolls)
formattedrolls.append("|")
formattedrolls.extend(newrolls)
i = 0
while i < len(newrolls):
if newrolls[i] == operand:
newrolls[i] = randint(1,numsides)
i += 1
else:
newrolls.pop(i)
iterations += 1
rolls.extend(newrolls)
formattedrolls.append("|")
formattedrolls.extend(newrolls)
if iterations == 20:
errorList.append("Too many expounded explosions")
elif "!" in explosion and operand in rolls:
formattedrolls.append("|")
for i in range(numdice):
if rolls[i] == operand:
rando = randint(1,numsides)
rolls.append(rando)
formattedrolls.append(rando)
return [rolls, formattedrolls, errorList, operand]
def run_operations(rolls, operations):
errorList = []
total = 0
#add rolls together
for i in rolls:
total += i
#apply operations to total
for i in operations:
operator = re.search(r"[(\+)(\-)(\*)(/)(\%)(\^)]", i).group(0)
operand = int(re.search(r"[0-9]+", i).group(0))
if operator == "+":
total += operand
elif operator == "-":
total -= operand
elif operator == "*":
total *= operand
elif operator == "/":
if operand == 0: #Make sure the divisor isn't 0
errorList.append("You can't divide by zero")
continue