-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path7xbot.py
More file actions
executable file
·1954 lines (1600 loc) · 64.2 KB
/
7xbot.py
File metadata and controls
executable file
·1954 lines (1600 loc) · 64.2 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
#!/usr/bin/python3
import sys
import re
import asyncio
import base64
import json
import traceback
import time
import os
import requests
import random
import io
import traceback
import contextlib
import string
from datetime import datetime
from typing import Optional
from dotenv import load_dotenv
import discord
from discord.channel import TextChannel
from discord.ext import commands
from discord.ext.commands import MissingRequiredArgument, has_any_role
from datetime import datetime, timezone
load_dotenv()
# :3
bot_start_time = datetime.now()
def get_uptime():
delta = datetime.now() - bot_start_time
return str(delta)
def days_until_christmas():
today = datetime.now()
christmas = datetime(today.year, 12, 25)
if today > christmas:
christmas = datetime(today.year + 1, 12, 25)
delta = christmas - today
return delta.days
status_hold = False
temporary_status = None
temporary_status_time = None
ecancel = False
shutdown_in_progress = False
status_queue = []
new_status = f"{days_until_christmas()} Days until Christmas!"
status_hold = False
my_secret = os.getenv('BOT_KEY')
ND_API_KEY = os.getenv('NOTDIAMOND_API_KEY')
fallback_model = "gpt-3.5-turbo-1106"
glasgow_block = True
from g4f.client import Client
client = Client()
def get_build_id():
return "v1.9"
os.system('cls' if os.name == 'nt' else 'clear')
tips = [
"Did you know? Of course you didn't.", "Run 7/help for help",
"Hiya!", "Hello, world!", ":3", "Netflix", "You", "For 7/ commands",
]
intents = discord.Intents.default()
intents.message_content = True
class MyBot(commands.Bot):
async def setup_hook(self):
# Schedule the terminal REPL task after the bot is ready.
time.sleep(15)
asyncio.create_task(terminal_repl())
async def terminal_repl():
loop = asyncio.get_event_loop()
print("Terminal REPL started. Type your Python code below:")
while True:
# Read a line from the terminal without blocking the event loop.
code_str = await loop.run_in_executor(None, sys.stdin.readline)
code_str = code_str.strip()
if not code_str:
continue
try:
# Attempt to compile and evaluate as an expression.
code_obj = compile(code_str, "<stdin>", "eval")
result = eval(code_obj, globals())
if asyncio.iscoroutine(result):
result = await result
if result is not None:
print(result)
except SyntaxError:
# If eval fails (likely due to statements), try exec.
try:
code_obj = compile(code_str, "<stdin>", "exec")
with io.StringIO() as buffer:
with contextlib.redirect_stdout(buffer):
exec(code_obj, globals())
output = buffer.getvalue()
if not output:
# output = "Code executed without output."
continue
print(output)
except Exception:
print("Execution error:\n", traceback.format_exc())
except Exception:
print("Evaluation error:\n", traceback.format_exc())
bot = MyBot(command_prefix=commands.when_mentioned_or("7/"),
intents=intents,
case_insensitive=True,
help_command=None)
@bot.group(invoke_without_command=True)
async def beta(ctx, option: str = None):
if option is None:
await ctx.send("Please provide a valid option: tester, info")
elif option == "info":
await ctx.send(f"Build ID: {get_build_id()} | Uptime: {get_uptime()}")
elif option == "tester":
await ctx.invoke(bot.get_command('beta tester'))
@bot.group(name="tester", invoke_without_command=True, help="Beta tester management commands.")
@commands.is_owner()
async def beta_tester(ctx):
if ctx.invoked_subcommand is None:
await ctx.send("Valid subcommands are: add, remove, list")
@beta_tester.command(name="add")
async def beta_tester_add(ctx, member: discord.Member = None):
if member is None:
await ctx.send("Please specify a member to add as a beta tester.")
return
if role := discord.utils.get(ctx.guild.roles, name="7x Waitlist"):
await member.add_roles(role)
await ctx.send(f"Added {member.mention} as a beta tester.")
else:
await ctx.send("Role '7x Waitlist' not found.")
@beta_tester.command(name="remove")
async def beta_tester_remove(ctx, member: discord.Member = None):
if member is None:
await ctx.send("Please specify a member to remove from beta testers.")
return
role = discord.utils.get(ctx.guild.roles, name="7x Waitlist")
if role in member.roles:
await member.remove_roles(role)
await ctx.send(f"Removed {member.mention} from beta testers.")
else:
await ctx.send(f"{member.mention} is not a tester.")
@beta_tester.command(name="list")
async def beta_tester_list(ctx):
if role := discord.utils.get(ctx.guild.roles, name="7x Waitlist"):
testers = [member.mention for member in role.members]
await ctx.send("Beta Testers: " + ", ".join(testers))
else:
await ctx.send("No beta testers found.")
@bot.command(name="query-status")
@commands.has_permissions(manage_guild=True)
async def query_status(ctx, *, messages: str):
global status_queue
# Split the messages by quotes and filter out any empty strings
messages_list = [msg for msg in messages.split('"') if msg.strip()]
status_queue.extend(messages_list)
await ctx.send(f"Queued {len(messages_list)} statuses.")
@bot.command(name="glasgow-block")
async def ggb(ctx, state: bool):
global glasgow_block
if state in {True, False}:
glasgow_block = state
word = "Applied" if state else "Removed"
await ctx.send(f"Glasgow Block: {word}")
else:
ctx.send(f"""Error: Expected bool, recieved: "{state}" """)
# Create a persistent global environment.
# Including __builtins__ is important for exec to work correctly.
global_env = {
"__builtins__": __builtins__,
"bot": None,
"discord": discord,
"commands": commands,
"asyncio": asyncio,
}
@bot.command(name="eval")
@commands.is_owner()
async def _eval(ctx, *, code: str):
# Update the persistent environment with current context and bot.
global_env["bot"] = bot
global_env["ctx"] = ctx
# If the code is wrapped in a code block, remove those markers.
if code.startswith("```") and code.endswith("```"):
lines = code.splitlines()
code = "\n".join(lines[1:-1]) if len(lines) >= 3 else code[3:-3].strip()
try:
# First, try to compile as an expression.
compiled = compile(code, "<eval>", "eval")
result = eval(compiled, global_env)
if asyncio.iscoroutine(result):
result = await result
await ctx.send(f"Result: {result}")
except SyntaxError:
try:
compiled = compile(code, "<exec>", "exec")
with io.StringIO() as buffer:
with contextlib.redirect_stdout(buffer):
exec(compiled, global_env)
output = buffer.getvalue()
if not output:
output = "Code executed without output."
await ctx.send(f"Output:\n```py\n{output}\n```")
except Exception:
tb = traceback.format_exc()
await ctx.send(f"Error during exec:\n```py\n{tb}\n```")
except Exception:
tb = traceback.format_exc()
await ctx.send(f"Error during eval:\n```py\n{tb}\n```")
async def force_status(ctx, *, status: str):
global status_hold, temporary_status, temporary_status_time
if '-indf' in status:
status_hold = True
status = status.replace('-indf', '').strip()
else:
status_hold = False
await bot.change_presence(activity=discord.Activity(
type=discord.ActivityType.watching, name=status))
if not status_hold:
temporary_status = status
temporary_status_time = datetime.now()
await asyncio.sleep(10)
temporary_status = None
temporary_status_time = None
await ctx.send(f"Status changed to: {status}")
# ────────────────────────────────────────────────────────────────────────────────
# 7/repl – owner-only live Python REPL that streams its output in Discord
# ────────────────────────────────────────────────────────────────────────────────
import textwrap # add with the other imports
REPL_TIMEOUT = 15 * 60 # seconds of inactivity before the session auto-closes
repl_sessions: dict[int, asyncio.Task] = {} # channel-id → running task
@bot.command(name="repl",
help="Start an owner-only live Python REPL in this channel.",
usage="7/repl ← start | exit() / quit() to stop")
@commands.is_owner()
async def repl(ctx: commands.Context):
"""
Interactive, *unsandboxed* Python – each line you send is executed.
The bot edits one message so you get a scrolling terminal-style view.
Use `exit()` or `quit()` (or let it time-out) to leave.
"""
# If there’s already a session in this channel, ignore the new request.
if ctx.channel.id in repl_sessions:
await ctx.send("A REPL is already active in this channel.")
return
# Persistent namespace for this session only
env = {
"__builtins__": __builtins__,
"bot": bot,
"ctx": ctx,
"discord": discord,
"asyncio": asyncio,
# feel free to expose extras here (db, client, …)
}
banner = "# ‣ Python REPL started – type exit() or quit() to stop\n>>> "
log_lines: list[str] = [banner]
# The message we’ll keep editing so the log scrolls in place
term_msg = await ctx.send(f"```py\n{banner}```")
def fmt_log() -> str:
"""Return the current log chunk wrapped in a code-block, truncated to 2 000 chars."""
txt = "\n".join(log_lines)[-1950:] # keep breathing room for the ```py
return f"```py\n{txt}\n```"
# Helper to append & display new output
async def push(line: str):
log_lines.append(line)
payload = fmt_log()
# If the edited message would be too large, send a fresh one instead.
if len(payload) > 2000:
await ctx.send(payload)
log_lines.clear()
else:
await term_msg.edit(content=payload)
# Wait-loop lives in its own task so multiple channels can run REPLs concurrently
async def repl_loop():
try:
while True:
# wait for the owner’s next message in this channel
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
try:
user_msg = await bot.wait_for("message",
check=check,
timeout=REPL_TIMEOUT)
except asyncio.TimeoutError:
await push("\n# Session timed-out, REPL closed.")
break
src = user_msg.content.strip()
# Allow triple-back-tick blocks; strip fences if present
if src.startswith("```") and src.endswith("```"):
src = "\n".join(src.splitlines()[1:-1])
if src in {"exit()", "quit()", "exit", "quit"}:
await push("\n# REPL closed.")
break
# Echo the input to the log
await push(f">>> {src}")
# Capture stdout/stderr
with io.StringIO() as buf, contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf):
try:
try:
# try expression first, then statements
compiled = compile(src, "<repl>", "eval")
result = eval(compiled, env)
if asyncio.iscoroutine(result):
result = await result
except SyntaxError:
compiled = compile(src, "<repl>", "exec")
exec(compiled, env)
result = None
except Exception:
result = traceback.format_exc()
output = buf.getvalue()
# Prepare what to print back
lines = []
if output:
lines.append(output.rstrip())
if result is not None:
lines.append(repr(result))
if not lines:
lines.append("None")
await push("\n".join(lines))
finally:
# Clean-up so another session can be started later
repl_sessions.pop(ctx.channel.id, None)
# Store and start the task
repl_sessions[ctx.channel.id] = asyncio.create_task(repl_loop())
async def change_status_task():
global status_hold, temporary_status, temporary_status_time, status_queue
last_status = None
while True:
if temporary_status and (datetime.now() - temporary_status_time).seconds > 10:
temporary_status = None
if status_hold:
pass
elif temporary_status:
await bot.change_presence(activity=discord.Activity(
type=discord.ActivityType.watching, name=temporary_status))
elif status_queue:
next_status = status_queue.pop(0)
await bot.change_presence(activity=discord.Activity(
type=discord.ActivityType.watching, name=next_status))
else:
new_status = random.choice(tips)
while new_status == last_status:
new_status = random.choice(tips)
await bot.change_presence(activity=discord.Activity(
type=discord.ActivityType.watching, name=new_status))
last_status = new_status
await asyncio.sleep(10)
shop_items = {
'item1': {
'price': 100,
'description': 'Item 1 Description'
},
'item2': {
'price': 200,
'description': 'Item 2 Description'
},
# placeholder for later updates
}
@bot.command(name="echo")
async def echo(ctx, *args):
# Join the args into a single string
message = " ".join(args)
await ctx.send(message)
await ctx.message.delete()
@bot.command(name="shop")
async def shop(ctx):
embed = discord.Embed(title="7x Shop",
description="Available items to purchase with points:",
color=0x00ff00)
for item_id, details in shop_items.items():
embed.add_field(name=f"{item_id} - {details['price']} points",
value=details['description'],
inline=False)
await ctx.send(embed=embed)
@bot.command(
name="fillerspam",
aliases=["fs"],
help="Creates a channel and generates spam test messages. DEVS ONLY")
async def filler_spam(ctx):
new_channel = await ctx.guild.create_text_channel("test-http-channel")
for _ in range(10):
gibberish = ''.join(
random.choices(string.ascii_letters + string.digits, k=20))
await new_channel.send(gibberish)
await ctx.send(
f"Channel {new_channel.mention} created and filled with test messages.")
# strike roles in order
strike_roles = [
"Warning 1",
"Warning 2",
"Warning 3",
"Time out warning 1", # 10 minutes
"Time out warning 2", # 1 hour
"Time out warning 3", # 1 day
"Kick warning",
"Banned"
]
@bot.command(help="Warn a user and escalate their strike.")
@commands.has_permissions(manage_messages=True)
async def warn(ctx, member: discord.Member, *, reason: str = "No reason provided"):
guild = ctx.guild
current_role = next(
(role for role in member.roles if role.name in strike_roles), None
)
if current_role is None:
next_role = discord.utils.get(guild.roles, name="Warning 1")
else:
current_index = strike_roles.index(current_role.name)
next_role_name = strike_roles[min(current_index + 1, len(strike_roles) - 1)]
next_role = discord.utils.get(guild.roles, name=next_role_name)
if current_role:
await member.remove_roles(current_role)
await member.add_roles(next_role)
await ctx.send(f"{member.mention} has been warned and given the role: {next_role.name} for: {reason}")
if next_role.name == "Time out warning 1":
await member.timeout_for(minutes=10)
elif next_role.name == "Time out warning 2":
await member.timeout_for(hours=1)
elif next_role.name == "Time out warning 3":
await member.timeout_for(days=1)
elif next_role.name == "Kick warning":
await member.kick(reason=f"Accumulated strikes: {reason}")
elif next_role.name == "Banned":
await member.ban(reason=f"Accumulated strikes: {reason}")
await ctx.guild.audit_logs(reason=f"Warned {member.display_name}: {reason}")
@bot.command(help="Reverse the last warning of a user.")
@commands.has_permissions(manage_messages=True)
async def pardon(ctx, member: discord.Member):
guild = ctx.guild
current_role = next(
(role for role in member.roles if role.name in strike_roles), None
)
if current_role is None:
await ctx.send(f"{member.mention} has no warnings to pardon.")
return
current_index = strike_roles.index(current_role.name)
if current_index == 0:
await member.remove_roles(current_role)
await ctx.send(f"{member.mention} has been fully pardoned. They now have no warning roles.")
else:
previous_role_name = strike_roles[current_index - 1]
previous_role = discord.utils.get(guild.roles, name=previous_role_name)
await member.remove_roles(current_role)
if previous_role:
await member.add_roles(previous_role)
await ctx.send(f"{member.mention} has been pardoned and demoted to {previous_role.name}.")
else:
await ctx.send(f"{member.mention} has been pardoned. They now have no warning roles.")
@bot.command(help="Initiate or deactivate lockdown mode.")
@commands.has_permissions(administrator=True)
async def lockdown(ctx, action: str):
guild = ctx.guild
if action.lower() == "initiate":
for channel in guild.text_channels:
await channel.edit(slowmode_delay=10)
invites = await guild.invites()
for invite in invites:
await invite.delete()
await ctx.send("Lockdown initiated. All invites have been paused, and slow mode is set to 10 seconds for all channels.")
elif action.lower() == "deactivate":
for channel in guild.text_channels:
await channel.edit(slowmode_delay=0)
await ctx.send("Lockdown deactivated. Channels are back to normal.")
else:
await ctx.send("Invalid action. Use 'initiate' or 'deactivate'.")
@bot.command(name="spamping",
help="Spam pings a user a specfied amount.",
usage="7/spam-ping <user> <amount>")
@has_any_role("mod", "7x Waitlist")
async def spamping(ctx,
member: Optional[discord.Member] = None,
*,
ping_count: Optional[int] = None):
await ctx.message.delete()
if member is None:
await ctx.send("Please specify a user to ping.")
return
if ping_count is None:
ping_count = 5
ping_count = min(ping_count, 25)
for i in range(ping_count):
if ecancel is False:
await ctx.send(f"{member.mention} | {i+1}/{ping_count} Pings left")
await asyncio.sleep(1)
elif ecancel:
await ctx.send("Spam pings cancelled.")
return
@bot.command()
async def cancel(ctx, ecancel: bool = False):
ecancel = not ecancel
await ctx.send(f"ecancel set to {ecancel}")
@bot.command(name="man")
async def man_command(ctx, *, arg: Optional[str] = None):
if arg is None or arg.strip() == "":
await ctx.send("Please provide a command name to get the manual entry.")
elif arg.strip() in ['--list', '--l']:
command_names = [f"`{command.name}`" for command in bot.commands]
command_list = ', '.join(command_names)
await ctx.send(f"Available commands:\n{command_list}")
elif command := bot.get_command(arg):
usage_text = command.usage
if not usage_text or usage_text == "":
usage_text = f"No detailed usage information available for `{command.name}`."
embed = discord.Embed(
title=f"Manual Entry for `{command.name}`",
description=usage_text,
color=0x00ff00
)
await ctx.send(embed=embed)
else:
await ctx.send(f"No command named '{arg}' found.")
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, MissingRequiredArgument):
command = ctx.command
await ctx.send(f"""
Missing required argument for {command.name}: {error.param.name}. Usage: {command.usage}
""")
tc_explanation = """
***Info:***
This will make 7x send a "Success" message to check
if 7x can send a message in that channel.
**Usage:**
`7/tc {end}`
**Example:**
`7/tc`
***Tip:***
- Don't try to add any arguments, none, except help, are supported.
"""
@bot.command(name='tc',
ignore_extra=False,
help="This command tests if 7x can send a message in a channel.",
usage="7/tc")
async def tc_command(ctx, *args):
if 'help' in args or args:
embed = discord.Embed(title="TC Command Help",
description=tc_explanation,
color=0x00ff00)
await ctx.send(embed=embed)
else:
await ctx.send("Success")
@bot.command()
async def derhop(ctx, *args):
await ctx.send("Derhop is a nerd or something idk")
@bot.command()
@commands.is_owner()
async def shutdown(ctx, *args):
global shutdown_in_progress
if '-e' in args:
await ctx.send("Emergency Shutdown Bypass: Activated | Force Quiting All Running Services...")
await bot.close()
if shutdown_in_progress:
shutdown_in_progress = False
await ctx.send("Shutdown sequence halted.")
return
shutdown_in_progress = True
countdown_message = await ctx.send(
"! - Shutdown Sequence Initiated: (--s) Run 7/shutdown again to cancel.")
for i in range(10, 0, -1):
if not shutdown_in_progress:
return
await countdown_message.edit(
content=
f"! - Shutdown Sequence Initiated: ({i}s) Run 7/shutdown again to cancel."
)
await asyncio.sleep(1)
if shutdown_in_progress:
await countdown_message.edit(
content="! - Shutdown Sequence Initiated: (0s)")
await asyncio.sleep(0.5)
await countdown_message.edit(
content="! - Shutdown Sequence Finished - 7x Shut Down.")
await bot.close()
shutdown_in_progress = False
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
print(f'With ID: {bot.user.id}')
print('------')
bot.loop.create_task(change_status_task())
channel = bot.get_channel(0)
if isinstance(channel, TextChannel):
await channel.send("7x - Now listening for commands!")
# -------------------------
# Database Load/Save
# -------------------------
def load_db(filename="database.json"):
"""
Loads the JSON database from disk, returns an empty dict if it doesn't exist.
"""
try:
if os.path.exists(filename):
with open(filename, 'r') as f:
return json.load(f)
return {}
except FileNotFoundError:
with open(filename, 'w') as f:
return {}
def save_db(data, filename="database.json"):
"""
Saves the provided dict to the JSON database with indentation for readability.
"""
with open(filename, 'w') as f:
json.dump(data, f, indent=4)
db = load_db()
def save_message(guild_id, user_id, message):
"""
Appends a message dict to the conversation history for (guild_id, user_id).
"""
key = f"{guild_id}-{user_id}"
messages = db.get(key, [])
messages.append(message)
db[key] = messages
save_db(db)
def get_messages(guild_id, user_id):
"""
Retrieves the conversation history for (guild_id, user_id).
"""
key = f"{guild_id}-{user_id}"
return db.get(key, [])
# List of global variable names to exclude from debug output.
SAFETY_BLACKLIST = ['my_secret', 'ND_API_KEY']
@bot.command()
async def debug(ctx, *args):
all_globals = globals()
debug_info = []
for name, value in all_globals.items():
# Skip private/system variables.
if name.startswith("__"):
continue
# Skip any variable that’s in our blacklist.
if name in SAFETY_BLACKLIST:
continue
if args and name not in args:
continue
debug_info.append(f"{name}: {value}")
output = "\n".join(debug_info)
# Check if the output is too long for a message.
if len(output) > 1900:
with io.StringIO(output) as file:
await ctx.send(file=discord.File(file, filename="debug.txt"))
else:
await ctx.send(f"```python\n{output}\n```")
# -------------------------
# AI Explanation / Help Text
# -------------------------
ai_explanation = (
"**Info:**\n"
"Interacts with an AI (model-specifiable) to simulate conversation or answer queries.\n"
"- Normal conversation maintains context for a more coherent interaction.\n"
"- Optional flag `-s` for a standalone query without context.\n"
"\n"
"**Usage:**\n"
"`7/ai \"<message>\" [-s] [-search] [-model <model>]`\n"
"\n"
"**Examples:**\n"
"`7/ai \"What is the capital of France?\"` (Contextual conversation)\n"
"`7/ai \"What is the capital of France?\" -s` (Standalone, without conversation history)\n"
"`7/ai \"What is the capital of France?\" -model gpt-4o` (Use the GPT-4o model)\n"
"`7/ai \"What is the capital of France?\" -search` (Enable web search if supported)\n"
"`7/ai \"What is the capital of France?\" -s -model gpt-4o -search` (Combine flags)\n"
"`7/ai models` (Displays a list of available models.)\n"
"\n"
"**Tips:**\n"
"- Use `-s` for quick queries when you don't need conversation context.\n"
"- The `-search` flag enables web search for GPT-based models, helping get more accurate info.\n"
"- The AI's response quality may vary based on the selected model.\n"
)
# A consolidated list of available models (remove duplicates)
available_models = [
"gemini-1.5-pro",
"llama-3.3-70b",
"qwen-2.5-coder-32b",
"hermes-3",
"llama-3.2-90b",
"blackboxai",
"gpt-4",
"gpt-4o",
"gemini-1.5-flash",
"claude-3.5-sonnet",
"blackboxai-pro",
"llama-3.1-8b",
"llama-3.1-70b",
"llama-3-1-405b",
"mixtral-7b",
"deepseek-chat",
"dbrx-instruct",
"qwq-32b",
"hermes-2-dpo",
"deepseek-r1",
"gpt-4o-mini",
"claude-3-haiku",
"mixtral-8x7b",
"wizardlm-2-8x22b",
"wizardlm-2-7b",
"qwen-2.5-72b",
"nemotron-70b"
]
available_models = sorted(set(available_models))
# Models that support web_search
allowed_search_models = ["gpt-4", "gpt-4o", "gpt-4o-mini"]
# -------------------------
# Utility: Parsing Flags
# -------------------------
def parse_flags_and_content(raw_message: str):
"""
Parses the user's raw message for flags and quoted content.
Returns: (message_content, standalone, search_enabled, selected_model).
"""
# Quick check for 'help' or 'models' before doing complex parse
# (If the user literally typed 'help' or 'models' without quotes.)
command_lower = raw_message.strip().lower()
if command_lower == "help":
return ("HELP_COMMAND", False, False, None)
if command_lower == "models":
return ("MODELS_LIST", False, False, None)
# Standalone mode
standalone = "-s" in raw_message
# Web search flag
search_enabled = "-search" in raw_message
# Default model
selected_model = "gpt-4o"
# Remove the flags from the raw string; do it carefully so we don't kill partial text
# We'll handle the -model part separately.
def remove_flag(text, flag):
return re.sub(rf"\s*{flag}\b", "", text)
flags = ["-s", "-search"]
for flag in flags:
raw_message = remove_flag(raw_message, flag)
# Check for "-model <model>"
model_match = re.search(r"-model\s+(\S+)", raw_message)
if model_match:
model_candidate = model_match[1]
# Remove it from the raw message
raw_message = re.sub(rf"-model\s+{model_candidate}", "", raw_message).strip()
selected_model = model_candidate
# Now parse the quoted string
message_content_pattern = r'"([^"]+)"'
match = re.search(message_content_pattern, raw_message)
message_content = match[1].strip() if match else ""
return (message_content, standalone, search_enabled, selected_model)
# -------------------------
# Context Truncation (Placeholder)
# -------------------------
def truncate_conversation(conversation, model="gpt-4o", max_tokens=4000):
"""
If you'd like to implement token-based truncation, you can place your logic here
using tiktoken or a similar library. For now, it just returns the conversation unmodified.
"""
# Example placeholder:
# total_tokens = count_tokens_in_messages(conversation, model)
# while total_tokens > max_tokens and len(conversation) > 2:
# conversation.pop(0) # remove oldest message
# total_tokens = count_tokens_in_messages(conversation, model)
return conversation
# -------------------------
# Response Splitting
# -------------------------
def split_into_chunks(text, chunk_size=2000):
"""
Splits a long string into chunks for Discord messages.
"""
return [text[i : i + chunk_size] for i in range(0, len(text), chunk_size)]
# -------------------------
# The Command
# -------------------------
@bot.command(name="ai", usage="7/ai <message> [-s] [-search] [-model <model>]", aliases=["ai_bot"])
async def ai_command(ctx, *, message: str = None):
global glasgow_block
if not message or not message.strip():
await ctx.send("✦ | Please provide a message. For help, type: `7/ai help`.")
return
# Parse the flags and content
message_content, standalone, search_enabled, selected_model = parse_flags_and_content(message)
# If user asked for help (no quotes or "help")
if message_content == "HELP_COMMAND":
await send_help_embed(ctx)
return
# If user asked for model list
if message_content == "MODELS_LIST":
await send_models_list(ctx)
return
# If no quoted text found and it's not help/models
if not message_content:
await ctx.send("Please provide a message within quotes. For help, type: `7/ai help`.")
return
# Validate model
if selected_model not in available_models:
model_list_str = ", ".join(available_models) if available_models else "No models currently available."
await ctx.send(f"Invalid model: **{selected_model}**.\nAvailable models: {model_list_str}")
return
# Validate -search usage for GPT models only
if search_enabled and selected_model not in allowed_search_models:
await ctx.send(f"⚠️ The **{selected_model}** model does not support web search.")
# If you want to force it off but still continue:
if glasgow_block:
search_enabled = False
return
# Retrieve conversation or create a new one
user_id = str(ctx.author.id)
guild_id = str(ctx.guild.id)
if standalone:
conversation = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": message_content}
]
else:
existing_convo = get_messages(guild_id, user_id)
# Insert system message right before user's new query
conversation = existing_convo + [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": message_content}
]
# Truncate conversation if needed (placeholder)
conversation = truncate_conversation(conversation, model=selected_model, max_tokens=4000)
# Show a "typing" indicator while generating the response
async with ctx.typing():
try:
print(f"AI Command: {message_content}")
print(f"Standalone: {standalone}")
print(f"Search Enabled: {search_enabled}")
print(f"Selected Model: {selected_model}")
# GPT4Free call (adjust to your actual library usage)
response = client.chat.completions.create(
model=selected_model,
messages=conversation,
web_search=search_enabled
)
ai_reply = response.choices[0].message.content
# Split the reply if it's too long for a single Discord message
parts = split_into_chunks(ai_reply, 2000)
for part in parts:
await ctx.send(part)
# If not standalone, save user/assistant messages to DB
if not standalone:
save_message(guild_id, user_id, {"role": "user", "content": message_content})
save_message(guild_id, user_id, {"role": "assistant", "content": ai_reply})
except Exception as e:
await ctx.send(f"An error occurred: {str(e)}")
# -------------------------
# Sending Help Embed
# -------------------------
async def send_help_embed(ctx):
"""
Sends a help embed with usage details, flag descriptions, and examples.
Splits it up if needed.
"""
embed = discord.Embed(title="AI Command Help", color=0x00ff00)
embed.add_field(name="Usage", value='`7/ai "<message>" [-s] [-search] [-model <model>]`', inline=False)
embed.add_field(
name="Flags",
value=(