main.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. import os
  2. from dotenv import load_dotenv
  3. import discord
  4. from discord.ext import commands
  5. from discord.commands import Option
  6. from discord.commands import slash_command
  7. from datetime import datetime, time
  8. import configparser
  9. import mysql.connector
  10. import asyncio
  11. intents = discord.Intents.default()
  12. intents.message_content = True
  13. intents.members = True
  14. intents.guilds = True
  15. intents.reactions = True
  16. client = discord.Client(intents=intents)
  17. #---------------------------------#
  18. #Load .env file
  19. load_dotenv()
  20. token = os.getenv("TOKEN")
  21. if token is None:
  22. raise ValueError("TOKEN not found in .env file")
  23. debug_guilds_up = []
  24. server_token = os.getenv("SERVER").split(",")
  25. for i in range(len(server_token)):
  26. debug_guilds_up.append(int(server_token[i]))
  27. dbhost = os.getenv("HOST")
  28. if dbhost is None:
  29. raise ValueError("HOST not found in .env file")
  30. dbname = os.getenv("NAME")
  31. if dbname is None:
  32. raise ValueError("NAME not found in .env file")
  33. dbpsswd = os.getenv("PASSWORD")
  34. if dbpsswd is None:
  35. raise ValueError("PASSWORD not found in .env file")
  36. dbdb = os.getenv("DATABASE")
  37. if dbdb is None:
  38. raise ValueError("DATABASE not found in .env file")
  39. #---------------------------------#
  40. #ConfigParser
  41. config = configparser.RawConfigParser()
  42. configFilePath = r'config.cfg'
  43. config.read_file(open(configFilePath))
  44. label_rules = config.get('Reactionroles Rules', 'label_rules')
  45. role_rules = config.get('Reactionroles Rules', 'rules_role')
  46. channel_log = config.get('Logs', 'channel_log')
  47. channel_banlog = config.get('Logs', 'ban_log')
  48. team_role_id = config.get('Team Roles', 'team_role_id')
  49. #---------------------------------#
  50. #Database initialization
  51. conn = mysql.connector.connect(
  52. host=dbhost,
  53. user=dbname,
  54. password=dbpsswd,
  55. charset='utf8mb4',
  56. collation='utf8mb4_unicode_ci'
  57. )
  58. cursor = conn.cursor()
  59. conn.database = dbdb
  60. cursor.execute("""
  61. CREATE TABLE IF NOT EXISTS User (
  62. userid BIGINT UNIQUE PRIMARY KEY,
  63. discordname VARCHAR(100),
  64. rolesnumber INT,
  65. Roles TEXT
  66. )
  67. """)
  68. cursor.execute("""
  69. CREATE TABLE IF NOT EXISTS Team (
  70. userid BIGINT UNIQUE PRIMARY KEY,
  71. discordname VARCHAR(100),
  72. Roles TEXT,
  73. Permissions TEXT
  74. )
  75. """)
  76. cursor.execute("""
  77. CREATE TABLE IF NOT EXISTS Warns (
  78. id INT AUTO_INCREMENT PRIMARY KEY,
  79. userid BIGINT,
  80. username VARCHAR(100),
  81. moderatorname VARCHAR(100),
  82. reason VARCHAR(250),
  83. date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  84. )
  85. """)
  86. cursor.execute("""
  87. CREATE TABLE IF NOT EXISTS Bans (
  88. id INT AUTO_INCREMENT PRIMARY KEY,
  89. userid BIGINT,
  90. username VARCHAR(100),
  91. moderatorname VARCHAR(100),
  92. reason VARCHAR(250),
  93. date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  94. )
  95. """)
  96. cursor.execute("""
  97. CREATE TABLE IF NOT EXISTS Unbans (
  98. id INT AUTO_INCREMENT PRIMARY KEY,
  99. userid BIGINT,
  100. username VARCHAR(100),
  101. moderatorname VARCHAR(100),
  102. reason VARCHAR(250),
  103. date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  104. )
  105. """
  106. )
  107. cursor.execute("""
  108. CREATE TABLE IF NOT EXISTS Kick (
  109. id INT AUTO_INCREMENT PRIMARY KEY,
  110. userid BIGINT,
  111. username VARCHAR(100),
  112. moderatorname VARCHAR(100),
  113. reason VARCHAR(250),
  114. date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  115. )
  116. """)
  117. #---------------------------------#
  118. #Initialize Bot
  119. bot = commands.Bot(
  120. command_prefix=commands.when_mentioned_or("!"),
  121. description="VicePD Bot",
  122. intents=intents,
  123. debug_guilds=debug_guilds_up if debug_guilds_up else None
  124. )
  125. #Loading Cogs
  126. def load_extensions():
  127. cogs_dir = "./cogs"
  128. if not os.path.exists(cogs_dir):
  129. print(f"Cogs directory '{cogs_dir}' not found!")
  130. return
  131. for filename in os.listdir(cogs_dir):
  132. if filename.endswith(".py"):
  133. cog_list = os.path.splitext(filename)[0]
  134. try:
  135. bot.load_extension(f"cogs.{cog_list}")
  136. print(f"Loaded cog: {cog_list}")
  137. except Exception as e:
  138. print(f"Failed to load cog {cog_list}: {e}")
  139. class Admin(commands.Cog):
  140. def __init__(self, bot):
  141. self.bot = bot
  142. #---------------------------------#
  143. #Print in Log if error occurs
  144. @bot.event
  145. async def on_application_command_error(ctx, error):
  146. channel = discord.utils.get(ctx.guild.channels, id=int(channel_log))
  147. if channel:
  148. await channel.send(f"Error occurred: {str(error)}")
  149. #---------------------------------#
  150. #Bot Online Console
  151. @bot.event
  152. async def on_ready():
  153. print(f"{bot.user} is online")
  154. if bot.guilds:
  155. channel = discord.utils.get(bot.guilds[0].channels, id=int(channel_log))
  156. if channel:
  157. await channel.send(f"{bot.user} is online")
  158. bot.add_view(PersistentRoleView()) #loading reactionrole memory
  159. print("Registrierte Slash-Commands:")
  160. command_list = "\n".join([f"- /{command.name}" for command in bot.pending_application_commands])
  161. for command in bot.pending_application_commands:
  162. print(f" - {command.name}")
  163. if channel and command_list:
  164. await channel.send(f"Registered Slash-Commands:\n{command_list}")
  165. bot.loop.create_task(update_users_periodically())
  166. #---------------------------------------------------------------------------------------#
  167. #DONT Touch anything above this line, unless you know what you are doing!#
  168. #---------------------------------------------------------------------------------------#
  169. #_________________________________#
  170. #BAN SYSTEM
  171. #---------------------------------#
  172. ##Ban
  173. @bot.slash_command(name="ban", description="Ban a user from this Server")
  174. async def ban(
  175. ctx,
  176. user: Option(discord.User, description = "Select User", required=True), # type: ignore
  177. reason: Option(str, description = "Reason for the ban", default="No reason provided") # type: ignore
  178. ):
  179. if not ctx.author.guild_permissions.ban_members:
  180. await ctx.respond("Error: You don't have the permission to ban Members!", ephemeral=True)
  181. return
  182. if user == bot.user:
  183. await ctx.respond("Error: I can't ban myself!", ephemeral=True)
  184. return
  185. if user == ctx.author:
  186. await ctx.respond("Error: You can't ban yourself!", ephemeral=True)
  187. return
  188. channel= discord.utils.get(ctx.guild.channels, id = int(channel_banlog))
  189. embed = discord.Embed(
  190. title=f"Ban of **{user.name}**",
  191. description=f"User {user.mention} has been banned from the Server",
  192. color=discord.Color.red()
  193. )
  194. time = discord.utils.format_dt(datetime.now(), "f")
  195. embed.add_field(name="Ban Date", value=time, inline=False)
  196. embed.add_field(name="Moderator", value=f"{ctx.author}", inline=False)
  197. embed.add_field(name="Reason", value=reason, inline=False)
  198. embed.add_field(name="User ID", value=user.id)
  199. embed.set_thumbnail(url=user.display_avatar.url)
  200. embed.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
  201. embed.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
  202. try:
  203. await ctx.guild.ban(user, reason=reason)
  204. await ctx.respond(f"User {user.mention} has been banned from this Server!", ephemeral=True)
  205. await channel.send(embed=embed)
  206. cursor.execute(
  207. "INSERT INTO Bans (userid, username, moderatorname, reason) VALUES (%s, %s, %s, %s)",
  208. (user.id, str(user), str(ctx.author), reason)
  209. )
  210. conn.commit()
  211. except discord.Forbidden:
  212. await ctx.respond("Error: I don't have permission to ban this user.", ephemeral=True)
  213. except discord.HTTPException as e:
  214. await ctx.respond(f"Error: Could not ban User {user.mention}. Reason: {e}", ephemeral=True)
  215. except Exception as e:
  216. await ctx.respond(f"Unexpected error: {e}", ephemeral=True)
  217. #---------------------------------#
  218. #Unban
  219. @bot.slash_command(name="unban", description="Unban a user from this Server")
  220. async def unban(
  221. ctx,
  222. user: Option(discord.User, description = "Insert User ID", required=True), # type: ignore
  223. reason: Option(str, description = "Reason for the unbanning", default="No reason provided") # type: ignore
  224. ):
  225. if not ctx.author.guild_permissions.ban_members:
  226. await ctx.respond("Error: You don't have the permission to unban Members!", ephemeral=True)
  227. return
  228. if user == bot.user:
  229. await ctx.respond("Error: I can't unban myself!", ephemeral=True)
  230. return
  231. if user == ctx.author:
  232. await ctx.respond("Error: You can't unban yourself!", ephemeral=True)
  233. return
  234. if user in ctx.guild.members:
  235. await ctx.respond("Error: This user is not banned!", ephemeral=True)
  236. return
  237. channel= discord.utils.get(ctx.guild.channels, id = int(channel_banlog))
  238. embed = discord.Embed(
  239. title=f"Unban of **{user.name}**",
  240. description=f"User {user.mention} was unbanned from this server.",
  241. color=discord.Color.green()
  242. )
  243. time = discord.utils.format_dt(datetime.now(), "f")
  244. embed.add_field(name="Unban Date", value=time, inline=False)
  245. embed.add_field(name="Moderator", value=f"{ctx.author}", inline=False)
  246. embed.add_field(name="Reason", value=reason, inline=False)
  247. embed.add_field(name="User ID", value=user.id)
  248. embed.set_thumbnail(url=user.display_avatar.url)
  249. embed.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
  250. embed.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
  251. try:
  252. await ctx.guild.unban(user, reason=reason)
  253. await ctx.respond(f"User {user.mention} is now unbanned!", ephemeral=True)
  254. await channel.send(embed=embed)
  255. cursor.execute(
  256. "INSERT INTO Unbans (userid, username, moderatorname, reason) VALUES (%s, %s, %s, %s)",
  257. (user.id, str(user), str(ctx.author), reason)
  258. )
  259. conn.commit()
  260. except discord.Forbidden:
  261. await ctx.respond("Error: I don't have permission to unban this user.", ephemeral=True)
  262. except discord.HTTPException as e:
  263. await ctx.respond(f"Error: Could not unban User {user.mention}. Reason: {e}", ephemeral=True)
  264. except Exception as e:
  265. await ctx.respond(f"Unexpected error: {e}", ephemeral=True)
  266. #---------------------------------#
  267. #_________________________________#
  268. #---------------------------------#
  269. #Kick
  270. @bot.slash_command(name="kick", description="Kick a user from this Server")
  271. async def kick(
  272. ctx,
  273. user: Option(discord.User, description = "Select User", required=True), # type: ignore
  274. reason: Option(str, description = "Reason for the ban", default="No reason provided") # type: ignore
  275. ):
  276. if not ctx.author.guild_permissions.kick_members:
  277. await ctx.respond("Error: You don't have the permission to kick Members!", ephemeral=True)
  278. return
  279. if user == bot.user:
  280. await ctx.respond("Error: I can't kick myself!", ephemeral=True)
  281. return
  282. if user == ctx.author:
  283. await ctx.respond("Error: You can't kick yourself!", ephemeral=True)
  284. return
  285. channel= discord.utils.get(ctx.guild.channels, id = int(channel_banlog))
  286. embed = discord.Embed(
  287. title=f"Kick of **{user.name}**",
  288. description=f"User {user.mention} has been kicked from the Server",
  289. color=discord.Color.red()
  290. )
  291. time = discord.utils.format_dt(datetime.now(), "f")
  292. embed.add_field(name="Kick Date", value=time, inline=False)
  293. embed.add_field(name="Moderator", value=f"{ctx.author}", inline=False)
  294. embed.add_field(name="Reason", value=reason, inline=False)
  295. embed.add_field(name="User ID", value=user.id)
  296. embed.set_thumbnail(url=user.display_avatar.url)
  297. embed.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
  298. embed.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
  299. try:
  300. await ctx.guild.kick(user, reason=reason)
  301. await ctx.respond(f"User {user.mention} has been kicked from this Server!", ephemeral=True)
  302. cursor.execute(
  303. "INSERT INTO Kick (userid, username, moderatorname, reason) VALUES (%s, %s, %s, %s)",
  304. (int(user.id), str(user), str(ctx.author), reason)
  305. )
  306. conn.commit()
  307. await channel.send(embed=embed)
  308. except discord.Forbidden:
  309. await ctx.respond("Error: I don't have permission to kick this user.", ephemeral=True)
  310. except discord.HTTPException as e:
  311. await ctx.respond(f"Error: Could not kick User {user.mention}. Reason: {e}", ephemeral=True)
  312. except Exception as e:
  313. await ctx.respond(f"Unexpected error: {e}", ephemeral=True)
  314. #---------------------------------#
  315. #---------------------------------#
  316. #Warn
  317. @bot.slash_command(name="warn", description="Warn a user from this Server")
  318. async def warn(
  319. ctx,
  320. user: Option(discord.User, required=True), # type: ignore
  321. reason: Option(str, default="No reason provided") # type: ignore
  322. ):
  323. await ctx.defer(ephemeral=True)
  324. if not ctx.author.guild_permissions.kick_members:
  325. await ctx.followup.send("No permission.", ephemeral=True)
  326. return
  327. if user in (bot.user, ctx.author):
  328. await ctx.followup.send("Invalid target.", ephemeral=True)
  329. return
  330. cursor.execute(
  331. "INSERT INTO Warns (userid, username, moderatorname, reason) VALUES (%s, %s, %s, %s)",
  332. (user.id, str(user), str(ctx.author), reason)
  333. )
  334. conn.commit()
  335. await ctx.followup.send(
  336. f"User {user.mention} has been warned for: {reason}",
  337. ephemeral=True
  338. )
  339. #---------------------------------#
  340. #Modinfo
  341. @bot.slash_command(name="modinfo", description="Shows the moderative history of a user from this Server")
  342. async def modinfo(
  343. ctx,
  344. user: Option(discord.User, required=True) # type: ignore
  345. ):
  346. await ctx.defer(ephemeral=False)
  347. if not ctx.author.guild_permissions.kick_members:
  348. await ctx.followup.send("No permission.", ephemeral=True)
  349. return
  350. embed = discord.Embed(
  351. title=f"__Moderation History for {user.name}__",
  352. color=discord.Color.orange()
  353. )
  354. cursor.execute(
  355. "SELECT moderatorname, reason, date FROM Warns WHERE userid = %s",
  356. (user.id,)
  357. )
  358. warns = cursor.fetchall()
  359. if warns:
  360. for moderatorname, reason, date in warns:
  361. embed.add_field(
  362. name=f"Warned by {moderatorname} on {date.strftime('%Y-%m-%d %H:%M:%S')}",
  363. value=f"Reason: {reason}",
  364. inline=False
  365. )
  366. cursor.execute(
  367. "SELECT moderatorname, reason, date FROM Kick WHERE userid = %s",
  368. (user.id,)
  369. )
  370. kicks = cursor.fetchall()
  371. if kicks:
  372. for moderatorname, reason, date in kicks:
  373. embed.add_field(
  374. name=f"Kicked by {moderatorname} on {date.strftime('%Y-%m-%d %H:%M:%S')}",
  375. value=f"Reason: {reason}",
  376. inline=False
  377. )
  378. cursor.execute(
  379. "SELECT moderatorname, reason, date FROM Bans WHERE userid = %s",
  380. (user.id,)
  381. )
  382. bans = cursor.fetchall()
  383. if bans:
  384. for moderatorname, reason, date in bans:
  385. embed.add_field(
  386. name=f"Banned by {moderatorname} on {date.strftime('%Y-%m-%d %H:%M:%S')}",
  387. value=f"Reason: {reason}",
  388. inline=False
  389. )
  390. cursor.execute(
  391. "SELECT moderatorname, reason, date FROM Unbans WHERE userid = %s",
  392. (user.id,)
  393. )
  394. unbans = cursor.fetchall()
  395. if unbans:
  396. for moderatorname, reason, date in unbans:
  397. embed.add_field(
  398. name=f"Unbanned by {moderatorname} on {date.strftime('%Y-%m-%d %H:%M:%S')}",
  399. value=f"Reason: {reason}",
  400. inline=False
  401. )
  402. if not warns and not kicks and not bans and not unbans:
  403. await ctx.followup.send(f"User `{user.name}` has no moderation history.", ephemeral=True)
  404. return
  405. embed.set_thumbnail(url=user.display_avatar.url)
  406. embed.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
  407. embed.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
  408. await ctx.followup.send(embed=embed, ephemeral=False)
  409. #_________________________________#
  410. ## Reaction role system
  411. #---------------------------------#
  412. #reaction role verfiy
  413. class PersistentRoleView(discord.ui.View):
  414. def __init__(self):
  415. super().__init__(timeout=None)
  416. @discord.ui.button(
  417. label=label_rules,
  418. style=discord.ButtonStyle.success,
  419. emoji="✅",
  420. custom_id="persistent_view:role_verify"
  421. )
  422. async def verify_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
  423. role = interaction.guild.get_role(int(role_rules))
  424. if role is None:
  425. await interaction.response.send_message("Error: The konfigured role was not found", ephemeral=True)
  426. return
  427. if role in interaction.user.roles:
  428. await interaction.user.remove_roles(role)
  429. await interaction.response.send_message(f"Rolle **{role.name}** wurde entfernt.", ephemeral=True)
  430. else:
  431. await interaction.user.add_roles(role)
  432. await interaction.response.send_message(f"Du hast die Rolle **{role.name}** erhalten!", ephemeral=True)
  433. @bot.slash_command(name="verify_message", description="Send the reactionrole message| This is for setup only!")
  434. async def setup_rr(
  435. ctx: discord.ApplicationContext,
  436. channel: discord.TextChannel,
  437. title: str,
  438. description: str
  439. ):
  440. if not ctx.author.guild_permissions.administrator:
  441. await ctx.respond("You dont have the permissions to do that..", ephemeral=True)
  442. return
  443. embed = discord.Embed(
  444. title=title,
  445. description=f"{description}\n\nViel Spass auf dem Server!",
  446. color=discord.Color.red()
  447. )
  448. embed.set_image(url="https://i.imgur.com/FoF791J.png")
  449. try:
  450. await channel.send(embed=embed, view=PersistentRoleView())
  451. await ctx.respond(f"Message was succesfully sent in {channel.mention}!", ephemeral=True)
  452. except discord.Forbidden:
  453. await ctx.respond("I dont have permissions to write in this channel", ephemeral=True)
  454. #---------------------------------#
  455. #_________________________________#
  456. #--------------------------------#
  457. #Get all Users in Database periodically
  458. async def update_users_periodically():
  459. await bot.wait_until_ready()
  460. while not bot.is_closed():
  461. try:
  462. for guild in bot.guilds:
  463. batch_count = 0
  464. async for member in guild.fetch_members(limit=None):
  465. role_ids_string = ",".join([str(role.id) for role in member.roles])
  466. cursor.execute(
  467. """INSERT INTO User (userid, discordname, rolesnumber, roles)
  468. VALUES (%s, %s, %s, %s)
  469. ON DUPLICATE KEY UPDATE discordname=%s, rolesnumber=%s, roles=%s""",
  470. (member.id, str(member), len(member.roles), role_ids_string,
  471. str(member), len(member.roles), role_ids_string)
  472. )
  473. batch_count += 1
  474. if batch_count >= 100:
  475. conn.commit()
  476. batch_count = 0
  477. if batch_count > 0:
  478. conn.commit()
  479. if team_role_id:
  480. for guild in bot.guilds:
  481. team_role = guild.get_role(int(team_role_id))
  482. if team_role is None:
  483. continue
  484. batch_count = 0
  485. async for member in guild.fetch_members(limit=None):
  486. if team_role in member.roles:
  487. role_ids_string = ",".join([str(role.id) for role in member.roles])
  488. cursor.execute(
  489. """INSERT INTO Team (userid, discordname, Roles)
  490. VALUES (%s, %s, %s)
  491. ON DUPLICATE KEY UPDATE discordname=%s, Roles=%s""",
  492. (member.id, str(member), role_ids_string,
  493. str(member), role_ids_string)
  494. )
  495. batch_count += 1
  496. if batch_count >= 100:
  497. conn.commit()
  498. batch_count = 0
  499. if batch_count > 0:
  500. conn.commit()
  501. #print(f"[✓] {datetime.now().strftime('%H:%M:%S')} - Datenbank mit Discord-Rollen synchronisiert.")
  502. except Exception as e:
  503. print(f"[!] Fehler beim Update der User: {e}")
  504. await asyncio.sleep(60) # Update every minute
  505. #_________________________________#
  506. ## TXADMIN ROLE PERMISSIONS
  507. #---------------------------------#
  508. #Run function
  509. load_extensions()
  510. bot.run(token)
  511. #---------------------------------#