-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathServerBot.py
More file actions
executable file
·2390 lines (2044 loc) · 84.1 KB
/
Copy pathServerBot.py
File metadata and controls
executable file
·2390 lines (2044 loc) · 84.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 subprocess
import os
import sys
import datetime
import sqlite3
# Bot Version
ver = "1.12.0"
# Bot Name
displayname = "ServerBot"
# Name of service in systemd; change if needed, WITHOUT .service file extension
servicename = "ServerBot"
#Directory
maindir = os.path.dirname(os.path.abspath(__file__))
SBbytes = os.path.getsize(f'{maindir}/ServerBot.py')
DB_PATH = f'{maindir}/Files/serverbot.db' # Database path
#Directory for music files; If you set ForceMediaDir to True, bot will be able to use local sounds only from this dir.
medialib = f'{maindir}/Media'
#List of modules/cogs you want to load at start; cogs from subdirectories (like 'modules/custom') you have to type like 'subdirName.cogName' - WITHOUT .py
#If LoadAllModules is True, this list will nothing do; bot will load every cog from 'modules' directory (not from subdirs!)
#If you use cogs from 'modules' directory or subdirectories and you want to load them all on start, type here all your modules and set LAM to False
loadList = [] # ['cog1', 'custom.cog2'] <- example; custom is the name of a directory inside 'modules' dir
# .env file template - if .env not exists, bot will automatically create a new one
# Do not type values here!
def create_env():
try:
with open(f'{maindir}/.env', 'w', encoding='utf-8') as env:
env.write(f"""#ServerBot v{ver} config file
TOKEN=''
admin_usr = ['']
custom_prefix = ''
addBot = 'inviteLink'
#AI
AI_token = ''
AI_model = 'gemini-2.5-flash'
instructions = ['Always answer in users language','Be precise and truthseeking','Do not answer to illegal, harmful, sexual or violent content']
#Music
JoinLeaveSounds = True
ForceMediaDir = False
#Command_dscserv
dscserv_link = 'https://discord.gg/UMtYGAx5ac'
#Modules
LoadAllModules = False
#ExtendedErrorMessages
extendedErrMess = False
#Service_module
service_list = ','""")
except Exception as err:
print(f"Error occurred while creating .env file.\nPossible cause: {err}")
#Check flags
if '--help' in sys.argv:
print(f"""ServerBot v{ver} made by Kamile320\n\n
Project: https://github.com/kamile320/serverbot\n
--help Shows this message\n
--ignore-pip Doesn't abort bot startup if an error occur
while loading pip libraries\n
--version Shows version information\n
--reset-env Removes .env file and creates a new one
with default values\n
""")
exit()
if '--version' in sys.argv:
print(f"ServerBot v{ver}")
exit()
if '--reset-env' in sys.argv:
print("Removing .env file...")
if os.path.exists(f'{maindir}/.env'):
os.remove(f'{maindir}/.env')
print("Removed .env file.\nCreating new one...")
create_env()
print("Created .env file.\nYou can now fill it with proper values.")
else:
print(".env file not found.\nCreating new one...")
create_env()
print("Created .env file.\nYou can now fill it with proper values.")
exit()
#Automatic .env creation
if os.path.exists(f'{maindir}/.env') == False:
create_env()
#Loading PIP Libraries
def os_selector():
print(f"====ServerBot v{ver} Recovery Menu====")
print("""Select Method:
1 - Linux
2 - Windows
3 - Setup.sh
4 - Exit
""")
sel = int(input('>>> '))
if sel == 1:
subprocess.run(['bash', 'Files/setup/setuplib.sh'])
elif sel == 2:
subprocess.run(['setup.bat'], shell=True)
elif sel == 3:
subprocess.run(['bash', 'setup.sh'])
elif sel == 4:
exit()
else:
print('Failed to run Script. Aborting Install...')
exit()
try:
import discord
from discord.ext import commands
from discord import FFmpegPCMAudio
from discord import app_commands
from dotenv import load_dotenv
import asyncio
import psutil
import requests
import random
import shutil
import pyfiglet
import platform
import yt_dlp as youtube_dl
except Exception as exc:
if '--ignore-pip' in sys.argv:
print(f"Error while importing libraries: {exc}\nIgnoring.. Expect unstable experience.")
else:
print(f"Error while importing libraries. Trying to install it and update pip3\nException: {exc}\n")
os_selector()
exit()
#Baner
banner = pyfiglet.figlet_format(displayname)
bluescreenface = pyfiglet.figlet_format(": (")
print(banner)
#Loading .env
try:
load_dotenv(f"{maindir}/.env")
############# token/intents/etc ################
TOKEN = os.getenv('TOKEN') or ''
prefix = os.getenv('custom_prefix') or '.'
admin_usr = os.getenv('admin_usr') or ''
extendedErrMess = str(os.getenv('extendedErrMess')).lower()
JLS = str(os.getenv('JoinLeaveSounds')).lower()
FMD = str(os.getenv('ForceMediaDir')).lower()
LAM = str(os.getenv('LoadAllModules')).lower()
################################################
except Exception as err:
print(f"CAN'T LOAD .env FILE!\nFill the .env file with proper values!\nException: {err}")
#Intents
intents = discord.Intents.default()
intents.message_content = True
status = ['Windows 98 SE', 'Minesweeper', f'{platform.system()} {platform.release()}', 'system32', 'Fallout 2', 'Windows Vista', 'MS-DOS', 'Team Fortress 2', 'Discord Moderator Simulator', 'Arch Linux', f'ServerBot v{ver}', displayname]
choice = random.choice(status)
client = commands.Bot(command_prefix=prefix, intents=intents, activity=discord.Game(name=choice))
client.maindir = maindir
client.version = ver
client.name = displayname
accept_value = ['true', 'enabled', 'ena', 'yes', 'y', '1', 1, True]
start_time = datetime.datetime.now()
#OS check from /etc/os-release
try:
os_release = platform.freedesktop_os_release()
OS_NAME = os_release.get('NAME', 'Unknown')
OS_VERSION_ID = os_release.get('VERSION_ID', 'Unknown')
OS_VERSION_CODENAME = os_release.get('VERSION_CODENAME', 'Unknown')
except OSError:
OS_NAME = OS_VERSION_ID = OS_VERSION_CODENAME = 'Unknown'
#YT_DLP
yt_dl_opts = {"format": "bestaudio/best"}
ytdl = youtube_dl.YoutubeDL(yt_dl_opts)
ffmpeg_options = {"options": "-vn -reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 2"}
#YT_DLP - search
ytdl_opts_search = {
'default_search': 'ytsearch',
'quiet': True,
'extract_flat': True,
'verbose': False, # True for debug
'noplaylist': True,
'format': 'bestaudio/best',
'http_headers': {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Referer': 'https://www.youtube.com/'}}
ytdl_search = youtube_dl.YoutubeDL(ytdl_opts_search)
#Log_File
def createlogs():
with open(f'{maindir}/Logs.txt', 'w', encoding='utf-8') as logs:
logs.write(f"""S E R V E R B O T
LOGS
Time: {datetime.datetime.now().strftime('%H:%M:%S, %d.%m.%Y')}
Info: Remember to shut down bot by .ShutDown command or log will be empty.
=============================================================================\n\n""")
createlogs()
#LogMessage
def logMessage(info):
time = datetime.datetime.now().strftime('%d.%m.%Y %H:%M:%S')
with open(f'{maindir}/Logs.txt', 'a', encoding='utf-8') as logs:
logs.write(f'[{time}] {info}\n')
#PrintMessage
def printMessage(info):
time = datetime.datetime.now().strftime('%d.%m.%Y %H:%M:%S')
print(f'[{time}] {info}')
#Database - create if not exists
if os.path.exists(f"{maindir}/Files/serverbot.db") == True:
if extendedErrMess in accept_value:
print("Database found.")
else:
print("Database not found. Creating new database...")
db_create = sqlite3.connect(f"{maindir}/Files/serverbot.db")
cur = db_create.cursor()
cur.execute("""CREATE TABLE IF NOT EXISTS users(
id integer not null primary key AUTOINCREMENT,
discord_id integer unique not null,
username text,
SBrole text default None,
exp_points integer default 0,
level integer default 0)""")
db_create.commit()
db_create.close()
#Database
SB_DB = sqlite3.connect(DB_PATH, check_same_thread=False, timeout=10)
#User registration
def register_user(id, name):
cur = SB_DB.cursor()
#SELECT
cur.execute('SELECT 1 FROM users WHERE discord_id=?', (id,))
if cur.fetchone() is None:
#INSERT
cur.execute(f"INSERT INTO users (discord_id, username) VALUES (?, ?) ON CONFLICT(discord_id) DO NOTHING", (id, f"{name}"))
SB_DB.commit()
#Check if mod
def is_mod(id):
cur = SB_DB.cursor()
cur.execute("SELECT 1 FROM users WHERE discord_id=? AND SBrole='mod'", (id,))
if cur.fetchone() is not None:
return True
#OS check
def os_check():
if psutil.LINUX:
return "Linux"
elif psutil.WINDOWS:
return "Windows"
elif psutil.MACOS:
return "macOS"
else:
return "Other / Unknown"
#Information/Errors
file_error = "Error: File not found"
file_large = "Error: File too large"
dir_error = "Error: Directory not found"
create_dir_fail = "Error: Can't create directory."
create_file_fail = "Error: Can't create file."
file_incomplete_cmd = "Incomplete command. Usage: .file { open | mkdir | size | create } <filename> [content]"
touch_incomplete_cmd = "Incomplete command. Usage: .touch <filename> [content]"
chksize_error = "Error occurred while checking file size."
copiedlog = f"Information[ServerLog]: Copied Log to {maindir}/Files"
thread_error = "Something went wrong. Try to type: `.thread <name> [slowmode] [reason]`"
not_allowed = "You're not allowed to use this command."
SBservice = "Run post installation commands to enable ServerBot.service to start with system startup:\nsudo chmod 775 -R /BotDirectory/*\nsudo systemctl enable ServerBot -> Enables automatic startup\nsudo systemctl start ServerBot -> Optional (turns on Service)\nsudo systemctl daemon-reload -> if you're running this command second time\nREMEBER about Reading/Executing permissions for others!"
badsite = "Something went wrong.\nHave you typed the correct address?\n..Or maybe the website just doesn't exist?"
random_err = "Something went wrong. Have you typed correct min/max values?"
VC_already_connected = "Already connected to Voice Channel."
VC_bot_not_connected = "Not connected to VC."
VC_usr_not_connected = "You must be connected to VC first!"
VC_invalid_channel = "Join to VC where the bot is."
VC_leave_error = "How can I leave, when I'm not in VC?"
VC_is_playing = "Music is playing right now."
VC_not_playing = "Music is not playing right now."
VC_ffmpeg_error = "FFmpeg is not installed or File not found."
#ClientEvent
@client.event
async def on_ready():
print(f'Logged as {client.user}')
print(f'Welcome in ServerBot v{ver}')
#Load_cog_modules_on_ready
# Load all built-in modules from 'modules' directory; cogs from subdirectories you have to load manually, or add to loading list as 'subdirName.cogName'
if LAM in accept_value:
for i in os.listdir(f'{maindir}/modules'):
try:
if i.endswith('.py'):
await client.load_extension(f"modules.{i[:-3]}")
if extendedErrMess in accept_value:
message = f"Loaded {i[:-3]} module."
print(message)
logMessage(message)
except Exception as err:
message = f"Failed to load {i} module: {err}"
print(message)
logMessage(message)
# If LAM is False, bot will load only modules selected in loadList variable
else:
if loadList != []:
for i in loadList:
try:
await client.load_extension(f"modules.{i}")
if extendedErrMess in accept_value:
message = f"Loaded {i} module"
print(message)
logMessage(message)
except Exception as err:
message = f"Failed to load {i} module: {err}"
print(message)
logMessage(message)
#Slash_command_sync
try:
syncd = await client.tree.sync()
print(f'Synced {len(syncd)} slash command(s).')
except Exception as err:
if extendedErrMess in accept_value:
print(f"Cannot sync slash commands: {err}")
else:
print("Cannot sync slash commands.\nSee Logs.txt for details.")
message = f"Information[SlashCommandSync]: Error occurred while syncing slash commands: {err}"
logMessage(message)
print(start_time.strftime('Time: %H:%M:%S\nDay: %d.%m.%Y'))
print('=' *40)
@client.event
async def on_message(message):
#Username
username = str(message.author).split('#')[0]
#UserMessage
user_message = str(message.content)
#Channel
try:
channel = str(message.channel.name)
except AttributeError:
channel = str(message.channel)
#Server
try:
server = str(message.guild.name)
except AttributeError:
server = str(message.guild)
#UserID
userid = message.author.id
#ChannelID
channelid = message.channel.id
#ServerID
try:
serverid = message.guild.id
except AttributeError:
serverid = "DM"
for cog in client.cogs.values():
if hasattr(cog, 'on_message_hook'):
await cog.on_message_hook(message)
register_user(userid, username)
await client.process_commands(message)
#ClientEvent-END
#Commands
#Random/Fun
#1
@client.hybrid_command(
name='random',
help="Shows your random number. Usage: .random <min> <max>"
)
@app_commands.describe(
min='Minimum value',
max='Maximum value'
)
async def random_num(
ctx,
min = commands.parameter(description="Minimum value", default=int(1)),
max = commands.parameter(description="Maximum value", default=int(100))
):
import random
await ctx.defer()
try:
random_num = random.randint(min, max)
await ctx.reply(f'This is your random number: {random_num}')
except Exception as err:
if extendedErrMess in accept_value:
await ctx.reply(f'{random_err}\nPossible cause: {err}')
else:
await ctx.reply(random_err)
#2
@client.hybrid_command(
name='botbanner',
help="Show bot's banner."
)
async def botbanner(ctx):
await ctx.send(f'```{banner}```')
#3
@client.hybrid_command(
name='banner',
help="Show your text as a banner."
)
@app_commands.describe(
text='Text to convert to banner.'
)
async def userbanner(
ctx, *,
text = commands.parameter(description='Text to convert to banner.', default=None)
):
if text is not None:
userbanner = pyfiglet.figlet_format(text)
await ctx.send(f'```{userbanner}```')
else:
await ctx.send("Incomplete command.\nType text to convert to banner.")
#4
@client.hybrid_command(
name='badge',
help="Shows user badges. Usage: .badge @user"
)
@app_commands.describe(
member = 'Mention user to check badges.'
)
async def badge(
ctx,
member: discord.Member = commands.parameter(description="Mention user to check badges.")
):
try:
user_flags = member.public_flags.all()
badges = [flag.name for flag in user_flags]
await ctx.send(f'{member} has the following badges: {", ".join(badges)}')
except:
await ctx.reply("Incorrect user or incomplete command. Use '.badge @user'")
#Random/Fun-END
#BotInfo
#1
@client.hybrid_command(
name='manual',
help="Sends HTML manual.\n'web' - see manual in browser\n'local' - download HTML manual from Discord"
)
@app_commands.describe(
type = "{web | local} to see in browser or download from discord",
lang = "Language; available PL, EN. Optional for local manual."
)
async def manual(
ctx,
type = commands.parameter(description="{web | local} to see in browser or download from discord"),
lang = commands.parameter(description="Language; available PL, EN. Optional for local manual.", default=None)
):
try:
if type == 'web':
await ctx.send("ServerBot user Manual [PL](https://Kamile320.github.io/ServerBot/manualPL.html) [EN](https://Kamile320.github.io/ServerBot/manualEN.html)")
elif type == 'local':
if lang is None: lang = ""
if lang.lower() == 'pl':
await ctx.send(file=discord.File(f'{maindir}/manualPL.html'))
elif lang.lower() == 'en':
await ctx.send(file=discord.File(f'{maindir}/manualEN.html'))
else:
await ctx.send(file=discord.File(f'{maindir}/manualEN.html'))
else:
await ctx.send("Wrong type.\nChoose 'web' to read manual in browser or 'local' to download .html from Discord")
except:
await ctx.send(f"Something went wrong. Try again.")
#2
@client.hybrid_command(
name='credits',
help="See credits."
)
async def credits(ctx):
embed = discord.Embed(
title="***S e r v e r B o t***",
description=f"Version: **{ver}**\nCreated By: [Kamile320](https://github.com/kamile320)",
color=0xd6930c
)
embed.set_author(name=ctx.bot.user.name, icon_url=ctx.bot.user.display_avatar.url)
embed.add_field(
name="Links:",
value="[Discord](https://discord.gg/UMtYGAx5ac)\n"
"[Source code](https://github.com/kamile320/ServerBot)"
)
embed.add_field(
name="Thanks to:",
value="- friends for testing Bot",
inline=False
)
embed.add_field(
name="Used sounds:",
value="- WinXP/98 sounds - files from OG OS by Microsoft\n"
"- [TF2 upgrade station](https://youtube.com/watch?v=Q7eJg7hRvqE)",
inline=False
)
await ctx.send(embed=embed)
#3
@client.hybrid_command(
name='time',
help="See local time."
)
async def time(ctx):
now = datetime.datetime.now()
await ctx.send(now.strftime("Time: %H:%M:%S\nDay: %d.%m.%Y"))
#4
@client.hybrid_command(
name='uptime',
help="See details about bot uptime."
)
async def uptime(ctx):
time_now = datetime.datetime.now()
started = start_time.strftime('Time: %H:%M:%S\nDay: %d.%m.%Y')
await ctx.send(f"""***S e r v e r B o t*** *uptime statistics*:
=============================
Local time: **{time_now.strftime('%H:%M:%S, %d.%m.%Y')}**
Start time: **{start_time.strftime('%H:%M:%S, %d.%m.%Y')}**
Runtime: **{(time_now - start_time).days} days running.**
=============================
"""
)
#5
@client.hybrid_command(
name='ping',
help="Ping the bot."
)
async def ping(ctx):
await ctx.send(f':tennis: Pong! ({round(client.latency * 1000)}ms)')
#6
@client.hybrid_command(
name='release',
help="View the latest changes made to the bot's code."
)
async def newest_update(ctx):
await ctx.send(f"""
[ServerBot v{ver}]
Changelog:
- Enhanced pingip: added count parameter, OS detection and better error handling; changed to hybrid command
- Updated .module command - now synces slash commands after every load/reload/unload
- Updated .service command; moved to separate module (service.py) and changed to hybrid command (prefix and slash at once)
- Changed .testbot .ping .random .ai .echo to hybrid commands; removed separate slash versions of these commands
- Moved AI command and related functions/variables to separate module (ai.py)
- Updating commands structure - in progress
- Moving most of the commands to hybrid commands (supporting prefix and slash commands at once) - in progress
- Updated .env file scheme and improved loading it
- Updated ACL to v5.0
- Updated file manager/directory commands
- Removed old unused/useless commands
- Updated template cog
- Updated converter commands to v2.0 and moved to separate module (converters.py)
- Added '.uptime' command
- Updated Music commands; improvements and better error handling. Now no one can turn off/pause/resume music outside the VC. Updated message/error variables.
- Updated .testbot and .testos commands - now you can see used CPU (%) and RAM (MB) by discord bot, and total (%) usage of CPU and RAM as before.
Additionally, '.testos' now reads Name, Version and Codename of the OS from os-release file (if exists; Linux-only).
- Updated .manual .thread commands
- Maindir variable can be passed to cogs
- Fixes and improvements
To see older releases, read 'updates.txt' in the 'Files' directory.
""")
#7
@client.hybrid_command(
name='next_update',
help="See the future function/update ideas."
)
async def next_update(ctx):
await ctx.send("""
Ideas for Future Updates:
- Better Informations/Errors
- More embed messages
- Database support and leveling system (sqlite3)
- More advanced module system (cogs) or whole code rewrite to make it more modular and easier to update
You can give your own ideas on my [Discord Server](https://discord.gg/UMtYGAx5ac)
""")
#BotInfo-END
#AdminOnly
#1
@client.command(
name='ShutDown',
help="Turn off the Bot."
)
async def ShutDown(ctx):
if str(ctx.message.author.id) not in admin_usr:
await ctx.reply(not_allowed)
return
await ctx.send(f'Shutting down...')
print("Information[ShutDown]: Started turning off the Bot...")
await asyncio.sleep(1)
try:
print("Saving Logs.txt...")
with open(f'{maindir}/Logs.txt', 'r') as src:
append = f"\n\n{src.read()}"
with open(f'{maindir}/Files/Logs.txt', 'a') as logs:
logs.write(append)
except:
print("Error occurred while saving log.")
try:
print("Closing Discord connection...")
await client.close()
except Exception as err:
message = f"Information[ShutDown]: Failed to disconnect from Discord.\nPossible cause: {err}"
printMessage(message)
logMessage(message)
await ctx.send("Failed to disconnect from Discord. See Logs.txt or console for details.")
try:
print("Closing database...")
SB_DB.close()
except:
print("Failed to close databse.")
print("Information[ShutDown]: Shutting down...")
#2
@client.hybrid_command(
name='copylog',
help="Copies Bot Log file.\nappend -> adds new value to older in Files/Logs.txt\nreplace -> clears old Files/Logs.txt and adds new content\nclearall -> clears all Logs"
)
@app_commands.describe(
mode="{ append | replace | clearall }"
)
async def copylog(
ctx,
mode = commands.parameter(description="{ append | replace | clearall }")
):
if str(ctx.message.author.id) not in admin_usr:
await ctx.reply(not_allowed)
return
await ctx.defer()
if mode == 'append':
try:
with open(f'{maindir}/Logs.txt', 'r') as src:
append = f"\n\n{src.read()}"
with open(f'{maindir}/Files/Logs.txt', 'a') as logs:
logs.write(append)
await ctx.send('Appending logs to Files/Logs.txt succeed.')
except:
await ctx.send(f"Error occurred while copying log.")
elif mode == 'replace':
try:
src_path = fr"{maindir}/Logs.txt"
dst_path = fr"{maindir}/Files/Logs.txt"
shutil.copy(src_path, dst_path)
print(copiedlog)
await ctx.send(f'Successfully replaced Files/Logs.txt content.')
except:
await ctx.send("Error occurred while copying log. Maybe folder doesn't exist?")
elif mode == 'clearall':
try:
with open(f"{maindir}/Logs.txt", 'w', encoding='utf-8') as l1:
l1.write("")
with open(f"{maindir}/Files/Logs.txt", 'w', encoding='utf-8') as l2:
l2.write("")
await ctx.send("Successfully cleared Logs.")
except:
await ctx.send("Can't clear logs.")
else:
await ctx.send("Wrong copylog mode.")
#3
@client.command(
name='bash',
help="Run Bash like scripts on hosting computer (Linux only).\nUses shell scripts.\nBest to work with '.touch' command."
)
async def bash(ctx, file=None):
if str(ctx.message.author.id) not in admin_usr:
await ctx.reply(not_allowed)
return
try:
if file is not None:
message = f'Information[Bash]: User {ctx.message.author.id} executed script: {file}'
printMessage(message)
logMessage(message)
subprocess.run(['bash', file])
else:
await ctx.reply("Incomplete command.\nType '.bash {filename}'")
except Exception as err:
message = f'Information[Bash]: User {ctx.message.author.id} failed to run script {file}.\nPossible cause: {err}'
printMessage(message)
logMessage(message)
if extendedErrMess in accept_value:
await ctx.send(f'Failed to run Script\nPossible cause: {err}')
else:
await ctx.send(f'Failed to run Script')
#4
@client.hybrid_command(
name='rebuild',
help="Rebuild files and directories."
)
async def rebuild(ctx):
if str(ctx.message.author.id) not in admin_usr:
await ctx.reply(not_allowed)
return
await ctx.defer()
await ctx.send('Trying to rebuild files...')
message = "Information[Rebuild]: Started rebuilding files and directories."
printMessage(message)
logMessage(message)
try:
print("Creating 'Logs.txt'...")
os.chdir(maindir)
logs1 = open('Logs.txt', 'w')
logs1.close()
print("Creating 'Files' directory...")
os.makedirs(f'{maindir}/Files')
os.chdir(f'{maindir}/Files')
print("Creating 'updates.txt'...")
updates = open('updates.txt', 'w')
updates.close()
print("Creating 'Files/Logs.txt'...")
logs2 = open('Logs.txt', 'w')
logs2.close()
print("Creating 'Files/setup' directory...")
os.makedirs(f'{maindir}/Files/setup')
print("Creating 'Media' directory...")
os.makedirs(f'{maindir}/Media')
os.chdir(maindir)
print("Creating 'modules' directory...")
os.makedirs(f'{maindir}/modules')
message = "Information[Rebuild]: Successfully rebuilded files and directories."
printMessage(message)
logMessage(message)
await ctx.send("Success.\nRebuilded Files with no content")
except Exception as error:
await ctx.send(f"Rebuilding files failed.\nException: {error}")
#5
@client.hybrid_command(
name='mkshortcut',
help="Creates a shortcut on your Desktop. (For Ubuntu 22.04 based systems only)\nType: .mkshortcut [Name of your Desktop Folder (Desktop/Pulpit etc.)]"
)
@app_commands.describe(
desk="Name of your desktop folder/directory."
)
async def mkshortcut(
ctx,
desk = commands.parameter(description="Name of your desktop folder/directory.")
):
if str(ctx.message.author.id) not in admin_usr:
await ctx.reply(not_allowed)
return
await ctx.defer()
try:
home_dir = os.path.expanduser('~')
os.chdir(home_dir)
os.chdir(desk)
with open('ServerBot.sh', 'w', encoding='utf-8') as shrt:
shrt.write(f'cd {maindir}\npython3 ServerBot.py')
os.chdir(maindir)
await ctx.send('Done.')
message = f"Information[mkshortcut]: Created desktop shortcut ({home_dir})"
printMessage(message)
logMessage(message)
except:
await ctx.send('Something went wrong, please try again.')
#6
@client.hybrid_command(
name='mkservice',
help="Add ServerBot to systemd to start with system startup. (Bot needs to be running as root)\nMode:\n'def' -> creates default autorun entry (python3)\n'venv' -> creates autorun entry that uses python virtual environment created by setup.sh (mkvenv.sh)\n.venv directory is located in the ServerBot main directory\nIt's recommended to save bot files into main (root) directory (/ServerBot) with 775 permissions (chmod 775 recursive). Without these permissions to bot files, systemd startup will not work. Do not place bot in your home dir."
)
@app_commands.describe(
mode="'def' for default autorun entry; 'your venv name' for entry in selected venv"
)
async def mkservice(
ctx,
mode = commands.parameter(description="{ 'def' | 'your venv name' }")
):
if str(ctx.message.author.id) not in admin_usr:
await ctx.reply(not_allowed)
return
await ctx.defer()
try:
if mode == 'def':
try:
await ctx.send("Making autorun.sh file..")
try:
with open(f'{maindir}/Files/autorun.sh', 'w', encoding='utf-8') as auto:
auto.write(f"#!/bin/bash\ncd {maindir}\npython3 ServerBot.py")
os.chmod(f'{maindir}/Files/autorun.sh', 0o775)
await ctx.send('Done.')
message = f"Information[mkservice]: Created autorun.sh file (Files/autorun.sh)"
logMessage(message)
printMessage(message)
except:
await ctx.send("Can't create file!")
await ctx.send(f'Making {servicename}.service in /etc/systemd/system..')
try:
with open(f'/etc/systemd/system/{servicename}.service', 'w', encoding='utf-8') as sys:
sys.write(f"[Unit]\nDescription=ServerBot autorun service\n\n[Service]\nExecStart={maindir}/Files/autorun.sh\n\n[Install]\nWantedBy=multi-user.target")
await ctx.send('Done!')
await ctx.send(SBservice)
message = f"Information[mkservice]: Created {servicename} service file (/etc/systemd/system/)\n{SBservice}"
logMessage(message)
printMessage(message)
except:
await ctx.send("Can't create service file!\nAre you root?")
except Exception as error:
await ctx.send(f'Got 1 error (or more) while creating systemd entry.\nPossible cause: {error}')
elif mode == 'venv':
try:
await ctx.send('Making autorun.sh file..')
try:
with open(f'{maindir}/Files/autorun.sh', 'w', encoding='utf-8') as auto:
auto.write(f'#!/bin/bash\ncd {maindir}\n.venv/bin/python3 ServerBot.py')
os.chmod('Files/autorun.sh', 0o775)
await ctx.send('Done.')
message = f"Information[mkservice]: Created autorun.sh file (Files/autorun.sh)"
logMessage(message)
printMessage(message)
except:
await ctx.send("Can't create file!")
await ctx.send(f'Making {servicename}.service in /etc/systemd/system..')
try:
with open(f'/etc/systemd/system/{servicename}.service', 'w', encoding='utf-8') as sys:
sys.write(f"[Unit]\nDescription=ServerBot autorun service\n\n[Service]\nExecStart={maindir}/Files/autorun.sh\n\n[Install]\nWantedBy=multi-user.target")
await ctx.send("Done!")
await ctx.send(SBservice)
message = f"Information[mkservice]: Created {servicename} service file (/etc/systemd/system/)\n{SBservice}"
logMessage(message)
printMessage(message)
except:
await ctx.send("Can't create service file!\nAre you root?")
except Exception as error:
await ctx.send(f'Got 1 error (or more) while creating systemd entry.\nPossible cause: {error}')
except:
await ctx.send(f"""```{bluescreenface}``` Unexpected problem occurred""")
#7
@client.hybrid_command(
name = 'pingip',
description = "Ping selected IPv4 address. Usage: .pingip <ip address> [count]"
)
@app_commands.describe(
ip = "IP address or domain/hostname.",
count = "How many pings/ICMP packets to send."
)
async def pingip(
ctx,
ip = commands.parameter(description="IP address or domain/hostname."),
count = commands.parameter(description="How many pings/ICMP packets to send.", default=1)
):
if str(ctx.message.author.id) not in admin_usr:
await ctx.reply(not_allowed)
return
await ctx.defer()
ipaddr = ip
param = '-n' if platform.system().lower() == 'windows' else '-c'
cmd = f'ping {ipaddr} {param} {count}'
await ctx.send(f"```{subprocess.getoutput(cmd)}```")
@pingip.error
async def pingip_error(ctx, error):
if isinstance(error, commands.BadArgument):
await ctx.send("Invalid argument. Usage: .pingip <ip_address> [count]")
elif isinstance(error, commands.MissingRequiredArgument):
await ctx.send("Missing argument. Usage: .pingip <ip_address> [count]")
else:
await ctx.send(f'Something went wrong: {error}')
#8
@client.hybrid_command(
name='module',
help="Manage built-in and additional modules (cogs).\nload -> loads module\nunload -> unloads module\nreload -> reload module\nlist -> lists available modules from 'modules' directory. Add 'active' to list only active modules."
)
@app_commands.describe(
mode="{ load | unload | reload | list }",
name="Name of your cog/module or 'active' to see active modules when 'list' mode selected"
)
async def module(
ctx,
mode = commands.parameter(description="{ load | unload | reload | list }", default=None), *,
name = commands.parameter(description="Cog/module name or 'active' when using 'list'", default=None)
):
if str(ctx.message.author.id) not in admin_usr:
await ctx.reply(not_allowed)
return
await ctx.defer()
async def sync_cmd():
try:
sync = await ctx.bot.tree.sync()
message = f"Synced {len(sync)} slash commands."
printMessage(message)
logMessage(message)
except Exception as err:
message = f"Failed to sync slash commands.\nPossible cause: {err}"
printMessage(message)
logMessage(message)
if mode is not None: mode = mode.lower()
if mode == 'list':
try:
br = '\n- '
if name == 'active':
loaded_modules = [cog for cog in client.cogs.keys()]
if not loaded_modules: