main.py 23 KB

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