Untitled

 avatar
unknown
python
a month ago
7.5 kB
3
Indexable
from discord.ui import Button, View, Select
from collections import defaultdict
from datetime import datetime, timedelta
import re
import json
import os


configurations = {
    "spam_detection": True,
    "link_blocking": True,
    "log_channel": None,
    "entry_channel": None,
    "exit_channel": None,
    "autorole": None,
    "spam_message_limit": 5,
    "spam_time_window": 10  # 10 segundos
}
user_messages = defaultdict(list)

# salvar configurações em arquivo
def save_configurations():
    with open("configurations.json", "w") as file:
        json.dump(configurations, file, indent=4)

# carregar configurações de arquivo
def load_configurations():
    global configurations
    if os.path.exists("configurations.json"):
        with open("configurations.json", "r") as file:
            configurations = json.load(file)

load_configurations()

# registrar logs no canal especificado
async def log_action(guild, action, user, reason):
    log_channel_id = configurations.get("log_channel")
    if log_channel_id:
        log_channel = guild.get_channel(log_channel_id)
        if log_channel:
            embed = discord.Embed(
                title="Registro de Moderação",
                description=f"Ação: {action}\nUsuário: {user}\nMotivo: {reason}",
                color=discord.Color.orange(),
                timestamp=datetime.utcnow()
            )
            await log_channel.send(embed=embed)

@bot.tree.command(name="botconfig", description="Configura o bot com funções interativas")
async def botconfig(interaction: discord.Interaction):
    if not interaction.user.guild_permissions.manage_guild:
        await interaction.response.send_message("Você precisa da permissão de Gerenciar Servidor para usar este comando.", ephemeral=True)
        return

    async def show_initial_config(interaction):
        embed = discord.Embed(
            title="Configuração do Bot",
            description="Escolha uma das opções abaixo para configurar:",
            color=discord.Color.blue()
        )
        embed.set_thumbnail(url=bot.user.avatar.url)

        button_mod = Button(label="Moderação", style=discord.ButtonStyle.green)
        button_mod.callback = show_moderation_config

        view = View(timeout=300)
        view.add_item(button_mod)

        await interaction.response.edit_message(embed=embed, view=view)

    async def show_moderation_config(interaction):
        embed = discord.Embed(
            title="Configuração de Moderação",
            description="Escolha uma das opções abaixo:",
            color=discord.Color.blue()
        )

        button_entry = Button(label="Entrada", style=discord.ButtonStyle.blurple)
        button_exit = Button(label="Saída", style=discord.ButtonStyle.blurple)
        button_autorole = Button(label="Autorole", style=discord.ButtonStyle.blurple)
        button_logs = Button(label="Canal de Logs", style=discord.ButtonStyle.blurple)
        button_back = Button(label="Voltar", style=discord.ButtonStyle.red)

        button_entry.callback = configure_entry
        button_exit.callback = configure_exit
        button_autorole.callback = configure_autorole
        button_logs.callback = configure_logs
        button_back.callback = show_initial_config

        view = View(timeout=300)
        view.add_item(button_entry)
        view.add_item(button_exit)
        view.add_item(button_autorole)
        view.add_item(button_logs)
        view.add_item(button_back)

        await interaction.response.edit_message(embed=embed, view=view)

    async def configure_logs(interaction):
        embed = discord.Embed(
            title="Configurar Canal de Logs",
            description="Escolha o canal para enviar registros de moderação:",
            color=discord.Color.orange()
        )

        select = Select(
            placeholder="Selecione um canal",
            options=[
                discord.SelectOption(label=channel.name, value=str(channel.id)) for channel in interaction.guild.text_channels
            ]
        )

        async def select_callback(interaction):
            configurations["log_channel"] = int(select.values[0])
            save_configurations()
            selected_channel = interaction.guild.get_channel(configurations["log_channel"])
            await interaction.response.send_message(f"Canal de logs configurado: {selected_channel.mention}", ephemeral=True)

        select.callback = select_callback

        view = View(timeout=300)
        view.add_item(select)

        await interaction.response.edit_message(embed=embed, view=view)

    # Configuração de entrada, saída e autorole

    await show_initial_config(interaction)

@bot.event
async def on_member_join(member):
    channel_id = configurations.get("entry_channel")
    if channel_id:
        channel = member.guild.get_channel(channel_id)
        if channel:
            embed = discord.Embed(
                title=f"Bem-vindo, {member.name}!",
                description=f"ID: {member.id}\nNome: {member}",
                color=discord.Color.green()
            )
            embed.set_thumbnail(url=member.avatar.url)
            embed.set_footer(text=member.guild.name, icon_url=member.guild.icon.url)
            await channel.send(embed=embed)

    role_id = configurations.get("autorole")
    if role_id:
        role = member.guild.get_role(role_id)
        if role:
            await member.add_roles(role)

@bot.event
async def on_member_remove(member):
    channel_id = configurations.get("exit_channel")
    if channel_id:
        channel = member.guild.get_channel(channel_id)
        if channel:
            embed = discord.Embed(
                title=f"{member.name} saiu do servidor.",
                description=f"ID: {member.id}\nNome: {member}",
                color=discord.Color.red()
            )
            embed.set_thumbnail(url=member.avatar.url)
            embed.set_footer(text=member.guild.name, icon_url=member.guild.icon.url)
            await channel.send(embed=embed)

@bot.event
async def on_message(message):
    if message.author.bot:
        return

    now = datetime.now()

    # Detecção de spam
    if configurations["spam_detection"]:
        user_id = message.author.id
        user_messages[user_id].append(now)
        user_messages[user_id] = [msg_time for msg_time in user_messages[user_id] if now - msg_time <= timedelta(seconds=configurations["spam_time_window"])]

        if len(user_messages[user_id]) > configurations["spam_message_limit"]:
            await message.delete()
            await message.channel.send(f"{message.author.mention}, suas mensagens foram bloqueadas por spam.", delete_after=5)
            await log_action(message.guild, "Spam Block", message.author, "Excesso de mensagens")

    # Bloqueio de links
    if configurations["link_blocking"]:
        discord_invite_pattern = r"(https?://)?(www\.)?(discord\.gg|discord\.com/invite)/\S+"
        if re.search(discord_invite_pattern, message.content):
            await message.delete()
            await message.channel.send(f"{message.author.mention}, links de servidores Discord não são permitidos.", delete_after=5)
            await log_action(message.guild, "Link Block", message.author, "Link de servidor Discord")

    await bot.process_commands(message)
Leave a Comment