main.py 23 KB

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