change_name_badge.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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, players.charinfo, users.discord
  67. FROM ny_groups_meta
  68. JOIN players ON ny_groups_meta.character_identifier = players.citizenid
  69. JOIN users ON players.userId = users.userId
  70. """)
  71. for internal_identifier, char_info, discord in cursor.fetchall():
  72. badgenr.append(internal_identifier)
  73. charinfo.append(char_info)
  74. discord_raw.append((discord,))
  75. #get users to the discordIDs
  76. for discord in discord_raw:
  77. discord_id = discord[0].split(":")
  78. for i in range(len(discord_id)):
  79. if discord_id[i].isdigit():
  80. user_id = int(discord_id[i])
  81. user = self.bot.get_user(user_id)
  82. if user is not None:
  83. users.append(user)
  84. break
  85. #check on duplicates
  86. valid_users = {}
  87. blacklisted_ids = []
  88. ignored_duplicates = []
  89. unique_users = []
  90. unique_badgenr = []
  91. unique_charinfo = []
  92. for user, badge, cinfo in zip(users, badgenr, charinfo):
  93. if user is None:
  94. continue
  95. #delete users if they are duplicated
  96. if user.id in blacklisted_ids:
  97. ignored_duplicates.append((user, badge, cinfo))
  98. continue
  99. elif user.id in valid_users:
  100. first_entry = valid_users.pop(user.id)
  101. ignored_duplicates.append(first_entry)
  102. ignored_duplicates.append((user, badge, cinfo))
  103. blacklisted_ids.append(user.id)
  104. else:
  105. valid_users[user.id] = (user, badge, cinfo)
  106. for user, badge, cinfo in valid_users.values():
  107. unique_users.append(user)
  108. unique_badgenr.append(badge)
  109. unique_charinfo.append(cinfo)
  110. users = unique_users
  111. badgenr = unique_badgenr
  112. charinfo = unique_charinfo
  113. print(f"Unique users: {len(users)}, Ignored duplicates: {len(ignored_duplicates)}")
  114. #get charname
  115. for char_data in charinfo:
  116. try:
  117. char_dict = json.loads(char_data)
  118. firstname.append(char_dict.get("firstname", ""))
  119. lastname.append(char_dict.get("lastname", ""))
  120. except (json.JSONDecodeError, KeyError, TypeError):
  121. firstname.append("")
  122. lastname.append("")
  123. #change username
  124. for user, badge, first, last in zip(users, badgenr, firstname, lastname):
  125. nick = f"[{badge}] {first} {last}"
  126. try:
  127. guild = self.bot.get_guild(int(guild_id))
  128. member = guild.get_member(user.id)
  129. #print(f"Changing nickname for {user.name} to {nick}")
  130. if member:
  131. await member.edit(nick=nick)
  132. except Exception as e:
  133. #print(f"Failed to change nickname for {user.name}: {e}")
  134. continue
  135. cursor.close()
  136. conn.close()
  137. def setup(bot: discord.Bot):
  138. bot.add_cog(changedcname(bot))