main.py 17 KB

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