main.py 18 KB

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