inaktive_remider_dm.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  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: this script will be pretty hardcoded and specific for our use case. It is deactivatable in the config.cfg file.
  11. class remiderinactive(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. @tasks.loop(hours=120) # Run every 5 days
  20. async def check_inactive_members(self):
  21. config = self._load_config()
  22. enable_inavtive_reminder_dm = config.getboolean("Welcome","enable_inavtive_reminder_dm")
  23. if not enable_inavtive_reminder_dm:
  24. return # Exit the function if the feature is disabled in the config
  25. log_channel_id = config.getint("Logs","action_log")
  26. log_channel = self.bot.get_channel(log_channel_id)
  27. #Load .env file for the gameserver database
  28. dbhost = os.getenv("HOST2")
  29. if dbhost is None:
  30. raise ValueError("HOST2 not found in .env file")
  31. dbname = os.getenv("NAME2")
  32. if dbname is None:
  33. raise ValueError("NAME2 not found in .env file")
  34. dbpsswd = os.getenv("PASSWORD2")
  35. if dbpsswd is None:
  36. raise ValueError("PASSWORD2 not found in .env file")
  37. dbdb = os.getenv("DATABASE2")
  38. if dbdb is None:
  39. raise ValueError("DATABASE2 not found in .env file")
  40. #Database initialization
  41. conn = mysql.connector.connect(
  42. host=dbhost,
  43. user=dbname,
  44. password=dbpsswd,
  45. charset='utf8mb4',
  46. collation='utf8mb4_unicode_ci'
  47. )
  48. cursor = conn.cursor()
  49. conn.database = dbdb
  50. inaktive_players = []
  51. cursor.execute("""
  52. SELECT users.discord, MAX(users.license2)AS license2, MAX(players.last_updated) AS last_logged_out FROM users JOIN players ON users.license2 = players.license GROUP BY users.discord HAVING MAX(players.last_updated) < CURDATE() - INTERVAL 14 DAY;
  53. """)
  54. for discord in cursor.fetchall():
  55. inaktive_players.append(discord)
  56. #print(f"Found inactive player: {discord[0]} with license {discord[1]} last logged out at {discord[2]}")
  57. #await log_channel.send(f"Found inactive player: {discord[0]} with license {discord[1]} last logged out at {discord[2]}")
  58. #Core script
  59. discord_ids = []
  60. for players in inaktive_players:
  61. discord_id = None
  62. discord_value = str(players[0]).strip() if players[0] is not None else ""
  63. discord_raw = discord_value.split(":")[-1].strip()
  64. if discord_raw.isdigit():
  65. discord_id = discord_raw
  66. else:
  67. print(f"Invalid Discord ID format for value {players[0]}: {discord_raw}")
  68. await log_channel.send(f"Invalid Discord ID format for value {players[0]}: {discord_raw}")
  69. continue
  70. if discord_id is not None:
  71. discord_ids.append(discord_id)
  72. for discord_id in discord_ids:
  73. user_id = int(discord_id)
  74. user = self.bot.get_user(user_id)
  75. if user is not None:
  76. try:
  77. await user.send("Hey, du warst eine ganze Weile außer Dienst – höchste Zeit, wieder einzusteigen und den Bürgern von Los Santos auf den Straßen zu helfen! 🚔")
  78. await log_channel.send(f"Sent inactivity reminder DM to {user.name} ({user.id})")
  79. except Exception as e:
  80. print(f"Could not send DM to {user.name}: {e}")
  81. await log_channel.send(f"Could not send DM to {user.name} ({user.id}): {e}")
  82. else:
  83. print(f"Could not find user with ID {user_id}")
  84. await log_channel.send(f"Could not find user with ID {user_id}")
  85. cursor.close()
  86. conn.close()
  87. @slash_command(name="inaktivedm", description= "Manually trigger the inactivity reminder DM.")
  88. async def promotion(
  89. self,
  90. ctx: discord.ApplicationContext
  91. ):
  92. if ctx.author.guild_permissions.administrator:
  93. await ctx.respond("Manually triggering the inactivity reminder DM...", ephemeral=True)
  94. await self.check_inactive_members()
  95. else:
  96. await ctx.respond("You do not have permission to use this command.", ephemeral=True)
  97. def setup(bot: discord.Bot):
  98. bot.add_cog(remiderinactive(bot))