main.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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 not os.path.exists(cogs_dir):
  117. print(f"Cogs directory '{cogs_dir}' not found!")
  118. return
  119. for filename in os.listdir(cogs_dir):
  120. if filename.endswith(".py"):
  121. cog_list = os.path.splitext(filename)[0]
  122. try:
  123. bot.load_extension(f"cogs.{cog_list}")
  124. print(f"Loaded cog: {cog_list}")
  125. except Exception as e:
  126. print(f"Failed to load cog {cog_list}: {e}")
  127. class Admin(commands.Cog):
  128. def __init__(self, bot):
  129. self.bot = bot
  130. #---------------------------------#
  131. #Print in Log if error occurs
  132. @bot.event
  133. async def on_application_command_error(ctx, error):
  134. channel = discord.utils.get(ctx.guild.channels, id=int(channel_log))
  135. if channel:
  136. await channel.send(f"Error occurred: {str(error)}")
  137. #---------------------------------#
  138. #Bot Online Console
  139. @bot.event
  140. async def on_ready():
  141. print(f"{bot.user} is online")
  142. if bot.guilds:
  143. channel = discord.utils.get(bot.guilds[0].channels, id=int(channel_log))
  144. if channel:
  145. await channel.send(f"{bot.user} is online")
  146. bot.add_view(PersistentRoleView()) #loading reactionrole memory
  147. print("Registrierte Slash-Commands:")
  148. await channel.send("Registered Slash-Commands:")
  149. for command in bot.pending_application_commands:
  150. print(f" - {command.name}")
  151. await channel.send(f"- {command.name}")
  152. #---------------------------------------------------------------------------------------#
  153. #DONT Touch anything above this line, unless you know what you are doing!#
  154. #---------------------------------------------------------------------------------------#
  155. #_________________________________#
  156. #BAN SYSTEM
  157. #---------------------------------#
  158. ##Ban
  159. @bot.slash_command(name="ban", description="Ban a user from this Server")
  160. async def ban(
  161. ctx,
  162. user: Option(discord.User, description = "Select User", required=True), # type: ignore
  163. reason: Option(str, description = "Reason for the ban", default="No reason provided") # type: ignore
  164. ):
  165. if not ctx.author.guild_permissions.ban_members:
  166. await ctx.respond("Error: You don't have the permission to ban Members!", ephemeral=True)
  167. return
  168. if user == bot.user:
  169. await ctx.respond("Error: I can't ban myself!", ephemeral=True)
  170. return
  171. if user == ctx.author:
  172. await ctx.respond("Error: You can't ban yourself!", ephemeral=True)
  173. return
  174. channel= discord.utils.get(ctx.guild.channels, id = int(channel_banlog))
  175. embed = discord.Embed(
  176. title=f"Ban of **{user.name}**",
  177. description=f"User {user.mention} has been banned from the Server",
  178. color=discord.Color.red()
  179. )
  180. time = discord.utils.format_dt(datetime.now(), "f")
  181. embed.add_field(name="Ban Date", value=time, inline=False)
  182. embed.add_field(name="Moderator", value=f"{ctx.author}", inline=False)
  183. embed.add_field(name="Reason", value=reason, inline=False)
  184. embed.add_field(name="User ID", value=user.id)
  185. embed.set_thumbnail(url=user.display_avatar.url)
  186. embed.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
  187. embed.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
  188. try:
  189. await ctx.guild.ban(user, reason=reason)
  190. await ctx.respond(f"User {user.mention} has been banned from this Server!", ephemeral=True)
  191. await channel.send(embed=embed)
  192. cursor.execute(
  193. "INSERT INTO Bans (userid, username, moderatorname, reason) VALUES (%s, %s, %s, %s)",
  194. (user.id, str(user), str(ctx.author), reason)
  195. )
  196. conn.commit()
  197. except discord.Forbidden:
  198. await ctx.respond("Error: I don't have permission to ban this user.", ephemeral=True)
  199. except discord.HTTPException as e:
  200. await ctx.respond(f"Error: Could not ban User {user.mention}. Reason: {e}", ephemeral=True)
  201. except Exception as e:
  202. await ctx.respond(f"Unexpected error: {e}", ephemeral=True)
  203. #---------------------------------#
  204. #Unban
  205. @bot.slash_command(name="unban", description="Unban a user from this Server")
  206. async def unban(
  207. ctx,
  208. user: Option(discord.User, description = "Insert User ID", required=True), # type: ignore
  209. reason: Option(str, description = "Reason for the unbanning", default="No reason provided") # type: ignore
  210. ):
  211. if not ctx.author.guild_permissions.ban_members:
  212. await ctx.respond("Error: You don't have the permission to unban Members!", ephemeral=True)
  213. return
  214. if user == bot.user:
  215. await ctx.respond("Error: I can't unban myself!", ephemeral=True)
  216. return
  217. if user == ctx.author:
  218. await ctx.respond("Error: You can't unban yourself!", ephemeral=True)
  219. return
  220. if user in ctx.guild.members:
  221. await ctx.respond("Error: This user is not banned!", ephemeral=True)
  222. return
  223. channel= discord.utils.get(ctx.guild.channels, id = int(channel_banlog))
  224. embed = discord.Embed(
  225. title=f"Unban of **{user.name}**",
  226. description=f"User {user.mention} was unbanned from this server.",
  227. color=discord.Color.green()
  228. )
  229. time = discord.utils.format_dt(datetime.now(), "f")
  230. embed.add_field(name="Unban Date", value=time, inline=False)
  231. embed.add_field(name="Moderator", value=f"{ctx.author}", inline=False)
  232. embed.add_field(name="Reason", value=reason, inline=False)
  233. embed.add_field(name="User ID", value=user.id)
  234. embed.set_thumbnail(url=user.display_avatar.url)
  235. embed.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
  236. embed.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
  237. try:
  238. await ctx.guild.unban(user, reason=reason)
  239. await ctx.respond(f"User {user.mention} is now unbanned!", ephemeral=True)
  240. await channel.send(embed=embed)
  241. cursor.execute(
  242. "INSERT INTO Unbans (userid, username, moderatorname, reason) VALUES (%s, %s, %s, %s)",
  243. (user.id, str(user), str(ctx.author), reason)
  244. )
  245. conn.commit()
  246. except discord.Forbidden:
  247. await ctx.respond("Error: I don't have permission to unban this user.", ephemeral=True)
  248. except discord.HTTPException as e:
  249. await ctx.respond(f"Error: Could not unban User {user.mention}. Reason: {e}", ephemeral=True)
  250. except Exception as e:
  251. await ctx.respond(f"Unexpected error: {e}", ephemeral=True)
  252. #---------------------------------#
  253. #_________________________________#
  254. #---------------------------------#
  255. #Kick
  256. @bot.slash_command(name="kick", description="Kick a user from this Server")
  257. async def kick(
  258. ctx,
  259. user: Option(discord.User, description = "Select User", required=True), # type: ignore
  260. reason: Option(str, description = "Reason for the ban", default="No reason provided") # type: ignore
  261. ):
  262. if not ctx.author.guild_permissions.kick_members:
  263. await ctx.respond("Error: You don't have the permission to kick Members!", ephemeral=True)
  264. return
  265. if user == bot.user:
  266. await ctx.respond("Error: I can't kick myself!", ephemeral=True)
  267. return
  268. if user == ctx.author:
  269. await ctx.respond("Error: You can't kick yourself!", ephemeral=True)
  270. return
  271. channel= discord.utils.get(ctx.guild.channels, id = int(channel_banlog))
  272. embed = discord.Embed(
  273. title=f"Kick of **{user.name}**",
  274. description=f"User {user.mention} has been kicked from the Server",
  275. color=discord.Color.red()
  276. )
  277. time = discord.utils.format_dt(datetime.now(), "f")
  278. embed.add_field(name="Kick Date", value=time, inline=False)
  279. embed.add_field(name="Moderator", value=f"{ctx.author}", inline=False)
  280. embed.add_field(name="Reason", value=reason, inline=False)
  281. embed.add_field(name="User ID", value=user.id)
  282. embed.set_thumbnail(url=user.display_avatar.url)
  283. embed.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
  284. embed.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
  285. try:
  286. await ctx.guild.kick(user, reason=reason)
  287. await ctx.respond(f"User {user.mention} has been kicked from this Server!", ephemeral=True)
  288. cursor.execute(
  289. "INSERT INTO Kick (userid, username, moderatorname, reason) VALUES (%s, %s, %s, %s)",
  290. (int(user.id), str(user), str(ctx.author), reason)
  291. )
  292. conn.commit()
  293. await channel.send(embed=embed)
  294. except discord.Forbidden:
  295. await ctx.respond("Error: I don't have permission to kick this user.", ephemeral=True)
  296. except discord.HTTPException as e:
  297. await ctx.respond(f"Error: Could not kick User {user.mention}. Reason: {e}", ephemeral=True)
  298. except Exception as e:
  299. await ctx.respond(f"Unexpected error: {e}", ephemeral=True)
  300. #---------------------------------#
  301. #---------------------------------#
  302. #Warn
  303. @bot.slash_command(name="warn", description="Warn a user from this Server")
  304. async def warn(
  305. ctx,
  306. user: Option(discord.User, required=True), # type: ignore
  307. reason: Option(str, default="No reason provided") # type: ignore
  308. ):
  309. await ctx.defer(ephemeral=True)
  310. if not ctx.author.guild_permissions.kick_members:
  311. await ctx.followup.send("No permission.", ephemeral=True)
  312. return
  313. if user in (bot.user, ctx.author):
  314. await ctx.followup.send("Invalid target.", ephemeral=True)
  315. return
  316. cursor.execute(
  317. "INSERT INTO Warns (userid, username, moderatorname, reason) VALUES (%s, %s, %s, %s)",
  318. (user.id, str(user), str(ctx.author), reason)
  319. )
  320. conn.commit()
  321. await ctx.followup.send(
  322. f"User {user.mention} has been warned for: {reason}",
  323. ephemeral=True
  324. )
  325. #---------------------------------#
  326. #Modinfo
  327. @bot.slash_command(name="modinfo", description="Shows the moderative history of a user from this Server")
  328. async def modinfo(
  329. ctx,
  330. user: Option(discord.User, required=True) # type: ignore
  331. ):
  332. await ctx.defer(ephemeral=False)
  333. if not ctx.author.guild_permissions.kick_members:
  334. await ctx.followup.send("No permission.", ephemeral=True)
  335. return
  336. embed = discord.Embed(
  337. title=f"__Moderation History for {user.name}__",
  338. color=discord.Color.orange()
  339. )
  340. cursor.execute(
  341. "SELECT moderatorname, reason, date FROM Warns WHERE userid = %s",
  342. (user.id,)
  343. )
  344. warns = cursor.fetchall()
  345. if warns:
  346. for moderatorname, reason, date in warns:
  347. embed.add_field(
  348. name=f"Warned by {moderatorname} on {date.strftime('%Y-%m-%d %H:%M:%S')}",
  349. value=f"Reason: {reason}",
  350. inline=False
  351. )
  352. cursor.execute(
  353. "SELECT moderatorname, reason, date FROM Kick WHERE userid = %s",
  354. (user.id,)
  355. )
  356. kicks = cursor.fetchall()
  357. if kicks:
  358. for moderatorname, reason, date in kicks:
  359. embed.add_field(
  360. name=f"Kicked by {moderatorname} on {date.strftime('%Y-%m-%d %H:%M:%S')}",
  361. value=f"Reason: {reason}",
  362. inline=False
  363. )
  364. cursor.execute(
  365. "SELECT moderatorname, reason, date FROM Bans WHERE userid = %s",
  366. (user.id,)
  367. )
  368. bans = cursor.fetchall()
  369. if bans:
  370. for moderatorname, reason, date in bans:
  371. embed.add_field(
  372. name=f"Banned by {moderatorname} on {date.strftime('%Y-%m-%d %H:%M:%S')}",
  373. value=f"Reason: {reason}",
  374. inline=False
  375. )
  376. cursor.execute(
  377. "SELECT moderatorname, reason, date FROM Unbans WHERE userid = %s",
  378. (user.id,)
  379. )
  380. unbans = cursor.fetchall()
  381. if unbans:
  382. for moderatorname, reason, date in unbans:
  383. embed.add_field(
  384. name=f"Unbanned by {moderatorname} on {date.strftime('%Y-%m-%d %H:%M:%S')}",
  385. value=f"Reason: {reason}",
  386. inline=False
  387. )
  388. if not warns and not kicks and not bans and not unbans:
  389. await ctx.followup.send(f"User `{user.name}` has no moderation history.", ephemeral=True)
  390. return
  391. embed.set_thumbnail(url=user.display_avatar.url)
  392. embed.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
  393. embed.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
  394. await ctx.followup.send(embed=embed, ephemeral=False)
  395. #_________________________________#
  396. ## Reaction role system
  397. #---------------------------------#
  398. #reaction role verfiy
  399. class PersistentRoleView(discord.ui.View):
  400. def __init__(self):
  401. super().__init__(timeout=None)
  402. @discord.ui.button(
  403. label=label_rules,
  404. style=discord.ButtonStyle.success,
  405. emoji="✅",
  406. custom_id="persistent_view:role_verify"
  407. )
  408. async def verify_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
  409. role = interaction.guild.get_role(int(role_rules))
  410. if role is None:
  411. await interaction.response.send_message("Error: The konfigured role was not found", ephemeral=True)
  412. return
  413. if role in interaction.user.roles:
  414. await interaction.user.remove_roles(role)
  415. await interaction.response.send_message(f"Rolle **{role.name}** wurde entfernt.", ephemeral=True)
  416. else:
  417. await interaction.user.add_roles(role)
  418. await interaction.response.send_message(f"Du hast die Rolle **{role.name}** erhalten!", ephemeral=True)
  419. @bot.slash_command(name="verify_message", description="Send the reactionrole message")
  420. async def setup_rr(
  421. ctx: discord.ApplicationContext,
  422. channel: discord.TextChannel,
  423. title: str,
  424. description: str
  425. ):
  426. if not ctx.author.guild_permissions.administrator:
  427. await ctx.respond("You dont have the permissions to do that..", ephemeral=True)
  428. return
  429. embed = discord.Embed(
  430. title=title,
  431. description=f"{description}\n\nViel Spass auf dem Server!",
  432. color=discord.Color.red()
  433. )
  434. embed.set_image(url="https://i.imgur.com/FoF791J.png")
  435. try:
  436. await channel.send(embed=embed, view=PersistentRoleView())
  437. await ctx.respond(f"Message was succesfully sent in {channel.mention}!", ephemeral=True)
  438. except discord.Forbidden:
  439. await ctx.respond("I dont have permissions to write in this channel", ephemeral=True)
  440. #---------------------------------#
  441. #_________________________________#
  442. #---------------------------------#
  443. #Run function
  444. load_extensions()
  445. bot.run(token)
  446. #---------------------------------#