-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot-v3.py
More file actions
1293 lines (1062 loc) · 46.1 KB
/
bot-v3.py
File metadata and controls
1293 lines (1062 loc) · 46.1 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
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 discord
from discord.ext import commands, tasks
from discord.ui import Button, View
import copy
import json
import base64
import requests
import io
import math
import asyncio
from collections import defaultdict
from difflib import get_close_matches
USER_GITHUB_TOKENS = {
947868777528307742: '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', # PG
1334835742047731733: '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', #Sagnik with Main acc token
#1032668335135019029: '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', #Ghosty with Main acc token
845690488752832522: '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', # Aakash
783972385882767400: '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', # dev
992284684425904168: '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', # SAMA
1099047739209293944: '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', # techon
909654814651195423: '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', # dipanshu with main acc token
878545726014107698: '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', # edu with main acc token
1090560686083559545: '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', # Promanhlo with main acc token
931065234762907668: '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', # CRAFTER32ON with main acc token
}
GITHUB_TOKEN = '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'
TOKEN = 'MTM1OTQ4Njc3MjM2NjY3MjAyMg.GNnFP5.MzwGW0qOss4baLDS-ePP0GFmNxk-4vgDvT8ipM'
REPO = 'CraftersMC-Guides-Project/guides-code'
FILE_PATH = 'market/mprices.txt'
MARKET_FILE_PATH = 'market/market.txt'
PET_FILE_PATH = 'market/pet-prices.txt'
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='.', intents=intents)
original_data = []
temp_data = []
change_history = []
def load_market_data():
with open("market.txt", "r") as file:
return json.load(file)
def save_market_data(data):
with open("market.txt", "w") as file:
json.dump(data, file, indent=4)
market_temp = load_market_data()
def load_file():
global original_data, temp_data
original_data = []
updated_lines = []
file_changed = False
def safe(val):
if val is None:
return "null"
return json.dumps(val)
try:
with open("mprices.txt", "r") as f:
for line in f:
try:
parts = line.strip().split(": ", 1)
if len(parts) != 2:
continue
clean_line = parts[1].replace("N/A", "null")
item = json.loads(clean_line)
name = item[0]
user_price = item[1]
npc_price = item[2] if len(item) > 2 else None
if npc_price is None:
npc_price = 0
file_changed = True
original_data.append([name, user_price, npc_price])
updated_lines.append(
f'{parts[0]}: [{safe(name)}, {safe(user_price)}, {safe(npc_price)}]\n'
)
except Exception as item_error:
print(f"Skipping line due to error: {item_error}\nLine: {line.strip()}")
temp_data = copy.deepcopy(original_data)
if file_changed:
with open("mprices.txt", "w") as f:
f.writelines(updated_lines)
try:
with open("mprices.txt", "r") as f:
content = f.read()
sha = get_file_sha_blank()
upload_to_github_blank(content, sha)
print("✅ NaN update committed to GitHub.")
except Exception as e:
print(f"❌ Error committing changes: {e}")
except Exception as e:
print(f"❌ Error loading mprices.txt: {e}")
ABBREVIATIONS = {
"enc": "enchanted",
"ench": "enchanted",
"green": "grean",
"cobble": "cobblestone",
"op": "OVERPRICED",
"up": "UNDERPRICED",
"st": "STABLE",
}
def expand_abbreviations(text):
words = text.lower().split()
expanded = [ABBREVIATIONS.get(w, w) for w in words]
return " ".join(expanded)
user_lock = defaultdict(lambda: None)
def check_lock(command_category, user_id):
if user_lock[command_category] is None or user_lock[command_category] == user_id:
return True
return False
# Command to update price
@bot.command(aliases=['up'])
async def updateprice(ctx, *, args):
category = "updateprice"
if not check_lock(category, ctx.author.id):
await ctx.send("Another user is currently using this command category. Please try again later.")
return
user_lock[category] = ctx.author.id
global temp_data, change_history
try:
parts = args.rsplit(" ", 2)
npc_price = None
if len(parts) == 3:
identifier, user_price_str, npc_price_str = parts
npc_price = round(float(npc_price_str))
elif len(parts) == 2:
identifier, user_price_str = parts
else:
raise ValueError
user_price = round(float(user_price_str))
identifier = identifier.strip()
except ValueError:
await ctx.send("Usage: `.updateprice <index or item name> <user_price> <npc_price>`")
user_lock[category] = None
return
def update_item(index):
change_history.append(copy.deepcopy(temp_data))
temp_data[index][1] = user_price
if npc_price is not None:
if len(temp_data[index]) > 2:
temp_data[index][2] = npc_price
else:
temp_data[index].append(npc_price)
npc_display = f"{npc_price}" if npc_price is not None else "(unchanged)"
return f"Updated **{temp_data[index][0]}** to **User: {user_price}**, **NPC: {npc_display}**."
# Check if identifier is numeric (index)
if identifier.isdigit():
index = int(identifier)
if 1 <= index <= len(temp_data):
msg = update_item(index - 1)
await ctx.send(msg)
else:
await ctx.send(f"Invalid index. Please provide a valid index between 1 and {len(temp_data)}.")
user_lock[category] = None
return
# Expand abbreviation for identifier
expanded_name = expand_abbreviations(identifier.lower())
item_names = [item[0].lower() for item in temp_data]
# Try to match expanded name to item names
matches = [(i, name) for i, name in enumerate(item_names) if expanded_name in name]
# No direct matches, try close matches
if not matches:
close_matches = get_close_matches(expanded_name, item_names, n=3, cutoff=0.6)
if not close_matches:
await ctx.send(f"No item found matching '{identifier}'.")
user_lock[category] = None
return
elif len(close_matches) > 1:
await ctx.send(f"Multiple items match '{identifier}': {close_matches}. Please be more specific.")
user_lock[category] = None
return
match_name = close_matches[0]
for i, item in enumerate(temp_data):
if item[0].lower() == match_name:
msg = update_item(i)
await ctx.send(f"{msg} (best match).")
user_lock[category] = None
return
# Handle multiple matches with buttons
if len(matches) > 1:
class ItemChoiceView(View):
def __init__(self, matches, user_id):
super().__init__(timeout=30)
self.user_id = user_id
for idx, _ in matches:
self.add_item(Button(label=temp_data[idx][0], custom_id=str(idx)))
async def interaction_check(self, interaction: discord.Interaction) -> bool:
return interaction.user.id == self.user_id
view = ItemChoiceView(matches, ctx.author.id)
await ctx.send("Multiple items match your input. Please select one:", view=view)
async def wait_for_choice():
try:
interaction: discord.Interaction = await bot.wait_for(
"interaction",
check=lambda i: i.user == ctx.author and i.data["custom_id"].isdigit(),
timeout=30
)
index = int(interaction.data["custom_id"])
await interaction.response.send_message(
"Enter the new **user price** and optionally the **NPC price**, separated by space (e.g., `1000 1200`):",
ephemeral=True
)
def price_check(m):
return m.author == ctx.author and m.channel == ctx.channel
msg = await bot.wait_for("message", check=price_check, timeout=30)
try:
parts = msg.content.strip().split()
user_price_local = round(float(parts[0]))
npc_price_local = round(float(parts[1])) if len(parts) > 1 else None
change_history.append(copy.deepcopy(temp_data))
temp_data[index][1] = user_price_local
if npc_price_local is not None:
if len(temp_data[index]) > 2:
temp_data[index][2] = npc_price_local
else:
temp_data[index].append(npc_price_local)
npc_display = f"{npc_price_local}" if npc_price_local is not None else "(unchanged)"
await ctx.send(f"Updated **{temp_data[index][0]}** to **User: {user_price_local}**, **NPC: {npc_display}**.")
except:
await ctx.send("Invalid input. Please try the command again.")
except asyncio.TimeoutError:
await ctx.send("Timed out. Please try again.")
await wait_for_choice()
user_lock[category] = None
return
# Single match, apply update
i, _ = matches[0]
msg = update_item(i)
await ctx.send(msg)
user_lock[category] = None
@bot.command(aliases=['un'])
async def updatenpc(ctx, *, args):
category = "updateprice"
if not check_lock(category, ctx.author.id):
await ctx.send("Another user is currently using this command category. Please try again later.")
return
user_lock[category] = ctx.author.id
global temp_data, change_history
try:
identifier, npc_price_str = args.rsplit(" ", 1)
npc_price = round(float(npc_price_str))
identifier = identifier.strip()
except ValueError:
await ctx.send("Usage: `.updatenpc <index or item name> <npc_price>`")
user_lock[category] = None
return
if identifier.isdigit():
index = int(identifier)
if 1 <= index <= len(temp_data):
change_history.append(copy.deepcopy(temp_data))
if len(temp_data[index - 1]) > 2:
temp_data[index - 1][2] = npc_price
else:
temp_data[index - 1].append(npc_price)
await ctx.send(f"Updated item {index} to **NPC: {npc_price}**.")
else:
await ctx.send(f"Invalid index. Please provide a valid index between 1 and {len(temp_data)}.")
user_lock[category] = None
return
expanded_name = expand_abbreviations(identifier.lower())
item_names = [item[0].lower() for item in temp_data]
matches = [(i, name) for i, name in enumerate(item_names) if expanded_name in name]
if not matches:
close_matches = get_close_matches(expanded_name, item_names, n=3, cutoff=0.6)
if not close_matches:
await ctx.send(f"No item found matching '{identifier}'.")
user_lock[category] = None
return
elif len(close_matches) > 1:
await ctx.send(f"Multiple items match '{identifier}': {close_matches}. Please be more specific.")
user_lock[category] = None
return
match_name = close_matches[0]
for i, item in enumerate(temp_data):
if item[0].lower() == match_name:
change_history.append(copy.deepcopy(temp_data))
if len(temp_data[i]) > 2:
temp_data[i][2] = npc_price
else:
temp_data[i].append(npc_price)
await ctx.send(f"Updated **{item[0]}** to **NPC: {npc_price}** (best match).")
user_lock[category] = None
return
if len(matches) > 1:
class ItemChoiceView(View):
def __init__(self, matches, user_id):
super().__init__(timeout=30)
self.user_id = user_id
for idx, _ in matches:
self.add_item(Button(label=temp_data[idx][0], custom_id=str(idx)))
async def interaction_check(self, interaction: discord.Interaction) -> bool:
return interaction.user.id == self.user_id
view = ItemChoiceView(matches, ctx.author.id)
await ctx.send("Multiple items match your input. Please select one:", view=view)
async def wait_for_choice():
try:
interaction: discord.Interaction = await bot.wait_for(
"interaction",
check=lambda i: i.user == ctx.author and i.data["custom_id"].isdigit(),
timeout=30
)
index = int(interaction.data["custom_id"])
change_history.append(copy.deepcopy(temp_data))
if len(temp_data[index]) > 2:
temp_data[index][2] = npc_price
else:
temp_data[index].append(npc_price)
await interaction.response.send_message(
f"Updated **{temp_data[index][0]}** to **NPC: {npc_price}**.",
ephemeral=False
)
except asyncio.TimeoutError:
await ctx.send("Timed out. Please try again.")
await wait_for_choice()
user_lock[category] = None
return
# Single match
i, _ = matches[0]
change_history.append(copy.deepcopy(temp_data))
if len(temp_data[i]) > 2:
temp_data[i][2] = npc_price
else:
temp_data[i].append(npc_price)
await ctx.send(f"Updated **{temp_data[i][0]}** to **NPC: {npc_price}**.")
user_lock[category] = None
class PriceChangeView(View):
def __init__(self, user_id):
super().__init__(timeout=60)
self.user_id = user_id
async def interaction_check(self, interaction: discord.Interaction) -> bool:
return interaction.user.id == self.user_id
@discord.ui.button(label="Commit Changes", style=discord.ButtonStyle.success, custom_id="price_commit_btn")
async def commit_changes(self, interaction: discord.Interaction, button: Button):
user_id = self.user_id
global temp_data, original_data, change_history
await interaction.response.defer(ephemeral=True)
try:
content = ""
for i, item in enumerate(temp_data, start=1):
name = item[0]
user_price = item[1] if item[1] is not None else "0"
npc_price = item[2] if len(item) > 2 and item[2] is not None else "0"
content += f'{i}: ["{name}", {user_price}, {npc_price}]\n'
with open("mprices.txt", "w") as f:
f.write(content)
sha = get_file_sha(user_id)
upload_to_github(content, sha, user_id)
load_file()
await interaction.followup.send("✅ Changes committed to GitHub and saved to `mprices.txt`.")
except Exception as e:
await interaction.followup.send(f"❌ Error committing changes: `{e}`")
@discord.ui.button(label="Undo Last", style=discord.ButtonStyle.danger, custom_id="price_undo_last_btn")
async def undo_last(self, interaction: discord.Interaction, button: Button):
global temp_data, change_history
await interaction.response.defer()
if change_history:
temp_data = change_history.pop()
await interaction.followup.send("🔁 Last change has been undone.")
else:
await interaction.followup.send("⚠️ No previous change to undo.")
@discord.ui.button(label="Undo All", style=discord.ButtonStyle.danger, custom_id="price_undo_all_btn")
async def undo_all(self, interaction: discord.Interaction, button: Button):
global temp_data, original_data, change_history
await interaction.response.defer()
if change_history:
temp_data = copy.deepcopy(original_data)
change_history.clear()
await interaction.followup.send("🔄 All changes have been undone.")
else:
await interaction.followup.send("⚠️ No changes to undo.")
@bot.command(aliases=['sc'])
async def showchanges(ctx):
category = "showchanges"
if not check_lock(category, ctx.author.id):
await ctx.send("Another user is currently using this command category. Please try again later.")
return
user_lock[category] = ctx.author.id
def format_entry(item):
name = item[0]
user_price = item[1] if item[1] is not None else "0"
npc_price = item[2] if len(item) > 2 and item[2] is not None else "0"
return f'["{name}", {user_price}, {npc_price}]'
diff = ""
for i, (new_item, old_item) in enumerate(zip(temp_data, original_data), start=1):
old_user_price = old_item[1] if old_item[1] is not None else 0
new_user_price = new_item[1] if new_item[1] is not None else 0
old_npc_price = old_item[2] if len(old_item) > 2 and old_item[2] is not None else 0
new_npc_price = new_item[2] if len(new_item) > 2 and new_item[2] is not None else 0
if old_user_price != new_user_price or old_npc_price != new_npc_price:
diff += f"{i}: {format_entry(old_item)} → {format_entry(new_item)}\n"
if len(temp_data) > len(original_data):
for i in range(len(original_data), len(temp_data)):
diff += f"{i + 1}: + {format_entry(temp_data[i])}\n"
elif len(temp_data) < len(original_data):
for i in range(len(temp_data), len(original_data)):
diff += f"{i + 1}: - {format_entry(original_data[i])}\n"
if not diff:
diff = "No changes."
user_token = get_user_github_token(ctx.author.id)
if not user_token:
await ctx.send("No GitHub token found for this user. Please ensure you have linked your GitHub account.")
user_lock[category] = None
return
try:
user_id = ctx.author.id
get_file_sha(user_id)
except ValueError as e:
await ctx.send(f"Error fetching file: {str(e)}")
user_lock[category] = None
return
except requests.exceptions.RequestException as e:
await ctx.send(f"GitHub request failed: {str(e)}")
user_lock[category] = None
return
view = PriceChangeView(ctx.author.id)
if len(diff) > 3900:
file = discord.File(io.StringIO(diff), filename="diff.txt")
await ctx.send("Here are the pending changes:", file=file, view=view)
else:
await ctx.send(f"```diff\n{diff}```", view=view)
user_lock[category] = None
market_original = []
market_temp = []
market_history = []
def load_market_data():
with open("market.txt", "r") as f:
return json.load(f)
def save_market_data(data):
with open("market.txt", "w") as f:
json.dump(data, f, indent=4)
def initialize_market():
global market_original, market_temp
market_original = load_market_data()
market_temp = copy.deepcopy(market_original)
def diff_market():
changes = []
for orig, temp in zip(market_original, market_temp):
if orig != temp:
changes.append(f"{orig['id']} {orig['name']}: {orig} -> {temp}")
# Debugging output
print(f"Detected Changes: {changes}")
return changes
def expand_abbreviations(text: str) -> str:
ABBREVIATIONS = {
"op": "OVERPRICE",
"st": "STABLE",
"up": "UNDERPRICE",
}
text = text.lower()
return ABBREVIATIONS.get(text, text)
@bot.command(aliases=['um'])
async def updatemarket(ctx, *, args):
global market_temp, market_history
parts = args.split()
if not parts:
await ctx.send("Usage: `.um <item name/id> [nature] [demand]`")
return
nature = demand = None
# Parse demand
if parts:
last = parts[-1]
if last.isdigit() or "/10" in last:
demand = parts.pop()
if "/" not in demand:
demand = f"{demand}/10"
# Parse nature
if parts:
potential_nature = parts[-1]
if not potential_nature.isdigit() and "/10" not in potential_nature:
nature = parts.pop().upper()
if not parts:
await ctx.send("❌ Could not parse item name. Please try again.")
return
# Apply abbreviation expansion to the identifier and nature/demand values
identifier = expand_abbreviations(" ".join(parts).lower().strip())
if nature:
nature = expand_abbreviations(nature.lower())
if demand:
demand = expand_abbreviations(demand.lower())
# Compare the identifier to item names in market_temp
matches = [
(i, item) for i, item in enumerate(market_temp)
if identifier in expand_abbreviations(item['name'].lower()) or str(item['id']) == identifier
]
# No direct matches, try close match
if not matches:
expanded_names = [expand_abbreviations(item['name'].lower()) for item in market_temp]
close = get_close_matches(identifier, expanded_names, n=3, cutoff=0.5)
if not close:
await ctx.send("❌ No matches found.")
return
elif len(close) > 1:
await ctx.send(f"Multiple items match '{identifier}': {close}. Please be more specific.")
return
matches = [
(i, item) for i, item in enumerate(market_temp)
if expand_abbreviations(item['name'].lower()) in close
]
async def apply_update(index: int):
market_history.append(copy.deepcopy(market_temp))
updates = []
if nature is not None:
market_temp[index]['nature'] = f"[{nature}]"
updates.append(f"nature **[{nature}]**")
if demand is not None:
market_temp[index]['demand'] = f"[{demand}]"
updates.append(f"demand **[{demand}]**")
updated_item = market_temp[index]
changes_msg = " and ".join(updates) if updates else "no changes"
await ctx.send(f"✅ Updated **{updated_item['name']}** with {changes_msg}.")
# Handle multiple matches
if len(matches) > 1:
class MarketChoiceView(View):
def __init__(self):
super().__init__(timeout=30)
for idx, item in matches:
label = f"{item['name']} ({item['id']})"
self.add_item(Button(label=label, custom_id=str(idx)))
async def interaction_check(self, interaction: discord.Interaction) -> bool:
return interaction.user == ctx.author
async def on_timeout(self):
for child in self.children:
child.disabled = True
view = MarketChoiceView()
await ctx.send("🔍 Multiple items found. Select one:", view=view)
def check(interaction: discord.Interaction):
return interaction.user == ctx.author and interaction.data['custom_id'].isdigit()
try:
interaction = await bot.wait_for("interaction", check=check, timeout=30)
await interaction.response.defer()
await apply_update(int(interaction.data['custom_id']))
except asyncio.TimeoutError:
await ctx.send("⏱️ Selection timed out.")
else:
index, _ = matches[0]
await apply_update(index)
class MarketChangeView(View):
def __init__(self):
super().__init__(timeout=300)
@discord.ui.button(label="Commit Changes", style=discord.ButtonStyle.success, custom_id="commit_market")
async def commit_changes(self, interaction: discord.Interaction, button: discord.ui.Button):
try:
user_id = interaction.user.id
content = json.dumps(market_temp, indent=4)
with open("market.txt", "w") as f:
f.write(content)
sha = get_market_sha(user_id)
upload_market_to_github(content, sha, user_id)
market_temp.clear()
market_temp.extend(load_market_data())
market_history.clear()
await interaction.response.send_message("✅ Committed market changes to GitHub and cleared temporary edits.")
except Exception as e:
await interaction.response.send_message(f"❌ Error committing market changes: `{e}`")
@discord.ui.button(label="Undo Last", style=discord.ButtonStyle.danger, custom_id="undo_last_market")
async def undo_last(self, interaction: discord.Interaction, button: discord.ui.Button):
if market_history:
market_temp[:] = market_history.pop()
await interaction.response.send_message("↩️ Last change undone.")
else:
await interaction.response.send_message("⚠️ No change to undo.")
@discord.ui.button(label="Undo All", style=discord.ButtonStyle.danger, custom_id="undo_all_market")
async def undo_all(self, interaction: discord.Interaction, button: discord.ui.Button):
market_temp.clear()
market_temp.extend(load_market_data())
market_history.clear()
await interaction.response.send_message("🔄 All changes undone.")
@bot.command(aliases=['smc'])
async def showmarketchanges(ctx):
diff = ""
for i, (temp_item, orig_item) in enumerate(zip(market_temp, market_original), start=1):
changes = []
for key in ['name', 'price', 'nature', 'demand']:
if temp_item.get(key) != orig_item.get(key):
changes.append(f"{key}: {orig_item.get(key)} → {temp_item.get(key)}")
if changes:
diff += f"{i}: {orig_item.get('name')} ({orig_item.get('id')}):\n " + "\n ".join(changes) + "\n"
if len(market_temp) > len(market_original):
for i in range(len(market_original), len(market_temp)):
item = market_temp[i]
diff += f"{i + 1}: + Added → {item['name']} ({item['id']})\n"
elif len(market_temp) < len(market_original):
for i in range(len(market_temp), len(market_original)):
item = market_original[i]
diff += f"{i + 1}: - Removed → {item['name']} ({item['id']})\n"
if not diff:
diff = "No changes."
view = MarketChangeView()
if len(diff) > 3900:
file = discord.File(io.StringIO(diff), filename="market_diff.txt")
await ctx.send("Here are the pending market changes:", file=file, view=view)
else:
await ctx.send(f"```diff\n{diff}```", view=view)
pet_temp_data = []
pet_change_history = []
pet_original_data = []
def load_pet_prices():
global pet_original_data, pet_temp_data
pet_original_data.clear()
pet_temp_data.clear()
file_changed = False
try:
with open("pet-prices.txt", "r") as f:
data = json.load(f)
# Filling missing values for rarities and preparing the data
for item in data:
for rarity in ["common", "uncommon", "rare", "epic", "legendary"]:
if item.get(rarity) is None:
item[rarity] = 0
file_changed = True
pet_original_data.append({
"petId": item.get("petId"),
"name": item.get("name", ""),
"common": item["common"],
"uncommon": item["uncommon"],
"rare": item["rare"],
"epic": item["epic"],
"legendary": item["legendary"]
})
# Initialize temp data with a copy of the original data
pet_temp_data.extend(copy.deepcopy(pet_original_data))
# If there were any missing values filled, save the changes
if file_changed:
with open("pet-prices.txt", "w") as f:
json.dump(pet_original_data, f, indent=2)
# Commit changes to GitHub
try:
with open("pet-prices.txt", "r") as f:
content = f.read()
sha = get_file_sha_blank()
upload_to_github_blank(content, sha)
print("✅ Missing values filled and committed to GitHub.")
except Exception as e:
print(f"❌ Error committing changes: {e}")
except Exception as e:
print(f"❌ Error loading pet-prices.txt: {e}")
def load_pet_data():
with open("pet-prices.txt", "r") as f:
return json.load(f)
load_pet_prices()
def save_pet_data(data):
with open("pet-prices.txt", "w") as file:
json.dump(data, file, indent=4)
@bot.command(aliases=['pu'])
async def updatepet(ctx, pet_identifier: str, rarity: str, price: float):
category = "updatepet"
if not check_lock(category, ctx.author.id):
await ctx.send("⚠️ Another user is currently using this command category. Please try again later.")
return
user_lock[category] = ctx.author.id
try:
rarity = rarity.lower()
if rarity not in {"common", "uncommon", "rare", "epic", "legendary"}:
await ctx.send("❌ Invalid rarity. Choose from: common, uncommon, rare, epic, legendary")
return
# Find the pet index in temp data
index = None
if pet_identifier.isdigit():
index = next((i for i, item in enumerate(pet_temp_data)
if str(item.get("petId")) == pet_identifier), None)
else:
lower_name = pet_identifier.lower()
index = next((i for i, item in enumerate(pet_temp_data)
if item.get("name", "").lower() == lower_name), None)
if index is None:
await ctx.send(f"❌ No pet found with ID or name `{pet_identifier}`.")
return
current_value = pet_temp_data[index].get(rarity)
if round(price) == current_value:
await ctx.send("⚠️ No changes made. The value is the same as the current one.")
return
# Record the changes in the history
pet_change_history.append(copy.deepcopy(pet_temp_data))
# Update the price in temp data
pet_temp_data[index][rarity] = round(price)
pet = pet_temp_data[index]
pet_name = pet.get("name") or f"Pet ID {pet.get('petId')}"
await ctx.send(f"✅ Updated `{pet_name}` rarity `{rarity.title()}` price to `{round(price)}`.")
except Exception as e:
await ctx.send(f"❌ An error occurred: {e}")
finally:
user_lock[category] = None
class PetPriceChangeView(View):
def __init__(self, user_id):
super().__init__(timeout=60)
self.user_id = user_id
async def interaction_check(self, interaction: discord.Interaction) -> bool:
return interaction.user.id == self.user_id
@discord.ui.button(label="Commit Pet Changes", style=discord.ButtonStyle.success)
async def commit_changes(self, interaction: discord.Interaction, button: Button):
global pet_temp_data, pet_original_data, pet_change_history
await interaction.response.defer(ephemeral=True)
try:
content = json.dumps(pet_temp_data, indent=2)
with open("pet-prices.txt", "w") as f:
f.write(content)
sha = get_pet_sha(self.user_id)
upload_pet_to_github(content, sha, self.user_id)
# Commit the changes
pet_original_data = copy.deepcopy(pet_temp_data)
pet_change_history.clear()
await interaction.followup.send("✅ Pet market changes committed to GitHub and saved to `pet-prices.txt`.")
except Exception as e:
await interaction.followup.send(f"❌ Error committing pet changes: `{e}`")
@discord.ui.button(label="Undo Last", style=discord.ButtonStyle.danger)
async def undo_last(self, interaction: discord.Interaction, button: Button):
global pet_temp_data, pet_change_history
await interaction.response.defer()
if pet_change_history:
pet_temp_data = pet_change_history.pop()
await interaction.followup.send("🔁 Last pet market change has been undone.")
else:
await interaction.followup.send("⚠️ No previous change to undo.")
@discord.ui.button(label="Undo All", style=discord.ButtonStyle.danger)
async def undo_all(self, interaction: discord.Interaction, button: Button):
global pet_temp_data, pet_original_data, pet_change_history
await interaction.response.defer()
if pet_change_history:
pet_temp_data = copy.deepcopy(pet_original_data)
pet_change_history.clear()
await interaction.followup.send("🔄 All pet market changes have been undone.")
else:
await interaction.followup.send("⚠️ No changes to undo.")
@bot.command(aliases=['spc'])
async def showpetchanges(ctx):
category = "updatepet"
if not check_lock(category, ctx.author.id):
await ctx.send("⚠️ Another user is currently using this command category. Please try again later.")
return
user_lock[category] = ctx.author.id
def format_change(pet_id, name, rarity, old_val, new_val):
label = f"{pet_id} - {name}" if name else f"{pet_id}"
return f"{label}: {rarity.title()} {old_val} → {new_val}"
diff = ""
id_map = {str(p["petId"]): p for p in pet_original_data}
temp_ids = {str(p["petId"]) for p in pet_temp_data}
for pet in pet_temp_data:
pet_id = str(pet["petId"])
name = pet.get("name", "")
original = id_map.get(pet_id)
if not original:
continue # skip new pets for now
for rarity in ["common", "uncommon", "rare", "epic", "legendary"]:
old_val = original.get(rarity, 0)
new_val = pet.get(rarity, 0)
if old_val != new_val:
diff += format_change(pet_id, name, rarity, old_val, new_val) + "\n"
if not diff:
diff = "No changes."
user_token = get_user_github_token(ctx.author.id)
if not user_token:
await ctx.send("❌ No GitHub token found for this user.")
user_lock[category] = None
return
try:
get_file_sha(ctx.author.id)
except Exception as e:
await ctx.send(f"❌ Error fetching GitHub SHA: {str(e)}")
user_lock[category] = None
return
view = PetPriceChangeView(ctx.author.id)
if len(diff) > 3900:
file = discord.File(io.StringIO(diff), filename="pet_diff.txt")
await ctx.send("Here are the pending pet market changes:", file=file, view=view)
else:
await ctx.send(f"```diff\n{diff}```", view=view)
user_lock[category] = None
def get_user_github_token(user_id):
"""Fetches the GitHub token for the user based on their ID."""
return USER_GITHUB_TOKENS.get(user_id)
def get_file_sha(user_id):
"""Get the SHA of the file using the user's GitHub token."""
token = get_user_github_token(user_id)
if not token:
raise ValueError("No GitHub token found for this user.")
url = f"https://api.github.com/repos/{REPO}/contents/{FILE_PATH}"
headers = {
"Authorization": f"token {token}",
"Accept": "application/vnd.github+json"
}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()["sha"]
def get_market_sha(user_id):
"""Get the SHA of the market file using the user's GitHub token."""
token = get_user_github_token(user_id)
if not token:
raise ValueError("No GitHub token found for this user.")
url = f"https://api.github.com/repos/{REPO}/contents/{MARKET_FILE_PATH}"
headers = {
"Authorization": f"token {token}",
"Accept": "application/vnd.github+json"
}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()["sha"]
def get_pet_sha(user_id):
"""Get the SHA of the pet-prices file using the user's GitHub token."""
token = get_user_github_token(user_id)
if not token:
raise ValueError("No GitHub token found for this user.")
url = f"https://api.github.com/repos/{REPO}/contents/{PET_FILE_PATH}"
headers = {
"Authorization": f"token {token}",
"Accept": "application/vnd.github+json"
}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()["sha"]
def get_file_sha_blank():
"""Get the SHA of the file using the user's GitHub token."""
url = f"https://api.github.com/repos/{REPO}/contents/{FILE_PATH}"
headers = {
"Authorization": f"token {GITHUB_TOKEN}",
"Accept": "application/vnd.github+json"
}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json()["sha"]
def upload_to_github_blank(content, sha):
"""Upload content to GitHub using the user's GitHub token."""
url = f"https://api.github.com/repos/{REPO}/contents/{FILE_PATH}"