-
Notifications
You must be signed in to change notification settings - Fork 0
/
7xbot.py
1378 lines (1072 loc) · 43.3 KB
/
7xbot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import base64
import json
import traceback
import time
import os
import requests
import random
import string
from datetime import datetime
from typing import Optional
from dotenv import load_dotenv
import discord
from discord.channel import TextChannel
import openai
from discord.ext import commands
from discord.ext.commands import MissingRequiredArgument, has_any_role
from notdiamond import NotDiamond
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')
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
ND_API_KEY = os.getenv('NOTDIAMOND_API_KEY')
openai.api_key = OPENAI_API_KEY
fallback_model = "gpt-3.5-turbo-1106"
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", "I'm alive!", "You", "For 7/ commands",
]
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(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
role = discord.utils.get(ctx.guild.roles, name="7x Waitlist")
if role:
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):
role = discord.utils.get(ctx.guild.roles, name="7x Waitlist")
if role:
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="force-status")
@commands.has_permissions(manage_guild=True)
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}")
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:
await asyncio.sleep(10)
elif temporary_status:
await bot.change_presence(activity=discord.Activity(
type=discord.ActivityType.watching, name=temporary_status))
await asyncio.sleep(10)
elif status_queue:
next_status = status_queue.pop(0)
await bot.change_presence(activity=discord.Activity(
type=discord.ActivityType.watching, name=next_status))
await asyncio.sleep(10)
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="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 = None
for role in member.roles:
if role.name in strike_roles:
current_role = role
break
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 = None
for role in member.roles:
if role.name in strike_roles:
current_role = role
break
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
if ping_count > 25:
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):
if ecancel is True:
ecancel = False
elif ecancel is False:
ecancel = True
else:
await ctx.send("Invalid option.")
return
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}")
else:
command = bot.get_command(arg)
if command:
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 len(args) > 0:
embed = discord.Embed(title="TC Command Help",
description=tc_explanation,
color=0x00ff00)
await ctx.send(embed=embed)
else:
await ctx.send("Success")
@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!")
def encode_image(image_path):
with open(image_path, "rb") as image_file:
print(f"Encoding image {image_path}")
return base64.b64encode(image_file.read()).decode("utf-8")
def load_db(filename="database.json"):
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"):
with open(filename, 'w') as f:
json.dump(data, f, indent=4)
db = load_db()
def save_message(guild_id, user_id, message):
key = f"{guild_id}-{user_id}"
messages = db.get(key, [])
messages.append(message)
db[key] = messages
print(messages)
def get_messages(guild_id, user_id):
key = f"{guild_id}-{user_id}"
print(f"Key: {key}")
return db.get(key, [])
client = NotDiamond()
def encode_image(image_path):
with open(image_path, "rb") as image_file:
print(f"Encoding image {image_path}")
return base64.b64encode(image_file.read()).decode("utf-8")
def load_db(filename="database.json"):
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"):
with open(filename, 'w') as f:
json.dump(data, f, indent=4)
db = load_db()
def save_message(guild_id, user_id, message):
key = f"{guild_id}-{user_id}"
messages = db.get(key, [])
messages.append(message)
db[key] = messages
save_db(db)
print(messages)
def get_messages(guild_id, user_id):
key = f"{guild_id}-{user_id}"
print(f"Key: {key}")
return db.get(key, [])
def check_points(user_id):
print("Checking points...")
return db.get(f"points_{user_id}", 0)
def set_points(user_id, points):
db[f"points_{user_id}"] = points
save_db(db)
print(f"Set points for user {user_id} to {points}")
def update_points(user_id, points):
current_points = check_points(user_id)
new_points = max(current_points + points, 0)
set_points(user_id, new_points)
print(f"Updated points for user {user_id} to {new_points}")
@bot.group(invoke_without_command=True)
async def points(ctx):
await ctx.send("Usage: `7/points <add/remove/query> <@user> [amount]`")
@points.command()
@commands.has_permissions(manage_guild=True)
async def add(ctx, member: discord.Member, amount: int):
user_id = str(member.id)
update_points(user_id, amount)
await ctx.send(f"Added {amount} points to {member.mention}. They now have {check_points(user_id)} points.")
@points.command()
@commands.has_permissions(manage_guild=True)
async def remove(ctx, member: discord.Member, amount: int):
user_id = str(member.id)
update_points(user_id, -amount)
await ctx.send(f"Removed {amount} points from {member.mention}. They now have {check_points(user_id)} points.")
@points.command()
async def query(ctx, member: Optional[discord.Member] = None):
if member is None:
member = ctx.author
user_id = str(member.id)
points = check_points(user_id)
await ctx.send(f"{member.mention} has {points} points.")
def check_points(user_id):
print("Checking points...")
return db.get(f"points_{user_id}", 0)
def update_points(user_id, points):
current_points = check_points(user_id)
new_points = max(current_points + points, 0)
db[f"points_{user_id}"] = new_points
save_db(db)
print("Updated points for user", user_id, "to", new_points)
async def process_query(messages, image_path=None):
if image_path:
encoded_image = encode_image(image_path)
messages.append({"role": "system", "content": f"data:image/jpeg;base64,{encoded_image}"})
try:
strong_model='openai/gpt-4o'
weak_model='openai/gpt-4o-mini'
result, session_id, provider = client.chat.completions.create(
messages=messages,
model=['openai/gpt-4o', 'openai/gpt-4o-mini', 'openai/gpt-3.5-turbo'],
tradeoff="cost"
)
response_text = result.content
model_used = provider.model
print("Not Diamond session ID: ", session_id)
print("LLM called: ", model_used)
print("LLM output: ", response_text)
except Exception as e:
response_text = "An error occurred while processing your request."
model_used = "unknown"
print(f"Error in NotDiamond client: {e}")
return response_text, model_used
ai_explanation = """
***Info:***
Interacts with an advanced AI to simulate conversation or answer queries. Costs points based on the complexity and model used.
Your queries will be processed and sent to an appropriate model selected by NotDiamond.
If an image is sent, it will automatically use an appropriate model that supports image inputs.
- Normal conversation maintains context for a more coherent interaction.
- Optional flag `-s` for a standalone query without context, which costs fewer points.
**Usage:**
`7/ai "<message>"` (Engages in a contextual conversation. Costs more points based on the AI model used.)
`7/ai "<message>" -s` (Engages in a standalone query without considering conversation history. Costs fewer points.)
**Examples:**
`7/ai "What is the capital of France?"` (Contextual conversation)
`7/ai "What is the capital of France?" -s` (Standalone query)
***Cost:***
- **openai/gpt-4o-mini**: 10 points per use.
- **openai/gpt-4o**: 20 points per use.
- **Discount for '-s' flag**: 50% off the above prices.
***Earning Points:***
- You earn **0.0625 points** for each message you send in the server.
***Tips:***
- Use the `-s` flag for quick queries when you don't need the context of a conversation. It saves your points.
- Ensure you have enough points before using the command. You can earn points by participating in the server and using other features.
- The AI's response quality and understanding may vary based on the auto-selected model by the complexity of your query.
"""
@bot.command(name="ai", usage="7/ai <message> <optional flag: -s>", aliases=["ai_bot"], help="Interacts with an advanced AI to simulate conversation or answer queries.")
async def ai_command(ctx, *, message: str = None):
if message is None or message.strip() == "":
await ctx.send("Please provide a message. For help, type: `7/ai help`")
return
print(message)
user_id = str(ctx.author.id)
guild_id = str(ctx.guild.id)
standalone = '-s' in message
message_content = message.replace('-s', '').strip()
if message_content.lower() == "help":
chunks = [ai_explanation[i:i + 1024] for i in range(0, len(ai_explanation), 1024)]
for i, chunk in enumerate(chunks):
embed = discord.Embed(
title=f"AI Command Help (Part {i+1}/{len(chunks)})",
description=chunk,
color=0x00ff00
)
await ctx.send(embed=embed)
return
model_costs = {
'openai/gpt-3.5-turbo': 1, # lowest-cost model
'openai/gpt-4o-mini': 10, # eco-cost model
'openai/gpt-4o': 20 # highest-cost model
}
# Estimate the maximum possible cost
max_cost = max(model_costs.values())
if standalone:
max_cost = int(max_cost * 0.5)
user_points = check_points(user_id)
if user_points >= max_cost:
if standalone:
messages = [{"role": "user", "content": message_content}]
else:
conversation = get_messages(guild_id, user_id)
messages = conversation + [{"role": "user", "content": message_content}]
response, model_used = await process_query(messages)
cost = model_costs.get(model_used, 10)
if standalone:
cost = int(cost * 0.5)
update_points(user_id, -cost)
await ctx.send(response)
if not standalone:
save_message(guild_id, user_id, {"role": "user", "content": message_content})
save_message(guild_id, user_id, {"role": "assistant", "content": response})
else:
await ctx.send(
f"You don't have enough points for this operation. It costs up to {max_cost} points, but you have {user_points}."
)
@bot.event
async def on_message(message):
if message.author.bot:
return
user_id = str(message.author.id)
print(f"User ID: {user_id}")
print(f"Current points: {check_points(user_id)}")
update_points(user_id, 0.0625)
print(f"Updated points: {check_points(user_id)}")
channel_id = message.channel.id
if channel_id in slowmode_settings and slowmode_settings[channel_id]["active"]:
settings = slowmode_settings[channel_id]
settings["message_count"] += 1
elapsed_time = time.time() - settings["last_check"]
if elapsed_time >= 30:
if settings["message_count"] > settings["mpm"]:
await message.channel.edit(slowmode_delay=settings["slowmode_amount"])
await message.channel.send(
f"Slow mode activated: {settings['slowmode_amount']} second slowmode due to high activity."
)
settings["message_count"] = 0
settings["last_check"] = time.time()
await bot.process_commands(message)
http_explanation = """
***Info:***
Deletes messages or entire channels based on flags.
- `-rm`: Deletes the channel.
- `-rmc`: Deletes and recreates the channel.
- `-trf`: Transfers messages from this channel to another.
- `-rmc.trf`: Deletes, clones, and transfers messages to a new channel.
- `-num`: Deletes or transfers a specified number of recent messages.
**Usage:**
`7/http -rm` (Deletes the channel)
`7/http -rmc` (Deletes and recreates the channel)
`7/http -trf <#target-channel>` (Transfers all messages)
`7/http -trf.num <#target-channel> <number>` (Transfers specified number of messages)
`7/http -rmc.trf <#target-channel>` (Deletes and transfers all messages to new channel)
**Examples:**
`7/http -rm`
`7/http -rmc`
`7/http -trf.num #new-channel 10`
***Tips:***
- Use `-rm` with caution; it can't be undone.
- `-trf` is useful for archiving messages from one channel to another.
- The `-num` flag can be used with both `-trf` and `-rmc`.
"""
@bot.command(help="Deletes messages or entire channels, or transfers messages.",
usage="7/http -rm / -rmc / -trf / -num")
@commands.is_owner()
async def http(ctx, *args):
if not args:
await ctx.send("Usage: `7/http help` for detailed info.")
return
channel = ctx.channel
if "help" in args:
embed = discord.Embed(title="HTTP Command",
description=http_explanation,
color=0x00ff00)
await ctx.send(embed=embed)
return
if "-rm" in args or "-rmc" in args or "-rmc.trf" in args:
channel_category = channel.category
channel_name = channel.name
channel_position = channel.position
channel_topic = channel.topic
target_channel = None
if "-rmc.trf" in args or "-trf" in args:
try:
target_channel = ctx.message.channel_mentions[0]
except IndexError:
await ctx.send("Please mention a valid target channel for message transfer.")
return
if "-trf" in args or "-rmc.trf" in args:
await transfer_messages(ctx, channel, target_channel, args)
if "-rm" in args or "-rmc" in args or "-rmc.trf" in args:
await channel.delete(reason="7/http command with -rm, -rmc or -rmc.trf flag")
if "-rmc" in args or "-rmc.trf" in args:
await channel_category.create_text_channel(
name=channel_name,
topic=channel_topic,
position=channel_position,
reason="7/http command with -rmc or -rmc.trf flag")
return
if "-all" in args:
countdown_message = await ctx.send(
"! - Server Purge Sequence Initiated: (--s) Run 7/shutdown -e again to cancel.")
for i in range(5, 0, -1):
await countdown_message.edit(
content=f"! - Server Purge Sequence Initiated: ({i}s) Run 7/shutdown -e again to cancel.")
await asyncio.sleep(1)
await countdown_message.edit(content="! - Delete All Sequence Initiated: (0s)")
await asyncio.sleep(0.5)
await countdown_message.edit(content="! - Delete All Sequence Finished - Deleting all channels, roles, and bans members.")
for channel in ctx.guild.channels:
try:
await channel.delete(reason="7/http command with -all flag")
except Exception as e:
await ctx.send(f"Failed to delete {channel.name}: {e}")
for role in ctx.guild.roles:
try:
await role.delete(reason="7/http command with -all flag")
except Exception as e:
await ctx.send(f"Failed to delete role {role.name}: {e}")
for member in ctx.guild.members:
try:
if member != ctx.guild.owner and ctx.me.top_role > member.top_role:
await member.ban(reason="7/http command with -all flag")
except Exception as e:
await ctx.send(f"Failed to ban {member.name}: {e}")
return
if "-num" in args or "-trf.num" in args:
try:
num_index = args.index("-num") + 1 if "-num" in args else args.index("-trf.num") + 2
num_messages = int(args[num_index])
target_channel = ctx.message.channel_mentions[0] if "-trf.num" in args else None
if "-trf.num" in args:
await transfer_messages(ctx, channel, target_channel, args, num_messages)
else:
await ctx.channel.purge(limit=num_messages + 1)
except (ValueError, IndexError):
await ctx.send("Invalid usage, please specify a valid number of messages.")
return
@bot.command()
@commands.is_owner()
async def test_fetch(ctx, source: discord.TextChannel, limit: int = 2):
try:
if not source.permissions_for(ctx.me).read_message_history:
await ctx.send("I don't have permission to read the message history.")
return
if not source.permissions_for(ctx.me).read_messages:
await ctx.send("I don't have permission to read messages in the source channel.")
return
await ctx.send(f"Attempting to fetch {limit} messages from {source.mention}...")
print("Fetching messages...")
messages = []
async for message in source.history(limit=limit):
messages.append(message)
if not messages:
await ctx.send("No messages were fetched.")
return
for message in messages:
await ctx.send(f"Message from {message.author}: {message.content}")
except asyncio.TimeoutError:
await ctx.send("Fetching messages took too long and timed out.")
except Exception as e:
await ctx.send(f"An error occurred: {e}")
@bot.command()
@commands.is_owner()
async def test_transfer(ctx, source: discord.TextChannel, target: discord.TextChannel, amount: int):
if not source.permissions_for(ctx.me).read_message_history:
await ctx.send("I don't have permission to read message history in the source channel.")
return
if not target.permissions_for(ctx.me).send_messages:
await ctx.send("I don't have permission to send messages in the target channel.")
return
await ctx.send(f"Moving {amount} messages...")
await transfer_messages(ctx, source, target, amount)
async def transfer_messages(ctx, source_channel: discord.TextChannel, target_channel: discord.TextChannel, limit=None):
print("Fetching messages from the source channel")
messages = []
async for message in source_channel.history(limit=limit):
messages.append(message)
if not messages:
await ctx.send("No messages found in the source channel.")
return
print("Fetched messages successfully")
messages.reverse()
for message in messages:
print(message.content)
try:
print("Skip system messages")
if message.type != discord.MessageType.default:
continue
print("Create a webhook with the original user's name and avatar")
webhook = await target_channel.create_webhook(name=f"{message.author.display_name} Webhook")
await webhook.send(content=message.content,
username=message.author.display_name,
avatar_url=message.author.avatar.url if message.author.avatar else None)
print("Delete the webhook after sending the message")
await webhook.delete()
except Exception as e:
await ctx.send(f"Error transferring message from {message.author}: {e}")
await ctx.send(f"Messages successfully transferred from {source_channel.mention} to {target_channel.mention}!")
@bot.command(help="Logs deleted messages for moderation purposes.",
usage="7/logger <activation length (-indf or -num)>")
@commands.has_permissions(manage_guild=True)
async def logger(ctx, activation_length: str):
logging_enabled = False
log_filename = f"{ctx.guild.name}_deleted_logs.txt"
with open(log_filename, "a") as log_file:
if activation_length.startswith("-indf"):
logging_enabled = True
print("Logger activated indefinitely.")
elif activation_length.startswith("-num"):
try:
minutes = int(activation_length[4:])
logging_enabled = True
print(f"Logger activated for {minutes} minutes.")
await asyncio.sleep(minutes * 60)
logging_enabled = False
print("Logging stopped after the time limit.")
except ValueError:
await ctx.send("Invalid logging time. Please enter a valid number.")
@bot.event
async def on_message_delete(message):
if logging_enabled:
try: