main.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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. ## Greet
  154. @bot.slash_command(description="Greet a User")
  155. async def greet(ctx, user: str = Option(discord.User, "The user, you want to greet")):
  156. await ctx.respond(f"Hello {user.mention}")
  157. #---------------------------------#
  158. #---------------------------------#
  159. ## Userinfo
  160. @bot.slash_command(name="userinfo", description="Show informations of a user from this server")
  161. async def userinfo(
  162. ctx,
  163. user: str = Option(discord.User, "Select User"),
  164. ):
  165. if user is None:
  166. user = ctx.author
  167. elif user not in ctx.guild.members:
  168. await ctx.respond("The selected user is not a member on this Server!", ephemeral=True)
  169. return
  170. elif user == bot.user:
  171. await ctx.respond(f"This is me - the {bot.user}", ephemeral=True)
  172. return
  173. embed = discord.Embed(
  174. title=f"Information about *{user.name}*",
  175. description=f"Here you see all details about {user.mention}",
  176. color=discord.Color.blue()
  177. )
  178. time = discord.utils.format_dt(user.created_at, "R")
  179. embed.add_field(name="Account creation date", value=time, inline=False)
  180. if len(user.roles) >= 2:
  181. embed.add_field(name="Roles", value=", ".join([role.mention for role in user.roles if role.name != "@everyone"]), inline=False)
  182. else:
  183. embed.add_field(name="Roles", value="User has no roles", inline=False)
  184. embed.add_field(name="Server join date", value=discord.utils.format_dt(user.joined_at, "R"), inline=False)
  185. embed.add_field(name="User ID", value=user.id)
  186. embed.set_thumbnail(url=user.display_avatar.url)
  187. embed.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
  188. embed.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
  189. await ctx.respond(embed=embed)
  190. #---------------------------------#
  191. #_________________________________#
  192. #BAN SYSTEM
  193. #---------------------------------#
  194. ##Ban
  195. @bot.slash_command(name="ban", description="Ban a user from this Server")
  196. async def ban(
  197. ctx,
  198. user: Option(discord.User, description = "Select User", required=True), # type: ignore
  199. reason: Option(str, description = "Reason for the ban", default="No reason provided") # type: ignore
  200. ):
  201. if not ctx.author.guild_permissions.ban_members:
  202. await ctx.respond("Error: You don't have the permission to ban Members!", ephemeral=True)
  203. return
  204. if user == bot.user:
  205. await ctx.respond("Error: I can't ban myself!", ephemeral=True)
  206. return
  207. if user == ctx.author:
  208. await ctx.respond("Error: You can't ban yourself!", ephemeral=True)
  209. return
  210. channel= discord.utils.get(ctx.guild.channels, id = int(channel_banlog))
  211. embed = discord.Embed(
  212. title=f"Ban of **{user.name}**",
  213. description=f"User {user.mention} has been banned from the Server",
  214. color=discord.Color.red()
  215. )
  216. time = discord.utils.format_dt(datetime.now(), "f")
  217. embed.add_field(name="Ban Date", value=time, inline=False)
  218. embed.add_field(name="Moderator", value=f"{ctx.author}", inline=False)
  219. embed.add_field(name="Reason", value=reason, inline=False)
  220. embed.add_field(name="User ID", value=user.id)
  221. embed.set_thumbnail(url=user.display_avatar.url)
  222. embed.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
  223. embed.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
  224. try:
  225. await ctx.guild.ban(user, reason=reason)
  226. await ctx.respond(f"User {user.mention} has been banned from this Server!", ephemeral=True)
  227. await channel.send(embed=embed)
  228. cursor.execute(
  229. "INSERT INTO Bans (userid, username, moderatorname, reason) VALUES (%s, %s, %s, %s)",
  230. (user.id, str(user), str(ctx.author), reason)
  231. )
  232. conn.commit()
  233. except discord.Forbidden:
  234. await ctx.respond("Error: I don't have permission to ban this user.", ephemeral=True)
  235. except discord.HTTPException as e:
  236. await ctx.respond(f"Error: Could not ban User {user.mention}. Reason: {e}", ephemeral=True)
  237. except Exception as e:
  238. await ctx.respond(f"Unexpected error: {e}", ephemeral=True)
  239. #---------------------------------#
  240. #Unban
  241. @bot.slash_command(name="unban", description="Unban a user from this Server")
  242. async def unban(
  243. ctx,
  244. user: Option(discord.User, description = "Insert User ID", required=True), # type: ignore
  245. reason: Option(str, description = "Reason for the unbanning", default="No reason provided") # type: ignore
  246. ):
  247. if not ctx.author.guild_permissions.ban_members:
  248. await ctx.respond("Error: You don't have the permission to unban Members!", ephemeral=True)
  249. return
  250. if user == bot.user:
  251. await ctx.respond("Error: I can't unban myself!", ephemeral=True)
  252. return
  253. if user == ctx.author:
  254. await ctx.respond("Error: You can't unban yourself!", ephemeral=True)
  255. return
  256. if user in ctx.guild.members:
  257. await ctx.respond("Error: This user is not banned!", ephemeral=True)
  258. return
  259. channel= discord.utils.get(ctx.guild.channels, id = int(channel_banlog))
  260. embed = discord.Embed(
  261. title=f"Unban of **{user.name}**",
  262. description=f"User {user.mention} was unbanned from this server.",
  263. color=discord.Color.green()
  264. )
  265. time = discord.utils.format_dt(datetime.now(), "f")
  266. embed.add_field(name="Unban Date", value=time, inline=False)
  267. embed.add_field(name="Moderator", value=f"{ctx.author}", inline=False)
  268. embed.add_field(name="Reason", value=reason, inline=False)
  269. embed.add_field(name="User ID", value=user.id)
  270. embed.set_thumbnail(url=user.display_avatar.url)
  271. embed.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
  272. embed.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
  273. try:
  274. await ctx.guild.unban(user, reason=reason)
  275. await ctx.respond(f"User {user.mention} is now unbanned!", ephemeral=True)
  276. await channel.send(embed=embed)
  277. cursor.execute(
  278. "INSERT INTO Unbans (userid, username, moderatorname, reason) VALUES (%s, %s, %s, %s)",
  279. (user.id, str(user), str(ctx.author), reason)
  280. )
  281. conn.commit()
  282. except discord.Forbidden:
  283. await ctx.respond("Error: I don't have permission to unban this user.", ephemeral=True)
  284. except discord.HTTPException as e:
  285. await ctx.respond(f"Error: Could not unban User {user.mention}. Reason: {e}", ephemeral=True)
  286. except Exception as e:
  287. await ctx.respond(f"Unexpected error: {e}", ephemeral=True)
  288. #---------------------------------#
  289. #_________________________________#
  290. #---------------------------------#
  291. #Kick
  292. @bot.slash_command(name="kick", description="Kick a user from this Server")
  293. async def kick(
  294. ctx,
  295. user: Option(discord.User, description = "Select User", required=True), # type: ignore
  296. reason: Option(str, description = "Reason for the ban", default="No reason provided") # type: ignore
  297. ):
  298. if not ctx.author.guild_permissions.kick_members:
  299. await ctx.respond("Error: You don't have the permission to kick Members!", ephemeral=True)
  300. return
  301. if user == bot.user:
  302. await ctx.respond("Error: I can't kick myself!", ephemeral=True)
  303. return
  304. if user == ctx.author:
  305. await ctx.respond("Error: You can't kick yourself!", ephemeral=True)
  306. return
  307. try:
  308. await ctx.guild.kick(user, reason=reason)
  309. await ctx.respond(f"User {user.mention} has been kicked from this Server!", ephemeral=True)
  310. cursor.execute(
  311. "INSERT INTO Kick (userid, username, moderatorname, reason) VALUES (%s, %s, %s, %s)",
  312. (int(user.id), str(user), str(ctx.author), reason)
  313. )
  314. conn.commit()
  315. channel= discord.utils.get(ctx.guild.channels, id = int(channel_banlog))
  316. embed = discord.Embed(
  317. title=f"Kick of **{user.name}**",
  318. description=f"User {user.mention} has been kicked from the Server",
  319. color=discord.Color.red()
  320. )
  321. time = discord.utils.format_dt(datetime.now(), "f")
  322. embed.add_field(name="Kick Date", value=time, inline=False)
  323. embed.add_field(name="Moderator", value=f"{ctx.author}", inline=False)
  324. embed.add_field(name="Reason", value=reason, inline=False)
  325. embed.add_field(name="User ID", value=user.id)
  326. embed.set_thumbnail(url=user.display_avatar.url)
  327. embed.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
  328. embed.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
  329. except discord.Forbidden:
  330. await ctx.respond("Error: I don't have permission to kick this user.", ephemeral=True)
  331. except discord.HTTPException as e:
  332. await ctx.respond(f"Error: Could not kick User {user.mention}. Reason: {e}", ephemeral=True)
  333. except Exception as e:
  334. await ctx.respond(f"Unexpected error: {e}", ephemeral=True)
  335. #---------------------------------#
  336. #---------------------------------#
  337. #Warn
  338. @bot.slash_command(name="warn", description="Warn a user from this Server")
  339. async def warn(
  340. ctx,
  341. user: Option(discord.User, required=True), # type: ignore
  342. reason: Option(str, default="No reason provided") # type: ignore
  343. ):
  344. await ctx.defer(ephemeral=True)
  345. if not ctx.author.guild_permissions.kick_members:
  346. await ctx.followup.send("No permission.", ephemeral=True)
  347. return
  348. if user in (bot.user, ctx.author):
  349. await ctx.followup.send("Invalid target.", ephemeral=True)
  350. return
  351. cursor.execute(
  352. "INSERT INTO Warns (userid, username, moderatorname, reason) VALUES (%s, %s, %s, %s)",
  353. (user.id, str(user), str(ctx.author), reason)
  354. )
  355. conn.commit()
  356. await ctx.followup.send(
  357. f"User {user.mention} has been warned for: {reason}",
  358. ephemeral=True
  359. )
  360. #---------------------------------#
  361. #Modinfo
  362. @bot.slash_command(name="modinfo", description="Shows the moderative history of a user from this Server")
  363. async def modinfo(
  364. ctx,
  365. user: Option(discord.User, required=True) # type: ignore
  366. ):
  367. await ctx.defer(ephemeral=False)
  368. if not ctx.author.guild_permissions.kick_members:
  369. await ctx.followup.send("No permission.", ephemeral=True)
  370. return
  371. embed = discord.Embed(
  372. title=f"__Moderation History for {user.name}__",
  373. color=discord.Color.orange()
  374. )
  375. cursor.execute(
  376. "SELECT moderatorname, reason, date FROM Warns WHERE userid = %s",
  377. (user.id,)
  378. )
  379. warns = cursor.fetchall()
  380. if warns:
  381. for moderatorname, reason, date in warns:
  382. embed.add_field(
  383. name=f"Warned by {moderatorname} on {date.strftime('%Y-%m-%d %H:%M:%S')}",
  384. value=f"Reason: {reason}",
  385. inline=False
  386. )
  387. cursor.execute(
  388. "SELECT moderatorname, reason, date FROM Kick WHERE userid = %s",
  389. (user.id,)
  390. )
  391. kicks = cursor.fetchall()
  392. if kicks:
  393. for moderatorname, reason, date in kicks:
  394. embed.add_field(
  395. name=f"Kicked by {moderatorname} on {date.strftime('%Y-%m-%d %H:%M:%S')}",
  396. value=f"Reason: {reason}",
  397. inline=False
  398. )
  399. cursor.execute(
  400. "SELECT moderatorname, reason, date FROM Bans WHERE userid = %s",
  401. (user.id,)
  402. )
  403. bans = cursor.fetchall()
  404. if bans:
  405. for moderatorname, reason, date in bans:
  406. embed.add_field(
  407. name=f"Banned by {moderatorname} on {date.strftime('%Y-%m-%d %H:%M:%S')}",
  408. value=f"Reason: {reason}",
  409. inline=False
  410. )
  411. cursor.execute(
  412. "SELECT moderatorname, reason, date FROM Unbans WHERE userid = %s",
  413. (user.id,)
  414. )
  415. unbans = cursor.fetchall()
  416. if unbans:
  417. for moderatorname, reason, date in unbans:
  418. embed.add_field(
  419. name=f"Unbanned by {moderatorname} on {date.strftime('%Y-%m-%d %H:%M:%S')}",
  420. value=f"Reason: {reason}",
  421. inline=False
  422. )
  423. if not warns and not kicks and not bans and not unbans:
  424. await ctx.followup.send(f"User {user.mention} has no moderation history.", ephemeral=True)
  425. return
  426. embed.set_thumbnail(url=user.display_avatar.url)
  427. embed.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
  428. embed.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
  429. await ctx.followup.send(embed=embed, ephemeral=False)
  430. #_________________________________#
  431. ## Reaction role system
  432. #---------------------------------#
  433. #reaction role verfiy
  434. class PersistentRoleView(discord.ui.View):
  435. def __init__(self):
  436. super().__init__(timeout=None)
  437. @discord.ui.button(
  438. label=label_rules,
  439. style=discord.ButtonStyle.success,
  440. emoji="✅",
  441. custom_id="persistent_view:role_verify"
  442. )
  443. async def verify_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
  444. role = interaction.guild.get_role(int(role_rules))
  445. if role is None:
  446. await interaction.response.send_message("Error: The konfigured role was not found", ephemeral=True)
  447. return
  448. if role in interaction.user.roles:
  449. await interaction.user.remove_roles(role)
  450. await interaction.response.send_message(f"Rolle **{role.name}** wurde entfernt.", ephemeral=True)
  451. else:
  452. await interaction.user.add_roles(role)
  453. await interaction.response.send_message(f"Du hast die Rolle **{role.name}** erhalten!", ephemeral=True)
  454. @bot.slash_command(name="verify_message", description="Send the reactionrole message")
  455. async def setup_rr(
  456. ctx: discord.ApplicationContext,
  457. channel: discord.TextChannel,
  458. title: str,
  459. description: str
  460. ):
  461. if not ctx.author.guild_permissions.administrator:
  462. await ctx.respond("You dont have the permissions to do that..", ephemeral=True)
  463. return
  464. embed = discord.Embed(
  465. title=title,
  466. description=f"{description}\n\nViel Spass auf dem Server!",
  467. color=discord.Color.red()
  468. )
  469. embed.set_image(url="https://i.imgur.com/FoF791J.png")
  470. try:
  471. await channel.send(embed=embed, view=PersistentRoleView())
  472. await ctx.respond(f"Message was succesfully sent in {channel.mention}!", ephemeral=True)
  473. except discord.Forbidden:
  474. await ctx.respond("I dont have permissions to write in this channel", ephemeral=True)
  475. #---------------------------------#
  476. #_________________________________#
  477. #---------------------------------#
  478. #Run function
  479. load_extensions()
  480. bot.run(token)
  481. #---------------------------------#