change_name_badge.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. import os
  2. from dotenv import load_dotenv
  3. import discord
  4. from discord.ext import commands, tasks
  5. from discord.commands import Option
  6. from discord.commands import slash_command
  7. import configparser
  8. import time
  9. import mysql.connector
  10. ## Note: to use this script on a other server you need to change the SQL querys. It is deactivatable in the config.cfg file.
  11. class changedcname(commands.Cog):
  12. def __init__(self, bot: discord.Bot):
  13. self.bot = bot
  14. def _load_config(self):
  15. config = configparser.ConfigParser()
  16. configFilePath = r'config.cfg'
  17. config.read(configFilePath)
  18. return config
  19. @commands.Cog.listener()
  20. async def on_ready(self):
  21. self.check_inactive_members.start()
  22. @tasks.loop(minutes=15)
  23. async def check_inactive_members(self):
  24. config = self._load_config()
  25. enable_change_dc_name = config.getboolean("Role Management","nable_change_dc_name")
  26. if not enable_change_dc_name:
  27. return # Exit the function if the feature is disabled in the config
  28. #Load .env file for the gameserver database
  29. dbhost = os.getenv("HOST2")
  30. if dbhost is None:
  31. raise ValueError("HOST2 not found in .env file")
  32. dbname = os.getenv("NAME2")
  33. if dbname is None:
  34. raise ValueError("NAME2 not found in .env file")
  35. dbpsswd = os.getenv("PASSWORD2")
  36. if dbpsswd is None:
  37. raise ValueError("PASSWORD2 not found in .env file")
  38. dbdb = os.getenv("DATABASE2")
  39. if dbdb is None:
  40. raise ValueError("DATABASE2 not found in .env file")
  41. #Database initialization
  42. conn = mysql.connector.connect(
  43. host=dbhost,
  44. user=dbname,
  45. password=dbpsswd,
  46. charset='utf8mb4',
  47. collation='utf8mb4_unicode_ci'
  48. )
  49. cursor = conn.cursor()
  50. conn.database = dbdb
  51. #needed arrays
  52. badgenr = []
  53. charinfo = []
  54. discord_raw = []
  55. user_id = []
  56. users = []
  57. firstname = []
  58. lastname = []
  59. #get information from database
  60. cursor.execute("""
  61. SELECT ny_groups_meta.internal_identifier FROM ny_groups_meta,
  62. users, players WHERE ny_groups_meta.character_identifier=players.citizenid AND
  63. players.userId=users.userId
  64. """)
  65. for internal_identifier in cursor.fetchall():
  66. badgenr.append((internal_identifier))
  67. cursor.execute("""
  68. SELECT players.charinfo FROM ny_groups_meta,
  69. users, players WHERE ny_groups_meta.character_identifier=players.citizenid AND
  70. players.userId=users.userId
  71. """)
  72. for charinfo in cursor.fetchall():
  73. charinfo.append((charinfo))
  74. cursor.execute("""
  75. SELECT users.discord FROM ny_groups_meta,
  76. users, players WHERE ny_groups_meta.character_identifier=players.citizenid AND
  77. players.userId=users.userId
  78. """)
  79. for discord in cursor.fetchall():
  80. discord_raw.append((discord))
  81. #get users to the discordIDs
  82. for discord in discord_raw:
  83. discord_id = discord_raw.split(":")
  84. for i in range(len(discord_raw)):
  85. if discord_raw[i].isdigit():
  86. user_id = int(discord_raw[i])
  87. user = self.bot.get_user(user_id)
  88. users.append(user)
  89. #check on dublicates
  90. for i in range(len(users)):
  91. for j in range(i + 1, len(users)):
  92. if users[i] == users[j]:
  93. print(f"Duplicate user found: {users[i].name} (ID: {users[i].id})")
  94. users.pop(j)
  95. charinfo.pop(j)
  96. badgenr.remove(badgenr[j])
  97. users.pop(i)
  98. #get charname
  99. for charinfo in charinfo:
  100. charinfo_split = charinfo.split(",")
  101. for i in range(len(charinfo_split)):
  102. if '"firstname"' in charinfo_split[i]:
  103. firstname.append(charinfo_split[i+1])
  104. if '"lastname"' in charinfo_split[i]:
  105. lastname.append(charinfo_split[i+1])
  106. #change username
  107. for i in range(len(users)):
  108. nick = f"[{badgenr[i]}] {firstname[i]} {lastname[i]}"
  109. try:
  110. await users[i].edit(nick=nick)
  111. except Exception as e:
  112. print(f"Failed to change nickname for {users[i].name}: {e}")
  113. cursor.close()
  114. conn.close()
  115. def setup(bot: discord.Bot):
  116. bot.add_cog(changedcname(bot))