main.py 18 KB

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