updatye filters

This commit is contained in:
Valerie 2025-02-22 20:47:49 -05:00
parent c749387965
commit 6359f4d19a

View file

@ -1,141 +1,135 @@
import discord import discord
import json import json
import re import io
from redbot.core import commands, Config from redbot.core import commands, Config
import asyncio
class FilterCog(commands.Cog): class FilterCog(commands.Cog):
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
self.config = Config.get_conf(self, identifier=1234567890, force_registration=True) self.config = Config.get_conf(self, identifier=1234567890, force_registration=True)
self.config.register_global( self.config.register_global(
regexes=[],
phrases=[], phrases=[],
words=[], words=[],
standAloneWords=[], standAloneWords=[],
targetChannelId=None, replacementChars=[],
logChannelId=None, mutedPlayers=[],
deleteFromBots=False, tempMutedPlayers=[],
deleteFromUsers=True, ignoredPlayers=[],
targetChannelOnly=False, logFiltered=True,
logFiltered=False, ignorePrivateMessages=False,
ignorePrivateMessages=True,
caseSensitive=False, caseSensitive=False,
muteCommand=False,
tellPlayer=True,
censorAndSend=False,
muteAfterOffense=False, muteAfterOffense=False,
muteAfterOffenseType="mute", muteAfterOffenseType="TEMPORARY",
muteAfterOffenseMinutes=10, muteAfterOffenseMinutes=5,
muteAfterOffenseNumber=3, muteAfterOffenseNumber=3,
offenseExpireMinutes=60, offenseExpireMinutes=30,
offenses={} offenses=[],
) )
@commands.Cog.listener() @commands.Cog.listener()
async def on_ready(self): async def on_ready(self):
print(f"{self.__class__.__name__} cog has been loaded.") print(f"{self.__class__.__name__} cog has been loaded.")
async def send_log(self, log_channel_id, message): @commands.slash_command()
log_channel = self.bot.get_channel(log_channel_id) async def addword(self, ctx, word: str):
if log_channel: """Add a word to the filter list."""
embed = discord.Embed(title="Log", description=message, color=0x00ff00)
await log_channel.send(embed=embed)
else:
print(f"Log channel {log_channel_id} not found.")
@commands.Cog.listener()
async def on_message(self, message):
if message.author.bot and not await self.config.deleteFromBots():
return
if message.channel.type == discord.ChannelType.private and await self.config.ignorePrivateMessages():
return
config = await self.config.all()
if config["targetChannelOnly"] and message.channel.id != config["targetChannelId"]:
return
triggers = config["phrases"] + config["words"]
standalone_triggers = [rf"\b{word}\b" for word in config["standAloneWords"]]
if any(trigger.lower() in message.content.lower() for trigger in triggers) or \
any(re.search(trigger, message.content, re.IGNORECASE) for trigger in standalone_triggers):
try:
await message.delete()
log_message = f"Deleted message from user **{message.author.name}** (ID: {message.author.id}) due to inappropriate content."
await message.channel.send(f"{message.author.mention}, your message was removed due to inappropriate content.")
if config["logFiltered"]:
await self.send_log(config["logChannelId"], log_message)
except discord.errors.Forbidden:
print("Missing permissions to delete messages.")
if config["muteAfterOffense"]:
async with self.config.offenses() as offenses:
if message.author.id not in offenses:
offenses[message.author.id] = 0
offenses[message.author.id] += 1
if offenses[message.author.id] >= config["muteAfterOffenseNumber"]:
if message.guild:
muted_role = discord.utils.get(message.guild.roles, name="Muted")
if muted_role:
await message.author.add_roles(muted_role)
await asyncio.sleep(config["muteAfterOffenseMinutes"] * 60)
await message.author.remove_roles(muted_role)
offenses[message.author.id] = 0
@commands.command()
async def addword(self, ctx, *, word: str):
async with self.config.words() as words: async with self.config.words() as words:
words.append(word) words.append(word)
await ctx.send(f"Added `{word}` to the filter list.") await ctx.respond(f"Added `{word}` to the filter list.")
@commands.command() @commands.slash_command()
async def removeword(self, ctx, *, word: str): async def removeword(self, ctx, word: str):
"""Remove a word from the filter list."""
async with self.config.words() as words: async with self.config.words() as words:
if word in words: if word in words:
words.remove(word) words.remove(word)
await ctx.send(f"Removed `{word}` from the filter list.") await ctx.respond(f"Removed `{word}` from the filter list.")
else: else:
await ctx.send(f"`{word}` was not found in the filter list.") await ctx.respond(f"`{word}` was not found in the filter list.")
@commands.command() @commands.slash_command()
async def addphrase(self, ctx, *, phrase: str): async def listwords(self, ctx):
async with self.config.phrases() as phrases: """List all words in the filter."""
phrases.append(phrase) words = await self.config.words()
await ctx.send(f"Added `{phrase}` to the filter list.") await ctx.respond(f"Filtered words: {', '.join(words) if words else 'None'}")
@commands.command() @commands.slash_command()
async def removephrase(self, ctx, *, phrase: str): async def clearwords(self, ctx):
async with self.config.phrases() as phrases: """Clear all words from the filter list."""
if phrase in phrases: await self.config.words.set([])
phrases.remove(phrase) await ctx.respond("All filtered words have been cleared.")
await ctx.send(f"Removed `{phrase}` from the filter list.")
else:
await ctx.send(f"`{phrase}` was not found in the filter list.")
@commands.command() @commands.slash_command()
async def addstandaloneword(self, ctx, *, word: str): async def importconfig(self, ctx, file: discord.Attachment):
async with self.config.standAloneWords() as standalone_words: """Import a config file."""
standalone_words.append(word) if file.filename.endswith(".json"):
await ctx.send(f"Added `{word}` to the standalone words filter list.") try:
data = await file.read()
config_data = json.loads(data.decode("utf-8"))
async with self.config.all() as config:
for key in config.keys():
if key in config_data:
config[key] = config_data[key]
await ctx.respond("Config imported successfully.")
except Exception as e:
await ctx.respond(f"Failed to import config: {str(e)}")
else:
await ctx.respond("Please upload a JSON file.")
@commands.command() @commands.slash_command()
async def removestandaloneword(self, ctx, *, word: str): async def exportconfig(self, ctx):
async with self.config.standAloneWords() as standalone_words: """Export the current config as a JSON file."""
if word in standalone_words: config_data = await self.config.all()
standalone_words.remove(word) file = discord.File(io.BytesIO(json.dumps(config_data, indent=4).encode()), filename="config.json")
await ctx.send(f"Removed `{word}` from the standalone words filter list.") await ctx.respond("Here is the current configuration:", file=file)
else:
await ctx.send(f"`{word}` was not found in the standalone words filter list.")
@commands.command() @commands.slash_command()
async def settargetchannel(self, ctx, channel: discord.TextChannel): async def togglelogging(self, ctx):
await self.config.targetChannelId.set(channel.id) """Toggle logging on or off."""
await ctx.send(f"Target channel set to {channel.mention}.") current = await self.config.logFiltered()
await self.config.logFiltered.set(not current)
await ctx.respond(f"Logging is now {'enabled' if not current else 'disabled'}.")
@commands.command() @commands.slash_command()
async def setlogchannel(self, ctx, channel: discord.TextChannel): async def setmuteoffense(self, ctx, number: int):
await self.config.logChannelId.set(channel.id) """Set the number of offenses before muting a user."""
await ctx.send(f"Log channel set to {channel.mention}.") await self.config.muteAfterOffenseNumber.set(number)
await ctx.respond(f"Users will now be muted after {number} offenses.")
@commands.slash_command()
async def enableautomod(self, ctx):
"""Enable Discord's built-in AutoMod."""
guild = ctx.guild
if guild:
await guild.edit(automod_enabled=True)
await ctx.respond("AutoMod has been enabled.")
else:
await ctx.respond("This command must be used in a server.")
@commands.slash_command()
async def disableautomod(self, ctx):
"""Disable Discord's built-in AutoMod."""
guild = ctx.guild
if guild:
await guild.edit(automod_enabled=False)
await ctx.respond("AutoMod has been disabled.")
else:
await ctx.respond("This command must be used in a server.")
@commands.slash_command()
async def listautomodrules(self, ctx):
"""List all AutoMod rules in the server."""
guild = ctx.guild
if guild:
rules = await guild.fetch_automod_rules()
rule_names = [rule.name for rule in rules]
await ctx.respond(f"AutoMod Rules: {', '.join(rule_names) if rule_names else 'None'}")
else:
await ctx.respond("This command must be used in a server.")
async def setup(bot): async def setup(bot):
await bot.add_cog(FilterCog(bot)) await bot.add_cog(FilterCog(bot))