Files
cogs
dashboard
.gitignore
bot.py
config.py
database.py
pyproject.toml
README.md
requirements.txt
run_bot.py
run_dashboard.py
utils.py
Code
21 1,550
bot.py
import logging
import re
from collections import defaultdict, deque
from datetime import datetime, timedelta, timezone
import discord
from discord import app_commands
from discord.ext import commands
from config import BOT_PREFIX, DISCORD_TOKEN
from database import Database
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
logger = logging.getLogger("community_bot")
class CommunityBot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
intents.presences = False
super().__init__(command_prefix=BOT_PREFIX, intents=intents, help_command=None)
self.db = Database()
self.message_times: dict[tuple[int, int], deque[datetime]] = defaultdict(deque)
self.xp_cooldowns: dict[tuple[int, int], datetime] = {}
self.recent_joins: dict[int, deque[datetime]] = defaultdict(deque)
async def setup_hook(self) -> None:
self.db.init()
from cogs.economy import EconomyCog
from cogs.info import InfoCog
from cogs.levels import LevelsCog
from cogs.moderation import ModerationCog
from cogs.setup import SetupCog
from cogs.tickets import TicketControlsView, TicketOpenView, TicketsCog
from cogs.verification import VerifyView, VerificationCog
from cogs.welcome import WelcomeCog
for cog in (ModerationCog, TicketsCog, VerificationCog, WelcomeCog, LevelsCog, EconomyCog, InfoCog, SetupCog):
await self.add_cog(cog(self))
self.add_view(TicketOpenView(self))
self.add_view(TicketControlsView(self))
self.add_view(VerifyView(self))
self.tree.on_error = self.on_app_command_error
await self.tree.sync()
logger.info("Comandos globales sincronizados")
async def on_ready(self) -> None:
logger.info("Conectado como %s en %d servidores", self.user, len(self.guilds))
async def on_guild_join(self, guild: discord.Guild) -> None:
self.db.ensure_guild(guild.id)
async def on_message(self, message: discord.Message) -> None:
if message.author.bot or not message.guild:
return
settings = self.db.settings(message.guild.id)
verify_role = message.guild.get_role(settings.get("verify_role_id")) if settings.get("verify_role_id") else None
if settings["verification_protection"] and verify_role and verify_role not in message.author.roles:
try:
await message.delete()
except discord.HTTPException:
logger.exception("No se pudo eliminar un mensaje de un usuario no verificado")
return
if settings["anti_links"] and re.search(r"(?:https?://|www\.|discord\.gg/)", message.content, re.IGNORECASE):
if not message.author.guild_permissions.manage_messages:
try:
await message.delete()
await message.channel.send(f"{message.author.mention}, los enlaces no están permitidos aquí.", delete_after=5)
await self._record_automatic(message, "anti-link", "Enlace eliminado")
except discord.HTTPException:
logger.exception("No se pudo gestionar un enlace")
return
if settings["anti_spam"]:
key = (message.guild.id, message.author.id)
now = datetime.now(timezone.utc)
history = self.message_times[key]
history.append(now)
while history and (now - history[0]).total_seconds() > 8:
history.popleft()
if len(history) >= 6:
try:
await message.delete()
await message.author.timeout(timedelta(seconds=30), reason="Anti-spam automático")
await self._record_automatic(message, "anti-spam", "Usuario limitado durante 30 segundos")
except (discord.HTTPException, discord.Forbidden):
logger.exception("No se pudo gestionar el spam")
history.clear()
return
if settings["levels_enabled"]:
key = (message.guild.id, message.author.id)
now = datetime.now(timezone.utc)
if now >= self.xp_cooldowns.get(key, datetime.min.replace(tzinfo=timezone.utc)):
self.xp_cooldowns[key] = now + timedelta(seconds=max(5, settings["xp_cooldown"]))
xp, level, advanced = self.db.add_xp(message.guild.id, message.author.id, 10)
if advanced:
await message.channel.send(f"🎉 {message.author.mention} ha alcanzado el nivel **{level}**.", delete_after=8)
await self.process_commands(message)
async def _record_automatic(self, message: discord.Message, action: str, details: str) -> None:
self.db.add_moderation_log(message.guild.id, action, message.author.id, self.user.id if self.user else 0, details)
async def on_app_command_error(self, interaction: discord.Interaction, error: app_commands.AppCommandError) -> None:
if isinstance(error, app_commands.errors.MissingPermissions):
text = "No tienes los permisos necesarios para usar este comando."
elif isinstance(error, app_commands.errors.CheckFailure):
text = "No puedes ejecutar este comando en este contexto."
else:
logger.exception("Error en comando de aplicación", exc_info=error)
text = "Ocurrió un error inesperado. El equipo ha sido notificado."
if interaction.response.is_done():
await interaction.followup.send(text, ephemeral=True)
else:
await interaction.response.send_message(text, ephemeral=True)
def main() -> None:
if not DISCORD_TOKEN:
raise SystemExit("Falta DISCORD_TOKEN. Copia .env.example a .env y configúralo.")
bot = CommunityBot()
bot.run(DISCORD_TOKEN, log_handler=None)
if __name__ == "__main__":
main()