-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerBot.py
More file actions
executable file
·2115 lines (1818 loc) · 84 KB
/
ServerBot.py
File metadata and controls
executable file
·2115 lines (1818 loc) · 84 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.11.0"
# Bot Name
displayname = "ServerBot"
# Name of service in systemd; change if needed, WITHOUT .service file extension
servicename = "ServerBot"
#Directory
maindir = os.getcwd()
SBbytes = os.path.getsize('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 'modules/custom' you have to type like 'custom.cogName' - WITHOUT .py
#If LoadAllModules is True, this list will nothing do; bot will load every cog from 'modules' directory (not from 'modules/custom'!)
#If you use cogs from 'modules' and 'modules/custom' dirs and you want to load them all on start, type here all your modules and set LAM to False
loadList = [] # ['cog1', 'custom.cog2'] <- example
# .env file template - if .env not exists, bot will automatically create a new one
# Do not type values here!
def create_env():
try:
env = open('.env', 'w')
env.write(f"""#ServerBot v{ver} config file
TOKEN=''
admin_usr = ['']
custom_prefix = ''
#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'
#Service_list
service_monitor = False
service_list = ','
#Command_addbot
addstable = 'stable_link'
addtesting = 'testing_link'
#Modules
LoadAllModules = False
#ExtendedErrorMessages
extendedErrMess = False""")
env.close()
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
from google import genai
from google.genai import types
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()
############# token/intents/etc ################
ai_token = os.getenv('AI_token')
if ai_token == '': ai_token = None
admin_usr = os.getenv('admin_usr')
ai_model = f"{os.getenv('AI_model')}" or 'gemini-2.5-flash'
ai_client = genai.Client(api_key=f"{ai_token}")
extendedErrMess = os.getenv('extendedErrMess')
JLS = os.getenv('JoinLeaveSounds')
FMD = os.getenv('ForceMediaDir')
################################################
except Exception as err:
print(f"CAN'T LOAD .env FILE!\nCreate .env file using setup.sh and fill it 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={os.getenv('custom_prefix') or '.'}, intents=intents, activity=discord.Game(name=choice))
testbot_cpu_type = platform.machine() or 'Unknown'
accept_value = ['True', 'true', 'Enabled', 'enabled', '1', 'yes', 'Yes', 'YES', True]
start_time = datetime.datetime.now()
#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
logs = open('Logs.txt', 'w')
def createlogs():
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""")
logs.close()
createlogs()
#LogMessage
def logMessage(info):
time = datetime.datetime.now().strftime('%d.%m.%Y %H:%M:%S')
logs = open(f'{maindir}/Logs.txt', 'a', encoding='utf-8')
logs.write(f'[{time}] {info}\n')
logs.close()
#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"
#Create modules/custom
def test_custom():
if os.path.exists(f'{maindir}/modules/custom') == False:
try:
os.makedirs(f'{maindir}/modules/custom')
return 0 # Was missing and created
except:
print(f"Cannot create 'modules/custom' directory!")
return 1 # Was missing and cannot create
elif os.path.exists(f'{maindir}/modules/custom') == True:
return 2 # All OK
#Information/Errors
fileerror = "Error: File not found"
filelarge = "Error: File too large"
direrror = "Error: Directory not found"
cannotcreatedir = "Error: Can't create directory."
cannotcreatefile = "Error: Can't create file."
chksize_error = "Error occurred while checking file size."
copiedlog = f"Information[ServerLog]: Copied Log to {maindir}/Files"
ffmpeg_error = "FFmpeg is not installed or File not found"
voice_not_connected_error = "You must be connected to VC first!"
not_playing = "Music is not playing right now."
leave_error = "How can I left, when I'm not in VC?"
thread_error = "Something went wrong. Try to type:\n.thread {NameWithoutSpaces} {Reason}\nReason is optional"
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!"
service_err = "Something went wrong.\nHave you added the service entries to the .env file?"
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?'
#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 'modules/custom' you have to load manually, or add to loading list as 'custom.cogName'
test_custom()
if os.getenv('LoadAllModules') 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} 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:
print("Can't sync slash commands\nSee Logs.txt for details.")
logMessage(f"Information[SlashCommandSync]: Error occurred while syncing slash commands: {err}")
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
#Chat
#1
@client.command()
async def hello(ctx):
await ctx.send(f'Hello, {ctx.author.mention}!')
#2
@client.command()
async def bye(ctx):
await ctx.send(f'See you later, {ctx.author.mention}!')
#3
@client.command()
async def hi(ctx):
await ctx.send(f'hi!')
#4
@client.command()
async def hello_there(ctx):
await ctx.send(f'OH, HELLO THERE!')
#Chat-END
#Random/Fun
#1
@client.command(name='random', help="Shows your random number.\nType .random [min] [max]")
async def random_num(ctx, min = int(), max = int()):
import random
try:
randomn = random.randrange(min, max)
await ctx.reply(f'This is your random number: {randomn}')
except Exception as err:
if extendedErrMess:
await ctx.reply(f'{random_err}\nPossible cause: {err}')
else:
await ctx.reply(random_err)
#2
@client.command(name='botbanner', help="Show bot's banner")
async def botbanner(ctx):
await ctx.send(f'```{banner}```')
#3
@client.command(name='banner', help="Show your text as Banner")
async def userbanner(ctx, *, text=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.command(name='blankthing', help="Just blank thing")
async def blank(ctx):
await ctx.send('ㅤ')
#5
@client.command(name='apple', help="Test for be an Apple")
async def blank(ctx):
await ctx.send('')
#6
@client.command(name='ai', help=f"Talk with AI.\nUses {ai_model} model.\n.ai [question]")
async def ai(ctx, *, question):
if ai_token is None:
await ctx.reply("AI token not found. Enter valid Gemini API token in the .env file to use this command.")
return
try:
response = ai_client.models.generate_content(
model=f"{ai_model}",
contents=f"[Your response MUST CONTAIN MAX 2000 CHARACTERS OR LESS] {question}",
config=types.GenerateContentConfig(
system_instruction=[f'{os.getenv("instructions")}', f'You are a {displayname} Discord Bot based on your language model ({ai_model}) and ServerBot v{ver} from GitHub project (https://github.com/kamile320/serverbot).'],
tools=[
types.Tool(
google_search=types.GoogleSearch()
)
]
)
)
await ctx.reply(response.text)
except Exception as err:
await ctx.reply(f"Something went wrong, possible cause:\n{err}")
error_message = f"DiscordCommandException[AI]: {err}"
printMessage(error_message)
logMessage(error_message)
#7
@client.command(name='GNU+Linux', help="Richard Stallman.")
async def gnu(ctx):
await ctx.send("I’d just like to interject for a moment. What you’re refering to as Linux, is in fact, GNU/Linux, or as I’ve recently taken to calling it, GNU plus Linux. Linux is not an operating system unto itself, but rather another free component of a fully functioning GNU system made useful by the GNU corelibs, shell utilities and vital system components comprising a full OS as defined by POSIX. Many computer users run a modified version of the GNU system every day, without realizing it. Through a peculiar turn of events, the version of GNU which is widely used today is often called Linux, and many of its users are not aware that it is basically the GNU system, developed by the GNU Project. There really is a Linux, and these people are using it, but it is just a part of the system they use. Linux is the kernel: the program in the system that allocates the machine’s resources to the other programs that you run. The kernel is an essential part of an operating system, but useless by itself; it can only function in the context of a complete operating system. Linux is normally used in combination with the GNU operating system: the whole system is basically GNU with Linux added, or GNU/Linux. All the so-called Linux distributions are really distributions of GNU/Linux!")
#8
@client.command(name='badge', help="Shows user badges.\n.badge @user")
async def badge(ctx, member: discord.Member):
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.command(name='manual', help="Sends HTML manual\n'web' - see manual in browser\n'local' - download HTML manual from Discord")
async def manual(ctx, type):
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':
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.command(name='credits', help="Shows Credits")
async def credits(ctx):
await ctx.send(f"""
***S e r v e r B o t***
Version: {ver}
Created By: *Kamile320*.
Thanks to:
- friends for testing Bot
- <@632682413776175107> for some retranslations
Source: ```https://github.com/kamile320/ServerBot```
Discord Server: [Here](https://discord.gg/UMtYGAx5ac)
Used Sounds:
WinXP/98 sounds -> files from OG OS by Microsoft
TF2 upgrade station: ```https://youtube.com/watch?v=Q7eJg7hRvqE```
""")
#3
@client.command(name='time', help="Shows 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.command(name='ping', help="Pings the Bot")
async def ping(ctx):
await ctx.send(f':tennis: Pong! ({round(client.latency * 1000)}ms)')
#5
@client.command(name='release', help="Shows last changes of Bot functions/Changelog")
async def newest_update(ctx):
await ctx.send(f"""
[ServerBot v{ver}]
Changelog:
- Added "portal" system - connect two channels and send messages between them with .psend command
- Added .portal and .psend commands
- Updated .ShutDown .testbot .rebuild .ai /ai commands
- Updated database support
- Added cog (module) support
- Updated .module command - now bot can load/unload/reload/list supported cog modules
- Updated ACL to v4.1 and removed from the main file
- Added 'modules' directory for 'built-in' modules and 'modules/custom' for additional ones
- Removed showmodulemessages and ACLmodule variables from .env file and functions that used them
- Updated .env file scheme
- Added custom_prefix variable in the .env file ('.' prefix is still set as default)
To see older releases, read 'updates.txt' in the 'Files' directory.
""")
#6
@client.command(name='next_update', help="Shows future functions/updates")
async def next_update(ctx):
await ctx.send("""
Ideas for Future Updates
- Better Informations/Errors
- More slash commands
- 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="Turns Off the Bot")
async def ShutDown(ctx):
if str(ctx.message.author.id) in admin_usr:
await ctx.send(f'Shutting down...')
print("Information[ShutDown]: Started turning off the Bot")
await asyncio.sleep(1)
try:
print("Saving Logs.txt...")
src = open(f'{maindir}/Logs.txt', 'r')
logs = open(f'{maindir}/Files/Logs.txt', 'a')
append = f"\n\n{src.read()}"
logs.write(append)
logs.close()
src.close()
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...")
else:
await ctx.reply(not_allowed)
#2
@client.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")
async def copylog(ctx, mode):
if str(ctx.message.author.id) in admin_usr:
if mode == 'append':
try:
src = open(f'{maindir}/Logs.txt', 'r')
logs = open(f'{maindir}/Files/Logs.txt', 'a')
append = f"\n\n{src.read()}"
logs.write(append)
logs.close()
src.close()
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:
l1 = open(f"{maindir}/Logs.txt", 'w')
l1.write("")
l1.close()
l2 = open(f"{maindir}/Files/Logs.txt", 'w')
l2.write("")
l2.close()
await ctx.send("Successfully cleared Logs.")
except:
await ctx.send("Can't clear logs.")
else:
await ctx.send("Wrong copylog mode.")
else:
await ctx.reply(not_allowed)
#3
@client.command(name='bash', help="Runs Bash like scripts on hosting computer (Linux only)\nUses .sh extensions\nBest to work with .touch command")
async def bash(ctx, file=None):
if str(ctx.message.author.id) in admin_usr:
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')
else:
await ctx.reply(not_allowed)
#4
@client.command(name='rebuild', help="Rebuilds files and directories")
async def rebuild(ctx):
if str(ctx.message.author.id) in admin_usr:
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')
print("Creating 'modules/custom' directory...")
os.makedirs(f'{maindir}/modules/custom')
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}")
else:
await ctx.reply(not_allowed)
#5
@client.command(name='mkshortcut', help="Creates a shortcut on your Desktop. (Linux (Ubuntu 22.04 based) only)\nType: .mkshortcut [Name of your Desktop Folder (Desktop/Pulpit etc.)]")
async def shrtct(ctx, desk):
if str(ctx.message.author.id) in admin_usr:
try:
home_dir = os.path.expanduser('~')
os.chdir(home_dir)
os.chdir(desk)
shrt = open('ServerBot.sh', 'w')
shrt.write(f'cd {maindir}\npython3 ServerBot.py')
shrt.close()
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.')
else:
await ctx.send(not_allowed)
#6
@client.command(name='mkservice', help="Adds 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.")
async def mkservice(ctx, mode):
if str(ctx.message.author.id) in admin_usr:
try:
if mode == 'def':
try:
await ctx.send("Making autorun.sh file..")
try:
auto = open('Files/autorun.sh', 'w')
auto.write(f"#!/bin/bash\ncd {maindir}\npython3 ServerBot.py")
auto.close()
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:
sys = open(f'/etc/systemd/system/{servicename}.service', 'w')
sys.write(f"[Unit]\nDescription=ServerBot autorun service\n\n[Service]\nExecStart={maindir}/Files/autorun.sh\n\n[Install]\nWantedBy=multi-user.target")
sys.close()
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:
auto = open('Files/autorun.sh', 'w')
auto.write(f'#!/bin/bash\ncd {maindir}\n.venv/bin/python3 ServerBot.py')
auto.close()
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:
sys = open(f'/etc/systemd/system/{servicename}.service', 'w')
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""")
else:
await ctx.send(not_allowed)
#7
if os.getenv('service_monitor') in accept_value:
@client.command(name='service', help="Lists active/inactive services. To add service entry, enter service name in .env file (service_list)\nUses systemctl\n\nlist -> lists entries in '.env' file\nstatus -> lists service entries and checks if they're active\nstatus-detailed -> same as above, but with details (systemctl status [service name])\n[service name] -> shows current status of service in systemd")
async def service(ctx, mode):
if str(ctx.message.author.id) in admin_usr:
try:
if mode == 'list':
try:
listdir_env = os.getenv('service_list')
await ctx.send(f'**Service Entries:**\n{listdir_env}')
except:
await ctx.send(service_err)
elif mode == 'status':
try:
listdir_env = os.getenv('service_list')
listdir = [item.strip() for item in listdir_env.split(',')]
await ctx.send("**Service Activity:**")
for file in listdir:
await ctx.send(f"```{file}: {subprocess.getoutput([f'systemctl is-active {file}'])}```")
except:
await ctx.send(service_err)
elif mode == 'status-detailed':
try:
listdir_env = os.getenv('service_list')
listdir = [item.strip() for item in listdir_env.split(',')]
await ctx.send("**Service Activity:**")
for file in listdir:
await ctx.send(f"```{file}: {subprocess.getoutput([f'systemctl status {file}'])}```")
except:
await ctx.send(service_err)
else:
try:
await ctx.send(f"**Service {mode}:**")
await ctx.send(f"```{subprocess.getoutput([f'systemctl status {mode}'])}```")
except Exception as err:
await ctx.send(f'Something went wrong.\nPossible cause: {err}')
except Exception as err:
await ctx.send(f'Something went wrong.\nPossible cause: {err}')
else:
await ctx.send(not_allowed)
#8
@client.command(name='pingip', help="Pings selected IPv4 address.")
async def pingip(ctx, ip):
if str(ctx.message.author.id) in admin_usr:
try:
ipaddr = ip
await ctx.send(f"```{subprocess.getoutput([f'ping {ipaddr} -c 1'])}```")
except Exception as err:
await ctx.send(f'Something went wrong.\nPossible cause: {err}')
else:
await ctx.send(not_allowed)
#9
@client.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.")
async def module(ctx, mode, *, name=None):
if str(ctx.message.author.id) in admin_usr:
if mode == 'load':
try:
if name is not None:
await client.load_extension(f'modules.{name}')
await ctx.reply(f"{name} module loaded.")
message = f"Information[modules]: {name} module loaded."
printMessage(message)
logMessage(message)
else:
await ctx.reply("Incomplete command. Enter module name.")
except Exception as e:
await ctx.reply(f'Failed to load {name} module: {e}')
message = f'Information[modules]: Failed to load {name} module: {e}'
printMessage(message)
logMessage(message)
elif mode == 'unload':
try:
if name is not None:
await client.unload_extension(f'modules.{name}')
await ctx.reply(f"{name} module unloaded.")
message = f"Information[modules]: {name} module unloaded."
printMessage(message)
logMessage(message)
else:
await ctx.reply("Incomplete command. Enter module name.")
except Exception as e:
await ctx.reply(f'Failed to unload {name} module: {e}')
message = f'Information[modules]: Failed to unload {name} module: {e}'
printMessage(message)
logMessage(message)
elif mode == 'reload':
try:
if name is not None:
await client.reload_extension(f'modules.{name}')
await ctx.reply(f"{name} module reloaded.")
message = f"Information[modules]: {name} module reloaded."
printMessage(message)
logMessage(message)
else:
await ctx.reply("Incomplete command. Enter module name.")
except Exception as e:
await ctx.reply(f'Failed to reload {name} module: {e}')
message = f'Information[modules]: Failed to reload {name} module: {e}'
printMessage(message)
logMessage(message)
elif mode == 'list':
if test_custom() == 0:
message = "Information[module]: Created missing 'modules/custom' directory."
print(message)
logMessage(message)
elif test_custom() == 1:
await ctx.send("The 'modules/custom' directory is missing and cannot be created.")
try:
if name == 'active':
loaded_modules = [cog for cog in client.cogs.keys()]
if not loaded_modules:
await ctx.send("There's no active modules.")
return
else:
await ctx.send(f"**Active modules:**\n{', '.join(loaded_modules)}")
else:
listdir = []
listdir_c = []
br = '\n- '
for f in os.listdir(f'{maindir}/modules'):
if f.endswith('.py'):
listdir.append(f.replace('.py', ''))
for f in os.listdir(f'{maindir}/modules/custom'):
if f.endswith('.py'):
listdir_c.append(f.replace('.py', ''))
await ctx.send(f"""
==========**ServerBot modules: **==========
Available modules:\n- {br.join(listdir)}
Additional modules (from modules/custom):\n- {br.join(listdir_c)}""")
except Exception as e:
await ctx.send(f'Unexpected error occurred. See Logs.txt for details.')
message = f'Information[modules]: Failed to list modules: {e}'
printMessage(message)
logMessage(message)
else:
await ctx.reply("Wrong mode selected. Use '.help module' for help.")
else:
await ctx.send(not_allowed)