change_name_badge.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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. import json
  11. ## Note: to use this script on a other server you need to change the SQL querys. It is deactivatable in the config.cfg file.
  12. class changedcname(commands.Cog):
  13. def __init__(self, bot: discord.Bot):
  14. self.bot = bot
  15. def _load_config(self):
  16. config = configparser.ConfigParser()
  17. configFilePath = r'config.cfg'
  18. config.read(configFilePath)
  19. return config
  20. @commands.Cog.listener()
  21. async def on_ready(self):
  22. self.change_name_badge.start()
  23. @tasks.loop(minutes=15)
  24. async def change_name_badge(self):
  25. config = self._load_config()
  26. enable_change_dc_name = config.getboolean("Role Management","enable_change_dc_name")
  27. if not enable_change_dc_name:
  28. return # Exit the function if the feature is disabled in the config
  29. #Load .env file for the gameserver database
  30. dbhost = os.getenv("HOST2")
  31. if dbhost is None:
  32. raise ValueError("HOST2 not found in .env file")
  33. dbname = os.getenv("NAME2")
  34. if dbname is None:
  35. raise ValueError("NAME2 not found in .env file")
  36. dbpsswd = os.getenv("PASSWORD2")
  37. if dbpsswd is None:
  38. raise ValueError("PASSWORD2 not found in .env file")
  39. dbdb = os.getenv("DATABASE2")
  40. if dbdb is None:
  41. raise ValueError("DATABASE2 not found in .env file")
  42. #Get guild ID
  43. load_dotenv()
  44. guild_id = os.getenv("SERVER")
  45. if guild_id is None:
  46. raise ValueError("SERVER not found in .env file")
  47. #Database initialization
  48. conn = mysql.connector.connect(
  49. host=dbhost,
  50. user=dbname,
  51. password=dbpsswd,
  52. charset='utf8mb4',
  53. collation='utf8mb4_unicode_ci'
  54. )
  55. cursor = conn.cursor()
  56. conn.database = dbdb
  57. #needed arrays
  58. badgenr = []
  59. charinfo = []
  60. users = []
  61. discord_raw = []
  62. firstname = []
  63. lastname = []
  64. #get information from database
  65. cursor.execute("""
  66. SELECT ny_groups_meta.internal_identifier FROM ny_groups_meta,
  67. users, players WHERE ny_groups_meta.character_identifier=players.citizenid AND
  68. players.userId=users.userId ORDER BY ny_groups_meta.internal_identifier
  69. """)
  70. for internal_identifier in cursor.fetchall():
  71. badgenr.append(internal_identifier[0])
  72. cursor.execute("""
  73. SELECT players.charinfo FROM ny_groups_meta,
  74. users, players WHERE ny_groups_meta.character_identifier=players.citizenid AND
  75. players.userId=users.userId ORDER BY ny_groups_meta.internal_identifier
  76. """)
  77. for char_info in cursor.fetchall():
  78. charinfo.append(char_info[0])
  79. cursor.execute("""
  80. SELECT users.discord FROM ny_groups_meta,
  81. users, players WHERE ny_groups_meta.character_identifier=players.citizenid AND
  82. players.userId=users.userId ORDER BY ny_groups_meta.internal_identifier
  83. """)
  84. for discord in cursor.fetchall():
  85. discord_raw.append((discord))
  86. #get users to the discordIDs
  87. for discord in discord_raw:
  88. discord_id = discord[0].split(":")
  89. for i in range(len(discord_id)):
  90. if discord_id[i].isdigit():
  91. user_id = int(discord_id[i])
  92. user = self.bot.get_user(user_id)
  93. users.append(user)
  94. break
  95. # check on duplicates
  96. unique_users = []
  97. unique_badgenr = []
  98. unique_charinfo = []
  99. seen_user_ids = [] # To track seen user IDs
  100. ignored_duplicates = [] # To track and ignore duplicate users
  101. for user, badge, cinfo in zip(users, badgenr, charinfo):
  102. if user is None:
  103. continue
  104. user_id = user.id
  105. if user_id in seen_user_ids:
  106. #print(f"Duplicate user found: {user.name} (ID: {user.id})")
  107. ignored_duplicates.append(user.id)
  108. ignored_duplicates.append(badge)
  109. ignored_duplicates.append(cinfo)
  110. #remove the duplicate user
  111. if user in unique_users:
  112. unique_badgenr.remove(badge)
  113. unique_users.remove(user)
  114. unique_charinfo.remove(cinfo)
  115. continue
  116. else:
  117. seen_user_ids.append(user_id)
  118. unique_users.append(user)
  119. unique_badgenr.append(badge)
  120. unique_charinfo.append(cinfo)
  121. users = unique_users
  122. badgenr = unique_badgenr
  123. charinfo = unique_charinfo
  124. #get charname
  125. for char_data in charinfo:
  126. try:
  127. char_dict = json.loads(char_data)
  128. firstname.append(char_dict.get("firstname", ""))
  129. lastname.append(char_dict.get("lastname", ""))
  130. except (json.JSONDecodeError, KeyError, TypeError):
  131. firstname.append("")
  132. lastname.append("")
  133. #change username
  134. for user, badge, first, last in zip(users, badgenr, firstname, lastname):
  135. nick = f"[{badge}] {first} {last}"
  136. try:
  137. guild = self.bot.get_guild(int(guild_id))
  138. member = guild.get_member(user.id)
  139. if member:
  140. await member.edit(nick=nick)
  141. except Exception as e:
  142. #print(f"Failed to change nickname for {user.name}: {e}")
  143. continue
  144. cursor.close()
  145. conn.close()
  146. def setup(bot: discord.Bot):
  147. bot.add_cog(changedcname(bot))