main.py 18 KB

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