auto_delete_msg.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import discord
  2. from discord.ext import commands
  3. from discord.commands import Option
  4. from discord.commands import slash_command
  5. import configparser
  6. import time
  7. import asyncio
  8. class autodelmsg(commands.Cog):
  9. def __init__(self, bot: discord.Bot):
  10. self.bot = bot
  11. def _load_config(self):
  12. config = configparser.ConfigParser()
  13. configFilePath = r'config.cfg'
  14. config.read(configFilePath)
  15. return config
  16. def _get_info_channel(self):
  17. config = self._load_config()
  18. channel_ids = [int(channel_id.strip()) for channel_id in config["Moderation"]["autodelete_channel_id"].split(",")]
  19. channels = [self.bot.get_channel(channel_id) for channel_id in channel_ids]
  20. if any(channel is None for channel in channels):
  21. print(f"One or more roles with IDs {channel_ids} not found.")
  22. return
  23. return channels
  24. def _get_message_age_limit(self):
  25. config = self._load_config()
  26. return config.getint("Moderation", "autodelete_message_age")
  27. @commands.Cog.listener()
  28. async def on_ready(self):
  29. channels = self._get_info_channel()
  30. if channels is None:
  31. return
  32. message_age_limit = self._get_message_age_limit()
  33. while True:
  34. for channel in channels:
  35. async for message in channel.history(limit=None):
  36. if (time.time() - message.created_at.timestamp()) > (message_age_limit * 3600):
  37. try:
  38. await message.delete()
  39. #print(f"Deleted message from {message.author} in {channel.name} due to age.")
  40. except Exception as e:
  41. print(f"Failed to delete message: {e}")
  42. await asyncio.sleep(3600) #Check every hour
  43. def setup(bot: discord.Bot):
  44. bot.add_cog(autodelmsg(bot))